o
    2j                  
   @   s  U d Z ddlZddlZddlZddlZddlZddlZddlZddl	m
Z
mZ ddlmZ ddlmZ ddlmZmZmZmZmZmZ ddlZddlZddlmZmZ ddlmZmZmZ dd	l m!Z! dd
l"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. e&/ Z0dZ1erddl2m3Z3 dde4dB ddfddZ5dZ6dde7e4 de4dB de4fddZ8ed e4B Z9e
e7e4 e:e4 ge;dB f Z<ede4dZ=de4dB dej>d ej?ddfd!d"Z@eAd#ZBG d$d% d%eZCg d&ZDe7eEe4e4f  eFd'< d ej?ddfd(d)ZGd*ejHdeIfd+d,ZJd*ejHd-e7e4 ddfd.d/ZKd-e7e4 deIfd0d1ZLd-e7e4 d2eId3eIddfd4d5ZMd6e4dd7fd8d9ZNd:ejOd;e4d<e7eEe4e4f  ddfd=d>ZP	dd?e<d@e
g e7eEe4e4f  f dB deQeC fdAdBZRddCe9de7e4 dB deQe fdDdEZSG dFdG dGejTZUddHe4de4dB dIeQe dB ddGfdJdKZVG dLdM dMejWZXG dNdO dOe4eZYee4ejZdPdQf Z[eeYej\dRdSdTdQf Z]eeYdB ej\dRdSdTdUdVf Z^ee4dB ej\dWdQf Z_eeIdB ej\dXdQf Z`ee4dB ej\dYdQf Zaee;ej\dZdQf Zbee4dB ej\d[dQf Zcee7e4 dB ej\d\dQf Zdee4dB ej\d]dQf Zeee7e4 dB ej\d^d_d`dQf Zfee7e4 dB ej\dadbdcdQf Zgee4dB ej\dddedQf Zhee4dB ej\dfdQf Zideje4e4f fdgdhZk		ddie7e4 dB dje4dB deje4e4dB f fdkdlZldmeje4e4dB f de7eje4e4f  dB fdndoZmee7e4 dB ej\dpdqdrdQf Zndse7e4 dB ddtfdudvZodwee= fdxdyZpdzed{ ddfd|d}Zqdzed{ ddfd~dZrdze4de4dB fddZsde4dB fddZtde;fddZude7e4 dB fddZvde7e4 dB fddZwdS )z*Contains CLI utilities (styling, helpers).    N)CallableSequence)Enum)Path)TYPE_CHECKING	AnnotatedAnyLiteralTypeVarcast)TyperCommand
TyperGroup)Volume__version__	constants)CLIError)get_sessionhf_raise_for_statusinstallation_methodloggingparse_hf_mount)load_dotenv   )StyledContext)OutputFormatout   HfApitokenreturnr   c                 C   s   ddl m} || dtdS )Nr   r   zhuggingface-cli)r   library_namelibrary_version)huggingface_hub.hf_apir   r   )r   r    r$   Y/var/www/html/whisper/venv/lib/python3.10/site-packages/huggingface_hub/cli/_cli_utils.py
get_hf_api8   s   r&   z9https://huggingface.co/docs/huggingface_hub/en/guides/cliexamplesdocs_anchorc                 C   s:   |rt  | nt }ddd | D }d| d| dS )a  Generate an epilog with examples and a Learn More section.

    Args:
        examples: List of example commands (without the `$ ` prefix).
        docs_anchor: Optional anchor for the docs URL (e.g., "#hf-download").

    Returns:
        Formatted epilog string.
    
c                 s   s    | ]}d | V  qdS )z  $ Nr$   ).0exr$   r$   r%   	<genexpr>O   s    z"generate_epilog.<locals>.<genexpr>z	Examples
zk

Learn more
  Use `hf <command> --help` for more information about a command.
  Read the documentation at )CLI_REFERENCE_URLjoin)r'   r(   docs_urlexamples_strr$   r$   r%   generate_epilogD   s   
r1   )mainhelpExpandPropertyT)boundepilogctx	formatterc                 C   s.   | r|   | dD ]	}|| qdS dS )z%Write the epilog without indentation.r)   N)write_paragraphsplit
write_text)r6   r7   r8   liner$   r$   r%   _format_epilog_no_indent_   s   r=   z\s*\|\s*c                       s   e Zd ZdZeZdejddf fddZdejde	e
 def fdd	Zed
ejde	e
 ddfddZdejde
dejdB f fddZdee
e	e
 f fddZdejdejddfddZdejdejddfddZdejde	e
 fddZ  ZS )HFCliTyperGroupa  
    Typer Group that:
    - lists commands alphabetically within sections.
    - separates commands by topic (main, help, etc.).
    - formats epilog without extra indentation.
    - supports aliases via pipe-separated names (e.g. ``name="list | ls"``).
    - consumes the global formatting flags (``--format``, ``--json``, ``-q`` / ``--quiet``, ``--no-truncate``)
      anywhere in the args of a leaf command and applies them to ``out``, so leaf
      commands don't need to declare these options themselves.
    - rewrites ``spaces/user/repo`` to ``user/repo --type space`` for commands that accept ``--type``.
    - enriches "No such option" / "No such command" errors with available options or commands.
    r7   r    Nc              
      s   zt  |W S  tjyT  z@jdurOjjdurOjj t tjr; fdd jD }t	d|  fdd 
jD }t	d|  dww )at  Enrich unknown-option errors with available options or subcommands.

        Catches `NoSuchOption` raised during subcommand `make_context()`
        (option parsing).  For leaf commands (e.g. `hf repos create --test`)
        we list the command's options; for groups (e.g. `hf cache --test`)
        we list subcommands since groups have no user-facing options.
        Nc                    s8   g | ]}  j| d urjs|jddfqS NP   limit)get_commandr7   hiddenget_short_help_strr*   name)cmdesubr$   r%   
<listcomp>   s
    z*HFCliTyperGroup.invoke.<locals>.<listcomp>commandsc                    s2   g | ]}t |tjr|js| j rqS r$   )
isinstanceclickOptionrD   get_help_recordr7   r*   p)rI   recordr$   r%   rK      s    
options)superinvokerN   NoSuchOptionr7   commandrM   Grouplist_commands_enrich_usage_error
get_params)selfr7   items	__class__)rH   rI   rS   rJ   r%   rV   z   s$   
	
zHFCliTyperGroup.invokeargsc              
      s.  |r|d  ds|d nd }|r |nd }|d ur#|| zt  |\}}}W nS tjy } zF|d u r}|d ur}dd j D }	t	
||	}
|
riddd |
D }|jd d	| d
|_ fdd D }t|d|  d }~ww |d urt|tjst|| |||fS )Nr   -c                 S   s*   g | ]\}}|j st|D ]}|qqS r$   )rD   _ALIAS_SPLITr:   )r*   key
registeredaliasr$   r$   r%   rK      s    z3HFCliTyperGroup.resolve_command.<locals>.<listcomp>, c                 s   s    | ]	}d | d V  qdS )'Nr$   r*   mr$   r$   r%   r,      s    z2HFCliTyperGroup.resolve_command.<locals>.<genexpr>.z. Did you mean ?c                    s6   g | ]}  | d urjs|jddfqS r?   )rC   rD   rE   rF   r7   r]   rJ   r$   r%   rK      s
    rL   )
startswithrC   _rewrite_repo_type_prefixrU   resolve_commandrN   
UsageErrorrL   r^   difflibget_close_matchesr.   messagerstriprZ   r[   rM   rY   _consume_format_flags_for_leaf)r]   r7   ra   cmd_namerH   rG   resolved_cmdsub_argsrI   visible_namesmatchessuggestionsr^   r_   rm   r%   rp      s2   

zHFCliTyperGroup.resolve_commandrH   c                 C   s2  t dd | jD }|sdS t }d}| jD ]}t|tjr,|jdv r(|| |d7 }q|s1dS t }| jD ]}t|tjrS|j	sSg |j
|jR D ]}|| qKq7d}g }	d}
|
t|k r||
 }|dkrin.|drd	|v sv||vr{|
d7 }
n|
d
7 }
n||v r|	|
 |d7 }|
d7 }
|
t|k s`|	sdS d}d}g }|	D ]I}|| dd
}t|dks|d tjvrq|d }tj| }|dur||krtd| d| d|}|}|||d  d|d
  f q|sdS t dd |D rtd| d|D ]	\}}|||< q|d|g dS )u  Rewrite prefixed repo IDs (e.g. ``spaces/user/repo``) to ``user/repo --type space``.

        Only applies to commands that have a ``--type`` / ``--repo-type`` option and
        at least one repo-ID positional argument (any ``click.Argument`` whose name
        ends with ``_id``, e.g. ``repo_id``, ``from_id``, ``to_id``).  When the
        token that maps to such an argument matches ``{prefix}/org/repo`` (where
        *prefix* is one of ``spaces``, ``datasets``, or ``models``), the prefix is
        stripped and an implicit ``--type {type}`` is appended.  An error is raised
        if ``--type`` is also provided explicitly or if multiple prefixed arguments
        disagree on the repo type.

        Only repo-ID positional slots are inspected so that other positional
        arguments (filenames, local paths, patterns …) are never misinterpreted as
        prefixed repo IDs.
        c                 s   s&    | ]}t |tjod |jv V  qdS )--typeN)rM   rN   rO   opts)r*   paramr$   r$   r%   r,      s   $ z<HFCliTyperGroup._rewrite_repo_type_prefix.<locals>.<genexpr>Nr   )repo_idfrom_idto_idr   --rb   =   /   z!Conflicting repo type prefixes: 'z/' and 'z/'.c                 s   s4    | ]}|d kp| dp|dkp| dV  qdS )r}   z--type=--repo-typez--repo-type=Nrn   r*   argr$   r$   r%   r,     s
    "
z!Ambiguous repo type: got prefix 'z8/' in repo ID and explicit --type. Use one or the other.r}   )anyparamssetrM   rN   ArgumentrG   addrO   is_flagr~   secondary_optslenrn   appendr:   r   REPO_TYPES_MAPPINGrq   extend)rH   ra   has_type_optionrepo_id_positionsarg_idxr   value_optionsoptpositional_countrepo_id_arg_indicesir   inferred_typefirst_prefixrewrites	arg_indexpartsprefixmapped_type	new_valuer$   r$   r%   ro      s|   








"

z)HFCliTyperGroup._rewrite_repo_type_prefixrw   c                    sL   t  ||}|d ur|S | j D ]\}}t|}||v r#|  S qd S N)rU   rC   rL   r^   rc   r:   )r]   r7   rw   rH   registered_nameregistered_cmdaliasesr_   r$   r%   rC   !  s   
zHFCliTyperGroup.get_commandc                 C   s6   i }| j D ]}t|}|d }|dd ||< q|S )zBBuild a mapping from primary command name to its aliases (if any).r   r   N)rL   rc   r:   )r]   resultr   r   primaryr$   r$   r%   
_alias_map.  s   

zHFCliTyperGroup._alias_mapr8   c           
   	   C   s(  i }|   }| |D ];}| ||}|d u s|jrq|j|jd}||g }|r5| dd| d}t|dd}	|	|	g 
||f q|d ||d  W d    n1 s^w   Y  t| D ](}	|	dkrpqi||	  d |||	  W d    n1 sw   Y  qid S )	NrA   z	 [alias: rg   ]topicr2   zMain commandsz	 commands)r   rZ   rC   rD   rE   widthgetr.   getattr
setdefaultr   sectionwrite_dlsortedkeys
capitalize)
r]   r7   r8   topics	alias_maprG   rH   	help_textr   r   r$   r$   r%   format_commands7  s.   zHFCliTyperGroup.format_commandsc                 C   s   g }|  |D ]}| ||}|d u s|jrqt|dg }|r&||d  q|r5t|}t||| d S | jrAt| j|| d S d S )Nr'   r   )rZ   rC   rD   r   r   r1   r=   r6   )r]   r7   r8   all_examplesrG   rH   cmd_examplesr6   r$   r$   r%   format_epilogN  s   zHFCliTyperGroup.format_epilogc                 C   s0   g }| j D ]}t|d }|| qt|S )Nr   )rL   rc   r:   r   r   )r]   r7   primary_namesrG   r   r$   r$   r%   rZ   `  s
   
zHFCliTyperGroup.list_commands)__name__
__module____qualname____doc__r   context_classrN   ContextrV   liststrtuplerp   staticmethodCommandro   rC   dictr   HelpFormatterr   r   rZ   __classcell__r$   r$   r_   r%   r>   j   s     '"`	 r>   ))z&--format [auto|human|agent|json|quiet]zWOutput format. Defaults to 'auto' which picks 'agent' or 'human' based on the terminal.)--jsonz+JSON output. Equivalent to '--format json'.)z-q, --quietz?Quiet output (one ID per line). Equivalent to '--format quiet'.)--no-truncatezQDo not truncate scalar values in human tables (list/dict columns stay shortened). _FORMATTING_OPTIONS_HELP_RECORDSc                 C   s:   |  d | t W d    d S 1 sw   Y  d S )NzFormatting options)r   r   r   )r8   r$   r$   r%   "_format_formatting_options_sectiont  s   "r   rH   c                 C   sV   | j D ]%}t|tjsqg |j|jR }d|v s%d|v s%d|v s%d|v r( dS qdS )a  Return True if the command defines its own --format, --json or --quiet / -q.

    Used to skip the global formatting flag pre-processor and the duplicated "Formatting options" help section for
    legacy commands like 'hf jobs ps' that have their own format/quiet options.
    --formatr   --quiet-qTF)r   rM   rN   rO   r~   r   )rH   r   r~   r$   r$   r%   _has_local_formatting_optiony  s   
 r   ra   c                    s  | j drdS t|}t| d}d}d}| jD ](}t|tjs#qg |j	|j
R }d|v r2d}d|v s:d|v r<d}d|v rBd}q|rPt|| | d	 dS tj}d d
tddf fdd}	d}
|
t|k r||
 }|dkrqnx|dkr|	d |
d t|krtdt||
d  }d ||
|
d = qb|dr|	d t|tdd }d ||
|
d = qb|dkr|	d tj}d ||
|
d = qb|dv r|	| tj}| ||
|
d = qb|
d7 }
|
t|k sht| dS )uJ  Apply global formatting flags from 'args' to a leaf command.

    Two modes, depending on the command:

    * **Pass-through commands** (ignore_unknown_options=True, e.g. 'hf extensions exec'):
      args are forwarded verbatim to an external binary; we don't touch them.

    * **Legacy commands with a local --format option** (e.g. 'hf jobs ps' whose '--format' accepts Go templates):
      the global flags are rewritten in-place to the legacy form ('--json' → '--format json', '--quiet'/'-q' → '--format quiet'
      when the cmd has no own '--quiet') so click can parse them locally. This preserves backwards compatibility with the previous shorthand behavior.

    * **Modern commands** (no local format/quiet/json options): the flags '--format <value>' / '--json' / '--quiet' / '-q' are stripped from 'args' and applied to the singleton 'out'.

    '--no-truncate' is stripped for all non-pass-through commands; when present, human table cells are not truncated.

    Raises click.UsageError if multiple conflicting flags are supplied (e.g. '--json' together with '--format table').
    ignore_unknown_optionsNFr   Tr   r   r   )rewrite_jsonrewrite_quietnew_flagr    c                    s$    d urt d  d|  dd S )Nrh   z' and 'z' are mutually exclusive.)rN   rq   )r   chosen_flagr$   r%   _check_conflict  s   z7_consume_format_flags_for_leaf.<locals>._check_conflictr   r   r   z#Option '--format' requires a value.r   	--format=)r   r   )context_settingsr   _consume_no_truncate_flagsr   set_no_truncater   rM   rN   rO   r~   r   _rewrite_legacy_shorthandsr   autor   r   rq   _parse_format_valuern   jsonquietset_mode)rH   ra   no_truncatehas_local_formathas_local_quiethas_local_jsonr   r~   chosen_moder   r   r   r$   r   r%   rv     st   



 rv   c                 C   sr   d}d}|t | k r7| | }|dkr	 |S |dkr#d}| ||d = q|dr-td|d7 }|t | k s
|S )	zSStrip all global --no-truncate flags from args and return whether any was provided.Fr   r   r   Tr   z--no-truncate=z-Option '--no-truncate' does not take a value.)r   rn   rN   rq   )ra   r   r   r   r$   r$   r%   r     s    

r   r   r   c                C   s   t dd | D }|r'd| v r'|rtd| d}ddg| ||d < d}|rWd	| v r/d	nd
| v r5d
nd}|durY|rFtd| d| |}ddg| ||d < dS dS dS )a  Rewrite --json / -q / --quiet to --format ... for legacy commands.

    Used for commands like 'hf jobs ps' that still own their '--format' option.
    The rewrite lets users keep using the global shorthand while click parses
    '--format <value>' locally.
    c                 s   s"    | ]}|d kp| dV  qdS )r   r   Nr   r   r$   r$   r%   r,          z-_rewrite_legacy_shorthands.<locals>.<genexpr>r   z/'--json' and '--format' are mutually exclusive.r   r   r   Tr   r   Nrh   z(' and '--format' are mutually exclusive.r   )r   rN   rq   index)ra   r   r   has_format_in_argsidxflagr$   r$   r%   r     s    


r   valuer   c              
   C   sH   zt | W S  ty#   ddd t D }td|  d| dd w )Nrg   c                 s   s    | ]}|j V  qd S r   r   ri   r$   r$   r%   r,     s    z&_parse_format_value.<locals>.<genexpr>zInvalid value for '--format': 'z'. Valid values: rk   )r   
ValueErrorr.   rN   rq   )r   validr$   r$   r%   r     s   
r   errorlabelr^   c                 C   s   |r| j du sd| d| jv rdS | j j}d| d| dg}|D ]\}}|d|dd	|  q"|d
| d t| tjrW| jrW|ddt	| j d g | _|  jd|7  _dS )zHAppend a list of available options or commands to a usage error message.Nz
Available z forz

Available z for 'z':z  30s z
Run 'z --help' for full details.z
Did you mean: rg   rl   r)   )
r7   rt   command_pathr   rM   rN   rW   possibilitiesr.   r   )r   r   r^   cmd_pathlinesrG   r   r$   r$   r%   r[     s    r[   fallback_handlerextra_commands_providerc                    s   G  fdddt }|S )zRReturn a Typer group class that runs a fallback handler before command resolution.c                       sR   e Zd Zdejdee def fddZdejdej	ddf fdd	Z
  ZS )
z8fallback_typer_group_factory.<locals>.FallbackTyperGroupr7   ra   r    c                    s2   |t | j }|d urt|t ||S r   )r   rL   r   
SystemExitrU   rp   )r]   r7   ra   fallback_exit_code)r`   r   r$   r%   rp   *  s   zHfallback_typer_group_factory.<locals>.FallbackTyperGroup.resolve_commandr8   Nc                    sb   t  || d ur- }|r/|d || W d    d S 1 s&w   Y  d S d S d S )NzExtension commands)rU   r   r   r   )r]   r7   r8   entries)r`   r   r$   r%   r   0  s   "zHfallback_typer_group_factory.<locals>.FallbackTyperGroup.format_commands)r   r   r   rN   r   r   r   r   rp   r   r   r   r$   r   r   r_   r%   FallbackTyperGroup)  s    "(r  )r>   )r   r   r  r$   r  r%   fallback_typer_group_factory#  s   r  r   c              
   C   s   dt jdt jdt jdd fdd}dtdt jdt jdd fdd}dt jdt jd	tt dtt fd
d}td|   tft	| |p@g |||dS )Nr]   r7   r8   r    c                 S   s   t | j|| d S r   )r=   r6   r]   r7   r8   r$   r$   r%   r   <  s   z#HFCliCommand.<locals>.format_epilogc                 S   s6   t | || t| rd S | jdrd S t| d S )Nr   )r   format_optionsr   r   r   r   r  r$   r$   r%   r  ?  s   z$HFCliCommand.<locals>.format_optionsra   c                 S   sH   |s|j stdd | jD rtj| |jd |  t	| ||S )Nc                 s   s"    | ]}t |tjo|jV  qd S r   )rM   rN   r   requiredrQ   r$   r$   r%   r,   M  r   z3HFCliCommand.<locals>.parse_args.<locals>.<genexpr>)color)
resilient_parsingr   r   rN   echoget_helpr	  exitr   
parse_args)r]   r7   ra   r$   r$   r%   r  I  s
   
z HFCliCommand.<locals>.parse_argsr   )r   r   r'   r   r  r  )
rN   r   r   r   r   r   r   typer   r   )r   r'   r   r  r  r$   r$   r%   HFCliCommand;  s    &
	r  c                "       s   e Zd ZdZ	dddddddddddddddedB d	ed
ee dB deeef dB dedB dedB dedB dede	de	de	de	dedB de
e
def ge
def f f fddZ  ZS )HFCliAppz&Custom Typer app for Hugging Face CLI.Nr2   z	[OPTIONS]TF)r   r'   r   r3   r6   
short_helpoptions_metavaradd_help_optionno_args_is_helprD   
deprecatedrich_help_panelrG   r   r'   r   r3   r6   r  r  r  r  rD   r  r  r    .c                   sZ   d u r
r
t dtdtf dtdtf f 	
fdd}|S )Nfunc.r    c                    s2   t tjt
	d| S )N)clsr   r3   r6   r  r  r  r  rD   r  r  )rU   r  rX   r  )r  )r`   r  r   r  r6   r'   r3   rD   rG   r  r  r  r]   r  r   r$   r%   _innerx  s    
z HFCliApp.command.<locals>._inner)r1   r   r   )r]   rG   r   r'   r   r3   r6   r  r  r  r  rD   r  r  r  r_   )r  r   r  r6   r'   r3   rD   rG   r  r  r  r]   r  r   r%   rX   c  s   BzHFCliApp.commandr   )r   r   r   r   r   TOPIC_Tr   r   r   boolr   rX   r   r$   r$   r_   r%   r  `  sZ    
	
r  r3   r  c                 C   s2   |du rt }t| |dd|dddddddgdd
S )	a+  Create a Typer app with consistent settings.

    Args:
        help: Help text for the app.
        epilog: Optional epilog text (use `generate_epilog` to create one).
        cls: Optional Click group class to use (defaults to `HFCliTyperGroup`).

    Returns:
        A configured Typer app.
    NTFx   z-hz--help)max_content_widthhelp_option_names)
r3   r6   add_completionr  r  rich_markup_moder  pretty_exceptions_enablesuggest_commandsr   )r>   r  )r3   r6   r  r$   r$   r%   typer_factory  s    r$  c                       s`   e Zd ZdZdee ee B ddf fddZde	de
jdB d	e
jdB def fd
dZ  ZS )
SoftChoicea  A click Choice that suggests choices for autocompletion/docs but accepts any string.

    Unlike `click.Choice`, unknown values are passed through as-is instead of raising an error.
    This makes CLI options future-compatible when new server-side values are added.

    Accepts either a sequence of strings or an Enum class:
    ```python
    SoftChoice(SpaceHardware)        # from an enum
    SoftChoice(["a", "b", "c"])      # from a list
    ```
    choicesr    Nc                    s>   t |trt|trdd |D nt|}t j|dd d S )Nc                 S   s   g | ]}|j qS r$   r   ri   r$   r$   r%   rK     s    z'SoftChoice.__init__.<locals>.<listcomp>T)case_sensitive)rM   r  
issubclassr   r   rU   __init__)r]   r&  valuesr_   r$   r%   r)    s   (zSoftChoice.__init__r   r   r7   c                    s2   z	t  |||W S  tjjy   t| Y S w r   )rU   convertrN   
exceptionsBadParameterr   )r]   r   r   r7   r_   r$   r%   r+    s
   zSoftChoice.convert)r   r   r   r   r   r   r  r   r)  r   rN   	Parameterr   r+  r   r$   r$   r_   r%   r%    s    "2r%  c                   @   s   e Zd ZdZdZdZdS )RepoTypemodeldatasetspaceN)r   r   r   r0  r1  r2  r$   r$   r$   r%   r/    s    r/  zNThe ID of the repo (e.g. `username/repo-name` or `spaces/username/repo-name`).)r3   r}   r   z2The type of repository (model, dataset, or space).r0  )r3   show_defaultzJA User Access Token generated from https://huggingface.co/settings/tokens.zfWhether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already exists.zDGit revision id which can be a branch name, a tag, or a commit hash.zLimit the number of results.z!Filter by author or organization.zHFilter by tags (e.g. 'text-classification'). Can be used multiple times.zSearch query.z-ez--envz/Set environment variables. E.g. --env ENV=valuez-sz	--secretszvSet secret environment variables. E.g. --secrets SECRET=value or `--secrets HF_TOKEN` to pass your Hugging Face token.z
--env-filez(Read in a file of environment variables.z/Read in a file of secret environment variables.c                  C   s0   ddl m}  tj }|   }dur||d< |S )zQReturn a copy of ``os.environ`` with the user's HF token injected (if available).r   )	get_tokenNHF_TOKEN)huggingface_hubr4  osenvironcopy)r4  extended_environr   r$   r$   r%   _get_extended_environ>  s
   
r;  envenv_filec                 C   sL   t  }i }|r|tt| |d | pg D ]}|t||d q|S )zParse ``-e``/``--env``/``-s``/``--secrets`` and ``--env-file``/``--secrets-file`` CLI args into a dict.

    Uses an extended environment that includes the user's HF token so that
    bare ``--secrets HF_TOKEN`` resolves correctly.
    )r8  )r;  updater   r   	read_text)r<  r=  r:  env_map	env_valuer$   r$   r%   parse_env_mapH  s   	rB  r@  c                 C   s   | sdS dd |   D S )z_Convert an env/secrets dict to the ``[{"key": ..., "value": ...}]`` format used by the Hub API.Nc                 S   s   g | ]\}}||p
d dqS ) )rd   r   r$   )r*   kvr$   r$   r%   rK   ^  s    z-env_map_to_key_value_list.<locals>.<listcomp>)r^   )r@  r$   r$   r%   env_map_to_key_value_listZ  s   rF  z-vz--volumeaV  Mount one or more volumes. Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. TYPE is one of: models, datasets, spaces, buckets. TYPE defaults to models if omitted. models, datasets and spaces are always mounted read-only. buckets are read+write by default. E.g. -v hf://org/m:/data or -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:rovolumeszlist[Volume] | Nonec                 C   sX   | sdS g }| D ]!}t |}|t|jj|jj|j|j|jjp d|jj	p%dd q|S )a_  Parse volume specs from CLI arguments.

    Format: hf://[TYPE/]SOURCE[/PATH]:/MOUNT_PATH[:ro|:rw]
    Where TYPE is one of: models, datasets, spaces, buckets (defaults to models if omitted).
    SOURCE is the repo/bucket identifier (e.g. 'username/my-model').
    PATH is an optional subfolder inside the repo/bucket.
    MOUNT_PATH starts with '/'.
    Optional ':ro' or ':rw' suffix for read-only or read-write.

    Examples:
        hf://my-org/my-model:/data                (model, implicit type)
        hf://models/my-org/my-model:/data         (model, explicit type)
        hf://datasets/my-org/my-dataset:/data:ro
        hf://buckets/my-org/my-bucket:/mnt
        hf://spaces/my-org/my-space:/app
        hf://datasets/org/ds/train:/data          (with path inside repo)
        hf://buckets/org/b/sub/dir:/mnt           (with path inside bucket)
    N)r  source
mount_path	read_onlypathrevision)
r   r   r   rH  r  idrI  rJ  path_in_reporL  )rG  r   raw_specmountr$   r$   r%   parse_volumeso  s    


rQ  valid_propertiesc                    s&   dt dB dtt dB f fdd}|S )zJCreate a callback to parse and validate comma-separated expand properties.r   Nr    c              	      s\   | d u rd S dd |  dD }|D ]}| vr&td| dd  qdd |D S )Nc                 S   s   g | ]}|  qS r$   )striprQ   r$   r$   r%   rK     s    zSmake_expand_properties_parser.<locals>._parse_expand_properties.<locals>.<listcomp>,zInvalid expand property: 'z'. Valid values are: rg   c                 S   s   g | ]}t t|qS r$   )r   r4   )r*   propr$   r$   r%   rK     s    )r:   typerr-  r.   )r   
propertiesrU  rR  r$   r%   _parse_expand_properties  s   z?make_expand_properties_parser.<locals>._parse_expand_properties)r   r   r4   )rR  rY  r$   rX  r%   make_expand_properties_parser  s   "rZ  library)r6  transformersc                 C   s2   zt |  W dS  ty   tjddd Y dS w )a  
    Check whether a newer version of a library is available on PyPI.

    If a newer version is found, print a hint pointing at `hf update`.

    If current version is a pre-release (e.g. `1.0.0.rc1`), or a dev version (e.g. `1.0.0.dev1`), no check is performed.
    If `HF_HUB_DISABLE_UPDATE_CHECK` is set, the check is skipped entirely.

    This function is called at the entry point of the CLI. It only performs the check once every 24 hours, and any error
    during the check is caught and logged, to avoid breaking the CLI.

    Args:
        library: The library to check for updates. Currently supports "huggingface_hub" and "transformers".
    z$Error while checking for CLI update.Texc_infoN)_check_cli_update	Exceptionloggerdebug)r[  r$   r$   r%   check_cli_update  s
   rc  c                    s&  t jrd S tj|  t fdddD rd S tjt j	r0tj
t j	}t | dk r0d S tt j	jjddd tt j	  | dkrOt dkrOt }nt| }|d u s[ |kr]d S | dkret }nt }d	|  d
| d  d}|d ur| dkr|d7 }n	 |dd| 7 }t| d S )Nc                 3   s    | ]}| v V  qd S r   r$   )r*   tagcurrent_versionr$   r%   r,     s    z$_check_cli_update.<locals>.<genexpr>)rcdeviQ T)parentsexist_okr6  brewzA new version of z (z&) is available! You are using version rk   z
To update, run: hf updatez
To update, run: r   )r   HF_HUB_DISABLE_UPDATE_CHECK	importlibmetadataversionr   r7  rK  existsCHECK_FOR_UPDATE_DONE_PATHgetmtimetimer   parentmkdirtouchr   _fetch_latest_brew_version_fetch_latest_pypi_version#_get_huggingface_hub_update_command _get_transformers_update_commandr.   r   hint)r[  mtimelatest_versionupdate_commandrt   r$   re  r%   r_    s6   
r_  c                 C   sV   zt  jd|  ddd}t| | d d W S  ty*   tjddd	 Y d
S w )zSFetch the latest version of a library from PyPI. Returns None if the request fails.zhttps://pypi.org/pypi/z/jsonr   timeoutinforo  z.Error while fetching latest version from PyPI.Tr]  Nr   r   r   r   r`  ra  rb  )r[  responser$   r$   r%   rx    s   rx  c                  C   sN   zt  jddd} t|  |  d d W S  ty&   tjddd Y d	S w )
zkFetch the latest version of the `hf` formula from the Homebrew registry. Returns None if the request fails.z,https://formulae.brew.sh/api/formula/hf.jsonr   r  versionsstablez2Error while fetching latest version from Homebrew.Tr]  Nr  )r  r$   r$   r%   rw    s   rw  c                  C   s    t  } | du rtdt| S )zRun the install-method-appropriate update command for the `hf` CLI.

    Raises CLIError if the installation method can't be determined.
    Returns the subprocess exit code on success/failure of the update itself.
    NzeCannot determine how to update huggingface_hub (unknown installation method). Please update manually.)ry  r   
subprocesscall)rH   r$   r$   r%   
run_update   s   
r  c                   C   sb   t   dkr g dS  dkrtjdkr g dS  dkr" g dS dkr.tjddd	d
dgS 	 dS )zlReturn the command to update huggingface_hub as an argv list, or None if the installation method is unknown.rk  )rk  upgradehfhf_installernt)
powershell
-NoProfile-Commandz-iwr -useb https://hf.co/cli/install.ps1 | iex)bash-cz0curl -LsSf https://hf.co/cli/install.sh | bash -pip-minstall-Ur6  Nr   r7  rG   sys
executabler$   r$   r$   r%   ry    s   

ry  c                   C   sP   t   dkrtjdkr g dS  dkr g dS dkr%tjddddd	gS 	 d
S )ziReturn the command to update transformers as an argv list, or None if the installation method is unknown.r  r  )r  r  r  z?iwr -useb https://hf.co/cli/install.ps1 | iex -WithTransformers)r  r  zHcurl -LsSf https://hf.co/cli/install.sh | bash -s -- --with-transformersr  r  r  r  r\  Nr  r$   r$   r$   r%   rz    s   
rz  r   )NN)xr   rr   importlib.metadatarm  r7  rer  r  rs  collections.abcr   r   enumr   pathlibr   typingr   r   r   r	   r
   r   rN   rV  
typer.corer   r   r6  r   r   r   huggingface_hub.errorsr   huggingface_hub.utilsr   r   r   r   r   huggingface_hub.utils._dotenvr   _help_formatterr   _outputr   r   
get_loggerra  REPO_LIST_DEFAULT_LIMITr#   r   r   r&   r-   r   r1   r  r   intFallbackHandlerTr4   r   r   r=   compilerc   r>   r   r   __annotations__r   r   r  r   rv   r   r   r   rq   r[   r  r  r  Typerr  r$  Choicer%  r/  r   	RepoIdArgrO   RepoTypeOptRepoTypeOptionalOptTokenOpt
PrivateOptRevisionOptLimitOpt	AuthorOpt	FilterOpt	SearchOptEnvOpt
SecretsOpt
EnvFileOptSecretsFileOptr   r;  rB  rF  
VolumesOptrQ  rZ  rc  r_  rx  rw  r  ry  rz  r$   r$   r$   r%   <module>   st   	 "
  Y(
$%(+#






	


.
&+