
    iۡ                      
   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+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2  e,jf                         Z4dZ5erddl6m7Z7 d}de8dz  ddfdZ9dZ:d}de;e8   de8dz  de8fdZ<ed   e8z  Z=ee;e8   e>e8   ge?dz  f   Z@ ede8      ZAde8dz  dej                  dej                  ddfdZD ej                  d      ZF G d  d!e      ZGd"ej                  d#e8d$e;eIe8e8f      ddfd%ZJ	 d}d&e@d'eg e;eIe8e8f      f   dz  deKeG   fd(ZLd}d)e=de;e8   dz  deKe   fd*ZM G d+ d,ej                        ZOd~d-e8de8dz  d.eKe   dz  dd,fd/ZP G d0 d1e8e      ZQee8 ej                  d23      f   ZSeeQ ej                  d4d5d63      f   ZUee8dz   ej                  d73      f   ZVeeWdz   ej                  d83      f   ZXee8dz   ej                  d93      f   ZYee? ej                  d:3      f   ZZee8dz   ej                  d;3      f   Z[ee;e8   dz   ej                  d<3      f   Z\ee8dz   ej                  d=3      f   Z]ee;e8   dz   ej                  d>d?d@3      f   Z^ee;e8   dz   ej                  dAdBdC3      f   Z_ee8dz   ej                  dDdE3      f   Z`ee8dz   ej                  dF3      f   Zadebe8e8f   fdGZc	 	 d~dHe;e8   dz  dIe8dz  debe8e8dz  f   fdJZddKebe8e8dz  f   de;ebe8e8f      dz  fdLZeee;e8   dz   ej                  dMdNdO3      f   ZfdPZge#j                  e#j                  e#j                  dQdRZkdSe;e8   dz  ddTfdUZl G dV dWe8e      Zmeem ej                  dX3      f   ZndYe1de1fdZZoee1 ej                  d[eo\      f   ZpeeW ej                  d]d^d_3      f   Zqd`e8de8fdaZrdYede8fdbZse5fdYedce?de8fddZt	 d}d$eebe8ef      dee;e8   dfeebe8ef   ge;e8   f   dgebe8e8f   dz  ddf
dhZu	 	 	 	 dd$eebe8ef      diemdjeWdke8dee;e8   dz  dfeebe8ef   ge;e8   f   dz  dgebe8e8f   dz  ddfdlZvdmewdewfdnZxdoedebe8ef   fdpZydqeeA   fdrZzdsedt   ddfduZ{dsedt   ddfdvZ|dse8dwe8dxe8dye;e8   ddf
dzZ}de;e8   dz  fd{Z~de;e8   dz  fd|Zy)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)ANSIdisable_progress_barsget_sessionhf_raise_for_statusinstallation_methodloggingtabulate)load_dotenv   )OutputFormatWithAutoout#   HfApitokenreturnr!   c                 ,    ddl m}  || dt              S )Nr   r    zhuggingface-cli)r"   library_namelibrary_version)huggingface_hub.hf_apir!   r   )r"   r!   s     o/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/huggingface_hub/cli/_cli_utils.py
get_hf_apir)   <   s    ,u+<kZZ    z9https://huggingface.co/docs/huggingface_hub/en/guides/cliexamplesdocs_anchorc                 h    |r
t          | nt         }dj                  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              3   &   K   | ]	  }d |   yw)z  $ N ).0exs     r(   	<genexpr>z"generate_epilog.<locals>.<genexpr>S   s     <RtB4[<s   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_strs       r(   generate_epilogr8   H   sS     7B#$[M2GXH99<8<<L  &J ' r*   )mainhelpExpandPropertyT)boundepilogctx	formatterc                 x    | r8|j                          | j                  d      D ]  }|j                  |        yy)z%Write the epilog without indentation.r.   N)write_paragraphsplit
write_text)r=   r>   r?   lines       r(   _format_epilog_no_indentrE   c   s<    !!#LL& 	'D  &	' r*   z\s*\|\s*c                       e Zd ZdZdej
                  ddf fdZdej
                  dee   de	f fdZ
edej                  dee   ddfd	       Zedej                  dee   ddfd
       Zedej                  dee   ddfd       Zdej
                  dedej                  dz  f fdZdeeee   f   fdZdej
                  dej&                  ddfdZdej
                  dej&                  ddfdZdej
                  dee   fdZ x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"``).
    - rewrites ``--json`` to ``--format json`` for commands that accept ``--format``.
    - 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.
    r>   r#   Nc                    	 t         	|   |      S # t        j                  $ rP}|j                  =|j                  j
                  &|j                  j
                  }t        |t        j                        rx|j                  |j                        D cg c]@  }|j                  |j                  |      x} |j                  s||j                  d      fB nc c}w }}t        |d|        |j                  |j                        D cg c]G  }t        |t        j                        r+|j                  s|j                  |j                        x}r|I nc c}w }}t        |d|        d}~ww xY 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.
        NP   limitcommandsoptions)superinvokeclickNoSuchOptionr>   command
isinstanceGrouplist_commandsget_commandhiddenget_short_help_str_enrich_usage_error
get_paramsOptionget_help_record)
selfr>   ecmdnamesubitemsprecord	__class__s
            r(   rO   zHFCliTyperGroup.invokez   sN   	7>#&&!! 	uu QUU]]%>eemmc5;;/ %($5$5aee$< #&??155$#??CLUXU_U_ s55B5?@ E 
 (:u= 	 "%!6%a6qxxWXWhWhijininWoMoVMo  E 
 (9e<'	s/    E6A1E1AC3E1AEE11E6argsc           	      l   |r|d   j                  d      s|d   nd }|r| j                  ||      nd }|6| j                  ||       | j                  ||       | j	                  ||       	 t
        |   ||      S # t        j                  $ r!}||| j                  j                         D cg c]-  \  }}|j                  st        j                  |      D ]  }| / nc c}}}w }	}}}t        j                  ||	      }
|
r>dj!                  d |
D              }|j"                  j%                  d       d| d|_        | j'                  |      D cg c]6  }| j                  ||      x} |j                  s||j)                  d	      f8 nc c}w }}t+        |d
|        d }~ww xY w)Nr   -, c              3   (   K   | ]
  }d | d   yw)'Nr0   )r1   ms     r(   r3   z2HFCliTyperGroup.resolve_command.<locals>.<genexpr>   s     +Fas!H+Fs   .z. Did you mean ?rI   rJ   rL   )
startswithrV   _rewrite_json_shorthand_rewrite_quiet_shorthand_rewrite_repo_type_prefixrN   resolve_commandrP   
UsageErrorrL   rb   rW   _ALIAS_SPLITrB   difflibget_close_matchesr5   messagerstriprU   rX   rY   )r]   r>   rf   cmd_namer_   r^   key
registeredaliasvisible_namesmatchessuggestionsr`   ra   rb   re   s                  r(   rs   zHFCliTyperGroup.resolve_command   s   "47+=+=c+B4719dsH-t?((d3))#t4**35	7*355 	{x3 ,0==+>+>+@! !'Z%,,!-!3!3C!8	!  !! ! ! "33HmL"&))+Fg+F"FK#$99#3#3C#8"9UV WAI !% 2 23 7#//T::GPSPZPZ 3111;<  
 $Az59)	s1   .A> >F3$F.62C)
(A5F.;FF..F3r_   c                     d|vryt        d | j                  D              }|rCt        d |D              rt        j                  d      |j	                  d      }ddg|||dz    yy)	a2  Rewrite hidden ``--json`` shorthand to ``--format json``.

        Only applies to commands that accept ``--format``.  This avoids rewriting
        ``--json`` for commands that pass args through to external binaries
        (e.g. ``hf extensions exec``) or that simply don't support ``--format``.
        z--jsonNc              3   p   K   | ].  }t        |t        j                        xr d |j                  v  0 yw--formatNrS   rP   r[   optsr1   params     r(   r3   z:HFCliTyperGroup._rewrite_json_shorthand.<locals>.<genexpr>   0     uaf
5%,, ? \JRWR\R\D\ \u   46c              3   L   K   | ]  }|d k(  xs |j                  d        ywr   z	--format=Nro   r1   args     r(   r3   z:HFCliTyperGroup._rewrite_json_shorthand.<locals>.<genexpr>   &     T3*$C{(CCT   "$z/'--json' and '--format' are mutually exclusive.r   jsonr   anyparamsrP   rt   index)r_   rf   has_format_optionidxs       r(   rp   z'HFCliTyperGroup._rewrite_json_shorthand   sr     4ujmjtjtuuTtTT&&'XYY**X&C#-v"6DsQw	 r*   c                 .   d|v xs d|v }|syt        d | j                  D              }t        d | j                  D              }|rN|sKt        d |D              rt        j                  d      d|v rdnd}|j	                  |      }dd	g|||d
z    yyy)zRewrite ``-q`` / ``--quiet`` shorthand to ``--format quiet``.

        Only applies to commands that accept ``--format`` but do NOT already
        have their own ``--quiet`` / ``-q`` option.
        -q--quietNc              3   p   K   | ].  }t        |t        j                        xr d |j                  v  0 ywr   r   r   s     r(   r3   z;HFCliTyperGroup._rewrite_quiet_shorthand.<locals>.<genexpr>   r   r   c              3      K   | ]>  }t        |t        j                        xr d |j                  v xs d|j                  v  @ yw)r   r   Nr   r   s     r(   r3   z;HFCliTyperGroup._rewrite_quiet_shorthand.<locals>.<genexpr>   sB      
diJuell+_ejj1H1^DTYT^T^L^_
s   AAc              3   L   K   | ]  }|d k(  xs |j                  d        ywr   r   r   s     r(   r3   z;HFCliTyperGroup._rewrite_quiet_shorthand.<locals>.<genexpr>   r   r   z0'--quiet' and '--format' are mutually exclusive.r   quietr   r   )r_   rf   	has_quietr   has_quiet_optionflagr   s          r(   rq   z(HFCliTyperGroup._rewrite_quiet_shorthand   s     DL5I$5	ujmjtjtuu 
mpmwmw
 
 %5TtTT&&'YZZ4<4YD**T"C#-w"7DsQw &6r*   c                    t        d | j                  D              }|syt               }d}| j                  D ]A  }t        |t        j
                        s|j                  dv r|j                  |       |dz  }C |syt               }| j                  D ][  }t        |t        j                        s|j                  r+g |j                  |j                  D ]  }|j                  |        ] d}g }	d}
|
t        |      k  r^||
   }|dk(  rnS|j                  d      rd|v s||vr|
dz  }
n%|
d	z  }
n||v r|	j                  |
       |dz  }|
dz  }
|
t        |      k  r^|	syd}d}g }|	D ]  }||   j                  d
d	      }t        |      dk7  s|d   t         j"                  vr<|d   }t         j"                  |   }|!||k7  rt	        j$                  d| d| d      |}|}|j                  ||d    d
|d	    f        |syt        d |D              rt	        j$                  d| d      |D ]
  \  }}|||<    |j'                  d|g       y)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              3   p   K   | ].  }t        |t        j                        xr d |j                  v  0 yw)--typeNr   r   s     r(   r3   z<HFCliTyperGroup._rewrite_repo_type_prefix.<locals>.<genexpr>   s-     q]bj=X(ejjBXXqr   Nr   )repo_idfrom_idto_idr   z--rh   =   /   z!Conflicting repo type prefixes: 'z/' and 'z/'.c              3      K   | ]6  }|d k(  xs+ |j                  d      xs |dk(  xs |j                  d       8 yw)r   z--type=--repo-typez--repo-type=Nr   r   s     r(   r3   z<HFCliTyperGroup._rewrite_repo_type_prefix.<locals>.<genexpr>4  sI      
 8Ors~~i8rC=<PrTWTbTbcqTrr
s   <>z!Ambiguous repo type: got prefix 'z8/' in repo ID and explicit --type. Use one or the other.r   )r   r   setrS   rP   Argumentr`   addr[   is_flagr   secondary_optslenro   appendrB   r   REPO_TYPES_MAPPINGrt   extend)r_   rf   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_values                       r(   rr   z)HFCliTyperGroup._rewrite_repo_type_prefix   s   " qfifpfpqq '*eZZ 	E%0::!@@%))'21		 ! #&%ZZ 	+E%.u}}?UZZ?%*>*>? +C!%%c*+	+ )+#d)mq'Cd{~~c"#:M!9FAFA#'88'..q1 A% Q #d)m # %)#'*,, 
	CIO))#q1E5zQ%()2N2N"N1XF#66v>K([M-I&&)J<.X`ag`hhk'lmm'M!LOOY58*AeAhZ(@AB
	C   

 
 ""3L>Ayz 
 %- 	( Iy'DO	(X}-.r*   rz   c                     t         |   ||      }||S | j                  j                         D ]"  \  }}t        j                  |      }||v s |c S  y N)rN   rV   rL   rb   ru   rB   )r]   r>   rz   r_   registered_nameregistered_cmdaliasesre   s          r(   rV   zHFCliTyperGroup.get_commandA  sd    g!#x0?J 04}}/B/B/D 	&+O^"((9G7"%%	& r*   c                 p    i }| j                   D ]$  }t        j                  |      }|d   }|dd ||<   & |S )zBBuild a mapping from primary command name to its aliases (if any).r   r   N)rL   ru   rB   )r]   resultr   r   primarys        r(   
_alias_mapzHFCliTyperGroup._alias_mapN  sI    ')#}} 	(O &&7EAhG#ABiF7O	( r*   r?   c                    i }| j                         }| j                  |      D ]  }| j                  ||      }||j                  r$|j	                  |j
                        }|j                  |g       }|r| ddj                  |       d}t        |dd      }	|j                  |	g       j                  ||f        |j                  d      5  |j                  |d          d d d        t        |j                               D ]G  }	|	dk(  r	|j                  |	j                          d      5  |j                  ||	          d d d        I y # 1 sw Y   mxY w# 1 sw Y   `xY w)	NrJ   z	 [alias: ri   ]topicr9   zMain commandsz	 commands)r   rU   rV   rW   rX   widthgetr5   getattr
setdefaultr   sectionwrite_dlsortedkeys
capitalize)
r]   r>   r?   topics	alias_mapr`   r_   	help_textr   r   s
             r(   format_commandszHFCliTyperGroup.format_commandsW  si   "$OO%	&&s+ 		CD""3-C{cjj..Y__.EImmD"-G(k499W3E2FaH	C&1EeR(//y0AB		C / 	/vf~.	/FKKM* 	2E""e&6&6&8%9#CD 2""6%=12 2	2	/ 	/
2 2s   E3EEE(	c                 <   g }| j                  |      D ]G  }| j                  ||      }||j                  r$t        |dg       }|s4|j	                  |d          I |rt        |      }t        |||       y | j                  rt        | j                  ||       y y )Nr+   r   )rU   rV   rW   r   r   r8   rE   r=   )r]   r>   r?   all_examplesr`   r_   cmd_examplesr=   s           r(   format_epilogzHFCliTyperGroup.format_epilogn  s     #%&&s+ 	5D""3-C{cjj"3
B7L##LO4	5 $\2F$VS)<[[$T[[#yA r*   c                     g }| j                   D ]+  }t        j                  |      d   }|j                  |       - t	        |      S )Nr   )rL   ru   rB   r   r   )r]   r>   primary_namesr`   r   s        r(   rU   zHFCliTyperGroup.list_commands  sJ    #%MM 	*D"((.q1G  )	* m$$r*   )__name__
__module____qualname____doc__rP   ContextrO   liststrtuplers   staticmethodCommandrp   rq   rr   rV   dictr   HelpFormatterr   r   rU   __classcell__re   s   @r(   rG   rG   n   s   	%-- D >5== S	 e B 7U]] 7$s) 7 7 7  8emm 849 8 8 8( ^/u}} ^/DI ^/$ ^/ ^/@u}}  PT@T Dd3i0 25== 2U=P=P 2UY 2.B B5;N;N BSW B$% %49 %r*   rG   errorlabelrb   c                    |r| j                   d| d| j                  v ry| j                   j                  }d| d| dg}|D ]  \  }}|j                  d|dd	|         |j                  d
| d       t	        | t
        j                        rJ| j                  r>|j                  ddj                  t        | j                               d       g | _        | xj                  dj                  |      z  c_        y)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: ri   rn   r.   )
r>   rx   command_pathr   rS   rP   rQ   possibilitiesr5   r   )r   r   rb   cmd_pathlinesr`   r   s          r(   rY   rY     s    EII%:eWD)AU]])Ryy%%HeWF8*B78E  2ir$s1YK012	LL78*$>?@%++,1D1D'		&9L9L2M(N'OqQR 	MMTYYu%%Mr*   fallback_handlerextra_commands_providerc                 .      G  fddt               }|S )zRReturn a Typer group class that runs a fallback handler before command resolution.c                        e Zd Zdej                  dee   def fdZdej                  dej                  ddf fdZ
 xZS )8fallback_typer_group_factory.<locals>.FallbackTyperGroupr>   rf   r#   c                      |t        | j                  j                                     }|t        |      t        |   ||      S r   )r   rL   r   
SystemExitrN   rs   )r]   r>   rf   fallback_exit_codere   r   s       r(   rs   zHfallback_typer_group_factory.<locals>.FallbackTyperGroup.resolve_command  sF    !1$DMM<N<N<P8Q!R!- !3447*355r*   r?   Nc                     t         |   ||       6        }|r,|j                  d      5  |j                  |       d d d        y y y # 1 sw Y   y xY w)NzExtension commands)rN   r   r   r   )r]   r>   r?   entriesre   r   s       r(   r   zHfallback_typer_group_factory.<locals>.FallbackTyperGroup.format_commands  sd    G#C3&213"**+?@ 4!**734 4  34 4s   AA)r   r   r   rP   r   r   r   r   rs   r   r   r   )re   r   r   s   @r(   FallbackTyperGroupr    sO    	6u}} 	6DI 	6% 	6	4u}} 	4ATAT 	4Y] 	4 	4r*   r  )rG   )r   r   r  s   `` r(   fallback_typer_group_factoryr	    s    4_ 4 r*   r   c                     dt         j                  dt         j                  dt         j                  dd fd}t	        d| j                          t        f| |xs g |d      S )Nr]   r>   r?   r#   c                 2    t        | j                  ||       y r   )rE   r=   )r]   r>   r?   s      r(   r   z#HFCliCommand.<locals>.format_epilog  s     c9=r*   r   r   r+   r   )rP   r   r   r   typer   r   r  s      r(   HFCliCommandr    sh    >EMM > >%J]J] >bf > 
u'')*+	X^mT r*   c            "            e Zd ZdZ	 dddddddddddddddedz  d	ed
ee   dz  deeef   dz  dedz  dedz  dedz  dede	de	de	de	dedz  de
e
def   ge
def   f   f fdZ xZS )HFCliAppz&Custom Typer app for Hugging Face CLI.Nr9   z	[OPTIONS]TF)r   r+   context_settingsr:   r=   
short_helpoptions_metavaradd_help_optionno_args_is_helprW   
deprecatedrich_help_panelr`   r   r+   r  r:   r=   r  r  r  r  rW   r  r  r#   .c                    	
 rt              dt        dt        f   dt        dt        f   f	
 fd}|S )Nfunc.r#   c                 `    t        t          	t              
      |       S )N)clsr  r:   r=   r  r  r  r  rW   r  r  )rN   r  rR   r  )r  re   r  r  r  r=   r+   r:   rW   r`   r  r  r  r]   r  r   s    r(   _innerz HFCliApp.command.<locals>._inner  sQ    40 1!1% / / /% / 1   r*   )r8   r   r	   )r]   r`   r   r+   r  r:   r=   r  r  r  r  rW   r  r  r  re   s   `````````````` r(   rR   zHFCliApp.command  sM    $ >h$X.F	#s(+ 	c0B 	 	 	  r*   r   )r   r   r   r   r   TOPIC_Tr   r   r	   boolr   rR   r   r   s   @r(   r  r    s   0  %  %)26!!%* $ % &*%Dj% 	%
 s)d"% sCx.4/% Dj% d
% $J% % % % % % t%  
8CH%&c(::	;!% %r*   r  r:   r  c                 F    |t         }t        | |dd|dddddddg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)
r:   r=   add_completionr  r  rich_markup_moder  pretty_exceptions_enablesuggest_commandsr  )rG   r  )r:   r=   r  s      r(   typer_factoryr'    sJ     {!&  "%"&!1
 r*   c                       e Zd ZdZdZdZy)RepoTypemodeldatasetspaceN)r   r   r   r*  r+  r,  r0   r*   r(   r)  r)  	  s    EGEr*   r)  zNThe ID of the repo (e.g. `username/repo-name` or `spaces/username/repo-name`).)r:   r   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                  j    ddl m}  t        j                  j	                         } |        x}||d<   |S )zQReturn a copy of ``os.environ`` with the user's HF token injected (if available).r   )	get_tokenHF_TOKEN)huggingface_hubr.  osenvironcopy)r.  extended_environr"   s      r(   _get_extended_environr5  r  s4    )zz()',$r*   envenv_filec                     t               }i }|r3|j                  t        t        |      j	                         |             | xs g D ]  }|j                  t        ||               |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.
    )r2  )r5  updater   r   	read_text)r6  r7  r4  env_map	env_values        r(   parse_env_mapr=  |  sd     -.%'G{4>#;#;#=GWXYYB I	{96FGHINr*   r;  c                 h    | sy| j                         D cg c]  \  }}||xs dd c}}S c c}}w )z_Convert an env/secrets dict to the ``[{"key": ..., "value": ...}]`` format used by the Hub API.N )r{   value)rb   )r;  kvs      r(   env_map_to_key_value_listrC    s/    5<]]_ETQAR(EEEs   .z-vz--volumeaU  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://gpt2:/data or -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:rozhf://bucket)modelsdatasetsspacesbucketsvolumeszlist[Volume] | Nonec           
         | syg }| D ]S  }|}d}|j                  d      rd}|dd }n|j                  d      rd}|dd }|j                  t              st        d| d      |t	        t              d }|j                  d	      }|d
k(  rt        d| d      |d| }||dz   d }|j                  d      }|d
k(  rt        j                  }	|}
d}ni|d| }|t        v rt        |   }	||dz   d }nt        j                  }	|}|j                  dd      }t	        |      dk\  r|d   dz   |d   z   }
|d   }n|}
d}|j                  t        |	|
|||             V |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://gpt2:/data                          (model, implicit type)
        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: 'ze'. Source must start with 'hf://'. Expected hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. E.g. hf://gpt2:/dataz:/zE'. Expected hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. E.g. hf://gpt2:/datar   r   r   r   r   )r  source
mount_path	read_onlypath)endswithro   
_HF_PREFIXr   r   findr   REPO_TYPE_MODEL_HF_VOLUME_TYPESrB   r   r   )rI  r   raw_specspecrO  colon_slash_idxsource_partrN  	slash_idxvol_type_strrM  rP  first_segment	remainingr   s                  r(   parse_volumesr^    s   * F A
	==I9D]]5!I9D z**8* 5U V  C
O%& ))D/b *8*4yz  +O,/A-/0
  $$S)	?$44L FD'
3M 00/>'	A8	  )88'	
 OOC+E5zQqC%(2Qx"!%#	
sA
D Mr*   c                       e Zd ZdZdZdZy)OutputFormatz$Output format for CLI list commands.tabler   N)r   r   r   r   ra  r   r0   r*   r(   r`  r`  	  s    .EDr*   r`  zOutput format (table or json).r@  c                     t        j                  |        t         j                  t        j                  k7  r
t                | S r   )r   set_modemoder   humanr   r@  s    r(   _set_output_moderg    s,    LL
xx'---Lr*   zOutput format.)r:   callbackr   r   zPrint only IDs (one per line).r`   c                 P    t        j                  dd|       }|j                         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)rera   upper)r`   ss     r(   
_to_headerrm  1  s!    
 (D1A779r*   c                    | syt        | t              r| rdS dS t        | t        j                        r| j                  d      S t        | t              rt        j                  d|       r| dd S t        | t              rdj                  d | D              S t        | t              r'd	| v rt	        | d	         S t        j                  |       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
   ri   c              3   2   K   | ]  }t        |        y wr   )_format_value)r1   rB  s     r(   r3   z _format_value.<locals>.<genexpr>B  s     9aq)9s   r`   )rS   r  datetimestrftimer   rj  matchr   r5   r   r   dumpsrf  s    r(   rq  rq  7  s    %u%2%%**+~~j))%"((+A5"ISbz%yy95999	E4	 U?uV}%%zz%  u:r*   max_lenc                 N    t        |       }t        |      |kD  r|d|dz
   dz   }|S )z/Format a value + truncate it for table display.Nr   z...)rq  r   )r@  rv  cells      r(   _format_cellry  K  s2    D
4y7Mgk"U*Kr*   headersrow_fn
alignmentsc           	      |   | st        d       yt        t        t        t        t        t
        f         | D cg c]
  } ||       c}      }|D cg c]  }t        |       }}|xs i j                         D 	ci c]  \  }}	t        |      |	 }
}}	t        t        |||
             yc c}w c c}w c c}	}w )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.N)rz  r|  )	printr   r   r   r   intrm  rb   r   )rb   rz  r{  r|  itemrowshscreaming_headersrA  rB  screaming_alignmentss              r(   print_as_tabler  S  s     !"T%S/*+u-MtfTl-MND0781A88:D:J9Q9Q9STAJqM1,TT	(4!2?S
TU	 .N8Ts   B.
B3=B8formatr   id_keyc                   	 |r| D ]  }t        ||           y|t        j                  k(  r/t        t        j                  t	        |       dt
                     yG| rt	        | d   j                               n|g}|D 		cg c]  	t        	fd| D              s	 c}	|&dt        t
        t        f   dt        t
           ffd}t        | ||	       yc c}	w )
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".
    Nr   )indentdefaultr   c              3   R   K   | ]  }t        |j                                 y wr   ry  r   )r1   r  cols     r(   r3   z$print_list_output.<locals>.<genexpr>  s     4cUY\$((3-5P4cs   $'r  r#   c                 ^    D cg c]  }t        | j                  |             c}S c c}w r   r  )r  r  rz  s     r(   r{  z!print_list_output.<locals>.row_fn  s$    ;BCCL#/CCCs   !*)rz  r{  r|  )r~  r`  r   ru  r   r   r   r   r   r	   r  )
rb   r  r   r  rz  r{  r|  r  all_columnsr  s
       `    `r(   print_list_outputr  k  s    (  	 D$v,	 """djjeQ<=/4d58==?+6("-d34c]b4c1c3d~	Dc3h 	DDI 	D 5'&ZP es   CCrB  c                 B   t        | t        j                        r| j                         S t        | t              r0| j	                         D ci c]  \  }}|	|t        |       c}}S t        | t              r| D cg c]  }t        |       c}S | S c c}}w c c}w )z4Recursively serialize a value to be JSON-compatible.)rS   rr  	isoformatr   rb   _serialize_valuer   )rB  r{   valr  s       r(   r  r    s    !X&&'{{}	At	;<779XxsC%c**XX	At	3454 &55H Y5s   
BB?Binfoc                     t        j                  |       j                         D ci c]  \  }}|	|t        |       c}}S c c}}w )z9Convert repo info dataclasses to json-serializable dicts.)dataclassesasdictrb   r  )r  rA  rB  s      r(   api_object_to_dictr    s?    /:/A/A$/G/M/M/Oatq!STS`A""aaas
   
AAvalid_propertiesc                 F     dt         dz  dt        t           dz  f fd}|S )zJCreate a callback to parse and validate comma-separated expand properties.r@  Nr#   c           	         | y | j                  d      D cg c]  }|j                          }}|D ]0  }|vst        j                  d| ddj	                                |D cg c]  }t        t        |       c}S c c}w c c}w )N,zInvalid expand property: 'z'. Valid values are: ri   )rB   striptyperBadParameterr5   r   r;   )r@  rc   
propertiespropr  s       r(   _parse_expand_propertiesz?make_expand_properties_parser.<locals>._parse_expand_properties  s    =).S)9:Aaggi:
: 	D++((06KDIIVfLgKhi 	
 9CC_d+CC ; Ds   B*B	)r   r   r;   )r  r  s   ` r(   make_expand_properties_parserr    s/    	Dd
 	DtO7Lt7S 	D $#r*   library)r0  transformersc                 h    	 t        |        y# t        $ r t        j                  dd       Y yw xY w)a  
    Check whether a newer version of a library is available on PyPI.

    If a newer version is found and stdin/stderr are attached to a TTY, prompt the user to update interactively.
    Otherwise (non-TTY or update command cannot be determined), print a warning to stderr.

    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.

    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  s    r(   check_cli_updater    s2    L'" L;dKLs     11c                 l   t         j                  j                  |       t        fddD              ry t        j
                  j                  t        j                        rHt        j
                  j                  t        j                        }t        j                         |z
  dk  ry t        t        j                        j                  j                  dd       t        t        j                        j                          t               j!                  d|  dd	      }t#        |       |j%                         }|d
   d   }|k(  ry | dk(  rt'               }n
t)               }t*        j,                  j/                         r/t*        j0                  j/                         r|t3        | ||       y |rdj5                  |      nd }|rdt7        j8                  |       nd}t;        j<                  t7        j>                  d|  d| d d|rd| ndz   dz         t*        j0                         y )Nc              3   &   K   | ]  }|v  
 y wr   r0   )r1   tagcurrent_versions     r(   r3   z$_check_cli_update.<locals>.<genexpr>  s     
;c3/!
;s   )rcdeviQ T)parentsexist_okzhttps://pypi.org/pypi/z/jsonr   )timeoutr  versionr0  r   zTo update, run: r?  zA new version of z (z&) is available! You are using version rm   r.   file) 	importlibmetadatar  r   r1  rP  existsr   CHECK_FOR_UPDATE_DONE_PATHgetmtimetimer   parentmkdirtouchr   r   r   r   #_get_huggingface_hub_update_command _get_transformers_update_commandsysstdinisattystderr_prompt_autoupdater5   r   boldrP   echoyellow)	r  mtimeresponsedatalatest_versionupdate_commanddisplay_cmdupdate_hintr  s	           @r(   r  r    s   ((009O 
;]
;; 
ww~~i::;  !E!EFIIK%9, 		-	-.55;;DSW;X	-	-.446 }  #9'%!HRS TH!==?D&\),N.(##<>9;
yycjj//1n6P7O^^T2@chh~.dEP(;)?(@AVX

KK#G9B~.> ?))8(9<U`K=?Qfhjlpq 	
r*   r  r  r  c           
         dj                  |      }t        j                  dt        j                         t        j                  t        j                  d|  d| d|       t        j                         t        j                  dt        j                         t        j                  t        j                  d      t        j                  d| d	      z   dz   t        j                  d
       	 t        j                  j                         }|dk(  r&t        j                  dt        j                         y|j                         j                         }|dv rpt        j                  dt        j                         t        j                  t        j                  d|       t        j                         t        j                  dt        j                         t        j                  |      }|dk(  rot        j                  dt        j                         t        j                  t        j                   d|  d| d      t        j                         t#        d      t        j                  dt        j                         t        j                  t        j$                  d| d      t        j                         n;t        j                  t        j                  d|       t        j                         t        j                  dt        j                         y# t        t        f$ r( t        j                  dt        j                         Y yw xY w)a  Interactively ask the user if they want to update, and run the update command if accepted.

    After a successful update the CLI exits so the user can re-run their command with the new version.
    All output goes to stderr to keep stdout clean for command output.
    r   r?  r  z  A new version of z is available: u    → z#  Do you want to update now? [Y/n] ()F)r  nlN)r?  yyesz  Running: r   u     ✓ Successfully updated z to z. Please re-run your command.u     ✗ Update failed (exit code z). Please update manually.z&  Skipped. You can update later with: )r5   rP   r  r  r  r   r  grayr  readlineEOFErrorKeyboardInterruptr  lower
subprocesscallgreenr  red)r  r  r  r  r  
raw_answeranswer
returncodes           r(   r  r    sV    ((>*K	JJr

#	JJ)'//ARRWXfWghiZZ 
JJr

#	JJ9:TYY;-WXGY=ZZ]``ZZ
YY'')

 R

2CJJ'%%'F!!

2CJJ'

499{;-89

K

2CJJ'__^4
?JJr

+JJ

8	nEUUrstZZ Q-JJr

+JJ::,F`abZZ
 	

II>{mLM	
 
JJr

#C '( 

2CJJ's   4L1 14M('M(c                      t               xdk(  r g dS xdk(  rt        j                  dk(  r g dS xdk(  r g dS dk(  rt        j                  ddd	d
dgS 	 y)zlReturn the command to update huggingface_hub as an argv list, or None if the installation method is unknown.brew)r  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-Ur0  Nr   r1  r`   r  
executabler0   r*   r(   r  r  :  sP    

,,rww$^llUUNND%DBSTTr*   c                      t               xdk(  rt        j                  dk(  r g dS xdk(  r g dS dk(  rt        j                  ddddd	gS 	 y
)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  r0   r*   r(   r  r  I  sL    

rww$^  mmNND%D.QQr*   r   )NN)idNNN)r   r  rr  rv   importlib.metadatar  r   r1  rj  r  r  r  collections.abcr   r   enumr   pathlibr   typingr   r   r	   r
   r   r   r   rP   r  
typer.corer   r   r0  r   r   r   huggingface_hub.errorsr   huggingface_hub.utilsr   r   r   r   r   r   r   huggingface_hub.utils._dotenvr   _outputr   r   
get_loggerr  _MAX_CELL_LENGTHr'   r!   r   r)   r4   r   r8   r  r   r  FallbackHandlerTr;   r   r   rE   compileru   rG   rt   r   rY   r  r	  r  Typerr  r'  r)  r   	RepoIdArgr[   RepoTypeOptTokenOptr  
PrivateOptRevisionOptLimitOpt	AuthorOpt	FilterOpt	SearchOptEnvOpt
SecretsOpt
EnvFileOptSecretsFileOptr   r5  r=  rC  
VolumesOptrR  rT  REPO_TYPE_DATASETREPO_TYPE_SPACErU  r^  r`  	FormatOptrg  FormatWithAutoOptQuietOptrm  rq  ry  r  r  objectr  r  r  r  r  r  r  r  r0   r*   r(   <module>r     sb   1      	 	  
  .   O O O   / : : +   6 . 
			  ,[cDj [G [ P d3i cDj C , .
!C
'T#YC13:=> +37'S4Z 'emm 'PUPcPc 'hl ' rzz+&X%j X%v&u// & &DsTWxDY &^b &" KO&%b$uS#X*?&?@4G 
/0 49t+; tLGY (u{{ (V   S4Z  T*=MPT=T  `j  FsD  ENN]	 ELLA $JELLY 4KELLu
 $JELLS ELL457
 $JELL9:<	
 IELL`ac	
 $JELLo&(	 
IELL>
 IELLH	

 $JELL7
 $JELL>tCH~  !	cT	Dj 
#sTz/$FtCtO'< Fd3PS8nAUX\A\ F IELLd	
 
''++''	 [49t+ [0E [|3  ELL-	0 5I  ELL!  ELL-S S   ( -=  c   )-	VDcN#V#YV d38n%tCy01V S#X%	V
 
V8  $;?(,&QDcN#&Q&Q &Q 	&Q
 #Y&Q d38n%tCy01D8&Q S#X%&Q 
&QR 6 bS bT#s(^ b
$H_4M $(Lg&GH LT L,*
w'HI *
d *
Z<$<$<$ <$ I	<$
 
<$~T#Y-= $s)d*: r*   