Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+6
- .venv/.gitignoreAdded+1
- .venv/.lockAdded
- .venv/CACHEDIR.TAGAdded+1
- .venv/bin/activateAdded+130
- .venv/bin/activate.batAdded+71
- .venv/bin/activate.cshAdded+76
- .venv/bin/activate.fishAdded+124
- .venv/bin/activate.nuAdded+117
- .venv/bin/activate.ps1Added+82
- .venv/bin/activate_this.pyAdded+59
- .venv/bin/deactivate.batAdded+39
- .venv/bin/huggingface-cliAdded+10
- .venv/bin/normalizerAdded+10
- .venv/bin/pydoc.batAdded+22
- .venv/bin/pythonAdded
- .venv/bin/python3Added
- .venv/bin/python3.13Added
- .venv/bin/tiny-agentsAdded+10
- .venv/bin/tqdmAdded+10
- .venv/lib/python3.13/site-packages/InquirerPy/base/__init__.pyAdded+15
- .venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/__init__.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/complex.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/control.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/list.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/simple.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/base/complex.pyAdded+294
- .venv/lib/python3.13/site-packages/InquirerPy/base/control.pyAdded+227
- .venv/lib/python3.13/site-packages/InquirerPy/base/list.pyAdded+238
- .venv/lib/python3.13/site-packages/InquirerPy/base/simple.pyAdded+378
- .venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/__init__.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/instruction.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/message.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/spinner.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/validation.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/containers/spinner.pyAdded+108
- .venv/lib/python3.13/site-packages/InquirerPy/containers/validation.pyAdded+60
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/__init__.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/checkbox.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/confirm.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/expand.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/filepath.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/fuzzy.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/input.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/list.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/number.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/rawlist.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/secret.cpython-313.pycAdded
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/checkbox.pyAdded+244
- .venv/lib/python3.13/site-packages/InquirerPy/prompts/filepath.pyAdded+192
56 unmodified lines57585956 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text56 unmodified lines57585960616263646556 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/yaml/_yaml.cpython-313-darwin.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/charset_normalizer/md.cpython-313-darwin.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/charset_normalizer/md__mypyc.cpython-313-darwin.so filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/huggingface_hub/__pycache__/hf_api.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/prompt_toolkit/layout/__pycache__/containers.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
1*1Signature: 8a477f597d28d172789f06886806bc55123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file must be used with "source bin/activate" *from bash*# you cannot run it directly
if ! [ -z "${SCRIPT_PATH+_}" ] ; then _OLD_SCRIPT_PATH="$SCRIPT_PATH"fi
# Get script path (only used if environment is relocatable).if [ -n "${BASH_VERSION:+x}" ] ; then SCRIPT_PATH="${BASH_SOURCE[0]}" if [ "$SCRIPT_PATH" = "$0" ]; then # Only bash has a reasonably robust check for source'dness. echo "You must source this script: \$ source $0" >&2 exit 33 fielif [ -n "${ZSH_VERSION:+x}" ] ; then SCRIPT_PATH="${(%):-%x}"elif [ -n "${KSH_VERSION:+x}" ] ; then SCRIPT_PATH="${.sh.file}"fi
deactivate () { unset -f pydoc >/dev/null 2>&1 || true
# reset old environment variables # ! [ -z ${VAR+_} ] returns true if VAR is declared at all if ! [ -z "${_OLD_VIRTUAL_PATH:+_}" ] ; then PATH="$_OLD_VIRTUAL_PATH" export PATH unset _OLD_VIRTUAL_PATH fi if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME" export PYTHONHOME unset _OLD_VIRTUAL_PYTHONHOME fi
# The hash command must be called to get it to forget past # commands. Without forgetting past commands the $PATH changes # we made may not be respected hash -r 2>/dev/null
if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then PS1="$_OLD_VIRTUAL_PS1" export PS1 unset _OLD_VIRTUAL_PS1 fi
unset VIRTUAL_ENV unset VIRTUAL_ENV_PROMPT if [ ! "${1-}" = "nondestructive" ] ; then # Self destruct! unset -f deactivate fi}
# unset irrelevant variablesdeactivate nondestructive
VIRTUAL_ENV='/Users/patrickramos/Documents/npb_data_app_data/.venv'if ([ "$OSTYPE" = "cygwin" ] || [ "$OSTYPE" = "msys" ]) && $(command -v cygpath &> /dev/null) ; then VIRTUAL_ENV=$(cygpath -u "$VIRTUAL_ENV")fiexport VIRTUAL_ENV
# Unset the `SCRIPT_PATH` variable, now that the `VIRTUAL_ENV` variable# has been set. This is important for relocatable environments.if ! [ -z "${_OLD_SCRIPT_PATH+_}" ] ; then SCRIPT_PATH="$_OLD_SCRIPT_PATH" export SCRIPT_PATH unset _OLD_SCRIPT_PATHelse unset SCRIPT_PATHfi
_OLD_VIRTUAL_PATH="$PATH"PATH="$VIRTUAL_ENV/bin:$PATH"export PATH
if [ "xnpb_data_app_data" != x ] ; then VIRTUAL_ENV_PROMPT="(npb_data_app_data) "else VIRTUAL_ENV_PROMPT="($(basename "$VIRTUAL_ENV")) "fiexport VIRTUAL_ENV_PROMPT
# unset PYTHONHOME if setif ! [ -z "${PYTHONHOME+_}" ] ; then _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME" unset PYTHONHOMEfi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then _OLD_VIRTUAL_PS1="${PS1-}" PS1="${VIRTUAL_ENV_PROMPT}${PS1-}" export PS1fi
# Make sure to unalias pydoc if it's already therealias pydoc 2>/dev/null >/dev/null && unalias pydoc || true
pydoc () { python -m pydoc "$@"}
# The hash command must be called to get it to forget past# commands. Without forgetting past commands the $PATH changes# we made may not be respectedhash -r 2>/dev/null1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071@REM Copyright (c) 2020-202x The virtualenv developers
@REM
@REM Permission is hereby granted, free of charge, to any person obtaining
@REM a copy of this software and associated documentation files (the
@REM "Software"), to deal in the Software without restriction, including
@REM without limitation the rights to use, copy, modify, merge, publish,
@REM distribute, sublicense, and/or sell copies of the Software, and to
@REM permit persons to whom the Software is furnished to do so, subject to
@REM the following conditions:
@REM
@REM The above copyright notice and this permission notice shall be
@REM included in all copies or substantial portions of the Software.
@REM
@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@REM This file is UTF-8 encoded, so we need to update the current code page while executing it
@for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a
@if defined _OLD_CODEPAGE (
@"%SystemRoot%\System32\chcp.com" 65001 > nul
)
@for %%i in ("/Users/patrickramos/Documents/npb_data_app_data/.venv") do @set "VIRTUAL_ENV=%%~fi"
@set "VIRTUAL_ENV_PROMPT=npb_data_app_data"
@if NOT DEFINED VIRTUAL_ENV_PROMPT (
@for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd"
)
@if defined _OLD_VIRTUAL_PROMPT (
@set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
) else (
@if not defined PROMPT (
@set "PROMPT=$P$G"
)
@if not defined VIRTUAL_ENV_DISABLE_PROMPT (
@set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
)
)
@if not defined VIRTUAL_ENV_DISABLE_PROMPT (
@set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%"
)
@REM Don't use () to avoid problems with them in %PATH%
@if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
@set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
:ENDIFVHOME
@set PYTHONHOME=
@REM if defined _OLD_VIRTUAL_PATH (
@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1
@set "PATH=%_OLD_VIRTUAL_PATH%"
:ENDIFVPATH1
@REM ) else (
@if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2
@set "_OLD_VIRTUAL_PATH=%PATH%"
:ENDIFVPATH2
@set "PATH=%VIRTUAL_ENV%\bin;%PATH%"
:END
@if defined _OLD_CODEPAGE (
@"%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
@set _OLD_CODEPAGE=
)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file must be used with "source bin/activate.csh" *from csh*.# You cannot run it directly.# Created by Davide Di Blasi <davidedb@gmail.com>.
set newline='\'
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH:q" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT:q" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc'
# Unset irrelevant variables.deactivate nondestructive
setenv VIRTUAL_ENV '/Users/patrickramos/Documents/npb_data_app_data/.venv'
set _OLD_VIRTUAL_PATH="$PATH:q"setenv PATH "$VIRTUAL_ENV:q/bin:$PATH:q"
if ('npb_data_app_data' != "") then setenv VIRTUAL_ENV_PROMPT 'npb_data_app_data'else setenv VIRTUAL_ENV_PROMPT "$VIRTUAL_ENV:t:q"endif
if ( $?VIRTUAL_ENV_DISABLE_PROMPT ) then if ( $VIRTUAL_ENV_DISABLE_PROMPT == "" ) then set do_prompt = "1" else set do_prompt = "0" endifelse set do_prompt = "1"endif
if ( $do_prompt == "1" ) then # Could be in a non-interactive environment, # in which case, $prompt is undefined and we wouldn't # care about the prompt anyway. if ( $?prompt ) then set _OLD_VIRTUAL_PROMPT="$prompt:q" if ( "$prompt:q" =~ *"$newline:q"* ) then : else set prompt = '('"$VIRTUAL_ENV_PROMPT:q"') '"$prompt:q" endif endifendif
unset env_nameunset do_prompt
alias pydoc python -m pydoc
rehash123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.# Do not run it directly.
function _bashify_path -d "Converts a fish path to something bash can recognize" set fishy_path $argv set bashy_path $fishy_path[1] for path_part in $fishy_path[2..-1] set bashy_path "$bashy_path:$path_part" end echo $bashy_pathend
function _fishify_path -d "Converts a bash path to something fish can recognize" echo $argv | tr ':' '\n'end
function deactivate -d 'Exit virtualenv mode and return to the normal environment.' # reset old environment variables if test -n "$_OLD_VIRTUAL_PATH" # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling if test (echo $FISH_VERSION | head -c 1) -lt 3 set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH") else set -gx PATH $_OLD_VIRTUAL_PATH end set -e _OLD_VIRTUAL_PATH end
if test -n "$_OLD_VIRTUAL_PYTHONHOME" set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME" set -e _OLD_VIRTUAL_PYTHONHOME end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE" and functions -q _old_fish_prompt # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`. set -l fish_function_path
# Erase virtualenv's `fish_prompt` and restore the original. functions -e fish_prompt functions -c _old_fish_prompt fish_prompt functions -e _old_fish_prompt set -e _OLD_FISH_PROMPT_OVERRIDE end
set -e VIRTUAL_ENV set -e VIRTUAL_ENV_PROMPT
if test "$argv[1]" != 'nondestructive' # Self-destruct! functions -e pydoc functions -e deactivate functions -e _bashify_path functions -e _fishify_path endend
# Unset irrelevant variables.deactivate nondestructive
set -gx VIRTUAL_ENV '/Users/patrickramos/Documents/npb_data_app_data/.venv'
# https://github.com/fish-shell/fish-shell/issues/436 altered PATH handlingif test (echo $FISH_VERSION | head -c 1) -lt 3 set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH)else set -gx _OLD_VIRTUAL_PATH $PATHendset -gx PATH "$VIRTUAL_ENV"'/bin' $PATH
# Prompt override provided?# If not, just use the environment name.if test -n 'npb_data_app_data' set -gx VIRTUAL_ENV_PROMPT 'npb_data_app_data'else set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV")end
# Unset `$PYTHONHOME` if set.if set -q PYTHONHOME set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME set -e PYTHONHOMEend
function pydoc python -m pydoc $argvend
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" # Copy the current `fish_prompt` function as `_old_fish_prompt`. functions -c fish_prompt _old_fish_prompt
function fish_prompt # Run the user's prompt first; it might depend on (pipe)status. set -l prompt (_old_fish_prompt)
printf '(%s) ' $VIRTUAL_ENV_PROMPT
string join -- \n $prompt # handle multi-line prompts end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"end123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# virtualenv activation module# Activate with `overlay use activate.nu`# Deactivate with `deactivate`, as usual## To customize the overlay name, you can call `overlay use activate.nu as foo`,# but then simply `deactivate` won't work because it is just an alias to hide# the "activate" overlay. You'd need to call `overlay hide foo` manually.
export-env { def is-string [x] { ($x | describe) == 'string' }
def has-env [...names] { $names | each {|n| $n in $env } | all {|i| $i == true} }
# Emulates a `test -z`, but better as it handles e.g 'false' def is-env-true [name: string] { if (has-env $name) { # Try to parse 'true', '0', '1', and fail if not convertible let parsed = (do -i { $env | get $name | into bool }) if ($parsed | describe) == 'bool' { $parsed } else { not ($env | get -i $name | is-empty) } } else { false } }
let virtual_env = '/Users/patrickramos/Documents/npb_data_app_data/.venv' let bin = 'bin'
let is_windows = ($nu.os-info.family) == 'windows' let path_name = (if (has-env 'Path') { 'Path' } else { 'PATH' } )
let venv_path = ([$virtual_env $bin] | path join) let new_path = ($env | get $path_name | prepend $venv_path)
# If there is no default prompt, then use the env name instead let virtual_env_prompt = (if ('npb_data_app_data' | is-empty) { ($virtual_env | path basename) } else { 'npb_data_app_data' })
let new_env = { $path_name : $new_path VIRTUAL_ENV : $virtual_env VIRTUAL_ENV_PROMPT : $virtual_env_prompt }
let new_env = (if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') { $new_env } else { # Creating the new prompt for the session let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
# Back up the old prompt builder let old_prompt_command = (if (has-env 'PROMPT_COMMAND') { $env.PROMPT_COMMAND } else { '' })
let new_prompt = (if (has-env 'PROMPT_COMMAND') { if 'closure' in ($old_prompt_command | describe) { {|| $'($virtual_prefix)(do $old_prompt_command)' } } else { {|| $'($virtual_prefix)($old_prompt_command)' } } } else { {|| $'($virtual_prefix)' } })
$new_env | merge { PROMPT_COMMAND : $new_prompt VIRTUAL_PREFIX : $virtual_prefix } })
# Environment variables that will be loaded as the virtual env load-env $new_env}
export alias pydoc = python -m pydocexport alias deactivate = overlay hide activate12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
$script:THIS_PATH = $myinvocation.mycommand.path$script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent
function global:deactivate([switch] $NonDestructive) { if (Test-Path variable:_OLD_VIRTUAL_PATH) { $env:PATH = $variable:_OLD_VIRTUAL_PATH Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global }
if (Test-Path function:_old_virtual_prompt) { $function:prompt = $function:_old_virtual_prompt Remove-Item function:\_old_virtual_prompt }
if ($env:VIRTUAL_ENV) { Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue }
if ($env:VIRTUAL_ENV_PROMPT) { Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue }
if (!$NonDestructive) { # Self destruct! Remove-Item function:deactivate Remove-Item function:pydoc }}
function global:pydoc { python -m pydoc $args}
# unset irrelevant variablesdeactivate -nondestructive
$VIRTUAL_ENV = $BASE_DIR$env:VIRTUAL_ENV = $VIRTUAL_ENV
if ("npb_data_app_data" -ne "") { $env:VIRTUAL_ENV_PROMPT = "npb_data_app_data"}else { $env:VIRTUAL_ENV_PROMPT = $( Split-Path $env:VIRTUAL_ENV -Leaf )}
New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH
$env:PATH = "$env:VIRTUAL_ENV/bin:" + $env:PATHif (!$env:VIRTUAL_ENV_DISABLE_PROMPT) { function global:_old_virtual_prompt { "" } $function:_old_virtual_prompt = $function:prompt
function global:prompt { # Add the custom prefix to the existing prompt $previous_prompt_value = & $function:_old_virtual_prompt ("(" + $env:VIRTUAL_ENV_PROMPT + ") " + $previous_prompt_value) }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Activate virtualenv for current interpreter:
import runpyrunpy.run_path(this_file)
This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.""" # noqa: D415
from __future__ import annotations
import osimport siteimport sys
try: abs_file = os.path.abspath(__file__)except NameError as exc: msg = "You must use import runpy; runpy.run_path(this_file)" raise AssertionError(msg) from exc
bin_dir = os.path.dirname(abs_file)base = bin_dir[: -len("bin") - 1] # strip away the bin part from the __file__, plus the path separator
# prepend bin to PATH (this file is inside the bin directory)os.environ["PATH"] = os.pathsep.join([bin_dir, *os.environ.get("PATH", "").split(os.pathsep)])os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directoryos.environ["VIRTUAL_ENV_PROMPT"] = "npb_data_app_data" or os.path.basename(base) # noqa: SIM222
# add the virtual environments libraries to the host python import mechanismprev_length = len(sys.path)for lib in "../lib/python3.13/site-packages".split(os.pathsep): path = os.path.realpath(os.path.join(bin_dir, lib)) site.addsitedir(path)sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
sys.real_prefix = sys.prefixsys.prefix = base123456789101112131415161718192021222324252627282930313233343536373839@REM Copyright (c) 2020-202x The virtualenv developers
@REM
@REM Permission is hereby granted, free of charge, to any person obtaining
@REM a copy of this software and associated documentation files (the
@REM "Software"), to deal in the Software without restriction, including
@REM without limitation the rights to use, copy, modify, merge, publish,
@REM distribute, sublicense, and/or sell copies of the Software, and to
@REM permit persons to whom the Software is furnished to do so, subject to
@REM the following conditions:
@REM
@REM The above copyright notice and this permission notice shall be
@REM included in all copies or substantial portions of the Software.
@REM
@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@set VIRTUAL_ENV=
@set VIRTUAL_ENV_PROMPT=
@REM Don't use () to avoid problems with them in %PATH%
@if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT
@set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
@set _OLD_VIRTUAL_PROMPT=
:ENDIFVPROMPT
@if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
@set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
@set _OLD_VIRTUAL_PYTHONHOME=
:ENDIFVHOME
@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH
@set "PATH=%_OLD_VIRTUAL_PATH%"
@set _OLD_VIRTUAL_PATH=
:ENDIFVPATH12345678910#!/Users/patrickramos/Documents/npb_data_app_data/.venv/bin/python3# -*- coding: utf-8 -*-import sysfrom huggingface_hub.commands.huggingface_cli import mainif __name__ == "__main__": if sys.argv[0].endswith("-script.pyw"): sys.argv[0] = sys.argv[0][:-11] elif sys.argv[0].endswith(".exe"): sys.argv[0] = sys.argv[0][:-4] sys.exit(main())12345678910#!/Users/patrickramos/Documents/npb_data_app_data/.venv/bin/python3# -*- coding: utf-8 -*-import sysfrom charset_normalizer import cliif __name__ == "__main__": if sys.argv[0].endswith("-script.pyw"): sys.argv[0] = sys.argv[0][:-11] elif sys.argv[0].endswith(".exe"): sys.argv[0] = sys.argv[0][:-4] sys.exit(cli.cli_detect())12345678910111213141516171819202122@REM Copyright (c) 2020-202x The virtualenv developers
@REM
@REM Permission is hereby granted, free of charge, to any person obtaining
@REM a copy of this software and associated documentation files (the
@REM "Software"), to deal in the Software without restriction, including
@REM without limitation the rights to use, copy, modify, merge, publish,
@REM distribute, sublicense, and/or sell copies of the Software, and to
@REM permit persons to whom the Software is furnished to do so, subject to
@REM the following conditions:
@REM
@REM The above copyright notice and this permission notice shall be
@REM included in all copies or substantial portions of the Software.
@REM
@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
python.exe -m pydoc %*12345678910#!/Users/patrickramos/Documents/npb_data_app_data/.venv/bin/python3# -*- coding: utf-8 -*-import sysfrom huggingface_hub.inference._mcp.cli import appif __name__ == "__main__": if sys.argv[0].endswith("-script.pyw"): sys.argv[0] = sys.argv[0][:-11] elif sys.argv[0].endswith(".exe"): sys.argv[0] = sys.argv[0][:-4] sys.exit(app())12345678910#!/Users/patrickramos/Documents/npb_data_app_data/.venv/bin/python3# -*- coding: utf-8 -*-import sysfrom tqdm.cli import mainif __name__ == "__main__": if sys.argv[0].endswith("-script.pyw"): sys.argv[0] = sys.argv[0][:-11] elif sys.argv[0].endswith(".exe"): sys.argv[0] = sys.argv[0][:-4] sys.exit(main())123456789101112131415"""Module contains base class for prompts.
BaseSimplePrompt ← InputPrompt ← SecretPrompt ... ↑BaseComplexPrompt ↑BaseListPrompt ← FuzzyPrompt ↑ListPrompt ← ExpandPrompt ..."""
from .complex import BaseComplexPrompt, FakeDocumentfrom .control import Choice, InquirerPyUIListControlfrom .list import BaseListPromptfrom .simple import BaseSimplePrompt123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294"""Contains the interface class :class:`.BaseComplexPrompt` for more complex prompts and the mocked document class :class:`.FakeDocument`."""import shutilfrom dataclasses import dataclassfrom typing import Any, Callable, List, Optional, Tuple, Union
from prompt_toolkit.application import Applicationfrom prompt_toolkit.enums import EditingModefrom prompt_toolkit.filters.base import Condition, FilterOrBoolfrom prompt_toolkit.key_binding.key_bindings import KeyHandlerCallablefrom prompt_toolkit.keys import Keys
from InquirerPy.base.simple import BaseSimplePromptfrom InquirerPy.enum import INQUIRERPY_KEYBOARD_INTERRUPTfrom InquirerPy.utils import ( InquirerPySessionResult, InquirerPyStyle, InquirerPyValidate,)
@dataclassclass FakeDocument: """A fake `prompt_toolkit` document class.
Work around to allow non-buffer type :class:`~prompt_toolkit.layout.UIControl` to use :class:`~prompt_toolkit.validation.Validator`.
Args: text: Content to be validated. cursor_position: Fake cursor position. """
text: str cursor_position: int = 0
class BaseComplexPrompt(BaseSimplePrompt): """A base class to create a more complex prompt that will involve :class:`~prompt_toolkit.application.Application`.
Note: This class does not create :class:`~prompt_toolkit.layout.Layout` nor :class:`~prompt_toolkit.application.Application`, it only contains the necessary attributes and helper functions to be consumed.
Note: Use :class:`~InquirerPy.base.BaseListPrompt` to create a complex list prompt which involves multiple choices. It has more methods and helper function implemented.
See Also: :class:`~InquirerPy.base.BaseListPrompt` :class:`~InquirerPy.prompts.fuzzy.FuzzyPrompt` """
def __init__( self, message: Union[str, Callable[[InquirerPySessionResult], str]], style: Optional[InquirerPyStyle] = None, border: bool = False, vi_mode: bool = False, qmark: str = "?", amark: str = "?", instruction: str = "", long_instruction: str = "", transformer: Optional[Callable[[Any], Any]] = None, filter: Optional[Callable[[Any], Any]] = None, validate: Optional[InquirerPyValidate] = None, invalid_message: str = "Invalid input", wrap_lines: bool = True, raise_keyboard_interrupt: bool = True, mandatory: bool = True, mandatory_message: str = "Mandatory prompt", session_result: Optional[InquirerPySessionResult] = None, ) -> None: super().__init__( message=message, style=style, vi_mode=vi_mode, qmark=qmark, amark=amark, instruction=instruction, transformer=transformer, filter=filter, invalid_message=invalid_message, validate=validate, wrap_lines=wrap_lines, raise_keyboard_interrupt=raise_keyboard_interrupt, mandatory=mandatory, mandatory_message=mandatory_message, session_result=session_result, ) self._invalid_message = invalid_message self._rendered = False self._invalid = False self._loading = False self._application: Application self._long_instruction = long_instruction self._border = border self._height_offset = 2 # prev prompt result + current prompt question if self._border: self._height_offset += 2 if self._long_instruction: self._height_offset += 1 self._validation_window_bottom_offset = 0 if not self._long_instruction else 1 if self._wrap_lines: self._validation_window_bottom_offset += ( self.extra_long_instruction_line_count )
self._is_vim_edit = Condition(lambda: self._editing_mode == EditingMode.VI) self._is_invalid = Condition(lambda: self._invalid) self._is_displaying_long_instruction = Condition( lambda: self._long_instruction != "" )
def _redraw(self) -> None: """Redraw the application UI.""" self._application.invalidate()
def register_kb( self, *keys: Union[Keys, str], filter: FilterOrBool = True ) -> Callable[[KeyHandlerCallable], KeyHandlerCallable]: """Decorate keybinding registration function.
Ensure that the `invalid` state is cleared on next keybinding entered. """ kb_dec = super().register_kb(*keys, filter=filter)
def decorator(func: KeyHandlerCallable) -> KeyHandlerCallable: @kb_dec def executable(event): if self._invalid: self._invalid = False func(event)
return executable
return decorator
def _exception_handler(self, _, context) -> None: """Set exception handler for the event loop.
Skip the question and raise exception.
Args: loop: Current event loop. context: Exception context. """ self._status["answered"] = True self._status["result"] = INQUIRERPY_KEYBOARD_INTERRUPT self._status["skipped"] = True self._application.exit(exception=context["exception"])
def _after_render(self, app: Optional[Application]) -> None: """Run after the :class:`~prompt_toolkit.application.Application` is rendered/updated.
Since this function is fired up on each render, adding a check on `self._rendered` to process logics that should only run once.
Set event loop exception handler here, since its guaranteed that the event loop is running in `_after_render`. """ if not self._rendered: self._rendered = True
self._keybinding_factory() self._on_rendered(app)
def _set_error(self, message: str) -> None: """Set error message and set invalid state.
Args: message: Error message to display. """ self._invalid_message = message self._invalid = True
def _get_error_message(self) -> List[Tuple[str, str]]: """Obtain the error message dynamically.
Returns: FormattedText in list of tuple format. """ return [ ( "class:validation-toolbar", self._invalid_message, ) ]
def _on_rendered(self, _: Optional[Application]) -> None: """Run once after the UI is rendered. Acts like `ComponentDidMount`.""" pass
def _get_prompt_message(self) -> List[Tuple[str, str]]: """Get the prompt message to display.
Returns: Formatted text in list of tuple format. """ pre_answer = ( "class:instruction", " %s " % self.instruction if self.instruction else " ", ) post_answer = ("class:answer", " %s" % self.status["result"]) return super()._get_prompt_message(pre_answer, post_answer)
def _run(self) -> Any: """Run the application.""" return self.application.run()
async def _run_async(self) -> None: """Run the application asynchronously.""" return await self.application.run_async()
@property def application(self) -> Application: """Get the application.
:class:`.BaseComplexPrompt` requires :attr:`.BaseComplexPrompt._application` to be defined since this class doesn't implement :class:`~prompt_toolkit.layout.Layout` and :class:`~prompt_toolkit.application.Application`.
Raises: NotImplementedError: When `self._application` is not defined. """ if not self._application: raise NotImplementedError return self._application
@application.setter def application(self, value: Application) -> None: self._application = value
@property def height_offset(self) -> int: """int: Height offset to apply.""" if not self._wrap_lines: return self._height_offset return self.extra_line_count + self._height_offset
@property def total_message_length(self) -> int: """int: Total length of the message.""" total_message_length = 0 if self._qmark: total_message_length += len(self._qmark) total_message_length += 1 # Extra space if qmark is present total_message_length += len(str(self._message)) total_message_length += 1 # Extra space between message and instruction total_message_length += len(str(self._instruction)) if self._instruction: total_message_length += 1 # Extra space behind the instruction return total_message_length
@property def extra_message_line_count(self) -> int: """int: Get the extra lines created caused by line wrapping.
Minus 1 on the totoal message length as we only want the extra line. 24 // 24 will equal to 1 however we only want the value to be 1 when we have 25 char which will create an extra line. """ term_width, _ = shutil.get_terminal_size() return (self.total_message_length - 1) // term_width
@property def extra_long_instruction_line_count(self) -> int: """int: Get the extra lines created caused by line wrapping.
See Also: :attr:`.BaseComplexPrompt.extra_message_line_count` """ if self._long_instruction: term_width, _ = shutil.get_terminal_size() return (len(self._long_instruction) - 1) // term_width else: return 0
@property def extra_line_count(self) -> int: """Get the extra lines created caused by line wrapping.
Used mainly to calculate how much additional offset should be applied when getting the height.
Returns: Total extra lines created due to line wrapping. """ result = 0
# message wrap result += self.extra_message_line_count # long instruction wrap result += self.extra_long_instruction_line_count
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227"""Contains the content control class :class:`.InquirerPyUIListControl`."""from abc import abstractmethodfrom dataclasses import asdict, dataclassfrom typing import Any, Callable, Dict, List, Optional, Tuple, cast
from prompt_toolkit.layout.controls import FormattedTextControl
from InquirerPy.exceptions import InvalidArgument, RequiredKeyNotFoundfrom InquirerPy.separator import Separatorfrom InquirerPy.utils import InquirerPyListChoices, InquirerPySessionResult
__all__ = ["Choice", "InquirerPyUIListControl"]
@dataclassclass Choice: """Class to create choices for list type prompts.
A simple dataclass that can be used as an alternate to using :class:`dict` when working with choices.
Args: value: The value of the choice when user selects this choice. name: The value that should be presented to the user prior/after selection of the choice. This value is optional, if not provided, it will fallback to the string representation of `value`. enabled: Indicates if the choice should be pre-selected. This only has effects when the prompt has `multiselect` enabled. """
value: Any name: Optional[str] = None enabled: bool = False
def __post_init__(self): """Assign strinify value to name if not present.""" if self.name is None: self.name = str(self.value)
class InquirerPyUIListControl(FormattedTextControl): """A base class to create :class:`~prompt_toolkit.layout.UIControl` to display list type contents.
Args: choices(InquirerPyListChoices): List of choices to display as the content. Can also be a callable or async callable that returns a list of choices. default: Default value, this will affect the cursor position. multiselect: Indicate if the current prompt has `multiselect` enabled. session_result: Current session result. """
def __init__( self, choices: InquirerPyListChoices, default: Any = None, multiselect: bool = False, session_result: Optional[InquirerPySessionResult] = None, ) -> None: self._session_result = session_result or {} self._selected_choice_index: int = 0 self._choice_func = None self._multiselect = multiselect self._default = ( default if not isinstance(default, Callable) else cast(Callable, default)(self._session_result) ) self._raw_choices = ( choices if not isinstance(choices, Callable) else cast(Callable, choices)(self._session_result) ) self._choices = self._get_choices(self._raw_choices, self._default) self._safety_check() self._format_choices() super().__init__(self._get_formatted_choices)
def _get_choices(self, choices: List[Any], default: Any) -> List[Dict[str, Any]]: """Process the raw user input choices and format it into dictionary.
Args: choices: List of chices to display. default: Default value, this will affect the :attr:`.InquirerPyUIListControl.selected_choice_index`
Returns: List of choices.
Raises: RequiredKeyNotFound: When the provided choice is missing the `name` or `value` key. """ processed_choices: List[Dict[str, Any]] = [] try: for index, choice in enumerate(choices, start=0): if isinstance(choice, dict): if choice["value"] == default: self.selected_choice_index = index processed_choices.append( { "name": str(choice["name"]), "value": choice["value"], "enabled": choice.get("enabled", False) if self._multiselect else False, } ) elif isinstance(choice, Separator): if self.selected_choice_index == index: self.selected_choice_index = ( self.selected_choice_index + 1 ) % len(choices) processed_choices.append( {"name": str(choice), "value": choice, "enabled": False} ) elif isinstance(choice, Choice): dict_choice = asdict(choice) if dict_choice["value"] == default: self.selected_choice_index = index if not self._multiselect: dict_choice["enabled"] = False processed_choices.append(dict_choice) else: if choice == default: self.selected_choice_index = index processed_choices.append( {"name": str(choice), "value": choice, "enabled": False} ) except KeyError: raise RequiredKeyNotFound( "dictionary type of choice require a 'name' key and a 'value' key" ) return processed_choices
@property def selected_choice_index(self) -> int: """int: Current highlighted index.""" return self._selected_choice_index
@selected_choice_index.setter def selected_choice_index(self, value: int) -> None: self._selected_choice_index = value
@property def choices(self) -> List[Dict[str, Any]]: """List[Dict[str, Any]]: Get all processed choices.""" return self._choices
@choices.setter def choices(self, value: List[Dict[str, Any]]) -> None: self._choices = value
def _safety_check(self) -> None: """Validate processed choices.
Check if the choices are empty or if it only contains :class:`~InquirerPy.separator.Separator`. """ if not self.choices: raise InvalidArgument("argument choices cannot be empty") should_proceed: bool = False for choice in self.choices: if not isinstance(choice["value"], Separator): should_proceed = True break if not should_proceed: raise InvalidArgument( "argument choices should contain choices other than separator" )
def _get_formatted_choices(self) -> List[Tuple[str, str]]: """Get all choices in formatted text format.
Returns: List of choices in formatted text form. """ display_choices = []
for index, choice in enumerate(self.choices): if index == self.selected_choice_index: display_choices += self._get_hover_text(choice) else: display_choices += self._get_normal_text(choice) display_choices.append(("", "\n")) if display_choices: display_choices.pop() return display_choices
def _format_choices(self) -> None: """Perform post processing on the choices.
Additional customisation to the choices after :meth:`.InquirerPyUIListControl._get_choices` call. """ pass
@abstractmethod def _get_hover_text(self, choice) -> List[Tuple[str, str]]: """Generate the formatted text for hovered choice.
Returns: Formatted text in list of tuple format. """ pass
@abstractmethod def _get_normal_text(self, choice) -> List[Tuple[str, str]]: """Generate the formatted text for non-hovered choices.
Returns: Formatted text in list of tuple format. """ pass
@property def choice_count(self) -> int: """int: Total count of choices.""" return len(self.choices)
@property def selection(self) -> Dict[str, Any]: """Dict[str, Any]: Current selected choice.""" return self.choices[self.selected_choice_index]
@property def loading(self) -> bool: """bool: Indicate if the content control is loading.""" return self._loading
@loading.setter def loading(self, value: bool) -> None: self._loading = value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238"""Contains the base class :class:`.BaseListPrompt` which can be used to create a prompt involving choices."""from abc import abstractmethodfrom typing import Any, Callable, List, Optional
from prompt_toolkit.filters.base import Conditionfrom prompt_toolkit.keys import Keys
from InquirerPy.base.complex import BaseComplexPromptfrom InquirerPy.base.control import InquirerPyUIListControlfrom InquirerPy.separator import Separatorfrom InquirerPy.utils import ( InquirerPyKeybindings, InquirerPyMessage, InquirerPySessionResult, InquirerPyStyle, InquirerPyValidate,)
class BaseListPrompt(BaseComplexPrompt): """A base class to create a complex prompt involving choice selections (i.e. list) using `prompt_toolkit` Application.
Note: This class does not create :class:`~prompt_toolkit.layout.Layout` nor :class:`~prompt_toolkit.application.Application`, it only contains the necessary attributes and helper functions to be consumed.
See Also: :class:`~InquirerPy.prompts.list.ListPrompt` :class:`~InquirerPy.prompts.fuzzy.FuzzyPrompt` """
def __init__( self, message: InquirerPyMessage, style: Optional[InquirerPyStyle] = None, vi_mode: bool = False, qmark: str = "?", amark: str = "?", instruction: str = "", long_instruction: str = "", border: bool = False, transformer: Optional[Callable[[Any], Any]] = None, filter: Optional[Callable[[Any], Any]] = None, validate: Optional[InquirerPyValidate] = None, invalid_message: str = "Invalid input", multiselect: bool = False, keybindings: Optional[InquirerPyKeybindings] = None, cycle: bool = True, wrap_lines: bool = True, raise_keyboard_interrupt: bool = True, mandatory: bool = True, mandatory_message: str = "Mandatory prompt", session_result: Optional[InquirerPySessionResult] = None, ) -> None: super().__init__( message=message, style=style, border=border, vi_mode=vi_mode, qmark=qmark, amark=amark, transformer=transformer, filter=filter, invalid_message=invalid_message, validate=validate, instruction=instruction, long_instruction=long_instruction, wrap_lines=wrap_lines, raise_keyboard_interrupt=raise_keyboard_interrupt, mandatory=mandatory, mandatory_message=mandatory_message, session_result=session_result, )
self._content_control: InquirerPyUIListControl self._multiselect = multiselect self._is_multiselect = Condition(lambda: self._multiselect) self._cycle = cycle
if not keybindings: keybindings = {}
self.kb_maps = { "down": [ {"key": "down"}, {"key": "c-n", "filter": ~self._is_vim_edit}, {"key": "j", "filter": self._is_vim_edit}, ], "up": [ {"key": "up"}, {"key": "c-p", "filter": ~self._is_vim_edit}, {"key": "k", "filter": self._is_vim_edit}, ], "toggle": [ {"key": "space"}, ], "toggle-down": [ {"key": Keys.Tab}, ], "toggle-up": [ {"key": Keys.BackTab}, ], "toggle-all": [ {"key": "alt-r"}, {"key": "c-r"}, ], "toggle-all-true": [ {"key": "alt-a"}, {"key": "c-a"}, ], "toggle-all-false": [], **keybindings, }
self.kb_func_lookup = { "down": [{"func": self._handle_down}], "up": [{"func": self._handle_up}], "toggle": [{"func": self._handle_toggle_choice}], "toggle-down": [ {"func": self._handle_toggle_choice}, {"func": self._handle_down}, ], "toggle-up": [ {"func": self._handle_toggle_choice}, {"func": self._handle_up}, ], "toggle-all": [{"func": self._handle_toggle_all}], "toggle-all-true": [{"func": self._handle_toggle_all, "args": [True]}], "toggle-all-false": [{"func": self._handle_toggle_all, "args": [False]}], }
@property def content_control(self) -> InquirerPyUIListControl: """Get the content controller object.
Needs to be an instance of :class:`~InquirerPy.base.control.InquirerPyUIListControl`.
Each :class:`.BaseComplexPrompt` requires a `content_control` to display custom contents for the prompt.
Raises: NotImplementedError: When `self._content_control` is not found. """ if not self._content_control: raise NotImplementedError return self._content_control
@content_control.setter def content_control(self, value: InquirerPyUIListControl) -> None: self._content_control = value
@property def result_name(self) -> Any: """Get the result value that should be printed to the terminal.
In multiselect scenario, return result as a list. """ if self._multiselect: return [choice["name"] for choice in self.selected_choices] else: try: return self.content_control.selection["name"] except IndexError: return ""
@property def result_value(self) -> Any: """Get the result value that should return to the user.
In multiselect scenario, return result as a list. """ if self._multiselect: return [choice["value"] for choice in self.selected_choices] else: try: return self.content_control.selection["value"] except IndexError: return ""
@property def selected_choices(self) -> List[Any]: """List[Any]: Get all user selected choices."""
def filter_choice(choice): return not isinstance(choice, Separator) and choice["enabled"]
return list(filter(filter_choice, self.content_control.choices))
def _handle_down(self, _) -> bool: """Handle event when user attempts to move down.
Returns: Boolean indicating if the action hits the cap. """ if self._cycle: self.content_control.selected_choice_index = ( self.content_control.selected_choice_index + 1 ) % self.content_control.choice_count return False else: self.content_control.selected_choice_index += 1 if ( self.content_control.selected_choice_index >= self.content_control.choice_count ): self.content_control.selected_choice_index = ( self.content_control.choice_count - 1 ) return True return False
def _handle_up(self, _) -> bool: """Handle event when user attempts to move up.
Returns: Boolean indicating if the action hits the cap. """ if self._cycle: self.content_control.selected_choice_index = ( self.content_control.selected_choice_index - 1 ) % self.content_control.choice_count return False else: self.content_control.selected_choice_index -= 1 if self.content_control.selected_choice_index < 0: self.content_control.selected_choice_index = 0 return True return False
@abstractmethod def _handle_toggle_choice(self, event) -> None: """Handle event when user attempting to toggle the state of the chocie.""" pass
@abstractmethod def _handle_toggle_all(self, event, value: bool) -> None: """Handle event when user attempting to alter the state of all choices.""" pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378"""Contains the base class :class:`.BaseSimplePrompt`."""import osimport refrom abc import ABC, abstractmethodfrom typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union, cast,)
from prompt_toolkit.enums import EditingModefrom prompt_toolkit.filters.base import Condition, FilterOrBoolfrom prompt_toolkit.key_binding.key_bindings import KeyBindings, KeyHandlerCallablefrom prompt_toolkit.keys import Keysfrom prompt_toolkit.styles.style import Stylefrom prompt_toolkit.validation import Validator
from InquirerPy.enum import INQUIRERPY_KEYBOARD_INTERRUPTfrom InquirerPy.exceptions import RequiredKeyNotFoundfrom InquirerPy.utils import ( InquirerPyMessage, InquirerPySessionResult, InquirerPyStyle, InquirerPyValidate, get_style,)
if TYPE_CHECKING: from prompt_toolkit.key_binding.key_processor import KeyPressEvent
class BaseSimplePrompt(ABC): """The base class to create a simple terminal input prompt.
Note: No actual :class:`~prompt_toolkit.application.Application` is created by this class. This class only creates some common interface and attributes that can be easily used by `prompt_toolkit`.
To have a functional prompt, you'll at least have to implement the :meth:`.BaseSimplePrompt._run` and :meth:`.BaseSimplePrompt._get_prompt_message`.
See Also: :class:`~InquirerPy.prompts.input.InputPrompt` """
def __init__( self, message: InquirerPyMessage, style: Optional[InquirerPyStyle] = None, vi_mode: bool = False, qmark: str = "?", amark: str = "?", instruction: str = "", validate: Optional[InquirerPyValidate] = None, invalid_message: str = "Invalid input", transformer: Optional[Callable[[Any], Any]] = None, filter: Optional[Callable[[Any], Any]] = None, default: Any = "", wrap_lines: bool = True, raise_keyboard_interrupt: bool = True, mandatory: bool = True, mandatory_message: str = "Mandatory prompt", session_result: Optional[InquirerPySessionResult] = None, ) -> None: self._mandatory = mandatory self._mandatory_message = mandatory_message self._result = session_result or {} self._message = ( message if not isinstance(message, Callable) else cast(Callable, message)(self._result) ) self._instruction = instruction self._default = ( default if not isinstance(default, Callable) else default(self._result) ) self._style = Style.from_dict(style.dict if style else get_style().dict) self._qmark = qmark self._amark = amark self._status = {"answered": False, "result": None, "skipped": False} self._kb = KeyBindings() self._lexer = "class:input" self._transformer = transformer self._filter = filter self._wrap_lines = wrap_lines self._editing_mode = ( EditingMode.VI if vi_mode or bool(os.getenv("INQUIRERPY_VI_MODE", False)) else EditingMode.EMACS ) if isinstance(validate, Validator): self._validator = validate else: self._validator = Validator.from_callable( validate if validate else lambda _: True, invalid_message, move_cursor_to_end=True, ) self._raise_kbi = not os.getenv( "INQUIRERPY_NO_RAISE_KBI", not raise_keyboard_interrupt ) self._is_rasing_kbi = Condition(lambda: self._raise_kbi)
self._kb_maps = { "answer": [{"key": Keys.Enter}], "interrupt": [ {"key": "c-c", "filter": self._is_rasing_kbi}, {"key": "c-d", "filter": ~self._is_rasing_kbi}, ], "skip": [{"key": "c-z"}, {"key": "c-c", "filter": ~self._is_rasing_kbi}], } self._kb_func_lookup = { "answer": [{"func": self._handle_enter}], "interrupt": [{"func": self._handle_interrupt}], "skip": [{"func": self._handle_skip}], }
def _keybinding_factory(self): """Register all keybindings in `self._kb_maps`.
It's required to call this function at the end of prompt constructor if it inherits from :class:`~InquirerPy.base.simple.BaseSimplePrompt` or :class:`~InquirerPy.base.complex.BaseComplexPrompt`. """
def _factory(keys, filter, action): if action not in self.kb_func_lookup: raise RequiredKeyNotFound(f"keybinding action {action} not found") if not isinstance(keys, list): keys = [keys]
@self.register_kb(*keys, filter=filter) def _(event): for method in self.kb_func_lookup[action]: method["func"](event, *method.get("args", []))
for key, item in self.kb_maps.items(): if not isinstance(item, list): item = [item] for kb in item: _factory(kb["key"], kb.get("filter", Condition(lambda: True)), key)
@abstractmethod def _set_error(self, message: str) -> None: """Set the error message for the prompt.
Args: message: Error message to set. """ pass
def _handle_skip(self, event: Optional["KeyPressEvent"]) -> None: """Handle the event when attempting to skip a prompt.
Skip the prompt if the `_mandatory` field is False, otherwise show an error message that the prompt cannot be skipped. """ if not self._mandatory: self.status["answered"] = True self.status["skipped"] = True self.status["result"] = None if event: event.app.exit(result=None) else: self._set_error(message=self._mandatory_message)
def _handle_interrupt(self, event: Optional["KeyPressEvent"]) -> None: """Handle the event when a KeyboardInterrupt signal is sent.""" self.status["answered"] = True self.status["result"] = INQUIRERPY_KEYBOARD_INTERRUPT self.status["skipped"] = True if event: event.app.exit(result=INQUIRERPY_KEYBOARD_INTERRUPT)
@abstractmethod def _handle_enter(self, event: Optional["KeyPressEvent"]) -> None: """Handle the event when user attempt to answer the question.""" pass
@property def status(self) -> Dict[str, Any]: """Dict[str, Any]: Get current prompt status.
The status contains 3 keys: "answered" and "result". answered: If the current prompt is answered. result: The result of the user answer. skipped: If the prompt is skipped. """ return self._status
@status.setter def status(self, value) -> None: self._status = value
def register_kb( self, *keys: Union[Keys, str], filter: FilterOrBool = True, **kwargs ) -> Callable[[KeyHandlerCallable], KeyHandlerCallable]: """Keybinding registration decorator.
This decorator wraps around the :meth:`prompt_toolkit.key_binding.KeyBindings.add` with added feature to process `alt` realted keybindings.
By default, `prompt_toolkit` doesn't process `alt` related keybindings, it requires `alt-ANY` to `escape` + `ANY`.
Args: keys: The keys to bind that can trigger the function. filter: :class:`~prompt_toolkit.filter.Condition` to indicate if this keybinding should be active.
Returns: A decorator that should be applied to the function thats intended to be active when the keys are pressed.
Examples: >>> @self.register_kb("alt-j") ... def test(event): ... pass """ alt_pattern = re.compile(r"^alt-(.*)")
def decorator(func: KeyHandlerCallable) -> KeyHandlerCallable: formatted_keys = [] for key in keys: match = alt_pattern.match(key) if match: formatted_keys.append("escape") formatted_keys.append(match.group(1)) else: formatted_keys.append(key)
@self._kb.add(*formatted_keys, filter=filter, **kwargs) def executable(event) -> None: func(event)
return executable
return decorator
@abstractmethod def _get_prompt_message( self, pre_answer: Tuple[str, str], post_answer: Tuple[str, str] ) -> List[Tuple[str, str]]: """Get the question message in formatted text form to display in the prompt.
This function is mainly used to render the question message dynamically based on the current status (answered or not answered) of the prompt.
Note: The function requires implementation when inheriting :class:`.BaseSimplePrompt`. You should call `super()._get_prompt_message(pre_answer, post_answer)` in the implemented `_get_prompt_message`.
Args: pre_answer: The message to display before the question is answered. post_answer: The information to display after the question is answered.
Returns: Formatted text in list of tuple format. """ display_message = [] if self.status["skipped"]: display_message.append(("class:skipped", self._qmark)) display_message.append( ("class:skipped", "%s%s " % (" " if self._qmark else "", self._message)) ) elif self.status["answered"]: display_message.append(("class:answermark", self._amark)) display_message.append( ( "class:answered_question", "%s%s" % (" " if self._amark else "", self._message), ) ) display_message.append( post_answer if not self._transformer else ( "class:answer", " %s" % self._transformer(self.status["result"]), ) ) else: display_message.append(("class:questionmark", self._qmark)) display_message.append( ( "class:question", "%s%s" % (" " if self._qmark else "", self._message), ) ) display_message.append(pre_answer) return display_message
@abstractmethod def _run(self) -> Any: """Abstractmethod to enforce a run function is implemented.
All prompt instance requires a `_run` call to initialise and run an instance of `PromptSession` or `Application`. """ pass
@abstractmethod async def _run_async(self) -> Any: """Abstractmethod to enforce a run function is implemented.
All prompt instance requires a `_run_async` call to initialise and run an instance of `PromptSession` or `Application`. """ pass
def execute(self, raise_keyboard_interrupt: Optional[bool] = None) -> Any: """Run the prompt and get the result.
Args: raise_keyboard_interrupt: **Deprecated**. Set this parameter on the prompt initialisation instead.
Returns: Value of the user answer. Types varies depending on the prompt.
Raises: KeyboardInterrupt: When `ctrl-c` is pressed and `raise_keyboard_interrupt` is True. """ result = self._run() if raise_keyboard_interrupt is not None: self._raise_kbi = not os.getenv( "INQUIRERPY_NO_RAISE_KBI", not raise_keyboard_interrupt ) if result == INQUIRERPY_KEYBOARD_INTERRUPT: raise KeyboardInterrupt if not self._filter: return result return self._filter(result)
async def execute_async(self) -> None: """Run the prompt asynchronously and get the result.
Returns: Value of the user answer. Types varies depending on the prompt.
Raises: KeyboardInterrupt: When `ctrl-c` is pressed and `raise_keyboard_interrupt` is True. """ result = await self._run_async() if result == INQUIRERPY_KEYBOARD_INTERRUPT: raise KeyboardInterrupt if not self._filter: return result return self._filter(result)
@property def instruction(self) -> str: """str: Instruction to display next to question.""" return self._instruction
@property def kb_maps(self) -> Dict[str, Any]: """Dict[str, Any]: Keybinding mappings.""" return self._kb_maps
@kb_maps.setter def kb_maps(self, value: Dict[str, Any]) -> None: self._kb_maps = {**self._kb_maps, **value}
@property def kb_func_lookup(self) -> Dict[str, Any]: """Dict[str, Any]: Keybinding function lookup mappings..""" return self._kb_func_lookup
@kb_func_lookup.setter def kb_func_lookup(self, value: Dict[str, Any]) -> None: self._kb_func_lookup = {**self._kb_func_lookup, **value}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Module contains spinner related resources.
Note: The spinner is not a standalone spinner to run in the terminal but rather a `prompt_toolkit` :class:`~prompt_toolkit.layout.Window` that displays a spinner.
Use library such as `yaspin <https://github.com/pavdmyt/yaspin>`_ if you need a plain spinner."""import asynciofrom typing import TYPE_CHECKING, Callable, List, NamedTuple, Optional, Tuple, Union
from prompt_toolkit.filters.utils import to_filterfrom prompt_toolkit.layout.containers import ConditionalContainer, Windowfrom prompt_toolkit.layout.controls import FormattedTextControl
if TYPE_CHECKING: from prompt_toolkit.filters.base import Filter
__all__ = ["SPINNERS", "SpinnerWindow"]
class SPINNERS(NamedTuple): """Presets of spinner patterns.
See Also: https://github.com/pavdmyt/yaspin/blob/master/yaspin/data/spinners.json
This only contains some basic ones thats ready to use. For more patterns, checkout the URL above.
Examples: >>> from InquirerPy import inquirer >>> from InquirerPy.spinner import SPINNERS >>> inquirer.select(message="", choices=lambda _: [1, 2, 3], spinner_pattern=SPINNERS.dots) """
dots = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] dots2 = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"] line = ["-", "\\", "|", "/"] line2 = ["⠂", "-", "–", "—", "–", "-"] pipe = ["┤", "┘", "┴", "└", "├", "┌", "┬", "┐"] star = ["✶", "✸", "✹", "✺", "✹", "✷"] star2 = ["+", "x", "*"] flip = ["_", "_", "_", "-", "`", "`", "'", "´", "-", "_", "_", "_"] hamburger = ["☱", "☲", "☴"] grow_vertical = ["▁", "▃", "▄", "▅", "▆", "▇", "▆", "▅", "▄", "▃"] grow_horizontal = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "▊", "▋", "▌", "▍", "▎"] box_bounce = ["▖", "▘", "▝", "▗"] triangle = ["◢", "◣", "◤", "◥"] arc = ["◜", "◠", "◝", "◞", "◡", "◟"] circle = ["◡", "⊙", "◠"]
class SpinnerWindow(ConditionalContainer): """Conditional `prompt_toolkit` :class:`~prompt_toolkit.layout.Window` that displays a spinner.
Args: loading: A :class:`~prompt_toolkit.filters.Condition` to indicate if the spinner should be visible. redraw: A redraw function (i.e. :meth:`~prompt_toolkit.application.Application.invalidate`) to refresh the UI. pattern: List of pattern to display as the spinner. delay: Spinner refresh frequency. text: Loading text to display. """
def __init__( self, loading: "Filter", redraw: Callable[[], None], pattern: Optional[Union[List[str], SPINNERS]] = None, delay: float = 0.1, text: str = "", ) -> None: self._loading = to_filter(loading) self._spinning = False self._redraw = redraw self._pattern = pattern or SPINNERS.line self._char = self._pattern[0] self._delay = delay self._text = text or "Loading ..."
super().__init__( content=Window(content=FormattedTextControl(text=self._get_text)), filter=self._loading, )
def _get_text(self) -> List[Tuple[str, str]]: """Dynamically get the text for the :class:`~prompt_toolkit.layout.Window`.
Returns: Formatted text. """ return [ ("class:spinner_pattern", self._char), ("", " "), ("class:spinner_text", self._text), ]
async def start(self) -> None: """Start the spinner.""" if self._spinning: return self._spinning = True while self._loading(): for char in self._pattern: await asyncio.sleep(self._delay) self._char = char self._redraw() self._spinning = False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Module contains :class:`.ValidationWindow` which can be used to display error."""
from typing import Optional
from prompt_toolkit.filters.base import FilterOrBoolfrom prompt_toolkit.formatted_text.base import AnyFormattedTextfrom prompt_toolkit.layout.containers import ConditionalContainer, Float, Windowfrom prompt_toolkit.layout.controls import FormattedTextControl
class ValidationWindow(ConditionalContainer): """Conditional `prompt_toolkit` :class:`~prompt_toolkit.layout.Window` that displays error.
Args: invalid_message: Error message to display when error occured. filter: Condition to display the error window. """
def __init__( self, invalid_message: AnyFormattedText, filter: FilterOrBool, **kwargs ) -> None: super().__init__( Window( FormattedTextControl(invalid_message), dont_extend_height=True, **kwargs ), filter=filter, )
class ValidationFloat(Float): """:class:`~prompt_toolkit.layout.Float` wrapper around :class:`.ValidationWindow`.
Args: invalid_message: Error message to display when error occured. filter: Condition to display the error window. left: Distance to left. right: Distance to right. bottom: Distance to bottom. top: Distance to top. """
def __init__( self, invalid_message: AnyFormattedText, filter: FilterOrBool, left: Optional[int] = None, right: Optional[int] = None, bottom: Optional[int] = None, top: Optional[int] = None, **kwargs ) -> None: super().__init__( content=ValidationWindow( invalid_message=invalid_message, filter=filter, **kwargs ), left=left, right=right, bottom=bottom, top=top, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""Module contains the class to create a checkbox prompt."""from typing import Any, Callable, List, Optional, Tuple, Union
from prompt_toolkit.validation import ValidationError
from InquirerPy.base import FakeDocument, InquirerPyUIListControlfrom InquirerPy.enum import ( INQUIRERPY_EMPTY_CIRCLE_SEQUENCE, INQUIRERPY_FILL_CIRCLE_SEQUENCE, INQUIRERPY_POINTER_SEQUENCE,)from InquirerPy.prompts.list import ListPromptfrom InquirerPy.separator import Separatorfrom InquirerPy.utils import ( InquirerPyKeybindings, InquirerPyListChoices, InquirerPyMessage, InquirerPySessionResult, InquirerPyStyle, InquirerPyValidate,)
__all__ = ["CheckboxPrompt"]
class InquirerPyCheckboxControl(InquirerPyUIListControl): """An :class:`~prompt_toolkit.layout.UIControl` class that displays a list of choices.
Reference the parameter definition in :class:`.CheckboxPrompt`. """
def __init__( self, choices: InquirerPyListChoices, default: Any, pointer: str, enabled_symbol: str, disabled_symbol: str, session_result: Optional[InquirerPySessionResult], ) -> None: """Initialise required attributes and call base class.""" self._pointer = pointer self._enabled_symbol = enabled_symbol self._disabled_symbol = disabled_symbol super().__init__( choices=choices, default=default, session_result=session_result, multiselect=True, )
def _format_choices(self) -> None: pass
def _get_hover_text(self, choice) -> List[Tuple[str, str]]: display_choices = [] display_choices.append(("class:pointer", self._pointer)) if self._pointer: display_choices.append(("", " ")) if not isinstance(choice["value"], Separator): display_choices.append( ( "class:checkbox", self._enabled_symbol if choice["enabled"] else self._disabled_symbol, ) ) if self._enabled_symbol and self._disabled_symbol: display_choices.append(("", " ")) display_choices.append(("[SetCursorPosition]", "")) display_choices.append(("class:pointer", choice["name"])) return display_choices
def _get_normal_text(self, choice) -> List[Tuple[str, str]]: display_choices = [] display_choices.append(("", len(self._pointer) * " ")) if self._pointer: display_choices.append(("", " ")) if not isinstance(choice["value"], Separator): display_choices.append( ( "class:checkbox", self._enabled_symbol if choice["enabled"] else self._disabled_symbol, ) ) if self._enabled_symbol and self._disabled_symbol: display_choices.append(("", " ")) display_choices.append(("", choice["name"])) else: display_choices.append(("class:separator", choice["name"])) return display_choices
class CheckboxPrompt(ListPrompt): """Create a prompt which displays a list of checkboxes to toggle.
A wrapper class around :class:`~prompt_toolkit.application.Application`.
User can toggle on/off on each checkbox.
Works very similar to :class:`~InquirerPy.prompts.list.ListPrompt` with `multiselect` enabled, the main difference is visual/UI and also when not toggling anything, the result will be empty.
Args: message: The question to ask the user. Refer to :ref:`pages/dynamic:message` documentation for more details. choices: List of choices to display and select. Refer to :ref:`pages/dynamic:choices` documentation for more details. style: An :class:`InquirerPyStyle` instance. Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details. vi_mode: Use vim keybinding for the prompt. Refer to :ref:`pages/kb:Keybindings` documentation for more details. default: Set the default value of the prompt. This will be used to determine which choice is highlighted (current selection), The default value should be the value of one of the choices. Refer to :ref:`pages/dynamic:default` documentation for more details. separator: Separator symbol. Custom symbol that will be used as a separator between the choice index number and the choices. qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered. amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered. pointer: Pointer symbol. Customer symbol that will be used to indicate the current choice selection. enabled_symbol: Checkbox ticked symbol. Custom symbol which indicate the checkbox is ticked. disabled_symbol: Checkbox not ticked symbol. Custom symbol which indicate the checkbox is not ticked. instruction: Short instruction to display next to the question. long_instruction: Long instructions to display at the bottom of the prompt. validate: Add validation to user input. The main use case for this prompt would be when `multiselect` is True, you can enforce a min/max selection. Refer to :ref:`pages/validator:Validator` documentation for more details. invalid_message: Error message to display when user input is invalid. Refer to :ref:`pages/validator:Validator` documentation for more details. transformer: A function which performs additional transformation on the value that gets printed to the terminal. Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`. Refer to :ref:`pages/dynamic:transformer` documentation for more details. filter: A function which performs additional transformation on the result. This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`. Refer to :ref:`pages/dynamic:filter` documentation for more details. height: Preferred height of the prompt. Refer to :ref:`pages/height:Height` documentation for more details. max_height: Max height of the prompt. Refer to :ref:`pages/height:Height` documentation for more details. border: Create border around the choice window. keybindings: Customise the builtin keybindings. Refer to :ref:`pages/kb:Keybindings` for more details. show_cursor: Display cursor at the end of the prompt. Set to False to hide the cursor. cycle: Return to top item if hit bottom during navigation or vice versa. wrap_lines: Soft wrap question lines when question exceeds the terminal width. raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result will be `None` and the question is skiped. mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped. mandatory_message: Error message to show when user attempts to skip mandatory prompt. session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
Examples: >>> from InquirerPy import inquirer >>> result = inquirer.checkbox(message="Select:", choices=[1, 2, 3]).execute() >>> print(result) [1] """
def __init__( self, message: InquirerPyMessage, choices: InquirerPyListChoices, default: Any = None, style: Optional[InquirerPyStyle] = None, vi_mode: bool = False, qmark: str = "?", amark: str = "?", pointer: str = INQUIRERPY_POINTER_SEQUENCE, enabled_symbol: str = INQUIRERPY_FILL_CIRCLE_SEQUENCE, disabled_symbol: str = INQUIRERPY_EMPTY_CIRCLE_SEQUENCE, border: bool = False, instruction: str = "", long_instruction: str = "", transformer: Optional[Callable[[Any], Any]] = None, filter: Optional[Callable[[Any], Any]] = None, height: Optional[Union[int, str]] = None, max_height: Optional[Union[int, str]] = None, validate: Optional[InquirerPyValidate] = None, invalid_message: str = "Invalid input", keybindings: Optional[InquirerPyKeybindings] = None, show_cursor: bool = True, cycle: bool = True, wrap_lines: bool = True, raise_keyboard_interrupt: bool = True, mandatory: bool = True, mandatory_message: str = "Mandatory prompt", session_result: Optional[InquirerPySessionResult] = None, ) -> None: self.content_control = InquirerPyCheckboxControl( choices=choices, default=default, pointer=pointer, enabled_symbol=enabled_symbol, disabled_symbol=disabled_symbol, session_result=session_result, ) super().__init__( message=message, choices=choices, style=style, border=border, vi_mode=vi_mode, qmark=qmark, amark=amark, instruction=instruction, long_instruction=long_instruction, transformer=transformer, filter=filter, height=height, max_height=max_height, validate=validate, invalid_message=invalid_message, multiselect=True, keybindings=keybindings, show_cursor=show_cursor, cycle=cycle, wrap_lines=wrap_lines, raise_keyboard_interrupt=raise_keyboard_interrupt, mandatory=mandatory, mandatory_message=mandatory_message, session_result=session_result, )
def _handle_enter(self, event) -> None: """Override this method to force empty array result.
When user does not select anything, exit with empty list.
Args: event: Keypress event. """ try: fake_document = FakeDocument(self.result_value) self._validator.validate(fake_document) # type: ignore except ValidationError: self._invalid = True else: self.status["answered"] = True self.status["result"] = self.result_name event.app.exit(result=self.result_value)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""Module contains the class to create filepath prompt and filepath completer class."""import osfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Generator, Optional
from prompt_toolkit.completion import Completer, Completionfrom prompt_toolkit.completion.base import ThreadedCompleter
from InquirerPy.prompts.input import InputPromptfrom InquirerPy.utils import ( InquirerPyDefault, InquirerPyKeybindings, InquirerPyMessage, InquirerPySessionResult, InquirerPyStyle, InquirerPyValidate,)
if TYPE_CHECKING: from prompt_toolkit.input.base import Input from prompt_toolkit.output.base import Output
__all__ = ["FilePathPrompt", "FilePathCompleter"]
class FilePathCompleter(Completer): """An auto completion class which generates system filepath.
See Also: :class:`~prompt_toolkit.completion.Completer`
Args: only_directories: Only complete directories. only_files: Only complete files. """
def __init__(self, only_directories: bool = False, only_files: bool = False): self._only_directories = only_directories self._only_files = only_files self._delimiter = "/" if os.name == "posix" else "\\"
def get_completions( self, document, complete_event ) -> Generator[Completion, None, None]: """Get a list of valid system paths.""" if document.text == "~": return
validation = lambda file, doc_text: str(file).startswith(doc_text)
if document.cursor_position == 0: dirname = Path.cwd() validation = lambda file, doc_text: True elif document.text.startswith("~"): dirname = Path(os.path.dirname(f"{Path.home()}{document.text[1:]}")) validation = lambda file, doc_text: str(file).startswith( f"{Path.home()}{doc_text[1:]}" ) elif document.text.startswith(f".{self._delimiter}"): dirname = Path(os.path.dirname(document.text)) validation = lambda file, doc_text: str(file).startswith(doc_text[2:]) else: dirname = Path(os.path.dirname(document.text))
for item in self._get_completion(document, dirname, validation): yield item
def _get_completion( self, document, path, validation ) -> Generator[Completion, None, None]: if not path.is_dir(): return for file in path.iterdir(): if self._only_directories and not file.is_dir(): continue if self._only_files and not file.is_file(): continue if validation(file, document.text): file_name = file.name display_name = file_name if file.is_dir(): display_name = f"{file_name}{self._delimiter}" yield Completion( file.name, start_position=-1 * len(os.path.basename(document.text)), display=display_name, )
class FilePathPrompt(InputPrompt): """Create a prompt that provides auto completion for system filepaths.
A wrapper class around :class:`~prompt_toolkit.shortcuts.PromptSession`.
Args: message: The question to ask the user. Refer to :ref:`pages/dynamic:message` documentation for more details. style: An :class:`InquirerPyStyle` instance. Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details. vi_mode: Use vim keybinding for the prompt. Refer to :ref:`pages/kb:Keybindings` documentation for more details. default: Set the default text value of the prompt. Refer to :ref:`pages/dynamic:default` documentation for more details. qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered. amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered. instruction: Short instruction to display next to the question. long_instruction: Long instructions to display at the bottom of the prompt. multicolumn_complete: Change the auto-completion UI to a multi column display. validate: Add validation to user input. Refer to :ref:`pages/validator:Validator` documentation for more details. invalid_message: Error message to display when user input is invalid. Refer to :ref:`pages/validator:Validator` documentation for more details. transformer: A function which performs additional transformation on the value that gets printed to the terminal. Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`. Refer to :ref:`pages/dynamic:transformer` documentation for more details. filter: A function which performs additional transformation on the result. This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`. Refer to :ref:`pages/dynamic:filter` documentation for more details. keybindings: Customise the builtin keybindings. Refer to :ref:`pages/kb:Keybindings` for more details. wrap_lines: Soft wrap question lines when question exceeds the terminal width. only_directories: Only complete directories. only_files: Only complete files. raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result will be `None` and the question is skiped. mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped. mandatory_message: Error message to show when user attempts to skip mandatory prompt. session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`. input: Used internally and will be removed in future updates. output: Used internally and will be removed in future updates.
Examples: >>> from InquirerPy import inquirer >>> result = inquirer.filepath(message="Enter a path:").execute() >>> print(result) /home/ubuntu/README.md """
def __init__( self, message: InquirerPyMessage, style: Optional[InquirerPyStyle] = None, vi_mode: bool = False, default: InquirerPyDefault = "", qmark: str = "?", amark: str = "?", instruction: str = "", long_instruction: str = "", multicolumn_complete: bool = False, validate: Optional[InquirerPyValidate] = None, invalid_message: str = "Invalid input", only_directories: bool = False, only_files: bool = False, transformer: Optional[Callable[[str], Any]] = None, filter: Optional[Callable[[str], Any]] = None, keybindings: Optional[InquirerPyKeybindings] = None, wrap_lines: bool = True, raise_keyboard_interrupt: bool = True, mandatory: bool = True, mandatory_message: str = "Mandatory prompt", session_result: Optional[InquirerPySessionResult] = None, input: Optional["Input"] = None, output: Optional["Output"] = None, ) -> None: super().__init__( message=message, style=style, vi_mode=vi_mode, default=default, qmark=qmark, amark=amark, instruction=instruction, long_instruction=long_instruction, completer=ThreadedCompleter( FilePathCompleter( only_directories=only_directories, only_files=only_files ) ), multicolumn_complete=multicolumn_complete, validate=validate, invalid_message=invalid_message, transformer=transformer, filter=filter, keybindings=keybindings, wrap_lines=wrap_lines, raise_keyboard_interrupt=raise_keyboard_interrupt, mandatory=mandatory, mandatory_message=mandatory_message, session_result=session_result, input=input, output=output, ).gitattributes+6
.venv/.gitignoreAdded+1
.venv/.lockAdded
.venv/CACHEDIR.TAGAdded+1
.venv/bin/activateAdded+130
.venv/bin/activate.batAdded+71
.venv/bin/activate.cshAdded+76
.venv/bin/activate.fishAdded+124
.venv/bin/activate.nuAdded+117
.venv/bin/activate.ps1Added+82
.venv/bin/activate_this.pyAdded+59
.venv/bin/deactivate.batAdded+39
.venv/bin/huggingface-cliAdded+10
.venv/bin/normalizerAdded+10
.venv/bin/pydoc.batAdded+22
.venv/bin/pythonAdded
.venv/bin/python3Added
.venv/bin/python3.13Added
.venv/bin/tiny-agentsAdded+10
.venv/bin/tqdmAdded+10
.venv/lib/python3.13/site-packages/InquirerPy/base/__init__.pyAdded+15
.venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/__init__.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/complex.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/control.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/list.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/base/__pycache__/simple.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/base/complex.pyAdded+294
.venv/lib/python3.13/site-packages/InquirerPy/base/control.pyAdded+227
.venv/lib/python3.13/site-packages/InquirerPy/base/list.pyAdded+238
.venv/lib/python3.13/site-packages/InquirerPy/base/simple.pyAdded+378
.venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/__init__.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/instruction.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/message.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/spinner.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/containers/__pycache__/validation.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/containers/spinner.pyAdded+108
.venv/lib/python3.13/site-packages/InquirerPy/containers/validation.pyAdded+60
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/__init__.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/checkbox.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/confirm.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/expand.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/filepath.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/fuzzy.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/input.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/list.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/number.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/rawlist.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/__pycache__/secret.cpython-313.pycAdded
.venv/lib/python3.13/site-packages/InquirerPy/prompts/checkbox.pyAdded+244
.venv/lib/python3.13/site-packages/InquirerPy/prompts/filepath.pyAdded+192