anbinh39 commited on
Commit
b33e5eb
·
verified ·
1 Parent(s): cfc7a54

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/bin/activate +130 -0
  2. .venv/bin/activate.bat +71 -0
  3. .venv/bin/activate.csh +76 -0
  4. .venv/bin/activate.fish +124 -0
  5. .venv/bin/activate.nu +117 -0
  6. .venv/bin/activate.ps1 +82 -0
  7. .venv/bin/activate_this.py +59 -0
  8. .venv/bin/deactivate.bat +39 -0
  9. .venv/bin/idna +10 -0
  10. .venv/bin/normalizer +10 -0
  11. .venv/bin/pydoc.bat +22 -0
  12. .venv/bin/python +0 -0
  13. .venv/bin/python3 +0 -0
  14. .venv/bin/python3.11 +0 -0
  15. .venv/bin/wandb +10 -0
  16. .venv/bin/wb +10 -0
  17. .venv/lib/python3.11/site-packages/__pycache__/_virtualenv.cpython-311.pyc +0 -0
  18. .venv/lib/python3.11/site-packages/_virtualenv.py +101 -0
  19. .venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/INSTALLER +1 -0
  20. .venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/METADATA +295 -0
  21. .venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/RECORD +9 -0
  22. .venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/REQUESTED +0 -0
  23. .venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/WHEEL +4 -0
  24. .venv/lib/python3.11/site-packages/charset_normalizer/__main__.py +6 -0
  25. .venv/lib/python3.11/site-packages/charset_normalizer/api.py +988 -0
  26. .venv/lib/python3.11/site-packages/charset_normalizer/cd.cpython-311-x86_64-linux-gnu.so +0 -0
  27. .venv/lib/python3.11/site-packages/charset_normalizer/cd.py +454 -0
  28. .venv/lib/python3.11/site-packages/charset_normalizer/constant.py +2050 -0
  29. .venv/lib/python3.11/site-packages/charset_normalizer/legacy.py +79 -0
  30. .venv/lib/python3.11/site-packages/charset_normalizer/md.py +936 -0
  31. .venv/lib/python3.11/site-packages/charset_normalizer/models.py +369 -0
  32. .venv/lib/python3.11/site-packages/charset_normalizer/py.typed +0 -0
  33. .venv/lib/python3.11/site-packages/charset_normalizer/utils.py +422 -0
  34. .venv/lib/python3.11/site-packages/charset_normalizer/version.py +8 -0
  35. .venv/lib/python3.11/site-packages/package_readme.md +116 -0
  36. .venv/lib/python3.11/site-packages/packaging/__init__.py +15 -0
  37. .venv/lib/python3.11/site-packages/packaging/_elffile.py +108 -0
  38. .venv/lib/python3.11/site-packages/packaging/_manylinux.py +262 -0
  39. .venv/lib/python3.11/site-packages/packaging/_musllinux.py +85 -0
  40. .venv/lib/python3.11/site-packages/packaging/_parser.py +393 -0
  41. .venv/lib/python3.11/site-packages/packaging/_structures.py +33 -0
  42. .venv/lib/python3.11/site-packages/packaging/_tokenizer.py +193 -0
  43. .venv/lib/python3.11/site-packages/packaging/dependency_groups.py +302 -0
  44. .venv/lib/python3.11/site-packages/packaging/direct_url.py +325 -0
  45. .venv/lib/python3.11/site-packages/packaging/errors.py +94 -0
  46. .venv/lib/python3.11/site-packages/packaging/markers.py +492 -0
  47. .venv/lib/python3.11/site-packages/packaging/metadata.py +964 -0
  48. .venv/lib/python3.11/site-packages/packaging/py.typed +0 -0
  49. .venv/lib/python3.11/site-packages/packaging/pylock.py +905 -0
  50. .venv/lib/python3.11/site-packages/packaging/requirements.py +129 -0
.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='/home/aiserver/works/fingerprint/sifq/.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
.venv/bin/activate.bat ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @REM This file is UTF-8 encoded, so we need to update the current code page while executing it
23
+ @for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a
24
+ @if defined _OLD_CODEPAGE (
25
+ @"%SystemRoot%\System32\chcp.com" 65001 > nul
26
+ )
27
+
28
+ @for %%i in ("/home/aiserver/works/fingerprint/sifq/.venv") do @set "VIRTUAL_ENV=%%~fi"
29
+
30
+ @set "VIRTUAL_ENV_PROMPT="
31
+ @if NOT DEFINED VIRTUAL_ENV_PROMPT (
32
+ @for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd"
33
+ )
34
+
35
+ @if defined _OLD_VIRTUAL_PROMPT (
36
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
37
+ ) else (
38
+ @if not defined PROMPT (
39
+ @set "PROMPT=$P$G"
40
+ )
41
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
42
+ @set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
43
+ )
44
+ )
45
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
46
+ @set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%"
47
+ )
48
+
49
+ @REM Don't use () to avoid problems with them in %PATH%
50
+ @if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
51
+ @set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
52
+ :ENDIFVHOME
53
+
54
+ @set PYTHONHOME=
55
+
56
+ @REM if defined _OLD_VIRTUAL_PATH (
57
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1
58
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
59
+ :ENDIFVPATH1
60
+ @REM ) else (
61
+ @if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2
62
+ @set "_OLD_VIRTUAL_PATH=%PATH%"
63
+ :ENDIFVPATH2
64
+
65
+ @set "PATH=%VIRTUAL_ENV%\bin;%PATH%"
66
+
67
+ :END
68
+ @if defined _OLD_CODEPAGE (
69
+ @"%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
70
+ @set _OLD_CODEPAGE=
71
+ )
.venv/bin/activate.csh ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used with "source bin/activate.csh" *from csh*.
23
+ # You cannot run it directly.
24
+ # Created by Davide Di Blasi <davidedb@gmail.com>.
25
+
26
+ set newline='\
27
+ '
28
+
29
+ alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH:q" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT:q" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc'
30
+
31
+ # Unset irrelevant variables.
32
+ deactivate nondestructive
33
+
34
+ setenv VIRTUAL_ENV '/home/aiserver/works/fingerprint/sifq/.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
.venv/bin/activate.fish ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.
23
+ # Do not run it directly.
24
+
25
+ function _bashify_path -d "Converts a fish path to something bash can recognize"
26
+ set fishy_path $argv
27
+ set bashy_path $fishy_path[1]
28
+ for path_part in $fishy_path[2..-1]
29
+ set bashy_path "$bashy_path:$path_part"
30
+ end
31
+ echo $bashy_path
32
+ end
33
+
34
+ function _fishify_path -d "Converts a bash path to something fish can recognize"
35
+ echo $argv | tr ':' '\n'
36
+ end
37
+
38
+ function deactivate -d 'Exit virtualenv mode and return to the normal environment.'
39
+ # reset old environment variables
40
+ if test -n "$_OLD_VIRTUAL_PATH"
41
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
42
+ if test (echo $FISH_VERSION | head -c 1) -lt 3
43
+ set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH")
44
+ else
45
+ set -gx PATH $_OLD_VIRTUAL_PATH
46
+ end
47
+ set -e _OLD_VIRTUAL_PATH
48
+ end
49
+
50
+ if test -n "$_OLD_VIRTUAL_PYTHONHOME"
51
+ set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME"
52
+ set -e _OLD_VIRTUAL_PYTHONHOME
53
+ end
54
+
55
+ if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
56
+ and functions -q _old_fish_prompt
57
+ # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.
58
+ set -l fish_function_path
59
+
60
+ # Erase virtualenv's `fish_prompt` and restore the original.
61
+ functions -e fish_prompt
62
+ functions -c _old_fish_prompt fish_prompt
63
+ functions -e _old_fish_prompt
64
+ set -e _OLD_FISH_PROMPT_OVERRIDE
65
+ end
66
+
67
+ set -e VIRTUAL_ENV
68
+ set -e VIRTUAL_ENV_PROMPT
69
+
70
+ if test "$argv[1]" != 'nondestructive'
71
+ # Self-destruct!
72
+ functions -e pydoc
73
+ functions -e deactivate
74
+ functions -e _bashify_path
75
+ functions -e _fishify_path
76
+ end
77
+ end
78
+
79
+ # Unset irrelevant variables.
80
+ deactivate nondestructive
81
+
82
+ set -gx VIRTUAL_ENV '/home/aiserver/works/fingerprint/sifq/.venv'
83
+
84
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
85
+ if test (echo $FISH_VERSION | head -c 1) -lt 3
86
+ set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH)
87
+ else
88
+ set -gx _OLD_VIRTUAL_PATH $PATH
89
+ end
90
+ set -gx PATH "$VIRTUAL_ENV"'/bin' $PATH
91
+
92
+ # Prompt override provided?
93
+ # If not, just use the environment name.
94
+ if test -n ''
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
.venv/bin/activate.nu ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # virtualenv activation module
23
+ # Activate with `overlay use activate.nu`
24
+ # Deactivate with `deactivate`, as usual
25
+ #
26
+ # To customize the overlay name, you can call `overlay use activate.nu as foo`,
27
+ # but then simply `deactivate` won't work because it is just an alias to hide
28
+ # the "activate" overlay. You'd need to call `overlay hide foo` manually.
29
+
30
+ export-env {
31
+ def is-string [x] {
32
+ ($x | describe) == 'string'
33
+ }
34
+
35
+ def has-env [...names] {
36
+ $names | each {|n|
37
+ $n in $env
38
+ } | all {|i| $i == true}
39
+ }
40
+
41
+ # Emulates a `test -z`, but better as it handles e.g 'false'
42
+ def is-env-true [name: string] {
43
+ if (has-env $name) {
44
+ # Try to parse 'true', '0', '1', and fail if not convertible
45
+ let parsed = (do -i { $env | get $name | into bool })
46
+ if ($parsed | describe) == 'bool' {
47
+ $parsed
48
+ } else {
49
+ not ($env | get -i $name | is-empty)
50
+ }
51
+ } else {
52
+ false
53
+ }
54
+ }
55
+
56
+ let virtual_env = '/home/aiserver/works/fingerprint/sifq/.venv'
57
+ let bin = 'bin'
58
+
59
+ let is_windows = ($nu.os-info.family) == 'windows'
60
+ let path_name = (if (has-env 'Path') {
61
+ 'Path'
62
+ } else {
63
+ 'PATH'
64
+ }
65
+ )
66
+
67
+ let venv_path = ([$virtual_env $bin] | path join)
68
+ let new_path = ($env | get $path_name | prepend $venv_path)
69
+
70
+ # If there is no default prompt, then use the env name instead
71
+ let virtual_env_prompt = (if ('' | is-empty) {
72
+ ($virtual_env | path basename)
73
+ } else {
74
+ ''
75
+ })
76
+
77
+ let new_env = {
78
+ $path_name : $new_path
79
+ VIRTUAL_ENV : $virtual_env
80
+ VIRTUAL_ENV_PROMPT : $virtual_env_prompt
81
+ }
82
+
83
+ let new_env = (if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') {
84
+ $new_env
85
+ } else {
86
+ # Creating the new prompt for the session
87
+ let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
88
+
89
+ # Back up the old prompt builder
90
+ let old_prompt_command = (if (has-env 'PROMPT_COMMAND') {
91
+ $env.PROMPT_COMMAND
92
+ } else {
93
+ ''
94
+ })
95
+
96
+ let new_prompt = (if (has-env 'PROMPT_COMMAND') {
97
+ if 'closure' in ($old_prompt_command | describe) {
98
+ {|| $'($virtual_prefix)(do $old_prompt_command)' }
99
+ } else {
100
+ {|| $'($virtual_prefix)($old_prompt_command)' }
101
+ }
102
+ } else {
103
+ {|| $'($virtual_prefix)' }
104
+ })
105
+
106
+ $new_env | merge {
107
+ PROMPT_COMMAND : $new_prompt
108
+ VIRTUAL_PREFIX : $virtual_prefix
109
+ }
110
+ })
111
+
112
+ # Environment variables that will be loaded as the virtual env
113
+ load-env $new_env
114
+ }
115
+
116
+ export alias pydoc = python -m pydoc
117
+ export alias deactivate = overlay hide activate
.venv/bin/activate.ps1 ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ $script:THIS_PATH = $myinvocation.mycommand.path
23
+ $script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent
24
+
25
+ function global:deactivate([switch] $NonDestructive) {
26
+ if (Test-Path variable:_OLD_VIRTUAL_PATH) {
27
+ $env:PATH = $variable:_OLD_VIRTUAL_PATH
28
+ Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global
29
+ }
30
+
31
+ if (Test-Path function:_old_virtual_prompt) {
32
+ $function:prompt = $function:_old_virtual_prompt
33
+ Remove-Item function:\_old_virtual_prompt
34
+ }
35
+
36
+ if ($env:VIRTUAL_ENV) {
37
+ Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue
38
+ }
39
+
40
+ if ($env:VIRTUAL_ENV_PROMPT) {
41
+ Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue
42
+ }
43
+
44
+ if (!$NonDestructive) {
45
+ # Self destruct!
46
+ Remove-Item function:deactivate
47
+ Remove-Item function:pydoc
48
+ }
49
+ }
50
+
51
+ function global:pydoc {
52
+ python -m pydoc $args
53
+ }
54
+
55
+ # unset irrelevant variables
56
+ deactivate -nondestructive
57
+
58
+ $VIRTUAL_ENV = $BASE_DIR
59
+ $env:VIRTUAL_ENV = $VIRTUAL_ENV
60
+
61
+ if ("" -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
+ }
.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
.venv/bin/deactivate.bat ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @set VIRTUAL_ENV=
23
+ @set VIRTUAL_ENV_PROMPT=
24
+
25
+ @REM Don't use () to avoid problems with them in %PATH%
26
+ @if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT
27
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
28
+ @set _OLD_VIRTUAL_PROMPT=
29
+ :ENDIFVPROMPT
30
+
31
+ @if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
32
+ @set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
33
+ @set _OLD_VIRTUAL_PYTHONHOME=
34
+ :ENDIFVHOME
35
+
36
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH
37
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
38
+ @set _OLD_VIRTUAL_PATH=
39
+ :ENDIFVPATH
.venv/bin/idna ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/aiserver/works/fingerprint/sifq/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from idna.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/normalizer ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/aiserver/works/fingerprint/sifq/.venv/bin/python3
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())
.venv/bin/pydoc.bat ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ python.exe -m pydoc %*
.venv/bin/python ADDED
Binary file (20.3 kB). View file
 
.venv/bin/python3 ADDED
Binary file (20.3 kB). View file
 
.venv/bin/python3.11 ADDED
Binary file (20.3 kB). View file
 
.venv/bin/wandb ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/aiserver/works/fingerprint/sifq/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from wandb.cli.cli import cli
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())
.venv/bin/wb ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/aiserver/works/fingerprint/sifq/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from wandb.cli.cli import cli
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())
.venv/lib/python3.11/site-packages/__pycache__/_virtualenv.cpython-311.pyc ADDED
Binary file (4.54 kB). View file
 
.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())
.venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
.venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/METADATA ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.3
2
+ Name: annotated-types
3
+ Version: 0.7.0
4
+ Summary: Reusable constraint types to use with typing.Annotated
5
+ Project-URL: Homepage, https://github.com/annotated-types/annotated-types
6
+ Project-URL: Source, https://github.com/annotated-types/annotated-types
7
+ Project-URL: Changelog, https://github.com/annotated-types/annotated-types/releases
8
+ Author-email: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Samuel Colvin <s@muelcolvin.com>, Zac Hatfield-Dodds <zac@zhd.dev>
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Environment :: MacOS X
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Information Technology
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: Unix
18
+ Classifier: Programming Language :: Python :: 3 :: Only
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: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.8
27
+ Requires-Dist: typing-extensions>=4.0.0; python_version < '3.9'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # annotated-types
31
+
32
+ [![CI](https://github.com/annotated-types/annotated-types/workflows/CI/badge.svg?event=push)](https://github.com/annotated-types/annotated-types/actions?query=event%3Apush+branch%3Amain+workflow%3ACI)
33
+ [![pypi](https://img.shields.io/pypi/v/annotated-types.svg)](https://pypi.python.org/pypi/annotated-types)
34
+ [![versions](https://img.shields.io/pypi/pyversions/annotated-types.svg)](https://github.com/annotated-types/annotated-types)
35
+ [![license](https://img.shields.io/github/license/annotated-types/annotated-types.svg)](https://github.com/annotated-types/annotated-types/blob/main/LICENSE)
36
+
37
+ [PEP-593](https://peps.python.org/pep-0593/) added `typing.Annotated` as a way of
38
+ adding context-specific metadata to existing types, and specifies that
39
+ `Annotated[T, x]` _should_ be treated as `T` by any tool or library without special
40
+ logic for `x`.
41
+
42
+ This package provides metadata objects which can be used to represent common
43
+ constraints such as upper and lower bounds on scalar values and collection sizes,
44
+ a `Predicate` marker for runtime checks, and
45
+ descriptions of how we intend these metadata to be interpreted. In some cases,
46
+ we also note alternative representations which do not require this package.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install annotated-types
52
+ ```
53
+
54
+ ## Examples
55
+
56
+ ```python
57
+ from typing import Annotated
58
+ from annotated_types import Gt, Len, Predicate
59
+
60
+ class MyClass:
61
+ age: Annotated[int, Gt(18)] # Valid: 19, 20, ...
62
+ # Invalid: 17, 18, "19", 19.0, ...
63
+ factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5, 7, 11, ...
64
+ # Invalid: 4, 8, -2, 5.0, "prime", ...
65
+
66
+ my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10, 20, 30, 40, 50]
67
+ # Invalid: (1, 2), ["abc"], [0] * 20
68
+ ```
69
+
70
+ ## Documentation
71
+
72
+ _While `annotated-types` avoids runtime checks for performance, users should not
73
+ construct invalid combinations such as `MultipleOf("non-numeric")` or `Annotated[int, Len(3)]`.
74
+ Downstream implementors may choose to raise an error, emit a warning, silently ignore
75
+ a metadata item, etc., if the metadata objects described below are used with an
76
+ incompatible type - or for any other reason!_
77
+
78
+ ### Gt, Ge, Lt, Le
79
+
80
+ Express inclusive and/or exclusive bounds on orderable values - which may be numbers,
81
+ dates, times, strings, sets, etc. Note that the boundary value need not be of the
82
+ same type that was annotated, so long as they can be compared: `Annotated[int, Gt(1.5)]`
83
+ is fine, for example, and implies that the value is an integer x such that `x > 1.5`.
84
+
85
+ We suggest that implementors may also interpret `functools.partial(operator.le, 1.5)`
86
+ as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime dependency on
87
+ the `annotated-types` package.
88
+
89
+ To be explicit, these types have the following meanings:
90
+
91
+ * `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive minimum
92
+ * `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to inclusive minimum
93
+ * `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum
94
+ * `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to inclusive maximum
95
+
96
+ ### Interval
97
+
98
+ `Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound with a single
99
+ metadata object. `None` attributes should be ignored, and non-`None` attributes
100
+ treated as per the single bounds above.
101
+
102
+ ### MultipleOf
103
+
104
+ `MultipleOf(multiple_of=x)` might be interpreted in two ways:
105
+
106
+ 1. Python semantics, implying `value % multiple_of == 0`, or
107
+ 2. [JSONschema semantics](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1),
108
+ where `int(value / multiple_of) == value / multiple_of`.
109
+
110
+ We encourage users to be aware of these two common interpretations and their
111
+ distinct behaviours, especially since very large or non-integer numbers make
112
+ it easy to cause silent data corruption due to floating-point imprecision.
113
+
114
+ We encourage libraries to carefully document which interpretation they implement.
115
+
116
+ ### MinLen, MaxLen, Len
117
+
118
+ `Len()` implies that `min_length <= len(value) <= max_length` - lower and upper bounds are inclusive.
119
+
120
+ As well as `Len()` which can optionally include upper and lower bounds, we also
121
+ provide `MinLen(x)` and `MaxLen(y)` which are equivalent to `Len(min_length=x)`
122
+ and `Len(max_length=y)` respectively.
123
+
124
+ `Len`, `MinLen`, and `MaxLen` may be used with any type which supports `len(value)`.
125
+
126
+ Examples of usage:
127
+
128
+ * `Annotated[list, MaxLen(10)]` (or `Annotated[list, Len(max_length=10))`) - list must have a length of 10 or less
129
+ * `Annotated[str, MaxLen(10)]` - string must have a length of 10 or less
130
+ * `Annotated[list, MinLen(3))` (or `Annotated[list, Len(min_length=3))`) - list must have a length of 3 or more
131
+ * `Annotated[list, Len(4, 6)]` - list must have a length of 4, 5, or 6
132
+ * `Annotated[list, Len(8, 8)]` - list must have a length of exactly 8
133
+
134
+ #### Changed in v0.4.0
135
+
136
+ * `min_inclusive` has been renamed to `min_length`, no change in meaning
137
+ * `max_exclusive` has been renamed to `max_length`, upper bound is now **inclusive** instead of **exclusive**
138
+ * The recommendation that slices are interpreted as `Len` has been removed due to ambiguity and different semantic
139
+ meaning of the upper bound in slices vs. `Len`
140
+
141
+ See [issue #23](https://github.com/annotated-types/annotated-types/issues/23) for discussion.
142
+
143
+ ### Timezone
144
+
145
+ `Timezone` can be used with a `datetime` or a `time` to express which timezones
146
+ are allowed. `Annotated[datetime, Timezone(None)]` must be a naive datetime.
147
+ `Timezone[...]` ([literal ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis))
148
+ expresses that any timezone-aware datetime is allowed. You may also pass a specific
149
+ timezone string or [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects)
150
+ object such as `Timezone(timezone.utc)` or `Timezone("Africa/Abidjan")` to express that you only
151
+ allow a specific timezone, though we note that this is often a symptom of fragile design.
152
+
153
+ #### Changed in v0.x.x
154
+
155
+ * `Timezone` accepts [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) objects instead of
156
+ `timezone`, extending compatibility to [`zoneinfo`](https://docs.python.org/3/library/zoneinfo.html) and third party libraries.
157
+
158
+ ### Unit
159
+
160
+ `Unit(unit: str)` expresses that the annotated numeric value is the magnitude of
161
+ a quantity with the specified unit. For example, `Annotated[float, Unit("m/s")]`
162
+ would be a float representing a velocity in meters per second.
163
+
164
+ Please note that `annotated_types` itself makes no attempt to parse or validate
165
+ the unit string in any way. That is left entirely to downstream libraries,
166
+ such as [`pint`](https://pint.readthedocs.io) or
167
+ [`astropy.units`](https://docs.astropy.org/en/stable/units/).
168
+
169
+ An example of how a library might use this metadata:
170
+
171
+ ```python
172
+ from annotated_types import Unit
173
+ from typing import Annotated, TypeVar, Callable, Any, get_origin, get_args
174
+
175
+ # given a type annotated with a unit:
176
+ Meters = Annotated[float, Unit("m")]
177
+
178
+
179
+ # you can cast the annotation to a specific unit type with any
180
+ # callable that accepts a string and returns the desired type
181
+ T = TypeVar("T")
182
+ def cast_unit(tp: Any, unit_cls: Callable[[str], T]) -> T | None:
183
+ if get_origin(tp) is Annotated:
184
+ for arg in get_args(tp):
185
+ if isinstance(arg, Unit):
186
+ return unit_cls(arg.unit)
187
+ return None
188
+
189
+
190
+ # using `pint`
191
+ import pint
192
+ pint_unit = cast_unit(Meters, pint.Unit)
193
+
194
+
195
+ # using `astropy.units`
196
+ import astropy.units as u
197
+ astropy_unit = cast_unit(Meters, u.Unit)
198
+ ```
199
+
200
+ ### Predicate
201
+
202
+ `Predicate(func: Callable)` expresses that `func(value)` is truthy for valid values.
203
+ Users should prefer the statically inspectable metadata above, but if you need
204
+ the full power and flexibility of arbitrary runtime predicates... here it is.
205
+
206
+ For some common constraints, we provide generic types:
207
+
208
+ * `IsLower = Annotated[T, Predicate(str.islower)]`
209
+ * `IsUpper = Annotated[T, Predicate(str.isupper)]`
210
+ * `IsDigit = Annotated[T, Predicate(str.isdigit)]`
211
+ * `IsFinite = Annotated[T, Predicate(math.isfinite)]`
212
+ * `IsNotFinite = Annotated[T, Predicate(Not(math.isfinite))]`
213
+ * `IsNan = Annotated[T, Predicate(math.isnan)]`
214
+ * `IsNotNan = Annotated[T, Predicate(Not(math.isnan))]`
215
+ * `IsInfinite = Annotated[T, Predicate(math.isinf)]`
216
+ * `IsNotInfinite = Annotated[T, Predicate(Not(math.isinf))]`
217
+
218
+ so that you can write e.g. `x: IsFinite[float] = 2.0` instead of the longer
219
+ (but exactly equivalent) `x: Annotated[float, Predicate(math.isfinite)] = 2.0`.
220
+
221
+ Some libraries might have special logic to handle known or understandable predicates,
222
+ for example by checking for `str.isdigit` and using its presence to both call custom
223
+ logic to enforce digit-only strings, and customise some generated external schema.
224
+ Users are therefore encouraged to avoid indirection like `lambda s: s.lower()`, in
225
+ favor of introspectable methods such as `str.lower` or `re.compile("pattern").search`.
226
+
227
+ To enable basic negation of commonly used predicates like `math.isnan` without introducing introspection that makes it impossible for implementers to introspect the predicate we provide a `Not` wrapper that simply negates the predicate in an introspectable manner. Several of the predicates listed above are created in this manner.
228
+
229
+ We do not specify what behaviour should be expected for predicates that raise
230
+ an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
231
+ skip invalid constraints, or statically raise an error; or it might try calling it
232
+ and then propagate or discard the resulting
233
+ `TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object`
234
+ exception. We encourage libraries to document the behaviour they choose.
235
+
236
+ ### Doc
237
+
238
+ `doc()` can be used to add documentation information in `Annotated`, for function and method parameters, variables, class attributes, return types, and any place where `Annotated` can be used.
239
+
240
+ It expects a value that can be statically analyzed, as the main use case is for static analysis, editors, documentation generators, and similar tools.
241
+
242
+ It returns a `DocInfo` class with a single attribute `documentation` containing the value passed to `doc()`.
243
+
244
+ This is the early adopter's alternative form of the [`typing-doc` proposal](https://github.com/tiangolo/fastapi/blob/typing-doc/typing_doc.md).
245
+
246
+ ### Integrating downstream types with `GroupedMetadata`
247
+
248
+ Implementers may choose to provide a convenience wrapper that groups multiple pieces of metadata.
249
+ This can help reduce verbosity and cognitive overhead for users.
250
+ For example, an implementer like Pydantic might provide a `Field` or `Meta` type that accepts keyword arguments and transforms these into low-level metadata:
251
+
252
+ ```python
253
+ from dataclasses import dataclass
254
+ from typing import Iterator
255
+ from annotated_types import GroupedMetadata, Ge
256
+
257
+ @dataclass
258
+ class Field(GroupedMetadata):
259
+ ge: int | None = None
260
+ description: str | None = None
261
+
262
+ def __iter__(self) -> Iterator[object]:
263
+ # Iterating over a GroupedMetadata object should yield annotated-types
264
+ # constraint metadata objects which describe it as fully as possible,
265
+ # and may include other unknown objects too.
266
+ if self.ge is not None:
267
+ yield Ge(self.ge)
268
+ if self.description is not None:
269
+ yield Description(self.description)
270
+ ```
271
+
272
+ Libraries consuming annotated-types constraints should check for `GroupedMetadata` and unpack it by iterating over the object and treating the results as if they had been "unpacked" in the `Annotated` type. The same logic should be applied to the [PEP 646 `Unpack` type](https://peps.python.org/pep-0646/), so that `Annotated[T, Field(...)]`, `Annotated[T, Unpack[Field(...)]]` and `Annotated[T, *Field(...)]` are all treated consistently.
273
+
274
+ Libraries consuming annotated-types should also ignore any metadata they do not recongize that came from unpacking a `GroupedMetadata`, just like they ignore unrecognized metadata in `Annotated` itself.
275
+
276
+ Our own `annotated_types.Interval` class is a `GroupedMetadata` which unpacks itself into `Gt`, `Lt`, etc., so this is not an abstract concern. Similarly, `annotated_types.Len` is a `GroupedMetadata` which unpacks itself into `MinLen` (optionally) and `MaxLen`.
277
+
278
+ ### Consuming metadata
279
+
280
+ We intend to not be prescriptive as to _how_ the metadata and constraints are used, but as an example of how one might parse constraints from types annotations see our [implementation in `test_main.py`](https://github.com/annotated-types/annotated-types/blob/f59cf6d1b5255a0fe359b93896759a180bec30ae/tests/test_main.py#L94-L103).
281
+
282
+ It is up to the implementer to determine how this metadata is used.
283
+ You could use the metadata for runtime type checking, for generating schemas or to generate example data, amongst other use cases.
284
+
285
+ ## Design & History
286
+
287
+ This package was designed at the PyCon 2022 sprints by the maintainers of Pydantic
288
+ and Hypothesis, with the goal of making it as easy as possible for end-users to
289
+ provide more informative annotations for use by runtime libraries.
290
+
291
+ It is deliberately minimal, and following PEP-593 allows considerable downstream
292
+ discretion in what (if anything!) they choose to support. Nonetheless, we expect
293
+ that staying simple and covering _only_ the most common use-cases will give users
294
+ and maintainers the best experience we can. If you'd like more constraints for your
295
+ types - follow our lead, by defining them and documenting them downstream!
.venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/RECORD ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ annotated_types-0.7.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
2
+ annotated_types-0.7.0.dist-info/METADATA,sha256=7ltqxksJJ0wCYFGBNIQCWTlWQGeAH0hRFdnK3CB895E,15046
3
+ annotated_types-0.7.0.dist-info/RECORD,,
4
+ annotated_types-0.7.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ annotated_types-0.7.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
6
+ annotated_types-0.7.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083
7
+ annotated_types/__init__.py,sha256=RynLsRKUEGI0KimXydlD1fZEfEzWwDo0Uon3zOKhG1Q,13819
8
+ annotated_types/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ annotated_types/test_cases.py,sha256=zHFX6EpcMbGJ8FzBYDbO56bPwx_DYIVSKbZM-4B3_lg,6421
.venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.11/site-packages/annotated_types-0.7.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.24.2
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv/lib/python3.11/site-packages/charset_normalizer/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from .cli import cli_detect
4
+
5
+ if __name__ == "__main__":
6
+ cli_detect()
.venv/lib/python3.11/site-packages/charset_normalizer/api.py ADDED
@@ -0,0 +1,988 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from os import PathLike
5
+ from typing import BinaryIO
6
+
7
+ from .cd import (
8
+ coherence_ratio,
9
+ encoding_languages,
10
+ mb_encoding_languages,
11
+ merge_coherence_ratios,
12
+ )
13
+ from .constant import (
14
+ IANA_SUPPORTED,
15
+ IANA_SUPPORTED_SIMILAR,
16
+ TOO_BIG_SEQUENCE,
17
+ TOO_SMALL_SEQUENCE,
18
+ TRACE,
19
+ )
20
+ from .md import mess_ratio
21
+ from .models import CharsetMatch, CharsetMatches
22
+ from .utils import (
23
+ any_specified_encoding,
24
+ cut_sequence_chunks,
25
+ iana_name,
26
+ identify_sig_or_bom,
27
+ is_multi_byte_encoding,
28
+ should_strip_sig_or_bom,
29
+ )
30
+
31
+ logger = logging.getLogger("charset_normalizer")
32
+ explain_handler = logging.StreamHandler()
33
+ explain_handler.setFormatter(
34
+ logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
35
+ )
36
+
37
+ # Pre-compute a reordered encoding list: multibyte first, then single-byte.
38
+ # This allows the mb_definitive_match optimization to fire earlier, skipping
39
+ # all single-byte encodings for genuine CJK content. Multibyte codecs
40
+ # hard-fail (UnicodeDecodeError) on single-byte data almost instantly, so
41
+ # testing them first costs negligible time for non-CJK files.
42
+ _mb_supported: list[str] = []
43
+ _sb_supported: list[str] = []
44
+
45
+ for _supported_enc in IANA_SUPPORTED:
46
+ try:
47
+ if is_multi_byte_encoding(_supported_enc):
48
+ _mb_supported.append(_supported_enc)
49
+ else:
50
+ _sb_supported.append(_supported_enc)
51
+ except ImportError:
52
+ _sb_supported.append(_supported_enc)
53
+
54
+ IANA_SUPPORTED_MB_FIRST: list[str] = _mb_supported + _sb_supported
55
+
56
+
57
+ def from_bytes(
58
+ sequences: bytes | bytearray,
59
+ steps: int = 5,
60
+ chunk_size: int = 512,
61
+ threshold: float = 0.2,
62
+ cp_isolation: list[str] | None = None,
63
+ cp_exclusion: list[str] | None = None,
64
+ preemptive_behaviour: bool = True,
65
+ explain: bool = False,
66
+ language_threshold: float = 0.1,
67
+ enable_fallback: bool = True,
68
+ ) -> CharsetMatches:
69
+ """
70
+ Given a raw bytes sequence, return the best possibles charset usable to render str objects.
71
+ If there is no results, it is a strong indicator that the source is binary/not text.
72
+ By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence.
73
+ And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.
74
+
75
+ The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page
76
+ but never take it for granted. Can improve the performance.
77
+
78
+ You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that
79
+ purpose.
80
+
81
+ This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32.
82
+ By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain'
83
+ toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging.
84
+ Custom logging format and handler can be set manually.
85
+ """
86
+
87
+ if not isinstance(sequences, (bytearray, bytes)):
88
+ raise TypeError(
89
+ "Expected object of type bytes or bytearray, got: {}".format(
90
+ type(sequences)
91
+ )
92
+ )
93
+
94
+ if explain:
95
+ previous_logger_level: int = logger.level
96
+ logger.addHandler(explain_handler)
97
+ logger.setLevel(TRACE)
98
+
99
+ length: int = len(sequences)
100
+
101
+ if length == 0:
102
+ logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.")
103
+ if explain: # Defensive: ensure exit path clean handler
104
+ logger.removeHandler(explain_handler)
105
+ logger.setLevel(previous_logger_level)
106
+ return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])
107
+
108
+ if cp_isolation is not None:
109
+ logger.log(
110
+ TRACE,
111
+ "cp_isolation is set. use this flag for debugging purpose. "
112
+ "limited list of encoding allowed : %s.",
113
+ ", ".join(cp_isolation),
114
+ )
115
+ cp_isolation = [iana_name(cp, False) for cp in cp_isolation]
116
+ else:
117
+ cp_isolation = []
118
+
119
+ if cp_exclusion is not None:
120
+ logger.log(
121
+ TRACE,
122
+ "cp_exclusion is set. use this flag for debugging purpose. "
123
+ "limited list of encoding excluded : %s.",
124
+ ", ".join(cp_exclusion),
125
+ )
126
+ cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion]
127
+ else:
128
+ cp_exclusion = []
129
+
130
+ if length <= (chunk_size * steps):
131
+ logger.log(
132
+ TRACE,
133
+ "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.",
134
+ steps,
135
+ chunk_size,
136
+ length,
137
+ )
138
+ steps = 1
139
+ chunk_size = length
140
+
141
+ if steps > 1 and length / steps < chunk_size:
142
+ chunk_size = int(length / steps)
143
+
144
+ is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE
145
+ is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE
146
+
147
+ if is_too_small_sequence:
148
+ logger.log(
149
+ TRACE,
150
+ "Trying to detect encoding from a tiny portion of ({}) byte(s).".format(
151
+ length
152
+ ),
153
+ )
154
+ elif is_too_large_sequence:
155
+ logger.log(
156
+ TRACE,
157
+ "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format(
158
+ length
159
+ ),
160
+ )
161
+
162
+ prioritized_encodings: list[str] = []
163
+
164
+ specified_encoding: str | None = (
165
+ any_specified_encoding(sequences) if preemptive_behaviour else None
166
+ )
167
+
168
+ if specified_encoding is not None:
169
+ prioritized_encodings.append(specified_encoding)
170
+ logger.log(
171
+ TRACE,
172
+ "Detected declarative mark in sequence. Priority +1 given for %s.",
173
+ specified_encoding,
174
+ )
175
+
176
+ tested: set[str] = set()
177
+ tested_but_hard_failure: list[str] = []
178
+ tested_but_soft_failure: list[str] = []
179
+ soft_failure_skip: set[str] = set()
180
+ success_fast_tracked: set[str] = set()
181
+
182
+ # Cache for decoded payload deduplication: hash(decoded_payload) -> (mean_mess_ratio, cd_ratios_merged, passed)
183
+ # When multiple encodings decode to the exact same string, we can skip the expensive
184
+ # mess_ratio and coherence_ratio analysis and reuse the results from the first encoding.
185
+ payload_result_cache: dict[int, tuple[float, list[tuple[str, float]], bool]] = {}
186
+
187
+ # When a definitive result (chaos=0.0 and good coherence) is found after testing
188
+ # the prioritized encodings (ascii, utf_8), we can significantly reduce the remaining
189
+ # work. Encodings that target completely different language families (e.g., Cyrillic
190
+ # when the definitive match is Latin) are skipped entirely.
191
+ # Additionally, for same-family encodings that pass chaos probing, we reuse the
192
+ # definitive match's coherence ratios instead of recomputing them — a major savings
193
+ # since coherence_ratio accounts for ~30% of total time on slow Latin files.
194
+ definitive_match_found: bool = False
195
+ definitive_target_languages: set[str] = set()
196
+ # After the definitive match fires, we cap the number of additional same-family
197
+ # single-byte encodings that pass chaos probing. Once we've accumulated enough
198
+ # good candidates (N), further same-family SB encodings are unlikely to produce
199
+ # a better best() result and just waste mess_ratio + coherence_ratio time.
200
+ # The first encoding to trigger the definitive match is NOT counted (it's already in).
201
+ post_definitive_sb_success_count: int = 0
202
+ POST_DEFINITIVE_SB_CAP: int = 7
203
+
204
+ # When a non-UTF multibyte encoding passes chaos probing with significant multibyte
205
+ # content (decoded length < 98% of raw length), skip all remaining single-byte encodings.
206
+ # Rationale: multi-byte decoders (CJK) have strict byte-sequence validation — if they
207
+ # decode without error AND pass chaos probing with substantial multibyte content, the
208
+ # data is genuinely multibyte encoded. Single-byte encodings will always decode (every
209
+ # byte maps to something) but waste time on mess_ratio before failing.
210
+ # The 98% threshold prevents false triggers on files that happen to have a few valid
211
+ # multibyte pairs (e.g., cp424/_ude_1.txt where big5 decodes with 99% ratio).
212
+ mb_definitive_match_found: bool = False
213
+
214
+ fallback_ascii: CharsetMatch | None = None
215
+ fallback_u8: CharsetMatch | None = None
216
+ fallback_specified: CharsetMatch | None = None
217
+
218
+ results: CharsetMatches = CharsetMatches()
219
+
220
+ early_stop_results: CharsetMatches = CharsetMatches()
221
+
222
+ sig_encoding, sig_payload = identify_sig_or_bom(sequences)
223
+
224
+ if sig_encoding is not None:
225
+ prioritized_encodings.append(sig_encoding)
226
+ logger.log(
227
+ TRACE,
228
+ "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.",
229
+ len(sig_payload),
230
+ sig_encoding,
231
+ )
232
+
233
+ prioritized_encodings.append("ascii")
234
+
235
+ if "utf_8" not in prioritized_encodings:
236
+ prioritized_encodings.append("utf_8")
237
+
238
+ for encoding_iana in prioritized_encodings + IANA_SUPPORTED_MB_FIRST:
239
+ if cp_isolation and encoding_iana not in cp_isolation:
240
+ continue
241
+
242
+ if cp_exclusion and encoding_iana in cp_exclusion:
243
+ continue
244
+
245
+ if encoding_iana in tested:
246
+ continue
247
+
248
+ tested.add(encoding_iana)
249
+
250
+ decoded_payload: str | None = None
251
+ bom_or_sig_available: bool = sig_encoding == encoding_iana
252
+ strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom(
253
+ encoding_iana
254
+ )
255
+
256
+ if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available:
257
+ logger.log(
258
+ TRACE,
259
+ "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.",
260
+ encoding_iana,
261
+ )
262
+ continue
263
+ if encoding_iana in {"utf_7"} and not bom_or_sig_available:
264
+ logger.log(
265
+ TRACE,
266
+ "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.",
267
+ encoding_iana,
268
+ )
269
+ continue
270
+
271
+ # Skip encodings similar to ones that already soft-failed (high mess ratio).
272
+ # Checked BEFORE the expensive decode attempt.
273
+ if encoding_iana in soft_failure_skip:
274
+ logger.log(
275
+ TRACE,
276
+ "%s is deemed too similar to a code page that was already considered unsuited. Continuing!",
277
+ encoding_iana,
278
+ )
279
+ continue
280
+
281
+ # Skip encodings that were already fast-tracked from a similar successful encoding.
282
+ if encoding_iana in success_fast_tracked:
283
+ logger.log(
284
+ TRACE,
285
+ "Skipping %s: already fast-tracked from a similar successful encoding.",
286
+ encoding_iana,
287
+ )
288
+ continue
289
+
290
+ try:
291
+ is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana)
292
+ except (ModuleNotFoundError, ImportError): # Defensive:
293
+ logger.log(
294
+ TRACE,
295
+ "Encoding %s does not provide an IncrementalDecoder",
296
+ encoding_iana,
297
+ )
298
+ continue
299
+
300
+ # When we've already found a definitive match (chaos=0.0 with good coherence)
301
+ # after testing the prioritized encodings, skip encodings that target
302
+ # completely different language families. This avoids running expensive
303
+ # mess_ratio + coherence_ratio on clearly unrelated candidates (e.g., Cyrillic
304
+ # when the definitive match is Latin-based).
305
+ if definitive_match_found:
306
+ if not is_multi_byte_decoder:
307
+ enc_languages = set(encoding_languages(encoding_iana))
308
+ else:
309
+ enc_languages = set(mb_encoding_languages(encoding_iana))
310
+ if not enc_languages.intersection(definitive_target_languages):
311
+ logger.log(
312
+ TRACE,
313
+ "Skipping %s: definitive match already found, this encoding targets different languages (%s vs %s).",
314
+ encoding_iana,
315
+ enc_languages,
316
+ definitive_target_languages,
317
+ )
318
+ continue
319
+
320
+ # After the definitive match, cap the number of additional same-family
321
+ # single-byte encodings that pass chaos probing. This avoids testing the
322
+ # tail of rare, low-value same-family encodings (mac_iceland, cp860, etc.)
323
+ # that almost never change best() but each cost ~1-2ms of mess_ratio + coherence.
324
+ if (
325
+ definitive_match_found
326
+ and not is_multi_byte_decoder
327
+ and post_definitive_sb_success_count >= POST_DEFINITIVE_SB_CAP
328
+ ):
329
+ logger.log(
330
+ TRACE,
331
+ "Skipping %s: already accumulated %d same-family results after definitive match (cap=%d).",
332
+ encoding_iana,
333
+ post_definitive_sb_success_count,
334
+ POST_DEFINITIVE_SB_CAP,
335
+ )
336
+ continue
337
+
338
+ # When a multibyte encoding with significant multibyte content has already
339
+ # passed chaos probing, skip all single-byte encodings. They will either fail
340
+ # chaos probing (wasting mess_ratio time) or produce inferior results.
341
+ if mb_definitive_match_found and not is_multi_byte_decoder:
342
+ logger.log(
343
+ TRACE,
344
+ "Skipping single-byte %s: multi-byte definitive match already found.",
345
+ encoding_iana,
346
+ )
347
+ continue
348
+
349
+ try:
350
+ if is_too_large_sequence and is_multi_byte_decoder is False:
351
+ str(
352
+ (
353
+ sequences[: int(50e4)]
354
+ if strip_sig_or_bom is False
355
+ else sequences[len(sig_payload) : int(50e4)]
356
+ ),
357
+ encoding=encoding_iana,
358
+ )
359
+ else:
360
+ # UTF-7 BOM is encoded in modified Base64 whose byte boundary
361
+ # can overlap with the next character. Stripping raw SIG bytes
362
+ # before decoding may leave stray bytes that decode as garbage.
363
+ # Decode the full sequence and remove the leading BOM char instead.
364
+ # see https://github.com/jawah/charset_normalizer/issues/718
365
+ # and https://github.com/jawah/charset_normalizer/issues/716
366
+ if encoding_iana == "utf_7" and bom_or_sig_available:
367
+ decoded_payload = str(
368
+ sequences,
369
+ encoding=encoding_iana,
370
+ )
371
+ if decoded_payload and decoded_payload[0] == "\ufeff":
372
+ decoded_payload = decoded_payload[1:]
373
+ else:
374
+ decoded_payload = str(
375
+ (
376
+ sequences
377
+ if strip_sig_or_bom is False
378
+ else sequences[len(sig_payload) :]
379
+ ),
380
+ encoding=encoding_iana,
381
+ )
382
+ except (UnicodeDecodeError, LookupError) as e:
383
+ if not isinstance(e, LookupError):
384
+ logger.log(
385
+ TRACE,
386
+ "Code page %s does not fit given bytes sequence at ALL. %s",
387
+ encoding_iana,
388
+ str(e),
389
+ )
390
+ tested_but_hard_failure.append(encoding_iana)
391
+ continue
392
+
393
+ r_ = range(
394
+ 0 if not bom_or_sig_available else len(sig_payload),
395
+ length,
396
+ int(length / steps),
397
+ )
398
+
399
+ multi_byte_bonus: bool = (
400
+ is_multi_byte_decoder
401
+ and decoded_payload is not None
402
+ and len(decoded_payload) < length
403
+ )
404
+
405
+ if multi_byte_bonus:
406
+ logger.log(
407
+ TRACE,
408
+ "Code page %s is a multi byte encoding table and it appear that at least one character "
409
+ "was encoded using n-bytes.",
410
+ encoding_iana,
411
+ )
412
+
413
+ # Payload-hash deduplication: if another encoding already decoded to the
414
+ # exact same string, reuse its mess_ratio and coherence results entirely.
415
+ # This is strictly more general than the old IANA_SUPPORTED_SIMILAR approach
416
+ # because it catches ALL identical decoding, not just pre-mapped ones.
417
+ if decoded_payload is not None and not is_multi_byte_decoder:
418
+ payload_hash: int = hash(decoded_payload)
419
+ cached = payload_result_cache.get(payload_hash)
420
+ if cached is not None:
421
+ cached_mess, cached_cd, cached_passed = cached
422
+ if cached_passed:
423
+ # The previous encoding with identical output passed chaos probing.
424
+ fast_match = CharsetMatch(
425
+ sequences,
426
+ encoding_iana,
427
+ cached_mess,
428
+ bom_or_sig_available,
429
+ cached_cd,
430
+ (
431
+ decoded_payload
432
+ if (
433
+ is_too_large_sequence is False
434
+ or encoding_iana
435
+ in [specified_encoding, "ascii", "utf_8"]
436
+ )
437
+ else None
438
+ ),
439
+ preemptive_declaration=specified_encoding,
440
+ )
441
+ results.append(fast_match)
442
+ success_fast_tracked.add(encoding_iana)
443
+ logger.log(
444
+ TRACE,
445
+ "%s fast-tracked (identical decoded payload to a prior encoding, chaos=%f %%).",
446
+ encoding_iana,
447
+ round(cached_mess * 100, ndigits=3),
448
+ )
449
+
450
+ if (
451
+ encoding_iana in [specified_encoding, "ascii", "utf_8"]
452
+ and cached_mess < 0.1
453
+ ):
454
+ if cached_mess == 0.0:
455
+ logger.debug(
456
+ "Encoding detection: %s is most likely the one.",
457
+ fast_match.encoding,
458
+ )
459
+ if explain:
460
+ logger.removeHandler(explain_handler)
461
+ logger.setLevel(previous_logger_level)
462
+ return CharsetMatches([fast_match])
463
+ early_stop_results.append(fast_match)
464
+
465
+ if (
466
+ len(early_stop_results)
467
+ and (specified_encoding is None or specified_encoding in tested)
468
+ and "ascii" in tested
469
+ and "utf_8" in tested
470
+ ):
471
+ probable_result: CharsetMatch = early_stop_results.best() # type: ignore[assignment]
472
+ logger.debug(
473
+ "Encoding detection: %s is most likely the one.",
474
+ probable_result.encoding,
475
+ )
476
+ if explain:
477
+ logger.removeHandler(explain_handler)
478
+ logger.setLevel(previous_logger_level)
479
+ return CharsetMatches([probable_result])
480
+
481
+ continue
482
+ else:
483
+ # The previous encoding with identical output failed chaos probing.
484
+ tested_but_soft_failure.append(encoding_iana)
485
+ logger.log(
486
+ TRACE,
487
+ "%s fast-skipped (identical decoded payload to a prior encoding that failed chaos probing).",
488
+ encoding_iana,
489
+ )
490
+ # Prepare fallbacks for special encodings even when skipped.
491
+ if enable_fallback and encoding_iana in [
492
+ "ascii",
493
+ "utf_8",
494
+ specified_encoding,
495
+ "utf_16",
496
+ "utf_32",
497
+ ]:
498
+ fallback_entry = CharsetMatch(
499
+ sequences,
500
+ encoding_iana,
501
+ threshold,
502
+ bom_or_sig_available,
503
+ [],
504
+ decoded_payload,
505
+ preemptive_declaration=specified_encoding,
506
+ )
507
+ if encoding_iana == specified_encoding:
508
+ fallback_specified = fallback_entry
509
+ elif encoding_iana == "ascii":
510
+ fallback_ascii = fallback_entry
511
+ else:
512
+ fallback_u8 = fallback_entry
513
+ continue
514
+
515
+ max_chunk_gave_up: int = int(len(r_) / 4)
516
+
517
+ max_chunk_gave_up = max(max_chunk_gave_up, 2)
518
+ early_stop_count: int = 0
519
+ lazy_str_hard_failure = False
520
+
521
+ md_chunks: list[str] = []
522
+ md_ratios = []
523
+
524
+ try:
525
+ for chunk in cut_sequence_chunks(
526
+ sequences,
527
+ encoding_iana,
528
+ r_,
529
+ chunk_size,
530
+ bom_or_sig_available,
531
+ strip_sig_or_bom,
532
+ sig_payload,
533
+ is_multi_byte_decoder,
534
+ decoded_payload,
535
+ ):
536
+ md_chunks.append(chunk)
537
+
538
+ md_ratios.append(
539
+ mess_ratio(
540
+ chunk,
541
+ threshold,
542
+ explain is True and 1 <= len(cp_isolation) <= 2,
543
+ )
544
+ )
545
+
546
+ if md_ratios[-1] >= threshold:
547
+ early_stop_count += 1
548
+
549
+ if (early_stop_count >= max_chunk_gave_up) or (
550
+ bom_or_sig_available and strip_sig_or_bom is False
551
+ ):
552
+ break
553
+ except (
554
+ UnicodeDecodeError
555
+ ) as e: # Lazy str loading may have missed something there
556
+ logger.log(
557
+ TRACE,
558
+ "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s",
559
+ encoding_iana,
560
+ str(e),
561
+ )
562
+ early_stop_count = max_chunk_gave_up
563
+ lazy_str_hard_failure = True
564
+
565
+ # We might want to check the sequence again with the whole content
566
+ # Only if initial MD tests passes
567
+ if (
568
+ not lazy_str_hard_failure
569
+ and is_too_large_sequence
570
+ and not is_multi_byte_decoder
571
+ ):
572
+ try:
573
+ sequences[int(50e3) :].decode(encoding_iana, errors="strict")
574
+ except UnicodeDecodeError as e:
575
+ logger.log(
576
+ TRACE,
577
+ "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s",
578
+ encoding_iana,
579
+ str(e),
580
+ )
581
+ tested_but_hard_failure.append(encoding_iana)
582
+ continue
583
+
584
+ mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0
585
+ if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up:
586
+ tested_but_soft_failure.append(encoding_iana)
587
+ if encoding_iana in IANA_SUPPORTED_SIMILAR:
588
+ soft_failure_skip.update(IANA_SUPPORTED_SIMILAR[encoding_iana])
589
+ # Cache this soft-failure so identical decoding from other encodings
590
+ # can be skipped immediately.
591
+ if decoded_payload is not None and not is_multi_byte_decoder:
592
+ payload_result_cache.setdefault(
593
+ hash(decoded_payload), (mean_mess_ratio, [], False)
594
+ )
595
+ logger.log(
596
+ TRACE,
597
+ "%s was excluded because of initial chaos probing. Gave up %i time(s). "
598
+ "Computed mean chaos is %f %%.",
599
+ encoding_iana,
600
+ early_stop_count,
601
+ round(mean_mess_ratio * 100, ndigits=3),
602
+ )
603
+ # Preparing those fallbacks in case we got nothing.
604
+ if (
605
+ enable_fallback
606
+ and encoding_iana
607
+ in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"]
608
+ and not lazy_str_hard_failure
609
+ ):
610
+ fallback_entry = CharsetMatch(
611
+ sequences,
612
+ encoding_iana,
613
+ threshold,
614
+ bom_or_sig_available,
615
+ [],
616
+ decoded_payload,
617
+ preemptive_declaration=specified_encoding,
618
+ )
619
+ if encoding_iana == specified_encoding:
620
+ fallback_specified = fallback_entry
621
+ elif encoding_iana == "ascii":
622
+ fallback_ascii = fallback_entry
623
+ else:
624
+ fallback_u8 = fallback_entry
625
+ continue
626
+
627
+ logger.log(
628
+ TRACE,
629
+ "%s passed initial chaos probing. Mean measured chaos is %f %%",
630
+ encoding_iana,
631
+ round(mean_mess_ratio * 100, ndigits=3),
632
+ )
633
+
634
+ if not is_multi_byte_decoder:
635
+ target_languages: list[str] = encoding_languages(encoding_iana)
636
+ else:
637
+ target_languages = mb_encoding_languages(encoding_iana)
638
+
639
+ if target_languages:
640
+ logger.log(
641
+ TRACE,
642
+ "{} should target any language(s) of {}".format(
643
+ encoding_iana, str(target_languages)
644
+ ),
645
+ )
646
+
647
+ cd_ratios = []
648
+
649
+ # Run coherence detection on all chunks. We previously tried limiting to
650
+ # 1-2 chunks for post-definitive encodings to save time, but this caused
651
+ # coverage regressions by producing unrepresentative coherence scores.
652
+ # The SB cap and language-family skip optimizations provide sufficient
653
+ # speedup without sacrificing coherence accuracy.
654
+ if encoding_iana != "ascii":
655
+ # We shall skip the CD when its about ASCII
656
+ # Most of the time its not relevant to run "language-detection" on it.
657
+ for chunk in md_chunks:
658
+ chunk_languages = coherence_ratio(
659
+ chunk,
660
+ language_threshold,
661
+ ",".join(target_languages) if target_languages else None,
662
+ )
663
+
664
+ cd_ratios.append(chunk_languages)
665
+ cd_ratios_merged = merge_coherence_ratios(cd_ratios)
666
+ else:
667
+ cd_ratios_merged = merge_coherence_ratios(cd_ratios)
668
+
669
+ if cd_ratios_merged:
670
+ logger.log(
671
+ TRACE,
672
+ "We detected language {} using {}".format(
673
+ cd_ratios_merged, encoding_iana
674
+ ),
675
+ )
676
+
677
+ current_match = CharsetMatch(
678
+ sequences,
679
+ encoding_iana,
680
+ mean_mess_ratio,
681
+ bom_or_sig_available,
682
+ cd_ratios_merged,
683
+ (
684
+ decoded_payload
685
+ if (
686
+ is_too_large_sequence is False
687
+ or encoding_iana in [specified_encoding, "ascii", "utf_8"]
688
+ )
689
+ else None
690
+ ),
691
+ preemptive_declaration=specified_encoding,
692
+ )
693
+
694
+ results.append(current_match)
695
+
696
+ # Cache the successful result for payload-hash deduplication.
697
+ if decoded_payload is not None and not is_multi_byte_decoder:
698
+ payload_result_cache.setdefault(
699
+ hash(decoded_payload),
700
+ (mean_mess_ratio, cd_ratios_merged, True),
701
+ )
702
+
703
+ # Count post-definitive same-family SB successes for the early termination cap.
704
+ # Only count low-mess encodings (< 2%) toward the cap. High-mess encodings are
705
+ # marginal results that shouldn't prevent better-quality candidates from being
706
+ # tested. For example, iso8859_4 (mess=0%) should not be skipped just because
707
+ # 7 high-mess Latin encodings (cp1252 at 8%, etc.) were tried first.
708
+ if (
709
+ definitive_match_found
710
+ and not is_multi_byte_decoder
711
+ and mean_mess_ratio < 0.02
712
+ ):
713
+ post_definitive_sb_success_count += 1
714
+
715
+ if (
716
+ encoding_iana in [specified_encoding, "ascii", "utf_8"]
717
+ and mean_mess_ratio < 0.1
718
+ ):
719
+ # If md says nothing to worry about, then... stop immediately!
720
+ if mean_mess_ratio == 0.0:
721
+ logger.debug(
722
+ "Encoding detection: %s is most likely the one.",
723
+ current_match.encoding,
724
+ )
725
+ if explain: # Defensive: ensure exit path clean handler
726
+ logger.removeHandler(explain_handler)
727
+ logger.setLevel(previous_logger_level)
728
+ return CharsetMatches([current_match])
729
+
730
+ early_stop_results.append(current_match)
731
+
732
+ if (
733
+ len(early_stop_results)
734
+ and (specified_encoding is None or specified_encoding in tested)
735
+ and "ascii" in tested
736
+ and "utf_8" in tested
737
+ ):
738
+ probable_result = early_stop_results.best() # type: ignore[assignment]
739
+ logger.debug(
740
+ "Encoding detection: %s is most likely the one.",
741
+ probable_result.encoding, # type: ignore[union-attr]
742
+ )
743
+ if explain: # Defensive: ensure exit path clean handler
744
+ logger.removeHandler(explain_handler)
745
+ logger.setLevel(previous_logger_level)
746
+
747
+ return CharsetMatches([probable_result])
748
+
749
+ # Once we find a result with good coherence (>= 0.5) after testing the
750
+ # prioritized encodings (ascii, utf_8), activate "definitive mode": skip
751
+ # encodings that target completely different language families. This avoids
752
+ # running expensive mess_ratio + coherence_ratio on clearly unrelated
753
+ # candidates (e.g., Cyrillic encodings when the match is Latin-based).
754
+ # We require coherence >= 0.5 to avoid false positives (e.g., cp1251 decoding
755
+ # Hebrew text with 0.0 chaos but wrong language detection at coherence 0.33).
756
+ if not definitive_match_found and not is_multi_byte_decoder:
757
+ best_coherence = (
758
+ max((v for _, v in cd_ratios_merged), default=0.0)
759
+ if cd_ratios_merged
760
+ else 0.0
761
+ )
762
+ if best_coherence >= 0.5 and "ascii" in tested and "utf_8" in tested:
763
+ definitive_match_found = True
764
+ definitive_target_languages.update(target_languages)
765
+ logger.log(
766
+ TRACE,
767
+ "Definitive match found: %s (chaos=%.3f, coherence=%.2f). Encodings targeting different language families will be skipped.",
768
+ encoding_iana,
769
+ mean_mess_ratio,
770
+ best_coherence,
771
+ )
772
+
773
+ # When a non-UTF multibyte encoding passes chaos probing with significant
774
+ # multibyte content (decoded < 98% of raw), activate mb_definitive_match.
775
+ # This skips all remaining single-byte encodings which would either soft-fail
776
+ # (running expensive mess_ratio for nothing) or produce inferior results.
777
+ if (
778
+ not mb_definitive_match_found
779
+ and is_multi_byte_decoder
780
+ and multi_byte_bonus
781
+ and decoded_payload is not None
782
+ and len(decoded_payload) < length * 0.98
783
+ and encoding_iana
784
+ not in {
785
+ "utf_8",
786
+ "utf_8_sig",
787
+ "utf_16",
788
+ "utf_16_be",
789
+ "utf_16_le",
790
+ "utf_32",
791
+ "utf_32_be",
792
+ "utf_32_le",
793
+ "utf_7",
794
+ }
795
+ and "ascii" in tested
796
+ and "utf_8" in tested
797
+ ):
798
+ mb_definitive_match_found = True
799
+ logger.log(
800
+ TRACE,
801
+ "Multi-byte definitive match: %s (chaos=%.3f, decoded=%d/%d=%.1f%%). Single-byte encodings will be skipped.",
802
+ encoding_iana,
803
+ mean_mess_ratio,
804
+ len(decoded_payload),
805
+ length,
806
+ len(decoded_payload) / length * 100,
807
+ )
808
+
809
+ if encoding_iana == sig_encoding:
810
+ logger.debug(
811
+ "Encoding detection: %s is most likely the one as we detected a BOM or SIG within "
812
+ "the beginning of the sequence.",
813
+ encoding_iana,
814
+ )
815
+ if explain: # Defensive: ensure exit path clean handler
816
+ logger.removeHandler(explain_handler)
817
+ logger.setLevel(previous_logger_level)
818
+ return CharsetMatches([results[encoding_iana]])
819
+
820
+ if len(results) == 0:
821
+ if fallback_u8 or fallback_ascii or fallback_specified:
822
+ logger.log(
823
+ TRACE,
824
+ "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.",
825
+ )
826
+
827
+ if fallback_specified:
828
+ logger.debug(
829
+ "Encoding detection: %s will be used as a fallback match",
830
+ fallback_specified.encoding,
831
+ )
832
+ results.append(fallback_specified)
833
+ elif (
834
+ (fallback_u8 and fallback_ascii is None)
835
+ or (
836
+ fallback_u8
837
+ and fallback_ascii
838
+ and fallback_u8.fingerprint != fallback_ascii.fingerprint
839
+ )
840
+ or (fallback_u8 is not None)
841
+ ):
842
+ logger.debug("Encoding detection: utf_8 will be used as a fallback match")
843
+ results.append(fallback_u8)
844
+ elif fallback_ascii:
845
+ logger.debug("Encoding detection: ascii will be used as a fallback match")
846
+ results.append(fallback_ascii)
847
+
848
+ if results:
849
+ logger.debug(
850
+ "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.",
851
+ results.best().encoding, # type: ignore
852
+ len(results) - 1,
853
+ )
854
+ else:
855
+ logger.debug("Encoding detection: Unable to determine any suitable charset.")
856
+
857
+ if explain:
858
+ logger.removeHandler(explain_handler)
859
+ logger.setLevel(previous_logger_level)
860
+
861
+ return results
862
+
863
+
864
+ def from_fp(
865
+ fp: BinaryIO,
866
+ steps: int = 5,
867
+ chunk_size: int = 512,
868
+ threshold: float = 0.20,
869
+ cp_isolation: list[str] | None = None,
870
+ cp_exclusion: list[str] | None = None,
871
+ preemptive_behaviour: bool = True,
872
+ explain: bool = False,
873
+ language_threshold: float = 0.1,
874
+ enable_fallback: bool = True,
875
+ ) -> CharsetMatches:
876
+ """
877
+ Same thing than the function from_bytes but using a file pointer that is already ready.
878
+ Will not close the file pointer.
879
+ """
880
+ return from_bytes(
881
+ fp.read(),
882
+ steps,
883
+ chunk_size,
884
+ threshold,
885
+ cp_isolation,
886
+ cp_exclusion,
887
+ preemptive_behaviour,
888
+ explain,
889
+ language_threshold,
890
+ enable_fallback,
891
+ )
892
+
893
+
894
+ def from_path(
895
+ path: str | bytes | PathLike, # type: ignore[type-arg]
896
+ steps: int = 5,
897
+ chunk_size: int = 512,
898
+ threshold: float = 0.20,
899
+ cp_isolation: list[str] | None = None,
900
+ cp_exclusion: list[str] | None = None,
901
+ preemptive_behaviour: bool = True,
902
+ explain: bool = False,
903
+ language_threshold: float = 0.1,
904
+ enable_fallback: bool = True,
905
+ ) -> CharsetMatches:
906
+ """
907
+ Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode.
908
+ Can raise IOError.
909
+ """
910
+ with open(path, "rb") as fp:
911
+ return from_fp(
912
+ fp,
913
+ steps,
914
+ chunk_size,
915
+ threshold,
916
+ cp_isolation,
917
+ cp_exclusion,
918
+ preemptive_behaviour,
919
+ explain,
920
+ language_threshold,
921
+ enable_fallback,
922
+ )
923
+
924
+
925
+ def is_binary(
926
+ fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg]
927
+ steps: int = 5,
928
+ chunk_size: int = 512,
929
+ threshold: float = 0.20,
930
+ cp_isolation: list[str] | None = None,
931
+ cp_exclusion: list[str] | None = None,
932
+ preemptive_behaviour: bool = True,
933
+ explain: bool = False,
934
+ language_threshold: float = 0.1,
935
+ enable_fallback: bool = False,
936
+ ) -> bool:
937
+ """
938
+ Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string.
939
+ Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match
940
+ are disabled to be stricter around ASCII-compatible but unlikely to be a string.
941
+ """
942
+ if isinstance(fp_or_path_or_payload, (str, PathLike)):
943
+ guesses = from_path(
944
+ fp_or_path_or_payload,
945
+ steps=steps,
946
+ chunk_size=chunk_size,
947
+ threshold=threshold,
948
+ cp_isolation=cp_isolation,
949
+ cp_exclusion=cp_exclusion,
950
+ preemptive_behaviour=preemptive_behaviour,
951
+ explain=explain,
952
+ language_threshold=language_threshold,
953
+ enable_fallback=enable_fallback,
954
+ )
955
+ elif isinstance(
956
+ fp_or_path_or_payload,
957
+ (
958
+ bytes,
959
+ bytearray,
960
+ ),
961
+ ):
962
+ guesses = from_bytes(
963
+ fp_or_path_or_payload,
964
+ steps=steps,
965
+ chunk_size=chunk_size,
966
+ threshold=threshold,
967
+ cp_isolation=cp_isolation,
968
+ cp_exclusion=cp_exclusion,
969
+ preemptive_behaviour=preemptive_behaviour,
970
+ explain=explain,
971
+ language_threshold=language_threshold,
972
+ enable_fallback=enable_fallback,
973
+ )
974
+ else:
975
+ guesses = from_fp(
976
+ fp_or_path_or_payload,
977
+ steps=steps,
978
+ chunk_size=chunk_size,
979
+ threshold=threshold,
980
+ cp_isolation=cp_isolation,
981
+ cp_exclusion=cp_exclusion,
982
+ preemptive_behaviour=preemptive_behaviour,
983
+ explain=explain,
984
+ language_threshold=language_threshold,
985
+ enable_fallback=enable_fallback,
986
+ )
987
+
988
+ return not guesses
.venv/lib/python3.11/site-packages/charset_normalizer/cd.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (15.9 kB). View file
 
.venv/lib/python3.11/site-packages/charset_normalizer/cd.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ from codecs import IncrementalDecoder
5
+ from collections import Counter
6
+ from functools import lru_cache
7
+ from typing import Counter as TypeCounter
8
+
9
+ from .constant import (
10
+ FREQUENCIES,
11
+ KO_NAMES,
12
+ LANGUAGE_SUPPORTED_COUNT,
13
+ TOO_SMALL_SEQUENCE,
14
+ ZH_NAMES,
15
+ _FREQUENCIES_SET,
16
+ _FREQUENCIES_RANK,
17
+ )
18
+ from .md import is_suspiciously_successive_range
19
+ from .models import CoherenceMatches
20
+ from .utils import (
21
+ is_accentuated,
22
+ is_latin,
23
+ is_multi_byte_encoding,
24
+ is_unicode_range_secondary,
25
+ unicode_range,
26
+ )
27
+
28
+
29
+ def encoding_unicode_range(iana_name: str) -> list[str]:
30
+ """
31
+ Return associated unicode ranges in a single byte code page.
32
+ """
33
+ if is_multi_byte_encoding(iana_name):
34
+ raise OSError( # Defensive:
35
+ "Function not supported on multi-byte code page"
36
+ )
37
+
38
+ decoder = importlib.import_module(f"encodings.{iana_name}").IncrementalDecoder
39
+
40
+ p: IncrementalDecoder = decoder(errors="ignore")
41
+ seen_ranges: dict[str, int] = {}
42
+ character_count: int = 0
43
+
44
+ for i in range(0x40, 0xFF):
45
+ chunk: str = p.decode(bytes([i]))
46
+
47
+ if chunk:
48
+ character_range: str | None = unicode_range(chunk)
49
+
50
+ if character_range is None:
51
+ continue
52
+
53
+ if is_unicode_range_secondary(character_range) is False:
54
+ if character_range not in seen_ranges:
55
+ seen_ranges[character_range] = 0
56
+ seen_ranges[character_range] += 1
57
+ character_count += 1
58
+
59
+ return sorted(
60
+ [
61
+ character_range
62
+ for character_range in seen_ranges
63
+ if seen_ranges[character_range] / character_count >= 0.15
64
+ ]
65
+ )
66
+
67
+
68
+ def unicode_range_languages(primary_range: str) -> list[str]:
69
+ """
70
+ Return inferred languages used with a unicode range.
71
+ """
72
+ languages: list[str] = []
73
+
74
+ for language, characters in FREQUENCIES.items():
75
+ for character in characters:
76
+ if unicode_range(character) == primary_range:
77
+ languages.append(language)
78
+ break
79
+
80
+ return languages
81
+
82
+
83
+ @lru_cache()
84
+ def encoding_languages(iana_name: str) -> list[str]:
85
+ """
86
+ Single-byte encoding language association. Some code page are heavily linked to particular language(s).
87
+ This function does the correspondence.
88
+ """
89
+ unicode_ranges: list[str] = encoding_unicode_range(iana_name)
90
+ primary_range: str | None = None
91
+
92
+ for specified_range in unicode_ranges:
93
+ if "Latin" not in specified_range:
94
+ primary_range = specified_range
95
+ break
96
+
97
+ if primary_range is None:
98
+ return ["Latin Based"]
99
+
100
+ return unicode_range_languages(primary_range)
101
+
102
+
103
+ @lru_cache()
104
+ def mb_encoding_languages(iana_name: str) -> list[str]:
105
+ """
106
+ Multi-byte encoding language association. Some code page are heavily linked to particular language(s).
107
+ This function does the correspondence.
108
+ """
109
+ if (
110
+ iana_name.startswith("shift_")
111
+ or iana_name.startswith("iso2022_jp")
112
+ or iana_name.startswith("euc_j")
113
+ or iana_name == "cp932"
114
+ ):
115
+ return ["Japanese"]
116
+ if iana_name.startswith("gb") or iana_name in ZH_NAMES:
117
+ return ["Chinese"]
118
+ if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES:
119
+ return ["Korean"]
120
+
121
+ return []
122
+
123
+
124
+ @lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT)
125
+ def get_target_features(language: str) -> tuple[bool, bool]:
126
+ """
127
+ Determine main aspects from a supported language if it contains accents and if is pure Latin.
128
+ """
129
+ target_have_accents: bool = False
130
+ target_pure_latin: bool = True
131
+
132
+ for character in FREQUENCIES[language]:
133
+ if not target_have_accents and is_accentuated(character):
134
+ target_have_accents = True
135
+ if target_pure_latin and is_latin(character) is False:
136
+ target_pure_latin = False
137
+
138
+ return target_have_accents, target_pure_latin
139
+
140
+
141
+ def alphabet_languages(
142
+ characters: list[str], ignore_non_latin: bool = False
143
+ ) -> list[str]:
144
+ """
145
+ Return associated languages associated to given characters.
146
+ """
147
+ languages: list[tuple[str, float]] = []
148
+
149
+ characters_set: frozenset[str] = frozenset(characters)
150
+ source_have_accents = any(is_accentuated(character) for character in characters)
151
+
152
+ for language, language_characters in FREQUENCIES.items():
153
+ target_have_accents, target_pure_latin = get_target_features(language)
154
+
155
+ if ignore_non_latin and target_pure_latin is False:
156
+ continue
157
+
158
+ if target_have_accents is False and source_have_accents:
159
+ continue
160
+
161
+ character_count: int = len(language_characters)
162
+
163
+ character_match_count: int = len(_FREQUENCIES_SET[language] & characters_set)
164
+
165
+ ratio: float = character_match_count / character_count
166
+
167
+ if ratio >= 0.2:
168
+ languages.append((language, ratio))
169
+
170
+ languages = sorted(languages, key=lambda x: x[1], reverse=True)
171
+
172
+ return [compatible_language[0] for compatible_language in languages]
173
+
174
+
175
+ def characters_popularity_compare(
176
+ language: str, ordered_characters: list[str]
177
+ ) -> float:
178
+ """
179
+ Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language.
180
+ The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit).
181
+ Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.)
182
+ """
183
+ if language not in FREQUENCIES:
184
+ raise ValueError(f"{language} not available") # Defensive:
185
+
186
+ character_approved_count: int = 0
187
+ frequencies_language_set: frozenset[str] = _FREQUENCIES_SET[language]
188
+ lang_rank: dict[str, int] = _FREQUENCIES_RANK[language]
189
+
190
+ ordered_characters_count: int = len(ordered_characters)
191
+ target_language_characters_count: int = len(FREQUENCIES[language])
192
+
193
+ large_alphabet: bool = target_language_characters_count > 26
194
+
195
+ expected_projection_ratio: float = (
196
+ target_language_characters_count / ordered_characters_count
197
+ )
198
+
199
+ # Pre-built rank dict for ordered_characters (avoids repeated list slicing).
200
+ ordered_rank: dict[str, int] = {
201
+ char: rank for rank, char in enumerate(ordered_characters)
202
+ }
203
+
204
+ # Pre-compute characters common to both orderings.
205
+ # Avoids repeated `c in ordered_rank` dict lookups in the inner counts.
206
+ common_chars: list[tuple[int, int]] = [
207
+ (lr, ordered_rank[c]) for c, lr in lang_rank.items() if c in ordered_rank
208
+ ]
209
+
210
+ # Pre-extract lr and orr arrays for faster iteration in the inner loop.
211
+ # Plain integer loops with local arrays are much faster under mypyc than
212
+ # generator expression sums over a list of tuples.
213
+ common_count: int = len(common_chars)
214
+ common_lr: list[int] = [p[0] for p in common_chars]
215
+ common_orr: list[int] = [p[1] for p in common_chars]
216
+
217
+ for character, character_rank in zip(
218
+ ordered_characters, range(0, ordered_characters_count)
219
+ ):
220
+ if character not in frequencies_language_set:
221
+ continue
222
+
223
+ character_rank_in_language: int = lang_rank[character]
224
+ character_rank_projection: int = int(character_rank * expected_projection_ratio)
225
+
226
+ if (
227
+ large_alphabet is False
228
+ and abs(character_rank_projection - character_rank_in_language) > 4
229
+ ):
230
+ continue
231
+
232
+ if (
233
+ large_alphabet is True
234
+ and abs(character_rank_projection - character_rank_in_language)
235
+ < target_language_characters_count / 3
236
+ ):
237
+ character_approved_count += 1
238
+ continue
239
+
240
+ # Count how many characters appear "before" in both orderings,
241
+ # and how many appear "at or after" in both orderings.
242
+ # Single pass over pre-extracted arrays — much faster under mypyc
243
+ # than two generator expression sums.
244
+ before_match_count: int = 0
245
+ after_match_count: int = 0
246
+ for i in range(common_count):
247
+ lr_i: int = common_lr[i]
248
+ orr_i: int = common_orr[i]
249
+ if lr_i < character_rank_in_language:
250
+ if orr_i < character_rank:
251
+ before_match_count += 1
252
+ else:
253
+ if orr_i >= character_rank:
254
+ after_match_count += 1
255
+
256
+ after_len: int = target_language_characters_count - character_rank_in_language
257
+
258
+ if character_rank_in_language == 0 and before_match_count <= 4:
259
+ character_approved_count += 1
260
+ continue
261
+
262
+ if after_len == 0 and after_match_count <= 4:
263
+ character_approved_count += 1
264
+ continue
265
+
266
+ if (
267
+ character_rank_in_language > 0
268
+ and before_match_count / character_rank_in_language >= 0.4
269
+ ) or (after_len > 0 and after_match_count / after_len >= 0.4):
270
+ character_approved_count += 1
271
+ continue
272
+
273
+ return character_approved_count / len(ordered_characters)
274
+
275
+
276
+ def alpha_unicode_split(decoded_sequence: str) -> list[str]:
277
+ """
278
+ Given a decoded text sequence, return a list of str. Unicode range / alphabet separation.
279
+ Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list;
280
+ One containing the latin letters and the other hebrew.
281
+ """
282
+ layers: dict[str, list[str]] = {}
283
+
284
+ # Fast path: track single-layer key to skip dict iteration for single-script text.
285
+ single_layer_key: str | None = None
286
+ multi_layer: bool = False
287
+
288
+ # Cache the last character_range and its resolved layer to avoid repeated
289
+ # is_suspiciously_successive_range calls for consecutive same-range chars.
290
+ prev_character_range: str | None = None
291
+ prev_layer_target: str | None = None
292
+
293
+ for character in decoded_sequence:
294
+ if character.isalpha() is False:
295
+ continue
296
+
297
+ # ASCII fast-path: a-z and A-Z are always "Basic Latin".
298
+ # Avoids unicode_range() function call overhead for the most common case.
299
+ character_ord: int = ord(character)
300
+ if character_ord < 128:
301
+ character_range: str | None = "Basic Latin"
302
+ else:
303
+ character_range = unicode_range(character)
304
+
305
+ if character_range is None:
306
+ continue
307
+
308
+ # Fast path: same range as previous character → reuse cached layer target.
309
+ if character_range == prev_character_range:
310
+ if prev_layer_target is not None:
311
+ layers[prev_layer_target].append(character)
312
+ continue
313
+
314
+ layer_target_range: str | None = None
315
+
316
+ if multi_layer:
317
+ for discovered_range in layers:
318
+ if (
319
+ is_suspiciously_successive_range(discovered_range, character_range)
320
+ is False
321
+ ):
322
+ layer_target_range = discovered_range
323
+ break
324
+ elif single_layer_key is not None:
325
+ if (
326
+ is_suspiciously_successive_range(single_layer_key, character_range)
327
+ is False
328
+ ):
329
+ layer_target_range = single_layer_key
330
+
331
+ if layer_target_range is None:
332
+ layer_target_range = character_range
333
+
334
+ if layer_target_range not in layers:
335
+ layers[layer_target_range] = []
336
+ if single_layer_key is None:
337
+ single_layer_key = layer_target_range
338
+ else:
339
+ multi_layer = True
340
+
341
+ layers[layer_target_range].append(character)
342
+
343
+ # Cache for next iteration
344
+ prev_character_range = character_range
345
+ prev_layer_target = layer_target_range
346
+
347
+ return ["".join(chars).lower() for chars in layers.values()]
348
+
349
+
350
+ def merge_coherence_ratios(results: list[CoherenceMatches]) -> CoherenceMatches:
351
+ """
352
+ This function merge results previously given by the function coherence_ratio.
353
+ The return type is the same as coherence_ratio.
354
+ """
355
+ per_language_ratios: dict[str, list[float]] = {}
356
+ for result in results:
357
+ for sub_result in result:
358
+ language, ratio = sub_result
359
+ if language not in per_language_ratios:
360
+ per_language_ratios[language] = [ratio]
361
+ continue
362
+ per_language_ratios[language].append(ratio)
363
+
364
+ merge = [
365
+ (
366
+ language,
367
+ round(
368
+ sum(per_language_ratios[language]) / len(per_language_ratios[language]),
369
+ 4,
370
+ ),
371
+ )
372
+ for language in per_language_ratios
373
+ ]
374
+
375
+ return sorted(merge, key=lambda x: x[1], reverse=True)
376
+
377
+
378
+ def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches:
379
+ """
380
+ We shall NOT return "English—" in CoherenceMatches because it is an alternative
381
+ of "English". This function only keeps the best match and remove the em-dash in it.
382
+ """
383
+ index_results: dict[str, list[float]] = dict()
384
+
385
+ for result in results:
386
+ language, ratio = result
387
+ no_em_name: str = language.replace("—", "")
388
+
389
+ if no_em_name not in index_results:
390
+ index_results[no_em_name] = []
391
+
392
+ index_results[no_em_name].append(ratio)
393
+
394
+ if any(len(index_results[e]) > 1 for e in index_results):
395
+ filtered_results: CoherenceMatches = []
396
+
397
+ for language in index_results:
398
+ filtered_results.append((language, max(index_results[language])))
399
+
400
+ return filtered_results
401
+
402
+ return results
403
+
404
+
405
+ @lru_cache(maxsize=2048)
406
+ def coherence_ratio(
407
+ decoded_sequence: str, threshold: float = 0.1, lg_inclusion: str | None = None
408
+ ) -> CoherenceMatches:
409
+ """
410
+ Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers.
411
+ A layer = Character extraction by alphabets/ranges.
412
+ """
413
+
414
+ results: list[tuple[str, float]] = []
415
+ ignore_non_latin: bool = False
416
+
417
+ sufficient_match_count: int = 0
418
+
419
+ lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else []
420
+ if "Latin Based" in lg_inclusion_list:
421
+ ignore_non_latin = True
422
+ lg_inclusion_list.remove("Latin Based")
423
+
424
+ for layer in alpha_unicode_split(decoded_sequence):
425
+ sequence_frequencies: TypeCounter[str] = Counter(layer)
426
+ most_common = sequence_frequencies.most_common()
427
+
428
+ character_count: int = len(layer)
429
+
430
+ if character_count <= TOO_SMALL_SEQUENCE:
431
+ continue
432
+
433
+ popular_character_ordered: list[str] = [c for c, o in most_common]
434
+
435
+ for language in lg_inclusion_list or alphabet_languages(
436
+ popular_character_ordered, ignore_non_latin
437
+ ):
438
+ ratio: float = characters_popularity_compare(
439
+ language, popular_character_ordered
440
+ )
441
+
442
+ if ratio < threshold:
443
+ continue
444
+ elif ratio >= 0.8:
445
+ sufficient_match_count += 1
446
+
447
+ results.append((language, round(ratio, 4)))
448
+
449
+ if sufficient_match_count >= 3:
450
+ break
451
+
452
+ return sorted(
453
+ filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True
454
+ )
.venv/lib/python3.11/site-packages/charset_normalizer/constant.py ADDED
@@ -0,0 +1,2050 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE
4
+ from encodings.aliases import aliases
5
+ from re import IGNORECASE
6
+ from re import compile as re_compile
7
+
8
+ # Contain for each eligible encoding a list of/item bytes SIG/BOM
9
+ ENCODING_MARKS: dict[str, bytes | list[bytes]] = {
10
+ "utf_8": BOM_UTF8,
11
+ "utf_7": [
12
+ b"\x2b\x2f\x76\x38\x2d",
13
+ b"\x2b\x2f\x76\x38",
14
+ b"\x2b\x2f\x76\x39",
15
+ b"\x2b\x2f\x76\x2b",
16
+ b"\x2b\x2f\x76\x2f",
17
+ ],
18
+ "gb18030": b"\x84\x31\x95\x33",
19
+ "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE],
20
+ "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE],
21
+ }
22
+
23
+ TOO_SMALL_SEQUENCE: int = 32
24
+ TOO_BIG_SEQUENCE: int = int(10e6)
25
+
26
+ UTF8_MAXIMAL_ALLOCATION: int = 1_112_064
27
+
28
+ # Up-to-date Unicode ucd/17.0.0
29
+ UNICODE_RANGES_COMBINED: dict[str, range] = {
30
+ "Control character": range(32),
31
+ "Basic Latin": range(32, 128),
32
+ "Latin-1 Supplement": range(128, 256),
33
+ "Latin Extended-A": range(256, 384),
34
+ "Latin Extended-B": range(384, 592),
35
+ "IPA Extensions": range(592, 688),
36
+ "Spacing Modifier Letters": range(688, 768),
37
+ "Combining Diacritical Marks": range(768, 880),
38
+ "Greek and Coptic": range(880, 1024),
39
+ "Cyrillic": range(1024, 1280),
40
+ "Cyrillic Supplement": range(1280, 1328),
41
+ "Armenian": range(1328, 1424),
42
+ "Hebrew": range(1424, 1536),
43
+ "Arabic": range(1536, 1792),
44
+ "Syriac": range(1792, 1872),
45
+ "Arabic Supplement": range(1872, 1920),
46
+ "Thaana": range(1920, 1984),
47
+ "NKo": range(1984, 2048),
48
+ "Samaritan": range(2048, 2112),
49
+ "Mandaic": range(2112, 2144),
50
+ "Syriac Supplement": range(2144, 2160),
51
+ "Arabic Extended-B": range(2160, 2208),
52
+ "Arabic Extended-A": range(2208, 2304),
53
+ "Devanagari": range(2304, 2432),
54
+ "Bengali": range(2432, 2560),
55
+ "Gurmukhi": range(2560, 2688),
56
+ "Gujarati": range(2688, 2816),
57
+ "Oriya": range(2816, 2944),
58
+ "Tamil": range(2944, 3072),
59
+ "Telugu": range(3072, 3200),
60
+ "Kannada": range(3200, 3328),
61
+ "Malayalam": range(3328, 3456),
62
+ "Sinhala": range(3456, 3584),
63
+ "Thai": range(3584, 3712),
64
+ "Lao": range(3712, 3840),
65
+ "Tibetan": range(3840, 4096),
66
+ "Myanmar": range(4096, 4256),
67
+ "Georgian": range(4256, 4352),
68
+ "Hangul Jamo": range(4352, 4608),
69
+ "Ethiopic": range(4608, 4992),
70
+ "Ethiopic Supplement": range(4992, 5024),
71
+ "Cherokee": range(5024, 5120),
72
+ "Unified Canadian Aboriginal Syllabics": range(5120, 5760),
73
+ "Ogham": range(5760, 5792),
74
+ "Runic": range(5792, 5888),
75
+ "Tagalog": range(5888, 5920),
76
+ "Hanunoo": range(5920, 5952),
77
+ "Buhid": range(5952, 5984),
78
+ "Tagbanwa": range(5984, 6016),
79
+ "Khmer": range(6016, 6144),
80
+ "Mongolian": range(6144, 6320),
81
+ "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6400),
82
+ "Limbu": range(6400, 6480),
83
+ "Tai Le": range(6480, 6528),
84
+ "New Tai Lue": range(6528, 6624),
85
+ "Khmer Symbols": range(6624, 6656),
86
+ "Buginese": range(6656, 6688),
87
+ "Tai Tham": range(6688, 6832),
88
+ "Combining Diacritical Marks Extended": range(6832, 6912),
89
+ "Balinese": range(6912, 7040),
90
+ "Sundanese": range(7040, 7104),
91
+ "Batak": range(7104, 7168),
92
+ "Lepcha": range(7168, 7248),
93
+ "Ol Chiki": range(7248, 7296),
94
+ "Cyrillic Extended-C": range(7296, 7312),
95
+ "Georgian Extended": range(7312, 7360),
96
+ "Sundanese Supplement": range(7360, 7376),
97
+ "Vedic Extensions": range(7376, 7424),
98
+ "Phonetic Extensions": range(7424, 7552),
99
+ "Phonetic Extensions Supplement": range(7552, 7616),
100
+ "Combining Diacritical Marks Supplement": range(7616, 7680),
101
+ "Latin Extended Additional": range(7680, 7936),
102
+ "Greek Extended": range(7936, 8192),
103
+ "General Punctuation": range(8192, 8304),
104
+ "Superscripts and Subscripts": range(8304, 8352),
105
+ "Currency Symbols": range(8352, 8400),
106
+ "Combining Diacritical Marks for Symbols": range(8400, 8448),
107
+ "Letterlike Symbols": range(8448, 8528),
108
+ "Number Forms": range(8528, 8592),
109
+ "Arrows": range(8592, 8704),
110
+ "Mathematical Operators": range(8704, 8960),
111
+ "Miscellaneous Technical": range(8960, 9216),
112
+ "Control Pictures": range(9216, 9280),
113
+ "Optical Character Recognition": range(9280, 9312),
114
+ "Enclosed Alphanumerics": range(9312, 9472),
115
+ "Box Drawing": range(9472, 9600),
116
+ "Block Elements": range(9600, 9632),
117
+ "Geometric Shapes": range(9632, 9728),
118
+ "Miscellaneous Symbols": range(9728, 9984),
119
+ "Dingbats": range(9984, 10176),
120
+ "Miscellaneous Mathematical Symbols-A": range(10176, 10224),
121
+ "Supplemental Arrows-A": range(10224, 10240),
122
+ "Braille Patterns": range(10240, 10496),
123
+ "Supplemental Arrows-B": range(10496, 10624),
124
+ "Miscellaneous Mathematical Symbols-B": range(10624, 10752),
125
+ "Supplemental Mathematical Operators": range(10752, 11008),
126
+ "Miscellaneous Symbols and Arrows": range(11008, 11264),
127
+ "Glagolitic": range(11264, 11360),
128
+ "Latin Extended-C": range(11360, 11392),
129
+ "Coptic": range(11392, 11520),
130
+ "Georgian Supplement": range(11520, 11568),
131
+ "Tifinagh": range(11568, 11648),
132
+ "Ethiopic Extended": range(11648, 11744),
133
+ "Cyrillic Extended-A": range(11744, 11776),
134
+ "Supplemental Punctuation": range(11776, 11904),
135
+ "CJK Radicals Supplement": range(11904, 12032),
136
+ "Kangxi Radicals": range(12032, 12256),
137
+ "Ideographic Description Characters": range(12272, 12288),
138
+ "CJK Symbols and Punctuation": range(12288, 12352),
139
+ "Hiragana": range(12352, 12448),
140
+ "Katakana": range(12448, 12544),
141
+ "Bopomofo": range(12544, 12592),
142
+ "Hangul Compatibility Jamo": range(12592, 12688),
143
+ "Kanbun": range(12688, 12704),
144
+ "Bopomofo Extended": range(12704, 12736),
145
+ "CJK Strokes": range(12736, 12784),
146
+ "Katakana Phonetic Extensions": range(12784, 12800),
147
+ "Enclosed CJK Letters and Months": range(12800, 13056),
148
+ "CJK Compatibility": range(13056, 13312),
149
+ "CJK Unified Ideographs Extension A": range(13312, 19904),
150
+ "Yijing Hexagram Symbols": range(19904, 19968),
151
+ "CJK Unified Ideographs": range(19968, 40960),
152
+ "Yi Syllables": range(40960, 42128),
153
+ "Yi Radicals": range(42128, 42192),
154
+ "Lisu": range(42192, 42240),
155
+ "Vai": range(42240, 42560),
156
+ "Cyrillic Extended-B": range(42560, 42656),
157
+ "Bamum": range(42656, 42752),
158
+ "Modifier Tone Letters": range(42752, 42784),
159
+ "Latin Extended-D": range(42784, 43008),
160
+ "Syloti Nagri": range(43008, 43056),
161
+ "Common Indic Number Forms": range(43056, 43072),
162
+ "Phags-pa": range(43072, 43136),
163
+ "Saurashtra": range(43136, 43232),
164
+ "Devanagari Extended": range(43232, 43264),
165
+ "Kayah Li": range(43264, 43312),
166
+ "Rejang": range(43312, 43360),
167
+ "Hangul Jamo Extended-A": range(43360, 43392),
168
+ "Javanese": range(43392, 43488),
169
+ "Myanmar Extended-B": range(43488, 43520),
170
+ "Cham": range(43520, 43616),
171
+ "Myanmar Extended-A": range(43616, 43648),
172
+ "Tai Viet": range(43648, 43744),
173
+ "Meetei Mayek Extensions": range(43744, 43776),
174
+ "Ethiopic Extended-A": range(43776, 43824),
175
+ "Latin Extended-E": range(43824, 43888),
176
+ "Cherokee Supplement": range(43888, 43968),
177
+ "Meetei Mayek": range(43968, 44032),
178
+ "Hangul Syllables": range(44032, 55216),
179
+ "Hangul Jamo Extended-B": range(55216, 55296),
180
+ "High Surrogates": range(55296, 56192),
181
+ "High Private Use Surrogates": range(56192, 56320),
182
+ "Low Surrogates": range(56320, 57344),
183
+ "Private Use Area": range(57344, 63744),
184
+ "CJK Compatibility Ideographs": range(63744, 64256),
185
+ "Alphabetic Presentation Forms": range(64256, 64336),
186
+ "Arabic Presentation Forms-A": range(64336, 65024),
187
+ "Variation Selectors": range(65024, 65040),
188
+ "Vertical Forms": range(65040, 65056),
189
+ "Combining Half Marks": range(65056, 65072),
190
+ "CJK Compatibility Forms": range(65072, 65104),
191
+ "Small Form Variants": range(65104, 65136),
192
+ "Arabic Presentation Forms-B": range(65136, 65280),
193
+ "Halfwidth and Fullwidth Forms": range(65280, 65520),
194
+ "Specials": range(65520, 65536),
195
+ "Linear B Syllabary": range(65536, 65664),
196
+ "Linear B Ideograms": range(65664, 65792),
197
+ "Aegean Numbers": range(65792, 65856),
198
+ "Ancient Greek Numbers": range(65856, 65936),
199
+ "Ancient Symbols": range(65936, 66000),
200
+ "Phaistos Disc": range(66000, 66048),
201
+ "Lycian": range(66176, 66208),
202
+ "Carian": range(66208, 66272),
203
+ "Coptic Epact Numbers": range(66272, 66304),
204
+ "Old Italic": range(66304, 66352),
205
+ "Gothic": range(66352, 66384),
206
+ "Old Permic": range(66384, 66432),
207
+ "Ugaritic": range(66432, 66464),
208
+ "Old Persian": range(66464, 66528),
209
+ "Deseret": range(66560, 66640),
210
+ "Shavian": range(66640, 66688),
211
+ "Osmanya": range(66688, 66736),
212
+ "Osage": range(66736, 66816),
213
+ "Elbasan": range(66816, 66864),
214
+ "Caucasian Albanian": range(66864, 66928),
215
+ "Vithkuqi": range(66928, 67008),
216
+ "Todhri": range(67008, 67072),
217
+ "Linear A": range(67072, 67456),
218
+ "Latin Extended-F": range(67456, 67520),
219
+ "Cypriot Syllabary": range(67584, 67648),
220
+ "Imperial Aramaic": range(67648, 67680),
221
+ "Palmyrene": range(67680, 67712),
222
+ "Nabataean": range(67712, 67760),
223
+ "Hatran": range(67808, 67840),
224
+ "Phoenician": range(67840, 67872),
225
+ "Lydian": range(67872, 67904),
226
+ "Sidetic": range(67904, 67936),
227
+ "Meroitic Hieroglyphs": range(67968, 68000),
228
+ "Meroitic Cursive": range(68000, 68096),
229
+ "Kharoshthi": range(68096, 68192),
230
+ "Old South Arabian": range(68192, 68224),
231
+ "Old North Arabian": range(68224, 68256),
232
+ "Manichaean": range(68288, 68352),
233
+ "Avestan": range(68352, 68416),
234
+ "Inscriptional Parthian": range(68416, 68448),
235
+ "Inscriptional Pahlavi": range(68448, 68480),
236
+ "Psalter Pahlavi": range(68480, 68528),
237
+ "Old Turkic": range(68608, 68688),
238
+ "Old Hungarian": range(68736, 68864),
239
+ "Hanifi Rohingya": range(68864, 68928),
240
+ "Garay": range(68928, 69008),
241
+ "Rumi Numeral Symbols": range(69216, 69248),
242
+ "Yezidi": range(69248, 69312),
243
+ "Arabic Extended-C": range(69312, 69376),
244
+ "Old Sogdian": range(69376, 69424),
245
+ "Sogdian": range(69424, 69488),
246
+ "Old Uyghur": range(69488, 69552),
247
+ "Chorasmian": range(69552, 69600),
248
+ "Elymaic": range(69600, 69632),
249
+ "Brahmi": range(69632, 69760),
250
+ "Kaithi": range(69760, 69840),
251
+ "Sora Sompeng": range(69840, 69888),
252
+ "Chakma": range(69888, 69968),
253
+ "Mahajani": range(69968, 70016),
254
+ "Sharada": range(70016, 70112),
255
+ "Sinhala Archaic Numbers": range(70112, 70144),
256
+ "Khojki": range(70144, 70224),
257
+ "Multani": range(70272, 70320),
258
+ "Khudawadi": range(70320, 70400),
259
+ "Grantha": range(70400, 70528),
260
+ "Tulu-Tigalari": range(70528, 70656),
261
+ "Newa": range(70656, 70784),
262
+ "Tirhuta": range(70784, 70880),
263
+ "Siddham": range(71040, 71168),
264
+ "Modi": range(71168, 71264),
265
+ "Mongolian Supplement": range(71264, 71296),
266
+ "Takri": range(71296, 71376),
267
+ "Myanmar Extended-C": range(71376, 71424),
268
+ "Ahom": range(71424, 71504),
269
+ "Dogra": range(71680, 71760),
270
+ "Warang Citi": range(71840, 71936),
271
+ "Dives Akuru": range(71936, 72032),
272
+ "Nandinagari": range(72096, 72192),
273
+ "Zanabazar Square": range(72192, 72272),
274
+ "Soyombo": range(72272, 72368),
275
+ "Unified Canadian Aboriginal Syllabics Extended-A": range(72368, 72384),
276
+ "Pau Cin Hau": range(72384, 72448),
277
+ "Devanagari Extended-A": range(72448, 72544),
278
+ "Sharada Supplement": range(72544, 72576),
279
+ "Sunuwar": range(72640, 72704),
280
+ "Bhaiksuki": range(72704, 72816),
281
+ "Marchen": range(72816, 72896),
282
+ "Masaram Gondi": range(72960, 73056),
283
+ "Gunjala Gondi": range(73056, 73136),
284
+ "Tolong Siki": range(73136, 73200),
285
+ "Makasar": range(73440, 73472),
286
+ "Kawi": range(73472, 73568),
287
+ "Lisu Supplement": range(73648, 73664),
288
+ "Tamil Supplement": range(73664, 73728),
289
+ "Cuneiform": range(73728, 74752),
290
+ "Cuneiform Numbers and Punctuation": range(74752, 74880),
291
+ "Early Dynastic Cuneiform": range(74880, 75088),
292
+ "Cypro-Minoan": range(77712, 77824),
293
+ "Egyptian Hieroglyphs": range(77824, 78896),
294
+ "Egyptian Hieroglyph Format Controls": range(78896, 78944),
295
+ "Egyptian Hieroglyphs Extended-A": range(78944, 82944),
296
+ "Anatolian Hieroglyphs": range(82944, 83584),
297
+ "Gurung Khema": range(90368, 90432),
298
+ "Bamum Supplement": range(92160, 92736),
299
+ "Mro": range(92736, 92784),
300
+ "Tangsa": range(92784, 92880),
301
+ "Bassa Vah": range(92880, 92928),
302
+ "Pahawh Hmong": range(92928, 93072),
303
+ "Kirat Rai": range(93504, 93568),
304
+ "Medefaidrin": range(93760, 93856),
305
+ "Beria Erfe": range(93856, 93920),
306
+ "Miao": range(93952, 94112),
307
+ "Ideographic Symbols and Punctuation": range(94176, 94208),
308
+ "Tangut": range(94208, 100352),
309
+ "Tangut Components": range(100352, 101120),
310
+ "Khitan Small Script": range(101120, 101632),
311
+ "Tangut Supplement": range(101632, 101760),
312
+ "Tangut Components Supplement": range(101760, 101888),
313
+ "Kana Extended-B": range(110576, 110592),
314
+ "Kana Supplement": range(110592, 110848),
315
+ "Kana Extended-A": range(110848, 110896),
316
+ "Small Kana Extension": range(110896, 110960),
317
+ "Nushu": range(110960, 111360),
318
+ "Duployan": range(113664, 113824),
319
+ "Shorthand Format Controls": range(113824, 113840),
320
+ "Symbols for Legacy Computing Supplement": range(117760, 118464),
321
+ "Miscellaneous Symbols Supplement": range(118464, 118528),
322
+ "Znamenny Musical Notation": range(118528, 118736),
323
+ "Byzantine Musical Symbols": range(118784, 119040),
324
+ "Musical Symbols": range(119040, 119296),
325
+ "Ancient Greek Musical Notation": range(119296, 119376),
326
+ "Kaktovik Numerals": range(119488, 119520),
327
+ "Mayan Numerals": range(119520, 119552),
328
+ "Tai Xuan Jing Symbols": range(119552, 119648),
329
+ "Counting Rod Numerals": range(119648, 119680),
330
+ "Mathematical Alphanumeric Symbols": range(119808, 120832),
331
+ "Sutton SignWriting": range(120832, 121520),
332
+ "Latin Extended-G": range(122624, 122880),
333
+ "Glagolitic Supplement": range(122880, 122928),
334
+ "Cyrillic Extended-D": range(122928, 123024),
335
+ "Nyiakeng Puachue Hmong": range(123136, 123216),
336
+ "Toto": range(123536, 123584),
337
+ "Wancho": range(123584, 123648),
338
+ "Nag Mundari": range(124112, 124160),
339
+ "Ol Onal": range(124368, 124416),
340
+ "Tai Yo": range(124608, 124672),
341
+ "Ethiopic Extended-B": range(124896, 124928),
342
+ "Mende Kikakui": range(124928, 125152),
343
+ "Adlam": range(125184, 125280),
344
+ "Indic Siyaq Numbers": range(126064, 126144),
345
+ "Ottoman Siyaq Numbers": range(126208, 126288),
346
+ "Arabic Mathematical Alphabetic Symbols": range(126464, 126720),
347
+ "Mahjong Tiles": range(126976, 127024),
348
+ "Domino Tiles": range(127024, 127136),
349
+ "Playing Cards": range(127136, 127232),
350
+ "Enclosed Alphanumeric Supplement": range(127232, 127488),
351
+ "Enclosed Ideographic Supplement": range(127488, 127744),
352
+ "Miscellaneous Symbols and Pictographs": range(127744, 128512),
353
+ "Emoticons": range(128512, 128592),
354
+ "Ornamental Dingbats": range(128592, 128640),
355
+ "Transport and Map Symbols": range(128640, 128768),
356
+ "Alchemical Symbols": range(128768, 128896),
357
+ "Geometric Shapes Extended": range(128896, 129024),
358
+ "Supplemental Arrows-C": range(129024, 129280),
359
+ "Supplemental Symbols and Pictographs": range(129280, 129536),
360
+ "Chess Symbols": range(129536, 129648),
361
+ "Symbols and Pictographs Extended-A": range(129648, 129792),
362
+ "Symbols for Legacy Computing": range(129792, 130048),
363
+ "CJK Unified Ideographs Extension B": range(131072, 173792),
364
+ "CJK Unified Ideographs Extension C": range(173824, 177984),
365
+ "CJK Unified Ideographs Extension D": range(177984, 178208),
366
+ "CJK Unified Ideographs Extension E": range(178208, 183984),
367
+ "CJK Unified Ideographs Extension F": range(183984, 191472),
368
+ "CJK Unified Ideographs Extension I": range(191472, 192096),
369
+ "CJK Compatibility Ideographs Supplement": range(194560, 195104),
370
+ "CJK Unified Ideographs Extension G": range(196608, 201552),
371
+ "CJK Unified Ideographs Extension H": range(201552, 205744),
372
+ "CJK Unified Ideographs Extension J": range(205744, 210048),
373
+ "Tags": range(917504, 917632),
374
+ "Variation Selectors Supplement": range(917760, 918000),
375
+ "Supplementary Private Use Area-A": range(983040, 1048576),
376
+ "Supplementary Private Use Area-B": range(1048576, 1114112),
377
+ }
378
+
379
+
380
+ UNICODE_SECONDARY_RANGE_KEYWORD: list[str] = [
381
+ "Supplement",
382
+ "Extended",
383
+ "Extensions",
384
+ "Modifier",
385
+ "Marks",
386
+ "Punctuation",
387
+ "Symbols",
388
+ "Forms",
389
+ "Operators",
390
+ "Miscellaneous",
391
+ "Drawing",
392
+ "Block",
393
+ "Shapes",
394
+ "Supplemental",
395
+ "Tags",
396
+ ]
397
+
398
+ RE_POSSIBLE_ENCODING_INDICATION = re_compile(
399
+ r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)",
400
+ IGNORECASE,
401
+ )
402
+
403
+ IANA_NO_ALIASES = [
404
+ "cp720",
405
+ "cp737",
406
+ "cp856",
407
+ "cp874",
408
+ "cp875",
409
+ "cp1006",
410
+ "koi8_r",
411
+ "koi8_t",
412
+ "koi8_u",
413
+ ]
414
+
415
+ IANA_SUPPORTED: list[str] = sorted(
416
+ filter(
417
+ lambda x: x.endswith("_codec") is False
418
+ and x not in {"rot_13", "tactis", "mbcs"},
419
+ list(set(aliases.values())) + IANA_NO_ALIASES,
420
+ )
421
+ )
422
+
423
+ IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED)
424
+
425
+ # pre-computed code page that are similar using the function cp_similarity.
426
+ IANA_SUPPORTED_SIMILAR: dict[str, list[str]] = {
427
+ "cp037": ["cp1026", "cp1140", "cp273", "cp500"],
428
+ "cp1026": ["cp037", "cp1140", "cp273", "cp500"],
429
+ "cp1125": ["cp866"],
430
+ "cp1140": ["cp037", "cp1026", "cp273", "cp500"],
431
+ "cp1250": ["iso8859_2"],
432
+ "cp1251": ["kz1048", "ptcp154"],
433
+ "cp1252": ["iso8859_15", "iso8859_9", "latin_1"],
434
+ "cp1253": ["iso8859_7"],
435
+ "cp1254": ["iso8859_15", "iso8859_9", "latin_1"],
436
+ "cp1257": ["iso8859_13"],
437
+ "cp273": ["cp037", "cp1026", "cp1140", "cp500"],
438
+ "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"],
439
+ "cp500": ["cp037", "cp1026", "cp1140", "cp273"],
440
+ "cp850": ["cp437", "cp857", "cp858", "cp865"],
441
+ "cp857": ["cp850", "cp858", "cp865"],
442
+ "cp858": ["cp437", "cp850", "cp857", "cp865"],
443
+ "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"],
444
+ "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"],
445
+ "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"],
446
+ "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"],
447
+ "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"],
448
+ "cp866": ["cp1125"],
449
+ "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"],
450
+ "iso8859_11": ["tis_620"],
451
+ "iso8859_13": ["cp1257"],
452
+ "iso8859_14": [
453
+ "iso8859_10",
454
+ "iso8859_15",
455
+ "iso8859_16",
456
+ "iso8859_3",
457
+ "iso8859_9",
458
+ "latin_1",
459
+ ],
460
+ "iso8859_15": [
461
+ "cp1252",
462
+ "cp1254",
463
+ "iso8859_10",
464
+ "iso8859_14",
465
+ "iso8859_16",
466
+ "iso8859_3",
467
+ "iso8859_9",
468
+ "latin_1",
469
+ ],
470
+ "iso8859_16": [
471
+ "iso8859_14",
472
+ "iso8859_15",
473
+ "iso8859_2",
474
+ "iso8859_3",
475
+ "iso8859_9",
476
+ "latin_1",
477
+ ],
478
+ "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"],
479
+ "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"],
480
+ "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"],
481
+ "iso8859_7": ["cp1253"],
482
+ "iso8859_9": [
483
+ "cp1252",
484
+ "cp1254",
485
+ "cp1258",
486
+ "iso8859_10",
487
+ "iso8859_14",
488
+ "iso8859_15",
489
+ "iso8859_16",
490
+ "iso8859_3",
491
+ "iso8859_4",
492
+ "latin_1",
493
+ ],
494
+ "kz1048": ["cp1251", "ptcp154"],
495
+ "latin_1": [
496
+ "cp1252",
497
+ "cp1254",
498
+ "cp1258",
499
+ "iso8859_10",
500
+ "iso8859_14",
501
+ "iso8859_15",
502
+ "iso8859_16",
503
+ "iso8859_3",
504
+ "iso8859_4",
505
+ "iso8859_9",
506
+ ],
507
+ "mac_iceland": ["mac_roman", "mac_turkish"],
508
+ "mac_roman": ["mac_iceland", "mac_turkish"],
509
+ "mac_turkish": ["mac_iceland", "mac_roman"],
510
+ "ptcp154": ["cp1251", "kz1048"],
511
+ "tis_620": ["iso8859_11"],
512
+ }
513
+
514
+
515
+ CHARDET_CORRESPONDENCE: dict[str, str] = {
516
+ "iso2022_kr": "ISO-2022-KR",
517
+ "iso2022_jp": "ISO-2022-JP",
518
+ "euc_kr": "EUC-KR",
519
+ "tis_620": "TIS-620",
520
+ "utf_32": "UTF-32",
521
+ "euc_jp": "EUC-JP",
522
+ "koi8_r": "KOI8-R",
523
+ "iso8859_1": "ISO-8859-1",
524
+ "iso8859_2": "ISO-8859-2",
525
+ "iso8859_5": "ISO-8859-5",
526
+ "iso8859_6": "ISO-8859-6",
527
+ "iso8859_7": "ISO-8859-7",
528
+ "iso8859_8": "ISO-8859-8",
529
+ "utf_16": "UTF-16",
530
+ "cp855": "IBM855",
531
+ "mac_cyrillic": "MacCyrillic",
532
+ "gb2312": "GB2312",
533
+ "gb18030": "GB18030",
534
+ "cp932": "CP932",
535
+ "cp866": "IBM866",
536
+ "utf_8": "utf-8",
537
+ "utf_8_sig": "UTF-8-SIG",
538
+ "shift_jis": "SHIFT_JIS",
539
+ "big5": "Big5",
540
+ "cp1250": "windows-1250",
541
+ "cp1251": "windows-1251",
542
+ "cp1252": "Windows-1252",
543
+ "cp1253": "windows-1253",
544
+ "cp1255": "windows-1255",
545
+ "cp1256": "windows-1256",
546
+ "cp1254": "Windows-1254",
547
+ "cp949": "CP949",
548
+ }
549
+
550
+
551
+ COMMON_SAFE_ASCII_CHARACTERS: frozenset[str] = frozenset(
552
+ {
553
+ "<",
554
+ ">",
555
+ "=",
556
+ ":",
557
+ "/",
558
+ "&",
559
+ ";",
560
+ "{",
561
+ "}",
562
+ "[",
563
+ "]",
564
+ ",",
565
+ "|",
566
+ '"',
567
+ "-",
568
+ "(",
569
+ ")",
570
+ }
571
+ )
572
+
573
+ # Sample character sets — replace with full lists if needed
574
+ COMMON_CHINESE_CHARACTERS = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严龙飞"
575
+
576
+ COMMON_JAPANESE_CHARACTERS = "日一国年大十二本中長出三時行見月分後前生五間上東四今金九入学高円子外八六下来気小七山話女北午百書先名川千水半男西電校語土木聞食車何南万毎白天母火右読友左休父雨"
577
+
578
+ COMMON_KOREAN_CHARACTERS = "一二三四五六七八九十百千萬上下左右中人女子大小山川日月火水木金土父母天地國名年時文校學生"
579
+
580
+ # Combine all into a frozenset
581
+ COMMON_CJK_CHARACTERS = frozenset(
582
+ "".join(
583
+ [
584
+ COMMON_CHINESE_CHARACTERS,
585
+ COMMON_JAPANESE_CHARACTERS,
586
+ COMMON_KOREAN_CHARACTERS,
587
+ ]
588
+ )
589
+ )
590
+
591
+ KO_NAMES: frozenset[str] = frozenset({"johab", "cp949", "euc_kr"})
592
+ ZH_NAMES: frozenset[str] = frozenset({"big5", "cp950", "big5hkscs", "hz"})
593
+
594
+ # Logging LEVEL below DEBUG
595
+ TRACE: int = 5
596
+
597
+
598
+ # Language label that contain the em dash "—"
599
+ # character are to be considered alternative seq to origin
600
+ FREQUENCIES: dict[str, list[str]] = {
601
+ "English": [
602
+ "e",
603
+ "a",
604
+ "t",
605
+ "i",
606
+ "o",
607
+ "n",
608
+ "s",
609
+ "r",
610
+ "h",
611
+ "l",
612
+ "d",
613
+ "c",
614
+ "u",
615
+ "m",
616
+ "f",
617
+ "p",
618
+ "g",
619
+ "w",
620
+ "y",
621
+ "b",
622
+ "v",
623
+ "k",
624
+ "x",
625
+ "j",
626
+ "z",
627
+ "q",
628
+ ],
629
+ "English—": [
630
+ "e",
631
+ "a",
632
+ "t",
633
+ "i",
634
+ "o",
635
+ "n",
636
+ "s",
637
+ "r",
638
+ "h",
639
+ "l",
640
+ "d",
641
+ "c",
642
+ "m",
643
+ "u",
644
+ "f",
645
+ "p",
646
+ "g",
647
+ "w",
648
+ "b",
649
+ "y",
650
+ "v",
651
+ "k",
652
+ "j",
653
+ "x",
654
+ "z",
655
+ "q",
656
+ ],
657
+ "German": [
658
+ "e",
659
+ "n",
660
+ "i",
661
+ "r",
662
+ "s",
663
+ "t",
664
+ "a",
665
+ "d",
666
+ "h",
667
+ "u",
668
+ "l",
669
+ "g",
670
+ "o",
671
+ "c",
672
+ "m",
673
+ "b",
674
+ "f",
675
+ "k",
676
+ "w",
677
+ "z",
678
+ "p",
679
+ "v",
680
+ "ü",
681
+ "ä",
682
+ "ö",
683
+ "j",
684
+ ],
685
+ "French": [
686
+ "e",
687
+ "a",
688
+ "s",
689
+ "n",
690
+ "i",
691
+ "t",
692
+ "r",
693
+ "l",
694
+ "u",
695
+ "o",
696
+ "d",
697
+ "c",
698
+ "p",
699
+ "m",
700
+ "é",
701
+ "v",
702
+ "g",
703
+ "f",
704
+ "b",
705
+ "h",
706
+ "q",
707
+ "à",
708
+ "x",
709
+ "è",
710
+ "y",
711
+ "j",
712
+ ],
713
+ "Dutch": [
714
+ "e",
715
+ "n",
716
+ "a",
717
+ "i",
718
+ "r",
719
+ "t",
720
+ "o",
721
+ "d",
722
+ "s",
723
+ "l",
724
+ "g",
725
+ "h",
726
+ "v",
727
+ "m",
728
+ "u",
729
+ "k",
730
+ "c",
731
+ "p",
732
+ "b",
733
+ "w",
734
+ "j",
735
+ "z",
736
+ "f",
737
+ "y",
738
+ "x",
739
+ "ë",
740
+ ],
741
+ "Italian": [
742
+ "e",
743
+ "i",
744
+ "a",
745
+ "o",
746
+ "n",
747
+ "l",
748
+ "t",
749
+ "r",
750
+ "s",
751
+ "c",
752
+ "d",
753
+ "u",
754
+ "p",
755
+ "m",
756
+ "g",
757
+ "v",
758
+ "f",
759
+ "b",
760
+ "z",
761
+ "h",
762
+ "q",
763
+ "è",
764
+ "à",
765
+ "k",
766
+ "y",
767
+ "ò",
768
+ ],
769
+ "Polish": [
770
+ "a",
771
+ "i",
772
+ "o",
773
+ "e",
774
+ "n",
775
+ "r",
776
+ "z",
777
+ "w",
778
+ "s",
779
+ "c",
780
+ "t",
781
+ "k",
782
+ "y",
783
+ "d",
784
+ "p",
785
+ "m",
786
+ "u",
787
+ "l",
788
+ "j",
789
+ "ł",
790
+ "g",
791
+ "b",
792
+ "h",
793
+ "ą",
794
+ "ę",
795
+ "ó",
796
+ ],
797
+ "Spanish": [
798
+ "e",
799
+ "a",
800
+ "o",
801
+ "n",
802
+ "s",
803
+ "r",
804
+ "i",
805
+ "l",
806
+ "d",
807
+ "t",
808
+ "c",
809
+ "u",
810
+ "m",
811
+ "p",
812
+ "b",
813
+ "g",
814
+ "v",
815
+ "f",
816
+ "y",
817
+ "ó",
818
+ "h",
819
+ "q",
820
+ "í",
821
+ "j",
822
+ "z",
823
+ "á",
824
+ ],
825
+ "Russian": [
826
+ "о",
827
+ "е",
828
+ "а",
829
+ "и",
830
+ "н",
831
+ "т",
832
+ "с",
833
+ "р",
834
+ "в",
835
+ "л",
836
+ "к",
837
+ "м",
838
+ "д",
839
+ "п",
840
+ "у",
841
+ "г",
842
+ "я",
843
+ "ы",
844
+ "з",
845
+ "б",
846
+ "й",
847
+ "ь",
848
+ "ч",
849
+ "х",
850
+ "ж",
851
+ "ц",
852
+ ],
853
+ # Jap-Kanji
854
+ "Japanese": [
855
+ "日",
856
+ "一",
857
+ "人",
858
+ "年",
859
+ "大",
860
+ "十",
861
+ "二",
862
+ "本",
863
+ "中",
864
+ "長",
865
+ "出",
866
+ "三",
867
+ "時",
868
+ "行",
869
+ "見",
870
+ "月",
871
+ "分",
872
+ "後",
873
+ "前",
874
+ "生",
875
+ "五",
876
+ "間",
877
+ "上",
878
+ "東",
879
+ "四",
880
+ "今",
881
+ "金",
882
+ "九",
883
+ "入",
884
+ "学",
885
+ "高",
886
+ "円",
887
+ "子",
888
+ "外",
889
+ "八",
890
+ "六",
891
+ "下",
892
+ "来",
893
+ "気",
894
+ "小",
895
+ "七",
896
+ "山",
897
+ "話",
898
+ "女",
899
+ "北",
900
+ "午",
901
+ "百",
902
+ "書",
903
+ "先",
904
+ "名",
905
+ "川",
906
+ "千",
907
+ "水",
908
+ "半",
909
+ "男",
910
+ "西",
911
+ "電",
912
+ "校",
913
+ "語",
914
+ "土",
915
+ "木",
916
+ "聞",
917
+ "食",
918
+ "車",
919
+ "何",
920
+ "南",
921
+ "万",
922
+ "毎",
923
+ "白",
924
+ "天",
925
+ "母",
926
+ "火",
927
+ "右",
928
+ "読",
929
+ "友",
930
+ "左",
931
+ "休",
932
+ "父",
933
+ "雨",
934
+ ],
935
+ # Jap-Katakana
936
+ "Japanese—": [
937
+ "ー",
938
+ "ン",
939
+ "ス",
940
+ "・",
941
+ "ル",
942
+ "ト",
943
+ "リ",
944
+ "イ",
945
+ "ア",
946
+ "ラ",
947
+ "ッ",
948
+ "ク",
949
+ "ド",
950
+ "シ",
951
+ "レ",
952
+ "ジ",
953
+ "タ",
954
+ "フ",
955
+ "ロ",
956
+ "カ",
957
+ "テ",
958
+ "マ",
959
+ "ィ",
960
+ "グ",
961
+ "バ",
962
+ "ム",
963
+ "プ",
964
+ "オ",
965
+ "コ",
966
+ "デ",
967
+ "ニ",
968
+ "ウ",
969
+ "メ",
970
+ "サ",
971
+ "ビ",
972
+ "ナ",
973
+ "ブ",
974
+ "ャ",
975
+ "エ",
976
+ "ュ",
977
+ "チ",
978
+ "キ",
979
+ "ズ",
980
+ "ダ",
981
+ "パ",
982
+ "ミ",
983
+ "ェ",
984
+ "ョ",
985
+ "ハ",
986
+ "セ",
987
+ "ベ",
988
+ "ガ",
989
+ "モ",
990
+ "ツ",
991
+ "ネ",
992
+ "ボ",
993
+ "ソ",
994
+ "ノ",
995
+ "ァ",
996
+ "ヴ",
997
+ "ワ",
998
+ "ポ",
999
+ "ペ",
1000
+ "ピ",
1001
+ "ケ",
1002
+ "ゴ",
1003
+ "ギ",
1004
+ "ザ",
1005
+ "ホ",
1006
+ "ゲ",
1007
+ "ォ",
1008
+ "ヤ",
1009
+ "ヒ",
1010
+ "ユ",
1011
+ "ヨ",
1012
+ "ヘ",
1013
+ "ゼ",
1014
+ "ヌ",
1015
+ "ゥ",
1016
+ "ゾ",
1017
+ "ヶ",
1018
+ "ヂ",
1019
+ "ヲ",
1020
+ "ヅ",
1021
+ "ヵ",
1022
+ "ヱ",
1023
+ "ヰ",
1024
+ "ヮ",
1025
+ "ヽ",
1026
+ "゠",
1027
+ "ヾ",
1028
+ "ヷ",
1029
+ "ヿ",
1030
+ "ヸ",
1031
+ "ヹ",
1032
+ "ヺ",
1033
+ ],
1034
+ # Jap-Hiragana
1035
+ "Japanese——": [
1036
+ "の",
1037
+ "に",
1038
+ "る",
1039
+ "た",
1040
+ "と",
1041
+ "は",
1042
+ "し",
1043
+ "い",
1044
+ "を",
1045
+ "で",
1046
+ "て",
1047
+ "が",
1048
+ "な",
1049
+ "れ",
1050
+ "か",
1051
+ "ら",
1052
+ "さ",
1053
+ "っ",
1054
+ "り",
1055
+ "す",
1056
+ "あ",
1057
+ "も",
1058
+ "こ",
1059
+ "ま",
1060
+ "う",
1061
+ "く",
1062
+ "よ",
1063
+ "き",
1064
+ "ん",
1065
+ "め",
1066
+ "お",
1067
+ "け",
1068
+ "そ",
1069
+ "つ",
1070
+ "だ",
1071
+ "や",
1072
+ "え",
1073
+ "ど",
1074
+ "わ",
1075
+ "ち",
1076
+ "み",
1077
+ "せ",
1078
+ "じ",
1079
+ "ば",
1080
+ "へ",
1081
+ "び",
1082
+ "ず",
1083
+ "ろ",
1084
+ "ほ",
1085
+ "げ",
1086
+ "む",
1087
+ "べ",
1088
+ "ひ",
1089
+ "ょ",
1090
+ "ゆ",
1091
+ "ぶ",
1092
+ "ご",
1093
+ "ゃ",
1094
+ "ね",
1095
+ "ふ",
1096
+ "ぐ",
1097
+ "ぎ",
1098
+ "ぼ",
1099
+ "ゅ",
1100
+ "づ",
1101
+ "ざ",
1102
+ "ぞ",
1103
+ "ぬ",
1104
+ "ぜ",
1105
+ "ぱ",
1106
+ "ぽ",
1107
+ "ぷ",
1108
+ "ぴ",
1109
+ "ぃ",
1110
+ "ぁ",
1111
+ "ぇ",
1112
+ "ぺ",
1113
+ "ゞ",
1114
+ "ぢ",
1115
+ "ぉ",
1116
+ "ぅ",
1117
+ "ゐ",
1118
+ "ゝ",
1119
+ "ゑ",
1120
+ "゛",
1121
+ "゜",
1122
+ "ゎ",
1123
+ "ゔ",
1124
+ "゚",
1125
+ "ゟ",
1126
+ "゙",
1127
+ "ゕ",
1128
+ "ゖ",
1129
+ ],
1130
+ "Portuguese": [
1131
+ "a",
1132
+ "e",
1133
+ "o",
1134
+ "s",
1135
+ "i",
1136
+ "r",
1137
+ "d",
1138
+ "n",
1139
+ "t",
1140
+ "m",
1141
+ "u",
1142
+ "c",
1143
+ "l",
1144
+ "p",
1145
+ "g",
1146
+ "v",
1147
+ "b",
1148
+ "f",
1149
+ "h",
1150
+ "ã",
1151
+ "q",
1152
+ "é",
1153
+ "ç",
1154
+ "á",
1155
+ "z",
1156
+ "í",
1157
+ ],
1158
+ "Swedish": [
1159
+ "e",
1160
+ "a",
1161
+ "n",
1162
+ "r",
1163
+ "t",
1164
+ "s",
1165
+ "i",
1166
+ "l",
1167
+ "d",
1168
+ "o",
1169
+ "m",
1170
+ "k",
1171
+ "g",
1172
+ "v",
1173
+ "h",
1174
+ "f",
1175
+ "u",
1176
+ "p",
1177
+ "ä",
1178
+ "c",
1179
+ "b",
1180
+ "ö",
1181
+ "å",
1182
+ "y",
1183
+ "j",
1184
+ "x",
1185
+ ],
1186
+ "Chinese": [
1187
+ "的",
1188
+ "一",
1189
+ "是",
1190
+ "不",
1191
+ "了",
1192
+ "在",
1193
+ "人",
1194
+ "有",
1195
+ "我",
1196
+ "他",
1197
+ "这",
1198
+ "个",
1199
+ "们",
1200
+ "中",
1201
+ "来",
1202
+ "上",
1203
+ "大",
1204
+ "为",
1205
+ "和",
1206
+ "国",
1207
+ "地",
1208
+ "到",
1209
+ "以",
1210
+ "说",
1211
+ "时",
1212
+ "要",
1213
+ "就",
1214
+ "出",
1215
+ "会",
1216
+ "可",
1217
+ "也",
1218
+ "你",
1219
+ "对",
1220
+ "生",
1221
+ "能",
1222
+ "而",
1223
+ "子",
1224
+ "那",
1225
+ "得",
1226
+ "于",
1227
+ "着",
1228
+ "下",
1229
+ "自",
1230
+ "之",
1231
+ "年",
1232
+ "过",
1233
+ "发",
1234
+ "后",
1235
+ "作",
1236
+ "里",
1237
+ "用",
1238
+ "道",
1239
+ "行",
1240
+ "所",
1241
+ "然",
1242
+ "家",
1243
+ "种",
1244
+ "事",
1245
+ "成",
1246
+ "方",
1247
+ "多",
1248
+ "经",
1249
+ "么",
1250
+ "去",
1251
+ "法",
1252
+ "学",
1253
+ "如",
1254
+ "都",
1255
+ "同",
1256
+ "现",
1257
+ "当",
1258
+ "没",
1259
+ "动",
1260
+ "面",
1261
+ "起",
1262
+ "看",
1263
+ "定",
1264
+ "天",
1265
+ "分",
1266
+ "还",
1267
+ "进",
1268
+ "好",
1269
+ "小",
1270
+ "部",
1271
+ "其",
1272
+ "些",
1273
+ "主",
1274
+ "样",
1275
+ "理",
1276
+ "心",
1277
+ "她",
1278
+ "本",
1279
+ "前",
1280
+ "开",
1281
+ "但",
1282
+ "因",
1283
+ "只",
1284
+ "从",
1285
+ "想",
1286
+ "实",
1287
+ ],
1288
+ "Ukrainian": [
1289
+ "о",
1290
+ "а",
1291
+ "н",
1292
+ "і",
1293
+ "и",
1294
+ "р",
1295
+ "в",
1296
+ "т",
1297
+ "е",
1298
+ "с",
1299
+ "к",
1300
+ "л",
1301
+ "у",
1302
+ "д",
1303
+ "м",
1304
+ "п",
1305
+ "з",
1306
+ "я",
1307
+ "ь",
1308
+ "б",
1309
+ "г",
1310
+ "й",
1311
+ "ч",
1312
+ "х",
1313
+ "ц",
1314
+ "ї",
1315
+ ],
1316
+ "Norwegian": [
1317
+ "e",
1318
+ "r",
1319
+ "n",
1320
+ "t",
1321
+ "a",
1322
+ "s",
1323
+ "i",
1324
+ "o",
1325
+ "l",
1326
+ "d",
1327
+ "g",
1328
+ "k",
1329
+ "m",
1330
+ "v",
1331
+ "f",
1332
+ "p",
1333
+ "u",
1334
+ "b",
1335
+ "h",
1336
+ "å",
1337
+ "y",
1338
+ "j",
1339
+ "ø",
1340
+ "c",
1341
+ "æ",
1342
+ "w",
1343
+ ],
1344
+ "Finnish": [
1345
+ "a",
1346
+ "i",
1347
+ "n",
1348
+ "t",
1349
+ "e",
1350
+ "s",
1351
+ "l",
1352
+ "o",
1353
+ "u",
1354
+ "k",
1355
+ "ä",
1356
+ "m",
1357
+ "r",
1358
+ "v",
1359
+ "j",
1360
+ "h",
1361
+ "p",
1362
+ "y",
1363
+ "d",
1364
+ "ö",
1365
+ "g",
1366
+ "c",
1367
+ "b",
1368
+ "f",
1369
+ "w",
1370
+ "z",
1371
+ ],
1372
+ "Vietnamese": [
1373
+ "n",
1374
+ "h",
1375
+ "t",
1376
+ "i",
1377
+ "c",
1378
+ "g",
1379
+ "a",
1380
+ "o",
1381
+ "u",
1382
+ "m",
1383
+ "l",
1384
+ "r",
1385
+ "à",
1386
+ "đ",
1387
+ "s",
1388
+ "e",
1389
+ "v",
1390
+ "p",
1391
+ "b",
1392
+ "y",
1393
+ "ư",
1394
+ "d",
1395
+ "á",
1396
+ "k",
1397
+ "ộ",
1398
+ "ế",
1399
+ ],
1400
+ "Czech": [
1401
+ "o",
1402
+ "e",
1403
+ "a",
1404
+ "n",
1405
+ "t",
1406
+ "s",
1407
+ "i",
1408
+ "l",
1409
+ "v",
1410
+ "r",
1411
+ "k",
1412
+ "d",
1413
+ "u",
1414
+ "m",
1415
+ "p",
1416
+ "í",
1417
+ "c",
1418
+ "h",
1419
+ "z",
1420
+ "á",
1421
+ "y",
1422
+ "j",
1423
+ "b",
1424
+ "ě",
1425
+ "é",
1426
+ "ř",
1427
+ ],
1428
+ "Hungarian": [
1429
+ "e",
1430
+ "a",
1431
+ "t",
1432
+ "l",
1433
+ "s",
1434
+ "n",
1435
+ "k",
1436
+ "r",
1437
+ "i",
1438
+ "o",
1439
+ "z",
1440
+ "á",
1441
+ "é",
1442
+ "g",
1443
+ "m",
1444
+ "b",
1445
+ "y",
1446
+ "v",
1447
+ "d",
1448
+ "h",
1449
+ "u",
1450
+ "p",
1451
+ "j",
1452
+ "ö",
1453
+ "f",
1454
+ "c",
1455
+ ],
1456
+ "Korean": [
1457
+ "이",
1458
+ "다",
1459
+ "에",
1460
+ "의",
1461
+ "는",
1462
+ "로",
1463
+ "하",
1464
+ "을",
1465
+ "가",
1466
+ "고",
1467
+ "지",
1468
+ "서",
1469
+ "한",
1470
+ "은",
1471
+ "기",
1472
+ "으",
1473
+ "년",
1474
+ "대",
1475
+ "사",
1476
+ "시",
1477
+ "를",
1478
+ "리",
1479
+ "도",
1480
+ "인",
1481
+ "스",
1482
+ "일",
1483
+ ],
1484
+ "Indonesian": [
1485
+ "a",
1486
+ "n",
1487
+ "e",
1488
+ "i",
1489
+ "r",
1490
+ "t",
1491
+ "u",
1492
+ "s",
1493
+ "d",
1494
+ "k",
1495
+ "m",
1496
+ "l",
1497
+ "g",
1498
+ "p",
1499
+ "b",
1500
+ "o",
1501
+ "h",
1502
+ "y",
1503
+ "j",
1504
+ "c",
1505
+ "w",
1506
+ "f",
1507
+ "v",
1508
+ "z",
1509
+ "x",
1510
+ "q",
1511
+ ],
1512
+ "Turkish": [
1513
+ "a",
1514
+ "e",
1515
+ "i",
1516
+ "n",
1517
+ "r",
1518
+ "l",
1519
+ "ı",
1520
+ "k",
1521
+ "d",
1522
+ "t",
1523
+ "s",
1524
+ "m",
1525
+ "y",
1526
+ "u",
1527
+ "o",
1528
+ "b",
1529
+ "ü",
1530
+ "ş",
1531
+ "v",
1532
+ "g",
1533
+ "z",
1534
+ "h",
1535
+ "c",
1536
+ "p",
1537
+ "ç",
1538
+ "ğ",
1539
+ ],
1540
+ "Romanian": [
1541
+ "e",
1542
+ "i",
1543
+ "a",
1544
+ "r",
1545
+ "n",
1546
+ "t",
1547
+ "u",
1548
+ "l",
1549
+ "o",
1550
+ "c",
1551
+ "s",
1552
+ "d",
1553
+ "p",
1554
+ "m",
1555
+ "ă",
1556
+ "f",
1557
+ "v",
1558
+ "î",
1559
+ "g",
1560
+ "b",
1561
+ "ș",
1562
+ "ț",
1563
+ "z",
1564
+ "h",
1565
+ "â",
1566
+ "j",
1567
+ ],
1568
+ "Farsi": [
1569
+ "ا",
1570
+ "ی",
1571
+ "ر",
1572
+ "د",
1573
+ "ن",
1574
+ "ه",
1575
+ "و",
1576
+ "م",
1577
+ "ت",
1578
+ "ب",
1579
+ "س",
1580
+ "ل",
1581
+ "ک",
1582
+ "ش",
1583
+ "ز",
1584
+ "ف",
1585
+ "گ",
1586
+ "ع",
1587
+ "خ",
1588
+ "ق",
1589
+ "ج",
1590
+ "آ",
1591
+ "پ",
1592
+ "ح",
1593
+ "ط",
1594
+ "ص",
1595
+ ],
1596
+ "Arabic": [
1597
+ "ا",
1598
+ "ل",
1599
+ "ي",
1600
+ "م",
1601
+ "و",
1602
+ "ن",
1603
+ "ر",
1604
+ "ت",
1605
+ "ب",
1606
+ "ة",
1607
+ "ع",
1608
+ "د",
1609
+ "س",
1610
+ "ف",
1611
+ "ه",
1612
+ "ك",
1613
+ "ق",
1614
+ "أ",
1615
+ "ح",
1616
+ "ج",
1617
+ "ش",
1618
+ "ط",
1619
+ "ص",
1620
+ "ى",
1621
+ "خ",
1622
+ "إ",
1623
+ ],
1624
+ "Danish": [
1625
+ "e",
1626
+ "r",
1627
+ "n",
1628
+ "t",
1629
+ "a",
1630
+ "i",
1631
+ "s",
1632
+ "d",
1633
+ "l",
1634
+ "o",
1635
+ "g",
1636
+ "m",
1637
+ "k",
1638
+ "f",
1639
+ "v",
1640
+ "u",
1641
+ "b",
1642
+ "h",
1643
+ "p",
1644
+ "å",
1645
+ "y",
1646
+ "ø",
1647
+ "æ",
1648
+ "c",
1649
+ "j",
1650
+ "w",
1651
+ ],
1652
+ "Serbian": [
1653
+ "а",
1654
+ "и",
1655
+ "о",
1656
+ "е",
1657
+ "н",
1658
+ "р",
1659
+ "с",
1660
+ "у",
1661
+ "т",
1662
+ "к",
1663
+ "ј",
1664
+ "в",
1665
+ "д",
1666
+ "м",
1667
+ "п",
1668
+ "л",
1669
+ "г",
1670
+ "з",
1671
+ "б",
1672
+ "a",
1673
+ "i",
1674
+ "e",
1675
+ "o",
1676
+ "n",
1677
+ "ц",
1678
+ "ш",
1679
+ ],
1680
+ "Lithuanian": [
1681
+ "i",
1682
+ "a",
1683
+ "s",
1684
+ "o",
1685
+ "r",
1686
+ "e",
1687
+ "t",
1688
+ "n",
1689
+ "u",
1690
+ "k",
1691
+ "m",
1692
+ "l",
1693
+ "p",
1694
+ "v",
1695
+ "d",
1696
+ "j",
1697
+ "g",
1698
+ "ė",
1699
+ "b",
1700
+ "y",
1701
+ "ų",
1702
+ "š",
1703
+ "ž",
1704
+ "c",
1705
+ "ą",
1706
+ "į",
1707
+ ],
1708
+ "Slovene": [
1709
+ "e",
1710
+ "a",
1711
+ "i",
1712
+ "o",
1713
+ "n",
1714
+ "r",
1715
+ "s",
1716
+ "l",
1717
+ "t",
1718
+ "j",
1719
+ "v",
1720
+ "k",
1721
+ "d",
1722
+ "p",
1723
+ "m",
1724
+ "u",
1725
+ "z",
1726
+ "b",
1727
+ "g",
1728
+ "h",
1729
+ "č",
1730
+ "c",
1731
+ "š",
1732
+ "ž",
1733
+ "f",
1734
+ "y",
1735
+ ],
1736
+ "Slovak": [
1737
+ "o",
1738
+ "a",
1739
+ "e",
1740
+ "n",
1741
+ "i",
1742
+ "r",
1743
+ "v",
1744
+ "t",
1745
+ "s",
1746
+ "l",
1747
+ "k",
1748
+ "d",
1749
+ "m",
1750
+ "p",
1751
+ "u",
1752
+ "c",
1753
+ "h",
1754
+ "j",
1755
+ "b",
1756
+ "z",
1757
+ "á",
1758
+ "y",
1759
+ "ý",
1760
+ "í",
1761
+ "č",
1762
+ "é",
1763
+ ],
1764
+ "Hebrew": [
1765
+ "י",
1766
+ "ו",
1767
+ "ה",
1768
+ "ל",
1769
+ "ר",
1770
+ "ב",
1771
+ "ת",
1772
+ "מ",
1773
+ "א",
1774
+ "ש",
1775
+ "נ",
1776
+ "ע",
1777
+ "ם",
1778
+ "ד",
1779
+ "ק",
1780
+ "ח",
1781
+ "פ",
1782
+ "ס",
1783
+ "כ",
1784
+ "ג",
1785
+ "ט",
1786
+ "צ",
1787
+ "ן",
1788
+ "ז",
1789
+ "ך",
1790
+ ],
1791
+ "Bulgarian": [
1792
+ "а",
1793
+ "и",
1794
+ "о",
1795
+ "е",
1796
+ "н",
1797
+ "т",
1798
+ "р",
1799
+ "с",
1800
+ "в",
1801
+ "л",
1802
+ "к",
1803
+ "д",
1804
+ "п",
1805
+ "м",
1806
+ "з",
1807
+ "г",
1808
+ "я",
1809
+ "ъ",
1810
+ "у",
1811
+ "б",
1812
+ "ч",
1813
+ "ц",
1814
+ "й",
1815
+ "ж",
1816
+ "щ",
1817
+ "х",
1818
+ ],
1819
+ "Croatian": [
1820
+ "a",
1821
+ "i",
1822
+ "o",
1823
+ "e",
1824
+ "n",
1825
+ "r",
1826
+ "j",
1827
+ "s",
1828
+ "t",
1829
+ "u",
1830
+ "k",
1831
+ "l",
1832
+ "v",
1833
+ "d",
1834
+ "m",
1835
+ "p",
1836
+ "g",
1837
+ "z",
1838
+ "b",
1839
+ "c",
1840
+ "č",
1841
+ "h",
1842
+ "š",
1843
+ "ž",
1844
+ "ć",
1845
+ "f",
1846
+ ],
1847
+ "Hindi": [
1848
+ "क",
1849
+ "र",
1850
+ "स",
1851
+ "न",
1852
+ "त",
1853
+ "म",
1854
+ "ह",
1855
+ "प",
1856
+ "य",
1857
+ "ल",
1858
+ "व",
1859
+ "ज",
1860
+ "द",
1861
+ "ग",
1862
+ "ब",
1863
+ "श",
1864
+ "ट",
1865
+ "अ",
1866
+ "ए",
1867
+ "थ",
1868
+ "भ",
1869
+ "ड",
1870
+ "च",
1871
+ "ध",
1872
+ "ष",
1873
+ "इ",
1874
+ ],
1875
+ "Estonian": [
1876
+ "a",
1877
+ "i",
1878
+ "e",
1879
+ "s",
1880
+ "t",
1881
+ "l",
1882
+ "u",
1883
+ "n",
1884
+ "o",
1885
+ "k",
1886
+ "r",
1887
+ "d",
1888
+ "m",
1889
+ "v",
1890
+ "g",
1891
+ "p",
1892
+ "j",
1893
+ "h",
1894
+ "ä",
1895
+ "b",
1896
+ "õ",
1897
+ "ü",
1898
+ "f",
1899
+ "c",
1900
+ "ö",
1901
+ "y",
1902
+ ],
1903
+ "Thai": [
1904
+ "า",
1905
+ "น",
1906
+ "ร",
1907
+ "อ",
1908
+ "ก",
1909
+ "เ",
1910
+ "ง",
1911
+ "ม",
1912
+ "ย",
1913
+ "ล",
1914
+ "ว",
1915
+ "ด",
1916
+ "ท",
1917
+ "ส",
1918
+ "ต",
1919
+ "ะ",
1920
+ "ป",
1921
+ "บ",
1922
+ "ค",
1923
+ "ห",
1924
+ "แ",
1925
+ "จ",
1926
+ "พ",
1927
+ "ช",
1928
+ "ข",
1929
+ "ใ",
1930
+ ],
1931
+ "Greek": [
1932
+ "α",
1933
+ "τ",
1934
+ "ο",
1935
+ "ι",
1936
+ "ε",
1937
+ "ν",
1938
+ "ρ",
1939
+ "σ",
1940
+ "κ",
1941
+ "η",
1942
+ "π",
1943
+ "ς",
1944
+ "υ",
1945
+ "μ",
1946
+ "λ",
1947
+ "ί",
1948
+ "ό",
1949
+ "ά",
1950
+ "γ",
1951
+ "έ",
1952
+ "δ",
1953
+ "ή",
1954
+ "ω",
1955
+ "χ",
1956
+ "θ",
1957
+ "ύ",
1958
+ ],
1959
+ "Tamil": [
1960
+ "க",
1961
+ "த",
1962
+ "ப",
1963
+ "ட",
1964
+ "ர",
1965
+ "ம",
1966
+ "ல",
1967
+ "ன",
1968
+ "வ",
1969
+ "ற",
1970
+ "ய",
1971
+ "ள",
1972
+ "ச",
1973
+ "ந",
1974
+ "இ",
1975
+ "ண",
1976
+ "அ",
1977
+ "ஆ",
1978
+ "ழ",
1979
+ "ங",
1980
+ "எ",
1981
+ "உ",
1982
+ "ஒ",
1983
+ "ஸ",
1984
+ ],
1985
+ "Kazakh": [
1986
+ "а",
1987
+ "ы",
1988
+ "е",
1989
+ "н",
1990
+ "т",
1991
+ "р",
1992
+ "л",
1993
+ "і",
1994
+ "д",
1995
+ "с",
1996
+ "м",
1997
+ "қ",
1998
+ "к",
1999
+ "о",
2000
+ "б",
2001
+ "и",
2002
+ "у",
2003
+ "ғ",
2004
+ "ж",
2005
+ "ң",
2006
+ "з",
2007
+ "ш",
2008
+ "й",
2009
+ "п",
2010
+ "г",
2011
+ "ө",
2012
+ ],
2013
+ }
2014
+
2015
+ LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES)
2016
+
2017
+ # Bit flags for unified character classification.
2018
+ # A single unicodedata.name() call sets all relevant flags at once.
2019
+ _LATIN: int = 1
2020
+ _ACCENTUATED: int = 1 << 1
2021
+ _CJK: int = 1 << 2
2022
+ _HANGUL: int = 1 << 3
2023
+ _KATAKANA: int = 1 << 4
2024
+ _HIRAGANA: int = 1 << 5
2025
+ _THAI: int = 1 << 6
2026
+ _ARABIC: int = 1 << 7
2027
+ _ARABIC_ISOLATED_FORM: int = 1 << 8
2028
+
2029
+ _ACCENT_KEYWORDS: tuple[str, ...] = (
2030
+ "WITH GRAVE",
2031
+ "WITH ACUTE",
2032
+ "WITH CEDILLA",
2033
+ "WITH DIAERESIS",
2034
+ "WITH CIRCUMFLEX",
2035
+ "WITH TILDE",
2036
+ "WITH MACRON",
2037
+ "WITH RING ABOVE",
2038
+ )
2039
+
2040
+ # Pre-built lookup structures for FREQUENCIES (computed once at import time).
2041
+ # character -> rank mapping per language (replaces list .index() calls).
2042
+ _FREQUENCIES_RANK: dict[str, dict[str, int]] = {
2043
+ lang: {char: rank for rank, char in enumerate(chars)}
2044
+ for lang, chars in FREQUENCIES.items()
2045
+ }
2046
+
2047
+ # frozenset per language (avoids rebuilding set() per call).
2048
+ _FREQUENCIES_SET: dict[str, frozenset[str]] = {
2049
+ lang: frozenset(chars) for lang, chars in FREQUENCIES.items()
2050
+ }
.venv/lib/python3.11/site-packages/charset_normalizer/legacy.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+ from warnings import warn
5
+
6
+ from .api import from_bytes
7
+ from .constant import CHARDET_CORRESPONDENCE, TOO_SMALL_SEQUENCE
8
+
9
+ if TYPE_CHECKING:
10
+ from typing import TypedDict
11
+
12
+ class ResultDict(TypedDict):
13
+ encoding: str | None
14
+ language: str
15
+ confidence: float | None
16
+
17
+
18
+ def detect(
19
+ byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any
20
+ ) -> ResultDict:
21
+ """
22
+ chardet legacy method
23
+ Detect the encoding of the given byte string. It should be mostly backward-compatible.
24
+ Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it)
25
+ This function is deprecated and should be used to migrate your project easily, consult the documentation for
26
+ further information. Not planned for removal.
27
+
28
+ :param byte_str: The byte sequence to examine.
29
+ :param should_rename_legacy: Should we rename legacy encodings
30
+ to their more modern equivalents?
31
+ """
32
+ if len(kwargs):
33
+ warn(
34
+ f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()"
35
+ )
36
+
37
+ if not isinstance(byte_str, (bytearray, bytes)):
38
+ raise TypeError( # pragma: nocover
39
+ f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
40
+ )
41
+
42
+ if isinstance(byte_str, bytearray):
43
+ byte_str = bytes(byte_str)
44
+
45
+ r = from_bytes(byte_str).best()
46
+
47
+ encoding = r.encoding if r is not None else None
48
+ language = r.language if r is not None and r.language != "Unknown" else ""
49
+ confidence = 1.0 - r.chaos if r is not None else None
50
+
51
+ # automatically lower confidence
52
+ # on small bytes samples.
53
+ # https://github.com/jawah/charset_normalizer/issues/391
54
+ if (
55
+ confidence is not None
56
+ and confidence >= 0.9
57
+ and encoding
58
+ not in {
59
+ "utf_8",
60
+ "ascii",
61
+ }
62
+ and r.bom is False # type: ignore[union-attr]
63
+ and len(byte_str) < TOO_SMALL_SEQUENCE
64
+ ):
65
+ confidence -= 0.2
66
+
67
+ # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process
68
+ # but chardet does return 'utf-8-sig' and it is a valid codec name.
69
+ if r is not None and encoding == "utf_8" and r.bom:
70
+ encoding += "_sig"
71
+
72
+ if should_rename_legacy is False and encoding in CHARDET_CORRESPONDENCE:
73
+ encoding = CHARDET_CORRESPONDENCE[encoding]
74
+
75
+ return {
76
+ "encoding": encoding,
77
+ "language": language,
78
+ "confidence": confidence,
79
+ }
.venv/lib/python3.11/site-packages/charset_normalizer/md.py ADDED
@@ -0,0 +1,936 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from functools import lru_cache
5
+ from logging import getLogger
6
+
7
+ if sys.version_info >= (3, 8):
8
+ from typing import final
9
+ else:
10
+ try:
11
+ from typing_extensions import final
12
+ except ImportError:
13
+
14
+ def final(cls): # type: ignore[misc,no-untyped-def]
15
+ return cls
16
+
17
+
18
+ from .constant import (
19
+ COMMON_CJK_CHARACTERS,
20
+ COMMON_SAFE_ASCII_CHARACTERS,
21
+ TRACE,
22
+ UNICODE_SECONDARY_RANGE_KEYWORD,
23
+ _ACCENTUATED,
24
+ _ARABIC,
25
+ _ARABIC_ISOLATED_FORM,
26
+ _CJK,
27
+ _HANGUL,
28
+ _HIRAGANA,
29
+ _KATAKANA,
30
+ _LATIN,
31
+ _THAI,
32
+ )
33
+ from .utils import (
34
+ _character_flags,
35
+ is_emoticon,
36
+ is_punctuation,
37
+ is_separator,
38
+ is_symbol,
39
+ remove_accent,
40
+ unicode_range,
41
+ )
42
+
43
+ # Combined bitmask for CJK/Hangul/Katakana/Hiragana/Thai glyph detection.
44
+ _GLYPH_MASK: int = _CJK | _HANGUL | _KATAKANA | _HIRAGANA | _THAI
45
+
46
+
47
+ @final
48
+ class CharInfo:
49
+ """Pre-computed character properties shared across all detectors.
50
+
51
+ Instantiated once and reused via :meth:`update` on every character
52
+ in the hot loop so that redundant calls to str methods
53
+ (``isalpha``, ``isupper``, …) and cached utility functions
54
+ (``_character_flags``, ``is_punctuation``, …) are avoided when
55
+ several plugins need the same information.
56
+ """
57
+
58
+ __slots__ = (
59
+ "character",
60
+ "printable",
61
+ "alpha",
62
+ "upper",
63
+ "lower",
64
+ "space",
65
+ "digit",
66
+ "is_ascii",
67
+ "case_variable",
68
+ "flags",
69
+ "accentuated",
70
+ "latin",
71
+ "is_cjk",
72
+ "is_arabic",
73
+ "is_glyph",
74
+ "punct",
75
+ "sym",
76
+ )
77
+
78
+ def __init__(self) -> None:
79
+ self.character: str = ""
80
+ self.printable: bool = False
81
+ self.alpha: bool = False
82
+ self.upper: bool = False
83
+ self.lower: bool = False
84
+ self.space: bool = False
85
+ self.digit: bool = False
86
+ self.is_ascii: bool = False
87
+ self.case_variable: bool = False
88
+ self.flags: int = 0
89
+ self.accentuated: bool = False
90
+ self.latin: bool = False
91
+ self.is_cjk: bool = False
92
+ self.is_arabic: bool = False
93
+ self.is_glyph: bool = False
94
+ self.punct: bool = False
95
+ self.sym: bool = False
96
+
97
+ def update(self, character: str) -> None:
98
+ """Update all properties for *character* (called once per character)."""
99
+ self.character = character
100
+
101
+ # ASCII fast-path: for characters with ord < 128, we can skip
102
+ # _character_flags() entirely and derive most properties from ord.
103
+ o: int = ord(character)
104
+ if o < 128:
105
+ self.is_ascii = True
106
+ self.accentuated = False
107
+ self.is_cjk = False
108
+ self.is_arabic = False
109
+ self.is_glyph = False
110
+ # ASCII alpha: a-z (97-122) or A-Z (65-90)
111
+ if 65 <= o <= 90:
112
+ # Uppercase ASCII letter
113
+ self.alpha = True
114
+ self.upper = True
115
+ self.lower = False
116
+ self.space = False
117
+ self.digit = False
118
+ self.printable = True
119
+ self.case_variable = True
120
+ self.flags = _LATIN
121
+ self.latin = True
122
+ self.punct = False
123
+ self.sym = False
124
+ elif 97 <= o <= 122:
125
+ # Lowercase ASCII letter
126
+ self.alpha = True
127
+ self.upper = False
128
+ self.lower = True
129
+ self.space = False
130
+ self.digit = False
131
+ self.printable = True
132
+ self.case_variable = True
133
+ self.flags = _LATIN
134
+ self.latin = True
135
+ self.punct = False
136
+ self.sym = False
137
+ elif 48 <= o <= 57:
138
+ # ASCII digit 0-9
139
+ self.alpha = False
140
+ self.upper = False
141
+ self.lower = False
142
+ self.space = False
143
+ self.digit = True
144
+ self.printable = True
145
+ self.case_variable = False
146
+ self.flags = 0
147
+ self.latin = False
148
+ self.punct = False
149
+ self.sym = False
150
+ elif o == 32 or (9 <= o <= 13):
151
+ # Space, tab, newline, etc.
152
+ self.alpha = False
153
+ self.upper = False
154
+ self.lower = False
155
+ self.space = True
156
+ self.digit = False
157
+ self.printable = o == 32
158
+ self.case_variable = False
159
+ self.flags = 0
160
+ self.latin = False
161
+ self.punct = False
162
+ self.sym = False
163
+ else:
164
+ # Other ASCII (punctuation, symbols, control chars)
165
+ self.printable = character.isprintable()
166
+ self.alpha = False
167
+ self.upper = False
168
+ self.lower = False
169
+ self.space = False
170
+ self.digit = False
171
+ self.case_variable = False
172
+ self.flags = 0
173
+ self.latin = False
174
+ self.punct = is_punctuation(character) if self.printable else False
175
+ self.sym = is_symbol(character) if self.printable else False
176
+ else:
177
+ # Non-ASCII path
178
+ self.is_ascii = False
179
+ self.printable = character.isprintable()
180
+ self.alpha = character.isalpha()
181
+ self.upper = character.isupper()
182
+ self.lower = character.islower()
183
+ self.space = character.isspace()
184
+ self.digit = character.isdigit()
185
+ self.case_variable = self.lower != self.upper
186
+
187
+ # Flag-based classification (single unicodedata.name() call, lru-cached)
188
+ flags: int
189
+ if self.alpha:
190
+ flags = _character_flags(character)
191
+ else:
192
+ flags = 0
193
+ self.flags = flags
194
+ self.accentuated = bool(flags & _ACCENTUATED)
195
+ self.latin = bool(flags & _LATIN)
196
+ self.is_cjk = bool(flags & _CJK)
197
+ self.is_arabic = bool(flags & _ARABIC)
198
+ self.is_glyph = bool(flags & _GLYPH_MASK)
199
+
200
+ # Eagerly compute punct and sym (avoids property dispatch overhead
201
+ # on 300K+ accesses in the hot loop).
202
+ self.punct = is_punctuation(character) if self.printable else False
203
+ self.sym = is_symbol(character) if self.printable else False
204
+
205
+
206
+ class MessDetectorPlugin:
207
+ """
208
+ Base abstract class used for mess detection plugins.
209
+ All detectors MUST extend and implement given methods.
210
+ """
211
+
212
+ __slots__ = ()
213
+
214
+ def feed_info(self, character: str, info: CharInfo) -> None:
215
+ """
216
+ The main routine to be executed upon character.
217
+ Insert the logic in witch the text would be considered chaotic.
218
+ """
219
+ raise NotImplementedError # Defensive:
220
+
221
+ def reset(self) -> None: # Defensive:
222
+ """
223
+ Permit to reset the plugin to the initial state.
224
+ """
225
+ raise NotImplementedError
226
+
227
+ @property
228
+ def ratio(self) -> float:
229
+ """
230
+ Compute the chaos ratio based on what your feed() has seen.
231
+ Must NOT be lower than 0.; No restriction gt 0.
232
+ """
233
+ raise NotImplementedError # Defensive:
234
+
235
+
236
+ @final
237
+ class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin):
238
+ __slots__ = (
239
+ "_punctuation_count",
240
+ "_symbol_count",
241
+ "_character_count",
242
+ "_last_printable_char",
243
+ "_frenzy_symbol_in_word",
244
+ )
245
+
246
+ def __init__(self) -> None:
247
+ self._punctuation_count: int = 0
248
+ self._symbol_count: int = 0
249
+ self._character_count: int = 0
250
+
251
+ self._last_printable_char: str | None = None
252
+ self._frenzy_symbol_in_word: bool = False
253
+
254
+ def feed_info(self, character: str, info: CharInfo) -> None:
255
+ """Optimized feed using pre-computed character info."""
256
+ self._character_count += 1
257
+
258
+ if (
259
+ character != self._last_printable_char
260
+ and character not in COMMON_SAFE_ASCII_CHARACTERS
261
+ ):
262
+ if info.punct:
263
+ self._punctuation_count += 1
264
+ elif not info.digit and info.sym and not is_emoticon(character):
265
+ self._symbol_count += 2
266
+
267
+ self._last_printable_char = character
268
+
269
+ def reset(self) -> None: # Abstract
270
+ self._punctuation_count = 0
271
+ self._character_count = 0
272
+ self._symbol_count = 0
273
+
274
+ @property
275
+ def ratio(self) -> float:
276
+ if self._character_count == 0:
277
+ return 0.0
278
+
279
+ ratio_of_punctuation: float = (
280
+ self._punctuation_count + self._symbol_count
281
+ ) / self._character_count
282
+
283
+ return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0
284
+
285
+
286
+ @final
287
+ class TooManyAccentuatedPlugin(MessDetectorPlugin):
288
+ __slots__ = ("_character_count", "_accentuated_count")
289
+
290
+ def __init__(self) -> None:
291
+ self._character_count: int = 0
292
+ self._accentuated_count: int = 0
293
+
294
+ def feed_info(self, character: str, info: CharInfo) -> None:
295
+ """Optimized feed using pre-computed character info."""
296
+ self._character_count += 1
297
+
298
+ if info.accentuated:
299
+ self._accentuated_count += 1
300
+
301
+ def reset(self) -> None: # Abstract
302
+ self._character_count = 0
303
+ self._accentuated_count = 0
304
+
305
+ @property
306
+ def ratio(self) -> float:
307
+ if self._character_count < 8:
308
+ return 0.0
309
+
310
+ ratio_of_accentuation: float = self._accentuated_count / self._character_count
311
+ return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0
312
+
313
+
314
+ @final
315
+ class UnprintablePlugin(MessDetectorPlugin):
316
+ __slots__ = ("_unprintable_count", "_character_count")
317
+
318
+ def __init__(self) -> None:
319
+ self._unprintable_count: int = 0
320
+ self._character_count: int = 0
321
+
322
+ def feed_info(self, character: str, info: CharInfo) -> None:
323
+ """Optimized feed using pre-computed character info."""
324
+ if (
325
+ not info.space
326
+ and not info.printable
327
+ and character != "\x1a"
328
+ and character != "\ufeff"
329
+ ):
330
+ self._unprintable_count += 1
331
+ self._character_count += 1
332
+
333
+ def reset(self) -> None: # Abstract
334
+ self._unprintable_count = 0
335
+
336
+ @property
337
+ def ratio(self) -> float:
338
+ if self._character_count == 0: # Defensive:
339
+ return 0.0
340
+
341
+ return (self._unprintable_count * 8) / self._character_count
342
+
343
+
344
+ @final
345
+ class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
346
+ __slots__ = (
347
+ "_successive_count",
348
+ "_character_count",
349
+ "_last_latin_character",
350
+ "_last_was_accentuated",
351
+ )
352
+
353
+ def __init__(self) -> None:
354
+ self._successive_count: int = 0
355
+ self._character_count: int = 0
356
+
357
+ self._last_latin_character: str | None = None
358
+ self._last_was_accentuated: bool = False
359
+
360
+ def feed_info(self, character: str, info: CharInfo) -> None:
361
+ """Optimized feed using pre-computed character info."""
362
+ self._character_count += 1
363
+ if (
364
+ self._last_latin_character is not None
365
+ and info.accentuated
366
+ and self._last_was_accentuated
367
+ ):
368
+ if info.upper and self._last_latin_character.isupper():
369
+ self._successive_count += 1
370
+ if remove_accent(character) == remove_accent(self._last_latin_character):
371
+ self._successive_count += 1
372
+ self._last_latin_character = character
373
+ self._last_was_accentuated = info.accentuated
374
+
375
+ def reset(self) -> None: # Abstract
376
+ self._successive_count = 0
377
+ self._character_count = 0
378
+ self._last_latin_character = None
379
+ self._last_was_accentuated = False
380
+
381
+ @property
382
+ def ratio(self) -> float:
383
+ if self._character_count == 0:
384
+ return 0.0
385
+
386
+ return (self._successive_count * 2) / self._character_count
387
+
388
+
389
+ @final
390
+ class SuspiciousRange(MessDetectorPlugin):
391
+ __slots__ = (
392
+ "_suspicious_successive_range_count",
393
+ "_character_count",
394
+ "_last_printable_seen",
395
+ "_last_printable_range",
396
+ )
397
+
398
+ def __init__(self) -> None:
399
+ self._suspicious_successive_range_count: int = 0
400
+ self._character_count: int = 0
401
+ self._last_printable_seen: str | None = None
402
+ self._last_printable_range: str | None = None
403
+
404
+ def feed_info(self, character: str, info: CharInfo) -> None:
405
+ """Optimized feed using pre-computed character info."""
406
+ self._character_count += 1
407
+
408
+ if info.space or info.punct or character in COMMON_SAFE_ASCII_CHARACTERS:
409
+ self._last_printable_seen = None
410
+ self._last_printable_range = None
411
+ return
412
+
413
+ if self._last_printable_seen is None:
414
+ self._last_printable_seen = character
415
+ self._last_printable_range = unicode_range(character)
416
+ return
417
+
418
+ unicode_range_a: str | None = self._last_printable_range
419
+ unicode_range_b: str | None = unicode_range(character)
420
+
421
+ if is_suspiciously_successive_range(unicode_range_a, unicode_range_b):
422
+ self._suspicious_successive_range_count += 1
423
+
424
+ self._last_printable_seen = character
425
+ self._last_printable_range = unicode_range_b
426
+
427
+ def reset(self) -> None: # Abstract
428
+ self._character_count = 0
429
+ self._suspicious_successive_range_count = 0
430
+ self._last_printable_seen = None
431
+ self._last_printable_range = None
432
+
433
+ @property
434
+ def ratio(self) -> float:
435
+ if self._character_count <= 13:
436
+ return 0.0
437
+
438
+ ratio_of_suspicious_range_usage: float = (
439
+ self._suspicious_successive_range_count * 2
440
+ ) / self._character_count
441
+
442
+ return ratio_of_suspicious_range_usage
443
+
444
+
445
+ @final
446
+ class SuperWeirdWordPlugin(MessDetectorPlugin):
447
+ __slots__ = (
448
+ "_word_count",
449
+ "_bad_word_count",
450
+ "_foreign_long_count",
451
+ "_is_current_word_bad",
452
+ "_foreign_long_watch",
453
+ "_character_count",
454
+ "_bad_character_count",
455
+ "_buffer_length",
456
+ "_buffer_last_char",
457
+ "_buffer_last_char_accentuated",
458
+ "_buffer_accent_count",
459
+ "_buffer_glyph_count",
460
+ "_buffer_upper_count",
461
+ )
462
+
463
+ def __init__(self) -> None:
464
+ self._word_count: int = 0
465
+ self._bad_word_count: int = 0
466
+ self._foreign_long_count: int = 0
467
+
468
+ self._is_current_word_bad: bool = False
469
+ self._foreign_long_watch: bool = False
470
+
471
+ self._character_count: int = 0
472
+ self._bad_character_count: int = 0
473
+
474
+ self._buffer_length: int = 0
475
+ self._buffer_last_char: str | None = None
476
+ self._buffer_last_char_accentuated: bool = False
477
+ self._buffer_accent_count: int = 0
478
+ self._buffer_glyph_count: int = 0
479
+ self._buffer_upper_count: int = 0
480
+
481
+ def feed_info(self, character: str, info: CharInfo) -> None:
482
+ """Optimized feed using pre-computed character info."""
483
+ if info.alpha:
484
+ self._buffer_length += 1
485
+ self._buffer_last_char = character
486
+
487
+ if info.upper:
488
+ self._buffer_upper_count += 1
489
+
490
+ self._buffer_last_char_accentuated = info.accentuated
491
+
492
+ if info.accentuated:
493
+ self._buffer_accent_count += 1
494
+ if (
495
+ not self._foreign_long_watch
496
+ and (not info.latin or info.accentuated)
497
+ and not info.is_glyph
498
+ ):
499
+ self._foreign_long_watch = True
500
+ if info.is_glyph:
501
+ self._buffer_glyph_count += 1
502
+ return
503
+ if not self._buffer_length:
504
+ return
505
+ if info.space or info.punct or is_separator(character):
506
+ self._word_count += 1
507
+ buffer_length: int = self._buffer_length
508
+
509
+ self._character_count += buffer_length
510
+
511
+ if buffer_length >= 4:
512
+ if self._buffer_accent_count / buffer_length >= 0.5:
513
+ self._is_current_word_bad = True
514
+ elif (
515
+ self._buffer_last_char_accentuated
516
+ and self._buffer_last_char.isupper() # type: ignore[union-attr]
517
+ and self._buffer_upper_count != buffer_length
518
+ ):
519
+ self._foreign_long_count += 1
520
+ self._is_current_word_bad = True
521
+ elif self._buffer_glyph_count == 1:
522
+ self._is_current_word_bad = True
523
+ self._foreign_long_count += 1
524
+ if buffer_length >= 24 and self._foreign_long_watch:
525
+ probable_camel_cased: bool = (
526
+ self._buffer_upper_count > 0
527
+ and self._buffer_upper_count / buffer_length <= 0.3
528
+ )
529
+
530
+ if not probable_camel_cased:
531
+ self._foreign_long_count += 1
532
+ self._is_current_word_bad = True
533
+
534
+ if self._is_current_word_bad:
535
+ self._bad_word_count += 1
536
+ self._bad_character_count += buffer_length
537
+ self._is_current_word_bad = False
538
+
539
+ self._foreign_long_watch = False
540
+ self._buffer_length = 0
541
+ self._buffer_last_char = None
542
+ self._buffer_last_char_accentuated = False
543
+ self._buffer_accent_count = 0
544
+ self._buffer_glyph_count = 0
545
+ self._buffer_upper_count = 0
546
+ elif (
547
+ character not in {"<", ">", "-", "=", "~", "|", "_"}
548
+ and not info.digit
549
+ and info.sym
550
+ ):
551
+ self._is_current_word_bad = True
552
+ self._buffer_length += 1
553
+ self._buffer_last_char = character
554
+ self._buffer_last_char_accentuated = False
555
+
556
+ def reset(self) -> None: # Abstract
557
+ self._buffer_length = 0
558
+ self._buffer_last_char = None
559
+ self._buffer_last_char_accentuated = False
560
+ self._is_current_word_bad = False
561
+ self._foreign_long_watch = False
562
+ self._bad_word_count = 0
563
+ self._word_count = 0
564
+ self._character_count = 0
565
+ self._bad_character_count = 0
566
+ self._foreign_long_count = 0
567
+ self._buffer_accent_count = 0
568
+ self._buffer_glyph_count = 0
569
+ self._buffer_upper_count = 0
570
+
571
+ @property
572
+ def ratio(self) -> float:
573
+ if self._word_count <= 10 and self._foreign_long_count == 0:
574
+ return 0.0
575
+
576
+ return self._bad_character_count / self._character_count
577
+
578
+
579
+ @final
580
+ class CjkUncommonPlugin(MessDetectorPlugin):
581
+ """
582
+ Detect messy CJK text that probably means nothing.
583
+ """
584
+
585
+ __slots__ = ("_character_count", "_uncommon_count")
586
+
587
+ def __init__(self) -> None:
588
+ self._character_count: int = 0
589
+ self._uncommon_count: int = 0
590
+
591
+ def feed_info(self, character: str, info: CharInfo) -> None:
592
+ """Optimized feed using pre-computed character info."""
593
+ self._character_count += 1
594
+
595
+ if character not in COMMON_CJK_CHARACTERS:
596
+ self._uncommon_count += 1
597
+
598
+ def reset(self) -> None: # Abstract
599
+ self._character_count = 0
600
+ self._uncommon_count = 0
601
+
602
+ @property
603
+ def ratio(self) -> float:
604
+ if self._character_count < 8:
605
+ return 0.0
606
+
607
+ uncommon_form_usage: float = self._uncommon_count / self._character_count
608
+
609
+ # we can be pretty sure it's garbage when uncommon characters are widely
610
+ # used. otherwise it could just be traditional chinese for example.
611
+ return uncommon_form_usage / 10 if uncommon_form_usage > 0.5 else 0.0
612
+
613
+
614
+ @final
615
+ class ArchaicUpperLowerPlugin(MessDetectorPlugin):
616
+ __slots__ = (
617
+ "_buf",
618
+ "_character_count_since_last_sep",
619
+ "_successive_upper_lower_count",
620
+ "_successive_upper_lower_count_final",
621
+ "_character_count",
622
+ "_last_alpha_seen",
623
+ "_last_alpha_seen_upper",
624
+ "_last_alpha_seen_lower",
625
+ "_current_ascii_only",
626
+ )
627
+
628
+ def __init__(self) -> None:
629
+ self._buf: bool = False
630
+
631
+ self._character_count_since_last_sep: int = 0
632
+
633
+ self._successive_upper_lower_count: int = 0
634
+ self._successive_upper_lower_count_final: int = 0
635
+
636
+ self._character_count: int = 0
637
+
638
+ self._last_alpha_seen: str | None = None
639
+ self._last_alpha_seen_upper: bool = False
640
+ self._last_alpha_seen_lower: bool = False
641
+ self._current_ascii_only: bool = True
642
+
643
+ def feed_info(self, character: str, info: CharInfo) -> None:
644
+ """Optimized feed using pre-computed character info."""
645
+ is_concerned: bool = info.alpha and info.case_variable
646
+ chunk_sep: bool = not is_concerned
647
+
648
+ if chunk_sep and self._character_count_since_last_sep > 0:
649
+ if (
650
+ self._character_count_since_last_sep <= 64
651
+ and not info.digit
652
+ and not self._current_ascii_only
653
+ ):
654
+ self._successive_upper_lower_count_final += (
655
+ self._successive_upper_lower_count
656
+ )
657
+
658
+ self._successive_upper_lower_count = 0
659
+ self._character_count_since_last_sep = 0
660
+ self._last_alpha_seen = None
661
+ self._buf = False
662
+ self._character_count += 1
663
+ self._current_ascii_only = True
664
+
665
+ return
666
+
667
+ if self._current_ascii_only and not info.is_ascii:
668
+ self._current_ascii_only = False
669
+
670
+ if self._last_alpha_seen is not None:
671
+ if (info.upper and self._last_alpha_seen_lower) or (
672
+ info.lower and self._last_alpha_seen_upper
673
+ ):
674
+ if self._buf:
675
+ self._successive_upper_lower_count += 2
676
+ self._buf = False
677
+ else:
678
+ self._buf = True
679
+ else:
680
+ self._buf = False
681
+
682
+ self._character_count += 1
683
+ self._character_count_since_last_sep += 1
684
+ self._last_alpha_seen = character
685
+ self._last_alpha_seen_upper = info.upper
686
+ self._last_alpha_seen_lower = info.lower
687
+
688
+ def reset(self) -> None: # Abstract
689
+ self._character_count = 0
690
+ self._character_count_since_last_sep = 0
691
+ self._successive_upper_lower_count = 0
692
+ self._successive_upper_lower_count_final = 0
693
+ self._last_alpha_seen = None
694
+ self._last_alpha_seen_upper = False
695
+ self._last_alpha_seen_lower = False
696
+ self._buf = False
697
+ self._current_ascii_only = True
698
+
699
+ @property
700
+ def ratio(self) -> float:
701
+ if self._character_count == 0: # Defensive:
702
+ return 0.0
703
+
704
+ return self._successive_upper_lower_count_final / self._character_count
705
+
706
+
707
+ @final
708
+ class ArabicIsolatedFormPlugin(MessDetectorPlugin):
709
+ __slots__ = ("_character_count", "_isolated_form_count")
710
+
711
+ def __init__(self) -> None:
712
+ self._character_count: int = 0
713
+ self._isolated_form_count: int = 0
714
+
715
+ def reset(self) -> None: # Abstract
716
+ self._character_count = 0
717
+ self._isolated_form_count = 0
718
+
719
+ def feed_info(self, character: str, info: CharInfo) -> None:
720
+ """Optimized feed using pre-computed character info."""
721
+ self._character_count += 1
722
+
723
+ if info.flags & _ARABIC_ISOLATED_FORM:
724
+ self._isolated_form_count += 1
725
+
726
+ @property
727
+ def ratio(self) -> float:
728
+ if self._character_count < 8:
729
+ return 0.0
730
+
731
+ isolated_form_usage: float = self._isolated_form_count / self._character_count
732
+
733
+ return isolated_form_usage
734
+
735
+
736
+ @lru_cache(maxsize=1024)
737
+ def is_suspiciously_successive_range(
738
+ unicode_range_a: str | None, unicode_range_b: str | None
739
+ ) -> bool:
740
+ """
741
+ Determine if two Unicode range seen next to each other can be considered as suspicious.
742
+ """
743
+ if unicode_range_a is None or unicode_range_b is None:
744
+ return True
745
+
746
+ if unicode_range_a == unicode_range_b:
747
+ return False
748
+
749
+ if "Latin" in unicode_range_a and "Latin" in unicode_range_b:
750
+ return False
751
+
752
+ if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b:
753
+ return False
754
+
755
+ # Latin characters can be accompanied with a combining diacritical mark
756
+ # eg. Vietnamese.
757
+ if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and (
758
+ "Combining" in unicode_range_a or "Combining" in unicode_range_b
759
+ ):
760
+ return False
761
+
762
+ keywords_range_a, keywords_range_b = (
763
+ unicode_range_a.split(" "),
764
+ unicode_range_b.split(" "),
765
+ )
766
+
767
+ for el in keywords_range_a:
768
+ if el in UNICODE_SECONDARY_RANGE_KEYWORD:
769
+ continue
770
+ if el in keywords_range_b:
771
+ return False
772
+
773
+ # Japanese Exception
774
+ range_a_jp_chars, range_b_jp_chars = (
775
+ unicode_range_a
776
+ in (
777
+ "Hiragana",
778
+ "Katakana",
779
+ ),
780
+ unicode_range_b in ("Hiragana", "Katakana"),
781
+ )
782
+ if (range_a_jp_chars or range_b_jp_chars) and (
783
+ "CJK" in unicode_range_a or "CJK" in unicode_range_b
784
+ ):
785
+ return False
786
+ if range_a_jp_chars and range_b_jp_chars:
787
+ return False
788
+
789
+ if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b:
790
+ if "CJK" in unicode_range_a or "CJK" in unicode_range_b:
791
+ return False
792
+ if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
793
+ return False
794
+
795
+ # Chinese/Japanese use dedicated range for punctuation and/or separators.
796
+ if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or (
797
+ unicode_range_a in ["Katakana", "Hiragana"]
798
+ and unicode_range_b in ["Katakana", "Hiragana"]
799
+ ):
800
+ if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b:
801
+ return False
802
+ if "Forms" in unicode_range_a or "Forms" in unicode_range_b:
803
+ return False
804
+ if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
805
+ return False
806
+
807
+ return True
808
+
809
+
810
+ @lru_cache(maxsize=2048)
811
+ def mess_ratio(
812
+ decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False
813
+ ) -> float:
814
+ """
815
+ Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier.
816
+ """
817
+
818
+ seq_len: int = len(decoded_sequence)
819
+
820
+ if seq_len < 511:
821
+ step: int = 32
822
+ elif seq_len < 1024:
823
+ step = 64
824
+ else:
825
+ step = 128
826
+
827
+ # Create each detector as a named local variable (unrolled from the generic loop).
828
+ # This eliminates per-character iteration over the detector list and
829
+ # per-character eligible() virtual dispatch, while keeping every plugin class
830
+ # intact and fully readable.
831
+ d_sp: TooManySymbolOrPunctuationPlugin = TooManySymbolOrPunctuationPlugin()
832
+ d_ta: TooManyAccentuatedPlugin = TooManyAccentuatedPlugin()
833
+ d_up: UnprintablePlugin = UnprintablePlugin()
834
+ d_sda: SuspiciousDuplicateAccentPlugin = SuspiciousDuplicateAccentPlugin()
835
+ d_sr: SuspiciousRange = SuspiciousRange()
836
+ d_sw: SuperWeirdWordPlugin = SuperWeirdWordPlugin()
837
+ d_cu: CjkUncommonPlugin = CjkUncommonPlugin()
838
+ d_au: ArchaicUpperLowerPlugin = ArchaicUpperLowerPlugin()
839
+ d_ai: ArabicIsolatedFormPlugin = ArabicIsolatedFormPlugin()
840
+
841
+ # Local references for feed_info methods called in the hot loop.
842
+ d_sp_feed = d_sp.feed_info
843
+ d_ta_feed = d_ta.feed_info
844
+ d_up_feed = d_up.feed_info
845
+ d_sda_feed = d_sda.feed_info
846
+ d_sr_feed = d_sr.feed_info
847
+ d_sw_feed = d_sw.feed_info
848
+ d_cu_feed = d_cu.feed_info
849
+ d_au_feed = d_au.feed_info
850
+ d_ai_feed = d_ai.feed_info
851
+
852
+ # Single reusable CharInfo object (avoids per-character allocation).
853
+ info: CharInfo = CharInfo()
854
+ info_update = info.update
855
+
856
+ mean_mess_ratio: float
857
+
858
+ for block_start in range(0, seq_len, step):
859
+ for character in decoded_sequence[block_start : block_start + step]:
860
+ # Pre-compute all character properties once (shared across all plugins).
861
+ info_update(character)
862
+
863
+ # Detectors with eligible() == always True
864
+ d_up_feed(character, info)
865
+ d_sw_feed(character, info)
866
+ d_au_feed(character, info)
867
+
868
+ # Detectors with eligible() == isprintable
869
+ if info.printable:
870
+ d_sp_feed(character, info)
871
+ d_sr_feed(character, info)
872
+
873
+ # Detectors with eligible() == isalpha
874
+ if info.alpha:
875
+ d_ta_feed(character, info)
876
+ # SuspiciousDuplicateAccent: isalpha() and is_latin()
877
+ if info.latin:
878
+ d_sda_feed(character, info)
879
+ # CjkUncommon: is_cjk()
880
+ if info.is_cjk:
881
+ d_cu_feed(character, info)
882
+ # ArabicIsolatedForm: is_arabic()
883
+ if info.is_arabic:
884
+ d_ai_feed(character, info)
885
+
886
+ mean_mess_ratio = (
887
+ d_sp.ratio
888
+ + d_ta.ratio
889
+ + d_up.ratio
890
+ + d_sda.ratio
891
+ + d_sr.ratio
892
+ + d_sw.ratio
893
+ + d_cu.ratio
894
+ + d_au.ratio
895
+ + d_ai.ratio
896
+ )
897
+
898
+ if mean_mess_ratio >= maximum_threshold:
899
+ break
900
+ else:
901
+ # Flush last word buffer in SuperWeirdWordPlugin via trailing newline.
902
+ info_update("\n")
903
+ d_sw_feed("\n", info)
904
+ d_au_feed("\n", info)
905
+ d_up_feed("\n", info)
906
+
907
+ mean_mess_ratio = (
908
+ d_sp.ratio
909
+ + d_ta.ratio
910
+ + d_up.ratio
911
+ + d_sda.ratio
912
+ + d_sr.ratio
913
+ + d_sw.ratio
914
+ + d_cu.ratio
915
+ + d_au.ratio
916
+ + d_ai.ratio
917
+ )
918
+
919
+ if debug: # Defensive:
920
+ logger = getLogger("charset_normalizer")
921
+
922
+ logger.log(
923
+ TRACE,
924
+ "Mess-detector extended-analysis start. "
925
+ f"intermediary_mean_mess_ratio_calc={step} mean_mess_ratio={mean_mess_ratio} "
926
+ f"maximum_threshold={maximum_threshold}",
927
+ )
928
+
929
+ if seq_len > 16:
930
+ logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}")
931
+ logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}")
932
+
933
+ for dt in [d_sp, d_ta, d_up, d_sda, d_sr, d_sw, d_cu, d_au, d_ai]:
934
+ logger.log(TRACE, f"{dt.__class__}: {dt.ratio}")
935
+
936
+ return round(mean_mess_ratio, 3)
.venv/lib/python3.11/site-packages/charset_normalizer/models.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from encodings.aliases import aliases
4
+ from json import dumps
5
+ from re import sub
6
+ from typing import Any, Iterator, List, Tuple
7
+
8
+ from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE
9
+ from .utils import iana_name, is_multi_byte_encoding, unicode_range
10
+
11
+
12
+ class CharsetMatch:
13
+ def __init__(
14
+ self,
15
+ payload: bytes | bytearray,
16
+ guessed_encoding: str,
17
+ mean_mess_ratio: float,
18
+ has_sig_or_bom: bool,
19
+ languages: CoherenceMatches,
20
+ decoded_payload: str | None = None,
21
+ preemptive_declaration: str | None = None,
22
+ ):
23
+ self._payload: bytes | bytearray = payload
24
+
25
+ self._encoding: str = guessed_encoding
26
+ self._mean_mess_ratio: float = mean_mess_ratio
27
+ self._languages: CoherenceMatches = languages
28
+ self._has_sig_or_bom: bool = has_sig_or_bom
29
+ self._unicode_ranges: list[str] | None = None
30
+
31
+ self._leaves: list[CharsetMatch] = []
32
+ self._mean_coherence_ratio: float = 0.0
33
+
34
+ self._output_payload: bytes | None = None
35
+ self._output_encoding: str | None = None
36
+
37
+ self._string: str | None = decoded_payload
38
+
39
+ self._preemptive_declaration: str | None = preemptive_declaration
40
+
41
+ def __eq__(self, other: object) -> bool:
42
+ if not isinstance(other, CharsetMatch):
43
+ if isinstance(other, str):
44
+ return iana_name(other) == self.encoding
45
+ return False
46
+ return self.encoding == other.encoding and self.fingerprint == other.fingerprint
47
+
48
+ def __lt__(self, other: object) -> bool:
49
+ """
50
+ Implemented to make sorted available upon CharsetMatches items.
51
+ """
52
+ if not isinstance(other, CharsetMatch):
53
+ raise ValueError
54
+
55
+ chaos_difference: float = abs(self.chaos - other.chaos)
56
+ coherence_difference: float = abs(self.coherence - other.coherence)
57
+
58
+ # Below 0.5% difference --> Use Coherence
59
+ if chaos_difference < 0.005 and coherence_difference > 0.02:
60
+ return self.coherence > other.coherence
61
+ elif chaos_difference < 0.005 and coherence_difference <= 0.02:
62
+ # When having a difficult decision, use the result that decoded as many multi-byte as possible.
63
+ # preserve RAM usage!
64
+ if len(self._payload) >= TOO_BIG_SEQUENCE:
65
+ return self.chaos < other.chaos
66
+ return self.multi_byte_usage > other.multi_byte_usage
67
+
68
+ return self.chaos < other.chaos
69
+
70
+ @property
71
+ def multi_byte_usage(self) -> float:
72
+ return 1.0 - (len(str(self)) / len(self.raw))
73
+
74
+ def __str__(self) -> str:
75
+ # Lazy Str Loading
76
+ if self._string is None:
77
+ self._string = str(self._payload, self._encoding, "strict")
78
+ # UTF-7 BOM is encoded in modified Base64 whose byte boundary
79
+ # can overlap with the next character, so raw-byte stripping
80
+ # is unreliable. Strip the decoded BOM character instead.
81
+ if (
82
+ self._has_sig_or_bom
83
+ and self._encoding == "utf_7"
84
+ and self._string
85
+ and self._string[0] == "\ufeff"
86
+ ):
87
+ self._string = self._string[1:]
88
+ return self._string
89
+
90
+ def __repr__(self) -> str:
91
+ return f"<CharsetMatch '{self.encoding}' fp({self.fingerprint})>"
92
+
93
+ def add_submatch(self, other: CharsetMatch) -> None:
94
+ if not isinstance(other, CharsetMatch) or other == self:
95
+ raise ValueError(
96
+ "Unable to add instance <{}> as a submatch of a CharsetMatch".format(
97
+ other.__class__
98
+ )
99
+ )
100
+
101
+ other._string = None # Unload RAM usage; dirty trick.
102
+ self._leaves.append(other)
103
+
104
+ @property
105
+ def encoding(self) -> str:
106
+ return self._encoding
107
+
108
+ @property
109
+ def encoding_aliases(self) -> list[str]:
110
+ """
111
+ Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855.
112
+ """
113
+ also_known_as: list[str] = []
114
+ for u, p in aliases.items():
115
+ if self.encoding == u:
116
+ also_known_as.append(p)
117
+ elif self.encoding == p:
118
+ also_known_as.append(u)
119
+ return also_known_as
120
+
121
+ @property
122
+ def bom(self) -> bool:
123
+ return self._has_sig_or_bom
124
+
125
+ @property
126
+ def byte_order_mark(self) -> bool:
127
+ return self._has_sig_or_bom
128
+
129
+ @property
130
+ def languages(self) -> list[str]:
131
+ """
132
+ Return the complete list of possible languages found in decoded sequence.
133
+ Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'.
134
+ """
135
+ return [e[0] for e in self._languages]
136
+
137
+ @property
138
+ def language(self) -> str:
139
+ """
140
+ Most probable language found in decoded sequence. If none were detected or inferred, the property will return
141
+ "Unknown".
142
+ """
143
+ if not self._languages:
144
+ # Trying to infer the language based on the given encoding
145
+ # Its either English or we should not pronounce ourselves in certain cases.
146
+ if "ascii" in self.could_be_from_charset:
147
+ return "English"
148
+
149
+ # doing it there to avoid circular import
150
+ from charset_normalizer.cd import encoding_languages, mb_encoding_languages
151
+
152
+ languages = (
153
+ mb_encoding_languages(self.encoding)
154
+ if is_multi_byte_encoding(self.encoding)
155
+ else encoding_languages(self.encoding)
156
+ )
157
+
158
+ if len(languages) == 0 or "Latin Based" in languages:
159
+ return "Unknown"
160
+
161
+ return languages[0]
162
+
163
+ return self._languages[0][0]
164
+
165
+ @property
166
+ def chaos(self) -> float:
167
+ return self._mean_mess_ratio
168
+
169
+ @property
170
+ def coherence(self) -> float:
171
+ if not self._languages:
172
+ return 0.0
173
+ return self._languages[0][1]
174
+
175
+ @property
176
+ def percent_chaos(self) -> float:
177
+ return round(self.chaos * 100, ndigits=3)
178
+
179
+ @property
180
+ def percent_coherence(self) -> float:
181
+ return round(self.coherence * 100, ndigits=3)
182
+
183
+ @property
184
+ def raw(self) -> bytes | bytearray:
185
+ """
186
+ Original untouched bytes.
187
+ """
188
+ return self._payload
189
+
190
+ @property
191
+ def submatch(self) -> list[CharsetMatch]:
192
+ return self._leaves
193
+
194
+ @property
195
+ def has_submatch(self) -> bool:
196
+ return len(self._leaves) > 0
197
+
198
+ @property
199
+ def alphabets(self) -> list[str]:
200
+ if self._unicode_ranges is not None:
201
+ return self._unicode_ranges
202
+ # list detected ranges
203
+ detected_ranges: list[str | None] = [unicode_range(char) for char in str(self)]
204
+ # filter and sort
205
+ self._unicode_ranges = sorted(list({r for r in detected_ranges if r}))
206
+ return self._unicode_ranges
207
+
208
+ @property
209
+ def could_be_from_charset(self) -> list[str]:
210
+ """
211
+ The complete list of encoding that output the exact SAME str result and therefore could be the originating
212
+ encoding.
213
+ This list does include the encoding available in property 'encoding'.
214
+ """
215
+ return [self._encoding] + [m.encoding for m in self._leaves]
216
+
217
+ def output(self, encoding: str = "utf_8") -> bytes:
218
+ """
219
+ Method to get re-encoded bytes payload using given target encoding. Default to UTF-8.
220
+ Any errors will be simply ignored by the encoder NOT replaced.
221
+ """
222
+ if self._output_encoding is None or self._output_encoding != encoding:
223
+ self._output_encoding = encoding
224
+ decoded_string = str(self)
225
+ if (
226
+ self._preemptive_declaration is not None
227
+ and self._preemptive_declaration.lower()
228
+ not in ["utf-8", "utf8", "utf_8"]
229
+ ):
230
+ patched_header = sub(
231
+ RE_POSSIBLE_ENCODING_INDICATION,
232
+ lambda m: m.string[m.span()[0] : m.span()[1]].replace(
233
+ m.groups()[0],
234
+ iana_name(self._output_encoding).replace("_", "-"), # type: ignore[arg-type]
235
+ ),
236
+ decoded_string[:8192],
237
+ count=1,
238
+ )
239
+
240
+ decoded_string = patched_header + decoded_string[8192:]
241
+
242
+ self._output_payload = decoded_string.encode(encoding, "replace")
243
+
244
+ return self._output_payload # type: ignore
245
+
246
+ @property
247
+ def fingerprint(self) -> int:
248
+ """
249
+ Retrieve a hash fingerprint of the decoded payload, used for deduplication.
250
+ """
251
+ return hash(str(self))
252
+
253
+
254
+ class CharsetMatches:
255
+ """
256
+ Container with every CharsetMatch items ordered by default from most probable to the less one.
257
+ Act like a list(iterable) but does not implements all related methods.
258
+ """
259
+
260
+ def __init__(self, results: list[CharsetMatch] | None = None):
261
+ self._results: list[CharsetMatch] = sorted(results) if results else []
262
+
263
+ def __iter__(self) -> Iterator[CharsetMatch]:
264
+ yield from self._results
265
+
266
+ def __getitem__(self, item: int | str) -> CharsetMatch:
267
+ """
268
+ Retrieve a single item either by its position or encoding name (alias may be used here).
269
+ Raise KeyError upon invalid index or encoding not present in results.
270
+ """
271
+ if isinstance(item, int):
272
+ return self._results[item]
273
+ if isinstance(item, str):
274
+ item = iana_name(item, False)
275
+ for result in self._results:
276
+ if item in result.could_be_from_charset:
277
+ return result
278
+ raise KeyError
279
+
280
+ def __len__(self) -> int:
281
+ return len(self._results)
282
+
283
+ def __bool__(self) -> bool:
284
+ return len(self._results) > 0
285
+
286
+ def append(self, item: CharsetMatch) -> None:
287
+ """
288
+ Insert a single match. Will be inserted accordingly to preserve sort.
289
+ Can be inserted as a submatch.
290
+ """
291
+ if not isinstance(item, CharsetMatch):
292
+ raise ValueError(
293
+ "Cannot append instance '{}' to CharsetMatches".format(
294
+ str(item.__class__)
295
+ )
296
+ )
297
+ # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage)
298
+ if len(item.raw) < TOO_BIG_SEQUENCE:
299
+ for match in self._results:
300
+ if match.fingerprint == item.fingerprint and match.chaos == item.chaos:
301
+ match.add_submatch(item)
302
+ return
303
+ self._results.append(item)
304
+ self._results = sorted(self._results)
305
+
306
+ def best(self) -> CharsetMatch | None:
307
+ """
308
+ Simply return the first match. Strict equivalent to matches[0].
309
+ """
310
+ if not self._results:
311
+ return None
312
+ return self._results[0]
313
+
314
+ def first(self) -> CharsetMatch | None:
315
+ """
316
+ Redundant method, call the method best(). Kept for BC reasons.
317
+ """
318
+ return self.best()
319
+
320
+
321
+ CoherenceMatch = Tuple[str, float]
322
+ CoherenceMatches = List[CoherenceMatch]
323
+
324
+
325
+ class CliDetectionResult:
326
+ def __init__(
327
+ self,
328
+ path: str,
329
+ encoding: str | None,
330
+ encoding_aliases: list[str],
331
+ alternative_encodings: list[str],
332
+ language: str,
333
+ alphabets: list[str],
334
+ has_sig_or_bom: bool,
335
+ chaos: float,
336
+ coherence: float,
337
+ unicode_path: str | None,
338
+ is_preferred: bool,
339
+ ):
340
+ self.path: str = path
341
+ self.unicode_path: str | None = unicode_path
342
+ self.encoding: str | None = encoding
343
+ self.encoding_aliases: list[str] = encoding_aliases
344
+ self.alternative_encodings: list[str] = alternative_encodings
345
+ self.language: str = language
346
+ self.alphabets: list[str] = alphabets
347
+ self.has_sig_or_bom: bool = has_sig_or_bom
348
+ self.chaos: float = chaos
349
+ self.coherence: float = coherence
350
+ self.is_preferred: bool = is_preferred
351
+
352
+ @property
353
+ def __dict__(self) -> dict[str, Any]: # type: ignore
354
+ return {
355
+ "path": self.path,
356
+ "encoding": self.encoding,
357
+ "encoding_aliases": self.encoding_aliases,
358
+ "alternative_encodings": self.alternative_encodings,
359
+ "language": self.language,
360
+ "alphabets": self.alphabets,
361
+ "has_sig_or_bom": self.has_sig_or_bom,
362
+ "chaos": self.chaos,
363
+ "coherence": self.coherence,
364
+ "unicode_path": self.unicode_path,
365
+ "is_preferred": self.is_preferred,
366
+ }
367
+
368
+ def to_json(self) -> str:
369
+ return dumps(self.__dict__, ensure_ascii=True, indent=4)
.venv/lib/python3.11/site-packages/charset_normalizer/py.typed ADDED
File without changes
.venv/lib/python3.11/site-packages/charset_normalizer/utils.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import logging
5
+ import unicodedata
6
+ from bisect import bisect_right
7
+ from codecs import IncrementalDecoder
8
+ from encodings.aliases import aliases
9
+ from functools import lru_cache
10
+ from re import findall
11
+ from typing import Generator
12
+
13
+ from _multibytecodec import ( # type: ignore[import-not-found,import]
14
+ MultibyteIncrementalDecoder,
15
+ )
16
+
17
+ from .constant import (
18
+ ENCODING_MARKS,
19
+ IANA_SUPPORTED_SIMILAR,
20
+ RE_POSSIBLE_ENCODING_INDICATION,
21
+ UNICODE_RANGES_COMBINED,
22
+ UNICODE_SECONDARY_RANGE_KEYWORD,
23
+ UTF8_MAXIMAL_ALLOCATION,
24
+ COMMON_CJK_CHARACTERS,
25
+ _LATIN,
26
+ _CJK,
27
+ _HANGUL,
28
+ _KATAKANA,
29
+ _HIRAGANA,
30
+ _THAI,
31
+ _ARABIC,
32
+ _ARABIC_ISOLATED_FORM,
33
+ _ACCENT_KEYWORDS,
34
+ _ACCENTUATED,
35
+ )
36
+
37
+
38
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
39
+ def _character_flags(character: str) -> int:
40
+ """Compute all name-based classification flags with a single unicodedata.name() call."""
41
+ try:
42
+ desc: str = unicodedata.name(character)
43
+ except ValueError:
44
+ return 0
45
+
46
+ flags: int = 0
47
+
48
+ if "LATIN" in desc:
49
+ flags |= _LATIN
50
+ if "CJK" in desc:
51
+ flags |= _CJK
52
+ if "HANGUL" in desc:
53
+ flags |= _HANGUL
54
+ if "KATAKANA" in desc:
55
+ flags |= _KATAKANA
56
+ if "HIRAGANA" in desc:
57
+ flags |= _HIRAGANA
58
+ if "THAI" in desc:
59
+ flags |= _THAI
60
+ if "ARABIC" in desc:
61
+ flags |= _ARABIC
62
+ if "ISOLATED FORM" in desc:
63
+ flags |= _ARABIC_ISOLATED_FORM
64
+
65
+ for kw in _ACCENT_KEYWORDS:
66
+ if kw in desc:
67
+ flags |= _ACCENTUATED
68
+ break
69
+
70
+ return flags
71
+
72
+
73
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
74
+ def is_accentuated(character: str) -> bool:
75
+ return bool(_character_flags(character) & _ACCENTUATED)
76
+
77
+
78
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
79
+ def remove_accent(character: str) -> str:
80
+ decomposed: str = unicodedata.decomposition(character)
81
+ if not decomposed:
82
+ return character
83
+
84
+ codes: list[str] = decomposed.split(" ")
85
+
86
+ return chr(int(codes[0], 16))
87
+
88
+
89
+ # Pre-built sorted lookup table for O(log n) binary search in unicode_range().
90
+ # Each entry is (range_start, range_end_exclusive, range_name).
91
+ _UNICODE_RANGES_SORTED: list[tuple[int, int, str]] = sorted(
92
+ (ord_range.start, ord_range.stop, name)
93
+ for name, ord_range in UNICODE_RANGES_COMBINED.items()
94
+ )
95
+ _UNICODE_RANGE_STARTS: list[int] = [e[0] for e in _UNICODE_RANGES_SORTED]
96
+
97
+
98
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
99
+ def unicode_range(character: str) -> str | None:
100
+ """
101
+ Retrieve the Unicode range official name from a single character.
102
+ """
103
+ character_ord: int = ord(character)
104
+
105
+ # Binary search: find the rightmost range whose start <= character_ord
106
+ idx = bisect_right(_UNICODE_RANGE_STARTS, character_ord) - 1
107
+ if idx >= 0:
108
+ start, stop, name = _UNICODE_RANGES_SORTED[idx]
109
+ if character_ord < stop:
110
+ return name
111
+
112
+ return None
113
+
114
+
115
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
116
+ def is_latin(character: str) -> bool:
117
+ return bool(_character_flags(character) & _LATIN)
118
+
119
+
120
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
121
+ def is_punctuation(character: str) -> bool:
122
+ character_category: str = unicodedata.category(character)
123
+
124
+ if "P" in character_category:
125
+ return True
126
+
127
+ character_range: str | None = unicode_range(character)
128
+
129
+ if character_range is None:
130
+ return False
131
+
132
+ return "Punctuation" in character_range
133
+
134
+
135
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
136
+ def is_symbol(character: str) -> bool:
137
+ character_category: str = unicodedata.category(character)
138
+
139
+ if "S" in character_category or "N" in character_category:
140
+ return True
141
+
142
+ character_range: str | None = unicode_range(character)
143
+
144
+ if character_range is None:
145
+ return False
146
+
147
+ return "Forms" in character_range and character_category != "Lo"
148
+
149
+
150
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
151
+ def is_emoticon(character: str) -> bool:
152
+ character_range: str | None = unicode_range(character)
153
+
154
+ if character_range is None:
155
+ return False
156
+
157
+ return "Emoticons" in character_range or "Pictographs" in character_range
158
+
159
+
160
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
161
+ def is_separator(character: str) -> bool:
162
+ if character.isspace() or character in {"|", "+", "<", ">"}:
163
+ return True
164
+
165
+ character_category: str = unicodedata.category(character)
166
+
167
+ return "Z" in character_category or character_category in {"Po", "Pd", "Pc"}
168
+
169
+
170
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
171
+ def is_case_variable(character: str) -> bool:
172
+ return character.islower() != character.isupper()
173
+
174
+
175
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
176
+ def is_cjk(character: str) -> bool:
177
+ return bool(_character_flags(character) & _CJK)
178
+
179
+
180
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
181
+ def is_hiragana(character: str) -> bool:
182
+ return bool(_character_flags(character) & _HIRAGANA)
183
+
184
+
185
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
186
+ def is_katakana(character: str) -> bool:
187
+ return bool(_character_flags(character) & _KATAKANA)
188
+
189
+
190
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
191
+ def is_hangul(character: str) -> bool:
192
+ return bool(_character_flags(character) & _HANGUL)
193
+
194
+
195
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
196
+ def is_thai(character: str) -> bool:
197
+ return bool(_character_flags(character) & _THAI)
198
+
199
+
200
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
201
+ def is_arabic(character: str) -> bool:
202
+ return bool(_character_flags(character) & _ARABIC)
203
+
204
+
205
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
206
+ def is_arabic_isolated_form(character: str) -> bool:
207
+ return bool(_character_flags(character) & _ARABIC_ISOLATED_FORM)
208
+
209
+
210
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
211
+ def is_cjk_uncommon(character: str) -> bool:
212
+ return character not in COMMON_CJK_CHARACTERS
213
+
214
+
215
+ @lru_cache(maxsize=len(UNICODE_RANGES_COMBINED))
216
+ def is_unicode_range_secondary(range_name: str) -> bool:
217
+ return any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD)
218
+
219
+
220
+ @lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)
221
+ def is_unprintable(character: str) -> bool:
222
+ return (
223
+ character.isspace() is False # includes \n \t \r \v
224
+ and character.isprintable() is False
225
+ and character != "\x1a" # Why? Its the ASCII substitute character.
226
+ and character != "\ufeff" # bug discovered in Python,
227
+ # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space.
228
+ )
229
+
230
+
231
+ def any_specified_encoding(
232
+ sequence: bytes | bytearray, search_zone: int = 8192
233
+ ) -> str | None:
234
+ """
235
+ Extract using ASCII-only decoder any specified encoding in the first n-bytes.
236
+ """
237
+ if not isinstance(sequence, (bytes, bytearray)):
238
+ raise TypeError
239
+
240
+ seq_len: int = len(sequence)
241
+
242
+ results: list[str] = findall(
243
+ RE_POSSIBLE_ENCODING_INDICATION,
244
+ sequence[: min(seq_len, search_zone)].decode("ascii", errors="ignore"),
245
+ )
246
+
247
+ if len(results) == 0:
248
+ return None
249
+
250
+ for specified_encoding in results:
251
+ specified_encoding = specified_encoding.lower().replace("-", "_")
252
+
253
+ encoding_alias: str
254
+ encoding_iana: str
255
+
256
+ for encoding_alias, encoding_iana in aliases.items():
257
+ if encoding_alias == specified_encoding:
258
+ return encoding_iana
259
+ if encoding_iana == specified_encoding:
260
+ return encoding_iana
261
+
262
+ return None
263
+
264
+
265
+ @lru_cache(maxsize=128)
266
+ def is_multi_byte_encoding(name: str) -> bool:
267
+ """
268
+ Verify is a specific encoding is a multi byte one based on it IANA name
269
+ """
270
+ return name in {
271
+ "utf_8",
272
+ "utf_8_sig",
273
+ "utf_16",
274
+ "utf_16_be",
275
+ "utf_16_le",
276
+ "utf_32",
277
+ "utf_32_le",
278
+ "utf_32_be",
279
+ "utf_7",
280
+ } or issubclass(
281
+ importlib.import_module(f"encodings.{name}").IncrementalDecoder,
282
+ MultibyteIncrementalDecoder,
283
+ )
284
+
285
+
286
+ def identify_sig_or_bom(sequence: bytes | bytearray) -> tuple[str | None, bytes]:
287
+ """
288
+ Identify and extract SIG/BOM in given sequence.
289
+ """
290
+
291
+ for iana_encoding in ENCODING_MARKS:
292
+ marks: bytes | list[bytes] = ENCODING_MARKS[iana_encoding]
293
+
294
+ if isinstance(marks, bytes):
295
+ marks = [marks]
296
+
297
+ for mark in marks:
298
+ if sequence.startswith(mark):
299
+ return iana_encoding, mark
300
+
301
+ return None, b""
302
+
303
+
304
+ def should_strip_sig_or_bom(iana_encoding: str) -> bool:
305
+ return iana_encoding not in {"utf_16", "utf_32"}
306
+
307
+
308
+ def iana_name(cp_name: str, strict: bool = True) -> str:
309
+ """Returns the Python normalized encoding name (Not the IANA official name)."""
310
+ cp_name = cp_name.lower().replace("-", "_")
311
+
312
+ encoding_alias: str
313
+ encoding_iana: str
314
+
315
+ for encoding_alias, encoding_iana in aliases.items():
316
+ if cp_name in [encoding_alias, encoding_iana]:
317
+ return encoding_iana
318
+
319
+ if strict:
320
+ raise ValueError(f"Unable to retrieve IANA for '{cp_name}'")
321
+
322
+ return cp_name
323
+
324
+
325
+ def cp_similarity(iana_name_a: str, iana_name_b: str) -> float:
326
+ if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b):
327
+ return 0.0
328
+
329
+ decoder_a = importlib.import_module(f"encodings.{iana_name_a}").IncrementalDecoder
330
+ decoder_b = importlib.import_module(f"encodings.{iana_name_b}").IncrementalDecoder
331
+
332
+ id_a: IncrementalDecoder = decoder_a(errors="ignore")
333
+ id_b: IncrementalDecoder = decoder_b(errors="ignore")
334
+
335
+ character_match_count: int = 0
336
+
337
+ for i in range(256):
338
+ to_be_decoded: bytes = bytes([i])
339
+ if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded):
340
+ character_match_count += 1
341
+
342
+ return character_match_count / 256
343
+
344
+
345
+ def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool:
346
+ """
347
+ Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using
348
+ the function cp_similarity.
349
+ """
350
+ return (
351
+ iana_name_a in IANA_SUPPORTED_SIMILAR
352
+ and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a]
353
+ )
354
+
355
+
356
+ def set_logging_handler(
357
+ name: str = "charset_normalizer",
358
+ level: int = logging.INFO,
359
+ format_string: str = "%(asctime)s | %(levelname)s | %(message)s",
360
+ ) -> None:
361
+ logger = logging.getLogger(name)
362
+ logger.setLevel(level)
363
+
364
+ handler = logging.StreamHandler()
365
+ handler.setFormatter(logging.Formatter(format_string))
366
+ logger.addHandler(handler)
367
+
368
+
369
+ def cut_sequence_chunks(
370
+ sequences: bytes | bytearray,
371
+ encoding_iana: str,
372
+ offsets: range,
373
+ chunk_size: int,
374
+ bom_or_sig_available: bool,
375
+ strip_sig_or_bom: bool,
376
+ sig_payload: bytes,
377
+ is_multi_byte_decoder: bool,
378
+ decoded_payload: str | None = None,
379
+ ) -> Generator[str, None, None]:
380
+ if decoded_payload and is_multi_byte_decoder is False:
381
+ for i in offsets:
382
+ chunk = decoded_payload[i : i + chunk_size]
383
+ if not chunk:
384
+ break
385
+ yield chunk
386
+ else:
387
+ for i in offsets:
388
+ chunk_end = i + chunk_size
389
+ if chunk_end > len(sequences) + 8:
390
+ continue
391
+
392
+ cut_sequence = sequences[i : i + chunk_size]
393
+
394
+ if bom_or_sig_available and strip_sig_or_bom is False:
395
+ cut_sequence = sig_payload + cut_sequence
396
+
397
+ chunk = cut_sequence.decode(
398
+ encoding_iana,
399
+ errors="ignore" if is_multi_byte_decoder else "strict",
400
+ )
401
+
402
+ # multi-byte bad cutting detector and adjustment
403
+ # not the cleanest way to perform that fix but clever enough for now.
404
+ if is_multi_byte_decoder and i > 0:
405
+ chunk_partial_size_chk: int = min(chunk_size, 16)
406
+
407
+ if (
408
+ decoded_payload
409
+ and chunk[:chunk_partial_size_chk] not in decoded_payload
410
+ ):
411
+ for j in range(i, i - 4, -1):
412
+ cut_sequence = sequences[j:chunk_end]
413
+
414
+ if bom_or_sig_available and strip_sig_or_bom is False:
415
+ cut_sequence = sig_payload + cut_sequence
416
+
417
+ chunk = cut_sequence.decode(encoding_iana, errors="ignore")
418
+
419
+ if chunk[:chunk_partial_size_chk] in decoded_payload:
420
+ break
421
+
422
+ yield chunk
.venv/lib/python3.11/site-packages/charset_normalizer/version.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Expose version
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ __version__ = "3.4.7"
8
+ VERSION = __version__.split(".")
.venv/lib/python3.11/site-packages/package_readme.md ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <img src="https://i.imgur.com/dQLeGCc.png" width="600" /><br><br>
3
+ </div>
4
+
5
+ <p align="center">
6
+ <a href="https://pypi.python.org/pypi/wandb"><img src="https://img.shields.io/pypi/v/wandb" /></a>
7
+ <a href="https://anaconda.org/conda-forge/wandb"><img src="https://img.shields.io/conda/vn/conda-forge/wandb" /></a>
8
+ <a href="https://pypi.python.org/pypi/wandb"><img src="https://img.shields.io/pypi/pyversions/wandb" /></a>
9
+ <a href="https://circleci.com/gh/wandb/wandb"><img src="https://img.shields.io/circleci/build/github/wandb/wandb/main" /></a>
10
+ <a href="https://codecov.io/gh/wandb/wandb"><img src="https://img.shields.io/codecov/c/gh/wandb/wandb" /></a>
11
+ </p>
12
+ <p align='center'>
13
+ <a href="https://colab.research.google.com/github/wandb/examples/blob/master/colabs/intro/Intro_to_Weights_%26_Biases.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" /></a>
14
+ </p>
15
+
16
+ Use W&B to build better models faster. Track and visualize all the pieces of your machine learning pipeline, from datasets to production machine learning models. Get started with W&B today, [sign up for a W&B account](https://wandb.com?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=readme)!
17
+
18
+ <br>
19
+
20
+ Building an LLM app? Track, debug, evaluate, and monitor LLM apps with [Weave](https://wandb.github.io/weave?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=readme), our new suite of tools for GenAI.
21
+
22
+ &nbsp;
23
+
24
+ # Documentation
25
+
26
+ See the [W&B Developer Guide](https://docs.wandb.ai?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=documentation) and [API Reference Guide](https://docs.wandb.ai/training/api-reference#api-overview?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=documentation) for a full technical description of the W&B platform.
27
+
28
+ &nbsp;
29
+
30
+ # Quickstart
31
+
32
+ Install W&B to track, visualize, and manage machine learning experiments of any size.
33
+
34
+ ## Install the wandb library
35
+
36
+ ```shell
37
+ pip install wandb
38
+ ```
39
+
40
+ ## Sign up and create an API key
41
+
42
+ Sign up for a [W&B account](https://wandb.ai/login?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=quickstart). Optionally, use the `wandb login` CLI to configure an API key on your machine. You can skip this step -- W&B will prompt you for an API key the first time you use it.
43
+
44
+ ## Create a machine learning training experiment
45
+
46
+ In your Python script or notebook, initialize a W&B run with `wandb.init()`.
47
+ Specify hyperparameters and log metrics and other information to W&B.
48
+
49
+ ```python
50
+ import wandb
51
+
52
+ # Project that the run is recorded to
53
+ project = "my-awesome-project"
54
+
55
+ # Dictionary with hyperparameters
56
+ config = {"epochs" : 1337, "lr" : 3e-4}
57
+
58
+ # The `with` syntax marks the run as finished upon exiting the `with` block,
59
+ # and it marks the run "failed" if there's an exception.
60
+ #
61
+ # In a notebook, it may be more convenient to write `run = wandb.init()`
62
+ # and manually call `run.finish()` instead of using a `with` block.
63
+ with wandb.init(project=project, config=config) as run:
64
+ # Training code here
65
+
66
+ # Log values to W&B with run.log()
67
+ run.log({"accuracy": 0.9, "loss": 0.1})
68
+ ```
69
+
70
+ Visit [wandb.ai/home](https://wandb.ai/home) to view recorded metrics such as accuracy and loss and how they changed during each training step. Each run object appears in the Runs column with generated names.
71
+
72
+ &nbsp;
73
+
74
+ # Integrations
75
+
76
+ W&B [integrates](https://docs.wandb.ai/models/integrations) with popular ML frameworks and libraries making it fast and easy to set up experiment tracking and data versioning inside existing projects.
77
+
78
+ For developers adding W&B to a new framework, follow the [W&B Developer Guide](https://docs.wandb.ai/models/integrations/add-wandb-to-any-library).
79
+
80
+ &nbsp;
81
+
82
+ # W&B Hosting Options
83
+
84
+ Weights & Biases is available in the cloud or installed on your private infrastructure. Set up a W&B Server in a production environment in one of three ways:
85
+
86
+ 1. [Multi-tenant Cloud](https://docs.wandb.ai/platform/hosting/hosting-options/multi_tenant_cloud?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=hosting): Fully managed platform deployed in W&B’s Google Cloud Platform (GCP) account in GCP’s North America regions.
87
+ 2. [Dedicated Cloud](https://docs.wandb.ai/platform/hosting/hosting-options/dedicated_cloud?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=hosting): Single-tenant, fully managed platform deployed in W&B’s AWS, GCP, or Azure cloud accounts. Each Dedicated Cloud instance has its own isolated network, compute and storage from other W&B Dedicated Cloud instances.
88
+ 3. [Self-Managed](https://docs.wandb.ai/platform/hosting/hosting-options/self-managed?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=hosting): Deploy W&B Server on your AWS, GCP, or Azure cloud account or within your on-premises infrastructure.
89
+
90
+ See the [Hosting documentation](https://docs.wandb.ai/platform/hosting?utm_source=github&utm_medium=code&utm_campaign=wandb&utm_content=hosting) in the W&B Developer Guide for more information.
91
+
92
+ &nbsp;
93
+
94
+ # Python Version Support
95
+
96
+ We are committed to supporting our minimum required Python version for _at least_ six months after its official end-of-life (EOL) date, as defined by the Python Software Foundation. You can find a list of Python EOL dates [here](https://devguide.python.org/versions/).
97
+
98
+ When we discontinue support for a Python version, we will increment the library’s minor version number to reflect this change.
99
+
100
+ &nbsp;
101
+
102
+ # Contribution guidelines
103
+
104
+ Weights & Biases ❤️ open source, and we welcome contributions from the community! See the [Contribution guide](https://github.com/wandb/wandb/blob/main/CONTRIBUTING.md) for more information on the development workflow and the internals of the wandb library. For wandb bugs and feature requests, visit [GitHub Issues](https://github.com/wandb/wandb/issues) or contact support@wandb.com.
105
+
106
+ &nbsp;
107
+
108
+ # W&B Community
109
+
110
+ Be a part of the growing W&B Community and interact with the W&B team in our [Discord](https://wandb.me/discord). Stay connected with the latest ML updates and tutorials with [W&B Fully Connected](https://wandb.ai/fully-connected).
111
+
112
+ &nbsp;
113
+
114
+ # License
115
+
116
+ [MIT License](https://github.com/wandb/wandb/blob/main/LICENSE)
.venv/lib/python3.11/site-packages/packaging/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ __title__ = "packaging"
6
+ __summary__ = "Core utilities for Python packages"
7
+ __uri__ = "https://github.com/pypa/packaging"
8
+
9
+ __version__ = "26.2"
10
+
11
+ __author__ = "Donald Stufft and individual contributors"
12
+ __email__ = "donald@stufft.io"
13
+
14
+ __license__ = "BSD-2-Clause or Apache-2.0"
15
+ __copyright__ = f"2014 {__author__}"
.venv/lib/python3.11/site-packages/packaging/_elffile.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ELF file parser.
3
+
4
+ This provides a class ``ELFFile`` that parses an ELF executable in a similar
5
+ interface to ``ZipFile``. Only the read interface is implemented.
6
+
7
+ ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import enum
13
+ import os
14
+ import struct
15
+ from typing import IO
16
+
17
+
18
+ class ELFInvalid(ValueError):
19
+ pass
20
+
21
+
22
+ class EIClass(enum.IntEnum):
23
+ C32 = 1
24
+ C64 = 2
25
+
26
+
27
+ class EIData(enum.IntEnum):
28
+ Lsb = 1
29
+ Msb = 2
30
+
31
+
32
+ class EMachine(enum.IntEnum):
33
+ I386 = 3
34
+ S390 = 22
35
+ Arm = 40
36
+ X8664 = 62
37
+ AArc64 = 183
38
+
39
+
40
+ class ELFFile:
41
+ """
42
+ Representation of an ELF executable.
43
+ """
44
+
45
+ def __init__(self, f: IO[bytes]) -> None:
46
+ self._f = f
47
+
48
+ try:
49
+ ident = self._read("16B")
50
+ except struct.error as e:
51
+ raise ELFInvalid("unable to parse identification") from e
52
+ magic = bytes(ident[:4])
53
+ if magic != b"\x7fELF":
54
+ raise ELFInvalid(f"invalid magic: {magic!r}")
55
+
56
+ self.capacity = ident[4] # Format for program header (bitness).
57
+ self.encoding = ident[5] # Data structure encoding (endianness).
58
+
59
+ try:
60
+ # e_fmt: Format for program header.
61
+ # p_fmt: Format for section header.
62
+ # p_idx: Indexes to find p_type, p_offset, and p_filesz.
63
+ e_fmt, self._p_fmt, self._p_idx = {
64
+ (1, 1): ("<HHIIIIIHHH", "<IIIIIIII", (0, 1, 4)), # 32-bit LSB.
65
+ (1, 2): (">HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB.
66
+ (2, 1): ("<HHIQQQIHHH", "<IIQQQQQQ", (0, 2, 5)), # 64-bit LSB.
67
+ (2, 2): (">HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB.
68
+ }[(self.capacity, self.encoding)]
69
+ except KeyError as e:
70
+ raise ELFInvalid(
71
+ f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})"
72
+ ) from e
73
+
74
+ try:
75
+ (
76
+ _,
77
+ self.machine, # Architecture type.
78
+ _,
79
+ _,
80
+ self._e_phoff, # Offset of program header.
81
+ _,
82
+ self.flags, # Processor-specific flags.
83
+ _,
84
+ self._e_phentsize, # Size of section.
85
+ self._e_phnum, # Number of sections.
86
+ ) = self._read(e_fmt)
87
+ except struct.error as e:
88
+ raise ELFInvalid("unable to parse machine and section information") from e
89
+
90
+ def _read(self, fmt: str) -> tuple[int, ...]:
91
+ return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
92
+
93
+ @property
94
+ def interpreter(self) -> str | None:
95
+ """
96
+ The path recorded in the ``PT_INTERP`` section header.
97
+ """
98
+ for index in range(self._e_phnum):
99
+ self._f.seek(self._e_phoff + self._e_phentsize * index)
100
+ try:
101
+ data = self._read(self._p_fmt)
102
+ except struct.error:
103
+ continue
104
+ if data[self._p_idx[0]] != 3: # Not PT_INTERP.
105
+ continue
106
+ self._f.seek(data[self._p_idx[1]])
107
+ return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0")
108
+ return None
.venv/lib/python3.11/site-packages/packaging/_manylinux.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import contextlib
5
+ import functools
6
+ import os
7
+ import re
8
+ import sys
9
+ import warnings
10
+ from typing import Generator, Iterator, NamedTuple, Sequence
11
+
12
+ from ._elffile import EIClass, EIData, ELFFile, EMachine
13
+
14
+ EF_ARM_ABIMASK = 0xFF000000
15
+ EF_ARM_ABI_VER5 = 0x05000000
16
+ EF_ARM_ABI_FLOAT_HARD = 0x00000400
17
+
18
+ _ALLOWED_ARCHS = {
19
+ "x86_64",
20
+ "aarch64",
21
+ "ppc64",
22
+ "ppc64le",
23
+ "s390x",
24
+ "loongarch64",
25
+ "riscv64",
26
+ }
27
+
28
+
29
+ # `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
30
+ # as the type for `path` until then.
31
+ @contextlib.contextmanager
32
+ def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]:
33
+ try:
34
+ with open(path, "rb") as f:
35
+ yield ELFFile(f)
36
+ except (OSError, TypeError, ValueError):
37
+ yield None
38
+
39
+
40
+ def _is_linux_armhf(executable: str) -> bool:
41
+ # hard-float ABI can be detected from the ELF header of the running
42
+ # process
43
+ # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
44
+ with _parse_elf(executable) as f:
45
+ return (
46
+ f is not None
47
+ and f.capacity == EIClass.C32
48
+ and f.encoding == EIData.Lsb
49
+ and f.machine == EMachine.Arm
50
+ and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
51
+ and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
52
+ )
53
+
54
+
55
+ def _is_linux_i686(executable: str) -> bool:
56
+ with _parse_elf(executable) as f:
57
+ return (
58
+ f is not None
59
+ and f.capacity == EIClass.C32
60
+ and f.encoding == EIData.Lsb
61
+ and f.machine == EMachine.I386
62
+ )
63
+
64
+
65
+ def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
66
+ if "armv7l" in archs:
67
+ return _is_linux_armhf(executable)
68
+ if "i686" in archs:
69
+ return _is_linux_i686(executable)
70
+ return any(arch in _ALLOWED_ARCHS for arch in archs)
71
+
72
+
73
+ # If glibc ever changes its major version, we need to know what the last
74
+ # minor version was, so we can build the complete list of all versions.
75
+ # For now, guess what the highest minor version might be, assume it will
76
+ # be 50 for testing. Once this actually happens, update the dictionary
77
+ # with the actual value.
78
+ _LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)
79
+
80
+
81
+ class _GLibCVersion(NamedTuple):
82
+ major: int
83
+ minor: int
84
+
85
+
86
+ def _glibc_version_string_confstr() -> str | None:
87
+ """
88
+ Primary implementation of glibc_version_string using os.confstr.
89
+ """
90
+ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
91
+ # to be broken or missing. This strategy is used in the standard library
92
+ # platform module.
93
+ # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
94
+ try:
95
+ # Should be a string like "glibc 2.17".
96
+ version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION")
97
+ assert version_string is not None
98
+ _, version = version_string.rsplit()
99
+ except (AssertionError, AttributeError, OSError, ValueError):
100
+ # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
101
+ return None
102
+ return version
103
+
104
+
105
+ def _glibc_version_string_ctypes() -> str | None:
106
+ """
107
+ Fallback implementation of glibc_version_string using ctypes.
108
+ """
109
+ try:
110
+ import ctypes # noqa: PLC0415
111
+ except ImportError:
112
+ return None
113
+
114
+ # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
115
+ # manpage says, "If filename is NULL, then the returned handle is for the
116
+ # main program". This way we can let the linker do the work to figure out
117
+ # which libc our process is actually using.
118
+ #
119
+ # We must also handle the special case where the executable is not a
120
+ # dynamically linked executable. This can occur when using musl libc,
121
+ # for example. In this situation, dlopen() will error, leading to an
122
+ # OSError. Interestingly, at least in the case of musl, there is no
123
+ # errno set on the OSError. The single string argument used to construct
124
+ # OSError comes from libc itself and is therefore not portable to
125
+ # hard code here. In any case, failure to call dlopen() means we
126
+ # can proceed, so we bail on our attempt.
127
+ try:
128
+ process_namespace = ctypes.CDLL(None)
129
+ except OSError:
130
+ return None
131
+
132
+ try:
133
+ gnu_get_libc_version = process_namespace.gnu_get_libc_version
134
+ except AttributeError:
135
+ # Symbol doesn't exist -> therefore, we are not linked to
136
+ # glibc.
137
+ return None
138
+
139
+ # Call gnu_get_libc_version, which returns a string like "2.5"
140
+ gnu_get_libc_version.restype = ctypes.c_char_p
141
+ version_str: str = gnu_get_libc_version()
142
+ # py2 / py3 compatibility:
143
+ if not isinstance(version_str, str):
144
+ version_str = version_str.decode("ascii")
145
+
146
+ return version_str
147
+
148
+
149
+ def _glibc_version_string() -> str | None:
150
+ """Returns glibc version string, or None if not using glibc."""
151
+ return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
152
+
153
+
154
+ def _parse_glibc_version(version_str: str) -> _GLibCVersion:
155
+ """Parse glibc version.
156
+
157
+ We use a regexp instead of str.split because we want to discard any
158
+ random junk that might come after the minor version -- this might happen
159
+ in patched/forked versions of glibc (e.g. Linaro's version of glibc
160
+ uses version strings like "2.20-2014.11"). See gh-3588.
161
+ """
162
+ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str)
163
+ if not m:
164
+ warnings.warn(
165
+ f"Expected glibc version with 2 components major.minor, got: {version_str}",
166
+ RuntimeWarning,
167
+ stacklevel=2,
168
+ )
169
+ return _GLibCVersion(-1, -1)
170
+ return _GLibCVersion(int(m.group("major")), int(m.group("minor")))
171
+
172
+
173
+ @functools.lru_cache
174
+ def _get_glibc_version() -> _GLibCVersion:
175
+ version_str = _glibc_version_string()
176
+ if version_str is None:
177
+ return _GLibCVersion(-1, -1)
178
+ return _parse_glibc_version(version_str)
179
+
180
+
181
+ # From PEP 513, PEP 600
182
+ def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
183
+ sys_glibc = _get_glibc_version()
184
+ if sys_glibc < version:
185
+ return False
186
+ # Check for presence of _manylinux module.
187
+ try:
188
+ import _manylinux # noqa: PLC0415
189
+ except ImportError:
190
+ return True
191
+ if hasattr(_manylinux, "manylinux_compatible"):
192
+ result = _manylinux.manylinux_compatible(version[0], version[1], arch)
193
+ if result is not None:
194
+ return bool(result)
195
+ return True
196
+ if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"):
197
+ return bool(_manylinux.manylinux1_compatible)
198
+ if version == _GLibCVersion(2, 12) and hasattr(
199
+ _manylinux, "manylinux2010_compatible"
200
+ ):
201
+ return bool(_manylinux.manylinux2010_compatible)
202
+ if version == _GLibCVersion(2, 17) and hasattr(
203
+ _manylinux, "manylinux2014_compatible"
204
+ ):
205
+ return bool(_manylinux.manylinux2014_compatible)
206
+ return True
207
+
208
+
209
+ _LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = {
210
+ # CentOS 7 w/ glibc 2.17 (PEP 599)
211
+ _GLibCVersion(2, 17): "manylinux2014",
212
+ # CentOS 6 w/ glibc 2.12 (PEP 571)
213
+ _GLibCVersion(2, 12): "manylinux2010",
214
+ # CentOS 5 w/ glibc 2.5 (PEP 513)
215
+ _GLibCVersion(2, 5): "manylinux1",
216
+ }
217
+
218
+
219
+ def platform_tags(archs: Sequence[str]) -> Iterator[str]:
220
+ """Generate manylinux tags compatible to the current platform.
221
+
222
+ :param archs: Sequence of compatible architectures.
223
+ The first one shall be the closest to the actual architecture and be the part of
224
+ platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
225
+ The ``linux_`` prefix is assumed as a prerequisite for the current platform to
226
+ be manylinux-compatible.
227
+
228
+ :returns: An iterator of compatible manylinux tags.
229
+ """
230
+ if not _have_compatible_abi(sys.executable, archs):
231
+ return
232
+ # Oldest glibc to be supported regardless of architecture is (2, 17).
233
+ too_old_glibc2 = _GLibCVersion(2, 16)
234
+ if set(archs) & {"x86_64", "i686"}:
235
+ # On x86/i686 also oldest glibc to be supported is (2, 5).
236
+ too_old_glibc2 = _GLibCVersion(2, 4)
237
+ current_glibc = _GLibCVersion(*_get_glibc_version())
238
+ glibc_max_list = [current_glibc]
239
+ # We can assume compatibility across glibc major versions.
240
+ # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
241
+ #
242
+ # Build a list of maximum glibc versions so that we can
243
+ # output the canonical list of all glibc from current_glibc
244
+ # down to too_old_glibc2, including all intermediary versions.
245
+ for glibc_major in range(current_glibc.major - 1, 1, -1):
246
+ glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
247
+ glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
248
+ for arch in archs:
249
+ for glibc_max in glibc_max_list:
250
+ if glibc_max.major == too_old_glibc2.major:
251
+ min_minor = too_old_glibc2.minor
252
+ else:
253
+ # For other glibc major versions oldest supported is (x, 0).
254
+ min_minor = -1
255
+ for glibc_minor in range(glibc_max.minor, min_minor, -1):
256
+ glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
257
+ if _is_compatible(arch, glibc_version):
258
+ yield "manylinux_{}_{}_{}".format(*glibc_version, arch)
259
+
260
+ # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
261
+ if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version):
262
+ yield f"{legacy_tag}_{arch}"
.venv/lib/python3.11/site-packages/packaging/_musllinux.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PEP 656 support.
2
+
3
+ This module implements logic to detect if the currently running Python is
4
+ linked against musl, and what musl version is used.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ from typing import Iterator, NamedTuple, Sequence
14
+
15
+ from ._elffile import ELFFile
16
+
17
+
18
+ class _MuslVersion(NamedTuple):
19
+ major: int
20
+ minor: int
21
+
22
+
23
+ def _parse_musl_version(output: str) -> _MuslVersion | None:
24
+ lines = [n for n in (n.strip() for n in output.splitlines()) if n]
25
+ if len(lines) < 2 or lines[0][:4] != "musl":
26
+ return None
27
+ m = re.match(r"Version (\d+)\.(\d+)", lines[1])
28
+ if not m:
29
+ return None
30
+ return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
31
+
32
+
33
+ @functools.lru_cache
34
+ def _get_musl_version(executable: str) -> _MuslVersion | None:
35
+ """Detect currently-running musl runtime version.
36
+
37
+ This is done by checking the specified executable's dynamic linking
38
+ information, and invoking the loader to parse its output for a version
39
+ string. If the loader is musl, the output would be something like::
40
+
41
+ musl libc (x86_64)
42
+ Version 1.2.2
43
+ Dynamic Program Loader
44
+ """
45
+ try:
46
+ with open(executable, "rb") as f:
47
+ ld = ELFFile(f).interpreter
48
+ except (OSError, TypeError, ValueError):
49
+ return None
50
+ if ld is None or "musl" not in ld:
51
+ return None
52
+ proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True)
53
+ return _parse_musl_version(proc.stderr)
54
+
55
+
56
+ def platform_tags(archs: Sequence[str]) -> Iterator[str]:
57
+ """Generate musllinux tags compatible to the current platform.
58
+
59
+ :param archs: Sequence of compatible architectures.
60
+ The first one shall be the closest to the actual architecture and be the part of
61
+ platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
62
+ The ``linux_`` prefix is assumed as a prerequisite for the current platform to
63
+ be musllinux-compatible.
64
+
65
+ :returns: An iterator of compatible musllinux tags.
66
+ """
67
+ sys_musl = _get_musl_version(sys.executable)
68
+ if sys_musl is None: # Python not dynamically linked against musl.
69
+ return
70
+ for arch in archs:
71
+ for minor in range(sys_musl.minor, -1, -1):
72
+ yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
73
+
74
+
75
+ if __name__ == "__main__": # pragma: no cover
76
+ import sysconfig
77
+
78
+ plat = sysconfig.get_platform()
79
+ assert plat.startswith("linux-"), "not linux"
80
+
81
+ print("plat:", plat)
82
+ print("musl:", _get_musl_version(sys.executable))
83
+ print("tags:", end=" ")
84
+ for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])):
85
+ print(t, end="\n ")
.venv/lib/python3.11/site-packages/packaging/_parser.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Handwritten parser of dependency specifiers.
2
+
3
+ The docstring for each __parse_* function contains EBNF-inspired grammar representing
4
+ the implementation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ from typing import List, Literal, NamedTuple, Sequence, Tuple, Union
11
+
12
+ from ._tokenizer import DEFAULT_RULES, Tokenizer
13
+
14
+
15
+ class Node:
16
+ __slots__ = ("value",)
17
+
18
+ def __init__(self, value: str) -> None:
19
+ self.value = value
20
+
21
+ def __str__(self) -> str:
22
+ return self.value
23
+
24
+ def __repr__(self) -> str:
25
+ return f"<{self.__class__.__name__}({self.value!r})>"
26
+
27
+ def serialize(self) -> str:
28
+ raise NotImplementedError
29
+
30
+ def __getstate__(self) -> str:
31
+ # Return just the value string for compactness and stability.
32
+ return self.value
33
+
34
+ def _restore_value(self, value: object) -> None:
35
+ if not isinstance(value, str):
36
+ raise TypeError(
37
+ f"Cannot restore {self.__class__.__name__} value from {value!r}"
38
+ )
39
+ self.value = value
40
+
41
+ def __setstate__(self, state: object) -> None:
42
+ if isinstance(state, str):
43
+ # New format (26.2+): just the value string.
44
+ self._restore_value(state)
45
+ return
46
+ if isinstance(state, tuple) and len(state) == 2:
47
+ # Old format (packaging <= 26.0, __slots__): (None, {slot: value}).
48
+ _, slot_dict = state
49
+ if isinstance(slot_dict, dict) and "value" in slot_dict:
50
+ self._restore_value(slot_dict["value"])
51
+ return
52
+ if isinstance(state, dict) and "value" in state:
53
+ # Old format (packaging <= 25.0, no __slots__): plain __dict__.
54
+ self._restore_value(state["value"])
55
+ return
56
+ raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}")
57
+
58
+
59
+ class Variable(Node):
60
+ __slots__ = ()
61
+
62
+ def serialize(self) -> str:
63
+ return str(self)
64
+
65
+
66
+ class Value(Node):
67
+ __slots__ = ()
68
+
69
+ def serialize(self) -> str:
70
+ return f'"{self}"'
71
+
72
+
73
+ class Op(Node):
74
+ __slots__ = ()
75
+
76
+ def serialize(self) -> str:
77
+ return str(self)
78
+
79
+
80
+ MarkerLogical = Literal["and", "or"]
81
+ MarkerVar = Union[Variable, Value]
82
+ MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
83
+ MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]
84
+ MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
85
+
86
+
87
+ class ParsedRequirement(NamedTuple):
88
+ name: str
89
+ url: str
90
+ extras: list[str]
91
+ specifier: str
92
+ marker: MarkerList | None
93
+
94
+
95
+ # --------------------------------------------------------------------------------------
96
+ # Recursive descent parser for dependency specifier
97
+ # --------------------------------------------------------------------------------------
98
+ def parse_requirement(source: str) -> ParsedRequirement:
99
+ return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
100
+
101
+
102
+ def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
103
+ """
104
+ requirement = WS? IDENTIFIER WS? extras WS? requirement_details
105
+ """
106
+ tokenizer.consume("WS")
107
+
108
+ name_token = tokenizer.expect(
109
+ "IDENTIFIER", expected="package name at the start of dependency specifier"
110
+ )
111
+ name = name_token.text
112
+ tokenizer.consume("WS")
113
+
114
+ extras = _parse_extras(tokenizer)
115
+ tokenizer.consume("WS")
116
+
117
+ url, specifier, marker = _parse_requirement_details(tokenizer)
118
+ tokenizer.expect("END", expected="end of dependency specifier")
119
+
120
+ return ParsedRequirement(name, url, extras, specifier, marker)
121
+
122
+
123
+ def _parse_requirement_details(
124
+ tokenizer: Tokenizer,
125
+ ) -> tuple[str, str, MarkerList | None]:
126
+ """
127
+ requirement_details = AT URL (WS requirement_marker?)?
128
+ | specifier WS? (requirement_marker)?
129
+ """
130
+
131
+ specifier = ""
132
+ url = ""
133
+ marker = None
134
+
135
+ if tokenizer.check("AT"):
136
+ tokenizer.read()
137
+ tokenizer.consume("WS")
138
+
139
+ url_start = tokenizer.position
140
+ url = tokenizer.expect("URL", expected="URL after @").text
141
+ if tokenizer.check("END", peek=True):
142
+ return (url, specifier, marker)
143
+
144
+ tokenizer.expect("WS", expected="whitespace after URL")
145
+
146
+ # The input might end after whitespace.
147
+ if tokenizer.check("END", peek=True):
148
+ return (url, specifier, marker)
149
+
150
+ marker = _parse_requirement_marker(
151
+ tokenizer,
152
+ span_start=url_start,
153
+ expected="semicolon (after URL and whitespace)",
154
+ )
155
+ else:
156
+ specifier_start = tokenizer.position
157
+ specifier = _parse_specifier(tokenizer)
158
+ tokenizer.consume("WS")
159
+
160
+ if tokenizer.check("END", peek=True):
161
+ return (url, specifier, marker)
162
+
163
+ marker = _parse_requirement_marker(
164
+ tokenizer,
165
+ span_start=specifier_start,
166
+ expected=(
167
+ "comma (within version specifier), semicolon (after version specifier)"
168
+ if specifier
169
+ else "semicolon (after name with no version specifier)"
170
+ ),
171
+ )
172
+
173
+ return (url, specifier, marker)
174
+
175
+
176
+ def _parse_requirement_marker(
177
+ tokenizer: Tokenizer, *, span_start: int, expected: str
178
+ ) -> MarkerList:
179
+ """
180
+ requirement_marker = SEMICOLON marker WS?
181
+ """
182
+
183
+ if not tokenizer.check("SEMICOLON"):
184
+ tokenizer.raise_syntax_error(
185
+ f"Expected {expected} or end",
186
+ span_start=span_start,
187
+ span_end=None,
188
+ )
189
+ tokenizer.read()
190
+
191
+ marker = _parse_marker(tokenizer)
192
+ tokenizer.consume("WS")
193
+
194
+ return marker
195
+
196
+
197
+ def _parse_extras(tokenizer: Tokenizer) -> list[str]:
198
+ """
199
+ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
200
+ """
201
+ if not tokenizer.check("LEFT_BRACKET", peek=True):
202
+ return []
203
+
204
+ with tokenizer.enclosing_tokens(
205
+ "LEFT_BRACKET",
206
+ "RIGHT_BRACKET",
207
+ around="extras",
208
+ ):
209
+ tokenizer.consume("WS")
210
+ extras = _parse_extras_list(tokenizer)
211
+ tokenizer.consume("WS")
212
+
213
+ return extras
214
+
215
+
216
+ def _parse_extras_list(tokenizer: Tokenizer) -> list[str]:
217
+ """
218
+ extras_list = identifier (wsp* ',' wsp* identifier)*
219
+ """
220
+ extras: list[str] = []
221
+
222
+ if not tokenizer.check("IDENTIFIER"):
223
+ return extras
224
+
225
+ extras.append(tokenizer.read().text)
226
+
227
+ while True:
228
+ tokenizer.consume("WS")
229
+ if tokenizer.check("IDENTIFIER", peek=True):
230
+ tokenizer.raise_syntax_error("Expected comma between extra names")
231
+ elif not tokenizer.check("COMMA"):
232
+ break
233
+
234
+ tokenizer.read()
235
+ tokenizer.consume("WS")
236
+
237
+ extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma")
238
+ extras.append(extra_token.text)
239
+
240
+ return extras
241
+
242
+
243
+ def _parse_specifier(tokenizer: Tokenizer) -> str:
244
+ """
245
+ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS
246
+ | WS? version_many WS?
247
+ """
248
+ with tokenizer.enclosing_tokens(
249
+ "LEFT_PARENTHESIS",
250
+ "RIGHT_PARENTHESIS",
251
+ around="version specifier",
252
+ ):
253
+ tokenizer.consume("WS")
254
+ parsed_specifiers = _parse_version_many(tokenizer)
255
+ tokenizer.consume("WS")
256
+
257
+ return parsed_specifiers
258
+
259
+
260
+ def _parse_version_many(tokenizer: Tokenizer) -> str:
261
+ """
262
+ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?
263
+ """
264
+ parsed_specifiers = ""
265
+ while tokenizer.check("SPECIFIER"):
266
+ span_start = tokenizer.position
267
+ parsed_specifiers += tokenizer.read().text
268
+ if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True):
269
+ tokenizer.raise_syntax_error(
270
+ ".* suffix can only be used with `==` or `!=` operators",
271
+ span_start=span_start,
272
+ span_end=tokenizer.position + 1,
273
+ )
274
+ if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True):
275
+ tokenizer.raise_syntax_error(
276
+ "Local version label can only be used with `==` or `!=` operators",
277
+ span_start=span_start,
278
+ span_end=tokenizer.position,
279
+ )
280
+ tokenizer.consume("WS")
281
+ if not tokenizer.check("COMMA"):
282
+ break
283
+ parsed_specifiers += tokenizer.read().text
284
+ tokenizer.consume("WS")
285
+
286
+ return parsed_specifiers
287
+
288
+
289
+ # --------------------------------------------------------------------------------------
290
+ # Recursive descent parser for marker expression
291
+ # --------------------------------------------------------------------------------------
292
+ def parse_marker(source: str) -> MarkerList:
293
+ return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
294
+
295
+
296
+ def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:
297
+ retval = _parse_marker(tokenizer)
298
+ tokenizer.expect("END", expected="end of marker expression")
299
+ return retval
300
+
301
+
302
+ def _parse_marker(tokenizer: Tokenizer) -> MarkerList:
303
+ """
304
+ marker = marker_atom (BOOLOP marker_atom)+
305
+ """
306
+ expression = [_parse_marker_atom(tokenizer)]
307
+ while tokenizer.check("BOOLOP"):
308
+ token = tokenizer.read()
309
+ expr_right = _parse_marker_atom(tokenizer)
310
+ expression.extend((token.text, expr_right))
311
+ return expression
312
+
313
+
314
+ def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:
315
+ """
316
+ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?
317
+ | WS? marker_item WS?
318
+ """
319
+
320
+ tokenizer.consume("WS")
321
+ if tokenizer.check("LEFT_PARENTHESIS", peek=True):
322
+ with tokenizer.enclosing_tokens(
323
+ "LEFT_PARENTHESIS",
324
+ "RIGHT_PARENTHESIS",
325
+ around="marker expression",
326
+ ):
327
+ tokenizer.consume("WS")
328
+ marker: MarkerAtom = _parse_marker(tokenizer)
329
+ tokenizer.consume("WS")
330
+ else:
331
+ marker = _parse_marker_item(tokenizer)
332
+ tokenizer.consume("WS")
333
+ return marker
334
+
335
+
336
+ def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
337
+ """
338
+ marker_item = WS? marker_var WS? marker_op WS? marker_var WS?
339
+ """
340
+ tokenizer.consume("WS")
341
+ marker_var_left = _parse_marker_var(tokenizer)
342
+ tokenizer.consume("WS")
343
+ marker_op = _parse_marker_op(tokenizer)
344
+ tokenizer.consume("WS")
345
+ marker_var_right = _parse_marker_var(tokenizer)
346
+ tokenizer.consume("WS")
347
+ return (marker_var_left, marker_op, marker_var_right)
348
+
349
+
350
+ def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503
351
+ """
352
+ marker_var = VARIABLE | QUOTED_STRING
353
+ """
354
+ if tokenizer.check("VARIABLE"):
355
+ return process_env_var(tokenizer.read().text.replace(".", "_"))
356
+ elif tokenizer.check("QUOTED_STRING"):
357
+ return process_python_str(tokenizer.read().text)
358
+ else:
359
+ tokenizer.raise_syntax_error(
360
+ message="Expected a marker variable or quoted string"
361
+ )
362
+
363
+
364
+ def process_env_var(env_var: str) -> Variable:
365
+ if env_var in ("platform_python_implementation", "python_implementation"):
366
+ return Variable("platform_python_implementation")
367
+ else:
368
+ return Variable(env_var)
369
+
370
+
371
+ def process_python_str(python_str: str) -> Value:
372
+ value = ast.literal_eval(python_str)
373
+ return Value(str(value))
374
+
375
+
376
+ def _parse_marker_op(tokenizer: Tokenizer) -> Op:
377
+ """
378
+ marker_op = IN | NOT IN | OP
379
+ """
380
+ if tokenizer.check("IN"):
381
+ tokenizer.read()
382
+ return Op("in")
383
+ elif tokenizer.check("NOT"):
384
+ tokenizer.read()
385
+ tokenizer.expect("WS", expected="whitespace after 'not'")
386
+ tokenizer.expect("IN", expected="'in' after 'not'")
387
+ return Op("not in")
388
+ elif tokenizer.check("OP"):
389
+ return Op(tokenizer.read().text)
390
+ else:
391
+ return tokenizer.raise_syntax_error(
392
+ "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in"
393
+ )
.venv/lib/python3.11/site-packages/packaging/_structures.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ """Backward-compatibility shim for unpickling Version objects serialized before
6
+ packaging 26.1.
7
+
8
+ Old pickles reference ``packaging._structures.InfinityType`` and
9
+ ``packaging._structures.NegativeInfinityType``. This module provides minimal
10
+ stand-in classes so that ``pickle.loads()`` can resolve those references.
11
+ The deserialized objects are not used for comparisons — ``Version.__setstate__``
12
+ discards the stale ``_key`` cache and recomputes it from the core version fields.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+
18
+ class InfinityType:
19
+ """Stand-in for the removed ``InfinityType`` used in old comparison keys."""
20
+
21
+ def __repr__(self) -> str:
22
+ return "Infinity"
23
+
24
+
25
+ class NegativeInfinityType:
26
+ """Stand-in for the removed ``NegativeInfinityType`` used in old comparison keys."""
27
+
28
+ def __repr__(self) -> str:
29
+ return "-Infinity"
30
+
31
+
32
+ Infinity = InfinityType()
33
+ NegativeInfinity = NegativeInfinityType()
.venv/lib/python3.11/site-packages/packaging/_tokenizer.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import re
5
+ from dataclasses import dataclass
6
+ from typing import Generator, Mapping, NoReturn
7
+
8
+ from .specifiers import Specifier
9
+
10
+
11
+ @dataclass
12
+ class Token:
13
+ name: str
14
+ text: str
15
+ position: int
16
+
17
+
18
+ class ParserSyntaxError(Exception):
19
+ """The provided source text could not be parsed correctly."""
20
+
21
+ def __init__(
22
+ self,
23
+ message: str,
24
+ *,
25
+ source: str,
26
+ span: tuple[int, int],
27
+ ) -> None:
28
+ self.span = span
29
+ self.message = message
30
+ self.source = source
31
+
32
+ super().__init__()
33
+
34
+ def __str__(self) -> str:
35
+ marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^"
36
+ return f"{self.message}\n {self.source}\n {marker}"
37
+
38
+
39
+ DEFAULT_RULES: dict[str, re.Pattern[str]] = {
40
+ "LEFT_PARENTHESIS": re.compile(r"\("),
41
+ "RIGHT_PARENTHESIS": re.compile(r"\)"),
42
+ "LEFT_BRACKET": re.compile(r"\["),
43
+ "RIGHT_BRACKET": re.compile(r"\]"),
44
+ "SEMICOLON": re.compile(r";"),
45
+ "COMMA": re.compile(r","),
46
+ "QUOTED_STRING": re.compile(
47
+ r"""
48
+ (
49
+ ('[^']*')
50
+ |
51
+ ("[^"]*")
52
+ )
53
+ """,
54
+ re.VERBOSE,
55
+ ),
56
+ "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"),
57
+ "BOOLOP": re.compile(r"\b(or|and)\b"),
58
+ "IN": re.compile(r"\bin\b"),
59
+ "NOT": re.compile(r"\bnot\b"),
60
+ "VARIABLE": re.compile(
61
+ r"""
62
+ \b(
63
+ python_version
64
+ |python_full_version
65
+ |os[._]name
66
+ |sys[._]platform
67
+ |platform_(release|system)
68
+ |platform[._](version|machine|python_implementation)
69
+ |python_implementation
70
+ |implementation_(name|version)
71
+ |extras?
72
+ |dependency_groups
73
+ )\b
74
+ """,
75
+ re.VERBOSE,
76
+ ),
77
+ "SPECIFIER": re.compile(
78
+ Specifier._specifier_regex_str,
79
+ re.VERBOSE | re.IGNORECASE,
80
+ ),
81
+ "AT": re.compile(r"\@"),
82
+ "URL": re.compile(r"[^ \t]+"),
83
+ "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"),
84
+ "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"),
85
+ "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"),
86
+ "WS": re.compile(r"[ \t]+"),
87
+ "END": re.compile(r"$"),
88
+ }
89
+
90
+
91
+ class Tokenizer:
92
+ """Context-sensitive token parsing.
93
+
94
+ Provides methods to examine the input stream to check whether the next token
95
+ matches.
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ source: str,
101
+ *,
102
+ rules: Mapping[str, re.Pattern[str]],
103
+ ) -> None:
104
+ self.source = source
105
+ self.rules = rules
106
+ self.next_token: Token | None = None
107
+ self.position = 0
108
+
109
+ def consume(self, name: str) -> None:
110
+ """Move beyond provided token name, if at current position."""
111
+ if self.check(name):
112
+ self.read()
113
+
114
+ def check(self, name: str, *, peek: bool = False) -> bool:
115
+ """Check whether the next token has the provided name.
116
+
117
+ By default, if the check succeeds, the token *must* be read before
118
+ another check. If `peek` is set to `True`, the token is not loaded and
119
+ would need to be checked again.
120
+ """
121
+ assert self.next_token is None, (
122
+ f"Cannot check for {name!r}, already have {self.next_token!r}"
123
+ )
124
+ assert name in self.rules, f"Unknown token name: {name!r}"
125
+
126
+ expression = self.rules[name]
127
+
128
+ match = expression.match(self.source, self.position)
129
+ if match is None:
130
+ return False
131
+ if not peek:
132
+ self.next_token = Token(name, match[0], self.position)
133
+ return True
134
+
135
+ def expect(self, name: str, *, expected: str) -> Token:
136
+ """Expect a certain token name next, failing with a syntax error otherwise.
137
+
138
+ The token is *not* read.
139
+ """
140
+ if not self.check(name):
141
+ raise self.raise_syntax_error(f"Expected {expected}")
142
+ return self.read()
143
+
144
+ def read(self) -> Token:
145
+ """Consume the next token and return it."""
146
+ token = self.next_token
147
+ assert token is not None
148
+
149
+ self.position += len(token.text)
150
+ self.next_token = None
151
+
152
+ return token
153
+
154
+ def raise_syntax_error(
155
+ self,
156
+ message: str,
157
+ *,
158
+ span_start: int | None = None,
159
+ span_end: int | None = None,
160
+ ) -> NoReturn:
161
+ """Raise ParserSyntaxError at the given position."""
162
+ span = (
163
+ self.position if span_start is None else span_start,
164
+ self.position if span_end is None else span_end,
165
+ )
166
+ raise ParserSyntaxError(
167
+ message,
168
+ source=self.source,
169
+ span=span,
170
+ )
171
+
172
+ @contextlib.contextmanager
173
+ def enclosing_tokens(
174
+ self, open_token: str, close_token: str, *, around: str
175
+ ) -> Generator[None, None, None]:
176
+ if self.check(open_token):
177
+ open_position = self.position
178
+ self.read()
179
+ else:
180
+ open_position = None
181
+
182
+ yield
183
+
184
+ if open_position is None:
185
+ return
186
+
187
+ if not self.check(close_token):
188
+ self.raise_syntax_error(
189
+ f"Expected matching {close_token} for {open_token}, after {around}",
190
+ span_start=open_position,
191
+ )
192
+
193
+ self.read()
.venv/lib/python3.11/site-packages/packaging/dependency_groups.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from collections.abc import Mapping, Sequence
5
+
6
+ from .errors import _ErrorCollector
7
+ from .requirements import Requirement
8
+
9
+ __all__ = [
10
+ "CyclicDependencyGroup",
11
+ "DependencyGroupInclude",
12
+ "DependencyGroupResolver",
13
+ "DuplicateGroupNames",
14
+ "InvalidDependencyGroupObject",
15
+ "resolve_dependency_groups",
16
+ ]
17
+
18
+
19
+ def __dir__() -> list[str]:
20
+ return __all__
21
+
22
+
23
+ # -----------
24
+ # Error Types
25
+ # -----------
26
+
27
+
28
+ class DuplicateGroupNames(ValueError):
29
+ """
30
+ The same dependency groups were defined twice, with different non-normalized names.
31
+ """
32
+
33
+
34
+ class CyclicDependencyGroup(ValueError):
35
+ """
36
+ The dependency group includes form a cycle.
37
+ """
38
+
39
+ def __init__(self, requested_group: str, group: str, include_group: str) -> None:
40
+ self.requested_group = requested_group
41
+ self.group = group
42
+ self.include_group = include_group
43
+
44
+ if include_group == group:
45
+ reason = f"{group} includes itself"
46
+ else:
47
+ reason = f"{include_group} -> {group}, {group} -> {include_group}"
48
+ super().__init__(
49
+ "Cyclic dependency group include while resolving "
50
+ f"{requested_group}: {reason}"
51
+ )
52
+
53
+
54
+ # in the PEP 735 spec, the tables in dependency group lists were described as
55
+ # "Dependency Object Specifiers", but the only defined type of object was a
56
+ # "Dependency Group Include" -- hence the naming of this error as "Object"
57
+ class InvalidDependencyGroupObject(ValueError):
58
+ """
59
+ A member of a dependency group was identified as a dict, but was not in a valid
60
+ format.
61
+ """
62
+
63
+
64
+ # ------------------------
65
+ # Object Model & Interface
66
+ # ------------------------
67
+
68
+
69
+ class DependencyGroupInclude:
70
+ __slots__ = ("include_group",)
71
+
72
+ def __init__(self, include_group: str) -> None:
73
+ """
74
+ Initialize a DependencyGroupInclude.
75
+
76
+ :param include_group: The name of the group referred to by this include.
77
+ """
78
+ self.include_group = include_group
79
+
80
+ def __repr__(self) -> str:
81
+ return f"{self.__class__.__name__}({self.include_group!r})"
82
+
83
+
84
+ class DependencyGroupResolver:
85
+ """
86
+ A resolver for Dependency Group data.
87
+
88
+ This class handles caching, name normalization, cycle detection, and other
89
+ parsing requirements. There are only two public methods for exploring the data:
90
+ ``lookup()`` and ``resolve()``.
91
+
92
+ :param dependency_groups: A mapping, as provided via pyproject
93
+ ``[dependency-groups]``.
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]],
99
+ ) -> None:
100
+ errors = _ErrorCollector()
101
+
102
+ self.dependency_groups = _normalize_group_names(dependency_groups, errors)
103
+
104
+ # a map of group names to parsed data
105
+ self._parsed_groups: dict[
106
+ str, tuple[Requirement | DependencyGroupInclude, ...]
107
+ ] = {}
108
+ # a map of group names to their ancestors, used for cycle detection
109
+ self._include_graph_ancestors: dict[str, tuple[str, ...]] = {}
110
+ # a cache of completed resolutions to Requirement lists
111
+ self._resolve_cache: dict[str, tuple[Requirement, ...]] = {}
112
+
113
+ errors.finalize("[dependency-groups] data was invalid")
114
+
115
+ def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]:
116
+ """
117
+ Lookup a group name, returning the parsed dependency data for that group.
118
+ This will not resolve includes.
119
+
120
+ :param group: the name of the group to lookup
121
+ """
122
+ group = _normalize_name(group)
123
+
124
+ with _ErrorCollector().on_exit(
125
+ f"[dependency-groups] data for {group!r} was malformed"
126
+ ) as errors:
127
+ return self._parse_group(group, errors)
128
+
129
+ def resolve(self, group: str) -> tuple[Requirement, ...]:
130
+ """
131
+ Resolve a dependency group to a list of requirements.
132
+
133
+ :param group: the name of the group to resolve
134
+ """
135
+ group = _normalize_name(group)
136
+
137
+ with _ErrorCollector().on_exit(
138
+ f"[dependency-groups] data for {group!r} was malformed"
139
+ ) as errors:
140
+ return self._resolve(group, group, errors)
141
+
142
+ def _resolve(
143
+ self, group: str, requested_group: str, errors: _ErrorCollector
144
+ ) -> tuple[Requirement, ...]:
145
+ """
146
+ This is a helper for cached resolution to strings. It preserves the name of the
147
+ group which the user initially requested in order to present a clearer error in
148
+ the event that a cycle is detected.
149
+
150
+ :param group: The normalized name of the group to resolve.
151
+ :param requested_group: The group which was used in the original, user-facing
152
+ request.
153
+ """
154
+ if group in self._resolve_cache:
155
+ return self._resolve_cache[group]
156
+
157
+ parsed = self._parse_group(group, errors)
158
+
159
+ resolved_group = []
160
+
161
+ for item in parsed:
162
+ if isinstance(item, Requirement):
163
+ resolved_group.append(item)
164
+ elif isinstance(item, DependencyGroupInclude):
165
+ include_group = _normalize_name(item.include_group)
166
+
167
+ # if a group is cyclic, record the error
168
+ # otherwise, follow the include_group reference
169
+ #
170
+ # this allows us to examine all includes in a group, even in the
171
+ # presence of errors
172
+ if include_group in self._include_graph_ancestors.get(group, ()):
173
+ errors.error(
174
+ CyclicDependencyGroup(
175
+ requested_group, group, item.include_group
176
+ )
177
+ )
178
+ else:
179
+ self._include_graph_ancestors[include_group] = (
180
+ *self._include_graph_ancestors.get(group, ()),
181
+ group,
182
+ )
183
+ resolved_group.extend(
184
+ self._resolve(include_group, requested_group, errors)
185
+ )
186
+ else: # pragma: no cover
187
+ raise NotImplementedError(
188
+ f"Invalid dependency group item after parse: {item}"
189
+ )
190
+
191
+ # in the event that errors were detected, present the group as empty and do not
192
+ # cache the result
193
+ # this ensures that repeated access to a cyclic group will raise multiple errors
194
+ if errors.errors:
195
+ return ()
196
+
197
+ self._resolve_cache[group] = tuple(resolved_group)
198
+ return self._resolve_cache[group]
199
+
200
+ def _parse_group(
201
+ self, group: str, errors: _ErrorCollector
202
+ ) -> tuple[Requirement | DependencyGroupInclude, ...]:
203
+ # short circuit -- never do the work twice
204
+ if group in self._parsed_groups:
205
+ return self._parsed_groups[group]
206
+
207
+ if group not in self.dependency_groups:
208
+ errors.error(LookupError(f"Dependency group '{group}' not found"))
209
+ return ()
210
+
211
+ raw_group = self.dependency_groups[group]
212
+ if isinstance(raw_group, str):
213
+ errors.error(
214
+ TypeError(
215
+ f"Dependency group {group!r} contained a string rather than a list."
216
+ )
217
+ )
218
+ return ()
219
+
220
+ if not isinstance(raw_group, Sequence):
221
+ errors.error(
222
+ TypeError(f"Dependency group {group!r} is not a sequence type.")
223
+ )
224
+ return ()
225
+
226
+ elements: list[Requirement | DependencyGroupInclude] = []
227
+ for item in raw_group:
228
+ if isinstance(item, str):
229
+ # packaging.requirements.Requirement parsing ensures that this is a
230
+ # valid PEP 508 Dependency Specifier
231
+ # raises InvalidRequirement on failure
232
+ elements.append(Requirement(item))
233
+ elif isinstance(item, Mapping):
234
+ if tuple(item.keys()) != ("include-group",):
235
+ errors.error(
236
+ InvalidDependencyGroupObject(
237
+ f"Invalid dependency group item: {item!r}"
238
+ )
239
+ )
240
+ else:
241
+ include_group = item["include-group"]
242
+ elements.append(DependencyGroupInclude(include_group=include_group))
243
+ else:
244
+ errors.error(TypeError(f"Invalid dependency group item: {item!r}"))
245
+
246
+ self._parsed_groups[group] = tuple(elements)
247
+ return self._parsed_groups[group]
248
+
249
+
250
+ # --------------------
251
+ # Functional Interface
252
+ # --------------------
253
+
254
+
255
+ def resolve_dependency_groups(
256
+ dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str
257
+ ) -> tuple[str, ...]:
258
+ """
259
+ Resolve a dependency group to a tuple of requirements, as strings.
260
+
261
+ :param dependency_groups: the parsed contents of the ``[dependency-groups]`` table
262
+ from ``pyproject.toml``
263
+ :param groups: the name of the group(s) to resolve
264
+ """
265
+ resolver = DependencyGroupResolver(dependency_groups)
266
+ return tuple(str(r) for group in groups for r in resolver.resolve(group))
267
+
268
+
269
+ # ----------------
270
+ # internal helpers
271
+ # ----------------
272
+
273
+
274
+ _NORMALIZE_PATTERN = re.compile(r"[-_.]+")
275
+
276
+
277
+ def _normalize_name(name: str) -> str:
278
+ return _NORMALIZE_PATTERN.sub("-", name).lower()
279
+
280
+
281
+ def _normalize_group_names(
282
+ dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]],
283
+ errors: _ErrorCollector,
284
+ ) -> dict[str, Sequence[str | Mapping[str, str]]]:
285
+ original_names: dict[str, list[str]] = {}
286
+ normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {}
287
+
288
+ for group_name, value in dependency_groups.items():
289
+ normed_group_name = _normalize_name(group_name)
290
+ original_names.setdefault(normed_group_name, []).append(group_name)
291
+ normalized_groups[normed_group_name] = value
292
+
293
+ for normed_name, names in original_names.items():
294
+ if len(names) > 1:
295
+ errors.error(
296
+ DuplicateGroupNames(
297
+ "Duplicate dependency group names: "
298
+ f"{normed_name} ({', '.join(names)})"
299
+ )
300
+ )
301
+
302
+ return normalized_groups
.venv/lib/python3.11/site-packages/packaging/direct_url.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import re
5
+ import urllib.parse
6
+ from collections.abc import Mapping
7
+ from typing import TYPE_CHECKING, Any, Protocol, TypeVar
8
+
9
+ if TYPE_CHECKING: # pragma: no cover
10
+ import sys
11
+ from collections.abc import Collection
12
+
13
+ if sys.version_info >= (3, 11):
14
+ from typing import Self
15
+ else:
16
+ from typing_extensions import Self
17
+
18
+ __all__ = [
19
+ "ArchiveInfo",
20
+ "DirInfo",
21
+ "DirectUrl",
22
+ "DirectUrlValidationError",
23
+ "VcsInfo",
24
+ ]
25
+
26
+
27
+ def __dir__() -> list[str]:
28
+ return __all__
29
+
30
+
31
+ _T = TypeVar("_T")
32
+
33
+
34
+ class _FromMappingProtocol(Protocol): # pragma: no cover
35
+ @classmethod
36
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
37
+
38
+
39
+ _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
40
+
41
+
42
+ def _json_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]:
43
+ return {key: value for key, value in data if value is not None}
44
+
45
+
46
+ def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None:
47
+ """Get a value from the dictionary and verify it's the expected type."""
48
+ if (value := d.get(key)) is None:
49
+ return None
50
+ if not isinstance(value, expected_type):
51
+ raise DirectUrlValidationError(
52
+ f"Unexpected type {type(value).__name__} "
53
+ f"(expected {expected_type.__name__})",
54
+ context=key,
55
+ )
56
+ return value
57
+
58
+
59
+ def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T:
60
+ """Get a required value from the dictionary and verify it's the expected type."""
61
+ if (value := _get(d, expected_type, key)) is None:
62
+ raise _DirectUrlRequiredKeyError(key)
63
+ return value
64
+
65
+
66
+ def _get_object(
67
+ d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str
68
+ ) -> _FromMappingProtocolT | None:
69
+ """Get a dictionary value from the dictionary and convert it to a dataclass."""
70
+ if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract]
71
+ return None
72
+ try:
73
+ return target_type._from_dict(value)
74
+ except Exception as e:
75
+ raise DirectUrlValidationError(e, context=key) from e
76
+
77
+
78
+ _PEP610_USER_PASS_ENV_VARS_REGEX = re.compile(
79
+ r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$"
80
+ )
81
+
82
+
83
+ def _strip_auth_from_netloc(netloc: str, safe_user_passwords: Collection[str]) -> str:
84
+ if "@" not in netloc:
85
+ return netloc
86
+ user_pass, netloc_no_user_pass = netloc.split("@", 1)
87
+ if user_pass in safe_user_passwords:
88
+ return netloc
89
+ if _PEP610_USER_PASS_ENV_VARS_REGEX.match(user_pass):
90
+ return netloc
91
+ return netloc_no_user_pass
92
+
93
+
94
+ def _strip_url(url: str, safe_user_passwords: Collection[str]) -> str:
95
+ """url with user:password part removed unless it is formed with
96
+ environment variables as specified in PEP 610, or it is a safe user:password
97
+ such as `git`.
98
+ """
99
+ parsed_url = urllib.parse.urlsplit(url)
100
+ netloc = _strip_auth_from_netloc(parsed_url.netloc, safe_user_passwords)
101
+ return urllib.parse.urlunsplit(
102
+ (
103
+ parsed_url.scheme,
104
+ netloc,
105
+ parsed_url.path,
106
+ parsed_url.query,
107
+ parsed_url.fragment,
108
+ )
109
+ )
110
+
111
+
112
+ class DirectUrlValidationError(Exception):
113
+ """Raised when when input data is not spec-compliant."""
114
+
115
+ context: str | None = None
116
+ message: str
117
+
118
+ def __init__(
119
+ self,
120
+ cause: str | Exception,
121
+ *,
122
+ context: str | None = None,
123
+ ) -> None:
124
+ if isinstance(cause, DirectUrlValidationError):
125
+ if cause.context:
126
+ self.context = (
127
+ f"{context}.{cause.context}" if context else cause.context
128
+ )
129
+ else:
130
+ self.context = context # pragma: no cover
131
+ self.message = cause.message
132
+ else:
133
+ self.context = context
134
+ self.message = str(cause)
135
+
136
+ def __str__(self) -> str:
137
+ if self.context:
138
+ return f"{self.message} in {self.context!r}"
139
+ return self.message
140
+
141
+
142
+ class _DirectUrlRequiredKeyError(DirectUrlValidationError):
143
+ def __init__(self, key: str) -> None:
144
+ super().__init__("Missing required value", context=key)
145
+
146
+
147
+ @dataclasses.dataclass(frozen=True, init=False)
148
+ class VcsInfo:
149
+ vcs: str
150
+ commit_id: str
151
+ requested_revision: str | None = None
152
+
153
+ def __init__(
154
+ self,
155
+ *,
156
+ vcs: str,
157
+ commit_id: str,
158
+ requested_revision: str | None = None,
159
+ ) -> None:
160
+ object.__setattr__(self, "vcs", vcs)
161
+ object.__setattr__(self, "commit_id", commit_id)
162
+ object.__setattr__(self, "requested_revision", requested_revision)
163
+
164
+ @classmethod
165
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
166
+ # We can't validate vcs value because is not closed.
167
+ return cls(
168
+ vcs=_get_required(d, str, "vcs"),
169
+ requested_revision=_get(d, str, "requested_revision"),
170
+ commit_id=_get_required(d, str, "commit_id"),
171
+ )
172
+
173
+
174
+ @dataclasses.dataclass(frozen=True, init=False)
175
+ class ArchiveInfo:
176
+ hashes: Mapping[str, str] | None = None
177
+
178
+ def __init__(
179
+ self,
180
+ *,
181
+ hashes: Mapping[str, str] | None = None,
182
+ ) -> None:
183
+ object.__setattr__(self, "hashes", hashes)
184
+
185
+ @classmethod
186
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
187
+ hashes = _get(d, Mapping, "hashes") # type: ignore[type-abstract]
188
+ if hashes is not None and not all(isinstance(h, str) for h in hashes.values()):
189
+ raise DirectUrlValidationError(
190
+ "Hash values must be strings", context="hashes"
191
+ )
192
+ legacy_hash = _get(d, str, "hash")
193
+ if legacy_hash is not None:
194
+ if "=" not in legacy_hash:
195
+ raise DirectUrlValidationError(
196
+ "Invalid hash format (expected '<algorithm>=<hash>')",
197
+ context="hash",
198
+ )
199
+ hash_algorithm, hash_value = legacy_hash.split("=", 1)
200
+ if hashes is None:
201
+ # if `hashes` are not present, we can derive it from the legacy `hash`
202
+ hashes = {hash_algorithm: hash_value}
203
+ else:
204
+ # if `hashes` are present, the legacy `hash` must match one of them
205
+ if hash_algorithm not in hashes:
206
+ raise DirectUrlValidationError(
207
+ f"Algorithm {hash_algorithm!r} used in hash field "
208
+ f"is not present in hashes field",
209
+ context="hashes",
210
+ )
211
+ if hashes[hash_algorithm] != hash_value:
212
+ raise DirectUrlValidationError(
213
+ f"Algorithm {hash_algorithm!r} used in hash field "
214
+ f"has different value in hashes field",
215
+ context="hash",
216
+ )
217
+ return cls(hashes=hashes)
218
+
219
+
220
+ @dataclasses.dataclass(frozen=True, init=False)
221
+ class DirInfo:
222
+ editable: bool | None = None
223
+
224
+ def __init__(
225
+ self,
226
+ *,
227
+ editable: bool | None = None,
228
+ ) -> None:
229
+ object.__setattr__(self, "editable", editable)
230
+
231
+ @classmethod
232
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
233
+ return cls(
234
+ editable=_get(d, bool, "editable"),
235
+ )
236
+
237
+
238
+ @dataclasses.dataclass(frozen=True, init=False)
239
+ class DirectUrl:
240
+ """A class representing a direct URL."""
241
+
242
+ url: str
243
+ archive_info: ArchiveInfo | None = None
244
+ vcs_info: VcsInfo | None = None
245
+ dir_info: DirInfo | None = None
246
+ subdirectory: str | None = None # XXX Path or str?
247
+
248
+ def __init__(
249
+ self,
250
+ *,
251
+ url: str,
252
+ archive_info: ArchiveInfo | None = None,
253
+ vcs_info: VcsInfo | None = None,
254
+ dir_info: DirInfo | None = None,
255
+ subdirectory: str | None = None,
256
+ ) -> None:
257
+ object.__setattr__(self, "url", url)
258
+ object.__setattr__(self, "archive_info", archive_info)
259
+ object.__setattr__(self, "vcs_info", vcs_info)
260
+ object.__setattr__(self, "dir_info", dir_info)
261
+ object.__setattr__(self, "subdirectory", subdirectory)
262
+
263
+ @classmethod
264
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
265
+ direct_url = cls(
266
+ url=_get_required(d, str, "url"),
267
+ archive_info=_get_object(d, ArchiveInfo, "archive_info"),
268
+ vcs_info=_get_object(d, VcsInfo, "vcs_info"),
269
+ dir_info=_get_object(d, DirInfo, "dir_info"),
270
+ subdirectory=_get(d, str, "subdirectory"),
271
+ )
272
+ if (
273
+ bool(direct_url.vcs_info)
274
+ + bool(direct_url.archive_info)
275
+ + bool(direct_url.dir_info)
276
+ ) != 1:
277
+ raise DirectUrlValidationError(
278
+ "Exactly one of vcs_info, archive_info, dir_info must be present"
279
+ )
280
+ if direct_url.dir_info is not None and not direct_url.url.startswith("file://"):
281
+ raise DirectUrlValidationError(
282
+ "URL scheme must be file:// when dir_info is present",
283
+ context="url",
284
+ )
285
+ # XXX subdirectory must be relative, can we, should we validate that here?
286
+ return direct_url
287
+
288
+ @classmethod
289
+ def from_dict(cls, d: Mapping[str, Any], /) -> Self:
290
+ """Create and validate a DirectUrl instance from a JSON dictionary."""
291
+ return cls._from_dict(d)
292
+
293
+ def to_dict(
294
+ self,
295
+ *,
296
+ generate_legacy_hash: bool = False,
297
+ strip_user_password: bool = True,
298
+ safe_user_passwords: Collection[str] = ("git",),
299
+ ) -> Mapping[str, Any]:
300
+ """Convert the DirectUrl instance to a JSON dictionary.
301
+
302
+ :param generate_legacy_hash: If True, include a legacy `hash` field in
303
+ `archive_info` for backward compatibility with tools that don't
304
+ support the `hashes` field.
305
+ :param strip_user_password: If True, strip user:password from the URL
306
+ unless it is formed with environment variables as specified in PEP
307
+ 610, or it is a safe user:password such as `git`.
308
+ :param safe_user_passwords: A collection of user:password strings that
309
+ should not be stripped from the URL even if `strip_user_password` is
310
+ True.
311
+ """
312
+ res = dataclasses.asdict(self, dict_factory=_json_dict_factory)
313
+ if generate_legacy_hash and self.archive_info and self.archive_info.hashes:
314
+ hash_algorithm, hash_value = next(iter(self.archive_info.hashes.items()))
315
+ res["archive_info"]["hash"] = f"{hash_algorithm}={hash_value}"
316
+ if strip_user_password:
317
+ res["url"] = _strip_url(self.url, safe_user_passwords)
318
+ return res
319
+
320
+ def validate(self) -> None:
321
+ """Validate the DirectUrl instance against the specification.
322
+
323
+ Raises :class:`DirectUrlValidationError` if invalid.
324
+ """
325
+ self.from_dict(self.to_dict())
.venv/lib/python3.11/site-packages/packaging/errors.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import dataclasses
5
+ import sys
6
+ import typing
7
+
8
+ __all__ = ["ExceptionGroup"]
9
+
10
+
11
+ def __dir__() -> list[str]:
12
+ return __all__
13
+
14
+
15
+ if sys.version_info >= (3, 11): # pragma: no cover
16
+ from builtins import ExceptionGroup
17
+ else: # pragma: no cover
18
+
19
+ class ExceptionGroup(Exception):
20
+ """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
21
+
22
+ If :external:exc:`ExceptionGroup` is already defined by Python itself,
23
+ that version is used instead.
24
+ """
25
+
26
+ message: str
27
+ exceptions: list[Exception]
28
+
29
+ def __init__(self, message: str, exceptions: list[Exception]) -> None:
30
+ self.message = message
31
+ self.exceptions = exceptions
32
+
33
+ def __repr__(self) -> str:
34
+ return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
35
+
36
+
37
+ @dataclasses.dataclass
38
+ class _ErrorCollector:
39
+ """
40
+ Collect errors into ExceptionGroups.
41
+
42
+ Used like this:
43
+
44
+ collector = _ErrorCollector()
45
+ # Add a single exception
46
+ collector.error(ValueError("one"))
47
+
48
+ # Supports nesting, including combining ExceptionGroups
49
+ with collector.collect():
50
+ raise ValueError("two")
51
+ collector.finalize("Found some errors")
52
+
53
+ Since making a collector and then calling finalize later is a common pattern,
54
+ a convenience method ``on_exit`` is provided.
55
+ """
56
+
57
+ errors: list[Exception] = dataclasses.field(default_factory=list, init=False)
58
+
59
+ def finalize(self, msg: str) -> None:
60
+ """Raise a group exception if there are any errors."""
61
+ if self.errors:
62
+ raise ExceptionGroup(msg, self.errors)
63
+
64
+ @contextlib.contextmanager
65
+ def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]:
66
+ """
67
+ Calls finalize if no uncollected errors were present.
68
+
69
+ Uncollected errors are raised normally.
70
+ """
71
+ yield self
72
+ self.finalize(msg)
73
+
74
+ @contextlib.contextmanager
75
+ def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]:
76
+ """
77
+ Context manager to collect errors into the error list.
78
+
79
+ Must be inside loops, as only one error can be collected at a time.
80
+ """
81
+ error_classes = err_cls or (Exception,)
82
+ try:
83
+ yield
84
+ except ExceptionGroup as error:
85
+ self.errors.extend(error.exceptions)
86
+ except error_classes as error:
87
+ self.errors.append(error)
88
+
89
+ def error(
90
+ self,
91
+ error: Exception,
92
+ ) -> None:
93
+ """Add an error to the list."""
94
+ self.errors.append(error)
.venv/lib/python3.11/site-packages/packaging/markers.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import operator
8
+ import os
9
+ import platform
10
+ import sys
11
+ from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast
12
+
13
+ from ._parser import MarkerAtom, MarkerList, Op, Value, Variable
14
+ from ._parser import parse_marker as _parse_marker
15
+ from ._tokenizer import ParserSyntaxError
16
+ from .specifiers import InvalidSpecifier, Specifier
17
+ from .utils import canonicalize_name
18
+
19
+ __all__ = [
20
+ "Environment",
21
+ "EvaluateContext",
22
+ "InvalidMarker",
23
+ "Marker",
24
+ "UndefinedComparison",
25
+ "UndefinedEnvironmentName",
26
+ "default_environment",
27
+ ]
28
+
29
+
30
+ def __dir__() -> list[str]:
31
+ return __all__
32
+
33
+
34
+ Operator = Callable[[str, Union[str, AbstractSet[str]]], bool]
35
+ EvaluateContext = Literal["metadata", "lock_file", "requirement"]
36
+ """A ``typing.Literal`` enumerating valid marker evaluation contexts.
37
+
38
+ Valid values for the ``context`` passed to :meth:`Marker.evaluate` are:
39
+
40
+ * ``"metadata"`` (for core metadata; default)
41
+ * ``"lock_file"`` (for lock files)
42
+ * ``"requirement"`` (i.e. all other situations)
43
+ """
44
+
45
+ MARKERS_ALLOWING_SET = {"extras", "dependency_groups"}
46
+ MARKERS_REQUIRING_VERSION = {
47
+ "implementation_version",
48
+ "platform_release",
49
+ "python_full_version",
50
+ "python_version",
51
+ }
52
+
53
+
54
+ class InvalidMarker(ValueError):
55
+ """Raised when attempting to create a :class:`Marker` from invalid input.
56
+
57
+ This error indicates that the given marker string does not conform to the
58
+ :ref:`specification of dependency specifiers <pypug:dependency-specifiers>`.
59
+ """
60
+
61
+
62
+ class UndefinedComparison(ValueError):
63
+ """Raised when evaluating an unsupported marker comparison.
64
+
65
+ This can happen when marker values are compared as versions but do not
66
+ conform to the :ref:`specification of version specifiers
67
+ <pypug:version-specifiers>`.
68
+ """
69
+
70
+
71
+ class UndefinedEnvironmentName(ValueError):
72
+ """Raised when evaluating a marker that references a missing environment key."""
73
+
74
+
75
+ class Environment(TypedDict):
76
+ """
77
+ A dictionary that represents a Python environment as captured by
78
+ :func:`default_environment`. All fields are required.
79
+ """
80
+
81
+ implementation_name: str
82
+ """The implementation's identifier, e.g. ``'cpython'``."""
83
+
84
+ implementation_version: str
85
+ """
86
+ The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or
87
+ ``'7.3.13'`` for PyPy3.10 v7.3.13.
88
+ """
89
+
90
+ os_name: str
91
+ """
92
+ The value of :py:data:`os.name`. The name of the operating system dependent module
93
+ imported, e.g. ``'posix'``.
94
+ """
95
+
96
+ platform_machine: str
97
+ """
98
+ Returns the machine type, e.g. ``'i386'``.
99
+
100
+ An empty string if the value cannot be determined.
101
+ """
102
+
103
+ platform_release: str
104
+ """
105
+ The system's release, e.g. ``'2.2.0'`` or ``'NT'``.
106
+
107
+ An empty string if the value cannot be determined.
108
+ """
109
+
110
+ platform_system: str
111
+ """
112
+ The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.
113
+
114
+ An empty string if the value cannot be determined.
115
+ """
116
+
117
+ platform_version: str
118
+ """
119
+ The system's release version, e.g. ``'#3 on degas'``.
120
+
121
+ An empty string if the value cannot be determined.
122
+ """
123
+
124
+ python_full_version: str
125
+ """
126
+ The Python version as string ``'major.minor.patchlevel'``.
127
+
128
+ Note that unlike the Python :py:data:`sys.version`, this value will always include
129
+ the patchlevel (it defaults to 0).
130
+ """
131
+
132
+ platform_python_implementation: str
133
+ """
134
+ A string identifying the Python implementation, e.g. ``'CPython'``.
135
+ """
136
+
137
+ python_version: str
138
+ """The Python version as string ``'major.minor'``."""
139
+
140
+ sys_platform: str
141
+ """
142
+ This string contains a platform identifier that can be used to append
143
+ platform-specific components to :py:data:`sys.path`, for instance.
144
+
145
+ For Unix systems, except on Linux and AIX, this is the lowercased OS name as
146
+ returned by ``uname -s`` with the first part of the version as returned by
147
+ ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python
148
+ was built.
149
+ """
150
+
151
+
152
+ def _normalize_extras(
153
+ result: MarkerList | MarkerAtom | str,
154
+ ) -> MarkerList | MarkerAtom | str:
155
+ if not isinstance(result, tuple):
156
+ return result
157
+
158
+ lhs, op, rhs = result
159
+ if isinstance(lhs, Variable) and lhs.value == "extra":
160
+ normalized_extra = canonicalize_name(rhs.value)
161
+ rhs = Value(normalized_extra)
162
+ elif isinstance(rhs, Variable) and rhs.value == "extra":
163
+ normalized_extra = canonicalize_name(lhs.value)
164
+ lhs = Value(normalized_extra)
165
+ return lhs, op, rhs
166
+
167
+
168
+ def _normalize_extra_values(results: MarkerList) -> MarkerList:
169
+ """
170
+ Normalize extra values.
171
+ """
172
+
173
+ return [_normalize_extras(r) for r in results]
174
+
175
+
176
+ def _format_marker(
177
+ marker: list[str] | MarkerAtom | str, first: bool | None = True
178
+ ) -> str:
179
+ assert isinstance(marker, (list, tuple, str))
180
+
181
+ # Sometimes we have a structure like [[...]] which is a single item list
182
+ # where the single item is itself it's own list. In that case we want skip
183
+ # the rest of this function so that we don't get extraneous () on the
184
+ # outside.
185
+ if (
186
+ isinstance(marker, list)
187
+ and len(marker) == 1
188
+ and isinstance(marker[0], (list, tuple))
189
+ ):
190
+ return _format_marker(marker[0])
191
+
192
+ if isinstance(marker, list):
193
+ inner = (_format_marker(m, first=False) for m in marker)
194
+ if first:
195
+ return " ".join(inner)
196
+ else:
197
+ return "(" + " ".join(inner) + ")"
198
+ elif isinstance(marker, tuple):
199
+ return " ".join([m.serialize() for m in marker])
200
+ else:
201
+ return marker
202
+
203
+
204
+ _operators: dict[str, Operator] = {
205
+ "in": lambda lhs, rhs: lhs in rhs,
206
+ "not in": lambda lhs, rhs: lhs not in rhs,
207
+ "<": lambda _lhs, _rhs: False,
208
+ "<=": operator.eq,
209
+ "==": operator.eq,
210
+ "!=": operator.ne,
211
+ ">=": operator.eq,
212
+ ">": lambda _lhs, _rhs: False,
213
+ }
214
+
215
+
216
+ def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool:
217
+ op_str = op.serialize()
218
+ if key in MARKERS_REQUIRING_VERSION:
219
+ try:
220
+ spec = Specifier(f"{op_str}{rhs}")
221
+ except InvalidSpecifier:
222
+ pass
223
+ else:
224
+ return spec.contains(lhs, prereleases=True)
225
+
226
+ oper: Operator | None = _operators.get(op_str)
227
+ if oper is None:
228
+ raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
229
+
230
+ return oper(lhs, rhs)
231
+
232
+
233
+ def _normalize(
234
+ lhs: str, rhs: str | AbstractSet[str], key: str
235
+ ) -> tuple[str, str | AbstractSet[str]]:
236
+ # PEP 685 - Comparison of extra names for optional distribution dependencies
237
+ # https://peps.python.org/pep-0685/
238
+ # > When comparing extra names, tools MUST normalize the names being
239
+ # > compared using the semantics outlined in PEP 503 for names
240
+ if key == "extra":
241
+ assert isinstance(rhs, str), "extra value must be a string"
242
+ # Both sides are normalized at this point already
243
+ return (lhs, rhs)
244
+ if key in MARKERS_ALLOWING_SET:
245
+ if isinstance(rhs, str): # pragma: no cover
246
+ return (canonicalize_name(lhs), canonicalize_name(rhs))
247
+ else:
248
+ return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs})
249
+
250
+ # other environment markers don't have such standards
251
+ return lhs, rhs
252
+
253
+
254
+ def _evaluate_markers(
255
+ markers: MarkerList, environment: dict[str, str | AbstractSet[str]]
256
+ ) -> bool:
257
+ groups: list[list[bool]] = [[]]
258
+
259
+ for marker in markers:
260
+ if isinstance(marker, list):
261
+ groups[-1].append(_evaluate_markers(marker, environment))
262
+ elif isinstance(marker, tuple):
263
+ lhs, op, rhs = marker
264
+
265
+ if isinstance(lhs, Variable):
266
+ environment_key = lhs.value
267
+ lhs_value = environment[environment_key]
268
+ rhs_value = rhs.value
269
+ else:
270
+ lhs_value = lhs.value
271
+ environment_key = rhs.value
272
+ rhs_value = environment[environment_key]
273
+
274
+ assert isinstance(lhs_value, str), "lhs must be a string"
275
+ lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)
276
+ groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key))
277
+ elif marker == "or":
278
+ groups.append([])
279
+ elif marker == "and":
280
+ pass
281
+ else: # pragma: nocover
282
+ raise TypeError(f"Unexpected marker {marker!r}")
283
+
284
+ return any(all(item) for item in groups)
285
+
286
+
287
+ def _format_full_version(info: sys._version_info) -> str:
288
+ version = f"{info.major}.{info.minor}.{info.micro}"
289
+ kind = info.releaselevel
290
+ if kind != "final":
291
+ version += kind[0] + str(info.serial)
292
+ return version
293
+
294
+
295
+ def default_environment() -> Environment:
296
+ """Return the default marker environment for the current Python process.
297
+
298
+ This is the base environment used by :meth:`Marker.evaluate`.
299
+ """
300
+ iver = _format_full_version(sys.implementation.version)
301
+ implementation_name = sys.implementation.name
302
+ return {
303
+ "implementation_name": implementation_name,
304
+ "implementation_version": iver,
305
+ "os_name": os.name,
306
+ "platform_machine": platform.machine(),
307
+ "platform_release": platform.release(),
308
+ "platform_system": platform.system(),
309
+ "platform_version": platform.version(),
310
+ "python_full_version": platform.python_version(),
311
+ "platform_python_implementation": platform.python_implementation(),
312
+ "python_version": ".".join(platform.python_version_tuple()[:2]),
313
+ "sys_platform": sys.platform,
314
+ }
315
+
316
+
317
+ class Marker:
318
+ """Represents a parsed dependency marker expression.
319
+
320
+ Marker expressions are parsed according to the
321
+ :ref:`specification of dependency specifiers <pypug:dependency-specifiers>`.
322
+
323
+ :param marker: The string representation of a marker expression.
324
+ :raises InvalidMarker: If ``marker`` cannot be parsed.
325
+
326
+ Instances are safe to serialize with :mod:`pickle`. They use a stable
327
+ format so the same pickle can be loaded in future packaging releases.
328
+
329
+ .. versionchanged:: 26.2
330
+
331
+ Added a stable pickle format. Pickles created with packaging 26.2+ can
332
+ be unpickled with future releases. Backward compatibility with pickles
333
+ from packaging < 26.2 is supported but may be removed in a future
334
+ release.
335
+ """
336
+
337
+ __slots__ = ("_markers",)
338
+
339
+ def __init__(self, marker: str) -> None:
340
+ # Note: We create a Marker object without calling this constructor in
341
+ # packaging.requirements.Requirement. If any additional logic is
342
+ # added here, make sure to mirror/adapt Requirement.
343
+
344
+ # If this fails and throws an error, the repr still expects _markers to
345
+ # be defined.
346
+ self._markers: MarkerList = []
347
+
348
+ try:
349
+ self._markers = _normalize_extra_values(_parse_marker(marker))
350
+ # The attribute `_markers` can be described in terms of a recursive type:
351
+ # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]
352
+ #
353
+ # For example, the following expression:
354
+ # python_version > "3.6" or (python_version == "3.6" and os_name == "unix")
355
+ #
356
+ # is parsed into:
357
+ # [
358
+ # (<Variable('python_version')>, <Op('>')>, <Value('3.6')>),
359
+ # 'and',
360
+ # [
361
+ # (<Variable('python_version')>, <Op('==')>, <Value('3.6')>),
362
+ # 'or',
363
+ # (<Variable('os_name')>, <Op('==')>, <Value('unix')>)
364
+ # ]
365
+ # ]
366
+ except ParserSyntaxError as e:
367
+ raise InvalidMarker(str(e)) from e
368
+
369
+ @classmethod
370
+ def _from_markers(cls, markers: MarkerList) -> Marker:
371
+ """Create a Marker instance from a pre-parsed marker tree.
372
+
373
+ This avoids re-parsing serialised marker strings when combining markers.
374
+ """
375
+ new = cls.__new__(cls)
376
+ new._markers = markers
377
+ return new
378
+
379
+ def __str__(self) -> str:
380
+ return _format_marker(self._markers)
381
+
382
+ def __repr__(self) -> str:
383
+ return f"<{self.__class__.__name__}({str(self)!r})>"
384
+
385
+ def __hash__(self) -> int:
386
+ return hash(str(self))
387
+
388
+ def __eq__(self, other: object) -> bool:
389
+ if not isinstance(other, Marker):
390
+ return NotImplemented
391
+
392
+ return str(self) == str(other)
393
+
394
+ def __getstate__(self) -> str:
395
+ # Return the marker expression string for compactness and stability.
396
+ # Internal Node objects are excluded; the string is re-parsed on load.
397
+ return str(self)
398
+
399
+ def __setstate__(self, state: object) -> None:
400
+ if isinstance(state, str):
401
+ # New format (26.2+): just the marker expression string.
402
+ try:
403
+ self._markers = _normalize_extra_values(_parse_marker(state))
404
+ except ParserSyntaxError as exc:
405
+ raise TypeError(f"Cannot restore Marker from {state!r}") from exc
406
+ return
407
+ if isinstance(state, dict) and "_markers" in state:
408
+ # Old format (packaging <= 26.1, no __slots__): plain __dict__.
409
+ markers = state["_markers"]
410
+ if isinstance(markers, list):
411
+ self._markers = markers
412
+ return
413
+ if isinstance(state, tuple) and len(state) == 2:
414
+ # Old format (packaging <= 26.1, __slots__): (None, {slot: value}).
415
+ _, slot_dict = state
416
+ if isinstance(slot_dict, dict) and "_markers" in slot_dict:
417
+ markers = slot_dict["_markers"]
418
+ if isinstance(markers, list):
419
+ self._markers = markers
420
+ return
421
+ raise TypeError(f"Cannot restore Marker from {state!r}")
422
+
423
+ def __and__(self, other: Marker) -> Marker:
424
+ if not isinstance(other, Marker):
425
+ return NotImplemented
426
+ return self._from_markers([self._markers, "and", other._markers])
427
+
428
+ def __or__(self, other: Marker) -> Marker:
429
+ if not isinstance(other, Marker):
430
+ return NotImplemented
431
+ return self._from_markers([self._markers, "or", other._markers])
432
+
433
+ def evaluate(
434
+ self,
435
+ environment: Mapping[str, str | AbstractSet[str]] | None = None,
436
+ context: EvaluateContext = "metadata",
437
+ ) -> bool:
438
+ """Evaluate a marker.
439
+
440
+ Return the boolean from evaluating this marker against the environment.
441
+ The environment is determined from the current Python process unless
442
+ passed in explicitly.
443
+
444
+ :param environment: Mapping containing keys and values to override the
445
+ detected environment.
446
+ :param EvaluateContext context: The context in which the marker is
447
+ evaluated, which influences what marker names are considered valid.
448
+ Accepted values are ``"metadata"`` (for core metadata; default),
449
+ ``"lock_file"``, and ``"requirement"`` (i.e. all other situations).
450
+ :raises UndefinedComparison: If the marker uses a comparison on values
451
+ that are not valid versions per the :ref:`specification of version
452
+ specifiers <pypug:version-specifiers>`.
453
+ :raises UndefinedEnvironmentName: If the marker references a value that
454
+ is missing from the evaluation environment.
455
+ :returns: ``True`` if the marker matches, otherwise ``False``.
456
+
457
+ """
458
+ current_environment = cast(
459
+ "dict[str, str | AbstractSet[str]]", default_environment()
460
+ )
461
+ if context == "lock_file":
462
+ current_environment.update(
463
+ extras=frozenset(), dependency_groups=frozenset()
464
+ )
465
+ elif context == "metadata":
466
+ current_environment["extra"] = ""
467
+
468
+ if environment is not None:
469
+ current_environment.update(environment)
470
+ if "extra" in current_environment:
471
+ # The API used to allow setting extra to None. We need to handle
472
+ # this case for backwards compatibility. Also skip running
473
+ # normalize name if extra is empty.
474
+ extra = cast("str | None", current_environment["extra"])
475
+ current_environment["extra"] = canonicalize_name(extra) if extra else ""
476
+
477
+ return _evaluate_markers(
478
+ self._markers, _repair_python_full_version(current_environment)
479
+ )
480
+
481
+
482
+ def _repair_python_full_version(
483
+ env: dict[str, str | AbstractSet[str]],
484
+ ) -> dict[str, str | AbstractSet[str]]:
485
+ """
486
+ Work around platform.python_version() returning something that is not PEP 440
487
+ compliant for non-tagged Python builds.
488
+ """
489
+ python_full_version = cast("str", env["python_full_version"])
490
+ if python_full_version.endswith("+"):
491
+ env["python_full_version"] = f"{python_full_version}local"
492
+ return env
.venv/lib/python3.11/site-packages/packaging/metadata.py ADDED
@@ -0,0 +1,964 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import email.header
4
+ import email.message
5
+ import email.parser
6
+ import email.policy
7
+ import keyword
8
+ import pathlib
9
+ import typing
10
+ from typing import (
11
+ Any,
12
+ Callable,
13
+ Generic,
14
+ Literal,
15
+ TypedDict,
16
+ cast,
17
+ )
18
+
19
+ from . import licenses, requirements, specifiers, utils
20
+ from . import version as version_module
21
+ from .errors import ExceptionGroup, _ErrorCollector
22
+
23
+ if typing.TYPE_CHECKING:
24
+ from .licenses import NormalizedLicenseExpression
25
+
26
+ T = typing.TypeVar("T")
27
+
28
+
29
+ __all__ = [
30
+ "ExceptionGroup", # Keep this for a bit (makes mypy happy w/ 26.0 compat)
31
+ "InvalidMetadata",
32
+ "Metadata",
33
+ "RFC822Message",
34
+ "RFC822Policy",
35
+ "RawMetadata",
36
+ "parse_email",
37
+ ]
38
+
39
+
40
+ def __dir__() -> list[str]:
41
+ return __all__
42
+
43
+
44
+ class InvalidMetadata(ValueError):
45
+ """A metadata field contains invalid data."""
46
+
47
+ field: str
48
+ """The name of the field that contains invalid data."""
49
+
50
+ def __init__(self, field: str, message: str) -> None:
51
+ self.field = field
52
+ super().__init__(message)
53
+
54
+
55
+ # The RawMetadata class attempts to make as few assumptions about the underlying
56
+ # serialization formats as possible. The idea is that as long as a serialization
57
+ # formats offer some very basic primitives in *some* way then we can support
58
+ # serializing to and from that format.
59
+ class RawMetadata(TypedDict, total=False):
60
+ """A dictionary of raw core metadata.
61
+
62
+ Each field in core metadata maps to a key of this dictionary (when data is
63
+ provided). The key is lower-case and underscores are used instead of dashes
64
+ compared to the equivalent core metadata field. Any core metadata field that
65
+ can be specified multiple times or can hold multiple values in a single
66
+ field have a key with a plural name. See :class:`Metadata` whose attributes
67
+ match the keys of this dictionary.
68
+
69
+ Core metadata fields that can be specified multiple times are stored as a
70
+ list or dict depending on which is appropriate for the field. Any fields
71
+ which hold multiple values in a single field are stored as a list. All fields
72
+ are considered optional.
73
+ """
74
+
75
+ # Metadata 1.0 - PEP 241
76
+ metadata_version: str
77
+ name: str
78
+ version: str
79
+ platforms: list[str]
80
+ summary: str
81
+ description: str
82
+ keywords: list[str]
83
+ home_page: str
84
+ author: str
85
+ author_email: str
86
+ license: str
87
+
88
+ # Metadata 1.1 - PEP 314
89
+ supported_platforms: list[str]
90
+ download_url: str
91
+ classifiers: list[str]
92
+ requires: list[str]
93
+ provides: list[str]
94
+ obsoletes: list[str]
95
+
96
+ # Metadata 1.2 - PEP 345
97
+ maintainer: str
98
+ maintainer_email: str
99
+ requires_dist: list[str]
100
+ provides_dist: list[str]
101
+ obsoletes_dist: list[str]
102
+ requires_python: str
103
+ requires_external: list[str]
104
+ project_urls: dict[str, str]
105
+
106
+ # Metadata 2.0
107
+ # PEP 426 attempted to completely revamp the metadata format
108
+ # but got stuck without ever being able to build consensus on
109
+ # it and ultimately ended up withdrawn.
110
+ #
111
+ # However, a number of tools had started emitting METADATA with
112
+ # `2.0` Metadata-Version, so for historical reasons, this version
113
+ # was skipped.
114
+
115
+ # Metadata 2.1 - PEP 566
116
+ description_content_type: str
117
+ provides_extra: list[str]
118
+
119
+ # Metadata 2.2 - PEP 643
120
+ dynamic: list[str]
121
+
122
+ # Metadata 2.3 - PEP 685
123
+ # No new fields were added in PEP 685, just some edge case were
124
+ # tightened up to provide better interoperability.
125
+
126
+ # Metadata 2.4 - PEP 639
127
+ license_expression: str
128
+ license_files: list[str]
129
+
130
+ # Metadata 2.5 - PEP 794
131
+ import_names: list[str]
132
+ import_namespaces: list[str]
133
+
134
+
135
+ # 'keywords' is special as it's a string in the core metadata spec, but we
136
+ # represent it as a list.
137
+ _STRING_FIELDS = {
138
+ "author",
139
+ "author_email",
140
+ "description",
141
+ "description_content_type",
142
+ "download_url",
143
+ "home_page",
144
+ "license",
145
+ "license_expression",
146
+ "maintainer",
147
+ "maintainer_email",
148
+ "metadata_version",
149
+ "name",
150
+ "requires_python",
151
+ "summary",
152
+ "version",
153
+ }
154
+
155
+ _LIST_FIELDS = {
156
+ "classifiers",
157
+ "dynamic",
158
+ "license_files",
159
+ "obsoletes",
160
+ "obsoletes_dist",
161
+ "platforms",
162
+ "provides",
163
+ "provides_dist",
164
+ "provides_extra",
165
+ "requires",
166
+ "requires_dist",
167
+ "requires_external",
168
+ "supported_platforms",
169
+ "import_names",
170
+ "import_namespaces",
171
+ }
172
+
173
+ _DICT_FIELDS = {
174
+ "project_urls",
175
+ }
176
+
177
+
178
+ def _parse_keywords(data: str) -> list[str]:
179
+ """Split a string of comma-separated keywords into a list of keywords."""
180
+ return [k.strip() for k in data.split(",")]
181
+
182
+
183
+ def _parse_project_urls(data: list[str]) -> dict[str, str]:
184
+ """Parse a list of label/URL string pairings separated by a comma."""
185
+ urls = {}
186
+ for pair in data:
187
+ # Our logic is slightly tricky here as we want to try and do
188
+ # *something* reasonable with malformed data.
189
+ #
190
+ # The main thing that we have to worry about, is data that does
191
+ # not have a ',' at all to split the label from the Value. There
192
+ # isn't a singular right answer here, and we will fail validation
193
+ # later on (if the caller is validating) so it doesn't *really*
194
+ # matter, but since the missing value has to be an empty str
195
+ # and our return value is dict[str, str], if we let the key
196
+ # be the missing value, then they'd have multiple '' values that
197
+ # overwrite each other in a accumulating dict.
198
+ #
199
+ # The other potential issue is that it's possible to have the
200
+ # same label multiple times in the metadata, with no solid "right"
201
+ # answer with what to do in that case. As such, we'll do the only
202
+ # thing we can, which is treat the field as unparsable and add it
203
+ # to our list of unparsed fields.
204
+ #
205
+ # TODO: The spec doesn't say anything about if the keys should be
206
+ # considered case sensitive or not... logically they should
207
+ # be case-preserving and case-insensitive, but doing that
208
+ # would open up more cases where we might have duplicate
209
+ # entries.
210
+ label, _, url = (s.strip() for s in pair.partition(","))
211
+
212
+ if label in urls:
213
+ # The label already exists in our set of urls, so this field
214
+ # is unparsable, and we can just add the whole thing to our
215
+ # unparsable data and stop processing it.
216
+ raise KeyError("duplicate labels in project urls")
217
+ urls[label] = url
218
+
219
+ return urls
220
+
221
+
222
+ def _get_payload(msg: email.message.Message, source: bytes | str) -> str:
223
+ """Get the body of the message."""
224
+ # If our source is a str, then our caller has managed encodings for us,
225
+ # and we don't need to deal with it.
226
+ if isinstance(source, str):
227
+ payload = msg.get_payload()
228
+ assert isinstance(payload, str)
229
+ return payload
230
+ # If our source is a bytes, then we're managing the encoding and we need
231
+ # to deal with it.
232
+ else:
233
+ bpayload = msg.get_payload(decode=True)
234
+ assert isinstance(bpayload, bytes)
235
+ try:
236
+ return bpayload.decode("utf8", "strict")
237
+ except UnicodeDecodeError as exc:
238
+ raise ValueError("payload in an invalid encoding") from exc
239
+
240
+
241
+ # The various parse_FORMAT functions here are intended to be as lenient as
242
+ # possible in their parsing, while still returning a correctly typed
243
+ # RawMetadata.
244
+ #
245
+ # To aid in this, we also generally want to do as little touching of the
246
+ # data as possible, except where there are possibly some historic holdovers
247
+ # that make valid data awkward to work with.
248
+ #
249
+ # While this is a lower level, intermediate format than our ``Metadata``
250
+ # class, some light touch ups can make a massive difference in usability.
251
+
252
+ # Map METADATA fields to RawMetadata.
253
+ _EMAIL_TO_RAW_MAPPING = {
254
+ "author": "author",
255
+ "author-email": "author_email",
256
+ "classifier": "classifiers",
257
+ "description": "description",
258
+ "description-content-type": "description_content_type",
259
+ "download-url": "download_url",
260
+ "dynamic": "dynamic",
261
+ "home-page": "home_page",
262
+ "import-name": "import_names",
263
+ "import-namespace": "import_namespaces",
264
+ "keywords": "keywords",
265
+ "license": "license",
266
+ "license-expression": "license_expression",
267
+ "license-file": "license_files",
268
+ "maintainer": "maintainer",
269
+ "maintainer-email": "maintainer_email",
270
+ "metadata-version": "metadata_version",
271
+ "name": "name",
272
+ "obsoletes": "obsoletes",
273
+ "obsoletes-dist": "obsoletes_dist",
274
+ "platform": "platforms",
275
+ "project-url": "project_urls",
276
+ "provides": "provides",
277
+ "provides-dist": "provides_dist",
278
+ "provides-extra": "provides_extra",
279
+ "requires": "requires",
280
+ "requires-dist": "requires_dist",
281
+ "requires-external": "requires_external",
282
+ "requires-python": "requires_python",
283
+ "summary": "summary",
284
+ "supported-platform": "supported_platforms",
285
+ "version": "version",
286
+ }
287
+ _RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
288
+
289
+
290
+ # This class is for writing RFC822 messages
291
+ class RFC822Policy(email.policy.EmailPolicy):
292
+ """
293
+ This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse``
294
+ implementation that handles multi-line values, and some nice defaults.
295
+ """
296
+
297
+ utf8 = True
298
+ mangle_from_ = False
299
+ max_line_length = 0
300
+
301
+ def header_store_parse(self, name: str, value: str) -> tuple[str, str]:
302
+ size = len(name) + 2
303
+ value = value.replace("\n", "\n" + " " * size)
304
+ return (name, value)
305
+
306
+
307
+ # This class is for writing RFC822 messages
308
+ class RFC822Message(email.message.EmailMessage):
309
+ """
310
+ This is :class:`email.message.EmailMessage` with two small changes: it defaults to
311
+ our `RFC822Policy`, and it correctly writes unicode when being called
312
+ with `bytes()`.
313
+ """
314
+
315
+ def __init__(self) -> None:
316
+ super().__init__(policy=RFC822Policy())
317
+
318
+ def as_bytes(
319
+ self, unixfrom: bool = False, policy: email.policy.Policy | None = None
320
+ ) -> bytes:
321
+ """
322
+ Return the bytes representation of the message.
323
+
324
+ This handles unicode encoding.
325
+ """
326
+ return self.as_string(unixfrom, policy=policy).encode("utf-8")
327
+
328
+
329
+ def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]:
330
+ """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
331
+
332
+ This function returns a two-item tuple of dicts. The first dict is of
333
+ recognized fields from the core metadata specification. Fields that can be
334
+ parsed and translated into Python's built-in types are converted
335
+ appropriately. All other fields are left as-is. Fields that are allowed to
336
+ appear multiple times are stored as lists.
337
+
338
+ The second dict contains all other fields from the metadata. This includes
339
+ any unrecognized fields. It also includes any fields which are expected to
340
+ be parsed into a built-in type but were not formatted appropriately. Finally,
341
+ any fields that are expected to appear only once but are repeated are
342
+ included in this dict.
343
+
344
+ """
345
+ raw: dict[str, str | list[str] | dict[str, str]] = {}
346
+ unparsed: dict[str, list[str]] = {}
347
+
348
+ if isinstance(data, str):
349
+ parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data)
350
+ else:
351
+ parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)
352
+
353
+ # We have to wrap parsed.keys() in a set, because in the case of multiple
354
+ # values for a key (a list), the key will appear multiple times in the
355
+ # list of keys, but we're avoiding that by using get_all().
356
+ for name_with_case in frozenset(parsed.keys()):
357
+ # Header names in RFC are case insensitive, so we'll normalize to all
358
+ # lower case to make comparisons easier.
359
+ name = name_with_case.lower()
360
+
361
+ # We use get_all() here, even for fields that aren't multiple use,
362
+ # because otherwise someone could have e.g. two Name fields, and we
363
+ # would just silently ignore it rather than doing something about it.
364
+ headers = parsed.get_all(name) or []
365
+
366
+ # The way the email module works when parsing bytes is that it
367
+ # unconditionally decodes the bytes as ascii using the surrogateescape
368
+ # handler. When you pull that data back out (such as with get_all() ),
369
+ # it looks to see if the str has any surrogate escapes, and if it does
370
+ # it wraps it in a Header object instead of returning the string.
371
+ #
372
+ # As such, we'll look for those Header objects, and fix up the encoding.
373
+ value = []
374
+ # Flag if we have run into any issues processing the headers, thus
375
+ # signalling that the data belongs in 'unparsed'.
376
+ valid_encoding = True
377
+ for h in headers:
378
+ # It's unclear if this can return more types than just a Header or
379
+ # a str, so we'll just assert here to make sure.
380
+ assert isinstance(h, (email.header.Header, str))
381
+
382
+ # If it's a header object, we need to do our little dance to get
383
+ # the real data out of it. In cases where there is invalid data
384
+ # we're going to end up with mojibake, but there's no obvious, good
385
+ # way around that without reimplementing parts of the Header object
386
+ # ourselves.
387
+ #
388
+ # That should be fine since, if mojibacked happens, this key is
389
+ # going into the unparsed dict anyways.
390
+ if isinstance(h, email.header.Header):
391
+ # The Header object stores it's data as chunks, and each chunk
392
+ # can be independently encoded, so we'll need to check each
393
+ # of them.
394
+ chunks: list[tuple[bytes, str | None]] = []
395
+ for binary, _encoding in email.header.decode_header(h):
396
+ try:
397
+ binary.decode("utf8", "strict")
398
+ except UnicodeDecodeError:
399
+ # Enable mojibake.
400
+ encoding = "latin1"
401
+ valid_encoding = False
402
+ else:
403
+ encoding = "utf8"
404
+ chunks.append((binary, encoding))
405
+
406
+ # Turn our chunks back into a Header object, then let that
407
+ # Header object do the right thing to turn them into a
408
+ # string for us.
409
+ value.append(str(email.header.make_header(chunks)))
410
+ # This is already a string, so just add it.
411
+ else:
412
+ value.append(h)
413
+
414
+ # We've processed all of our values to get them into a list of str,
415
+ # but we may have mojibake data, in which case this is an unparsed
416
+ # field.
417
+ if not valid_encoding:
418
+ unparsed[name] = value
419
+ continue
420
+
421
+ raw_name = _EMAIL_TO_RAW_MAPPING.get(name)
422
+ if raw_name is None:
423
+ # This is a bit of a weird situation, we've encountered a key that
424
+ # we don't know what it means, so we don't know whether it's meant
425
+ # to be a list or not.
426
+ #
427
+ # Since we can't really tell one way or another, we'll just leave it
428
+ # as a list, even though it may be a single item list, because that's
429
+ # what makes the most sense for email headers.
430
+ unparsed[name] = value
431
+ continue
432
+
433
+ # If this is one of our string fields, then we'll check to see if our
434
+ # value is a list of a single item. If it is then we'll assume that
435
+ # it was emitted as a single string, and unwrap the str from inside
436
+ # the list.
437
+ #
438
+ # If it's any other kind of data, then we haven't the faintest clue
439
+ # what we should parse it as, and we have to just add it to our list
440
+ # of unparsed stuff.
441
+ if raw_name in _STRING_FIELDS and len(value) == 1:
442
+ raw[raw_name] = value[0]
443
+ # If this is import_names, we need to special case the empty field
444
+ # case, which converts to an empty list instead of None. We can't let
445
+ # the empty case slip through, as it will fail validation.
446
+ elif raw_name == "import_names" and value == [""]:
447
+ raw[raw_name] = []
448
+ # If this is one of our list of string fields, then we can just assign
449
+ # the value, since email *only* has strings, and our get_all() call
450
+ # above ensures that this is a list.
451
+ elif raw_name in _LIST_FIELDS:
452
+ raw[raw_name] = value
453
+ # Special Case: Keywords
454
+ # The keywords field is implemented in the metadata spec as a str,
455
+ # but it conceptually is a list of strings, and is serialized using
456
+ # ", ".join(keywords), so we'll do some light data massaging to turn
457
+ # this into what it logically is.
458
+ elif raw_name == "keywords" and len(value) == 1:
459
+ raw[raw_name] = _parse_keywords(value[0])
460
+ # Special Case: Project-URL
461
+ # The project urls is implemented in the metadata spec as a list of
462
+ # specially-formatted strings that represent a key and a value, which
463
+ # is fundamentally a mapping, however the email format doesn't support
464
+ # mappings in a sane way, so it was crammed into a list of strings
465
+ # instead.
466
+ #
467
+ # We will do a little light data massaging to turn this into a map as
468
+ # it logically should be.
469
+ elif raw_name == "project_urls":
470
+ try:
471
+ raw[raw_name] = _parse_project_urls(value)
472
+ except KeyError:
473
+ unparsed[name] = value
474
+ # Nothing that we've done has managed to parse this, so it'll just
475
+ # throw it in our unparsable data and move on.
476
+ else:
477
+ unparsed[name] = value
478
+
479
+ # We need to support getting the Description from the message payload in
480
+ # addition to getting it from the the headers. This does mean, though, there
481
+ # is the possibility of it being set both ways, in which case we put both
482
+ # in 'unparsed' since we don't know which is right.
483
+ try:
484
+ payload = _get_payload(parsed, data)
485
+ except ValueError:
486
+ unparsed.setdefault("description", []).append(
487
+ parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload]
488
+ )
489
+ else:
490
+ if payload:
491
+ # Check to see if we've already got a description, if so then both
492
+ # it, and this body move to unparsable.
493
+ if "description" in raw:
494
+ description_header = cast("str", raw.pop("description"))
495
+ unparsed.setdefault("description", []).extend(
496
+ [description_header, payload]
497
+ )
498
+ elif "description" in unparsed:
499
+ unparsed["description"].append(payload)
500
+ else:
501
+ raw["description"] = payload
502
+
503
+ # We need to cast our `raw` to a metadata, because a TypedDict only support
504
+ # literal key names, but we're computing our key names on purpose, but the
505
+ # way this function is implemented, our `TypedDict` can only have valid key
506
+ # names.
507
+ return cast("RawMetadata", raw), unparsed
508
+
509
+
510
+ _NOT_FOUND = object()
511
+
512
+
513
+ # Keep the two values in sync.
514
+ _VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
515
+ _MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"]
516
+
517
+ _REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
518
+
519
+
520
+ class _Validator(Generic[T]):
521
+ """Validate a metadata field.
522
+
523
+ All _process_*() methods correspond to a core metadata field. The method is
524
+ called with the field's raw value. If the raw value is valid it is returned
525
+ in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field).
526
+ If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause
527
+ as appropriate).
528
+ """
529
+
530
+ name: str
531
+ raw_name: str
532
+ added: _MetadataVersion
533
+
534
+ def __init__(
535
+ self,
536
+ *,
537
+ added: _MetadataVersion = "1.0",
538
+ ) -> None:
539
+ self.added = added
540
+
541
+ def __set_name__(self, _owner: Metadata, name: str) -> None:
542
+ self.name = name
543
+ self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
544
+
545
+ def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T:
546
+ # With Python 3.8, the caching can be replaced with functools.cached_property().
547
+ # No need to check the cache as attribute lookup will resolve into the
548
+ # instance's __dict__ before __get__ is called.
549
+ cache = instance.__dict__
550
+ value = instance._raw.get(self.name)
551
+
552
+ # To make the _process_* methods easier, we'll check if the value is None
553
+ # and if this field is NOT a required attribute, and if both of those
554
+ # things are true, we'll skip the the converter. This will mean that the
555
+ # converters never have to deal with the None union.
556
+ if self.name in _REQUIRED_ATTRS or value is not None:
557
+ try:
558
+ converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}")
559
+ except AttributeError:
560
+ pass
561
+ else:
562
+ value = converter(value)
563
+
564
+ cache[self.name] = value
565
+ try:
566
+ del instance._raw[self.name] # type: ignore[misc]
567
+ except KeyError:
568
+ pass
569
+
570
+ return cast("T", value)
571
+
572
+ def _invalid_metadata(
573
+ self, msg: str, cause: Exception | None = None
574
+ ) -> InvalidMetadata:
575
+ exc = InvalidMetadata(
576
+ self.raw_name, msg.format_map({"field": repr(self.raw_name)})
577
+ )
578
+ exc.__cause__ = cause
579
+ return exc
580
+
581
+ def _process_metadata_version(self, value: str) -> _MetadataVersion:
582
+ # Implicitly makes Metadata-Version required.
583
+ if value not in _VALID_METADATA_VERSIONS:
584
+ raise self._invalid_metadata(f"{value!r} is not a valid metadata version")
585
+ return cast("_MetadataVersion", value)
586
+
587
+ def _process_name(self, value: str) -> str:
588
+ if not value:
589
+ raise self._invalid_metadata("{field} is a required field")
590
+ # Validate the name as a side-effect.
591
+ try:
592
+ utils.canonicalize_name(value, validate=True)
593
+ except utils.InvalidName as exc:
594
+ raise self._invalid_metadata(
595
+ f"{value!r} is invalid for {{field}}", cause=exc
596
+ ) from exc
597
+ else:
598
+ return value
599
+
600
+ def _process_version(self, value: str) -> version_module.Version:
601
+ if not value:
602
+ raise self._invalid_metadata("{field} is a required field")
603
+ try:
604
+ return version_module.parse(value)
605
+ except version_module.InvalidVersion as exc:
606
+ raise self._invalid_metadata(
607
+ f"{value!r} is invalid for {{field}}", cause=exc
608
+ ) from exc
609
+
610
+ def _process_summary(self, value: str) -> str:
611
+ """Check the field contains no newlines."""
612
+ if "\n" in value:
613
+ raise self._invalid_metadata("{field} must be a single line")
614
+ return value
615
+
616
+ def _process_description_content_type(self, value: str) -> str:
617
+ content_types = {"text/plain", "text/x-rst", "text/markdown"}
618
+ message = email.message.EmailMessage()
619
+ message["content-type"] = value
620
+
621
+ content_type, parameters = (
622
+ # Defaults to `text/plain` if parsing failed.
623
+ message.get_content_type().lower(),
624
+ message["content-type"].params,
625
+ )
626
+ # Check if content-type is valid or defaulted to `text/plain` and thus was
627
+ # not parseable.
628
+ if content_type not in content_types or content_type not in value.lower():
629
+ raise self._invalid_metadata(
630
+ f"{{field}} must be one of {list(content_types)}, not {value!r}"
631
+ )
632
+
633
+ charset = parameters.get("charset", "UTF-8")
634
+ if charset != "UTF-8":
635
+ raise self._invalid_metadata(
636
+ f"{{field}} can only specify the UTF-8 charset, not {charset!r}"
637
+ )
638
+
639
+ markdown_variants = {"GFM", "CommonMark"}
640
+ variant = parameters.get("variant", "GFM") # Use an acceptable default.
641
+ if content_type == "text/markdown" and variant not in markdown_variants:
642
+ raise self._invalid_metadata(
643
+ f"valid Markdown variants for {{field}} are {list(markdown_variants)}, "
644
+ f"not {variant!r}",
645
+ )
646
+ return value
647
+
648
+ def _process_dynamic(self, value: list[str]) -> list[str]:
649
+ for dynamic_field in map(str.lower, value):
650
+ if dynamic_field in {"name", "version", "metadata-version"}:
651
+ raise self._invalid_metadata(
652
+ f"{dynamic_field!r} is not allowed as a dynamic field"
653
+ )
654
+ elif dynamic_field not in _EMAIL_TO_RAW_MAPPING:
655
+ raise self._invalid_metadata(
656
+ f"{dynamic_field!r} is not a valid dynamic field"
657
+ )
658
+ return list(map(str.lower, value))
659
+
660
+ def _process_provides_extra(
661
+ self,
662
+ value: list[str],
663
+ ) -> list[utils.NormalizedName]:
664
+ normalized_names = []
665
+ try:
666
+ for name in value:
667
+ normalized_names.append(utils.canonicalize_name(name, validate=True))
668
+ except utils.InvalidName as exc:
669
+ raise self._invalid_metadata(
670
+ f"{name!r} is invalid for {{field}}", cause=exc
671
+ ) from exc
672
+ else:
673
+ return normalized_names
674
+
675
+ def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:
676
+ try:
677
+ return specifiers.SpecifierSet(value)
678
+ except specifiers.InvalidSpecifier as exc:
679
+ raise self._invalid_metadata(
680
+ f"{value!r} is invalid for {{field}}", cause=exc
681
+ ) from exc
682
+
683
+ def _process_requires_dist(
684
+ self,
685
+ value: list[str],
686
+ ) -> list[requirements.Requirement]:
687
+ reqs = []
688
+ try:
689
+ for req in value:
690
+ reqs.append(requirements.Requirement(req))
691
+ except requirements.InvalidRequirement as exc:
692
+ raise self._invalid_metadata(
693
+ f"{req!r} is invalid for {{field}}", cause=exc
694
+ ) from exc
695
+ else:
696
+ return reqs
697
+
698
+ def _process_license_expression(self, value: str) -> NormalizedLicenseExpression:
699
+ try:
700
+ return licenses.canonicalize_license_expression(value)
701
+ except ValueError as exc:
702
+ raise self._invalid_metadata(
703
+ f"{value!r} is invalid for {{field}}", cause=exc
704
+ ) from exc
705
+
706
+ def _process_license_files(self, value: list[str]) -> list[str]:
707
+ paths = []
708
+ for path in value:
709
+ if ".." in path:
710
+ raise self._invalid_metadata(
711
+ f"{path!r} is invalid for {{field}}, "
712
+ "parent directory indicators are not allowed"
713
+ )
714
+ if "*" in path:
715
+ raise self._invalid_metadata(
716
+ f"{path!r} is invalid for {{field}}, paths must be resolved"
717
+ )
718
+ if (
719
+ pathlib.PurePosixPath(path).is_absolute()
720
+ or pathlib.PureWindowsPath(path).is_absolute()
721
+ ):
722
+ raise self._invalid_metadata(
723
+ f"{path!r} is invalid for {{field}}, paths must be relative"
724
+ )
725
+ if pathlib.PureWindowsPath(path).as_posix() != path:
726
+ raise self._invalid_metadata(
727
+ f"{path!r} is invalid for {{field}}, paths must use '/' delimiter"
728
+ )
729
+ paths.append(path)
730
+ return paths
731
+
732
+ def _process_import_names(self, value: list[str]) -> list[str]:
733
+ for import_name in value:
734
+ name, semicolon, private = import_name.partition(";")
735
+ name = name.rstrip()
736
+ for identifier in name.split("."):
737
+ if not identifier.isidentifier():
738
+ raise self._invalid_metadata(
739
+ f"{name!r} is invalid for {{field}}; "
740
+ f"{identifier!r} is not a valid identifier"
741
+ )
742
+ elif keyword.iskeyword(identifier):
743
+ raise self._invalid_metadata(
744
+ f"{name!r} is invalid for {{field}}; "
745
+ f"{identifier!r} is a keyword"
746
+ )
747
+ if semicolon and private.lstrip() != "private":
748
+ raise self._invalid_metadata(
749
+ f"{import_name!r} is invalid for {{field}}; "
750
+ "the only valid option is 'private'"
751
+ )
752
+ return value
753
+
754
+ _process_import_namespaces = _process_import_names
755
+
756
+
757
+ class Metadata:
758
+ """Representation of distribution metadata.
759
+
760
+ Compared to :class:`RawMetadata`, this class provides objects representing
761
+ metadata fields instead of only using built-in types. Any invalid metadata
762
+ will cause :exc:`InvalidMetadata` to be raised (with a
763
+ :py:attr:`~BaseException.__cause__` attribute as appropriate).
764
+ """
765
+
766
+ _raw: RawMetadata
767
+
768
+ @classmethod
769
+ def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata:
770
+ """Create an instance from :class:`RawMetadata`.
771
+
772
+ If *validate* is true, all metadata will be validated. All exceptions
773
+ related to validation will be gathered and raised as an :class:`ExceptionGroup`.
774
+ """
775
+ ins = cls()
776
+ ins._raw = data.copy() # Mutations occur due to caching enriched values.
777
+
778
+ if validate:
779
+ collector = _ErrorCollector()
780
+ metadata_version = None
781
+ with collector.collect(InvalidMetadata):
782
+ metadata_version = ins.metadata_version
783
+ metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)
784
+
785
+ # Make sure to check for the fields that are present, the required
786
+ # fields (so their absence can be reported).
787
+ fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS
788
+ # Remove fields that have already been checked.
789
+ fields_to_check -= {"metadata_version"}
790
+
791
+ for key in fields_to_check:
792
+ try:
793
+ if metadata_version:
794
+ # Can't use getattr() as that triggers descriptor protocol which
795
+ # will fail due to no value for the instance argument.
796
+ try:
797
+ field_metadata_version = cls.__dict__[key].added
798
+ except KeyError:
799
+ exc = InvalidMetadata(key, f"unrecognized field: {key!r}")
800
+ collector.error(exc)
801
+ continue
802
+ field_age = _VALID_METADATA_VERSIONS.index(
803
+ field_metadata_version
804
+ )
805
+ if field_age > metadata_age:
806
+ field = _RAW_TO_EMAIL_MAPPING[key]
807
+ exc = InvalidMetadata(
808
+ field,
809
+ f"{field} introduced in metadata version "
810
+ f"{field_metadata_version}, not {metadata_version}",
811
+ )
812
+ collector.error(exc)
813
+ continue
814
+ getattr(ins, key)
815
+ except InvalidMetadata as exc:
816
+ collector.error(exc)
817
+
818
+ collector.finalize("invalid metadata")
819
+
820
+ return ins
821
+
822
+ @classmethod
823
+ def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata:
824
+ """Parse metadata from email headers.
825
+
826
+ If *validate* is true, the metadata will be validated. All exceptions
827
+ related to validation will be gathered and raised as an :class:`ExceptionGroup`.
828
+ """
829
+ raw, unparsed = parse_email(data)
830
+
831
+ if validate:
832
+ with _ErrorCollector().on_exit("unparsed") as collector:
833
+ for unparsed_key in unparsed:
834
+ if unparsed_key in _EMAIL_TO_RAW_MAPPING:
835
+ message = f"{unparsed_key!r} has invalid data"
836
+ else:
837
+ message = f"unrecognized field: {unparsed_key!r}"
838
+ collector.error(InvalidMetadata(unparsed_key, message))
839
+
840
+ try:
841
+ return cls.from_raw(raw, validate=validate)
842
+ except ExceptionGroup as exc_group:
843
+ raise ExceptionGroup(
844
+ "invalid or unparsed metadata", exc_group.exceptions
845
+ ) from None
846
+
847
+ metadata_version: _Validator[_MetadataVersion] = _Validator()
848
+ """:external:ref:`core-metadata-metadata-version`
849
+ (required; validated to be a valid metadata version)"""
850
+ # `name` is not normalized/typed to NormalizedName so as to provide access to
851
+ # the original/raw name.
852
+ name: _Validator[str] = _Validator()
853
+ """:external:ref:`core-metadata-name`
854
+ (required; validated using :func:`~packaging.utils.canonicalize_name` and its
855
+ *validate* parameter)"""
856
+ version: _Validator[version_module.Version] = _Validator()
857
+ """:external:ref:`core-metadata-version` (required)"""
858
+ dynamic: _Validator[list[str] | None] = _Validator(
859
+ added="2.2",
860
+ )
861
+ """:external:ref:`core-metadata-dynamic`
862
+ (validated against core metadata field names and lowercased)"""
863
+ platforms: _Validator[list[str] | None] = _Validator()
864
+ """:external:ref:`core-metadata-platform`"""
865
+ supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1")
866
+ """:external:ref:`core-metadata-supported-platform`"""
867
+ summary: _Validator[str | None] = _Validator()
868
+ """:external:ref:`core-metadata-summary` (validated to contain no newlines)"""
869
+ description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body
870
+ """:external:ref:`core-metadata-description`"""
871
+ description_content_type: _Validator[str | None] = _Validator(added="2.1")
872
+ """:external:ref:`core-metadata-description-content-type` (validated)"""
873
+ keywords: _Validator[list[str] | None] = _Validator()
874
+ """:external:ref:`core-metadata-keywords`"""
875
+ home_page: _Validator[str | None] = _Validator()
876
+ """:external:ref:`core-metadata-home-page`"""
877
+ download_url: _Validator[str | None] = _Validator(added="1.1")
878
+ """:external:ref:`core-metadata-download-url`"""
879
+ author: _Validator[str | None] = _Validator()
880
+ """:external:ref:`core-metadata-author`"""
881
+ author_email: _Validator[str | None] = _Validator()
882
+ """:external:ref:`core-metadata-author-email`"""
883
+ maintainer: _Validator[str | None] = _Validator(added="1.2")
884
+ """:external:ref:`core-metadata-maintainer`"""
885
+ maintainer_email: _Validator[str | None] = _Validator(added="1.2")
886
+ """:external:ref:`core-metadata-maintainer-email`"""
887
+ license: _Validator[str | None] = _Validator()
888
+ """:external:ref:`core-metadata-license`"""
889
+ license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator(
890
+ added="2.4"
891
+ )
892
+ """:external:ref:`core-metadata-license-expression`"""
893
+ license_files: _Validator[list[str] | None] = _Validator(added="2.4")
894
+ """:external:ref:`core-metadata-license-file`"""
895
+ classifiers: _Validator[list[str] | None] = _Validator(added="1.1")
896
+ """:external:ref:`core-metadata-classifier`"""
897
+ requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator(
898
+ added="1.2"
899
+ )
900
+ """:external:ref:`core-metadata-requires-dist`"""
901
+ requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator(
902
+ added="1.2"
903
+ )
904
+ """:external:ref:`core-metadata-requires-python`"""
905
+ # Because `Requires-External` allows for non-PEP 440 version specifiers, we
906
+ # don't do any processing on the values.
907
+ requires_external: _Validator[list[str] | None] = _Validator(added="1.2")
908
+ """:external:ref:`core-metadata-requires-external`"""
909
+ project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2")
910
+ """:external:ref:`core-metadata-project-url`"""
911
+ # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation
912
+ # regardless of metadata version.
913
+ provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator(
914
+ added="2.1",
915
+ )
916
+ """:external:ref:`core-metadata-provides-extra`"""
917
+ provides_dist: _Validator[list[str] | None] = _Validator(added="1.2")
918
+ """:external:ref:`core-metadata-provides-dist`"""
919
+ obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2")
920
+ """:external:ref:`core-metadata-obsoletes-dist`"""
921
+ import_names: _Validator[list[str] | None] = _Validator(added="2.5")
922
+ """:external:ref:`core-metadata-import-name`"""
923
+ import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5")
924
+ """:external:ref:`core-metadata-import-namespace`"""
925
+ requires: _Validator[list[str] | None] = _Validator(added="1.1")
926
+ """``Requires`` (deprecated)"""
927
+ provides: _Validator[list[str] | None] = _Validator(added="1.1")
928
+ """``Provides`` (deprecated)"""
929
+ obsoletes: _Validator[list[str] | None] = _Validator(added="1.1")
930
+ """``Obsoletes`` (deprecated)"""
931
+
932
+ def as_rfc822(self) -> RFC822Message:
933
+ """
934
+ Return an RFC822 message with the metadata.
935
+ """
936
+ message = RFC822Message()
937
+ self._write_metadata(message)
938
+ return message
939
+
940
+ def _write_metadata(self, message: RFC822Message) -> None:
941
+ """
942
+ Return an RFC822 message with the metadata.
943
+ """
944
+ for name, validator in self.__class__.__dict__.items():
945
+ if isinstance(validator, _Validator) and name != "description":
946
+ value = getattr(self, name)
947
+ email_name = _RAW_TO_EMAIL_MAPPING[name]
948
+ if value is not None:
949
+ if email_name == "project-url":
950
+ for label, url in value.items():
951
+ message[email_name] = f"{label}, {url}"
952
+ elif email_name == "keywords":
953
+ message[email_name] = ",".join(value)
954
+ elif email_name == "import-name" and value == []:
955
+ message[email_name] = ""
956
+ elif isinstance(value, list):
957
+ for item in value:
958
+ message[email_name] = str(item)
959
+ else:
960
+ message[email_name] = str(value)
961
+
962
+ # The description is a special case because it is in the body of the message.
963
+ if self.description is not None:
964
+ message.set_payload(self.description)
.venv/lib/python3.11/site-packages/packaging/py.typed ADDED
File without changes
.venv/lib/python3.11/site-packages/packaging/pylock.py ADDED
@@ -0,0 +1,905 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import logging
5
+ import re
6
+ from collections.abc import Mapping, Sequence
7
+ from dataclasses import dataclass
8
+ from datetime import datetime
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ Callable,
13
+ Protocol,
14
+ TypeVar,
15
+ cast,
16
+ )
17
+ from urllib.parse import urlparse
18
+
19
+ from .markers import Environment, Marker, default_environment
20
+ from .specifiers import SpecifierSet
21
+ from .tags import create_compatible_tags_selector, sys_tags
22
+ from .utils import (
23
+ NormalizedName,
24
+ is_normalized_name,
25
+ parse_sdist_filename,
26
+ parse_wheel_filename,
27
+ )
28
+ from .version import Version
29
+
30
+ if TYPE_CHECKING: # pragma: no cover
31
+ from collections.abc import Collection, Iterator
32
+ from pathlib import Path
33
+
34
+ from typing_extensions import Self
35
+
36
+ from .tags import Tag
37
+
38
+ _logger = logging.getLogger(__name__)
39
+
40
+ __all__ = [
41
+ "Package",
42
+ "PackageArchive",
43
+ "PackageDirectory",
44
+ "PackageSdist",
45
+ "PackageVcs",
46
+ "PackageWheel",
47
+ "Pylock",
48
+ "PylockUnsupportedVersionError",
49
+ "PylockValidationError",
50
+ "is_valid_pylock_path",
51
+ ]
52
+
53
+
54
+ def __dir__() -> list[str]:
55
+ return __all__
56
+
57
+
58
+ _T = TypeVar("_T")
59
+ _T2 = TypeVar("_T2")
60
+
61
+
62
+ class _FromMappingProtocol(Protocol): # pragma: no cover
63
+ @classmethod
64
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
65
+
66
+
67
+ _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
68
+
69
+
70
+ _PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$")
71
+
72
+
73
+ def is_valid_pylock_path(path: Path) -> bool:
74
+ """Check if the given path is a valid pylock file path."""
75
+ return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name))
76
+
77
+
78
+ def _toml_key(key: str) -> str:
79
+ return key.replace("_", "-")
80
+
81
+
82
+ def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401
83
+ if isinstance(value, (Version, Marker, SpecifierSet)):
84
+ return str(value)
85
+ if isinstance(value, Sequence) and key == "environments":
86
+ return [str(v) for v in value]
87
+ return value
88
+
89
+
90
+ def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]:
91
+ return {
92
+ _toml_key(key): _toml_value(key, value)
93
+ for key, value in data
94
+ if value is not None
95
+ }
96
+
97
+
98
+ def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None:
99
+ """Get a value from the dictionary and verify it's the expected type."""
100
+ if (value := d.get(key)) is None:
101
+ return None
102
+ if not isinstance(value, expected_type):
103
+ raise PylockValidationError(
104
+ f"Unexpected type {type(value).__name__} "
105
+ f"(expected {expected_type.__name__})",
106
+ context=key,
107
+ )
108
+ return value
109
+
110
+
111
+ def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T:
112
+ """Get a required value from the dictionary and verify it's the expected type."""
113
+ if (value := _get(d, expected_type, key)) is None:
114
+ raise _PylockRequiredKeyError(key)
115
+ return value
116
+
117
+
118
+ def _get_sequence(
119
+ d: Mapping[str, Any], expected_item_type: type[_T], key: str
120
+ ) -> Sequence[_T] | None:
121
+ """Get a list value from the dictionary and verify it's the expected items type."""
122
+ if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract]
123
+ return None
124
+ if isinstance(value, (str, bytes)):
125
+ # special case: str and bytes are Sequences, but we want to reject it
126
+ raise PylockValidationError(
127
+ f"Unexpected type {type(value).__name__} (expected Sequence)",
128
+ context=key,
129
+ )
130
+ for i, item in enumerate(value):
131
+ if not isinstance(item, expected_item_type):
132
+ raise PylockValidationError(
133
+ f"Unexpected type {type(item).__name__} "
134
+ f"(expected {expected_item_type.__name__})",
135
+ context=f"{key}[{i}]",
136
+ )
137
+ return value
138
+
139
+
140
+ def _get_as(
141
+ d: Mapping[str, Any],
142
+ expected_type: type[_T],
143
+ target_type: Callable[[_T], _T2],
144
+ key: str,
145
+ ) -> _T2 | None:
146
+ """Get a value from the dictionary, verify it's the expected type,
147
+ and convert to the target type.
148
+
149
+ This assumes the target_type constructor accepts the value.
150
+ """
151
+ if (value := _get(d, expected_type, key)) is None:
152
+ return None
153
+ try:
154
+ return target_type(value)
155
+ except Exception as e:
156
+ raise PylockValidationError(e, context=key) from e
157
+
158
+
159
+ def _get_required_as(
160
+ d: Mapping[str, Any],
161
+ expected_type: type[_T],
162
+ target_type: Callable[[_T], _T2],
163
+ key: str,
164
+ ) -> _T2:
165
+ """Get a required value from the dict, verify it's the expected type,
166
+ and convert to the target type."""
167
+ if (value := _get_as(d, expected_type, target_type, key)) is None:
168
+ raise _PylockRequiredKeyError(key)
169
+ return value
170
+
171
+
172
+ def _get_sequence_as(
173
+ d: Mapping[str, Any],
174
+ expected_item_type: type[_T],
175
+ target_item_type: Callable[[_T], _T2],
176
+ key: str,
177
+ ) -> list[_T2] | None:
178
+ """Get list value from dictionary and verify expected items type."""
179
+ if (value := _get_sequence(d, expected_item_type, key)) is None:
180
+ return None
181
+ result = []
182
+ try:
183
+ for item in value:
184
+ typed_item = target_item_type(item)
185
+ result.append(typed_item)
186
+ except Exception as e:
187
+ raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
188
+ return result
189
+
190
+
191
+ def _get_object(
192
+ d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str
193
+ ) -> _FromMappingProtocolT | None:
194
+ """Get a dictionary value from the dictionary and convert it to a dataclass."""
195
+ if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract]
196
+ return None
197
+ try:
198
+ return target_type._from_dict(value)
199
+ except Exception as e:
200
+ raise PylockValidationError(e, context=key) from e
201
+
202
+
203
+ def _get_sequence_of_objects(
204
+ d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
205
+ ) -> list[_FromMappingProtocolT] | None:
206
+ """Get a list value from the dictionary and convert its items to a dataclass."""
207
+ if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract]
208
+ return None
209
+ result: list[_FromMappingProtocolT] = []
210
+ try:
211
+ for item in value:
212
+ typed_item = target_item_type._from_dict(item)
213
+ result.append(typed_item)
214
+ except Exception as e:
215
+ raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e
216
+ return result
217
+
218
+
219
+ def _get_required_sequence_of_objects(
220
+ d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str
221
+ ) -> Sequence[_FromMappingProtocolT]:
222
+ """Get a required list value from the dictionary and convert its items to a
223
+ dataclass."""
224
+ if (result := _get_sequence_of_objects(d, target_item_type, key)) is None:
225
+ raise _PylockRequiredKeyError(key)
226
+ return result
227
+
228
+
229
+ def _validate_normalized_name(name: str) -> NormalizedName:
230
+ """Validate that a string is a NormalizedName."""
231
+ if not is_normalized_name(name):
232
+ raise PylockValidationError(f"Name {name!r} is not normalized")
233
+ return NormalizedName(name)
234
+
235
+
236
+ def _validate_path_url(path: str | None, url: str | None) -> None:
237
+ if not path and not url:
238
+ raise PylockValidationError("path or url must be provided")
239
+
240
+
241
+ def _path_name(path: str | None) -> str | None:
242
+ if not path:
243
+ return None
244
+ # If the path is relative it MAY use POSIX-style path separators explicitly
245
+ # for portability
246
+ if "/" in path:
247
+ return path.rsplit("/", 1)[-1]
248
+ elif "\\" in path:
249
+ return path.rsplit("\\", 1)[-1]
250
+ else:
251
+ return path
252
+
253
+
254
+ def _url_name(url: str | None) -> str | None:
255
+ if not url:
256
+ return None
257
+ url_path = urlparse(url).path
258
+ return url_path.rsplit("/", 1)[-1]
259
+
260
+
261
+ def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]:
262
+ if not hashes:
263
+ raise PylockValidationError("At least one hash must be provided")
264
+ if not all(isinstance(hash_val, str) for hash_val in hashes.values()):
265
+ raise PylockValidationError("Hash values must be strings")
266
+ return hashes
267
+
268
+
269
+ class PylockValidationError(Exception):
270
+ """Raised when when input data is not spec-compliant."""
271
+
272
+ context: str | None = None
273
+ message: str
274
+
275
+ def __init__(
276
+ self,
277
+ cause: str | Exception,
278
+ *,
279
+ context: str | None = None,
280
+ ) -> None:
281
+ if isinstance(cause, PylockValidationError):
282
+ if cause.context:
283
+ self.context = (
284
+ f"{context}.{cause.context}" if context else cause.context
285
+ )
286
+ else:
287
+ self.context = context
288
+ self.message = cause.message
289
+ else:
290
+ self.context = context
291
+ self.message = str(cause)
292
+
293
+ def __str__(self) -> str:
294
+ if self.context:
295
+ return f"{self.message} in {self.context!r}"
296
+ return self.message
297
+
298
+
299
+ class _PylockRequiredKeyError(PylockValidationError):
300
+ def __init__(self, key: str) -> None:
301
+ super().__init__("Missing required value", context=key)
302
+
303
+
304
+ class PylockUnsupportedVersionError(PylockValidationError):
305
+ """Raised when encountering an unsupported `lock_version`."""
306
+
307
+
308
+ class PylockSelectError(Exception):
309
+ """Base exception for errors raised by :meth:`Pylock.select`."""
310
+
311
+
312
+ @dataclass(frozen=True, init=False)
313
+ class PackageVcs:
314
+ type: str
315
+ url: str | None = None
316
+ path: str | None = None
317
+ requested_revision: str | None = None
318
+ commit_id: str # type: ignore[misc]
319
+ subdirectory: str | None = None
320
+
321
+ def __init__(
322
+ self,
323
+ *,
324
+ type: str,
325
+ url: str | None = None,
326
+ path: str | None = None,
327
+ requested_revision: str | None = None,
328
+ commit_id: str,
329
+ subdirectory: str | None = None,
330
+ ) -> None:
331
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
332
+ object.__setattr__(self, "type", type)
333
+ object.__setattr__(self, "url", url)
334
+ object.__setattr__(self, "path", path)
335
+ object.__setattr__(self, "requested_revision", requested_revision)
336
+ object.__setattr__(self, "commit_id", commit_id)
337
+ object.__setattr__(self, "subdirectory", subdirectory)
338
+
339
+ @classmethod
340
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
341
+ package_vcs = cls(
342
+ type=_get_required(d, str, "type"),
343
+ url=_get(d, str, "url"),
344
+ path=_get(d, str, "path"),
345
+ requested_revision=_get(d, str, "requested-revision"),
346
+ commit_id=_get_required(d, str, "commit-id"),
347
+ subdirectory=_get(d, str, "subdirectory"),
348
+ )
349
+ _validate_path_url(package_vcs.path, package_vcs.url)
350
+ return package_vcs
351
+
352
+
353
+ @dataclass(frozen=True, init=False)
354
+ class PackageDirectory:
355
+ path: str
356
+ editable: bool | None = None
357
+ subdirectory: str | None = None
358
+
359
+ def __init__(
360
+ self,
361
+ *,
362
+ path: str,
363
+ editable: bool | None = None,
364
+ subdirectory: str | None = None,
365
+ ) -> None:
366
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
367
+ object.__setattr__(self, "path", path)
368
+ object.__setattr__(self, "editable", editable)
369
+ object.__setattr__(self, "subdirectory", subdirectory)
370
+
371
+ @classmethod
372
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
373
+ return cls(
374
+ path=_get_required(d, str, "path"),
375
+ editable=_get(d, bool, "editable"),
376
+ subdirectory=_get(d, str, "subdirectory"),
377
+ )
378
+
379
+
380
+ @dataclass(frozen=True, init=False)
381
+ class PackageArchive:
382
+ url: str | None = None
383
+ path: str | None = None
384
+ size: int | None = None
385
+ upload_time: datetime | None = None
386
+ hashes: Mapping[str, str] # type: ignore[misc]
387
+ subdirectory: str | None = None
388
+
389
+ def __init__(
390
+ self,
391
+ *,
392
+ url: str | None = None,
393
+ path: str | None = None,
394
+ size: int | None = None,
395
+ upload_time: datetime | None = None,
396
+ hashes: Mapping[str, str],
397
+ subdirectory: str | None = None,
398
+ ) -> None:
399
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
400
+ object.__setattr__(self, "url", url)
401
+ object.__setattr__(self, "path", path)
402
+ object.__setattr__(self, "size", size)
403
+ object.__setattr__(self, "upload_time", upload_time)
404
+ object.__setattr__(self, "hashes", hashes)
405
+ object.__setattr__(self, "subdirectory", subdirectory)
406
+
407
+ @classmethod
408
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
409
+ package_archive = cls(
410
+ url=_get(d, str, "url"),
411
+ path=_get(d, str, "path"),
412
+ size=_get(d, int, "size"),
413
+ upload_time=_get(d, datetime, "upload-time"),
414
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
415
+ subdirectory=_get(d, str, "subdirectory"),
416
+ )
417
+ _validate_path_url(package_archive.path, package_archive.url)
418
+ return package_archive
419
+
420
+
421
+ @dataclass(frozen=True, init=False)
422
+ class PackageSdist:
423
+ name: str | None = None
424
+ upload_time: datetime | None = None
425
+ url: str | None = None
426
+ path: str | None = None
427
+ size: int | None = None
428
+ hashes: Mapping[str, str] # type: ignore[misc]
429
+
430
+ def __init__(
431
+ self,
432
+ *,
433
+ name: str | None = None,
434
+ upload_time: datetime | None = None,
435
+ url: str | None = None,
436
+ path: str | None = None,
437
+ size: int | None = None,
438
+ hashes: Mapping[str, str],
439
+ ) -> None:
440
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
441
+ object.__setattr__(self, "name", name)
442
+ object.__setattr__(self, "upload_time", upload_time)
443
+ object.__setattr__(self, "url", url)
444
+ object.__setattr__(self, "path", path)
445
+ object.__setattr__(self, "size", size)
446
+ object.__setattr__(self, "hashes", hashes)
447
+
448
+ @classmethod
449
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
450
+ package_sdist = cls(
451
+ name=_get(d, str, "name"),
452
+ upload_time=_get(d, datetime, "upload-time"),
453
+ url=_get(d, str, "url"),
454
+ path=_get(d, str, "path"),
455
+ size=_get(d, int, "size"),
456
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
457
+ )
458
+ _validate_path_url(package_sdist.path, package_sdist.url)
459
+ return package_sdist
460
+
461
+ @property
462
+ def filename(self) -> str:
463
+ """Get the filename of the sdist."""
464
+ filename = self.name or _path_name(self.path) or _url_name(self.url)
465
+ if not filename:
466
+ raise PylockValidationError("Cannot determine sdist filename")
467
+ return filename
468
+
469
+
470
+ @dataclass(frozen=True, init=False)
471
+ class PackageWheel:
472
+ name: str | None = None
473
+ upload_time: datetime | None = None
474
+ url: str | None = None
475
+ path: str | None = None
476
+ size: int | None = None
477
+ hashes: Mapping[str, str] # type: ignore[misc]
478
+
479
+ def __init__(
480
+ self,
481
+ *,
482
+ name: str | None = None,
483
+ upload_time: datetime | None = None,
484
+ url: str | None = None,
485
+ path: str | None = None,
486
+ size: int | None = None,
487
+ hashes: Mapping[str, str],
488
+ ) -> None:
489
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
490
+ object.__setattr__(self, "name", name)
491
+ object.__setattr__(self, "upload_time", upload_time)
492
+ object.__setattr__(self, "url", url)
493
+ object.__setattr__(self, "path", path)
494
+ object.__setattr__(self, "size", size)
495
+ object.__setattr__(self, "hashes", hashes)
496
+
497
+ @classmethod
498
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
499
+ package_wheel = cls(
500
+ name=_get(d, str, "name"),
501
+ upload_time=_get(d, datetime, "upload-time"),
502
+ url=_get(d, str, "url"),
503
+ path=_get(d, str, "path"),
504
+ size=_get(d, int, "size"),
505
+ hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract]
506
+ )
507
+ _validate_path_url(package_wheel.path, package_wheel.url)
508
+ return package_wheel
509
+
510
+ @property
511
+ def filename(self) -> str:
512
+ """Get the filename of the wheel."""
513
+ filename = self.name or _path_name(self.path) or _url_name(self.url)
514
+ if not filename:
515
+ raise PylockValidationError("Cannot determine wheel filename")
516
+ return filename
517
+
518
+
519
+ @dataclass(frozen=True, init=False)
520
+ class Package:
521
+ name: NormalizedName
522
+ version: Version | None = None
523
+ marker: Marker | None = None
524
+ requires_python: SpecifierSet | None = None
525
+ dependencies: Sequence[Mapping[str, Any]] | None = None
526
+ vcs: PackageVcs | None = None
527
+ directory: PackageDirectory | None = None
528
+ archive: PackageArchive | None = None
529
+ index: str | None = None
530
+ sdist: PackageSdist | None = None
531
+ wheels: Sequence[PackageWheel] | None = None
532
+ attestation_identities: Sequence[Mapping[str, Any]] | None = None
533
+ tool: Mapping[str, Any] | None = None
534
+
535
+ def __init__(
536
+ self,
537
+ *,
538
+ name: NormalizedName,
539
+ version: Version | None = None,
540
+ marker: Marker | None = None,
541
+ requires_python: SpecifierSet | None = None,
542
+ dependencies: Sequence[Mapping[str, Any]] | None = None,
543
+ vcs: PackageVcs | None = None,
544
+ directory: PackageDirectory | None = None,
545
+ archive: PackageArchive | None = None,
546
+ index: str | None = None,
547
+ sdist: PackageSdist | None = None,
548
+ wheels: Sequence[PackageWheel] | None = None,
549
+ attestation_identities: Sequence[Mapping[str, Any]] | None = None,
550
+ tool: Mapping[str, Any] | None = None,
551
+ ) -> None:
552
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
553
+ object.__setattr__(self, "name", name)
554
+ object.__setattr__(self, "version", version)
555
+ object.__setattr__(self, "marker", marker)
556
+ object.__setattr__(self, "requires_python", requires_python)
557
+ object.__setattr__(self, "dependencies", dependencies)
558
+ object.__setattr__(self, "vcs", vcs)
559
+ object.__setattr__(self, "directory", directory)
560
+ object.__setattr__(self, "archive", archive)
561
+ object.__setattr__(self, "index", index)
562
+ object.__setattr__(self, "sdist", sdist)
563
+ object.__setattr__(self, "wheels", wheels)
564
+ object.__setattr__(self, "attestation_identities", attestation_identities)
565
+ object.__setattr__(self, "tool", tool)
566
+
567
+ @classmethod
568
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
569
+ package = cls(
570
+ name=_get_required_as(d, str, _validate_normalized_name, "name"),
571
+ version=_get_as(d, str, Version, "version"),
572
+ requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
573
+ dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract]
574
+ marker=_get_as(d, str, Marker, "marker"),
575
+ vcs=_get_object(d, PackageVcs, "vcs"),
576
+ directory=_get_object(d, PackageDirectory, "directory"),
577
+ archive=_get_object(d, PackageArchive, "archive"),
578
+ index=_get(d, str, "index"),
579
+ sdist=_get_object(d, PackageSdist, "sdist"),
580
+ wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"),
581
+ attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract]
582
+ tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract]
583
+ )
584
+ distributions = bool(package.sdist) + len(package.wheels or [])
585
+ direct_urls = (
586
+ bool(package.vcs) + bool(package.directory) + bool(package.archive)
587
+ )
588
+ if distributions > 0 and direct_urls > 0:
589
+ raise PylockValidationError(
590
+ "None of vcs, directory, archive must be set if sdist or wheels are set"
591
+ )
592
+ if distributions == 0 and direct_urls != 1:
593
+ raise PylockValidationError(
594
+ "Exactly one of vcs, directory, archive must be set "
595
+ "if sdist and wheels are not set"
596
+ )
597
+ for i, wheel in enumerate(package.wheels or []):
598
+ try:
599
+ (name, version, _, _) = parse_wheel_filename(wheel.filename)
600
+ except Exception as e:
601
+ raise PylockValidationError(
602
+ f"Invalid wheel filename {wheel.filename!r}",
603
+ context=f"wheels[{i}]",
604
+ ) from e
605
+ if name != package.name:
606
+ raise PylockValidationError(
607
+ f"Name in {wheel.filename!r} is not consistent with "
608
+ f"package name {package.name!r}",
609
+ context=f"wheels[{i}]",
610
+ )
611
+ if package.version and version != package.version:
612
+ raise PylockValidationError(
613
+ f"Version in {wheel.filename!r} is not consistent with "
614
+ f"package version {str(package.version)!r}",
615
+ context=f"wheels[{i}]",
616
+ )
617
+ if package.sdist:
618
+ try:
619
+ name, version = parse_sdist_filename(package.sdist.filename)
620
+ except Exception as e:
621
+ raise PylockValidationError(
622
+ f"Invalid sdist filename {package.sdist.filename!r}",
623
+ context="sdist",
624
+ ) from e
625
+ if name != package.name:
626
+ raise PylockValidationError(
627
+ f"Name in {package.sdist.filename!r} is not consistent with "
628
+ f"package name {package.name!r}",
629
+ context="sdist",
630
+ )
631
+ if package.version and version != package.version:
632
+ raise PylockValidationError(
633
+ f"Version in {package.sdist.filename!r} is not consistent with "
634
+ f"package version {str(package.version)!r}",
635
+ context="sdist",
636
+ )
637
+ try:
638
+ for i, attestation_identity in enumerate( # noqa: B007
639
+ package.attestation_identities or []
640
+ ):
641
+ _get_required(attestation_identity, str, "kind")
642
+ except Exception as e:
643
+ raise PylockValidationError(
644
+ e, context=f"attestation-identities[{i}]"
645
+ ) from e
646
+ return package
647
+
648
+ @property
649
+ def is_direct(self) -> bool:
650
+ return not (self.sdist or self.wheels)
651
+
652
+
653
+ @dataclass(frozen=True, init=False)
654
+ class Pylock:
655
+ """A class representing a pylock file."""
656
+
657
+ lock_version: Version
658
+ environments: Sequence[Marker] | None = None
659
+ requires_python: SpecifierSet | None = None
660
+ extras: Sequence[NormalizedName] | None = None
661
+ dependency_groups: Sequence[str] | None = None
662
+ default_groups: Sequence[str] | None = None
663
+ created_by: str # type: ignore[misc]
664
+ packages: Sequence[Package] # type: ignore[misc]
665
+ tool: Mapping[str, Any] | None = None
666
+
667
+ def __init__(
668
+ self,
669
+ *,
670
+ lock_version: Version,
671
+ environments: Sequence[Marker] | None = None,
672
+ requires_python: SpecifierSet | None = None,
673
+ extras: Sequence[NormalizedName] | None = None,
674
+ dependency_groups: Sequence[str] | None = None,
675
+ default_groups: Sequence[str] | None = None,
676
+ created_by: str,
677
+ packages: Sequence[Package],
678
+ tool: Mapping[str, Any] | None = None,
679
+ ) -> None:
680
+ # In Python 3.10+ make dataclass kw_only=True and remove __init__
681
+ object.__setattr__(self, "lock_version", lock_version)
682
+ object.__setattr__(self, "environments", environments)
683
+ object.__setattr__(self, "requires_python", requires_python)
684
+ object.__setattr__(self, "extras", extras)
685
+ object.__setattr__(self, "dependency_groups", dependency_groups)
686
+ object.__setattr__(self, "default_groups", default_groups)
687
+ object.__setattr__(self, "created_by", created_by)
688
+ object.__setattr__(self, "packages", packages)
689
+ object.__setattr__(self, "tool", tool)
690
+
691
+ @classmethod
692
+ def _from_dict(cls, d: Mapping[str, Any]) -> Self:
693
+ pylock = cls(
694
+ lock_version=_get_required_as(d, str, Version, "lock-version"),
695
+ environments=_get_sequence_as(d, str, Marker, "environments"),
696
+ extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"),
697
+ dependency_groups=_get_sequence(d, str, "dependency-groups"),
698
+ default_groups=_get_sequence(d, str, "default-groups"),
699
+ created_by=_get_required(d, str, "created-by"),
700
+ requires_python=_get_as(d, str, SpecifierSet, "requires-python"),
701
+ packages=_get_required_sequence_of_objects(d, Package, "packages"),
702
+ tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract]
703
+ )
704
+ if not Version("1") <= pylock.lock_version < Version("2"):
705
+ raise PylockUnsupportedVersionError(
706
+ f"pylock version {pylock.lock_version} is not supported"
707
+ )
708
+ if pylock.lock_version > Version("1.0"):
709
+ _logger.warning(
710
+ "pylock minor version %s is not supported", pylock.lock_version
711
+ )
712
+ return pylock
713
+
714
+ @classmethod
715
+ def from_dict(cls, d: Mapping[str, Any], /) -> Self:
716
+ """Create and validate a Pylock instance from a TOML dictionary.
717
+
718
+ Raises :class:`PylockValidationError` if the input data is not
719
+ spec-compliant.
720
+ """
721
+ return cls._from_dict(d)
722
+
723
+ def to_dict(self) -> Mapping[str, Any]:
724
+ """Convert the Pylock instance to a TOML dictionary."""
725
+ return dataclasses.asdict(self, dict_factory=_toml_dict_factory)
726
+
727
+ def validate(self) -> None:
728
+ """Validate the Pylock instance against the specification.
729
+
730
+ Raises :class:`PylockValidationError` otherwise."""
731
+ self.from_dict(self.to_dict())
732
+
733
+ def select(
734
+ self,
735
+ *,
736
+ environment: Environment | None = None,
737
+ tags: Sequence[Tag] | None = None,
738
+ extras: Collection[str] | None = None,
739
+ dependency_groups: Collection[str] | None = None,
740
+ ) -> Iterator[
741
+ tuple[
742
+ Package,
743
+ PackageVcs
744
+ | PackageDirectory
745
+ | PackageArchive
746
+ | PackageWheel
747
+ | PackageSdist,
748
+ ]
749
+ ]:
750
+ """Select what to install from the lock file.
751
+
752
+ The *environment* and *tags* parameters represent the environment being
753
+ selected for. If unspecified, ``packaging.markers.default_environment()`` and
754
+ ``packaging.tags.sys_tags()`` are used.
755
+
756
+ The *extras* parameter represents the extras to install.
757
+
758
+ The *dependency_groups* parameter represents the groups to install. If
759
+ unspecified, the default groups are used.
760
+
761
+ This method must be used on valid Pylock instances (i.e. one obtained
762
+ from :meth:`Pylock.from_dict` or if constructed manually, after calling
763
+ :meth:`Pylock.validate`).
764
+ """
765
+ compatible_tags_selector = create_compatible_tags_selector(tags or sys_tags())
766
+
767
+ # #. Gather the extras and dependency groups to install and set ``extras`` and
768
+ # ``dependency_groups`` for marker evaluation, respectively.
769
+ #
770
+ # #. ``extras`` SHOULD be set to the empty set by default.
771
+ # #. ``dependency_groups`` SHOULD be the set created from
772
+ # :ref:`pylock-default-groups` by default.
773
+ env = cast(
774
+ "dict[str, str | frozenset[str]]",
775
+ dict(
776
+ environment or {}, # Marker.evaluate will fill-up
777
+ extras=frozenset(extras or []),
778
+ dependency_groups=frozenset(
779
+ (self.default_groups or [])
780
+ if dependency_groups is None # to allow selecting no group
781
+ else dependency_groups
782
+ ),
783
+ ),
784
+ )
785
+ env_python_full_version = (
786
+ environment["python_full_version"]
787
+ if environment
788
+ else default_environment()["python_full_version"]
789
+ )
790
+
791
+ # #. Check if the metadata version specified by :ref:`pylock-lock-version` is
792
+ # supported; an error or warning MUST be raised as appropriate.
793
+ # Covered by lock.validate() which is a precondition for this method.
794
+
795
+ # #. If :ref:`pylock-requires-python` is specified, check that the environment
796
+ # being installed for meets the requirement; an error MUST be raised if it is
797
+ # not met.
798
+ if self.requires_python and not self.requires_python.contains(
799
+ env_python_full_version,
800
+ ):
801
+ raise PylockSelectError(
802
+ f"python_full_version {env_python_full_version!r} "
803
+ f"in provided environment does not satisfy the Python version "
804
+ f"requirement {str(self.requires_python)!r}"
805
+ )
806
+
807
+ # #. If :ref:`pylock-environments` is specified, check that at least one of the
808
+ # environment marker expressions is satisfied; an error MUST be raised if no
809
+ # expression is satisfied.
810
+ if self.environments:
811
+ for env_marker in self.environments:
812
+ if env_marker.evaluate(
813
+ cast("dict[str, str]", environment or {}), context="requirement"
814
+ ):
815
+ break
816
+ else:
817
+ raise PylockSelectError(
818
+ "Provided environment does not satisfy any of the "
819
+ "environments specified in the lock file"
820
+ )
821
+
822
+ # #. For each package listed in :ref:`pylock-packages`:
823
+ selected_packages_by_name: dict[str, tuple[int, Package]] = {}
824
+ for package_index, package in enumerate(self.packages):
825
+ # #. If :ref:`pylock-packages-marker` is specified, check if it is
826
+ # satisfied;if it isn't, skip to the next package.
827
+ if package.marker and not package.marker.evaluate(env, context="lock_file"):
828
+ continue
829
+
830
+ # #. If :ref:`pylock-packages-requires-python` is specified, check if it is
831
+ # satisfied; an error MUST be raised if it isn't.
832
+ if package.requires_python and not package.requires_python.contains(
833
+ env_python_full_version,
834
+ ):
835
+ raise PylockSelectError(
836
+ f"python_full_version {env_python_full_version!r} "
837
+ f"in provided environment does not satisfy the Python version "
838
+ f"requirement {str(package.requires_python)!r} for package "
839
+ f"{package.name!r} at packages[{package_index}]"
840
+ )
841
+
842
+ # #. Check that no other conflicting instance of the package has been slated
843
+ # to be installed; an error about the ambiguity MUST be raised otherwise.
844
+ if package.name in selected_packages_by_name:
845
+ raise PylockSelectError(
846
+ f"Multiple packages with the name {package.name!r} are "
847
+ f"selected at packages[{package_index}] and "
848
+ f"packages[{selected_packages_by_name[package.name][0]}]"
849
+ )
850
+
851
+ # #. Check that the source of the package is specified appropriately (i.e.
852
+ # there are no conflicting sources in the package entry);
853
+ # an error MUST be raised if any issues are found.
854
+ # Covered by lock.validate() which is a precondition for this method.
855
+
856
+ # #. Add the package to the set of packages to install.
857
+ selected_packages_by_name[package.name] = (package_index, package)
858
+
859
+ # #. For each package to be installed:
860
+ for package_index, package in selected_packages_by_name.values():
861
+ # - If :ref:`pylock-packages-vcs` is set:
862
+ if package.vcs is not None:
863
+ yield package, package.vcs
864
+
865
+ # - Else if :ref:`pylock-packages-directory` is set:
866
+ elif package.directory is not None:
867
+ yield package, package.directory
868
+
869
+ # - Else if :ref:`pylock-packages-archive` is set:
870
+ elif package.archive is not None:
871
+ yield package, package.archive
872
+
873
+ # - Else if there are entries for :ref:`pylock-packages-wheels`:
874
+ elif package.wheels:
875
+ # #. Look for the appropriate wheel file based on
876
+ # :ref:`pylock-packages-wheels-name`; if one is not found then move
877
+ # on to :ref:`pylock-packages-sdist` or an error MUST be raised about
878
+ # a lack of source for the project.
879
+ best_wheel = next(
880
+ compatible_tags_selector(
881
+ (wheel, parse_wheel_filename(wheel.filename)[-1])
882
+ for wheel in package.wheels
883
+ ),
884
+ None,
885
+ )
886
+ if best_wheel:
887
+ yield package, best_wheel
888
+ elif package.sdist is not None:
889
+ yield package, package.sdist
890
+ else:
891
+ raise PylockSelectError(
892
+ f"No wheel found matching the provided tags "
893
+ f"for package {package.name!r} "
894
+ f"at packages[{package_index}], "
895
+ f"and no sdist available as a fallback"
896
+ )
897
+
898
+ # - Else if no :ref:`pylock-packages-wheels` file is found or
899
+ # :ref:`pylock-packages-sdist` is solely set:
900
+ elif package.sdist is not None:
901
+ yield package, package.sdist
902
+
903
+ else:
904
+ # Covered by lock.validate() which is a precondition for this method.
905
+ raise NotImplementedError # pragma: no cover
.venv/lib/python3.11/site-packages/packaging/requirements.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+ from __future__ import annotations
5
+
6
+ from typing import Iterator
7
+
8
+ from ._parser import parse_requirement as _parse_requirement
9
+ from ._tokenizer import ParserSyntaxError
10
+ from .markers import Marker, _normalize_extra_values
11
+ from .specifiers import SpecifierSet
12
+ from .utils import canonicalize_name
13
+
14
+ __all__ = [
15
+ "InvalidRequirement",
16
+ "Requirement",
17
+ ]
18
+
19
+
20
+ def __dir__() -> list[str]:
21
+ return __all__
22
+
23
+
24
+ class InvalidRequirement(ValueError):
25
+ """
26
+ An invalid requirement was found, users should refer to PEP 508.
27
+ """
28
+
29
+
30
+ class Requirement:
31
+ """Parse a requirement.
32
+
33
+ Parse a given requirement string into its parts, such as name, specifier,
34
+ URL, and extras. Raises InvalidRequirement on a badly-formed requirement
35
+ string.
36
+
37
+ Instances are safe to serialize with :mod:`pickle`. They use a stable
38
+ format so the same pickle can be loaded in future packaging releases.
39
+
40
+ .. versionchanged:: 26.2
41
+
42
+ Added a stable pickle format. Pickles created with packaging 26.2+ can
43
+ be unpickled with future releases. Backward compatibility with pickles
44
+ from packaging < 26.2 is supported but may be removed in a future
45
+ release.
46
+ """
47
+
48
+ # TODO: Can we test whether something is contained within a requirement?
49
+ # If so how do we do that? Do we need to test against the _name_ of
50
+ # the thing as well as the version? What about the markers?
51
+ # TODO: Can we normalize the name and extra name?
52
+
53
+ def __init__(self, requirement_string: str) -> None:
54
+ try:
55
+ parsed = _parse_requirement(requirement_string)
56
+ except ParserSyntaxError as e:
57
+ raise InvalidRequirement(str(e)) from e
58
+
59
+ self.name: str = parsed.name
60
+ self.url: str | None = parsed.url or None
61
+ self.extras: set[str] = set(parsed.extras or [])
62
+ self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
63
+ self.marker: Marker | None = None
64
+ if parsed.marker is not None:
65
+ self.marker = Marker.__new__(Marker)
66
+ self.marker._markers = _normalize_extra_values(parsed.marker)
67
+
68
+ def _iter_parts(self, name: str) -> Iterator[str]:
69
+ yield name
70
+
71
+ if self.extras:
72
+ formatted_extras = ",".join(sorted(self.extras))
73
+ yield f"[{formatted_extras}]"
74
+
75
+ if self.specifier:
76
+ yield str(self.specifier)
77
+
78
+ if self.url:
79
+ yield f" @ {self.url}"
80
+ if self.marker:
81
+ yield " "
82
+
83
+ if self.marker:
84
+ yield f"; {self.marker}"
85
+
86
+ def __getstate__(self) -> str:
87
+ # Return the requirement string for compactness and stability.
88
+ # Re-parsed on load to reconstruct all fields.
89
+ return str(self)
90
+
91
+ def __setstate__(self, state: object) -> None:
92
+ if isinstance(state, str):
93
+ # New format (26.2+): just the requirement string.
94
+ try:
95
+ tmp = Requirement(state)
96
+ except InvalidRequirement as exc:
97
+ raise TypeError(f"Cannot restore Requirement from {state!r}") from exc
98
+ self.name = tmp.name
99
+ self.url = tmp.url
100
+ self.extras = tmp.extras
101
+ self.specifier = tmp.specifier
102
+ self.marker = tmp.marker
103
+ return
104
+ if isinstance(state, dict):
105
+ # Old format (packaging <= 26.1, no __slots__): plain __dict__.
106
+ self.__dict__.update(state)
107
+ return
108
+ raise TypeError(f"Cannot restore Requirement from {state!r}")
109
+
110
+ def __str__(self) -> str:
111
+ return "".join(self._iter_parts(self.name))
112
+
113
+ def __repr__(self) -> str:
114
+ return f"<{self.__class__.__name__}({str(self)!r})>"
115
+
116
+ def __hash__(self) -> int:
117
+ return hash(tuple(self._iter_parts(canonicalize_name(self.name))))
118
+
119
+ def __eq__(self, other: object) -> bool:
120
+ if not isinstance(other, Requirement):
121
+ return NotImplemented
122
+
123
+ return (
124
+ canonicalize_name(self.name) == canonicalize_name(other.name)
125
+ and self.extras == other.extras
126
+ and self.specifier == other.specifier
127
+ and self.url == other.url
128
+ and self.marker == other.marker
129
+ )