o
    0j                     @   sx  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	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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/m0Z0 e*1 Z2dZ3dZ4erddl5m6Z6 dde7dB ddfddZ8dZ9dde:e7 de7dB de7fddZ;ed e7B Z<ee:e7 e=e7 ge>dB f Z?ede7dZ@de7dB dejAd ejBddfd!d"ZCeDd#ZEG d$d% d%eZFg d&ZGe:eHe7e7f  eId'< d ejBddfd(d)ZJd*ejKdeLfd+d,ZMd*ejKd-e:e7 ddfd.d/ZNd-e:e7 d0eLd1eLddfd2d3ZOd4e7dd5fd6d7ZPd8ejQd9e7d:e:eHe7e7f  ddfd;d<ZR	dd=e?d>eg e:eHe7e7f  f dB deSeF fd?d@ZTddAe<de:e7 dB deSe fdBdCZUG dDdE dEejVZWddFe7de7dB dGeSe dB ddEfdHdIZXG dJdK dKe7eZYee7ejZdLdMf Z[eeYej\dNdOdPdMf Z]ee7dB ej\dQdMf Z^eeLdB ej\dRdMf Z_ee7dB ej\dSdMf Z`ee>ej\dTdMf Zaee7dB ej\dUdMf Zbee:e7 dB ej\dVdMf Zcee7dB ej\dWdMf Zdee:e7 dB ej\dXdYdZdMf Zeee:e7 dB ej\d[d\d]dMf Zfee7dB ej\d^d_dMf Zgee7dB ej\d`dMf Zhdeie7e7f fdadbZj		ddce:e7 dB dde7dB deie7e7dB f fdedfZkdgeie7e7dB f de:eie7e7f  dB fdhdiZlee:e7 dB ej\djdkdldMf ZmdmZne#joe#jpe#jqdndoZrdpe:e7 dB ddqfdrdsZsG dtdu due7eZteetej\dvdMf Zud4e/de/fdwdxZvee/ej\dyevdzf ZweeLej\d{d|d}dMf Zxd~e7de7fddZyd4ede7fddZze3fd4ede>de7fddZ{	dd:eeie7ef  de:e7 deeie7ef ge:e7 f deie7e7f dB ddf
ddZ|				dd:eeie7ef  detdeLde7de:e7 dB deeie7ef ge:e7 f dB deie7e7f dB ddfddZ}de~de~fddZdedeie7ef fddZdee@ fddZded ddfddZded ddfddZde7de7dB fddZde>fddZde:e7 dB fddZde:e7 dB fddZdS )z*Contains CLI utilities (styling, helpers).    N)CallableSequence)Enum)Path)TYPE_CHECKING	AnnotatedAnyLiteralTypeVarUnioncast)TyperCommand
TyperGroup)Volume__version__	constants)CLIError)get_sessionhf_raise_for_statusinstallation_methodloggingtabulate)load_dotenv   )OutputFormatWithAutoout#      HfApitokenreturnr   c                 C   s   ddl m} || dtdS )Nr   r   zhuggingface-cli)r    Zlibrary_nameZlibrary_version)huggingface_hub.hf_apir   r   )r    r    r#   _/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/huggingface_hub/cli/_cli_utils.py
get_hf_api=   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>T   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'   Zdocs_urlZexamples_strr#   r#   r$   generate_epilogI   s   
r.   )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)Zwrite_paragraphsplit
write_text)r3   r4   r5   liner#   r#   r$   _format_epilog_no_indentd   s   r9   z\s*\|\s*c                       s   e Zd Zd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``)
      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.
    r4   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_commandr4   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Optionr@   Zget_help_recordr4   r)   p)rE   recordr#   r$   rG      s    
options)superinvokerJ   NoSuchOptionr4   commandrI   Grouplist_commands_enrich_usage_error
get_params)selfr4   items	__class__)rD   rE   rN   rF   r$   rQ   }   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#   )r@   _ALIAS_SPLITr6   )r)   key
registeredaliasr#   r#   r$   rG      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;   )r?   r@   rA   rB   r4   rX   rF   r#   r$   rG      s
    rH   )
startswithr?   _rewrite_repo_type_prefixrP   resolve_commandrJ   
UsageErrorrH   rY   difflibget_close_matchesr-   messagerstriprU   rV   rI   rT   _consume_format_flags_for_leaf)rX   r4   r\   cmd_namerD   rC   Zresolved_cmdZsub_argsrE   Zvisible_namesmatchesZsuggestionsrY   rZ   rh   r$   rk      s2   

zHFCliTyperGroup.resolve_commandrD   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)rI   rJ   rK   opts)r)   paramr#   r#   r$   r+      s   $ z<HFCliTyperGroup._rewrite_repo_type_prefix.<locals>.<genexpr>Nr   )Zrepo_idZfrom_idZto_idr   --r]   =   /   z!Conflicting repo type prefixes: 'z/' and 'z/'.c                 s   s4    | ]}|d kp| dp|dkp| dV  qdS )rt   z--type=--repo-typez--repo-type=Nri   r)   argr#   r#   r$   r+     s
    "
z!Ambiguous repo type: got prefix 'z8/' in repo ID and explicit --type. Use one or the other.rt   )anyparamssetrI   rJ   ArgumentrC   addrK   Zis_flagru   secondary_optslenri   appendr6   r   ZREPO_TYPES_MAPPINGrl   extend)rD   r\   Zhas_type_optionZrepo_id_positionsZarg_idxrv   Zvalue_optionsoptZpositional_countZrepo_id_arg_indicesir   Zinferred_typeZfirst_prefixZrewritesZ	arg_indexpartsprefixZmapped_type	new_valuer#   r#   r$   rj      s|   








"

z)HFCliTyperGroup._rewrite_repo_type_prefixrr   c                    sL   t  ||}|d ur|S | j D ]\}}t|}||v r#|  S qd S N)rP   r?   rH   rY   r^   r6   )rX   r4   rr   rD   registered_nameZregistered_cmdaliasesrZ   r#   r$   r?   $  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)rH   r^   r6   )rX   resultr   r   primaryr#   r#   r$   
_alias_map1  s   

zHFCliTyperGroup._alias_mapr5   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 )	Nr=   z	 [alias: rb   ]topicr/   zMain commandsz	 commands)r   rU   r?   r@   rA   widthgetr-   getattr
setdefaultr   sectionwrite_dlsortedkeys
capitalize)
rX   r4   r5   ZtopicsZ	alias_maprC   rD   	help_textr   r   r#   r#   r$   format_commands:  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   )rU   r?   r@   r   r   r.   r9   r3   )rX   r4   r5   Zall_examplesrC   rD   Zcmd_examplesr3   r#   r#   r$   format_epilogQ  s   zHFCliTyperGroup.format_epilogc                 C   s0   g }| j D ]}t|d }|| qt|S )Nr   )rH   r^   r6   r   r   )rX   r4   Zprimary_namesrC   r   r#   r#   r$   rU   c  s
   
zHFCliTyperGroup.list_commands)__name__
__module____qualname____doc__rJ   ContextrQ   liststrtuplerk   staticmethodCommandrj   r?   dictr   HelpFormatterr   r   rU   __classcell__r#   r#   rZ   r$   r:   o   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'. _FORMATTING_OPTIONS_HELP_RECORDSc                 C   s:   |  d | t W d    d S 1 sw   Y  d S )NzFormatting options)r   r   r   )r5   r#   r#   r$   "_format_formatting_options_sectionv  s   "r   rD   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   rI   rJ   rK   ru   r   )rD   rv   ru   r#   r#   r$   _has_local_formatting_option{  s   
 r   r\   c                    s  | j drdS d}d}d}| jD ](}t|tjsqg |j|jR }d|v r)d}d|v s1d|v r3d}d|v r9d}q|rGt|| | d	 dS t	j
}d d
tddf fdd}d}	|	t|k r||	 }
|
dkrhnx|
dkr|d |	d t|kr}tdt||	d  }d ||	|	d = qY|
dr|d t|
tdd }d ||	|	d = qY|
dkr|d t	j}d ||	|	d = qY|
dv r||
 t	j}|
 ||	|	d = qY|	d7 }	|	t|k s_t| dS )u  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'.

    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 )Nrc   z' and 'z' are mutually exclusive.)rJ   rl   )r   Zchosen_flagr#   r$   _check_conflict  s   z7_consume_format_flags_for_leaf.<locals>._check_conflictr   rw   r   z#Option '--format' requires a value.ry   	--format=)r   r   )context_settingsr   r   rI   rJ   rK   ru   r   _rewrite_legacy_shorthandsr   autor   r   rl   _parse_format_valueri   jsonquietr   set_mode)rD   r\   Zhas_local_formatZhas_local_quietZhas_local_jsonrv   ru   Zchosen_moder   r   r   r#   r   r$   rq     sp   


 rq   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   Nrc   z(' and '--format' are mutually exclusive.r   )r   rJ   rl   index)r\   r   r   Z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 )Nrb   c                 s   s    | ]}|j V  qd S r   r   rd   r#   r#   r$   r+     s    z&_parse_format_value.<locals>.<genexpr>zInvalid value for '--format': 'z'. Valid values: rf   )r   
ValueErrorr-   rJ   rl   )r   validr#   r#   r$   r     s   
r   errorlabelrY   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  Z30s z
Run 'z --help' for full details.z
Did you mean: rb   rg   r(   )
r4   ro   Zcommand_pathr   rI   rJ   rR   possibilitiesr-   r   )r   r   rY   Zcmd_pathlinesrC   r   r#   r#   r$   rV     s    rV   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>.FallbackTyperGroupr4   r\   r!   c                    s2   |t | j }|d urt|t ||S r   )r   rH   r   
SystemExitrP   rk   )rX   r4   r\   Zfallback_exit_code)r[   r   r#   r$   rk     s   zHfallback_typer_group_factory.<locals>.FallbackTyperGroup.resolve_commandr5   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)rP   r   r   r   )rX   r4   r5   entries)r[   r   r#   r$   r     s   "zHfallback_typer_group_factory.<locals>.FallbackTyperGroup.format_commands)r   r   r   rJ   r   r   r   r   rk   r   r   r   r#   r   r   rZ   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| |p?g |||dS )NrX   r4   r5   r!   c                 S   s   t | j|| d S r   )r9   r3   rX   r4   r5   r#   r#   r$   r   '     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_optionsr\   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   )rI   rJ   r   requiredrL   r#   r#   r$   r+   8  r   z3HFCliCommand.<locals>.parse_args.<locals>.<genexpr>)color)
Zresilient_parsingr   r   rJ   ZechoZget_helpr   exitr   
parse_args)rX   r4   r\   r#   r#   r$   r   4  s
   
z HFCliCommand.<locals>.parse_argsr   r   r&   r   r   r   )	rJ   r   r   r   r   r   r   typer   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.Nr/   z	[OPTIONS]TF)r   r&   r   r0   r3   
short_helpoptions_metavaradd_help_optionno_args_is_helpr@   
deprecatedrich_help_panelrC   r   r&   r   r0   r3   r   r   r   r   r@   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   r0   r3   r   r   r   r   r@   r   r   )rP   r   rS   r   )r   )r[   r   r   r   r3   r&   r0   r@   rC   r   r   r   rX   r   r   r#   r$   _innerb  s    
z HFCliApp.command.<locals>._inner)r.   r   r   )rX   rC   r   r&   r   r0   r3   r   r   r   r   r@   r   r   r   rZ   )r   r   r   r3   r&   r0   r@   rC   r   r   r   rX   r   r   r$   rS   M  s   BzHFCliApp.commandr   )r   r   r   r   r   TOPIC_Tr   r   r   boolr   rS   r   r#   r#   rZ   r$   r   J  sZ    
	
r   r0   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)Zmax_content_widthZhelp_option_names)
r0   r3   Zadd_completionr   r   Zrich_markup_moder   Zpretty_exceptions_enableZsuggest_commandsr   )r:   r   )r0   r3   r   r#   r#   r$   typer_factoryu  s    r   c                   @      e Zd ZdZdZdZdS )RepoTypemodeldatasetspaceN)r   r   r   r   r   r   r#   r#   r#   r$   r     s    r   zNThe ID of the repo (e.g. `username/repo-name` or `spaces/username/repo-name`).)r0   rt   r|   z2The type of repository (model, dataset, or space).zJA 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_tokenNZHF_TOKEN)huggingface_hubr   osenvironcopy)r   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.
    )r   )r   updater   r   	read_text)r   r   r   env_mapZ	env_valuer#   r#   r$   parse_env_map  s   	r  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 ) )r_   r   r#   r)   kvr#   r#   r$   rG   !  s    z-env_map_to_key_value_list.<locals>.<listcomp>rY   )r   r#   r#   r$   env_map_to_key_value_list  s   r  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:rozhf://Zbucket)modelsZdatasetsspacesZbucketsvolumeszlist[Volume] | Nonec              
   C   sp  | sdS g }| D ]}|}d}| drd}|dd }n| dr)d}|dd }|ts6td| d|ttd }|d	}|d
krOtd| d|d| }||d d }|d}|d
krntj}	|}
d}n;|d| }|tv rt| }	||d d }ntj}	|}|	dd}t|dkr|d d |d  }
|d }n|}
d}|
t|	|
|||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)
    Nz:roTz:rwFzInvalid volume format: 'zf'. Source must start with 'hf://'. Expected hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. E.g. hf://org/m:/dataz:/zF'. Expected hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. E.g. hf://org/m:/datar   rz   ry   r{   r   )r   source
mount_path	read_onlypath)endswithri   
_HF_PREFIXr   r   findr   REPO_TYPE_MODEL_HF_VOLUME_TYPESr6   r   r   )r
  r   Zraw_specspecr  Zcolon_slash_idxZsource_partr  Z	slash_idxZvol_type_strr  r  Zfirst_segment	remainingr   r#   r#   r$   parse_volumes:  sf   







	r  c                   @   r   )OutputFormatz$Output format for CLI list commands.tabler   N)r   r   r   r   r  r   r#   r#   r#   r$   r    s    r  zOutput format (table or json).c                 C   s   t |  | S )aL  Callback for the legacy FormatWithAutoOpt option type.

    Most commands now rely on the global --format / --json / -q flags consumed by _consume_format_flags_for_leaf instead
    of declaring FormatWithAutoOpt themselves.  This callback is kept for the rare cases where a command still wires
    FormatWithAutoOpt explicitly.
    )r   r   r   r#   r#   r$   _set_output_mode  s   
r  zOutput format.)r0   callbackr   r   zPrint only IDs (one per line).rC   c                 C   s   t dd| }| S )z\Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE to be used as table header.z([a-z])([A-Z])z\1_\2)rerF   upper)rC   sr#   r#   r$   
_to_header  s   r   c                 C   s   | sdS t | tr| rdS dS t | tjr| dS t | tr+td| r+| dd S t | tr:ddd	 | D S t | t	rNd
| v rIt| d
 S t
| S t| S )z/Convert a value to string for terminal display.r  u   ✔z%Y-%m-%dz^\d{4}-\d{2}-\d{2}TN
   rb   c                 s   s    | ]}t |V  qd S r   )_format_value)r)   r  r#   r#   r$   r+         z _format_value.<locals>.<genexpr>rC   )rI   r   datetimestrftimer   r  matchr   r-   r   r   dumpsr   r#   r#   r$   r"    s   




r"  max_lenc                 C   s,   t | }t||kr|d|d  d }|S )z/Format a value + truncate it for table display.Nr{   z...)r"  r   )r   r(  cellr#   r#   r$   _format_cell  s   r*  headersrow_fn
alignmentsc                    sr   | st d dS ttttttf    fdd| D }dd |D }dd |p)i  D }t t|||d dS )	ai  Print items as a formatted table.

    Args:
        items: Sequence of dictionaries representing the items to display.
        headers: List of column headers.
        row_fn: Function that takes an item dict and returns a list of string values for each column.
        alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
    zNo results found.Nc                    s   g | ]} |qS r#   r#   r)   itemr,  r#   r$   rG         z"print_as_table.<locals>.<listcomp>c                 S      g | ]}t |qS r#   r   )r)   hr#   r#   r$   rG     r1  c                 S   s   i | ]	\}}t ||qS r#   r3  r  r#   r#   r$   
<dictcomp>      z"print_as_table.<locals>.<dictcomp>)r+  r-  )printr   r   r   r   intrY   r   )rY   r+  r,  r-  rowsZscreaming_headersZscreaming_alignmentsr#   r0  r$   print_as_table  s   (r:  idformatr   id_keyc           	         s   |rD ]}t ||  qdS |tjkr"t tjtdtd dS  du r<r0td  n|g}fdd|D  |du rQdtttf dtt f fd	d
}t	 ||d dS )aP  Print list command output in the specified format.

    Args:
        items: Sequence of dictionaries representing the items to display.
        format: Output format.
        quiet: If True, print only IDs (one per line).
        id_key: Key to use for extracting IDs in quiet mode.
        headers: Optional list of column names for headers. If not provided, auto-detected from keys.
        row_fn: Optional function to extract row values. If not provided, uses _format_cell on each column.
        alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
    Nry   )indentdefaultr   c                    s&   g | ] t  fd dD r qS )c                 3   s    | ]
}t | V  qd S r   r*  r   r.  colr#   r$   r+     s    z/print_list_output.<locals>.<listcomp>.<genexpr>)r   )r)   r  rA  r$   rG     s   & z%print_list_output.<locals>.<listcomp>r/  r!   c                    s    fddD S )Nc                    s   g | ]	}t  |qS r#   r@  )r)   rB  r/  r#   r$   rG     r6  z5print_list_output.<locals>.row_fn.<locals>.<listcomp>r#   rC  )r+  rC  r$   r,    r   z!print_list_output.<locals>.row_fn)r+  r,  r-  )
r7  r  r   r'  r   r   r   r   r   r:  )	rY   r<  r   r=  r+  r,  r-  r/  Zall_columnsr#   )r+  rY   r$   print_list_output  s   
"rD  r  c                 C   sL   t | tjr
|  S t | trdd |  D S t | tr$dd | D S | S )z4Recursively serialize a value to be JSON-compatible.c                 S   "   i | ]\}}|d ur|t |qS r   _serialize_value)r)   r_   valr#   r#   r$   r5  $     " z$_serialize_value.<locals>.<dictcomp>c                 S   r2  r#   rF  r.  r#   r#   r$   rG   &  r1  z$_serialize_value.<locals>.<listcomp>)rI   r$  	isoformatr   rY   r   )r  r#   r#   r$   rG    s   

rG  infoc                 C   s   dd t |  D S )z9Convert repo info dataclasses to json-serializable dicts.c                 S   rE  r   rF  r  r#   r#   r$   r5  ,  rI  z&api_object_to_dict.<locals>.<dictcomp>)dataclassesasdictrY   )rK  r#   r#   r$   api_object_to_dict*  s   rN  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#   )striprL   r#   r#   r$   rG   5  r1  zSmake_expand_properties_parser.<locals>._parse_expand_properties.<locals>.<listcomp>,zInvalid expand property: 'z'. Valid values are: rb   c                 S   s   g | ]}t t|qS r#   )r   r1   )r)   propr#   r#   r$   rG   ;  s    )r6   typerZBadParameterr-   )r   
propertiesrR  rO  r#   r$   _parse_expand_properties2  s   z?make_expand_properties_parser.<locals>._parse_expand_properties)r   r   r1   )rO  rV  r#   rU  r$   make_expand_properties_parser/  s   "rW  library)r   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)rX  r#   r#   r$   check_cli_updateC  s
   r`  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	  t| }|d u sN |krPd S | dkrXt }nt }d|  d	| d
  d}|d ur| dkrt|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+   `  r#  z$_check_cli_update.<locals>.<genexpr>)rcdeviQ T)parentsexist_okr   zA new version of z (z&) is available! You are using version rf   z
To update, run: hf updatez
To update, run: r   )r   ZHF_HUB_DISABLE_UPDATE_CHECK	importlibmetadataversionr   r   r  existsZCHECK_FOR_UPDATE_DONE_PATHgetmtimetimer   parentmkdirtouch_fetch_latest_pypi_version#_get_huggingface_hub_update_command _get_transformers_update_commandr-   r   hint)rX  mtimeZlatest_versionZupdate_commandro   r#   rb  r$   r\  Y  s2   
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/jsonry   )timeoutrK  rj  z.Error while fetching latest version from PyPI.TrZ  N)r   r   r   r   r]  r^  r_  )rX  responser#   r#   r$   rq    s   rq  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.)rr  r   
subprocesscall)rD   r#   r#   r$   
run_update  s   
rz  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.brew)r{  upgradeZ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-Ur   Nr   r   rC   sys
executabler#   r#   r#   r$   rr    s   

rr  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  rY  Nr  r#   r#   r#   r$   rs    s   
rs  r   )NN)r;  NNN)r   rL  r$  rm   importlib.metadatarh  r   r   r  rx  r  rm  collections.abcr   r   enumr   pathlibr   typingr   r   r   r	   r
   r   r   rJ   rS  Z
typer.corer   r   r   r   r   r   Zhuggingface_hub.errorsr   Zhuggingface_hub.utilsr   r   r   r   r   Zhuggingface_hub.utils._dotenvr   _outputr   r   Z
get_loggerr^  Z_MAX_CELL_LENGTHZREPO_LIST_DEFAULT_LIMITr"   r   r   r%   r,   r   r.   r   r   r8  ZFallbackHandlerTr1   r   r   r9   compiler^   r:   r   r   __annotations__r   r   r   r   rq   r   r   rl   rV   r   r   r   ZTyperr   r   r   r   Z	RepoIdArgrK   ZRepoTypeOptZTokenOptZ
PrivateOptZRevisionOptZLimitOptZ	AuthorOptZ	FilterOptZ	SearchOptZEnvOptZ
SecretsOptZ
EnvFileOptZSecretsFileOptr   r   r  r  Z
VolumesOptr  r  ZREPO_TYPE_DATASETZREPO_TYPE_SPACEr  r  r  Z	FormatOptr  ZFormatWithAutoOptZQuietOptr   r"  r*  r:  rD  objectrG  rN  rW  r`  r\  rq  rz  rr  rs  r#   r#   r#   r$   <module>   s  $	 "
 ~
T(
$$(+#	





	


.
]


)(