ygauravyy commited on
Commit
d49f7bc
1 Parent(s): c141554

Upload 722 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +12 -0
  2. animated_drawings/__init__.py +3 -0
  3. animated_drawings/__pycache__/__init__.cpython-38.pyc +0 -0
  4. animated_drawings/__pycache__/config.cpython-38.pyc +0 -0
  5. animated_drawings/__pycache__/render.cpython-38.pyc +0 -0
  6. animated_drawings/__pycache__/utils.cpython-38.pyc +0 -0
  7. animated_drawings/bin/Activate.ps1 +241 -0
  8. animated_drawings/bin/activate +66 -0
  9. animated_drawings/bin/activate.csh +25 -0
  10. animated_drawings/bin/activate.fish +64 -0
  11. animated_drawings/bin/pip +8 -0
  12. animated_drawings/bin/pip3 +8 -0
  13. animated_drawings/bin/pip3.9 +8 -0
  14. animated_drawings/config.py +619 -0
  15. animated_drawings/controller/__pycache__/controller.cpython-38.pyc +0 -0
  16. animated_drawings/controller/__pycache__/video_render_controller.cpython-38.pyc +0 -0
  17. animated_drawings/controller/controller.py +104 -0
  18. animated_drawings/controller/interactive_controller.py +117 -0
  19. animated_drawings/controller/video_render_controller.py +216 -0
  20. animated_drawings/lib/python3.9/site-packages/_distutils_hack/__init__.py +128 -0
  21. animated_drawings/lib/python3.9/site-packages/_distutils_hack/override.py +1 -0
  22. animated_drawings/lib/python3.9/site-packages/distutils-precedence.pth +1 -0
  23. animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/INSTALLER +1 -0
  24. animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/LICENSE.txt +20 -0
  25. animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/METADATA +92 -0
  26. animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/RECORD +0 -0
  27. animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/REQUESTED +0 -0
  28. animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/WHEEL +5 -0
  29. animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/entry_points.txt +5 -0
  30. animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/top_level.txt +1 -0
  31. animated_drawings/lib/python3.9/site-packages/pip/__init__.py +13 -0
  32. animated_drawings/lib/python3.9/site-packages/pip/__main__.py +31 -0
  33. animated_drawings/lib/python3.9/site-packages/pip/_internal/__init__.py +19 -0
  34. animated_drawings/lib/python3.9/site-packages/pip/_internal/build_env.py +294 -0
  35. animated_drawings/lib/python3.9/site-packages/pip/_internal/cache.py +287 -0
  36. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/__init__.py +4 -0
  37. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py +163 -0
  38. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/base_command.py +214 -0
  39. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/cmdoptions.py +1009 -0
  40. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/command_context.py +27 -0
  41. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/main.py +70 -0
  42. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py +87 -0
  43. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/parser.py +292 -0
  44. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/progress_bars.py +250 -0
  45. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/req_command.py +453 -0
  46. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/spinners.py +157 -0
  47. animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/status_codes.py +6 -0
  48. animated_drawings/lib/python3.9/site-packages/pip/_internal/commands/__init__.py +112 -0
  49. animated_drawings/lib/python3.9/site-packages/pip/_internal/commands/cache.py +216 -0
  50. animated_drawings/lib/python3.9/site-packages/pip/_internal/commands/check.py +47 -0
.gitattributes CHANGED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ examples/characters/char4/background.png filter=lfs diff=lfs merge=lfs -text
2
+ examples/characters/char4/original_img.png filter=lfs diff=lfs merge=lfs -text
3
+ examples/drawings/garlic.png filter=lfs diff=lfs merge=lfs -text
4
+ examples/garlic_out/image.png filter=lfs diff=lfs merge=lfs -text
5
+ examples/garlic_out/video.gif filter=lfs diff=lfs merge=lfs -text
6
+ media/background_example.gif filter=lfs diff=lfs merge=lfs -text
7
+ media/different_bvh_skeleton_example.gif filter=lfs diff=lfs merge=lfs -text
8
+ media/garlic.gif filter=lfs diff=lfs merge=lfs -text
9
+ media/gif_export_video.gif filter=lfs diff=lfs merge=lfs -text
10
+ media/interactive_window_example.gif filter=lfs diff=lfs merge=lfs -text
11
+ media/mp4_export_video.gif filter=lfs diff=lfs merge=lfs -text
12
+ media/multiple_characters_example.gif filter=lfs diff=lfs merge=lfs -text
animated_drawings/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # This source code is licensed under the MIT license found in the
3
+ # LICENSE file in the root directory of this source tree.
animated_drawings/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (156 Bytes). View file
 
animated_drawings/__pycache__/config.cpython-38.pyc ADDED
Binary file (19.1 kB). View file
 
animated_drawings/__pycache__/render.cpython-38.pyc ADDED
Binary file (864 Bytes). View file
 
animated_drawings/__pycache__/utils.cpython-38.pyc ADDED
Binary file (1.78 kB). View file
 
animated_drawings/bin/Activate.ps1 ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .Synopsis
3
+ Activate a Python virtual environment for the current PowerShell session.
4
+
5
+ .Description
6
+ Pushes the python executable for a virtual environment to the front of the
7
+ $Env:PATH environment variable and sets the prompt to signify that you are
8
+ in a Python virtual environment. Makes use of the command line switches as
9
+ well as the `pyvenv.cfg` file values present in the virtual environment.
10
+
11
+ .Parameter VenvDir
12
+ Path to the directory that contains the virtual environment to activate. The
13
+ default value for this is the parent of the directory that the Activate.ps1
14
+ script is located within.
15
+
16
+ .Parameter Prompt
17
+ The prompt prefix to display when this virtual environment is activated. By
18
+ default, this prompt is the name of the virtual environment folder (VenvDir)
19
+ surrounded by parentheses and followed by a single space (ie. '(.venv) ').
20
+
21
+ .Example
22
+ Activate.ps1
23
+ Activates the Python virtual environment that contains the Activate.ps1 script.
24
+
25
+ .Example
26
+ Activate.ps1 -Verbose
27
+ Activates the Python virtual environment that contains the Activate.ps1 script,
28
+ and shows extra information about the activation as it executes.
29
+
30
+ .Example
31
+ Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
32
+ Activates the Python virtual environment located in the specified location.
33
+
34
+ .Example
35
+ Activate.ps1 -Prompt "MyPython"
36
+ Activates the Python virtual environment that contains the Activate.ps1 script,
37
+ and prefixes the current prompt with the specified string (surrounded in
38
+ parentheses) while the virtual environment is active.
39
+
40
+ .Notes
41
+ On Windows, it may be required to enable this Activate.ps1 script by setting the
42
+ execution policy for the user. You can do this by issuing the following PowerShell
43
+ command:
44
+
45
+ PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
46
+
47
+ For more information on Execution Policies:
48
+ https://go.microsoft.com/fwlink/?LinkID=135170
49
+
50
+ #>
51
+ Param(
52
+ [Parameter(Mandatory = $false)]
53
+ [String]
54
+ $VenvDir,
55
+ [Parameter(Mandatory = $false)]
56
+ [String]
57
+ $Prompt
58
+ )
59
+
60
+ <# Function declarations --------------------------------------------------- #>
61
+
62
+ <#
63
+ .Synopsis
64
+ Remove all shell session elements added by the Activate script, including the
65
+ addition of the virtual environment's Python executable from the beginning of
66
+ the PATH variable.
67
+
68
+ .Parameter NonDestructive
69
+ If present, do not remove this function from the global namespace for the
70
+ session.
71
+
72
+ #>
73
+ function global:deactivate ([switch]$NonDestructive) {
74
+ # Revert to original values
75
+
76
+ # The prior prompt:
77
+ if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
78
+ Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
79
+ Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
80
+ }
81
+
82
+ # The prior PYTHONHOME:
83
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
84
+ Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
85
+ Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
86
+ }
87
+
88
+ # The prior PATH:
89
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
90
+ Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
91
+ Remove-Item -Path Env:_OLD_VIRTUAL_PATH
92
+ }
93
+
94
+ # Just remove the VIRTUAL_ENV altogether:
95
+ if (Test-Path -Path Env:VIRTUAL_ENV) {
96
+ Remove-Item -Path env:VIRTUAL_ENV
97
+ }
98
+
99
+ # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
100
+ if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
101
+ Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
102
+ }
103
+
104
+ # Leave deactivate function in the global namespace if requested:
105
+ if (-not $NonDestructive) {
106
+ Remove-Item -Path function:deactivate
107
+ }
108
+ }
109
+
110
+ <#
111
+ .Description
112
+ Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
113
+ given folder, and returns them in a map.
114
+
115
+ For each line in the pyvenv.cfg file, if that line can be parsed into exactly
116
+ two strings separated by `=` (with any amount of whitespace surrounding the =)
117
+ then it is considered a `key = value` line. The left hand string is the key,
118
+ the right hand is the value.
119
+
120
+ If the value starts with a `'` or a `"` then the first and last character is
121
+ stripped from the value before being captured.
122
+
123
+ .Parameter ConfigDir
124
+ Path to the directory that contains the `pyvenv.cfg` file.
125
+ #>
126
+ function Get-PyVenvConfig(
127
+ [String]
128
+ $ConfigDir
129
+ ) {
130
+ Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
131
+
132
+ # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
133
+ $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
134
+
135
+ # An empty map will be returned if no config file is found.
136
+ $pyvenvConfig = @{ }
137
+
138
+ if ($pyvenvConfigPath) {
139
+
140
+ Write-Verbose "File exists, parse `key = value` lines"
141
+ $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
142
+
143
+ $pyvenvConfigContent | ForEach-Object {
144
+ $keyval = $PSItem -split "\s*=\s*", 2
145
+ if ($keyval[0] -and $keyval[1]) {
146
+ $val = $keyval[1]
147
+
148
+ # Remove extraneous quotations around a string value.
149
+ if ("'""".Contains($val.Substring(0, 1))) {
150
+ $val = $val.Substring(1, $val.Length - 2)
151
+ }
152
+
153
+ $pyvenvConfig[$keyval[0]] = $val
154
+ Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
155
+ }
156
+ }
157
+ }
158
+ return $pyvenvConfig
159
+ }
160
+
161
+
162
+ <# Begin Activate script --------------------------------------------------- #>
163
+
164
+ # Determine the containing directory of this script
165
+ $VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
166
+ $VenvExecDir = Get-Item -Path $VenvExecPath
167
+
168
+ Write-Verbose "Activation script is located in path: '$VenvExecPath'"
169
+ Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
170
+ Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
171
+
172
+ # Set values required in priority: CmdLine, ConfigFile, Default
173
+ # First, get the location of the virtual environment, it might not be
174
+ # VenvExecDir if specified on the command line.
175
+ if ($VenvDir) {
176
+ Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
177
+ }
178
+ else {
179
+ Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
180
+ $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
181
+ Write-Verbose "VenvDir=$VenvDir"
182
+ }
183
+
184
+ # Next, read the `pyvenv.cfg` file to determine any required value such
185
+ # as `prompt`.
186
+ $pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
187
+
188
+ # Next, set the prompt from the command line, or the config file, or
189
+ # just use the name of the virtual environment folder.
190
+ if ($Prompt) {
191
+ Write-Verbose "Prompt specified as argument, using '$Prompt'"
192
+ }
193
+ else {
194
+ Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
195
+ if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
196
+ Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
197
+ $Prompt = $pyvenvCfg['prompt'];
198
+ }
199
+ else {
200
+ Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virutal environment)"
201
+ Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
202
+ $Prompt = Split-Path -Path $venvDir -Leaf
203
+ }
204
+ }
205
+
206
+ Write-Verbose "Prompt = '$Prompt'"
207
+ Write-Verbose "VenvDir='$VenvDir'"
208
+
209
+ # Deactivate any currently active virtual environment, but leave the
210
+ # deactivate function in place.
211
+ deactivate -nondestructive
212
+
213
+ # Now set the environment variable VIRTUAL_ENV, used by many tools to determine
214
+ # that there is an activated venv.
215
+ $env:VIRTUAL_ENV = $VenvDir
216
+
217
+ if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
218
+
219
+ Write-Verbose "Setting prompt to '$Prompt'"
220
+
221
+ # Set the prompt to include the env name
222
+ # Make sure _OLD_VIRTUAL_PROMPT is global
223
+ function global:_OLD_VIRTUAL_PROMPT { "" }
224
+ Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
225
+ New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
226
+
227
+ function global:prompt {
228
+ Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
229
+ _OLD_VIRTUAL_PROMPT
230
+ }
231
+ }
232
+
233
+ # Clear PYTHONHOME
234
+ if (Test-Path -Path Env:PYTHONHOME) {
235
+ Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
236
+ Remove-Item -Path Env:PYTHONHOME
237
+ }
238
+
239
+ # Add the venv to the PATH
240
+ Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
241
+ $Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
animated_drawings/bin/activate ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source bin/activate" *from bash*
2
+ # you cannot run it directly
3
+
4
+ deactivate () {
5
+ # reset old environment variables
6
+ if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
7
+ PATH="${_OLD_VIRTUAL_PATH:-}"
8
+ export PATH
9
+ unset _OLD_VIRTUAL_PATH
10
+ fi
11
+ if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
12
+ PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
13
+ export PYTHONHOME
14
+ unset _OLD_VIRTUAL_PYTHONHOME
15
+ fi
16
+
17
+ # This should detect bash and zsh, which have a hash command that must
18
+ # be called to get it to forget past commands. Without forgetting
19
+ # past commands the $PATH changes we made may not be respected
20
+ if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
21
+ hash -r 2> /dev/null
22
+ fi
23
+
24
+ if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
25
+ PS1="${_OLD_VIRTUAL_PS1:-}"
26
+ export PS1
27
+ unset _OLD_VIRTUAL_PS1
28
+ fi
29
+
30
+ unset VIRTUAL_ENV
31
+ if [ ! "${1:-}" = "nondestructive" ] ; then
32
+ # Self destruct!
33
+ unset -f deactivate
34
+ fi
35
+ }
36
+
37
+ # unset irrelevant variables
38
+ deactivate nondestructive
39
+
40
+ VIRTUAL_ENV="/Users/gauravyadav/AnimatedDrawings/animated_drawings"
41
+ export VIRTUAL_ENV
42
+
43
+ _OLD_VIRTUAL_PATH="$PATH"
44
+ PATH="$VIRTUAL_ENV/bin:$PATH"
45
+ export PATH
46
+
47
+ # unset PYTHONHOME if set
48
+ # this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
49
+ # could use `if (set -u; : $PYTHONHOME) ;` in bash
50
+ if [ -n "${PYTHONHOME:-}" ] ; then
51
+ _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
52
+ unset PYTHONHOME
53
+ fi
54
+
55
+ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
56
+ _OLD_VIRTUAL_PS1="${PS1:-}"
57
+ PS1="(animated_drawings) ${PS1:-}"
58
+ export PS1
59
+ fi
60
+
61
+ # This should detect bash and zsh, which have a hash command that must
62
+ # be called to get it to forget past commands. Without forgetting
63
+ # past commands the $PATH changes we made may not be respected
64
+ if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
65
+ hash -r 2> /dev/null
66
+ fi
animated_drawings/bin/activate.csh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source bin/activate.csh" *from csh*.
2
+ # You cannot run it directly.
3
+ # Created by Davide Di Blasi <davidedb@gmail.com>.
4
+ # Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
5
+
6
+ alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
7
+
8
+ # Unset irrelevant variables.
9
+ deactivate nondestructive
10
+
11
+ setenv VIRTUAL_ENV "/Users/gauravyadav/AnimatedDrawings/animated_drawings"
12
+
13
+ set _OLD_VIRTUAL_PATH="$PATH"
14
+ setenv PATH "$VIRTUAL_ENV/bin:$PATH"
15
+
16
+
17
+ set _OLD_VIRTUAL_PROMPT="$prompt"
18
+
19
+ if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
20
+ set prompt = "(animated_drawings) $prompt"
21
+ endif
22
+
23
+ alias pydoc python -m pydoc
24
+
25
+ rehash
animated_drawings/bin/activate.fish ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source <venv>/bin/activate.fish" *from fish*
2
+ # (https://fishshell.com/); you cannot run it directly.
3
+
4
+ function deactivate -d "Exit virtual environment and return to normal shell environment"
5
+ # reset old environment variables
6
+ if test -n "$_OLD_VIRTUAL_PATH"
7
+ set -gx PATH $_OLD_VIRTUAL_PATH
8
+ set -e _OLD_VIRTUAL_PATH
9
+ end
10
+ if test -n "$_OLD_VIRTUAL_PYTHONHOME"
11
+ set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
12
+ set -e _OLD_VIRTUAL_PYTHONHOME
13
+ end
14
+
15
+ if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
16
+ functions -e fish_prompt
17
+ set -e _OLD_FISH_PROMPT_OVERRIDE
18
+ functions -c _old_fish_prompt fish_prompt
19
+ functions -e _old_fish_prompt
20
+ end
21
+
22
+ set -e VIRTUAL_ENV
23
+ if test "$argv[1]" != "nondestructive"
24
+ # Self-destruct!
25
+ functions -e deactivate
26
+ end
27
+ end
28
+
29
+ # Unset irrelevant variables.
30
+ deactivate nondestructive
31
+
32
+ set -gx VIRTUAL_ENV "/Users/gauravyadav/AnimatedDrawings/animated_drawings"
33
+
34
+ set -gx _OLD_VIRTUAL_PATH $PATH
35
+ set -gx PATH "$VIRTUAL_ENV/bin" $PATH
36
+
37
+ # Unset PYTHONHOME if set.
38
+ if set -q PYTHONHOME
39
+ set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
40
+ set -e PYTHONHOME
41
+ end
42
+
43
+ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
44
+ # fish uses a function instead of an env var to generate the prompt.
45
+
46
+ # Save the current fish_prompt function as the function _old_fish_prompt.
47
+ functions -c fish_prompt _old_fish_prompt
48
+
49
+ # With the original prompt function renamed, we can override with our own.
50
+ function fish_prompt
51
+ # Save the return status of the last command.
52
+ set -l old_status $status
53
+
54
+ # Output the venv prompt; color taken from the blue of the Python logo.
55
+ printf "%s%s%s" (set_color 4B8BBE) "(animated_drawings) " (set_color normal)
56
+
57
+ # Restore the return status of the previous command.
58
+ echo "exit $old_status" | .
59
+ # Output the original/"old" prompt.
60
+ _old_fish_prompt
61
+ end
62
+
63
+ set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
64
+ end
animated_drawings/bin/pip ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/gauravyadav/AnimatedDrawings/animated_drawings/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from pip._internal.cli.main import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
animated_drawings/bin/pip3 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/gauravyadav/AnimatedDrawings/animated_drawings/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from pip._internal.cli.main import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
animated_drawings/bin/pip3.9 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/Users/gauravyadav/AnimatedDrawings/animated_drawings/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from pip._internal.cli.main import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
animated_drawings/config.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # This source code is licensed under the MIT license found in the
3
+ # LICENSE file in the root directory of this source tree.
4
+
5
+ from __future__ import annotations
6
+ import logging
7
+ from collections import defaultdict
8
+ from pathlib import Path
9
+ from typing import Union, List, Tuple, Dict, TypedDict, Optional
10
+ import yaml
11
+ from pkg_resources import resource_filename
12
+ from animated_drawings.utils import resolve_ad_filepath
13
+
14
+
15
+ class Config():
16
+
17
+ def __init__(self, user_mvc_cfg_fn: str) -> None:
18
+ # get the base mvc config
19
+ with open(resource_filename(__name__, "mvc_base_cfg.yaml"), 'r') as f:
20
+ base_cfg = defaultdict(dict, yaml.load(f, Loader=yaml.FullLoader) or {}) # pyright: ignore[reportUnknownMemberType])
21
+
22
+ # search for the user-specified mvc config
23
+ user_mvc_cfg_p: Path = resolve_ad_filepath(user_mvc_cfg_fn, 'user mvc config')
24
+ logging.info(f'Using user-specified mvc config file located at {user_mvc_cfg_p.resolve()}')
25
+ with open(str(user_mvc_cfg_p), 'r') as f:
26
+ user_cfg = defaultdict(dict, yaml.load(f, Loader=yaml.FullLoader) or {}) # pyright: ignore[reportUnknownMemberType]
27
+
28
+ # overlay user specified mvc options onto base mvc, use to generate subconfig classes
29
+ self.view: ViewConfig = ViewConfig({**base_cfg['view'], **user_cfg['view']})
30
+ self.scene: SceneConfig = SceneConfig({**base_cfg['scene'], **user_cfg['scene']})
31
+ self.controller: ControllerConfig = ControllerConfig({**base_cfg['controller'], **user_cfg['controller']})
32
+
33
+ # cannot use an interactive controller with a headless mesa viewer
34
+ if self.controller.mode == 'interact':
35
+ try:
36
+ assert self.view.use_mesa is False, 'cannot use interactive controller when USE_MESA is True'
37
+ except AssertionError as e:
38
+ msg = f'Config error: {e}'
39
+ logging.critical(msg)
40
+ assert False, msg
41
+
42
+ # output video path must be set for render controller
43
+ if self.controller.mode == 'video_render':
44
+ try:
45
+ assert self.controller.output_video_path is not None, 'output_video_path must be set when using video_render controller'
46
+ except AssertionError as e:
47
+ msg = f'Config error: {e}'
48
+ logging.critical(msg)
49
+ assert False, msg
50
+
51
+ # output video codec must be set for render controller with .mp4 output filetype
52
+ if self.controller.mode == 'video_render' and self.controller.output_video_path is not None and self.controller.output_video_path.endswith('.mp4'):
53
+ try:
54
+ assert self.controller.output_video_codec is not None, 'output_video_codec must be set when using video_render controller'
55
+ except AssertionError as e:
56
+ msg = f'Config error: {e}'
57
+ logging.critical(msg)
58
+ assert False, msg
59
+
60
+
61
+ class SceneConfig():
62
+
63
+ def __init__(self, scene_cfg: dict) -> None:
64
+
65
+ # show or hide the floor
66
+ try:
67
+ self.add_floor: bool = scene_cfg['ADD_FLOOR']
68
+ assert isinstance(self.add_floor, bool), 'is not bool'
69
+ except (AssertionError, ValueError) as e:
70
+ msg = f'Error in ADD_FLOOR config parameter: {e}'
71
+ logging.critical(msg)
72
+ assert False, msg
73
+
74
+ # show or hide visualization of BVH motion driving characters
75
+ try:
76
+ self.add_ad_retarget_bvh: bool = scene_cfg['ADD_AD_RETARGET_BVH']
77
+ assert isinstance(self.add_ad_retarget_bvh, bool), 'is not bool'
78
+ except (AssertionError, ValueError) as e:
79
+ msg = f'Error in ADD_AD_RETARGET_BVH config parameter: {e}'
80
+ logging.critical(msg)
81
+ assert False, msg
82
+
83
+ # config files for characters, driving motions, and retargeting
84
+ self.animated_characters: List[Tuple[CharacterConfig, RetargetConfig, MotionConfig]] = []
85
+
86
+ each: Dict[str, str]
87
+ for each in scene_cfg['ANIMATED_CHARACTERS']:
88
+ char_cfg_fn: str = each['character_cfg']
89
+ motion_cfg_fn: str = each['motion_cfg']
90
+ retarget_cfg_fn: str = each['retarget_cfg']
91
+ self.animated_characters.append((
92
+ CharacterConfig(char_cfg_fn),
93
+ RetargetConfig(retarget_cfg_fn),
94
+ MotionConfig(motion_cfg_fn)
95
+ ))
96
+
97
+
98
+ class ViewConfig():
99
+
100
+ def __init__(self, view_cfg: dict) -> None: # noqa: C901
101
+
102
+ # set color used to clear render buffer
103
+ try:
104
+ self.clear_color: list[Union[float, int]] = view_cfg["CLEAR_COLOR"]
105
+ assert len(self.clear_color) == 4, 'length not four'
106
+ for val in self.clear_color:
107
+ assert isinstance(val, (float, int)), f'{val} not float or int'
108
+ assert val <= 1.0, 'values must be <= 1.0'
109
+ assert val >= 0.0, 'values must be >= 0.0'
110
+ except (AssertionError, ValueError) as e:
111
+ msg = f'Error in CLEAR_COLOR config parameter: {e}'
112
+ logging.critical(msg)
113
+ assert False, msg
114
+
115
+ # set an image to use for the background, if desired
116
+ try:
117
+ self.background_image: Union[None, str] = view_cfg["BACKGROUND_IMAGE"]
118
+ assert isinstance(self.background_image, (NoneType, str)), 'type not NoneType or str'
119
+ except (AssertionError, ValueError) as e:
120
+ msg = f'Error in BACKGROUND_IMAGE config parameter: {e}'
121
+ logging.critical(msg)
122
+ assert False, msg
123
+
124
+ # set the dimensions of the window or output video
125
+ try:
126
+ self.window_dimensions: tuple[int, int] = view_cfg["WINDOW_DIMENSIONS"]
127
+ assert len(self.window_dimensions) == 2, 'length is not 2'
128
+ for val in self.window_dimensions:
129
+ assert val > 0, f'{val} must be > 0'
130
+ assert isinstance(val, int), 'type not int'
131
+ except (AssertionError, ValueError) as e:
132
+ msg = f'Error in WINDOW_DIMENSIONS config parameter: {e}'
133
+ logging.critical(msg)
134
+ assert False, msg
135
+
136
+ # set whether we want the character rigs to be visible
137
+ try:
138
+ self.draw_ad_rig: bool = view_cfg['DRAW_AD_RIG']
139
+ assert isinstance(self.draw_ad_rig, bool), 'value is not bool type'
140
+ except (AssertionError, ValueError) as e:
141
+ msg = f'Error in DRAW_AD_RIG config parameter: {e}'
142
+ logging.critical(msg)
143
+ assert False, msg
144
+
145
+ # set whether we want the character textures to be visible
146
+ try:
147
+ self.draw_ad_txtr: bool = view_cfg['DRAW_AD_TXTR']
148
+ assert isinstance(self.draw_ad_txtr, bool), 'value is not bool type'
149
+ except (AssertionError, ValueError) as e:
150
+ msg = f'Error in DRAW_AD_TXTR config parameter: {e}'
151
+ logging.critical(msg)
152
+ assert False, msg
153
+
154
+ # set whether we want the character triangle->bone assignment colors to be visible
155
+ try:
156
+ self.draw_ad_color: bool = view_cfg['DRAW_AD_COLOR']
157
+ assert isinstance(self.draw_ad_color, bool), 'value is not bool type'
158
+ except (AssertionError, ValueError) as e:
159
+ msg = f'Error in DRAW_AD_COLOR config parameter: {e}'
160
+ logging.critical(msg)
161
+ assert False, msg
162
+
163
+ # set whether we want the character mesh lines to be visible
164
+ try:
165
+ self.draw_ad_mesh_lines: bool = view_cfg['DRAW_AD_MESH_LINES']
166
+ assert isinstance(self.draw_ad_mesh_lines, bool), 'value is not bool type'
167
+ except (AssertionError, ValueError) as e:
168
+ msg = f'Error in DRAW_AD_MESH_LINES config parameter: {e}'
169
+ logging.critical(msg)
170
+ assert False, msg
171
+
172
+ # set whether we want to use mesa on the back end (necessary for headless rendering)
173
+ try:
174
+ self.use_mesa: bool = view_cfg['USE_MESA']
175
+ assert isinstance(self.use_mesa, bool), 'value is not bool type'
176
+ except (AssertionError, ValueError) as e:
177
+ msg = f'Error in USE_MESA config parameter: {e}'
178
+ logging.critical(msg)
179
+ assert False, msg
180
+
181
+ # set the position of the view camera
182
+ try:
183
+ self.camera_pos: list[Union[float, int]] = view_cfg['CAMERA_POS']
184
+ assert len(self.camera_pos) == 3, 'length != 3'
185
+ for val in self.camera_pos:
186
+ assert isinstance(val, (float, int)), f' {val} is not float or int'
187
+ except (AssertionError, ValueError) as e:
188
+ msg = f'Error in CAMERA_POS config parameter: {e}'
189
+ logging.critical(msg)
190
+ assert False, msg
191
+
192
+ # set the forward vector of the view camera (but it renders out of it's rear)
193
+ try:
194
+ self.camera_fwd: list[Union[float, int]] = view_cfg['CAMERA_FWD']
195
+ assert len(self.camera_fwd) == 3, 'length != 3'
196
+ for val in self.camera_fwd:
197
+ assert isinstance(val, (float, int)), f' {val} is not float or int'
198
+ except (AssertionError, ValueError) as e:
199
+ msg = f'Error in CAMERA_FWD config parameter: {e}'
200
+ logging.critical(msg)
201
+ assert False, msg
202
+
203
+
204
+ class ControllerConfig():
205
+
206
+ def __init__(self, controller_cfg: dict) -> None:
207
+
208
+ # set controller mode
209
+ try:
210
+ self.mode: str = controller_cfg["MODE"]
211
+ assert isinstance(self.mode, str), 'is not str'
212
+ assert self.mode in ('interactive', 'video_render'), 'mode not interactive or video_render'
213
+ except (AssertionError, ValueError) as e:
214
+ msg = f'Error in MODE config parameter: {e}'
215
+ logging.critical(msg)
216
+ assert False, msg
217
+
218
+ # set timestep for user interactions in interactive mode
219
+ try:
220
+ self.keyboard_timestep: Union[float, int] = controller_cfg["KEYBOARD_TIMESTEP"]
221
+ assert isinstance(self.keyboard_timestep, (float, int)), 'is not floar or int'
222
+ assert self.keyboard_timestep > 0, 'timestep val must be > 0'
223
+ except (AssertionError, ValueError) as e:
224
+ msg = f'Error in KEYBOARD_TIMESTEP config parameter: {e}'
225
+ logging.critical(msg)
226
+ assert False, msg
227
+
228
+ # set output video path (only use in video_render mode)
229
+ try:
230
+ self.output_video_path: Union[None, str] = controller_cfg['OUTPUT_VIDEO_PATH']
231
+ assert isinstance(self.output_video_path, (NoneType, str)), 'type is not None or str'
232
+ if isinstance(self.output_video_path, str):
233
+ assert Path(self.output_video_path).suffix in ('.gif', '.mp4'), 'output video extension not .gif or .mp4 '
234
+ except (AssertionError, ValueError) as e:
235
+ msg = f'Error in OUTPUT_VIDEO_PATH config parameter: {e}'
236
+ logging.critical(msg)
237
+ assert False, msg
238
+
239
+ # set output video codec (only use in video_render mode with .mp4)
240
+ try:
241
+ self.output_video_codec: Union[None, str] = controller_cfg['OUTPUT_VIDEO_CODEC']
242
+ assert isinstance(self.output_video_codec, (NoneType, str)), 'type is not None or str'
243
+ except (AssertionError, ValueError) as e:
244
+ msg = f'Error in OUTPUT_VIDEO_CODEC config parameter: {e}'
245
+ logging.critical(msg)
246
+ assert False, msg
247
+
248
+
249
+ class CharacterConfig():
250
+
251
+ class JointDict(TypedDict):
252
+ loc: List[float]
253
+ name: str
254
+ parent: Union[None, str]
255
+
256
+ def __init__(self, char_cfg_fn: str) -> None: # noqa: C901
257
+ character_cfg_p = resolve_ad_filepath(char_cfg_fn, 'character cfg')
258
+ with open(str(character_cfg_p), 'r') as f:
259
+ char_cfg = yaml.load(f, Loader=yaml.FullLoader)
260
+
261
+ # validate image height
262
+ try:
263
+ self.img_height: int = char_cfg['height']
264
+ assert isinstance(self.img_height, int), 'type not int'
265
+ assert self.img_height > 0, 'must be > 0'
266
+ except (AssertionError, ValueError) as e:
267
+ msg = f'Error in character height config parameter: {e}'
268
+ logging.critical(msg)
269
+ assert False, msg
270
+
271
+ # validate image width
272
+ try:
273
+ self.img_width: int = char_cfg['width']
274
+ assert isinstance(self.img_width, int), 'type not int'
275
+ assert self.img_width > 0, 'must be > 0'
276
+ except (AssertionError, ValueError) as e:
277
+ msg = f'Error in character width config parameter: {e}'
278
+ logging.critical(msg)
279
+ assert False, msg
280
+
281
+ # based on height and width, determine what final img dimension will be (post padding)
282
+ self.img_dim: int = max(self.img_height, self.img_width)
283
+
284
+ # validate skeleton
285
+ try:
286
+ self.skeleton: List[CharacterConfig.JointDict] = []
287
+ for joint in char_cfg['skeleton']:
288
+
289
+ # ensure loc input is valid...
290
+ loc: List[int] = joint['loc']
291
+ assert len(loc) == 2, 'joint loc must be of length 2'
292
+ assert loc[0] >= 0, 'x val must be >= 0'
293
+ assert loc[0] < self.img_width, 'x val must be < image width'
294
+ assert loc[1] >= 0, 'y val must be >= 0'
295
+ assert loc[1] < self.img_height, 'y val must be < image height'
296
+
297
+ # ... then scale to between 0-1 based on img dim
298
+ loc_x: float = loc[0] / self.img_dim # width
299
+ loc_y: float = loc[1] / self.img_dim + (1 - self.img_height / self.img_dim) # height
300
+
301
+ # validate joint name
302
+ name: str = joint['name']
303
+ assert isinstance(name, str), 'name must be str'
304
+
305
+ # validate joint parent
306
+ parent: Union[None, str] = joint['parent']
307
+ assert isinstance(parent, (NoneType, str)), 'parent must be str or NoneType'
308
+
309
+ self.skeleton.append({'loc': [loc_x, loc_y], 'name': name, 'parent': parent})
310
+ except AssertionError as e:
311
+ msg = f'Error in character skeleton: {e}'
312
+ logging.critical(msg)
313
+ assert False, msg
314
+
315
+ # validate skeleton joint parents
316
+ try:
317
+ names: List[str] = [joint['name'] for joint in self.skeleton]
318
+ for joint in self.skeleton:
319
+ assert isinstance(joint['parent'], NoneType) or joint['parent'] in names, f'joint.parent not None and not valid joint name: {joint}'
320
+ except AssertionError as e:
321
+ msg = f'Error in character skeleton: {e}'
322
+ logging.critical(msg)
323
+ assert False, msg
324
+
325
+ # validate mask and texture files
326
+ try:
327
+ self.mask_p: Path = character_cfg_p.parent / 'mask.png'
328
+ self.txtr_p: Path = character_cfg_p.parent / 'texture.png'
329
+ assert self.mask_p.exists(), f'cannot find character mask: {self.mask_p}'
330
+ assert self.txtr_p.exists(), f'cannot find character texture: {self.txtr_p}'
331
+ except AssertionError as e:
332
+ msg = f'Error validating character files: {e}'
333
+ logging.critical(msg)
334
+ assert False, msg
335
+
336
+
337
+ class MotionConfig():
338
+
339
+ def __init__(self, motion_cfg_fn: str) -> None: # noqa: C901
340
+ motion_cfg_p = resolve_ad_filepath(motion_cfg_fn, 'motion cfg')
341
+ with open(str(motion_cfg_p), 'r') as f:
342
+ motion_cfg = yaml.load(f, Loader=yaml.FullLoader)
343
+
344
+ # validate start_frame_idx
345
+ try:
346
+ self.start_frame_idx: int = motion_cfg.get('start_frame_idx', 0)
347
+ assert isinstance(self.start_frame_idx, int), 'type not int'
348
+ assert self.start_frame_idx >= 0, 'start_frame_idx must be > 0'
349
+ except (AssertionError, ValueError) as e:
350
+ msg = f'Error validating start_frame_idx: {e}'
351
+ logging.critical(msg)
352
+ assert False, msg
353
+
354
+ # validate end_frame_idx
355
+ try:
356
+ self.end_frame_idx: Optional[int] = motion_cfg.get('end_frame_idx', None)
357
+ assert isinstance(self.end_frame_idx, (NoneType, int)), 'type not NoneType or int'
358
+ if isinstance(self.end_frame_idx, int):
359
+ assert self.end_frame_idx >= self.start_frame_idx, 'end_frame_idx must be > start_frame_idx'
360
+ except (AssertionError, ValueError) as e:
361
+ msg = f'Error validating end_frame_idx: {e}'
362
+ logging.critical(msg)
363
+ assert False, msg
364
+
365
+ # validate frame time override
366
+ try:
367
+ self.frame_time: Optional[float] = motion_cfg.get('frame_time', None)
368
+ assert isinstance(self.frame_time, (NoneType, float)), 'is not None or float'
369
+ except (AssertionError, ValueError) as e:
370
+ msg = f'Error in frame_time config parameter: {e}'
371
+ logging.critical(msg)
372
+ assert False, msg
373
+
374
+ # validate groundplane joint
375
+ try:
376
+ self.groundplane_joint: str = motion_cfg['groundplane_joint']
377
+ assert isinstance(self.groundplane_joint, str), 'groundplane joint must be str'
378
+ except (AssertionError, ValueError) as e:
379
+ msg = f'Error validating groundplane joint: {e}'
380
+ logging.critical(msg)
381
+ assert False, msg
382
+
383
+ # validate forward_perp_joint_vectors
384
+ try:
385
+ self.forward_perp_joint_vectors: List[Tuple[str, str]] = motion_cfg['forward_perp_joint_vectors']
386
+ assert len(self.forward_perp_joint_vectors) > 0, 'forward_perp_joint_vectors len must be > 0'
387
+ for each in self.forward_perp_joint_vectors:
388
+ assert len(each) == 2, 'each list in forrward_perp_joint_vectors must have len = 2'
389
+ except (AssertionError, ValueError) as e:
390
+ msg = f'Error validating forward_perp_joint_vectors: {e}'
391
+ logging.critical(msg)
392
+ assert False, msg
393
+
394
+ # validate scale
395
+ try:
396
+ self.scale: float = motion_cfg['scale']
397
+ assert isinstance(self.scale, (int, float)), 'scale must be float or int'
398
+ assert self.scale > 0, 'scale must be > 0'
399
+ except (AssertionError, ValueError) as e:
400
+ msg = f'Error validating scale: {e}'
401
+ logging.critical(msg)
402
+ assert False, msg
403
+
404
+ # validate up
405
+ try:
406
+ self.up: str = motion_cfg['up']
407
+ assert self.up in ['+y', '+z'], 'up must be "+y" or "+z'
408
+ except (AssertionError, ValueError) as e:
409
+ msg = f'Error validating up: {e}'
410
+ logging.critical(msg)
411
+ assert False, msg
412
+
413
+ # validate bvh_p
414
+ try:
415
+ self.bvh_p: Path = resolve_ad_filepath(motion_cfg['filepath'], 'bvh filepath')
416
+ except (AssertionError, ValueError) as e:
417
+ msg = f'Error validating bvh_p: {e}'
418
+ logging.critical(msg)
419
+ assert False, msg
420
+
421
+ def validate_bvh(self, bvh_joint_names: List[str]) -> None:
422
+ """ Performs all the validation steps that depend upon knowing the BVH joint names. This should be called once the BVH had been loaded."""
423
+ try:
424
+ for prox_joint_name, dist_joint_name in self.forward_perp_joint_vectors:
425
+ assert prox_joint_name in bvh_joint_names, f'invalid prox_joint name in motion_cfg.forward_perp_joint_vectors: {prox_joint_name}'
426
+ assert dist_joint_name in bvh_joint_names, f'invalid dist_joint name in motion_cfg.forward_perp_joint_vectors: {dist_joint_name}'
427
+ except (AssertionError, ValueError) as e:
428
+ msg = f'Error validating forward_perp_joint_vector joints: {e}'
429
+ logging.critical(msg)
430
+ assert False, msg
431
+
432
+
433
+ class RetargetConfig():
434
+
435
+ class BvhProjectionBodypartGroup(TypedDict):
436
+ bvh_joint_names: List[str]
437
+ method: str
438
+ name: str
439
+
440
+ class CharBodypartGroup(TypedDict):
441
+ bvh_depth_drivers: List[str]
442
+ char_joints: List[str]
443
+
444
+ class CharBvhRootOffset(TypedDict):
445
+ bvh_projection_bodypart_group_for_offset: str
446
+ bvh_joints: List[List[str]]
447
+ char_joints: List[List[str]]
448
+
449
+ def __init__(self, retarget_cfg_fn: str) -> None: # noqa: C901
450
+ retarget_cfg_p = resolve_ad_filepath(retarget_cfg_fn, 'retarget cfg')
451
+ with open(str(retarget_cfg_p), 'r') as f:
452
+ retarget_cfg = yaml.load(f, Loader=yaml.FullLoader)
453
+
454
+ # validate character starting location
455
+ try:
456
+ self.char_start_loc = retarget_cfg['char_starting_location']
457
+ assert len(self.char_start_loc) == 3, 'char start loc must be of len 3'
458
+ for val in self.char_start_loc:
459
+ assert isinstance(val, (float, int)), 'type must be float or int'
460
+ except (AssertionError, ValueError) as e:
461
+ msg = f'Error validating char start location: {e}'
462
+ logging.critical(msg)
463
+ assert False, msg
464
+
465
+ # validate bvh project bodypart groups
466
+ self.bvh_projection_bodypart_groups: List[RetargetConfig.BvhProjectionBodypartGroup]
467
+ try:
468
+ self.bvh_projection_bodypart_groups = retarget_cfg['bvh_projection_bodypart_groups']
469
+
470
+ for group in self.bvh_projection_bodypart_groups:
471
+ assert group['method'] in ['pca', 'sagittal', 'frontal'], 'group method must be "pca", "sagittal", or "frontal"'
472
+ except (AssertionError, ValueError) as e:
473
+ msg = f'Error validating bvh_projection_bodypart_groups: {e}'
474
+ logging.critical(msg)
475
+ assert False, msg
476
+
477
+ # Check that group names are unique
478
+ try:
479
+ group_names = [group['name'] for group in self.bvh_projection_bodypart_groups]
480
+ assert len(group_names) == len(set(group_names)), 'group names are not unique'
481
+ except AssertionError as e:
482
+ msg = f'Error validating bvh_projection_bodypart_groups: {e}'
483
+ logging.critical(msg)
484
+ assert False, msg
485
+
486
+ # validate char bodypart groups
487
+ self.char_bodypart_groups: List[RetargetConfig.CharBodypartGroup]
488
+ try:
489
+ self.char_bodypart_groups = retarget_cfg['char_bodypart_groups']
490
+ for group in self.char_bodypart_groups:
491
+ assert len(group['bvh_depth_drivers']) > 0, 'bvh_depth_drivers must have at least one joint specified'
492
+ except (AssertionError, ValueError) as e:
493
+ msg = f'Error validating char_bodypart_groups: {e}'
494
+ logging.critical(msg)
495
+ assert False, msg
496
+
497
+ # validate char bvh root offset
498
+ self.char_bvh_root_offset: RetargetConfig.CharBvhRootOffset
499
+ try:
500
+ self.char_bvh_root_offset = retarget_cfg['char_bvh_root_offset']
501
+ assert len(self.char_bvh_root_offset['bvh_joints']) > 0, 'bvh_joints list must be greater than zero'
502
+ for each in self.char_bvh_root_offset['bvh_joints']:
503
+ assert len(each) > 0, 'each list in bvh_joints must have len > 0'
504
+
505
+ assert len(self.char_bvh_root_offset['char_joints']) > 0, 'char_joints list must be greater than zero'
506
+ for each in self.char_bvh_root_offset['char_joints']:
507
+ assert len(each) > 0, 'each list in char_joints must have len > 0'
508
+
509
+ assert isinstance(self.char_bvh_root_offset['bvh_projection_bodypart_group_for_offset'], str), 'bvh_projection_bodypart_group_for_offset must be str'
510
+ except (AssertionError, ValueError) as e:
511
+ msg = f'Error validating char_bvh_root_offset: {e}'
512
+ logging.critical(msg)
513
+ assert False, msg
514
+
515
+ # validate char joint bvh joints mapping
516
+ self.char_joint_bvh_joints_mapping: Dict[str, Tuple[str, str]]
517
+ try:
518
+ self.char_joint_bvh_joints_mapping = retarget_cfg['char_joint_bvh_joints_mapping']
519
+ for key, val in self.char_joint_bvh_joints_mapping.items():
520
+ assert isinstance(key, str), 'key must be str'
521
+ assert isinstance(val, tuple), 'val must be tuple'
522
+ assert len(val) == 2, 'val must be of len 2'
523
+ assert isinstance(val[0], str) and isinstance(val[1], str), 'values must be str'
524
+ except (AssertionError, ValueError) as e:
525
+ msg = f'Error validating char_bvh_root_offset: {e}'
526
+ logging.critical(msg)
527
+ assert False, msg
528
+
529
+ # validate char runtime checks
530
+ self.char_runtime_checks: List[str]
531
+ try:
532
+ self.char_runtime_checks = retarget_cfg['char_runtime_checks']
533
+ for check in self.char_runtime_checks:
534
+ assert check[0] in ['above'], 'currently only above check is supported'
535
+ if check[0] == 'above':
536
+ assert len(check) == 4, 'above check needs 3 additional parameters'
537
+ except (AssertionError, ValueError) as e:
538
+ msg = f'Error validating char_runtime_checks: {e}'
539
+ logging.critical(msg)
540
+ assert False, msg
541
+
542
+ def validate_char_and_bvh_joint_names(self, char_joint_names: List[str], bvh_joint_names: List[str]) -> None: # noqa: C901
543
+
544
+ # validate bvh_projection_bodypart_groups
545
+ try:
546
+ for group in self.bvh_projection_bodypart_groups:
547
+ for bvh_joint_name in group['bvh_joint_names']:
548
+ assert bvh_joint_name in bvh_joint_names, f'bvh_joint_name not valid: {bvh_joint_name}'
549
+ except AssertionError as e:
550
+ msg = f'Error validating bvh_projection_bodypart_groups: {e}'
551
+ logging.critical(msg)
552
+ assert False, msg
553
+
554
+ # validate char_bodypart_groups
555
+ try:
556
+ for group in self.char_bodypart_groups:
557
+ # check that bvh joint drivers are valid bvh joints
558
+ for bvh_joint_name in group['bvh_depth_drivers']:
559
+ assert bvh_joint_name in bvh_joint_names, f'bvh_depth_driver joint name invalid: {bvh_joint_name}'
560
+
561
+ # check that all char_joints are valid character joints
562
+ for char_joint_name in group['char_joints']:
563
+ assert char_joint_name in char_joint_names, f'char_joints joint name invalid: {char_joint_name}'
564
+ except AssertionError as e:
565
+ msg = f'Error validating char_bodypart_groups: {e}'
566
+ logging.critical(msg)
567
+ assert False, msg
568
+
569
+ # validate char_bvh_root_offset
570
+ try:
571
+ # check that bvh_projection_bodypart_group_for_offset matches a bvh_projection_bodypart_group name
572
+ group_names = [group['name'] for group in self.bvh_projection_bodypart_groups]
573
+ assert self.char_bvh_root_offset['bvh_projection_bodypart_group_for_offset'] in group_names, 'invalid bvh_projection_bodypart_group_for_offset'
574
+
575
+ # check bvh_joints contains valid joints
576
+ for bvh_joint_name_group in self.char_bvh_root_offset['bvh_joints']:
577
+ for joint_name in bvh_joint_name_group:
578
+ assert joint_name in bvh_joint_names, f'invalid joint name in bvh_joints: {joint_name}'
579
+
580
+ # check char_joints are valid joints
581
+ for char_joint_name_group in self.char_bvh_root_offset['char_joints']:
582
+ for joint_name in char_joint_name_group:
583
+ assert joint_name in char_joint_names, f'invalid joint name in char_joints: {joint_name}'
584
+ except AssertionError as e:
585
+ msg = f'Error validating char_bvh_root_offset: {e}'
586
+ logging.critical(msg)
587
+ assert False, msg
588
+
589
+ # validate char_joint_bvh_joints_mapping
590
+ try:
591
+ # check that dict keys correspond to valid character joints
592
+ for char_joint_name in self.char_joint_bvh_joints_mapping.keys():
593
+ assert char_joint_name in char_joint_names, f'invalid char_joint_name: {char_joint_name}'
594
+
595
+ # check that dict values correspond to valid bvh joints
596
+ for bvh_prox_joint_name, bvh_dist_joint_name in self.char_joint_bvh_joints_mapping.values():
597
+ assert bvh_prox_joint_name in bvh_joint_names, f'invalid bvh_prox_joint_name: {bvh_prox_joint_name}'
598
+ assert bvh_dist_joint_name in bvh_joint_names, f'invalid bvh_dist_joint_name: {bvh_dist_joint_name}'
599
+ except AssertionError as e:
600
+ msg = f'Error validating char_joint_bvh_joints_mapping: {e}'
601
+ logging.critical(msg)
602
+ assert False, msg
603
+
604
+ # validate char runtime checks
605
+ try:
606
+ for check in self.char_runtime_checks:
607
+ if check[0] == 'above':
608
+ # check that, if above test, following 3 params are valid character joint names
609
+ _, target_joint_name, joint1_name, joint2_name = check
610
+ assert target_joint_name in char_joint_names, f'above test target_joint_name invalid {target_joint_name}'
611
+ assert joint1_name in char_joint_names, f'above test joint1_name invalid {joint1_name}'
612
+ assert joint2_name in char_joint_names, f'above test joint2_name invalid {joint2_name}'
613
+ except AssertionError as e:
614
+ msg = f'Error validating char_runtime_checks: {e}'
615
+ logging.critical(msg)
616
+ assert False, msg
617
+
618
+
619
+ NoneType = type(None) # needed for type checking
animated_drawings/controller/__pycache__/controller.cpython-38.pyc ADDED
Binary file (4.76 kB). View file
 
animated_drawings/controller/__pycache__/video_render_controller.cpython-38.pyc ADDED
Binary file (9.18 kB). View file
 
animated_drawings/controller/controller.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # This source code is licensed under the MIT license found in the
3
+ # LICENSE file in the root directory of this source tree.
4
+
5
+ """ Controller Abstract Base Class Module """
6
+
7
+ from __future__ import annotations
8
+ from typing import Optional
9
+ from abc import abstractmethod
10
+ import logging
11
+
12
+ from animated_drawings.model.scene import Scene
13
+ from animated_drawings.view.view import View
14
+ from animated_drawings.config import ControllerConfig
15
+
16
+
17
+ class Controller():
18
+ """
19
+ Base Controller class from which all other Controllers will be derived.
20
+ Controllers are responsible for:
21
+ - running the game loop.
22
+ - handling user input and forwarding it to the view or scene.
23
+ - triggering the scene's update method
24
+ - trigger the view's render method
25
+ """
26
+
27
+ def __init__(self, cfg: ControllerConfig, scene: Scene) -> None:
28
+ self.cfg: ControllerConfig = cfg
29
+ self.scene: Scene = scene
30
+ self.view: Optional[View] = None
31
+
32
+ def set_scene(self, scene: Scene) -> None:
33
+ """ Sets the scene attached to this controller."""
34
+ self.scene = scene
35
+
36
+ def set_view(self, view: View) -> None:
37
+ """ Sets the view attached to this controller."""
38
+ self.view = view
39
+
40
+ @abstractmethod
41
+ def _tick(self) -> None:
42
+ """Subclass and add logic is necessary to progress time"""
43
+
44
+ @abstractmethod
45
+ def _update(self) -> None:
46
+ """Subclass and add logic is necessary to update scene after progressing time"""
47
+
48
+ @abstractmethod
49
+ def _is_run_over(self) -> bool:
50
+ """Subclass and add logic is necessary to end the scene"""
51
+
52
+ @abstractmethod
53
+ def _start_run_loop_iteration(self) -> None:
54
+ """Subclass and add code to start run loop iteration"""
55
+
56
+ @abstractmethod
57
+ def _handle_user_input(self) -> None:
58
+ """Subclass and add code to handle user input"""
59
+
60
+ @abstractmethod
61
+ def _render(self) -> None:
62
+ """Subclass and add logic needed to have viewer render the scene"""
63
+
64
+ @abstractmethod
65
+ def _finish_run_loop_iteration(self) -> None:
66
+ """Subclass and add steps necessary before starting next iteration of run loop. """
67
+
68
+ @abstractmethod
69
+ def _prep_for_run_loop(self) -> None:
70
+ """Subclass and add anything necessary to do immediately prior to run loop. """
71
+
72
+ @abstractmethod
73
+ def _cleanup_after_run_loop(self) -> None:
74
+ """Subclass and add anything necessary to do after run loop has finished. """
75
+
76
+ def run(self) -> None:
77
+ """ The run loop. Subclassed controllers should overload and define functionality for each step in this function."""
78
+
79
+ self._prep_for_run_loop()
80
+ while not self._is_run_over():
81
+ self._start_run_loop_iteration()
82
+ self._update()
83
+ self._render()
84
+ self._tick()
85
+ self._handle_user_input()
86
+ self._finish_run_loop_iteration()
87
+
88
+ self._cleanup_after_run_loop()
89
+
90
+ @staticmethod
91
+ def create_controller(controller_cfg: ControllerConfig, scene: Scene, view: View) -> Controller:
92
+ """ Takes in a controller dictionary from mvc config file, scene, and view. Constructs and return appropriate controller."""
93
+ if controller_cfg.mode == 'video_render':
94
+ from animated_drawings.controller.video_render_controller import VideoRenderController
95
+ return VideoRenderController(controller_cfg, scene, view,)
96
+ elif controller_cfg.mode == 'interactive':
97
+ from animated_drawings.controller.interactive_controller import InteractiveController
98
+ from animated_drawings.view.window_view import WindowView
99
+ assert isinstance(view, WindowView) # for static analysis. checks elsewhere ensure this always passes
100
+ return InteractiveController(controller_cfg, scene, view)
101
+ else:
102
+ msg = f'Unknown controller mode specified: {controller_cfg.mode}'
103
+ logging.critical(msg)
104
+ assert False, msg
animated_drawings/controller/interactive_controller.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # This source code is licensed under the MIT license found in the
3
+ # LICENSE file in the root directory of this source tree.
4
+
5
+ """ Interactive Controller Class Module """
6
+
7
+ import time
8
+ from typing import Optional
9
+ import glfw
10
+
11
+ from animated_drawings.controller.controller import Controller
12
+ from animated_drawings.model.scene import Scene
13
+ from animated_drawings.view.window_view import WindowView
14
+ from animated_drawings.config import ControllerConfig
15
+
16
+
17
+ class InteractiveController(Controller):
18
+ """ Interactive Controller Class """
19
+
20
+ def __init__(self, cfg: ControllerConfig, scene: Scene, view: WindowView) -> None:
21
+ super().__init__(cfg, scene)
22
+
23
+ self.view: WindowView = view
24
+ self.prev_time: float = 0.0 # tracks real-world time passing between run loops
25
+ self.pause: bool = False # tracks whether time progresses in the scene
26
+
27
+ glfw.init()
28
+ glfw.set_key_callback(self.view.win, self._on_key)
29
+
30
+ def _on_key(self, _win, key: int, _scancode, action, _mods) -> None: # noqa: C901
31
+
32
+ if action not in (glfw.PRESS, glfw.REPEAT):
33
+ return
34
+
35
+ # close window
36
+ if key in (glfw.KEY_ESCAPE, glfw.KEY_Q):
37
+ glfw.set_window_should_close(self.view.win, True)
38
+
39
+ # move camera forward
40
+ elif key == glfw.KEY_W:
41
+ _, _, fwd = self.view.camera.get_right_up_fwd_vectors()
42
+ self.view.camera.offset(-0.1 * fwd)
43
+
44
+ # move camera back
45
+ elif key == glfw.KEY_S:
46
+ _, _, fwd = self.view.camera.get_right_up_fwd_vectors()
47
+ self.view.camera.offset(0.1 * fwd)
48
+
49
+ # move camera right
50
+ elif key == glfw.KEY_A:
51
+ right, _, _ = self.view.camera.get_right_up_fwd_vectors()
52
+ self.view.camera.offset(-0.1 * right)
53
+
54
+ # move camera left
55
+ elif key == glfw.KEY_D:
56
+ right, _, _ = self.view.camera.get_right_up_fwd_vectors()
57
+ self.view.camera.offset(0.1 * right)
58
+
59
+ # move camera up
60
+ elif key == glfw.KEY_E:
61
+ _, up, _ = self.view.camera.get_right_up_fwd_vectors()
62
+ self.view.camera.offset(0.1 * up)
63
+
64
+ # move camera down
65
+ elif key == glfw.KEY_R:
66
+ _, up, _ = self.view.camera.get_right_up_fwd_vectors()
67
+ self.view.camera.offset(-0.1 * up)
68
+
69
+ # toggle start/stop time
70
+ elif key == glfw.KEY_SPACE:
71
+ self.pause = not self.pause
72
+ self.prev_time = time.time()
73
+
74
+ # step forward in time
75
+ elif key == glfw.KEY_RIGHT:
76
+ self._tick(self.cfg.keyboard_timestep)
77
+
78
+ # step backward in time
79
+ elif key == glfw.KEY_LEFT:
80
+ self._tick(-self.cfg.keyboard_timestep)
81
+
82
+ def _is_run_over(self) -> None:
83
+ return glfw.window_should_close(self.view.win)
84
+
85
+ def _prep_for_run_loop(self) -> None:
86
+ self.prev_time = time.time()
87
+
88
+ def _start_run_loop_iteration(self) -> None:
89
+ self.view.clear_window()
90
+
91
+ def _tick(self, delta_t: Optional[float] = None) -> None:
92
+ # if passed a specific value to progress time by, do so
93
+ if delta_t:
94
+ self.scene.progress_time(delta_t)
95
+ # otherwise, if scene is paused, do nothing
96
+ elif self.pause:
97
+ pass
98
+ # otherwise, calculate real time passed since last call and progress scene by that amount
99
+ else:
100
+ cur_time = time.time()
101
+ self.scene.progress_time(cur_time - self.prev_time)
102
+ self.prev_time = cur_time
103
+
104
+ def _update(self) -> None:
105
+ self.scene.update_transforms()
106
+
107
+ def _handle_user_input(self) -> None:
108
+ glfw.poll_events()
109
+
110
+ def _render(self) -> None:
111
+ self.view.render(self.scene)
112
+
113
+ def _finish_run_loop_iteration(self) -> None:
114
+ self.view.swap_buffers()
115
+
116
+ def _cleanup_after_run_loop(self) -> None:
117
+ self.view.cleanup()
animated_drawings/controller/video_render_controller.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # This source code is licensed under the MIT license found in the
3
+ # LICENSE file in the root directory of this source tree.
4
+
5
+ """ Video Render Controller Class Module """
6
+
7
+ from __future__ import annotations
8
+ import time
9
+ import logging
10
+ from typing import List
11
+ from pathlib import Path
12
+ from abc import abstractmethod
13
+ import numpy as np
14
+ import numpy.typing as npt
15
+ import cv2
16
+ from OpenGL import GL
17
+ from tqdm import tqdm
18
+
19
+ from animated_drawings.controller.controller import Controller
20
+ from animated_drawings.model.scene import Scene
21
+ from animated_drawings.model.animated_drawing import AnimatedDrawing
22
+ from animated_drawings.view.view import View
23
+ from animated_drawings.config import ControllerConfig
24
+
25
+ NoneType = type(None) # for type checking below
26
+
27
+
28
+ class VideoRenderController(Controller):
29
+ """ Video Render Controller is used to non-interactively generate a video file """
30
+
31
+ def __init__(self, cfg: ControllerConfig, scene: Scene, view: View) -> None:
32
+ super().__init__(cfg, scene)
33
+
34
+ self.view: View = view
35
+
36
+ self.scene: Scene = scene
37
+
38
+ self.frames_left_to_render: int # when this becomes zero, stop rendering
39
+ self.delta_t: float # amount of time to progress scene between renders
40
+ self._set_frames_left_to_render_and_delta_t()
41
+
42
+ self.render_start_time: float # track when we started to render frames (for performance stats)
43
+ self.frames_rendered: int = 0 # track how many frames we've rendered
44
+
45
+ self.video_width: int
46
+ self.video_height: int
47
+ self.video_width, self.video_height = self.view.get_framebuffer_size()
48
+
49
+ self.video_writer: VideoWriter = VideoWriter.create_video_writer(self)
50
+
51
+ self.frame_data = np.empty([self.video_height, self.video_width, 4], dtype='uint8') # 4 for RGBA
52
+
53
+ self.progress_bar = tqdm(total=self.frames_left_to_render)
54
+
55
+ def _set_frames_left_to_render_and_delta_t(self) -> None:
56
+ """
57
+ Based upon the animated drawings within the scene, computes maximum number of frames in a BVH.
58
+ Checks that all frame times within BVHs are equal, logs a warning if not.
59
+ Uses results to determine number of frames and frame time for output video.
60
+ """
61
+
62
+ max_frames = 0
63
+ frame_time: List[float] = []
64
+ for child in self.scene.get_children():
65
+ if not isinstance(child, AnimatedDrawing):
66
+ continue
67
+ max_frames = max(max_frames, child.retargeter.bvh.frame_max_num)
68
+ frame_time.append(child.retargeter.bvh.frame_time)
69
+
70
+ if not all(x == frame_time[0] for x in frame_time):
71
+ msg = f'frame time of BVH files don\'t match. Using first value: {frame_time[0]}'
72
+ logging.warning(msg)
73
+
74
+ self.frames_left_to_render = max_frames
75
+ self.delta_t = frame_time[0]
76
+
77
+ def _prep_for_run_loop(self) -> None:
78
+ self.run_loop_start_time = time.time()
79
+
80
+ def _is_run_over(self) -> bool:
81
+ return self.frames_left_to_render == 0
82
+
83
+ def _start_run_loop_iteration(self) -> None:
84
+ self.view.clear_window()
85
+
86
+ def _update(self) -> None:
87
+ self.scene.update_transforms()
88
+
89
+ def _render(self) -> None:
90
+ self.view.render(self.scene)
91
+
92
+ def _tick(self) -> None:
93
+ self.scene.progress_time(self.delta_t)
94
+
95
+ def _handle_user_input(self) -> None:
96
+ """ ignore all user input when rendering video file """
97
+
98
+ def _finish_run_loop_iteration(self) -> None:
99
+ # get pixel values from the frame buffer, send them to the video writer
100
+ GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, 0)
101
+ GL.glReadPixels(0, 0, self.video_width, self.video_height, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE, self.frame_data)
102
+ self.video_writer.process_frame(self.frame_data[::-1, :, :].copy())
103
+
104
+ # update our counts and progress_bar
105
+ self.frames_left_to_render -= 1
106
+ self.frames_rendered += 1
107
+ self.progress_bar.update(1)
108
+
109
+ def _cleanup_after_run_loop(self) -> None:
110
+ logging.info(f'Rendered {self.frames_rendered} frames in {time.time()-self.run_loop_start_time} seconds.')
111
+ self.view.cleanup()
112
+
113
+ _time = time.time()
114
+ self.video_writer.cleanup()
115
+ logging.info(f'Wrote video to file in in {time.time()-_time} seconds.')
116
+
117
+
118
+ class VideoWriter():
119
+ """ Wrapper to abstract the different backends necessary for writing different video filetypes """
120
+
121
+ def __init__(self) -> None:
122
+ pass
123
+
124
+ @abstractmethod
125
+ def process_frame(self, frame: npt.NDArray[np.uint8]) -> None:
126
+ """ Subclass must specify how to handle each frame of data received. """
127
+ pass
128
+
129
+ @abstractmethod
130
+ def cleanup(self) -> None:
131
+ """ Subclass must specify how to finish up after all frames have been received. """
132
+ pass
133
+
134
+ @staticmethod
135
+ def create_video_writer(controller: VideoRenderController) -> VideoWriter:
136
+
137
+ assert isinstance(controller.cfg.output_video_path, str) # for static analysis
138
+
139
+ output_p = Path(controller.cfg.output_video_path)
140
+ output_p.parent.mkdir(exist_ok=True, parents=True)
141
+
142
+ msg = f' Writing video to: {output_p.resolve()}'
143
+ logging.info(msg)
144
+ print(msg)
145
+
146
+ if output_p.suffix == '.gif':
147
+ return GIFWriter(controller)
148
+ elif output_p.suffix == '.mp4':
149
+ return MP4Writer(controller)
150
+ else:
151
+ msg = f'Unsupported output video file extension ({output_p.suffix}). Only .gif and .mp4 are supported.'
152
+ logging.critical(msg)
153
+ assert False, msg
154
+
155
+
156
+ class GIFWriter(VideoWriter):
157
+ """ Video writer for creating transparent, animated GIFs with Pillow """
158
+
159
+ def __init__(self, controller: VideoRenderController) -> None:
160
+ assert isinstance(controller.cfg.output_video_path, str) # for static analysis
161
+ self.output_p = Path(controller.cfg.output_video_path)
162
+
163
+ self.duration = int(controller.delta_t*1000)
164
+ if self.duration < 20:
165
+ msg = f'Specified duration of .gif is too low, replacing with 20: {self.duration}'
166
+ logging.warn(msg)
167
+ self.duration = 20
168
+
169
+ self.frames: List[npt.NDArray[np.uint8]] = []
170
+
171
+ def process_frame(self, frame: npt.NDArray[np.uint8]) -> None:
172
+ """ Reorder channels and save frames as they arrive"""
173
+ self.frames.append(cv2.cvtColor(frame, cv2.COLOR_BGRA2RGBA).astype(np.uint8))
174
+
175
+ def cleanup(self) -> None:
176
+ """ Write all frames to output path specified."""
177
+ from PIL import Image
178
+ self.output_p.parent.mkdir(exist_ok=True, parents=True)
179
+ logging.info(f'VideoWriter will write to {self.output_p.resolve()}')
180
+ ims = [Image.fromarray(a_frame) for a_frame in self.frames]
181
+ ims[0].save(self.output_p, save_all=True, append_images=ims[1:], duration=self.duration, disposal=2, loop=0)
182
+
183
+
184
+ class MP4Writer(VideoWriter):
185
+ """ Video writer for creating mp4 videos with cv2.VideoWriter """
186
+ def __init__(self, controller: VideoRenderController) -> None:
187
+
188
+ # validate and prep output path
189
+ if isinstance(controller.cfg.output_video_path, NoneType):
190
+ msg = 'output video path not specified for mp4 video writer'
191
+ logging.critical(msg)
192
+ assert False, msg
193
+ output_p = Path(controller.cfg.output_video_path)
194
+ output_p.parent.mkdir(exist_ok=True, parents=True)
195
+ logging.info(f'VideoWriter will write to {output_p.resolve()}')
196
+
197
+ # validate and prep codec
198
+ if isinstance(controller.cfg.output_video_codec, NoneType):
199
+ msg = 'output video codec not specified for mp4 video writer'
200
+ logging.critical(msg)
201
+ assert False, msg
202
+ fourcc = cv2.VideoWriter_fourcc(*controller.cfg.output_video_codec)
203
+ logging.info(f'Using codec {controller.cfg.output_video_codec}')
204
+
205
+ # calculate video writer framerate
206
+ frame_rate = round(1/controller.delta_t)
207
+
208
+ # initialize the video writer
209
+ self.video_writer = cv2.VideoWriter(str(output_p), fourcc, frame_rate, (controller.video_width, controller.video_height))
210
+
211
+ def process_frame(self, frame: npt.NDArray[np.uint8]) -> None:
212
+ """ Remove the alpha channel and send to the video writer as it arrives. """
213
+ self.video_writer.write(frame[:, :, :3])
214
+
215
+ def cleanup(self) -> None:
216
+ self.video_writer.release()
animated_drawings/lib/python3.9/site-packages/_distutils_hack/__init__.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import re
4
+ import importlib
5
+ import warnings
6
+
7
+
8
+ is_pypy = '__pypy__' in sys.builtin_module_names
9
+
10
+
11
+ warnings.filterwarnings('ignore',
12
+ r'.+ distutils\b.+ deprecated',
13
+ DeprecationWarning)
14
+
15
+
16
+ def warn_distutils_present():
17
+ if 'distutils' not in sys.modules:
18
+ return
19
+ if is_pypy and sys.version_info < (3, 7):
20
+ # PyPy for 3.6 unconditionally imports distutils, so bypass the warning
21
+ # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
22
+ return
23
+ warnings.warn(
24
+ "Distutils was imported before Setuptools, but importing Setuptools "
25
+ "also replaces the `distutils` module in `sys.modules`. This may lead "
26
+ "to undesirable behaviors or errors. To avoid these issues, avoid "
27
+ "using distutils directly, ensure that setuptools is installed in the "
28
+ "traditional way (e.g. not an editable install), and/or make sure "
29
+ "that setuptools is always imported before distutils.")
30
+
31
+
32
+ def clear_distutils():
33
+ if 'distutils' not in sys.modules:
34
+ return
35
+ warnings.warn("Setuptools is replacing distutils.")
36
+ mods = [name for name in sys.modules if re.match(r'distutils\b', name)]
37
+ for name in mods:
38
+ del sys.modules[name]
39
+
40
+
41
+ def enabled():
42
+ """
43
+ Allow selection of distutils by environment variable.
44
+ """
45
+ which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')
46
+ return which == 'local'
47
+
48
+
49
+ def ensure_local_distutils():
50
+ clear_distutils()
51
+ distutils = importlib.import_module('setuptools._distutils')
52
+ distutils.__name__ = 'distutils'
53
+ sys.modules['distutils'] = distutils
54
+
55
+ # sanity check that submodules load as expected
56
+ core = importlib.import_module('distutils.core')
57
+ assert '_distutils' in core.__file__, core.__file__
58
+
59
+
60
+ def do_override():
61
+ """
62
+ Ensure that the local copy of distutils is preferred over stdlib.
63
+
64
+ See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
65
+ for more motivation.
66
+ """
67
+ if enabled():
68
+ warn_distutils_present()
69
+ ensure_local_distutils()
70
+
71
+
72
+ class DistutilsMetaFinder:
73
+ def find_spec(self, fullname, path, target=None):
74
+ if path is not None:
75
+ return
76
+
77
+ method_name = 'spec_for_{fullname}'.format(**locals())
78
+ method = getattr(self, method_name, lambda: None)
79
+ return method()
80
+
81
+ def spec_for_distutils(self):
82
+ import importlib.abc
83
+ import importlib.util
84
+
85
+ class DistutilsLoader(importlib.abc.Loader):
86
+
87
+ def create_module(self, spec):
88
+ return importlib.import_module('setuptools._distutils')
89
+
90
+ def exec_module(self, module):
91
+ pass
92
+
93
+ return importlib.util.spec_from_loader('distutils', DistutilsLoader())
94
+
95
+ def spec_for_pip(self):
96
+ """
97
+ Ensure stdlib distutils when running under pip.
98
+ See pypa/pip#8761 for rationale.
99
+ """
100
+ if self.pip_imported_during_build():
101
+ return
102
+ clear_distutils()
103
+ self.spec_for_distutils = lambda: None
104
+
105
+ @staticmethod
106
+ def pip_imported_during_build():
107
+ """
108
+ Detect if pip is being imported in a build script. Ref #2355.
109
+ """
110
+ import traceback
111
+ return any(
112
+ frame.f_globals['__file__'].endswith('setup.py')
113
+ for frame, line in traceback.walk_stack(None)
114
+ )
115
+
116
+
117
+ DISTUTILS_FINDER = DistutilsMetaFinder()
118
+
119
+
120
+ def add_shim():
121
+ sys.meta_path.insert(0, DISTUTILS_FINDER)
122
+
123
+
124
+ def remove_shim():
125
+ try:
126
+ sys.meta_path.remove(DISTUTILS_FINDER)
127
+ except ValueError:
128
+ pass
animated_drawings/lib/python3.9/site-packages/_distutils_hack/override.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __import__('_distutils_hack').do_override()
animated_drawings/lib/python3.9/site-packages/distutils-precedence.pth ADDED
@@ -0,0 +1 @@
 
 
1
+ import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os.environ.get(var, 'stdlib') == 'local'; enabled and __import__('_distutils_hack').add_shim();
animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2008-2021 The pip developers (see AUTHORS.txt file)
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.
animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/METADATA ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: pip
3
+ Version: 21.2.4
4
+ Summary: The PyPA recommended tool for installing Python packages.
5
+ Home-page: https://pip.pypa.io/
6
+ Author: The pip developers
7
+ Author-email: distutils-sig@python.org
8
+ License: MIT
9
+ Project-URL: Documentation, https://pip.pypa.io
10
+ Project-URL: Source, https://github.com/pypa/pip
11
+ Project-URL: Changelog, https://pip.pypa.io/en/stable/news/
12
+ Platform: UNKNOWN
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Topic :: Software Development :: Build Tools
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.6
21
+ Classifier: Programming Language :: Python :: 3.7
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: Implementation :: CPython
25
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
26
+ Requires-Python: >=3.6
27
+ License-File: LICENSE.txt
28
+
29
+ pip - The Python Package Installer
30
+ ==================================
31
+
32
+ .. image:: https://img.shields.io/pypi/v/pip.svg
33
+ :target: https://pypi.org/project/pip/
34
+
35
+ .. image:: https://readthedocs.org/projects/pip/badge/?version=latest
36
+ :target: https://pip.pypa.io/en/latest
37
+
38
+ pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.
39
+
40
+ Please take a look at our documentation for how to install and use pip:
41
+
42
+ * `Installation`_
43
+ * `Usage`_
44
+
45
+ We release updates regularly, with a new version every 3 months. Find more details in our documentation:
46
+
47
+ * `Release notes`_
48
+ * `Release process`_
49
+
50
+ In pip 20.3, we've `made a big improvement to the heart of pip`_; `learn more`_. We want your input, so `sign up for our user experience research studies`_ to help us do it right.
51
+
52
+ **Note**: pip 21.0, in January 2021, removed Python 2 support, per pip's `Python 2 support policy`_. Please migrate to Python 3.
53
+
54
+ If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
55
+
56
+ * `Issue tracking`_
57
+ * `Discourse channel`_
58
+ * `User IRC`_
59
+
60
+ If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:
61
+
62
+ * `GitHub page`_
63
+ * `Development documentation`_
64
+ * `Development mailing list`_
65
+ * `Development IRC`_
66
+
67
+ Code of Conduct
68
+ ---------------
69
+
70
+ Everyone interacting in the pip project's codebases, issue trackers, chat
71
+ rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
72
+
73
+ .. _package installer: https://packaging.python.org/guides/tool-recommendations/
74
+ .. _Python Package Index: https://pypi.org
75
+ .. _Installation: https://pip.pypa.io/en/stable/installation/
76
+ .. _Usage: https://pip.pypa.io/en/stable/
77
+ .. _Release notes: https://pip.pypa.io/en/stable/news.html
78
+ .. _Release process: https://pip.pypa.io/en/latest/development/release-process/
79
+ .. _GitHub page: https://github.com/pypa/pip
80
+ .. _Development documentation: https://pip.pypa.io/en/latest/development
81
+ .. _made a big improvement to the heart of pip: https://pyfound.blogspot.com/2020/11/pip-20-3-new-resolver.html
82
+ .. _learn more: https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-3-2020
83
+ .. _sign up for our user experience research studies: https://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html
84
+ .. _Python 2 support policy: https://pip.pypa.io/en/latest/development/release-process/#python-2-support
85
+ .. _Issue tracking: https://github.com/pypa/pip/issues
86
+ .. _Discourse channel: https://discuss.python.org/c/packaging
87
+ .. _Development mailing list: https://mail.python.org/mailman3/lists/distutils-sig.python.org/
88
+ .. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa
89
+ .. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev
90
+ .. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
91
+
92
+
animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/REQUESTED ADDED
File without changes
animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.36.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/entry_points.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [console_scripts]
2
+ pip = pip._internal.cli.main:main
3
+ pip3 = pip._internal.cli.main:main
4
+ pip3.9 = pip._internal.cli.main:main
5
+
animated_drawings/lib/python3.9/site-packages/pip-21.2.4.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
animated_drawings/lib/python3.9/site-packages/pip/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ __version__ = "21.2.4"
4
+
5
+
6
+ def main(args: Optional[List[str]] = None) -> int:
7
+ """This is an internal API only meant for use by pip's own console scripts.
8
+
9
+ For additional details, see https://github.com/pypa/pip/issues/7498.
10
+ """
11
+ from pip._internal.utils.entrypoints import _wrapper
12
+
13
+ return _wrapper(args)
animated_drawings/lib/python3.9/site-packages/pip/__main__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import warnings
4
+
5
+ # Remove '' and current working directory from the first entry
6
+ # of sys.path, if present to avoid using current directory
7
+ # in pip commands check, freeze, install, list and show,
8
+ # when invoked as python -m pip <command>
9
+ if sys.path[0] in ("", os.getcwd()):
10
+ sys.path.pop(0)
11
+
12
+ # If we are running from a wheel, add the wheel to sys.path
13
+ # This allows the usage python pip-*.whl/pip install pip-*.whl
14
+ if __package__ == "":
15
+ # __file__ is pip-*.whl/pip/__main__.py
16
+ # first dirname call strips of '/__main__.py', second strips off '/pip'
17
+ # Resulting path is the name of the wheel itself
18
+ # Add that to sys.path so we can import pip
19
+ path = os.path.dirname(os.path.dirname(__file__))
20
+ sys.path.insert(0, path)
21
+
22
+ if __name__ == "__main__":
23
+ # Work around the error reported in #9540, pending a proper fix.
24
+ # Note: It is essential the warning filter is set *before* importing
25
+ # pip, as the deprecation happens at import time, not runtime.
26
+ warnings.filterwarnings(
27
+ "ignore", category=DeprecationWarning, module=".*packaging\\.version"
28
+ )
29
+ from pip._internal.cli.main import main as _main
30
+
31
+ sys.exit(_main())
animated_drawings/lib/python3.9/site-packages/pip/_internal/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+
3
+ import pip._internal.utils.inject_securetransport # noqa
4
+ from pip._internal.utils import _log
5
+
6
+ # init_logging() must be called before any call to logging.getLogger()
7
+ # which happens at import of most modules.
8
+ _log.init_logging()
9
+
10
+
11
+ def main(args: (Optional[List[str]]) = None) -> int:
12
+ """This is preserved for old console scripts that may still be referencing
13
+ it.
14
+
15
+ For additional details, see https://github.com/pypa/pip/issues/7498.
16
+ """
17
+ from pip._internal.utils.entrypoints import _wrapper
18
+
19
+ return _wrapper(args)
animated_drawings/lib/python3.9/site-packages/pip/_internal/build_env.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build Environment used for isolation during sdist building
2
+ """
3
+
4
+ import contextlib
5
+ import logging
6
+ import os
7
+ import pathlib
8
+ import sys
9
+ import textwrap
10
+ import zipfile
11
+ from collections import OrderedDict
12
+ from sysconfig import get_paths
13
+ from types import TracebackType
14
+ from typing import TYPE_CHECKING, Iterable, Iterator, List, Optional, Set, Tuple, Type
15
+
16
+ from pip._vendor.certifi import where
17
+ from pip._vendor.packaging.requirements import Requirement
18
+ from pip._vendor.packaging.version import Version
19
+
20
+ from pip import __file__ as pip_location
21
+ from pip._internal.cli.spinners import open_spinner
22
+ from pip._internal.locations import get_platlib, get_prefixed_libs, get_purelib
23
+ from pip._internal.metadata import get_environment
24
+ from pip._internal.utils.subprocess import call_subprocess
25
+ from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
26
+
27
+ if TYPE_CHECKING:
28
+ from pip._internal.index.package_finder import PackageFinder
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class _Prefix:
34
+
35
+ def __init__(self, path):
36
+ # type: (str) -> None
37
+ self.path = path
38
+ self.setup = False
39
+ self.bin_dir = get_paths(
40
+ 'nt' if os.name == 'nt' else 'posix_prefix',
41
+ vars={'base': path, 'platbase': path}
42
+ )['scripts']
43
+ self.lib_dirs = get_prefixed_libs(path)
44
+
45
+
46
+ @contextlib.contextmanager
47
+ def _create_standalone_pip() -> Iterator[str]:
48
+ """Create a "standalone pip" zip file.
49
+
50
+ The zip file's content is identical to the currently-running pip.
51
+ It will be used to install requirements into the build environment.
52
+ """
53
+ source = pathlib.Path(pip_location).resolve().parent
54
+
55
+ # Return the current instance if `source` is not a directory. We can't build
56
+ # a zip from this, and it likely means the instance is already standalone.
57
+ if not source.is_dir():
58
+ yield str(source)
59
+ return
60
+
61
+ with TempDirectory(kind="standalone-pip") as tmp_dir:
62
+ pip_zip = os.path.join(tmp_dir.path, "__env_pip__.zip")
63
+ kwargs = {}
64
+ if sys.version_info >= (3, 8):
65
+ kwargs["strict_timestamps"] = False
66
+ with zipfile.ZipFile(pip_zip, "w", **kwargs) as zf:
67
+ for child in source.rglob("*"):
68
+ zf.write(child, child.relative_to(source.parent).as_posix())
69
+ yield os.path.join(pip_zip, "pip")
70
+
71
+
72
+ class BuildEnvironment:
73
+ """Creates and manages an isolated environment to install build deps
74
+ """
75
+
76
+ def __init__(self):
77
+ # type: () -> None
78
+ temp_dir = TempDirectory(
79
+ kind=tempdir_kinds.BUILD_ENV, globally_managed=True
80
+ )
81
+
82
+ self._prefixes = OrderedDict(
83
+ (name, _Prefix(os.path.join(temp_dir.path, name)))
84
+ for name in ('normal', 'overlay')
85
+ )
86
+
87
+ self._bin_dirs = [] # type: List[str]
88
+ self._lib_dirs = [] # type: List[str]
89
+ for prefix in reversed(list(self._prefixes.values())):
90
+ self._bin_dirs.append(prefix.bin_dir)
91
+ self._lib_dirs.extend(prefix.lib_dirs)
92
+
93
+ # Customize site to:
94
+ # - ensure .pth files are honored
95
+ # - prevent access to system site packages
96
+ system_sites = {
97
+ os.path.normcase(site) for site in (get_purelib(), get_platlib())
98
+ }
99
+ self._site_dir = os.path.join(temp_dir.path, 'site')
100
+ if not os.path.exists(self._site_dir):
101
+ os.mkdir(self._site_dir)
102
+ with open(os.path.join(self._site_dir, 'sitecustomize.py'), 'w') as fp:
103
+ fp.write(textwrap.dedent(
104
+ '''
105
+ import os, site, sys
106
+
107
+ # First, drop system-sites related paths.
108
+ original_sys_path = sys.path[:]
109
+ known_paths = set()
110
+ for path in {system_sites!r}:
111
+ site.addsitedir(path, known_paths=known_paths)
112
+ system_paths = set(
113
+ os.path.normcase(path)
114
+ for path in sys.path[len(original_sys_path):]
115
+ )
116
+ original_sys_path = [
117
+ path for path in original_sys_path
118
+ if os.path.normcase(path) not in system_paths
119
+ ]
120
+ sys.path = original_sys_path
121
+
122
+ # Second, add lib directories.
123
+ # ensuring .pth file are processed.
124
+ for path in {lib_dirs!r}:
125
+ assert not path in sys.path
126
+ site.addsitedir(path)
127
+ '''
128
+ ).format(system_sites=system_sites, lib_dirs=self._lib_dirs))
129
+
130
+ def __enter__(self):
131
+ # type: () -> None
132
+ self._save_env = {
133
+ name: os.environ.get(name, None)
134
+ for name in ('PATH', 'PYTHONNOUSERSITE', 'PYTHONPATH')
135
+ }
136
+
137
+ path = self._bin_dirs[:]
138
+ old_path = self._save_env['PATH']
139
+ if old_path:
140
+ path.extend(old_path.split(os.pathsep))
141
+
142
+ pythonpath = [self._site_dir]
143
+
144
+ os.environ.update({
145
+ 'PATH': os.pathsep.join(path),
146
+ 'PYTHONNOUSERSITE': '1',
147
+ 'PYTHONPATH': os.pathsep.join(pythonpath),
148
+ })
149
+
150
+ def __exit__(
151
+ self,
152
+ exc_type, # type: Optional[Type[BaseException]]
153
+ exc_val, # type: Optional[BaseException]
154
+ exc_tb # type: Optional[TracebackType]
155
+ ):
156
+ # type: (...) -> None
157
+ for varname, old_value in self._save_env.items():
158
+ if old_value is None:
159
+ os.environ.pop(varname, None)
160
+ else:
161
+ os.environ[varname] = old_value
162
+
163
+ def check_requirements(self, reqs):
164
+ # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
165
+ """Return 2 sets:
166
+ - conflicting requirements: set of (installed, wanted) reqs tuples
167
+ - missing requirements: set of reqs
168
+ """
169
+ missing = set()
170
+ conflicting = set()
171
+ if reqs:
172
+ env = get_environment(self._lib_dirs)
173
+ for req_str in reqs:
174
+ req = Requirement(req_str)
175
+ dist = env.get_distribution(req.name)
176
+ if not dist:
177
+ missing.add(req_str)
178
+ continue
179
+ if isinstance(dist.version, Version):
180
+ installed_req_str = f"{req.name}=={dist.version}"
181
+ else:
182
+ installed_req_str = f"{req.name}==={dist.version}"
183
+ if dist.version not in req.specifier:
184
+ conflicting.add((installed_req_str, req_str))
185
+ # FIXME: Consider direct URL?
186
+ return conflicting, missing
187
+
188
+ def install_requirements(
189
+ self,
190
+ finder, # type: PackageFinder
191
+ requirements, # type: Iterable[str]
192
+ prefix_as_string, # type: str
193
+ message # type: str
194
+ ):
195
+ # type: (...) -> None
196
+ prefix = self._prefixes[prefix_as_string]
197
+ assert not prefix.setup
198
+ prefix.setup = True
199
+ if not requirements:
200
+ return
201
+ with contextlib.ExitStack() as ctx:
202
+ # TODO: Remove this block when dropping 3.6 support. Python 3.6
203
+ # lacks importlib.resources and pep517 has issues loading files in
204
+ # a zip, so we fallback to the "old" method by adding the current
205
+ # pip directory to the child process's sys.path.
206
+ if sys.version_info < (3, 7):
207
+ pip_runnable = os.path.dirname(pip_location)
208
+ else:
209
+ pip_runnable = ctx.enter_context(_create_standalone_pip())
210
+ self._install_requirements(
211
+ pip_runnable,
212
+ finder,
213
+ requirements,
214
+ prefix,
215
+ message,
216
+ )
217
+
218
+ @staticmethod
219
+ def _install_requirements(
220
+ pip_runnable: str,
221
+ finder: "PackageFinder",
222
+ requirements: Iterable[str],
223
+ prefix: _Prefix,
224
+ message: str,
225
+ ) -> None:
226
+ args = [
227
+ sys.executable, pip_runnable, 'install',
228
+ '--ignore-installed', '--no-user', '--prefix', prefix.path,
229
+ '--no-warn-script-location',
230
+ ] # type: List[str]
231
+ if logger.getEffectiveLevel() <= logging.DEBUG:
232
+ args.append('-v')
233
+ for format_control in ('no_binary', 'only_binary'):
234
+ formats = getattr(finder.format_control, format_control)
235
+ args.extend(('--' + format_control.replace('_', '-'),
236
+ ','.join(sorted(formats or {':none:'}))))
237
+
238
+ index_urls = finder.index_urls
239
+ if index_urls:
240
+ args.extend(['-i', index_urls[0]])
241
+ for extra_index in index_urls[1:]:
242
+ args.extend(['--extra-index-url', extra_index])
243
+ else:
244
+ args.append('--no-index')
245
+ for link in finder.find_links:
246
+ args.extend(['--find-links', link])
247
+
248
+ for host in finder.trusted_hosts:
249
+ args.extend(['--trusted-host', host])
250
+ if finder.allow_all_prereleases:
251
+ args.append('--pre')
252
+ if finder.prefer_binary:
253
+ args.append('--prefer-binary')
254
+ args.append('--')
255
+ args.extend(requirements)
256
+ extra_environ = {"_PIP_STANDALONE_CERT": where()}
257
+ with open_spinner(message) as spinner:
258
+ call_subprocess(args, spinner=spinner, extra_environ=extra_environ)
259
+
260
+
261
+ class NoOpBuildEnvironment(BuildEnvironment):
262
+ """A no-op drop-in replacement for BuildEnvironment
263
+ """
264
+
265
+ def __init__(self):
266
+ # type: () -> None
267
+ pass
268
+
269
+ def __enter__(self):
270
+ # type: () -> None
271
+ pass
272
+
273
+ def __exit__(
274
+ self,
275
+ exc_type, # type: Optional[Type[BaseException]]
276
+ exc_val, # type: Optional[BaseException]
277
+ exc_tb # type: Optional[TracebackType]
278
+ ):
279
+ # type: (...) -> None
280
+ pass
281
+
282
+ def cleanup(self):
283
+ # type: () -> None
284
+ pass
285
+
286
+ def install_requirements(
287
+ self,
288
+ finder, # type: PackageFinder
289
+ requirements, # type: Iterable[str]
290
+ prefix_as_string, # type: str
291
+ message # type: str
292
+ ):
293
+ # type: (...) -> None
294
+ raise NotImplementedError()
animated_drawings/lib/python3.9/site-packages/pip/_internal/cache.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cache Management
2
+ """
3
+
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import os
8
+ from typing import Any, Dict, List, Optional, Set
9
+
10
+ from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version
11
+ from pip._vendor.packaging.utils import canonicalize_name
12
+
13
+ from pip._internal.exceptions import InvalidWheelFilename
14
+ from pip._internal.models.format_control import FormatControl
15
+ from pip._internal.models.link import Link
16
+ from pip._internal.models.wheel import Wheel
17
+ from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
18
+ from pip._internal.utils.urls import path_to_url
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def _hash_dict(d):
24
+ # type: (Dict[str, str]) -> str
25
+ """Return a stable sha224 of a dictionary."""
26
+ s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
27
+ return hashlib.sha224(s.encode("ascii")).hexdigest()
28
+
29
+
30
+ class Cache:
31
+ """An abstract class - provides cache directories for data from links
32
+
33
+
34
+ :param cache_dir: The root of the cache.
35
+ :param format_control: An object of FormatControl class to limit
36
+ binaries being read from the cache.
37
+ :param allowed_formats: which formats of files the cache should store.
38
+ ('binary' and 'source' are the only allowed values)
39
+ """
40
+
41
+ def __init__(self, cache_dir, format_control, allowed_formats):
42
+ # type: (str, FormatControl, Set[str]) -> None
43
+ super().__init__()
44
+ assert not cache_dir or os.path.isabs(cache_dir)
45
+ self.cache_dir = cache_dir or None
46
+ self.format_control = format_control
47
+ self.allowed_formats = allowed_formats
48
+
49
+ _valid_formats = {"source", "binary"}
50
+ assert self.allowed_formats.union(_valid_formats) == _valid_formats
51
+
52
+ def _get_cache_path_parts(self, link):
53
+ # type: (Link) -> List[str]
54
+ """Get parts of part that must be os.path.joined with cache_dir
55
+ """
56
+
57
+ # We want to generate an url to use as our cache key, we don't want to
58
+ # just re-use the URL because it might have other items in the fragment
59
+ # and we don't care about those.
60
+ key_parts = {"url": link.url_without_fragment}
61
+ if link.hash_name is not None and link.hash is not None:
62
+ key_parts[link.hash_name] = link.hash
63
+ if link.subdirectory_fragment:
64
+ key_parts["subdirectory"] = link.subdirectory_fragment
65
+
66
+ # Include interpreter name, major and minor version in cache key
67
+ # to cope with ill-behaved sdists that build a different wheel
68
+ # depending on the python version their setup.py is being run on,
69
+ # and don't encode the difference in compatibility tags.
70
+ # https://github.com/pypa/pip/issues/7296
71
+ key_parts["interpreter_name"] = interpreter_name()
72
+ key_parts["interpreter_version"] = interpreter_version()
73
+
74
+ # Encode our key url with sha224, we'll use this because it has similar
75
+ # security properties to sha256, but with a shorter total output (and
76
+ # thus less secure). However the differences don't make a lot of
77
+ # difference for our use case here.
78
+ hashed = _hash_dict(key_parts)
79
+
80
+ # We want to nest the directories some to prevent having a ton of top
81
+ # level directories where we might run out of sub directories on some
82
+ # FS.
83
+ parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
84
+
85
+ return parts
86
+
87
+ def _get_candidates(self, link, canonical_package_name):
88
+ # type: (Link, str) -> List[Any]
89
+ can_not_cache = (
90
+ not self.cache_dir or
91
+ not canonical_package_name or
92
+ not link
93
+ )
94
+ if can_not_cache:
95
+ return []
96
+
97
+ formats = self.format_control.get_allowed_formats(
98
+ canonical_package_name
99
+ )
100
+ if not self.allowed_formats.intersection(formats):
101
+ return []
102
+
103
+ candidates = []
104
+ path = self.get_path_for_link(link)
105
+ if os.path.isdir(path):
106
+ for candidate in os.listdir(path):
107
+ candidates.append((candidate, path))
108
+ return candidates
109
+
110
+ def get_path_for_link(self, link):
111
+ # type: (Link) -> str
112
+ """Return a directory to store cached items in for link.
113
+ """
114
+ raise NotImplementedError()
115
+
116
+ def get(
117
+ self,
118
+ link, # type: Link
119
+ package_name, # type: Optional[str]
120
+ supported_tags, # type: List[Tag]
121
+ ):
122
+ # type: (...) -> Link
123
+ """Returns a link to a cached item if it exists, otherwise returns the
124
+ passed link.
125
+ """
126
+ raise NotImplementedError()
127
+
128
+
129
+ class SimpleWheelCache(Cache):
130
+ """A cache of wheels for future installs.
131
+ """
132
+
133
+ def __init__(self, cache_dir, format_control):
134
+ # type: (str, FormatControl) -> None
135
+ super().__init__(cache_dir, format_control, {"binary"})
136
+
137
+ def get_path_for_link(self, link):
138
+ # type: (Link) -> str
139
+ """Return a directory to store cached wheels for link
140
+
141
+ Because there are M wheels for any one sdist, we provide a directory
142
+ to cache them in, and then consult that directory when looking up
143
+ cache hits.
144
+
145
+ We only insert things into the cache if they have plausible version
146
+ numbers, so that we don't contaminate the cache with things that were
147
+ not unique. E.g. ./package might have dozens of installs done for it
148
+ and build a version of 0.0...and if we built and cached a wheel, we'd
149
+ end up using the same wheel even if the source has been edited.
150
+
151
+ :param link: The link of the sdist for which this will cache wheels.
152
+ """
153
+ parts = self._get_cache_path_parts(link)
154
+ assert self.cache_dir
155
+ # Store wheels within the root cache_dir
156
+ return os.path.join(self.cache_dir, "wheels", *parts)
157
+
158
+ def get(
159
+ self,
160
+ link, # type: Link
161
+ package_name, # type: Optional[str]
162
+ supported_tags, # type: List[Tag]
163
+ ):
164
+ # type: (...) -> Link
165
+ candidates = []
166
+
167
+ if not package_name:
168
+ return link
169
+
170
+ canonical_package_name = canonicalize_name(package_name)
171
+ for wheel_name, wheel_dir in self._get_candidates(
172
+ link, canonical_package_name
173
+ ):
174
+ try:
175
+ wheel = Wheel(wheel_name)
176
+ except InvalidWheelFilename:
177
+ continue
178
+ if canonicalize_name(wheel.name) != canonical_package_name:
179
+ logger.debug(
180
+ "Ignoring cached wheel %s for %s as it "
181
+ "does not match the expected distribution name %s.",
182
+ wheel_name, link, package_name,
183
+ )
184
+ continue
185
+ if not wheel.supported(supported_tags):
186
+ # Built for a different python/arch/etc
187
+ continue
188
+ candidates.append(
189
+ (
190
+ wheel.support_index_min(supported_tags),
191
+ wheel_name,
192
+ wheel_dir,
193
+ )
194
+ )
195
+
196
+ if not candidates:
197
+ return link
198
+
199
+ _, wheel_name, wheel_dir = min(candidates)
200
+ return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
201
+
202
+
203
+ class EphemWheelCache(SimpleWheelCache):
204
+ """A SimpleWheelCache that creates it's own temporary cache directory
205
+ """
206
+
207
+ def __init__(self, format_control):
208
+ # type: (FormatControl) -> None
209
+ self._temp_dir = TempDirectory(
210
+ kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
211
+ globally_managed=True,
212
+ )
213
+
214
+ super().__init__(self._temp_dir.path, format_control)
215
+
216
+
217
+ class CacheEntry:
218
+ def __init__(
219
+ self,
220
+ link, # type: Link
221
+ persistent, # type: bool
222
+ ):
223
+ self.link = link
224
+ self.persistent = persistent
225
+
226
+
227
+ class WheelCache(Cache):
228
+ """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
229
+
230
+ This Cache allows for gracefully degradation, using the ephem wheel cache
231
+ when a certain link is not found in the simple wheel cache first.
232
+ """
233
+
234
+ def __init__(self, cache_dir, format_control):
235
+ # type: (str, FormatControl) -> None
236
+ super().__init__(cache_dir, format_control, {'binary'})
237
+ self._wheel_cache = SimpleWheelCache(cache_dir, format_control)
238
+ self._ephem_cache = EphemWheelCache(format_control)
239
+
240
+ def get_path_for_link(self, link):
241
+ # type: (Link) -> str
242
+ return self._wheel_cache.get_path_for_link(link)
243
+
244
+ def get_ephem_path_for_link(self, link):
245
+ # type: (Link) -> str
246
+ return self._ephem_cache.get_path_for_link(link)
247
+
248
+ def get(
249
+ self,
250
+ link, # type: Link
251
+ package_name, # type: Optional[str]
252
+ supported_tags, # type: List[Tag]
253
+ ):
254
+ # type: (...) -> Link
255
+ cache_entry = self.get_cache_entry(link, package_name, supported_tags)
256
+ if cache_entry is None:
257
+ return link
258
+ return cache_entry.link
259
+
260
+ def get_cache_entry(
261
+ self,
262
+ link, # type: Link
263
+ package_name, # type: Optional[str]
264
+ supported_tags, # type: List[Tag]
265
+ ):
266
+ # type: (...) -> Optional[CacheEntry]
267
+ """Returns a CacheEntry with a link to a cached item if it exists or
268
+ None. The cache entry indicates if the item was found in the persistent
269
+ or ephemeral cache.
270
+ """
271
+ retval = self._wheel_cache.get(
272
+ link=link,
273
+ package_name=package_name,
274
+ supported_tags=supported_tags,
275
+ )
276
+ if retval is not link:
277
+ return CacheEntry(retval, persistent=True)
278
+
279
+ retval = self._ephem_cache.get(
280
+ link=link,
281
+ package_name=package_name,
282
+ supported_tags=supported_tags,
283
+ )
284
+ if retval is not link:
285
+ return CacheEntry(retval, persistent=False)
286
+
287
+ return None
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Subpackage containing all of pip's command line interface related code
2
+ """
3
+
4
+ # This file intentionally does not import submodules
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic that powers autocompletion installed by ``pip completion``.
2
+ """
3
+
4
+ import optparse
5
+ import os
6
+ import sys
7
+ from itertools import chain
8
+ from typing import Any, Iterable, List, Optional
9
+
10
+ from pip._internal.cli.main_parser import create_main_parser
11
+ from pip._internal.commands import commands_dict, create_command
12
+ from pip._internal.metadata import get_default_environment
13
+
14
+
15
+ def autocomplete() -> None:
16
+ """Entry Point for completion of main and subcommand options."""
17
+ # Don't complete if user hasn't sourced bash_completion file.
18
+ if "PIP_AUTO_COMPLETE" not in os.environ:
19
+ return
20
+ cwords = os.environ["COMP_WORDS"].split()[1:]
21
+ cword = int(os.environ["COMP_CWORD"])
22
+ try:
23
+ current = cwords[cword - 1]
24
+ except IndexError:
25
+ current = ""
26
+
27
+ parser = create_main_parser()
28
+ subcommands = list(commands_dict)
29
+ options = []
30
+
31
+ # subcommand
32
+ subcommand_name: Optional[str] = None
33
+ for word in cwords:
34
+ if word in subcommands:
35
+ subcommand_name = word
36
+ break
37
+ # subcommand options
38
+ if subcommand_name is not None:
39
+ # special case: 'help' subcommand has no options
40
+ if subcommand_name == "help":
41
+ sys.exit(1)
42
+ # special case: list locally installed dists for show and uninstall
43
+ should_list_installed = not current.startswith("-") and subcommand_name in [
44
+ "show",
45
+ "uninstall",
46
+ ]
47
+ if should_list_installed:
48
+ env = get_default_environment()
49
+ lc = current.lower()
50
+ installed = [
51
+ dist.canonical_name
52
+ for dist in env.iter_installed_distributions(local_only=True)
53
+ if dist.canonical_name.startswith(lc)
54
+ and dist.canonical_name not in cwords[1:]
55
+ ]
56
+ # if there are no dists installed, fall back to option completion
57
+ if installed:
58
+ for dist in installed:
59
+ print(dist)
60
+ sys.exit(1)
61
+
62
+ subcommand = create_command(subcommand_name)
63
+
64
+ for opt in subcommand.parser.option_list_all:
65
+ if opt.help != optparse.SUPPRESS_HELP:
66
+ for opt_str in opt._long_opts + opt._short_opts:
67
+ options.append((opt_str, opt.nargs))
68
+
69
+ # filter out previously specified options from available options
70
+ prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
71
+ options = [(x, v) for (x, v) in options if x not in prev_opts]
72
+ # filter options by current input
73
+ options = [(k, v) for k, v in options if k.startswith(current)]
74
+ # get completion type given cwords and available subcommand options
75
+ completion_type = get_path_completion_type(
76
+ cwords,
77
+ cword,
78
+ subcommand.parser.option_list_all,
79
+ )
80
+ # get completion files and directories if ``completion_type`` is
81
+ # ``<file>``, ``<dir>`` or ``<path>``
82
+ if completion_type:
83
+ paths = auto_complete_paths(current, completion_type)
84
+ options = [(path, 0) for path in paths]
85
+ for option in options:
86
+ opt_label = option[0]
87
+ # append '=' to options which require args
88
+ if option[1] and option[0][:2] == "--":
89
+ opt_label += "="
90
+ print(opt_label)
91
+ else:
92
+ # show main parser options only when necessary
93
+
94
+ opts = [i.option_list for i in parser.option_groups]
95
+ opts.append(parser.option_list)
96
+ flattened_opts = chain.from_iterable(opts)
97
+ if current.startswith("-"):
98
+ for opt in flattened_opts:
99
+ if opt.help != optparse.SUPPRESS_HELP:
100
+ subcommands += opt._long_opts + opt._short_opts
101
+ else:
102
+ # get completion type given cwords and all available options
103
+ completion_type = get_path_completion_type(cwords, cword, flattened_opts)
104
+ if completion_type:
105
+ subcommands = list(auto_complete_paths(current, completion_type))
106
+
107
+ print(" ".join([x for x in subcommands if x.startswith(current)]))
108
+ sys.exit(1)
109
+
110
+
111
+ def get_path_completion_type(
112
+ cwords: List[str], cword: int, opts: Iterable[Any]
113
+ ) -> Optional[str]:
114
+ """Get the type of path completion (``file``, ``dir``, ``path`` or None)
115
+
116
+ :param cwords: same as the environmental variable ``COMP_WORDS``
117
+ :param cword: same as the environmental variable ``COMP_CWORD``
118
+ :param opts: The available options to check
119
+ :return: path completion type (``file``, ``dir``, ``path`` or None)
120
+ """
121
+ if cword < 2 or not cwords[cword - 2].startswith("-"):
122
+ return None
123
+ for opt in opts:
124
+ if opt.help == optparse.SUPPRESS_HELP:
125
+ continue
126
+ for o in str(opt).split("/"):
127
+ if cwords[cword - 2].split("=")[0] == o:
128
+ if not opt.metavar or any(
129
+ x in ("path", "file", "dir") for x in opt.metavar.split("/")
130
+ ):
131
+ return opt.metavar
132
+ return None
133
+
134
+
135
+ def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
136
+ """If ``completion_type`` is ``file`` or ``path``, list all regular files
137
+ and directories starting with ``current``; otherwise only list directories
138
+ starting with ``current``.
139
+
140
+ :param current: The word to be completed
141
+ :param completion_type: path completion type(`file`, `path` or `dir`)i
142
+ :return: A generator of regular files and/or directories
143
+ """
144
+ directory, filename = os.path.split(current)
145
+ current_path = os.path.abspath(directory)
146
+ # Don't complete paths if they can't be accessed
147
+ if not os.access(current_path, os.R_OK):
148
+ return
149
+ filename = os.path.normcase(filename)
150
+ # list all files that start with ``filename``
151
+ file_list = (
152
+ x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
153
+ )
154
+ for f in file_list:
155
+ opt = os.path.join(current_path, f)
156
+ comp_file = os.path.normcase(os.path.join(directory, f))
157
+ # complete regular files when there is not ``<dir>`` after option
158
+ # complete directories when there is ``<file>``, ``<path>`` or
159
+ # ``<dir>``after option
160
+ if completion_type != "dir" and os.path.isfile(opt):
161
+ yield comp_file
162
+ elif os.path.isdir(opt):
163
+ yield os.path.join(comp_file, "")
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/base_command.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base Command class, and related routines"""
2
+
3
+ import logging
4
+ import logging.config
5
+ import optparse
6
+ import os
7
+ import sys
8
+ import traceback
9
+ from optparse import Values
10
+ from typing import Any, List, Optional, Tuple
11
+
12
+ from pip._internal.cli import cmdoptions
13
+ from pip._internal.cli.command_context import CommandContextMixIn
14
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
15
+ from pip._internal.cli.status_codes import (
16
+ ERROR,
17
+ PREVIOUS_BUILD_DIR_ERROR,
18
+ UNKNOWN_ERROR,
19
+ VIRTUALENV_NOT_FOUND,
20
+ )
21
+ from pip._internal.exceptions import (
22
+ BadCommand,
23
+ CommandError,
24
+ InstallationError,
25
+ NetworkConnectionError,
26
+ PreviousBuildDirError,
27
+ UninstallationError,
28
+ )
29
+ from pip._internal.utils.deprecation import deprecated
30
+ from pip._internal.utils.filesystem import check_path_owner
31
+ from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
32
+ from pip._internal.utils.misc import get_prog, normalize_path
33
+ from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
34
+ from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
35
+ from pip._internal.utils.virtualenv import running_under_virtualenv
36
+
37
+ __all__ = ["Command"]
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ class Command(CommandContextMixIn):
43
+ usage: str = ""
44
+ ignore_require_venv: bool = False
45
+
46
+ def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
47
+ super().__init__()
48
+
49
+ self.name = name
50
+ self.summary = summary
51
+ self.parser = ConfigOptionParser(
52
+ usage=self.usage,
53
+ prog=f"{get_prog()} {name}",
54
+ formatter=UpdatingDefaultsHelpFormatter(),
55
+ add_help_option=False,
56
+ name=name,
57
+ description=self.__doc__,
58
+ isolated=isolated,
59
+ )
60
+
61
+ self.tempdir_registry: Optional[TempDirRegistry] = None
62
+
63
+ # Commands should add options to this option group
64
+ optgroup_name = f"{self.name.capitalize()} Options"
65
+ self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
66
+
67
+ # Add the general options
68
+ gen_opts = cmdoptions.make_option_group(
69
+ cmdoptions.general_group,
70
+ self.parser,
71
+ )
72
+ self.parser.add_option_group(gen_opts)
73
+
74
+ self.add_options()
75
+
76
+ def add_options(self) -> None:
77
+ pass
78
+
79
+ def handle_pip_version_check(self, options: Values) -> None:
80
+ """
81
+ This is a no-op so that commands by default do not do the pip version
82
+ check.
83
+ """
84
+ # Make sure we do the pip version check if the index_group options
85
+ # are present.
86
+ assert not hasattr(options, "no_index")
87
+
88
+ def run(self, options: Values, args: List[Any]) -> int:
89
+ raise NotImplementedError
90
+
91
+ def parse_args(self, args: List[str]) -> Tuple[Any, Any]:
92
+ # factored out for testability
93
+ return self.parser.parse_args(args)
94
+
95
+ def main(self, args: List[str]) -> int:
96
+ try:
97
+ with self.main_context():
98
+ return self._main(args)
99
+ finally:
100
+ logging.shutdown()
101
+
102
+ def _main(self, args: List[str]) -> int:
103
+ # We must initialize this before the tempdir manager, otherwise the
104
+ # configuration would not be accessible by the time we clean up the
105
+ # tempdir manager.
106
+ self.tempdir_registry = self.enter_context(tempdir_registry())
107
+ # Intentionally set as early as possible so globally-managed temporary
108
+ # directories are available to the rest of the code.
109
+ self.enter_context(global_tempdir_manager())
110
+
111
+ options, args = self.parse_args(args)
112
+
113
+ # Set verbosity so that it can be used elsewhere.
114
+ self.verbosity = options.verbose - options.quiet
115
+
116
+ level_number = setup_logging(
117
+ verbosity=self.verbosity,
118
+ no_color=options.no_color,
119
+ user_log_file=options.log,
120
+ )
121
+
122
+ # TODO: Try to get these passing down from the command?
123
+ # without resorting to os.environ to hold these.
124
+ # This also affects isolated builds and it should.
125
+
126
+ if options.no_input:
127
+ os.environ["PIP_NO_INPUT"] = "1"
128
+
129
+ if options.exists_action:
130
+ os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
131
+
132
+ if options.require_venv and not self.ignore_require_venv:
133
+ # If a venv is required check if it can really be found
134
+ if not running_under_virtualenv():
135
+ logger.critical("Could not find an activated virtualenv (required).")
136
+ sys.exit(VIRTUALENV_NOT_FOUND)
137
+
138
+ if options.cache_dir:
139
+ options.cache_dir = normalize_path(options.cache_dir)
140
+ if not check_path_owner(options.cache_dir):
141
+ logger.warning(
142
+ "The directory '%s' or its parent directory is not owned "
143
+ "or is not writable by the current user. The cache "
144
+ "has been disabled. Check the permissions and owner of "
145
+ "that directory. If executing pip with sudo, you should "
146
+ "use sudo's -H flag.",
147
+ options.cache_dir,
148
+ )
149
+ options.cache_dir = None
150
+
151
+ if getattr(options, "build_dir", None):
152
+ deprecated(
153
+ reason=(
154
+ "The -b/--build/--build-dir/--build-directory "
155
+ "option is deprecated and has no effect anymore."
156
+ ),
157
+ replacement=(
158
+ "use the TMPDIR/TEMP/TMP environment variable, "
159
+ "possibly combined with --no-clean"
160
+ ),
161
+ gone_in="21.3",
162
+ issue=8333,
163
+ )
164
+
165
+ if "2020-resolver" in options.features_enabled:
166
+ logger.warning(
167
+ "--use-feature=2020-resolver no longer has any effect, "
168
+ "since it is now the default dependency resolver in pip. "
169
+ "This will become an error in pip 21.0."
170
+ )
171
+
172
+ try:
173
+ status = self.run(options, args)
174
+ assert isinstance(status, int)
175
+ return status
176
+ except PreviousBuildDirError as exc:
177
+ logger.critical(str(exc))
178
+ logger.debug("Exception information:", exc_info=True)
179
+
180
+ return PREVIOUS_BUILD_DIR_ERROR
181
+ except (
182
+ InstallationError,
183
+ UninstallationError,
184
+ BadCommand,
185
+ NetworkConnectionError,
186
+ ) as exc:
187
+ logger.critical(str(exc))
188
+ logger.debug("Exception information:", exc_info=True)
189
+
190
+ return ERROR
191
+ except CommandError as exc:
192
+ logger.critical("%s", exc)
193
+ logger.debug("Exception information:", exc_info=True)
194
+
195
+ return ERROR
196
+ except BrokenStdoutLoggingError:
197
+ # Bypass our logger and write any remaining messages to stderr
198
+ # because stdout no longer works.
199
+ print("ERROR: Pipe to stdout was broken", file=sys.stderr)
200
+ if level_number <= logging.DEBUG:
201
+ traceback.print_exc(file=sys.stderr)
202
+
203
+ return ERROR
204
+ except KeyboardInterrupt:
205
+ logger.critical("Operation cancelled by user")
206
+ logger.debug("Exception information:", exc_info=True)
207
+
208
+ return ERROR
209
+ except BaseException:
210
+ logger.critical("Exception:", exc_info=True)
211
+
212
+ return UNKNOWN_ERROR
213
+ finally:
214
+ self.handle_pip_version_check(options)
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/cmdoptions.py ADDED
@@ -0,0 +1,1009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ shared options and groups
3
+
4
+ The principle here is to define options once, but *not* instantiate them
5
+ globally. One reason being that options with action='append' can carry state
6
+ between parses. pip parses general options twice internally, and shouldn't
7
+ pass on state. To be consistent, all options will follow this design.
8
+ """
9
+
10
+ # The following comment should be removed at some point in the future.
11
+ # mypy: strict-optional=False
12
+
13
+ import os
14
+ import textwrap
15
+ import warnings
16
+ from functools import partial
17
+ from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values
18
+ from textwrap import dedent
19
+ from typing import Any, Callable, Dict, Optional, Tuple
20
+
21
+ from pip._vendor.packaging.utils import canonicalize_name
22
+
23
+ from pip._internal.cli.parser import ConfigOptionParser
24
+ from pip._internal.cli.progress_bars import BAR_TYPES
25
+ from pip._internal.exceptions import CommandError
26
+ from pip._internal.locations import USER_CACHE_DIR, get_src_prefix
27
+ from pip._internal.models.format_control import FormatControl
28
+ from pip._internal.models.index import PyPI
29
+ from pip._internal.models.target_python import TargetPython
30
+ from pip._internal.utils.hashes import STRONG_HASHES
31
+ from pip._internal.utils.misc import strtobool
32
+
33
+
34
+ def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:
35
+ """
36
+ Raise an option parsing error using parser.error().
37
+
38
+ Args:
39
+ parser: an OptionParser instance.
40
+ option: an Option instance.
41
+ msg: the error text.
42
+ """
43
+ msg = f"{option} error: {msg}"
44
+ msg = textwrap.fill(" ".join(msg.split()))
45
+ parser.error(msg)
46
+
47
+
48
+ def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:
49
+ """
50
+ Return an OptionGroup object
51
+ group -- assumed to be dict with 'name' and 'options' keys
52
+ parser -- an optparse Parser
53
+ """
54
+ option_group = OptionGroup(parser, group["name"])
55
+ for option in group["options"]:
56
+ option_group.add_option(option())
57
+ return option_group
58
+
59
+
60
+ def check_install_build_global(
61
+ options: Values, check_options: Optional[Values] = None
62
+ ) -> None:
63
+ """Disable wheels if per-setup.py call options are set.
64
+
65
+ :param options: The OptionParser options to update.
66
+ :param check_options: The options to check, if not supplied defaults to
67
+ options.
68
+ """
69
+ if check_options is None:
70
+ check_options = options
71
+
72
+ def getname(n: str) -> Optional[Any]:
73
+ return getattr(check_options, n, None)
74
+
75
+ names = ["build_options", "global_options", "install_options"]
76
+ if any(map(getname, names)):
77
+ control = options.format_control
78
+ control.disallow_binaries()
79
+ warnings.warn(
80
+ "Disabling all use of wheels due to the use of --build-option "
81
+ "/ --global-option / --install-option.",
82
+ stacklevel=2,
83
+ )
84
+
85
+
86
+ def check_dist_restriction(options: Values, check_target: bool = False) -> None:
87
+ """Function for determining if custom platform options are allowed.
88
+
89
+ :param options: The OptionParser options.
90
+ :param check_target: Whether or not to check if --target is being used.
91
+ """
92
+ dist_restriction_set = any(
93
+ [
94
+ options.python_version,
95
+ options.platforms,
96
+ options.abis,
97
+ options.implementation,
98
+ ]
99
+ )
100
+
101
+ binary_only = FormatControl(set(), {":all:"})
102
+ sdist_dependencies_allowed = (
103
+ options.format_control != binary_only and not options.ignore_dependencies
104
+ )
105
+
106
+ # Installations or downloads using dist restrictions must not combine
107
+ # source distributions and dist-specific wheels, as they are not
108
+ # guaranteed to be locally compatible.
109
+ if dist_restriction_set and sdist_dependencies_allowed:
110
+ raise CommandError(
111
+ "When restricting platform and interpreter constraints using "
112
+ "--python-version, --platform, --abi, or --implementation, "
113
+ "either --no-deps must be set, or --only-binary=:all: must be "
114
+ "set and --no-binary must not be set (or must be set to "
115
+ ":none:)."
116
+ )
117
+
118
+ if check_target:
119
+ if dist_restriction_set and not options.target_dir:
120
+ raise CommandError(
121
+ "Can not use any platform or abi specific options unless "
122
+ "installing via '--target'"
123
+ )
124
+
125
+
126
+ def _path_option_check(option: Option, opt: str, value: str) -> str:
127
+ return os.path.expanduser(value)
128
+
129
+
130
+ def _package_name_option_check(option: Option, opt: str, value: str) -> str:
131
+ return canonicalize_name(value)
132
+
133
+
134
+ class PipOption(Option):
135
+ TYPES = Option.TYPES + ("path", "package_name")
136
+ TYPE_CHECKER = Option.TYPE_CHECKER.copy()
137
+ TYPE_CHECKER["package_name"] = _package_name_option_check
138
+ TYPE_CHECKER["path"] = _path_option_check
139
+
140
+
141
+ ###########
142
+ # options #
143
+ ###########
144
+
145
+ help_: Callable[..., Option] = partial(
146
+ Option,
147
+ "-h",
148
+ "--help",
149
+ dest="help",
150
+ action="help",
151
+ help="Show help.",
152
+ )
153
+
154
+ isolated_mode: Callable[..., Option] = partial(
155
+ Option,
156
+ "--isolated",
157
+ dest="isolated_mode",
158
+ action="store_true",
159
+ default=False,
160
+ help=(
161
+ "Run pip in an isolated mode, ignoring environment variables and user "
162
+ "configuration."
163
+ ),
164
+ )
165
+
166
+ require_virtualenv: Callable[..., Option] = partial(
167
+ Option,
168
+ # Run only if inside a virtualenv, bail if not.
169
+ "--require-virtualenv",
170
+ "--require-venv",
171
+ dest="require_venv",
172
+ action="store_true",
173
+ default=False,
174
+ help=SUPPRESS_HELP,
175
+ )
176
+
177
+ verbose: Callable[..., Option] = partial(
178
+ Option,
179
+ "-v",
180
+ "--verbose",
181
+ dest="verbose",
182
+ action="count",
183
+ default=0,
184
+ help="Give more output. Option is additive, and can be used up to 3 times.",
185
+ )
186
+
187
+ no_color: Callable[..., Option] = partial(
188
+ Option,
189
+ "--no-color",
190
+ dest="no_color",
191
+ action="store_true",
192
+ default=False,
193
+ help="Suppress colored output.",
194
+ )
195
+
196
+ version: Callable[..., Option] = partial(
197
+ Option,
198
+ "-V",
199
+ "--version",
200
+ dest="version",
201
+ action="store_true",
202
+ help="Show version and exit.",
203
+ )
204
+
205
+ quiet: Callable[..., Option] = partial(
206
+ Option,
207
+ "-q",
208
+ "--quiet",
209
+ dest="quiet",
210
+ action="count",
211
+ default=0,
212
+ help=(
213
+ "Give less output. Option is additive, and can be used up to 3"
214
+ " times (corresponding to WARNING, ERROR, and CRITICAL logging"
215
+ " levels)."
216
+ ),
217
+ )
218
+
219
+ progress_bar: Callable[..., Option] = partial(
220
+ Option,
221
+ "--progress-bar",
222
+ dest="progress_bar",
223
+ type="choice",
224
+ choices=list(BAR_TYPES.keys()),
225
+ default="on",
226
+ help=(
227
+ "Specify type of progress to be displayed ["
228
+ + "|".join(BAR_TYPES.keys())
229
+ + "] (default: %default)"
230
+ ),
231
+ )
232
+
233
+ log: Callable[..., Option] = partial(
234
+ PipOption,
235
+ "--log",
236
+ "--log-file",
237
+ "--local-log",
238
+ dest="log",
239
+ metavar="path",
240
+ type="path",
241
+ help="Path to a verbose appending log.",
242
+ )
243
+
244
+ no_input: Callable[..., Option] = partial(
245
+ Option,
246
+ # Don't ask for input
247
+ "--no-input",
248
+ dest="no_input",
249
+ action="store_true",
250
+ default=False,
251
+ help="Disable prompting for input.",
252
+ )
253
+
254
+ proxy: Callable[..., Option] = partial(
255
+ Option,
256
+ "--proxy",
257
+ dest="proxy",
258
+ type="str",
259
+ default="",
260
+ help="Specify a proxy in the form [user:passwd@]proxy.server:port.",
261
+ )
262
+
263
+ retries: Callable[..., Option] = partial(
264
+ Option,
265
+ "--retries",
266
+ dest="retries",
267
+ type="int",
268
+ default=5,
269
+ help="Maximum number of retries each connection should attempt "
270
+ "(default %default times).",
271
+ )
272
+
273
+ timeout: Callable[..., Option] = partial(
274
+ Option,
275
+ "--timeout",
276
+ "--default-timeout",
277
+ metavar="sec",
278
+ dest="timeout",
279
+ type="float",
280
+ default=15,
281
+ help="Set the socket timeout (default %default seconds).",
282
+ )
283
+
284
+
285
+ def exists_action() -> Option:
286
+ return Option(
287
+ # Option when path already exist
288
+ "--exists-action",
289
+ dest="exists_action",
290
+ type="choice",
291
+ choices=["s", "i", "w", "b", "a"],
292
+ default=[],
293
+ action="append",
294
+ metavar="action",
295
+ help="Default action when a path already exists: "
296
+ "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.",
297
+ )
298
+
299
+
300
+ cert: Callable[..., Option] = partial(
301
+ PipOption,
302
+ "--cert",
303
+ dest="cert",
304
+ type="path",
305
+ metavar="path",
306
+ help=(
307
+ "Path to PEM-encoded CA certificate bundle. "
308
+ "If provided, overrides the default. "
309
+ "See 'SSL Certificate Verification' in pip documentation "
310
+ "for more information."
311
+ ),
312
+ )
313
+
314
+ client_cert: Callable[..., Option] = partial(
315
+ PipOption,
316
+ "--client-cert",
317
+ dest="client_cert",
318
+ type="path",
319
+ default=None,
320
+ metavar="path",
321
+ help="Path to SSL client certificate, a single file containing the "
322
+ "private key and the certificate in PEM format.",
323
+ )
324
+
325
+ index_url: Callable[..., Option] = partial(
326
+ Option,
327
+ "-i",
328
+ "--index-url",
329
+ "--pypi-url",
330
+ dest="index_url",
331
+ metavar="URL",
332
+ default=PyPI.simple_url,
333
+ help="Base URL of the Python Package Index (default %default). "
334
+ "This should point to a repository compliant with PEP 503 "
335
+ "(the simple repository API) or a local directory laid out "
336
+ "in the same format.",
337
+ )
338
+
339
+
340
+ def extra_index_url() -> Option:
341
+ return Option(
342
+ "--extra-index-url",
343
+ dest="extra_index_urls",
344
+ metavar="URL",
345
+ action="append",
346
+ default=[],
347
+ help="Extra URLs of package indexes to use in addition to "
348
+ "--index-url. Should follow the same rules as "
349
+ "--index-url.",
350
+ )
351
+
352
+
353
+ no_index: Callable[..., Option] = partial(
354
+ Option,
355
+ "--no-index",
356
+ dest="no_index",
357
+ action="store_true",
358
+ default=False,
359
+ help="Ignore package index (only looking at --find-links URLs instead).",
360
+ )
361
+
362
+
363
+ def find_links() -> Option:
364
+ return Option(
365
+ "-f",
366
+ "--find-links",
367
+ dest="find_links",
368
+ action="append",
369
+ default=[],
370
+ metavar="url",
371
+ help="If a URL or path to an html file, then parse for links to "
372
+ "archives such as sdist (.tar.gz) or wheel (.whl) files. "
373
+ "If a local path or file:// URL that's a directory, "
374
+ "then look for archives in the directory listing. "
375
+ "Links to VCS project URLs are not supported.",
376
+ )
377
+
378
+
379
+ def trusted_host() -> Option:
380
+ return Option(
381
+ "--trusted-host",
382
+ dest="trusted_hosts",
383
+ action="append",
384
+ metavar="HOSTNAME",
385
+ default=[],
386
+ help="Mark this host or host:port pair as trusted, even though it "
387
+ "does not have valid or any HTTPS.",
388
+ )
389
+
390
+
391
+ def constraints() -> Option:
392
+ return Option(
393
+ "-c",
394
+ "--constraint",
395
+ dest="constraints",
396
+ action="append",
397
+ default=[],
398
+ metavar="file",
399
+ help="Constrain versions using the given constraints file. "
400
+ "This option can be used multiple times.",
401
+ )
402
+
403
+
404
+ def requirements() -> Option:
405
+ return Option(
406
+ "-r",
407
+ "--requirement",
408
+ dest="requirements",
409
+ action="append",
410
+ default=[],
411
+ metavar="file",
412
+ help="Install from the given requirements file. "
413
+ "This option can be used multiple times.",
414
+ )
415
+
416
+
417
+ def editable() -> Option:
418
+ return Option(
419
+ "-e",
420
+ "--editable",
421
+ dest="editables",
422
+ action="append",
423
+ default=[],
424
+ metavar="path/url",
425
+ help=(
426
+ "Install a project in editable mode (i.e. setuptools "
427
+ '"develop mode") from a local project path or a VCS url.'
428
+ ),
429
+ )
430
+
431
+
432
+ def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:
433
+ value = os.path.abspath(value)
434
+ setattr(parser.values, option.dest, value)
435
+
436
+
437
+ src: Callable[..., Option] = partial(
438
+ PipOption,
439
+ "--src",
440
+ "--source",
441
+ "--source-dir",
442
+ "--source-directory",
443
+ dest="src_dir",
444
+ type="path",
445
+ metavar="dir",
446
+ default=get_src_prefix(),
447
+ action="callback",
448
+ callback=_handle_src,
449
+ help="Directory to check out editable projects into. "
450
+ 'The default in a virtualenv is "<venv path>/src". '
451
+ 'The default for global installs is "<current dir>/src".',
452
+ )
453
+
454
+
455
+ def _get_format_control(values: Values, option: Option) -> Any:
456
+ """Get a format_control object."""
457
+ return getattr(values, option.dest)
458
+
459
+
460
+ def _handle_no_binary(
461
+ option: Option, opt_str: str, value: str, parser: OptionParser
462
+ ) -> None:
463
+ existing = _get_format_control(parser.values, option)
464
+ FormatControl.handle_mutual_excludes(
465
+ value,
466
+ existing.no_binary,
467
+ existing.only_binary,
468
+ )
469
+
470
+
471
+ def _handle_only_binary(
472
+ option: Option, opt_str: str, value: str, parser: OptionParser
473
+ ) -> None:
474
+ existing = _get_format_control(parser.values, option)
475
+ FormatControl.handle_mutual_excludes(
476
+ value,
477
+ existing.only_binary,
478
+ existing.no_binary,
479
+ )
480
+
481
+
482
+ def no_binary() -> Option:
483
+ format_control = FormatControl(set(), set())
484
+ return Option(
485
+ "--no-binary",
486
+ dest="format_control",
487
+ action="callback",
488
+ callback=_handle_no_binary,
489
+ type="str",
490
+ default=format_control,
491
+ help="Do not use binary packages. Can be supplied multiple times, and "
492
+ 'each time adds to the existing value. Accepts either ":all:" to '
493
+ 'disable all binary packages, ":none:" to empty the set (notice '
494
+ "the colons), or one or more package names with commas between "
495
+ "them (no colons). Note that some packages are tricky to compile "
496
+ "and may fail to install when this option is used on them.",
497
+ )
498
+
499
+
500
+ def only_binary() -> Option:
501
+ format_control = FormatControl(set(), set())
502
+ return Option(
503
+ "--only-binary",
504
+ dest="format_control",
505
+ action="callback",
506
+ callback=_handle_only_binary,
507
+ type="str",
508
+ default=format_control,
509
+ help="Do not use source packages. Can be supplied multiple times, and "
510
+ 'each time adds to the existing value. Accepts either ":all:" to '
511
+ 'disable all source packages, ":none:" to empty the set, or one '
512
+ "or more package names with commas between them. Packages "
513
+ "without binary distributions will fail to install when this "
514
+ "option is used on them.",
515
+ )
516
+
517
+
518
+ platforms: Callable[..., Option] = partial(
519
+ Option,
520
+ "--platform",
521
+ dest="platforms",
522
+ metavar="platform",
523
+ action="append",
524
+ default=None,
525
+ help=(
526
+ "Only use wheels compatible with <platform>. Defaults to the "
527
+ "platform of the running system. Use this option multiple times to "
528
+ "specify multiple platforms supported by the target interpreter."
529
+ ),
530
+ )
531
+
532
+
533
+ # This was made a separate function for unit-testing purposes.
534
+ def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]:
535
+ """
536
+ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
537
+
538
+ :return: A 2-tuple (version_info, error_msg), where `error_msg` is
539
+ non-None if and only if there was a parsing error.
540
+ """
541
+ if not value:
542
+ # The empty string is the same as not providing a value.
543
+ return (None, None)
544
+
545
+ parts = value.split(".")
546
+ if len(parts) > 3:
547
+ return ((), "at most three version parts are allowed")
548
+
549
+ if len(parts) == 1:
550
+ # Then we are in the case of "3" or "37".
551
+ value = parts[0]
552
+ if len(value) > 1:
553
+ parts = [value[0], value[1:]]
554
+
555
+ try:
556
+ version_info = tuple(int(part) for part in parts)
557
+ except ValueError:
558
+ return ((), "each version part must be an integer")
559
+
560
+ return (version_info, None)
561
+
562
+
563
+ def _handle_python_version(
564
+ option: Option, opt_str: str, value: str, parser: OptionParser
565
+ ) -> None:
566
+ """
567
+ Handle a provided --python-version value.
568
+ """
569
+ version_info, error_msg = _convert_python_version(value)
570
+ if error_msg is not None:
571
+ msg = "invalid --python-version value: {!r}: {}".format(
572
+ value,
573
+ error_msg,
574
+ )
575
+ raise_option_error(parser, option=option, msg=msg)
576
+
577
+ parser.values.python_version = version_info
578
+
579
+
580
+ python_version: Callable[..., Option] = partial(
581
+ Option,
582
+ "--python-version",
583
+ dest="python_version",
584
+ metavar="python_version",
585
+ action="callback",
586
+ callback=_handle_python_version,
587
+ type="str",
588
+ default=None,
589
+ help=dedent(
590
+ """\
591
+ The Python interpreter version to use for wheel and "Requires-Python"
592
+ compatibility checks. Defaults to a version derived from the running
593
+ interpreter. The version can be specified using up to three dot-separated
594
+ integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor
595
+ version can also be given as a string without dots (e.g. "37" for 3.7.0).
596
+ """
597
+ ),
598
+ )
599
+
600
+
601
+ implementation: Callable[..., Option] = partial(
602
+ Option,
603
+ "--implementation",
604
+ dest="implementation",
605
+ metavar="implementation",
606
+ default=None,
607
+ help=(
608
+ "Only use wheels compatible with Python "
609
+ "implementation <implementation>, e.g. 'pp', 'jy', 'cp', "
610
+ " or 'ip'. If not specified, then the current "
611
+ "interpreter implementation is used. Use 'py' to force "
612
+ "implementation-agnostic wheels."
613
+ ),
614
+ )
615
+
616
+
617
+ abis: Callable[..., Option] = partial(
618
+ Option,
619
+ "--abi",
620
+ dest="abis",
621
+ metavar="abi",
622
+ action="append",
623
+ default=None,
624
+ help=(
625
+ "Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. "
626
+ "If not specified, then the current interpreter abi tag is used. "
627
+ "Use this option multiple times to specify multiple abis supported "
628
+ "by the target interpreter. Generally you will need to specify "
629
+ "--implementation, --platform, and --python-version when using this "
630
+ "option."
631
+ ),
632
+ )
633
+
634
+
635
+ def add_target_python_options(cmd_opts: OptionGroup) -> None:
636
+ cmd_opts.add_option(platforms())
637
+ cmd_opts.add_option(python_version())
638
+ cmd_opts.add_option(implementation())
639
+ cmd_opts.add_option(abis())
640
+
641
+
642
+ def make_target_python(options: Values) -> TargetPython:
643
+ target_python = TargetPython(
644
+ platforms=options.platforms,
645
+ py_version_info=options.python_version,
646
+ abis=options.abis,
647
+ implementation=options.implementation,
648
+ )
649
+
650
+ return target_python
651
+
652
+
653
+ def prefer_binary() -> Option:
654
+ return Option(
655
+ "--prefer-binary",
656
+ dest="prefer_binary",
657
+ action="store_true",
658
+ default=False,
659
+ help="Prefer older binary packages over newer source packages.",
660
+ )
661
+
662
+
663
+ cache_dir: Callable[..., Option] = partial(
664
+ PipOption,
665
+ "--cache-dir",
666
+ dest="cache_dir",
667
+ default=USER_CACHE_DIR,
668
+ metavar="dir",
669
+ type="path",
670
+ help="Store the cache data in <dir>.",
671
+ )
672
+
673
+
674
+ def _handle_no_cache_dir(
675
+ option: Option, opt: str, value: str, parser: OptionParser
676
+ ) -> None:
677
+ """
678
+ Process a value provided for the --no-cache-dir option.
679
+
680
+ This is an optparse.Option callback for the --no-cache-dir option.
681
+ """
682
+ # The value argument will be None if --no-cache-dir is passed via the
683
+ # command-line, since the option doesn't accept arguments. However,
684
+ # the value can be non-None if the option is triggered e.g. by an
685
+ # environment variable, like PIP_NO_CACHE_DIR=true.
686
+ if value is not None:
687
+ # Then parse the string value to get argument error-checking.
688
+ try:
689
+ strtobool(value)
690
+ except ValueError as exc:
691
+ raise_option_error(parser, option=option, msg=str(exc))
692
+
693
+ # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()
694
+ # converted to 0 (like "false" or "no") caused cache_dir to be disabled
695
+ # rather than enabled (logic would say the latter). Thus, we disable
696
+ # the cache directory not just on values that parse to True, but (for
697
+ # backwards compatibility reasons) also on values that parse to False.
698
+ # In other words, always set it to False if the option is provided in
699
+ # some (valid) form.
700
+ parser.values.cache_dir = False
701
+
702
+
703
+ no_cache: Callable[..., Option] = partial(
704
+ Option,
705
+ "--no-cache-dir",
706
+ dest="cache_dir",
707
+ action="callback",
708
+ callback=_handle_no_cache_dir,
709
+ help="Disable the cache.",
710
+ )
711
+
712
+ no_deps: Callable[..., Option] = partial(
713
+ Option,
714
+ "--no-deps",
715
+ "--no-dependencies",
716
+ dest="ignore_dependencies",
717
+ action="store_true",
718
+ default=False,
719
+ help="Don't install package dependencies.",
720
+ )
721
+
722
+ build_dir: Callable[..., Option] = partial(
723
+ PipOption,
724
+ "-b",
725
+ "--build",
726
+ "--build-dir",
727
+ "--build-directory",
728
+ dest="build_dir",
729
+ type="path",
730
+ metavar="dir",
731
+ help=SUPPRESS_HELP,
732
+ )
733
+
734
+ ignore_requires_python: Callable[..., Option] = partial(
735
+ Option,
736
+ "--ignore-requires-python",
737
+ dest="ignore_requires_python",
738
+ action="store_true",
739
+ help="Ignore the Requires-Python information.",
740
+ )
741
+
742
+ no_build_isolation: Callable[..., Option] = partial(
743
+ Option,
744
+ "--no-build-isolation",
745
+ dest="build_isolation",
746
+ action="store_false",
747
+ default=True,
748
+ help="Disable isolation when building a modern source distribution. "
749
+ "Build dependencies specified by PEP 518 must be already installed "
750
+ "if this option is used.",
751
+ )
752
+
753
+
754
+ def _handle_no_use_pep517(
755
+ option: Option, opt: str, value: str, parser: OptionParser
756
+ ) -> None:
757
+ """
758
+ Process a value provided for the --no-use-pep517 option.
759
+
760
+ This is an optparse.Option callback for the no_use_pep517 option.
761
+ """
762
+ # Since --no-use-pep517 doesn't accept arguments, the value argument
763
+ # will be None if --no-use-pep517 is passed via the command-line.
764
+ # However, the value can be non-None if the option is triggered e.g.
765
+ # by an environment variable, for example "PIP_NO_USE_PEP517=true".
766
+ if value is not None:
767
+ msg = """A value was passed for --no-use-pep517,
768
+ probably using either the PIP_NO_USE_PEP517 environment variable
769
+ or the "no-use-pep517" config file option. Use an appropriate value
770
+ of the PIP_USE_PEP517 environment variable or the "use-pep517"
771
+ config file option instead.
772
+ """
773
+ raise_option_error(parser, option=option, msg=msg)
774
+
775
+ # Otherwise, --no-use-pep517 was passed via the command-line.
776
+ parser.values.use_pep517 = False
777
+
778
+
779
+ use_pep517: Any = partial(
780
+ Option,
781
+ "--use-pep517",
782
+ dest="use_pep517",
783
+ action="store_true",
784
+ default=None,
785
+ help="Use PEP 517 for building source distributions "
786
+ "(use --no-use-pep517 to force legacy behaviour).",
787
+ )
788
+
789
+ no_use_pep517: Any = partial(
790
+ Option,
791
+ "--no-use-pep517",
792
+ dest="use_pep517",
793
+ action="callback",
794
+ callback=_handle_no_use_pep517,
795
+ default=None,
796
+ help=SUPPRESS_HELP,
797
+ )
798
+
799
+ install_options: Callable[..., Option] = partial(
800
+ Option,
801
+ "--install-option",
802
+ dest="install_options",
803
+ action="append",
804
+ metavar="options",
805
+ help="Extra arguments to be supplied to the setup.py install "
806
+ 'command (use like --install-option="--install-scripts=/usr/local/'
807
+ 'bin"). Use multiple --install-option options to pass multiple '
808
+ "options to setup.py install. If you are using an option with a "
809
+ "directory path, be sure to use absolute path.",
810
+ )
811
+
812
+ build_options: Callable[..., Option] = partial(
813
+ Option,
814
+ "--build-option",
815
+ dest="build_options",
816
+ metavar="options",
817
+ action="append",
818
+ help="Extra arguments to be supplied to 'setup.py bdist_wheel'.",
819
+ )
820
+
821
+ global_options: Callable[..., Option] = partial(
822
+ Option,
823
+ "--global-option",
824
+ dest="global_options",
825
+ action="append",
826
+ metavar="options",
827
+ help="Extra global options to be supplied to the setup.py "
828
+ "call before the install or bdist_wheel command.",
829
+ )
830
+
831
+ no_clean: Callable[..., Option] = partial(
832
+ Option,
833
+ "--no-clean",
834
+ action="store_true",
835
+ default=False,
836
+ help="Don't clean up build directories.",
837
+ )
838
+
839
+ pre: Callable[..., Option] = partial(
840
+ Option,
841
+ "--pre",
842
+ action="store_true",
843
+ default=False,
844
+ help="Include pre-release and development versions. By default, "
845
+ "pip only finds stable versions.",
846
+ )
847
+
848
+ disable_pip_version_check: Callable[..., Option] = partial(
849
+ Option,
850
+ "--disable-pip-version-check",
851
+ dest="disable_pip_version_check",
852
+ action="store_true",
853
+ default=False,
854
+ help="Don't periodically check PyPI to determine whether a new version "
855
+ "of pip is available for download. Implied with --no-index.",
856
+ )
857
+
858
+
859
+ def _handle_merge_hash(
860
+ option: Option, opt_str: str, value: str, parser: OptionParser
861
+ ) -> None:
862
+ """Given a value spelled "algo:digest", append the digest to a list
863
+ pointed to in a dict by the algo name."""
864
+ if not parser.values.hashes:
865
+ parser.values.hashes = {}
866
+ try:
867
+ algo, digest = value.split(":", 1)
868
+ except ValueError:
869
+ parser.error(
870
+ "Arguments to {} must be a hash name " # noqa
871
+ "followed by a value, like --hash=sha256:"
872
+ "abcde...".format(opt_str)
873
+ )
874
+ if algo not in STRONG_HASHES:
875
+ parser.error(
876
+ "Allowed hash algorithms for {} are {}.".format( # noqa
877
+ opt_str, ", ".join(STRONG_HASHES)
878
+ )
879
+ )
880
+ parser.values.hashes.setdefault(algo, []).append(digest)
881
+
882
+
883
+ hash: Callable[..., Option] = partial(
884
+ Option,
885
+ "--hash",
886
+ # Hash values eventually end up in InstallRequirement.hashes due to
887
+ # __dict__ copying in process_line().
888
+ dest="hashes",
889
+ action="callback",
890
+ callback=_handle_merge_hash,
891
+ type="string",
892
+ help="Verify that the package's archive matches this "
893
+ "hash before installing. Example: --hash=sha256:abcdef...",
894
+ )
895
+
896
+
897
+ require_hashes: Callable[..., Option] = partial(
898
+ Option,
899
+ "--require-hashes",
900
+ dest="require_hashes",
901
+ action="store_true",
902
+ default=False,
903
+ help="Require a hash to check each requirement against, for "
904
+ "repeatable installs. This option is implied when any package in a "
905
+ "requirements file has a --hash option.",
906
+ )
907
+
908
+
909
+ list_path: Callable[..., Option] = partial(
910
+ PipOption,
911
+ "--path",
912
+ dest="path",
913
+ type="path",
914
+ action="append",
915
+ help="Restrict to the specified installation path for listing "
916
+ "packages (can be used multiple times).",
917
+ )
918
+
919
+
920
+ def check_list_path_option(options: Values) -> None:
921
+ if options.path and (options.user or options.local):
922
+ raise CommandError("Cannot combine '--path' with '--user' or '--local'")
923
+
924
+
925
+ list_exclude: Callable[..., Option] = partial(
926
+ PipOption,
927
+ "--exclude",
928
+ dest="excludes",
929
+ action="append",
930
+ metavar="package",
931
+ type="package_name",
932
+ help="Exclude specified package from the output",
933
+ )
934
+
935
+
936
+ no_python_version_warning: Callable[..., Option] = partial(
937
+ Option,
938
+ "--no-python-version-warning",
939
+ dest="no_python_version_warning",
940
+ action="store_true",
941
+ default=False,
942
+ help="Silence deprecation warnings for upcoming unsupported Pythons.",
943
+ )
944
+
945
+
946
+ use_new_feature: Callable[..., Option] = partial(
947
+ Option,
948
+ "--use-feature",
949
+ dest="features_enabled",
950
+ metavar="feature",
951
+ action="append",
952
+ default=[],
953
+ choices=["2020-resolver", "fast-deps", "in-tree-build"],
954
+ help="Enable new functionality, that may be backward incompatible.",
955
+ )
956
+
957
+ use_deprecated_feature: Callable[..., Option] = partial(
958
+ Option,
959
+ "--use-deprecated",
960
+ dest="deprecated_features_enabled",
961
+ metavar="feature",
962
+ action="append",
963
+ default=[],
964
+ choices=["legacy-resolver"],
965
+ help=("Enable deprecated functionality, that will be removed in the future."),
966
+ )
967
+
968
+
969
+ ##########
970
+ # groups #
971
+ ##########
972
+
973
+ general_group: Dict[str, Any] = {
974
+ "name": "General Options",
975
+ "options": [
976
+ help_,
977
+ isolated_mode,
978
+ require_virtualenv,
979
+ verbose,
980
+ version,
981
+ quiet,
982
+ log,
983
+ no_input,
984
+ proxy,
985
+ retries,
986
+ timeout,
987
+ exists_action,
988
+ trusted_host,
989
+ cert,
990
+ client_cert,
991
+ cache_dir,
992
+ no_cache,
993
+ disable_pip_version_check,
994
+ no_color,
995
+ no_python_version_warning,
996
+ use_new_feature,
997
+ use_deprecated_feature,
998
+ ],
999
+ }
1000
+
1001
+ index_group: Dict[str, Any] = {
1002
+ "name": "Package Index Options",
1003
+ "options": [
1004
+ index_url,
1005
+ extra_index_url,
1006
+ no_index,
1007
+ find_links,
1008
+ ],
1009
+ }
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/command_context.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import ExitStack, contextmanager
2
+ from typing import ContextManager, Iterator, TypeVar
3
+
4
+ _T = TypeVar("_T", covariant=True)
5
+
6
+
7
+ class CommandContextMixIn:
8
+ def __init__(self) -> None:
9
+ super().__init__()
10
+ self._in_main_context = False
11
+ self._main_context = ExitStack()
12
+
13
+ @contextmanager
14
+ def main_context(self) -> Iterator[None]:
15
+ assert not self._in_main_context
16
+
17
+ self._in_main_context = True
18
+ try:
19
+ with self._main_context:
20
+ yield
21
+ finally:
22
+ self._in_main_context = False
23
+
24
+ def enter_context(self, context_provider: ContextManager[_T]) -> _T:
25
+ assert self._in_main_context
26
+
27
+ return self._main_context.enter_context(context_provider)
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/main.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Primary application entrypoint.
2
+ """
3
+ import locale
4
+ import logging
5
+ import os
6
+ import sys
7
+ from typing import List, Optional
8
+
9
+ from pip._internal.cli.autocompletion import autocomplete
10
+ from pip._internal.cli.main_parser import parse_command
11
+ from pip._internal.commands import create_command
12
+ from pip._internal.exceptions import PipError
13
+ from pip._internal.utils import deprecation
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ # Do not import and use main() directly! Using it directly is actively
19
+ # discouraged by pip's maintainers. The name, location and behavior of
20
+ # this function is subject to change, so calling it directly is not
21
+ # portable across different pip versions.
22
+
23
+ # In addition, running pip in-process is unsupported and unsafe. This is
24
+ # elaborated in detail at
25
+ # https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
26
+ # That document also provides suggestions that should work for nearly
27
+ # all users that are considering importing and using main() directly.
28
+
29
+ # However, we know that certain users will still want to invoke pip
30
+ # in-process. If you understand and accept the implications of using pip
31
+ # in an unsupported manner, the best approach is to use runpy to avoid
32
+ # depending on the exact location of this entry point.
33
+
34
+ # The following example shows how to use runpy to invoke pip in that
35
+ # case:
36
+ #
37
+ # sys.argv = ["pip", your, args, here]
38
+ # runpy.run_module("pip", run_name="__main__")
39
+ #
40
+ # Note that this will exit the process after running, unlike a direct
41
+ # call to main. As it is not safe to do any processing after calling
42
+ # main, this should not be an issue in practice.
43
+
44
+
45
+ def main(args: Optional[List[str]] = None) -> int:
46
+ if args is None:
47
+ args = sys.argv[1:]
48
+
49
+ # Configure our deprecation warnings to be sent through loggers
50
+ deprecation.install_warning_logger()
51
+
52
+ autocomplete()
53
+
54
+ try:
55
+ cmd_name, cmd_args = parse_command(args)
56
+ except PipError as exc:
57
+ sys.stderr.write(f"ERROR: {exc}")
58
+ sys.stderr.write(os.linesep)
59
+ sys.exit(1)
60
+
61
+ # Needed for locale.getpreferredencoding(False) to work
62
+ # in pip._internal.utils.encoding.auto_decode
63
+ try:
64
+ locale.setlocale(locale.LC_ALL, "")
65
+ except locale.Error as e:
66
+ # setlocale can apparently crash if locale are uninitialized
67
+ logger.debug("Ignoring error %s when setting locale", e)
68
+ command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
69
+
70
+ return command.main(cmd_args)
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/main_parser.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A single place for constructing and exposing the main parser
2
+ """
3
+
4
+ import os
5
+ import sys
6
+ from typing import List, Tuple
7
+
8
+ from pip._internal.cli import cmdoptions
9
+ from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
10
+ from pip._internal.commands import commands_dict, get_similar_commands
11
+ from pip._internal.exceptions import CommandError
12
+ from pip._internal.utils.misc import get_pip_version, get_prog
13
+
14
+ __all__ = ["create_main_parser", "parse_command"]
15
+
16
+
17
+ def create_main_parser() -> ConfigOptionParser:
18
+ """Creates and returns the main parser for pip's CLI"""
19
+
20
+ parser = ConfigOptionParser(
21
+ usage="\n%prog <command> [options]",
22
+ add_help_option=False,
23
+ formatter=UpdatingDefaultsHelpFormatter(),
24
+ name="global",
25
+ prog=get_prog(),
26
+ )
27
+ parser.disable_interspersed_args()
28
+
29
+ parser.version = get_pip_version()
30
+
31
+ # add the general options
32
+ gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
33
+ parser.add_option_group(gen_opts)
34
+
35
+ # so the help formatter knows
36
+ parser.main = True # type: ignore
37
+
38
+ # create command listing for description
39
+ description = [""] + [
40
+ f"{name:27} {command_info.summary}"
41
+ for name, command_info in commands_dict.items()
42
+ ]
43
+ parser.description = "\n".join(description)
44
+
45
+ return parser
46
+
47
+
48
+ def parse_command(args: List[str]) -> Tuple[str, List[str]]:
49
+ parser = create_main_parser()
50
+
51
+ # Note: parser calls disable_interspersed_args(), so the result of this
52
+ # call is to split the initial args into the general options before the
53
+ # subcommand and everything else.
54
+ # For example:
55
+ # args: ['--timeout=5', 'install', '--user', 'INITools']
56
+ # general_options: ['--timeout==5']
57
+ # args_else: ['install', '--user', 'INITools']
58
+ general_options, args_else = parser.parse_args(args)
59
+
60
+ # --version
61
+ if general_options.version:
62
+ sys.stdout.write(parser.version)
63
+ sys.stdout.write(os.linesep)
64
+ sys.exit()
65
+
66
+ # pip || pip help -> print_help()
67
+ if not args_else or (args_else[0] == "help" and len(args_else) == 1):
68
+ parser.print_help()
69
+ sys.exit()
70
+
71
+ # the subcommand name
72
+ cmd_name = args_else[0]
73
+
74
+ if cmd_name not in commands_dict:
75
+ guess = get_similar_commands(cmd_name)
76
+
77
+ msg = [f'unknown command "{cmd_name}"']
78
+ if guess:
79
+ msg.append(f'maybe you meant "{guess}"')
80
+
81
+ raise CommandError(" - ".join(msg))
82
+
83
+ # all the args without the subcommand
84
+ cmd_args = args[:]
85
+ cmd_args.remove(cmd_name)
86
+
87
+ return cmd_name, cmd_args
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/parser.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base option parser setup"""
2
+
3
+ import logging
4
+ import optparse
5
+ import shutil
6
+ import sys
7
+ import textwrap
8
+ from contextlib import suppress
9
+ from typing import Any, Dict, Iterator, List, Tuple
10
+
11
+ from pip._internal.cli.status_codes import UNKNOWN_ERROR
12
+ from pip._internal.configuration import Configuration, ConfigurationError
13
+ from pip._internal.utils.misc import redact_auth_from_url, strtobool
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
19
+ """A prettier/less verbose help formatter for optparse."""
20
+
21
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
22
+ # help position must be aligned with __init__.parseopts.description
23
+ kwargs["max_help_position"] = 30
24
+ kwargs["indent_increment"] = 1
25
+ kwargs["width"] = shutil.get_terminal_size()[0] - 2
26
+ super().__init__(*args, **kwargs)
27
+
28
+ def format_option_strings(self, option: optparse.Option) -> str:
29
+ return self._format_option_strings(option)
30
+
31
+ def _format_option_strings(
32
+ self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", "
33
+ ) -> str:
34
+ """
35
+ Return a comma-separated list of option strings and metavars.
36
+
37
+ :param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
38
+ :param mvarfmt: metavar format string
39
+ :param optsep: separator
40
+ """
41
+ opts = []
42
+
43
+ if option._short_opts:
44
+ opts.append(option._short_opts[0])
45
+ if option._long_opts:
46
+ opts.append(option._long_opts[0])
47
+ if len(opts) > 1:
48
+ opts.insert(1, optsep)
49
+
50
+ if option.takes_value():
51
+ assert option.dest is not None
52
+ metavar = option.metavar or option.dest.lower()
53
+ opts.append(mvarfmt.format(metavar.lower()))
54
+
55
+ return "".join(opts)
56
+
57
+ def format_heading(self, heading: str) -> str:
58
+ if heading == "Options":
59
+ return ""
60
+ return heading + ":\n"
61
+
62
+ def format_usage(self, usage: str) -> str:
63
+ """
64
+ Ensure there is only one newline between usage and the first heading
65
+ if there is no description.
66
+ """
67
+ msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " "))
68
+ return msg
69
+
70
+ def format_description(self, description: str) -> str:
71
+ # leave full control over description to us
72
+ if description:
73
+ if hasattr(self.parser, "main"):
74
+ label = "Commands"
75
+ else:
76
+ label = "Description"
77
+ # some doc strings have initial newlines, some don't
78
+ description = description.lstrip("\n")
79
+ # some doc strings have final newlines and spaces, some don't
80
+ description = description.rstrip()
81
+ # dedent, then reindent
82
+ description = self.indent_lines(textwrap.dedent(description), " ")
83
+ description = f"{label}:\n{description}\n"
84
+ return description
85
+ else:
86
+ return ""
87
+
88
+ def format_epilog(self, epilog: str) -> str:
89
+ # leave full control over epilog to us
90
+ if epilog:
91
+ return epilog
92
+ else:
93
+ return ""
94
+
95
+ def indent_lines(self, text: str, indent: str) -> str:
96
+ new_lines = [indent + line for line in text.split("\n")]
97
+ return "\n".join(new_lines)
98
+
99
+
100
+ class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
101
+ """Custom help formatter for use in ConfigOptionParser.
102
+
103
+ This is updates the defaults before expanding them, allowing
104
+ them to show up correctly in the help listing.
105
+
106
+ Also redact auth from url type options
107
+ """
108
+
109
+ def expand_default(self, option: optparse.Option) -> str:
110
+ default_values = None
111
+ if self.parser is not None:
112
+ assert isinstance(self.parser, ConfigOptionParser)
113
+ self.parser._update_defaults(self.parser.defaults)
114
+ assert option.dest is not None
115
+ default_values = self.parser.defaults.get(option.dest)
116
+ help_text = super().expand_default(option)
117
+
118
+ if default_values and option.metavar == "URL":
119
+ if isinstance(default_values, str):
120
+ default_values = [default_values]
121
+
122
+ # If its not a list, we should abort and just return the help text
123
+ if not isinstance(default_values, list):
124
+ default_values = []
125
+
126
+ for val in default_values:
127
+ help_text = help_text.replace(val, redact_auth_from_url(val))
128
+
129
+ return help_text
130
+
131
+
132
+ class CustomOptionParser(optparse.OptionParser):
133
+ def insert_option_group(
134
+ self, idx: int, *args: Any, **kwargs: Any
135
+ ) -> optparse.OptionGroup:
136
+ """Insert an OptionGroup at a given position."""
137
+ group = self.add_option_group(*args, **kwargs)
138
+
139
+ self.option_groups.pop()
140
+ self.option_groups.insert(idx, group)
141
+
142
+ return group
143
+
144
+ @property
145
+ def option_list_all(self) -> List[optparse.Option]:
146
+ """Get a list of all options, including those in option groups."""
147
+ res = self.option_list[:]
148
+ for i in self.option_groups:
149
+ res.extend(i.option_list)
150
+
151
+ return res
152
+
153
+
154
+ class ConfigOptionParser(CustomOptionParser):
155
+ """Custom option parser which updates its defaults by checking the
156
+ configuration files and environmental variables"""
157
+
158
+ def __init__(
159
+ self,
160
+ *args: Any,
161
+ name: str,
162
+ isolated: bool = False,
163
+ **kwargs: Any,
164
+ ) -> None:
165
+ self.name = name
166
+ self.config = Configuration(isolated)
167
+
168
+ assert self.name
169
+ super().__init__(*args, **kwargs)
170
+
171
+ def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:
172
+ try:
173
+ return option.check_value(key, val)
174
+ except optparse.OptionValueError as exc:
175
+ print(f"An error occurred during configuration: {exc}")
176
+ sys.exit(3)
177
+
178
+ def _get_ordered_configuration_items(self) -> Iterator[Tuple[str, Any]]:
179
+ # Configuration gives keys in an unordered manner. Order them.
180
+ override_order = ["global", self.name, ":env:"]
181
+
182
+ # Pool the options into different groups
183
+ section_items: Dict[str, List[Tuple[str, Any]]] = {
184
+ name: [] for name in override_order
185
+ }
186
+ for section_key, val in self.config.items():
187
+ # ignore empty values
188
+ if not val:
189
+ logger.debug(
190
+ "Ignoring configuration key '%s' as it's value is empty.",
191
+ section_key,
192
+ )
193
+ continue
194
+
195
+ section, key = section_key.split(".", 1)
196
+ if section in override_order:
197
+ section_items[section].append((key, val))
198
+
199
+ # Yield each group in their override order
200
+ for section in override_order:
201
+ for key, val in section_items[section]:
202
+ yield key, val
203
+
204
+ def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
205
+ """Updates the given defaults with values from the config files and
206
+ the environ. Does a little special handling for certain types of
207
+ options (lists)."""
208
+
209
+ # Accumulate complex default state.
210
+ self.values = optparse.Values(self.defaults)
211
+ late_eval = set()
212
+ # Then set the options with those values
213
+ for key, val in self._get_ordered_configuration_items():
214
+ # '--' because configuration supports only long names
215
+ option = self.get_option("--" + key)
216
+
217
+ # Ignore options not present in this parser. E.g. non-globals put
218
+ # in [global] by users that want them to apply to all applicable
219
+ # commands.
220
+ if option is None:
221
+ continue
222
+
223
+ assert option.dest is not None
224
+
225
+ if option.action in ("store_true", "store_false"):
226
+ try:
227
+ val = strtobool(val)
228
+ except ValueError:
229
+ self.error(
230
+ "{} is not a valid value for {} option, " # noqa
231
+ "please specify a boolean value like yes/no, "
232
+ "true/false or 1/0 instead.".format(val, key)
233
+ )
234
+ elif option.action == "count":
235
+ with suppress(ValueError):
236
+ val = strtobool(val)
237
+ with suppress(ValueError):
238
+ val = int(val)
239
+ if not isinstance(val, int) or val < 0:
240
+ self.error(
241
+ "{} is not a valid value for {} option, " # noqa
242
+ "please instead specify either a non-negative integer "
243
+ "or a boolean value like yes/no or false/true "
244
+ "which is equivalent to 1/0.".format(val, key)
245
+ )
246
+ elif option.action == "append":
247
+ val = val.split()
248
+ val = [self.check_default(option, key, v) for v in val]
249
+ elif option.action == "callback":
250
+ assert option.callback is not None
251
+ late_eval.add(option.dest)
252
+ opt_str = option.get_opt_string()
253
+ val = option.convert_value(opt_str, val)
254
+ # From take_action
255
+ args = option.callback_args or ()
256
+ kwargs = option.callback_kwargs or {}
257
+ option.callback(option, opt_str, val, self, *args, **kwargs)
258
+ else:
259
+ val = self.check_default(option, key, val)
260
+
261
+ defaults[option.dest] = val
262
+
263
+ for key in late_eval:
264
+ defaults[key] = getattr(self.values, key)
265
+ self.values = None
266
+ return defaults
267
+
268
+ def get_default_values(self) -> optparse.Values:
269
+ """Overriding to make updating the defaults after instantiation of
270
+ the option parser possible, _update_defaults() does the dirty work."""
271
+ if not self.process_default_values:
272
+ # Old, pre-Optik 1.5 behaviour.
273
+ return optparse.Values(self.defaults)
274
+
275
+ # Load the configuration, or error out in case of an error
276
+ try:
277
+ self.config.load()
278
+ except ConfigurationError as err:
279
+ self.exit(UNKNOWN_ERROR, str(err))
280
+
281
+ defaults = self._update_defaults(self.defaults.copy()) # ours
282
+ for option in self._get_all_options():
283
+ assert option.dest is not None
284
+ default = defaults.get(option.dest)
285
+ if isinstance(default, str):
286
+ opt_str = option.get_opt_string()
287
+ defaults[option.dest] = option.check_value(opt_str, default)
288
+ return optparse.Values(defaults)
289
+
290
+ def error(self, msg: str) -> None:
291
+ self.print_usage(sys.stderr)
292
+ self.exit(UNKNOWN_ERROR, f"{msg}\n")
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/progress_bars.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import sys
3
+ from signal import SIGINT, default_int_handler, signal
4
+ from typing import Any
5
+
6
+ from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar
7
+ from pip._vendor.progress.spinner import Spinner
8
+
9
+ from pip._internal.utils.compat import WINDOWS
10
+ from pip._internal.utils.logging import get_indentation
11
+ from pip._internal.utils.misc import format_size
12
+
13
+ try:
14
+ from pip._vendor import colorama
15
+ # Lots of different errors can come from this, including SystemError and
16
+ # ImportError.
17
+ except Exception:
18
+ colorama = None
19
+
20
+
21
+ def _select_progress_class(preferred: Bar, fallback: Bar) -> Bar:
22
+ encoding = getattr(preferred.file, "encoding", None)
23
+
24
+ # If we don't know what encoding this file is in, then we'll just assume
25
+ # that it doesn't support unicode and use the ASCII bar.
26
+ if not encoding:
27
+ return fallback
28
+
29
+ # Collect all of the possible characters we want to use with the preferred
30
+ # bar.
31
+ characters = [
32
+ getattr(preferred, "empty_fill", ""),
33
+ getattr(preferred, "fill", ""),
34
+ ]
35
+ characters += list(getattr(preferred, "phases", []))
36
+
37
+ # Try to decode the characters we're using for the bar using the encoding
38
+ # of the given file, if this works then we'll assume that we can use the
39
+ # fancier bar and if not we'll fall back to the plaintext bar.
40
+ try:
41
+ "".join(characters).encode(encoding)
42
+ except UnicodeEncodeError:
43
+ return fallback
44
+ else:
45
+ return preferred
46
+
47
+
48
+ _BaseBar: Any = _select_progress_class(IncrementalBar, Bar)
49
+
50
+
51
+ class InterruptibleMixin:
52
+ """
53
+ Helper to ensure that self.finish() gets called on keyboard interrupt.
54
+
55
+ This allows downloads to be interrupted without leaving temporary state
56
+ (like hidden cursors) behind.
57
+
58
+ This class is similar to the progress library's existing SigIntMixin
59
+ helper, but as of version 1.2, that helper has the following problems:
60
+
61
+ 1. It calls sys.exit().
62
+ 2. It discards the existing SIGINT handler completely.
63
+ 3. It leaves its own handler in place even after an uninterrupted finish,
64
+ which will have unexpected delayed effects if the user triggers an
65
+ unrelated keyboard interrupt some time after a progress-displaying
66
+ download has already completed, for example.
67
+ """
68
+
69
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
70
+ """
71
+ Save the original SIGINT handler for later.
72
+ """
73
+ # https://github.com/python/mypy/issues/5887
74
+ super().__init__(*args, **kwargs) # type: ignore
75
+
76
+ self.original_handler = signal(SIGINT, self.handle_sigint)
77
+
78
+ # If signal() returns None, the previous handler was not installed from
79
+ # Python, and we cannot restore it. This probably should not happen,
80
+ # but if it does, we must restore something sensible instead, at least.
81
+ # The least bad option should be Python's default SIGINT handler, which
82
+ # just raises KeyboardInterrupt.
83
+ if self.original_handler is None:
84
+ self.original_handler = default_int_handler
85
+
86
+ def finish(self) -> None:
87
+ """
88
+ Restore the original SIGINT handler after finishing.
89
+
90
+ This should happen regardless of whether the progress display finishes
91
+ normally, or gets interrupted.
92
+ """
93
+ super().finish() # type: ignore
94
+ signal(SIGINT, self.original_handler)
95
+
96
+ def handle_sigint(self, signum, frame): # type: ignore
97
+ """
98
+ Call self.finish() before delegating to the original SIGINT handler.
99
+
100
+ This handler should only be in place while the progress display is
101
+ active.
102
+ """
103
+ self.finish()
104
+ self.original_handler(signum, frame)
105
+
106
+
107
+ class SilentBar(Bar):
108
+ def update(self) -> None:
109
+ pass
110
+
111
+
112
+ class BlueEmojiBar(IncrementalBar):
113
+
114
+ suffix = "%(percent)d%%"
115
+ bar_prefix = " "
116
+ bar_suffix = " "
117
+ phases = ("\U0001F539", "\U0001F537", "\U0001F535")
118
+
119
+
120
+ class DownloadProgressMixin:
121
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
122
+ # https://github.com/python/mypy/issues/5887
123
+ super().__init__(*args, **kwargs) # type: ignore
124
+ self.message: str = (" " * (get_indentation() + 2)) + self.message
125
+
126
+ @property
127
+ def downloaded(self) -> str:
128
+ return format_size(self.index) # type: ignore
129
+
130
+ @property
131
+ def download_speed(self) -> str:
132
+ # Avoid zero division errors...
133
+ if self.avg == 0.0: # type: ignore
134
+ return "..."
135
+ return format_size(1 / self.avg) + "/s" # type: ignore
136
+
137
+ @property
138
+ def pretty_eta(self) -> str:
139
+ if self.eta: # type: ignore
140
+ return f"eta {self.eta_td}" # type: ignore
141
+ return ""
142
+
143
+ def iter(self, it): # type: ignore
144
+ for x in it:
145
+ yield x
146
+ # B305 is incorrectly raised here
147
+ # https://github.com/PyCQA/flake8-bugbear/issues/59
148
+ self.next(len(x)) # noqa: B305
149
+ self.finish()
150
+
151
+
152
+ class WindowsMixin:
153
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
154
+ # The Windows terminal does not support the hide/show cursor ANSI codes
155
+ # even with colorama. So we'll ensure that hide_cursor is False on
156
+ # Windows.
157
+ # This call needs to go before the super() call, so that hide_cursor
158
+ # is set in time. The base progress bar class writes the "hide cursor"
159
+ # code to the terminal in its init, so if we don't set this soon
160
+ # enough, we get a "hide" with no corresponding "show"...
161
+ if WINDOWS and self.hide_cursor: # type: ignore
162
+ self.hide_cursor = False
163
+
164
+ # https://github.com/python/mypy/issues/5887
165
+ super().__init__(*args, **kwargs) # type: ignore
166
+
167
+ # Check if we are running on Windows and we have the colorama module,
168
+ # if we do then wrap our file with it.
169
+ if WINDOWS and colorama:
170
+ self.file = colorama.AnsiToWin32(self.file) # type: ignore
171
+ # The progress code expects to be able to call self.file.isatty()
172
+ # but the colorama.AnsiToWin32() object doesn't have that, so we'll
173
+ # add it.
174
+ self.file.isatty = lambda: self.file.wrapped.isatty()
175
+ # The progress code expects to be able to call self.file.flush()
176
+ # but the colorama.AnsiToWin32() object doesn't have that, so we'll
177
+ # add it.
178
+ self.file.flush = lambda: self.file.wrapped.flush()
179
+
180
+
181
+ class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin, DownloadProgressMixin):
182
+
183
+ file = sys.stdout
184
+ message = "%(percent)d%%"
185
+ suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s"
186
+
187
+
188
+ class DefaultDownloadProgressBar(BaseDownloadProgressBar, _BaseBar):
189
+ pass
190
+
191
+
192
+ class DownloadSilentBar(BaseDownloadProgressBar, SilentBar):
193
+ pass
194
+
195
+
196
+ class DownloadBar(BaseDownloadProgressBar, Bar):
197
+ pass
198
+
199
+
200
+ class DownloadFillingCirclesBar(BaseDownloadProgressBar, FillingCirclesBar):
201
+ pass
202
+
203
+
204
+ class DownloadBlueEmojiProgressBar(BaseDownloadProgressBar, BlueEmojiBar):
205
+ pass
206
+
207
+
208
+ class DownloadProgressSpinner(
209
+ WindowsMixin, InterruptibleMixin, DownloadProgressMixin, Spinner
210
+ ):
211
+
212
+ file = sys.stdout
213
+ suffix = "%(downloaded)s %(download_speed)s"
214
+
215
+ def next_phase(self) -> str:
216
+ if not hasattr(self, "_phaser"):
217
+ self._phaser = itertools.cycle(self.phases)
218
+ return next(self._phaser)
219
+
220
+ def update(self) -> None:
221
+ message = self.message % self
222
+ phase = self.next_phase()
223
+ suffix = self.suffix % self
224
+ line = "".join(
225
+ [
226
+ message,
227
+ " " if message else "",
228
+ phase,
229
+ " " if suffix else "",
230
+ suffix,
231
+ ]
232
+ )
233
+
234
+ self.writeln(line)
235
+
236
+
237
+ BAR_TYPES = {
238
+ "off": (DownloadSilentBar, DownloadSilentBar),
239
+ "on": (DefaultDownloadProgressBar, DownloadProgressSpinner),
240
+ "ascii": (DownloadBar, DownloadProgressSpinner),
241
+ "pretty": (DownloadFillingCirclesBar, DownloadProgressSpinner),
242
+ "emoji": (DownloadBlueEmojiProgressBar, DownloadProgressSpinner),
243
+ }
244
+
245
+
246
+ def DownloadProgressProvider(progress_bar, max=None): # type: ignore
247
+ if max is None or max == 0:
248
+ return BAR_TYPES[progress_bar][1]().iter
249
+ else:
250
+ return BAR_TYPES[progress_bar][0](max=max).iter
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/req_command.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains the Command base classes that depend on PipSession.
2
+
3
+ The classes in this module are in a separate module so the commands not
4
+ needing download / PackageFinder capability don't unnecessarily import the
5
+ PackageFinder machinery and all its vendored dependencies, etc.
6
+ """
7
+
8
+ import logging
9
+ import os
10
+ import sys
11
+ from functools import partial
12
+ from optparse import Values
13
+ from typing import Any, List, Optional, Tuple
14
+
15
+ from pip._internal.cache import WheelCache
16
+ from pip._internal.cli import cmdoptions
17
+ from pip._internal.cli.base_command import Command
18
+ from pip._internal.cli.command_context import CommandContextMixIn
19
+ from pip._internal.exceptions import CommandError, PreviousBuildDirError
20
+ from pip._internal.index.collector import LinkCollector
21
+ from pip._internal.index.package_finder import PackageFinder
22
+ from pip._internal.models.selection_prefs import SelectionPreferences
23
+ from pip._internal.models.target_python import TargetPython
24
+ from pip._internal.network.session import PipSession
25
+ from pip._internal.operations.prepare import RequirementPreparer
26
+ from pip._internal.req.constructors import (
27
+ install_req_from_editable,
28
+ install_req_from_line,
29
+ install_req_from_parsed_requirement,
30
+ install_req_from_req_string,
31
+ )
32
+ from pip._internal.req.req_file import parse_requirements
33
+ from pip._internal.req.req_install import InstallRequirement
34
+ from pip._internal.req.req_tracker import RequirementTracker
35
+ from pip._internal.resolution.base import BaseResolver
36
+ from pip._internal.self_outdated_check import pip_self_version_check
37
+ from pip._internal.utils.temp_dir import (
38
+ TempDirectory,
39
+ TempDirectoryTypeRegistry,
40
+ tempdir_kinds,
41
+ )
42
+ from pip._internal.utils.virtualenv import running_under_virtualenv
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+
47
+ class SessionCommandMixin(CommandContextMixIn):
48
+
49
+ """
50
+ A class mixin for command classes needing _build_session().
51
+ """
52
+
53
+ def __init__(self) -> None:
54
+ super().__init__()
55
+ self._session: Optional[PipSession] = None
56
+
57
+ @classmethod
58
+ def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
59
+ """Return a list of index urls from user-provided options."""
60
+ index_urls = []
61
+ if not getattr(options, "no_index", False):
62
+ url = getattr(options, "index_url", None)
63
+ if url:
64
+ index_urls.append(url)
65
+ urls = getattr(options, "extra_index_urls", None)
66
+ if urls:
67
+ index_urls.extend(urls)
68
+ # Return None rather than an empty list
69
+ return index_urls or None
70
+
71
+ def get_default_session(self, options: Values) -> PipSession:
72
+ """Get a default-managed session."""
73
+ if self._session is None:
74
+ self._session = self.enter_context(self._build_session(options))
75
+ # there's no type annotation on requests.Session, so it's
76
+ # automatically ContextManager[Any] and self._session becomes Any,
77
+ # then https://github.com/python/mypy/issues/7696 kicks in
78
+ assert self._session is not None
79
+ return self._session
80
+
81
+ def _build_session(
82
+ self,
83
+ options: Values,
84
+ retries: Optional[int] = None,
85
+ timeout: Optional[int] = None,
86
+ ) -> PipSession:
87
+ assert not options.cache_dir or os.path.isabs(options.cache_dir)
88
+ session = PipSession(
89
+ cache=(
90
+ os.path.join(options.cache_dir, "http") if options.cache_dir else None
91
+ ),
92
+ retries=retries if retries is not None else options.retries,
93
+ trusted_hosts=options.trusted_hosts,
94
+ index_urls=self._get_index_urls(options),
95
+ )
96
+
97
+ # Handle custom ca-bundles from the user
98
+ if options.cert:
99
+ session.verify = options.cert
100
+
101
+ # Handle SSL client certificate
102
+ if options.client_cert:
103
+ session.cert = options.client_cert
104
+
105
+ # Handle timeouts
106
+ if options.timeout or timeout:
107
+ session.timeout = timeout if timeout is not None else options.timeout
108
+
109
+ # Handle configured proxies
110
+ if options.proxy:
111
+ session.proxies = {
112
+ "http": options.proxy,
113
+ "https": options.proxy,
114
+ }
115
+
116
+ # Determine if we can prompt the user for authentication or not
117
+ session.auth.prompting = not options.no_input
118
+
119
+ return session
120
+
121
+
122
+ class IndexGroupCommand(Command, SessionCommandMixin):
123
+
124
+ """
125
+ Abstract base class for commands with the index_group options.
126
+
127
+ This also corresponds to the commands that permit the pip version check.
128
+ """
129
+
130
+ def handle_pip_version_check(self, options: Values) -> None:
131
+ """
132
+ Do the pip version check if not disabled.
133
+
134
+ This overrides the default behavior of not doing the check.
135
+ """
136
+ # Make sure the index_group options are present.
137
+ assert hasattr(options, "no_index")
138
+
139
+ if options.disable_pip_version_check or options.no_index:
140
+ return
141
+
142
+ # Otherwise, check if we're using the latest version of pip available.
143
+ session = self._build_session(
144
+ options, retries=0, timeout=min(5, options.timeout)
145
+ )
146
+ with session:
147
+ pip_self_version_check(session, options)
148
+
149
+
150
+ KEEPABLE_TEMPDIR_TYPES = [
151
+ tempdir_kinds.BUILD_ENV,
152
+ tempdir_kinds.EPHEM_WHEEL_CACHE,
153
+ tempdir_kinds.REQ_BUILD,
154
+ ]
155
+
156
+
157
+ def warn_if_run_as_root() -> None:
158
+ """Output a warning for sudo users on Unix.
159
+
160
+ In a virtual environment, sudo pip still writes to virtualenv.
161
+ On Windows, users may run pip as Administrator without issues.
162
+ This warning only applies to Unix root users outside of virtualenv.
163
+ """
164
+ if running_under_virtualenv():
165
+ return
166
+ if not hasattr(os, "getuid"):
167
+ return
168
+ # On Windows, there are no "system managed" Python packages. Installing as
169
+ # Administrator via pip is the correct way of updating system environments.
170
+ #
171
+ # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
172
+ # checks: https://mypy.readthedocs.io/en/stable/common_issues.html
173
+ if sys.platform == "win32" or sys.platform == "cygwin":
174
+ return
175
+ if sys.platform == "darwin" or sys.platform == "linux":
176
+ if os.getuid() != 0:
177
+ return
178
+ logger.warning(
179
+ "Running pip as the 'root' user can result in broken permissions and "
180
+ "conflicting behaviour with the system package manager. "
181
+ "It is recommended to use a virtual environment instead: "
182
+ "https://pip.pypa.io/warnings/venv"
183
+ )
184
+
185
+
186
+ def with_cleanup(func: Any) -> Any:
187
+ """Decorator for common logic related to managing temporary
188
+ directories.
189
+ """
190
+
191
+ def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
192
+ for t in KEEPABLE_TEMPDIR_TYPES:
193
+ registry.set_delete(t, False)
194
+
195
+ def wrapper(
196
+ self: RequirementCommand, options: Values, args: List[Any]
197
+ ) -> Optional[int]:
198
+ assert self.tempdir_registry is not None
199
+ if options.no_clean:
200
+ configure_tempdir_registry(self.tempdir_registry)
201
+
202
+ try:
203
+ return func(self, options, args)
204
+ except PreviousBuildDirError:
205
+ # This kind of conflict can occur when the user passes an explicit
206
+ # build directory with a pre-existing folder. In that case we do
207
+ # not want to accidentally remove it.
208
+ configure_tempdir_registry(self.tempdir_registry)
209
+ raise
210
+
211
+ return wrapper
212
+
213
+
214
+ class RequirementCommand(IndexGroupCommand):
215
+ def __init__(self, *args: Any, **kw: Any) -> None:
216
+ super().__init__(*args, **kw)
217
+
218
+ self.cmd_opts.add_option(cmdoptions.no_clean())
219
+
220
+ @staticmethod
221
+ def determine_resolver_variant(options: Values) -> str:
222
+ """Determines which resolver should be used, based on the given options."""
223
+ if "legacy-resolver" in options.deprecated_features_enabled:
224
+ return "legacy"
225
+
226
+ return "2020-resolver"
227
+
228
+ @classmethod
229
+ def make_requirement_preparer(
230
+ cls,
231
+ temp_build_dir: TempDirectory,
232
+ options: Values,
233
+ req_tracker: RequirementTracker,
234
+ session: PipSession,
235
+ finder: PackageFinder,
236
+ use_user_site: bool,
237
+ download_dir: Optional[str] = None,
238
+ ) -> RequirementPreparer:
239
+ """
240
+ Create a RequirementPreparer instance for the given parameters.
241
+ """
242
+ temp_build_dir_path = temp_build_dir.path
243
+ assert temp_build_dir_path is not None
244
+
245
+ resolver_variant = cls.determine_resolver_variant(options)
246
+ if resolver_variant == "2020-resolver":
247
+ lazy_wheel = "fast-deps" in options.features_enabled
248
+ if lazy_wheel:
249
+ logger.warning(
250
+ "pip is using lazily downloaded wheels using HTTP "
251
+ "range requests to obtain dependency information. "
252
+ "This experimental feature is enabled through "
253
+ "--use-feature=fast-deps and it is not ready for "
254
+ "production."
255
+ )
256
+ else:
257
+ lazy_wheel = False
258
+ if "fast-deps" in options.features_enabled:
259
+ logger.warning(
260
+ "fast-deps has no effect when used with the legacy resolver."
261
+ )
262
+
263
+ return RequirementPreparer(
264
+ build_dir=temp_build_dir_path,
265
+ src_dir=options.src_dir,
266
+ download_dir=download_dir,
267
+ build_isolation=options.build_isolation,
268
+ req_tracker=req_tracker,
269
+ session=session,
270
+ progress_bar=options.progress_bar,
271
+ finder=finder,
272
+ require_hashes=options.require_hashes,
273
+ use_user_site=use_user_site,
274
+ lazy_wheel=lazy_wheel,
275
+ in_tree_build="in-tree-build" in options.features_enabled,
276
+ )
277
+
278
+ @classmethod
279
+ def make_resolver(
280
+ cls,
281
+ preparer: RequirementPreparer,
282
+ finder: PackageFinder,
283
+ options: Values,
284
+ wheel_cache: Optional[WheelCache] = None,
285
+ use_user_site: bool = False,
286
+ ignore_installed: bool = True,
287
+ ignore_requires_python: bool = False,
288
+ force_reinstall: bool = False,
289
+ upgrade_strategy: str = "to-satisfy-only",
290
+ use_pep517: Optional[bool] = None,
291
+ py_version_info: Optional[Tuple[int, ...]] = None,
292
+ ) -> BaseResolver:
293
+ """
294
+ Create a Resolver instance for the given parameters.
295
+ """
296
+ make_install_req = partial(
297
+ install_req_from_req_string,
298
+ isolated=options.isolated_mode,
299
+ use_pep517=use_pep517,
300
+ )
301
+ resolver_variant = cls.determine_resolver_variant(options)
302
+ # The long import name and duplicated invocation is needed to convince
303
+ # Mypy into correctly typechecking. Otherwise it would complain the
304
+ # "Resolver" class being redefined.
305
+ if resolver_variant == "2020-resolver":
306
+ import pip._internal.resolution.resolvelib.resolver
307
+
308
+ return pip._internal.resolution.resolvelib.resolver.Resolver(
309
+ preparer=preparer,
310
+ finder=finder,
311
+ wheel_cache=wheel_cache,
312
+ make_install_req=make_install_req,
313
+ use_user_site=use_user_site,
314
+ ignore_dependencies=options.ignore_dependencies,
315
+ ignore_installed=ignore_installed,
316
+ ignore_requires_python=ignore_requires_python,
317
+ force_reinstall=force_reinstall,
318
+ upgrade_strategy=upgrade_strategy,
319
+ py_version_info=py_version_info,
320
+ )
321
+ import pip._internal.resolution.legacy.resolver
322
+
323
+ return pip._internal.resolution.legacy.resolver.Resolver(
324
+ preparer=preparer,
325
+ finder=finder,
326
+ wheel_cache=wheel_cache,
327
+ make_install_req=make_install_req,
328
+ use_user_site=use_user_site,
329
+ ignore_dependencies=options.ignore_dependencies,
330
+ ignore_installed=ignore_installed,
331
+ ignore_requires_python=ignore_requires_python,
332
+ force_reinstall=force_reinstall,
333
+ upgrade_strategy=upgrade_strategy,
334
+ py_version_info=py_version_info,
335
+ )
336
+
337
+ def get_requirements(
338
+ self,
339
+ args: List[str],
340
+ options: Values,
341
+ finder: PackageFinder,
342
+ session: PipSession,
343
+ ) -> List[InstallRequirement]:
344
+ """
345
+ Parse command-line arguments into the corresponding requirements.
346
+ """
347
+ requirements: List[InstallRequirement] = []
348
+ for filename in options.constraints:
349
+ for parsed_req in parse_requirements(
350
+ filename,
351
+ constraint=True,
352
+ finder=finder,
353
+ options=options,
354
+ session=session,
355
+ ):
356
+ req_to_add = install_req_from_parsed_requirement(
357
+ parsed_req,
358
+ isolated=options.isolated_mode,
359
+ user_supplied=False,
360
+ )
361
+ requirements.append(req_to_add)
362
+
363
+ for req in args:
364
+ req_to_add = install_req_from_line(
365
+ req,
366
+ None,
367
+ isolated=options.isolated_mode,
368
+ use_pep517=options.use_pep517,
369
+ user_supplied=True,
370
+ )
371
+ requirements.append(req_to_add)
372
+
373
+ for req in options.editables:
374
+ req_to_add = install_req_from_editable(
375
+ req,
376
+ user_supplied=True,
377
+ isolated=options.isolated_mode,
378
+ use_pep517=options.use_pep517,
379
+ )
380
+ requirements.append(req_to_add)
381
+
382
+ # NOTE: options.require_hashes may be set if --require-hashes is True
383
+ for filename in options.requirements:
384
+ for parsed_req in parse_requirements(
385
+ filename, finder=finder, options=options, session=session
386
+ ):
387
+ req_to_add = install_req_from_parsed_requirement(
388
+ parsed_req,
389
+ isolated=options.isolated_mode,
390
+ use_pep517=options.use_pep517,
391
+ user_supplied=True,
392
+ )
393
+ requirements.append(req_to_add)
394
+
395
+ # If any requirement has hash options, enable hash checking.
396
+ if any(req.has_hash_options for req in requirements):
397
+ options.require_hashes = True
398
+
399
+ if not (args or options.editables or options.requirements):
400
+ opts = {"name": self.name}
401
+ if options.find_links:
402
+ raise CommandError(
403
+ "You must give at least one requirement to {name} "
404
+ '(maybe you meant "pip {name} {links}"?)'.format(
405
+ **dict(opts, links=" ".join(options.find_links))
406
+ )
407
+ )
408
+ else:
409
+ raise CommandError(
410
+ "You must give at least one requirement to {name} "
411
+ '(see "pip help {name}")'.format(**opts)
412
+ )
413
+
414
+ return requirements
415
+
416
+ @staticmethod
417
+ def trace_basic_info(finder: PackageFinder) -> None:
418
+ """
419
+ Trace basic information about the provided objects.
420
+ """
421
+ # Display where finder is looking for packages
422
+ search_scope = finder.search_scope
423
+ locations = search_scope.get_formatted_locations()
424
+ if locations:
425
+ logger.info(locations)
426
+
427
+ def _build_package_finder(
428
+ self,
429
+ options: Values,
430
+ session: PipSession,
431
+ target_python: Optional[TargetPython] = None,
432
+ ignore_requires_python: Optional[bool] = None,
433
+ ) -> PackageFinder:
434
+ """
435
+ Create a package finder appropriate to this requirement command.
436
+
437
+ :param ignore_requires_python: Whether to ignore incompatible
438
+ "Requires-Python" values in links. Defaults to False.
439
+ """
440
+ link_collector = LinkCollector.create(session, options=options)
441
+ selection_prefs = SelectionPreferences(
442
+ allow_yanked=True,
443
+ format_control=options.format_control,
444
+ allow_all_prereleases=options.pre,
445
+ prefer_binary=options.prefer_binary,
446
+ ignore_requires_python=ignore_requires_python,
447
+ )
448
+
449
+ return PackageFinder.create(
450
+ link_collector=link_collector,
451
+ selection_prefs=selection_prefs,
452
+ target_python=target_python,
453
+ )
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/spinners.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import itertools
3
+ import logging
4
+ import sys
5
+ import time
6
+ from typing import IO, Iterator
7
+
8
+ from pip._vendor.progress import HIDE_CURSOR, SHOW_CURSOR
9
+
10
+ from pip._internal.utils.compat import WINDOWS
11
+ from pip._internal.utils.logging import get_indentation
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class SpinnerInterface:
17
+ def spin(self) -> None:
18
+ raise NotImplementedError()
19
+
20
+ def finish(self, final_status: str) -> None:
21
+ raise NotImplementedError()
22
+
23
+
24
+ class InteractiveSpinner(SpinnerInterface):
25
+ def __init__(
26
+ self,
27
+ message: str,
28
+ file: IO[str] = None,
29
+ spin_chars: str = "-\\|/",
30
+ # Empirically, 8 updates/second looks nice
31
+ min_update_interval_seconds: float = 0.125,
32
+ ):
33
+ self._message = message
34
+ if file is None:
35
+ file = sys.stdout
36
+ self._file = file
37
+ self._rate_limiter = RateLimiter(min_update_interval_seconds)
38
+ self._finished = False
39
+
40
+ self._spin_cycle = itertools.cycle(spin_chars)
41
+
42
+ self._file.write(" " * get_indentation() + self._message + " ... ")
43
+ self._width = 0
44
+
45
+ def _write(self, status: str) -> None:
46
+ assert not self._finished
47
+ # Erase what we wrote before by backspacing to the beginning, writing
48
+ # spaces to overwrite the old text, and then backspacing again
49
+ backup = "\b" * self._width
50
+ self._file.write(backup + " " * self._width + backup)
51
+ # Now we have a blank slate to add our status
52
+ self._file.write(status)
53
+ self._width = len(status)
54
+ self._file.flush()
55
+ self._rate_limiter.reset()
56
+
57
+ def spin(self) -> None:
58
+ if self._finished:
59
+ return
60
+ if not self._rate_limiter.ready():
61
+ return
62
+ self._write(next(self._spin_cycle))
63
+
64
+ def finish(self, final_status: str) -> None:
65
+ if self._finished:
66
+ return
67
+ self._write(final_status)
68
+ self._file.write("\n")
69
+ self._file.flush()
70
+ self._finished = True
71
+
72
+
73
+ # Used for dumb terminals, non-interactive installs (no tty), etc.
74
+ # We still print updates occasionally (once every 60 seconds by default) to
75
+ # act as a keep-alive for systems like Travis-CI that take lack-of-output as
76
+ # an indication that a task has frozen.
77
+ class NonInteractiveSpinner(SpinnerInterface):
78
+ def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:
79
+ self._message = message
80
+ self._finished = False
81
+ self._rate_limiter = RateLimiter(min_update_interval_seconds)
82
+ self._update("started")
83
+
84
+ def _update(self, status: str) -> None:
85
+ assert not self._finished
86
+ self._rate_limiter.reset()
87
+ logger.info("%s: %s", self._message, status)
88
+
89
+ def spin(self) -> None:
90
+ if self._finished:
91
+ return
92
+ if not self._rate_limiter.ready():
93
+ return
94
+ self._update("still running...")
95
+
96
+ def finish(self, final_status: str) -> None:
97
+ if self._finished:
98
+ return
99
+ self._update(f"finished with status '{final_status}'")
100
+ self._finished = True
101
+
102
+
103
+ class RateLimiter:
104
+ def __init__(self, min_update_interval_seconds: float) -> None:
105
+ self._min_update_interval_seconds = min_update_interval_seconds
106
+ self._last_update: float = 0
107
+
108
+ def ready(self) -> bool:
109
+ now = time.time()
110
+ delta = now - self._last_update
111
+ return delta >= self._min_update_interval_seconds
112
+
113
+ def reset(self) -> None:
114
+ self._last_update = time.time()
115
+
116
+
117
+ @contextlib.contextmanager
118
+ def open_spinner(message: str) -> Iterator[SpinnerInterface]:
119
+ # Interactive spinner goes directly to sys.stdout rather than being routed
120
+ # through the logging system, but it acts like it has level INFO,
121
+ # i.e. it's only displayed if we're at level INFO or better.
122
+ # Non-interactive spinner goes through the logging system, so it is always
123
+ # in sync with logging configuration.
124
+ if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
125
+ spinner: SpinnerInterface = InteractiveSpinner(message)
126
+ else:
127
+ spinner = NonInteractiveSpinner(message)
128
+ try:
129
+ with hidden_cursor(sys.stdout):
130
+ yield spinner
131
+ except KeyboardInterrupt:
132
+ spinner.finish("canceled")
133
+ raise
134
+ except Exception:
135
+ spinner.finish("error")
136
+ raise
137
+ else:
138
+ spinner.finish("done")
139
+
140
+
141
+ @contextlib.contextmanager
142
+ def hidden_cursor(file: IO[str]) -> Iterator[None]:
143
+ # The Windows terminal does not support the hide/show cursor ANSI codes,
144
+ # even via colorama. So don't even try.
145
+ if WINDOWS:
146
+ yield
147
+ # We don't want to clutter the output with control characters if we're
148
+ # writing to a file, or if the user is running with --quiet.
149
+ # See https://github.com/pypa/pip/issues/3418
150
+ elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
151
+ yield
152
+ else:
153
+ file.write(HIDE_CURSOR)
154
+ try:
155
+ yield
156
+ finally:
157
+ file.write(SHOW_CURSOR)
animated_drawings/lib/python3.9/site-packages/pip/_internal/cli/status_codes.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ SUCCESS = 0
2
+ ERROR = 1
3
+ UNKNOWN_ERROR = 2
4
+ VIRTUALENV_NOT_FOUND = 3
5
+ PREVIOUS_BUILD_DIR_ERROR = 4
6
+ NO_MATCHES_FOUND = 23
animated_drawings/lib/python3.9/site-packages/pip/_internal/commands/__init__.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Package containing all pip commands
3
+ """
4
+
5
+ import importlib
6
+ from collections import OrderedDict, namedtuple
7
+ from typing import Any, Dict, Optional
8
+
9
+ from pip._internal.cli.base_command import Command
10
+
11
+ CommandInfo = namedtuple('CommandInfo', 'module_path, class_name, summary')
12
+
13
+ # The ordering matters for help display.
14
+ # Also, even though the module path starts with the same
15
+ # "pip._internal.commands" prefix in each case, we include the full path
16
+ # because it makes testing easier (specifically when modifying commands_dict
17
+ # in test setup / teardown by adding info for a FakeCommand class defined
18
+ # in a test-related module).
19
+ # Finally, we need to pass an iterable of pairs here rather than a dict
20
+ # so that the ordering won't be lost when using Python 2.7.
21
+ commands_dict: Dict[str, CommandInfo] = OrderedDict([
22
+ ('install', CommandInfo(
23
+ 'pip._internal.commands.install', 'InstallCommand',
24
+ 'Install packages.',
25
+ )),
26
+ ('download', CommandInfo(
27
+ 'pip._internal.commands.download', 'DownloadCommand',
28
+ 'Download packages.',
29
+ )),
30
+ ('uninstall', CommandInfo(
31
+ 'pip._internal.commands.uninstall', 'UninstallCommand',
32
+ 'Uninstall packages.',
33
+ )),
34
+ ('freeze', CommandInfo(
35
+ 'pip._internal.commands.freeze', 'FreezeCommand',
36
+ 'Output installed packages in requirements format.',
37
+ )),
38
+ ('list', CommandInfo(
39
+ 'pip._internal.commands.list', 'ListCommand',
40
+ 'List installed packages.',
41
+ )),
42
+ ('show', CommandInfo(
43
+ 'pip._internal.commands.show', 'ShowCommand',
44
+ 'Show information about installed packages.',
45
+ )),
46
+ ('check', CommandInfo(
47
+ 'pip._internal.commands.check', 'CheckCommand',
48
+ 'Verify installed packages have compatible dependencies.',
49
+ )),
50
+ ('config', CommandInfo(
51
+ 'pip._internal.commands.configuration', 'ConfigurationCommand',
52
+ 'Manage local and global configuration.',
53
+ )),
54
+ ('search', CommandInfo(
55
+ 'pip._internal.commands.search', 'SearchCommand',
56
+ 'Search PyPI for packages.',
57
+ )),
58
+ ('cache', CommandInfo(
59
+ 'pip._internal.commands.cache', 'CacheCommand',
60
+ "Inspect and manage pip's wheel cache.",
61
+ )),
62
+ ('index', CommandInfo(
63
+ 'pip._internal.commands.index', 'IndexCommand',
64
+ "Inspect information available from package indexes.",
65
+ )),
66
+ ('wheel', CommandInfo(
67
+ 'pip._internal.commands.wheel', 'WheelCommand',
68
+ 'Build wheels from your requirements.',
69
+ )),
70
+ ('hash', CommandInfo(
71
+ 'pip._internal.commands.hash', 'HashCommand',
72
+ 'Compute hashes of package archives.',
73
+ )),
74
+ ('completion', CommandInfo(
75
+ 'pip._internal.commands.completion', 'CompletionCommand',
76
+ 'A helper command used for command completion.',
77
+ )),
78
+ ('debug', CommandInfo(
79
+ 'pip._internal.commands.debug', 'DebugCommand',
80
+ 'Show information useful for debugging.',
81
+ )),
82
+ ('help', CommandInfo(
83
+ 'pip._internal.commands.help', 'HelpCommand',
84
+ 'Show help for commands.',
85
+ )),
86
+ ])
87
+
88
+
89
+ def create_command(name: str, **kwargs: Any) -> Command:
90
+ """
91
+ Create an instance of the Command class with the given name.
92
+ """
93
+ module_path, class_name, summary = commands_dict[name]
94
+ module = importlib.import_module(module_path)
95
+ command_class = getattr(module, class_name)
96
+ command = command_class(name=name, summary=summary, **kwargs)
97
+
98
+ return command
99
+
100
+
101
+ def get_similar_commands(name: str) -> Optional[str]:
102
+ """Command name auto-correct."""
103
+ from difflib import get_close_matches
104
+
105
+ name = name.lower()
106
+
107
+ close_commands = get_close_matches(name, commands_dict.keys())
108
+
109
+ if close_commands:
110
+ return close_commands[0]
111
+ else:
112
+ return None
animated_drawings/lib/python3.9/site-packages/pip/_internal/commands/cache.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import textwrap
3
+ from optparse import Values
4
+ from typing import Any, List
5
+
6
+ import pip._internal.utils.filesystem as filesystem
7
+ from pip._internal.cli.base_command import Command
8
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
9
+ from pip._internal.exceptions import CommandError, PipError
10
+ from pip._internal.utils.logging import getLogger
11
+
12
+ logger = getLogger(__name__)
13
+
14
+
15
+ class CacheCommand(Command):
16
+ """
17
+ Inspect and manage pip's wheel cache.
18
+
19
+ Subcommands:
20
+
21
+ - dir: Show the cache directory.
22
+ - info: Show information about the cache.
23
+ - list: List filenames of packages stored in the cache.
24
+ - remove: Remove one or more package from the cache.
25
+ - purge: Remove all items from the cache.
26
+
27
+ ``<pattern>`` can be a glob expression or a package name.
28
+ """
29
+
30
+ ignore_require_venv = True
31
+ usage = """
32
+ %prog dir
33
+ %prog info
34
+ %prog list [<pattern>] [--format=[human, abspath]]
35
+ %prog remove <pattern>
36
+ %prog purge
37
+ """
38
+
39
+ def add_options(self) -> None:
40
+
41
+ self.cmd_opts.add_option(
42
+ '--format',
43
+ action='store',
44
+ dest='list_format',
45
+ default="human",
46
+ choices=('human', 'abspath'),
47
+ help="Select the output format among: human (default) or abspath"
48
+ )
49
+
50
+ self.parser.insert_option_group(0, self.cmd_opts)
51
+
52
+ def run(self, options: Values, args: List[Any]) -> int:
53
+ handlers = {
54
+ "dir": self.get_cache_dir,
55
+ "info": self.get_cache_info,
56
+ "list": self.list_cache_items,
57
+ "remove": self.remove_cache_items,
58
+ "purge": self.purge_cache,
59
+ }
60
+
61
+ if not options.cache_dir:
62
+ logger.error("pip cache commands can not "
63
+ "function since cache is disabled.")
64
+ return ERROR
65
+
66
+ # Determine action
67
+ if not args or args[0] not in handlers:
68
+ logger.error(
69
+ "Need an action (%s) to perform.",
70
+ ", ".join(sorted(handlers)),
71
+ )
72
+ return ERROR
73
+
74
+ action = args[0]
75
+
76
+ # Error handling happens here, not in the action-handlers.
77
+ try:
78
+ handlers[action](options, args[1:])
79
+ except PipError as e:
80
+ logger.error(e.args[0])
81
+ return ERROR
82
+
83
+ return SUCCESS
84
+
85
+ def get_cache_dir(self, options: Values, args: List[Any]) -> None:
86
+ if args:
87
+ raise CommandError('Too many arguments')
88
+
89
+ logger.info(options.cache_dir)
90
+
91
+ def get_cache_info(self, options: Values, args: List[Any]) -> None:
92
+ if args:
93
+ raise CommandError('Too many arguments')
94
+
95
+ num_http_files = len(self._find_http_files(options))
96
+ num_packages = len(self._find_wheels(options, '*'))
97
+
98
+ http_cache_location = self._cache_dir(options, 'http')
99
+ wheels_cache_location = self._cache_dir(options, 'wheels')
100
+ http_cache_size = filesystem.format_directory_size(http_cache_location)
101
+ wheels_cache_size = filesystem.format_directory_size(
102
+ wheels_cache_location
103
+ )
104
+
105
+ message = textwrap.dedent("""
106
+ Package index page cache location: {http_cache_location}
107
+ Package index page cache size: {http_cache_size}
108
+ Number of HTTP files: {num_http_files}
109
+ Wheels location: {wheels_cache_location}
110
+ Wheels size: {wheels_cache_size}
111
+ Number of wheels: {package_count}
112
+ """).format(
113
+ http_cache_location=http_cache_location,
114
+ http_cache_size=http_cache_size,
115
+ num_http_files=num_http_files,
116
+ wheels_cache_location=wheels_cache_location,
117
+ package_count=num_packages,
118
+ wheels_cache_size=wheels_cache_size,
119
+ ).strip()
120
+
121
+ logger.info(message)
122
+
123
+ def list_cache_items(self, options: Values, args: List[Any]) -> None:
124
+ if len(args) > 1:
125
+ raise CommandError('Too many arguments')
126
+
127
+ if args:
128
+ pattern = args[0]
129
+ else:
130
+ pattern = '*'
131
+
132
+ files = self._find_wheels(options, pattern)
133
+ if options.list_format == 'human':
134
+ self.format_for_human(files)
135
+ else:
136
+ self.format_for_abspath(files)
137
+
138
+ def format_for_human(self, files: List[str]) -> None:
139
+ if not files:
140
+ logger.info('Nothing cached.')
141
+ return
142
+
143
+ results = []
144
+ for filename in files:
145
+ wheel = os.path.basename(filename)
146
+ size = filesystem.format_file_size(filename)
147
+ results.append(f' - {wheel} ({size})')
148
+ logger.info('Cache contents:\n')
149
+ logger.info('\n'.join(sorted(results)))
150
+
151
+ def format_for_abspath(self, files: List[str]) -> None:
152
+ if not files:
153
+ return
154
+
155
+ results = []
156
+ for filename in files:
157
+ results.append(filename)
158
+
159
+ logger.info('\n'.join(sorted(results)))
160
+
161
+ def remove_cache_items(self, options: Values, args: List[Any]) -> None:
162
+ if len(args) > 1:
163
+ raise CommandError('Too many arguments')
164
+
165
+ if not args:
166
+ raise CommandError('Please provide a pattern')
167
+
168
+ files = self._find_wheels(options, args[0])
169
+
170
+ # Only fetch http files if no specific pattern given
171
+ if args[0] == '*':
172
+ files += self._find_http_files(options)
173
+
174
+ if not files:
175
+ raise CommandError('No matching packages')
176
+
177
+ for filename in files:
178
+ os.unlink(filename)
179
+ logger.verbose("Removed %s", filename)
180
+ logger.info("Files removed: %s", len(files))
181
+
182
+ def purge_cache(self, options: Values, args: List[Any]) -> None:
183
+ if args:
184
+ raise CommandError('Too many arguments')
185
+
186
+ return self.remove_cache_items(options, ['*'])
187
+
188
+ def _cache_dir(self, options: Values, subdir: str) -> str:
189
+ return os.path.join(options.cache_dir, subdir)
190
+
191
+ def _find_http_files(self, options: Values) -> List[str]:
192
+ http_dir = self._cache_dir(options, 'http')
193
+ return filesystem.find_files(http_dir, '*')
194
+
195
+ def _find_wheels(self, options: Values, pattern: str) -> List[str]:
196
+ wheel_dir = self._cache_dir(options, 'wheels')
197
+
198
+ # The wheel filename format, as specified in PEP 427, is:
199
+ # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
200
+ #
201
+ # Additionally, non-alphanumeric values in the distribution are
202
+ # normalized to underscores (_), meaning hyphens can never occur
203
+ # before `-{version}`.
204
+ #
205
+ # Given that information:
206
+ # - If the pattern we're given contains a hyphen (-), the user is
207
+ # providing at least the version. Thus, we can just append `*.whl`
208
+ # to match the rest of it.
209
+ # - If the pattern we're given doesn't contain a hyphen (-), the
210
+ # user is only providing the name. Thus, we append `-*.whl` to
211
+ # match the hyphen before the version, followed by anything else.
212
+ #
213
+ # PEP 427: https://www.python.org/dev/peps/pep-0427/
214
+ pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl")
215
+
216
+ return filesystem.find_files(wheel_dir, pattern)
animated_drawings/lib/python3.9/site-packages/pip/_internal/commands/check.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from optparse import Values
3
+ from typing import Any, List
4
+
5
+ from pip._internal.cli.base_command import Command
6
+ from pip._internal.cli.status_codes import ERROR, SUCCESS
7
+ from pip._internal.operations.check import (
8
+ check_package_set,
9
+ create_package_set_from_installed,
10
+ )
11
+ from pip._internal.utils.misc import write_output
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class CheckCommand(Command):
17
+ """Verify installed packages have compatible dependencies."""
18
+
19
+ usage = """
20
+ %prog [options]"""
21
+
22
+ def run(self, options: Values, args: List[Any]) -> int:
23
+
24
+ package_set, parsing_probs = create_package_set_from_installed()
25
+ missing, conflicting = check_package_set(package_set)
26
+
27
+ for project_name in missing:
28
+ version = package_set[project_name].version
29
+ for dependency in missing[project_name]:
30
+ write_output(
31
+ "%s %s requires %s, which is not installed.",
32
+ project_name, version, dependency[0],
33
+ )
34
+
35
+ for project_name in conflicting:
36
+ version = package_set[project_name].version
37
+ for dep_name, dep_version, req in conflicting[project_name]:
38
+ write_output(
39
+ "%s %s has requirement %s, but you have %s %s.",
40
+ project_name, version, req, dep_name, dep_version,
41
+ )
42
+
43
+ if missing or conflicting or parsing_probs:
44
+ return ERROR
45
+ else:
46
+ write_output("No broken requirements found.")
47
+ return SUCCESS