
    ^ja                        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
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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(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0  e#jb                         Z2dZ3erddl4m5Z5 d{de6dz  ddfdZ7dZ8d{de9e6   de6dz  de6fdZ:ed   e6z  Z;ee9e6   e<e6   ge=dz  f   Z> ede6      Z?de6dz  dej                  dej                  ddfdZB ej                  d       ZD G d! d"e*      ZEg d#ZFe9eGe6e6f      eHd$<   dej                  ddfd%ZId&ej                  deKfd'ZLd&ej                  d(e9e6   ddfd)ZMd(e9e6   deKfd*ZNd(e9e6   d+eKd,eKddfd-ZOd.e6dd/fd0ZPd1ej                  d2e6d3e9eGe6e6f      ddfd4ZR	 d{d5e>d6eg e9eGe6e6f      f   dz  deSeE   fd7ZTd{d8e;de9e6   dz  deSe)   fd9ZUd|d:e6de6dz  d;eSeE   dz  dd"fd<ZV G d= d>ej                        ZX G d? d@e6e      ZYee6 e(dAB      f   ZZeeY e+dCdDdEB      f   Z[eeYdz   e+dCdDdEdFG      f   Z\ee6dz   e+dHB      f   Z]eeKdz   e+dIB      f   Z^ee6dz   e+dJB      f   Z_ee= e+dKB      f   Z`ee6dz   e+dLB      f   Zaee9e6   dz   e+dMB      f   Zbee6dz   e+dNB      f   Zcee9e6   dz   e+dOdPdQB      f   Zdee9e6   dz   e+dRdSdTB      f   Zeee6dz   e+dUdVB      f   Zfee6dz   e+dWB      f   Zgdehe6e6f   fdXZi	 	 d|dYe9e6   dz  dZe6dz  dehe6e6dz  f   fd[Zjd\ehe6e6dz  f   de9ehe6e6f      dz  fd]Zkee9e6   dz   e+d^d_d`B      f   Zldae9e6   dz  ddbfdcZmddee?   fdeZneedz   e+dfdgdhB      f   ZoeeK e+didjB      f   Zpdddkdldme6dne=dz  doedz  dpeKddf
dqZqdreds   ddfdtZrdreds   ddfduZsdre6de6dz  fdvZtde6dz  fdwZude=fdxZvde9e6   dz  fdyZwde9e6   dz  fdzZxy)}z*Contains CLI utilities (styling, helpers).    N)CallableSequence)Enum)Path)TYPE_CHECKING	AnnotatedAnyLiteralTypeVarcast)Volume__version__	constants)CLIError)get_sessionhf_raise_for_statusinstallation_methodloggingparse_hf_mount)load_dotenv   )Argument	HfCommandHfGroupOption)StyledContext)OutputFormat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     i/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/huggingface_hub/cli/_cli_utils.py
get_hf_apir)   8   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>O   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   D   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   _   s<    !!#LL& 	'D  &	' r*   z\s*\|\s*c                       e Zd ZdZe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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	 dddddde
dz  dede	e
   dz  de
dz  dedeedef   gedef   f   f fdZ xZS )HFCliTyperGroupa  
    CLI 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.
    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_paramsr   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           	         |r|d   j                  d      s|d   nd }|r| j                  ||      nd }|| j                  ||       	 t        |   ||      \  }}}|&t+        |t
        j,                        st/        ||       |||fS # t
        j                  $ r'}||| j                  j                         D 	
cg c]-  \  }	}
|
j                  st        j                  |	      D ]  }| / nc c}}
}	w }}
}	}t        j                  ||      }|rDdj                  d |D              }t        |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   message.z. Did you mean ?rI   rJ   rL   )
startswithrV   _rewrite_repo_type_prefixrN   resolve_commandrP   
UsageErrorrL   ra   rW   _ALIAS_SPLITrB   difflibget_close_matchesr5   setattrrm   rstriprU   rX   rY   rS   rT   _consume_format_flags_for_leaf)r\   r>   re   cmd_namer^   r_   resolved_cmdsub_argsr]   key
registeredaliasvisible_namesmatchessuggestionsr`   ra   rd   s                    r(   rr   zHFCliTyperGroup.resolve_command   s   "47+=+=c+B4719dsH-t?**35	+07+B3+M(D,4 #J|U[[,Q*<B\8++9  	{x3 ,0==+>+>+@! !'Z%,,!-!3!3C!8	!  !! ! ! "33HmL"&))+Fg+F"FKAyQYY-=-=c-B,C?S^R__`*ab !% 2 23 7#//T::GPSPZPZ 3111;<  
 $Az59)	s1   
B G$G2C6
5A;G0;F,+GG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)--typeN)rS   rP   r   opts)r1   params     r(   r3   z<HFCliTyperGroup._rewrite_repo_type_prefix.<locals>.<genexpr>   s-     q]bj=X(ejjBXXqs   46Nr   )repo_idfrom_idto_idr   --rg   =   /   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=Nrp   r1   args     r(   r3   z<HFCliTyperGroup._rewrite_repo_type_prefix.<locals>.<genexpr>  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   )anyparamssetrS   rP   r   r_   addr   is_flagr   secondary_optslenrp   appendrB   r   REPO_TYPES_MAPPINGrs   extend)r^   re   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(   rq   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   ra   rt   rB   )r\   r>   rz   r^   registered_nameregistered_cmdaliasesrd   s          r(   rV   zHFCliTyperGroup.get_command!  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   rt   rB   )r\   resultr   r   primarys        r(   
_alias_mapzHFCliTyperGroup._alias_map.  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: rh   ]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_commands7  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   rt   rB   r   r   )r\   r>   primary_namesr_   r   s        r(   rU   zHFCliTyperGroup.list_commands`  sJ    #%MM 	*D"((.q1G  )	* m$$r*   r9   )r   r+   r=   r_   r   r+   r=   kwargs.c                \    ||rt        |      }t        |   |ft        ||      |d|S )N)clsr=   )r8   rN   rR   HFCliCommand)r\   r_   r   r+   r=   r   rd   s         r(   rR   zHFCliTyperGroup.commandh  s9     >h$X.Fwt`eX)Fv`Y_``r*   r   )__name__
__module____qualname____doc__r   context_classrP   ContextrO   liststrtuplerr   staticmethodCommandrq   rV   dictr   HelpFormatterr   r   rU   TOPIC_Tr	   r   rR   __classcell__rd   s   @r(   rG   rG   j   s    "M%-- D >%,5== %,S	 %,e %,N ^/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 %  a  %)!aDja 	a
 s)d"a d
a a 
8CH%&c(::	;a ar*   rG   ))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                 z    | j                  d      5  | j                  t               d d d        y # 1 sw Y   y xY w)NzFormatting options)r   r   r   )r?   s    r(   "_format_formatting_options_sectionr     s5    			/	0 =;<= = =s   1:r^   c                     | j                   D ]J  }t        |t        j                        sg |j                  |j
                  }d|v sd|v s	d|v sd|v sJ y y)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 ls' that have their own format/quiet options.
    --formatr   --quiet-qTF)r   rS   rP   r   r   r   )r^   r   r   s      r(   _has_local_formatting_optionr     sf      %.33e223T!1Y$5F$RV, r*   re   c                    | j                   j                  d      ryt        |      }t        j                  |       d}d}d}| j
                  D ]O  }t        |t        j                        sg |j                  |j                  }d|v rd}d|v sd|v rd}d|v sNd}Q |rt        || | 	       yt        j                  }dd
t        ddffd}	d}
|
t        |      k  r||
   }|dk(  rn|dk(  rJ |	d       |
dz   t        |      k\  rt        j                   d      t#        ||
dz            }d||
|
dz   = h|j%                  d      r* |	d       t#        |t        d      d       }d||
|
dz   = |dk(  r# |	d       t        j&                  }d||
|
dz   = |dv r# |	|       t        j(                  }|||
|
dz   = |
dz  }
|
t        |      k  rt        j*                  |       y)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 ls' 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                 B    t        j                  d d|  d      y )Nrj   z' and 'z' are mutually exclusive.)rP   rs   )r   chosen_flags    r(   _check_conflictz7_consume_format_flags_for_leaf.<locals>._check_conflict  s1     """Q{m78*D]#^__ #r*   r   r   r   z#Option '--format' requires a value.r   	--format=)r   r   )context_settingsr   _consume_no_truncate_flagsr   set_no_truncater   rS   rP   r   r   r   _rewrite_legacy_shorthandsr   autor   r   rs   _parse_format_valuerp   jsonquietset_mode)r^   re   no_truncatehas_local_formathas_local_quiethas_local_jsonr   r   chosen_moder   r   r   r   s               @r(   ry   ry     s>   $  89,T2K$ON 	"%.33e223#"Ot!N	" "4.6H\kXkl !- 1 1K"K`# `$ ` 	
A
c$i-1g$;*J'1uD	!&&'LMM-d1q5k:K$KQQY>>+&J'-c#k2B2D.EFK$KQQY(?H%&++K"KQQY##C &,,KKQQY	Q= c$i-@ LLr*   c                     d}d}|t        |       k  rW| |   }|dk(  r	 |S |dk(  rd}| ||dz   = +|j                  d      rt        j                  d      |dz  }|t        |       k  rW|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   rp   rP   rs   )re   r   r   r   s       r(   r   r     s    K	A
c$i-1g$;  /!KQQY>>*+""#RSS	Q c$i- r*   r   r   c                0   t        d | D              }|r8d| v r4|rt        j                  d      | j                  d      }ddg| ||dz    d}|rHd| v rdnd	| v rd	nd
}|7|rt        j                  d| d      | j                  |      }ddg| ||dz    y
y
y
)a  Rewrite --json / -q / --quiet to --format ... for legacy commands.

    Used for commands like 'hf jobs ls' that still own their '--format' option.
    The rewrite lets users keep using the global shorthand while click parses
    '--format <value>' locally.
    c              3   L   K   | ]  }|d k(  xs |j                  d        yw)r   r   Nr   r   s     r(   r3   z-_rewrite_legacy_shorthands.<locals>.<genexpr>	  s'     ^RUSJ.M#..2MM^s   "$r   z/'--json' and '--format' are mutually exclusive.r   r   r   Tr   r   Nrj   z(' and '--format' are mutually exclusive.r   )r   rP   rs   index)re   r   r   has_format_in_argsidxflags         r(   r   r     s     ^Y]^^D(""#TUUjj")62S37!t|tyD7H)d!&&4&0X'YZZ**T"C#-w"7DsQw	  r*   valuer   c                     	 t        |       S # t        $ r: dj                  d t         D              }t        j                  d|  d| d      d w xY w)Nrh   c              3   4   K   | ]  }|j                     y wr   )r
  rk   s     r(   r3   z&_parse_format_value.<locals>.<genexpr>  s     8a!''8s   zInvalid value for '--format': 'z'. Valid values: rn   )r   
ValueErrorr5   rP   rs   )r
  valids     r(   r   r     s`    mE"" m		8<88!@GXY^X__`abhllms
   
 AAerrorlabelra   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                        rP| j                  rD|j                  ddj                  t        | j                               d       t        | dg        t        | d| j                  dj                  |      z          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: rh   ro   possibilitiesrm   r.   )r>   rm   command_pathr   rS   rP   rQ   r  r5   r   rw   )r  r  ra   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+E9emmdii.>>?r*   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>   re   r#   c                      |t        | j                  j                                     }|t        |      t        |   ||      S r   )r   rL   r   
SystemExitrN   rr   )r\   r>   re   fallback_exit_coderd   r  s       r(   rr   zHfallback_typer_group_factory.<locals>.FallbackTyperGroup.resolve_command9  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?   entriesrd   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   rr   r   r   r   )rd   r  r  s   @r(   FallbackTyperGroupr  8  sO    	6u}} 	6DI 	6% 	6	4u}} 	4ATAT 	4Y] 	4 	4r*   r"  rG   )r  r  r"  s   `` r(   fallback_typer_group_factoryr$  2  s    4_ 4 r*   r   c                    dt         j                  dt         j                  dt         j                  dd fd}dt        dt         j                  dt         j                  dd fd}dt         j                  dt         j                  dt
        t           dt
        t           fd}t        d	| j                          t        ft        | |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_epilogK  s     c9=r*   c                     t        j                  | ||       t        |       ry | j                  j	                  d      ry t        |       y )Nr   )r   format_optionsr   r   r   r   r'  s      r(   r)  z$HFCliCommand.<locals>.format_optionsN  sA      sI6 (-  $$%=>*95r*   re   c                    |sg|j                   s[t        d | j                  D              r?t        j                  |j                         |j                         |j                          t        j                  | ||      S )Nc              3   l   K   | ],  }t        |t        j                        xr |j                   . y wr   )rS   rP   r   required)r1   rb   s     r(   r3   z3HFCliCommand.<locals>.parse_args.<locals>.<genexpr>\  s'     UA:a0?QZZ?Us   24)color)
resilient_parsingr   r   rP   echoget_helpr-  exitr   
parse_args)r\   r>   re   s      r(   r2  z HFCliCommand.<locals>.parse_argsX  sW     C11UUU

3<<>;
##D#t44r*   r   )r   r   r+   r   r)  r2  )
rP   r   r   r   r   r   r   typer   r   )r   r+   r   r)  r2  s        r(   r   r   J  s    >EMM > >%J]J] >bf >6Y 6U]] 6uGZGZ 6_c 65 5U]] 5$s) 5PTUXPY 5 
E$$&'(	* B*,$	
 r*   r:   r   c                 4    |t         } || |ddddgd      S )a	  Create a CLI command group with consistent settings.

    The returned group is the app: register commands with ``@group.command(...)``,
    subgroups with ``group.add_group(sub, name=...)``, and a group-level callback
    with ``@group.callback(...)``.

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

    Returns:
        A configured `HFCliTyperGroup` instance.
    Tx   z-hz--help)max_content_widthhelp_option_names)r:   r=   no_args_is_helpr   r#  )r:   r=   r   s      r(   typer_factoryr9  o  s6     { "%"&!1
	 	r*   c                        e Zd ZdZdee   ee   z  ddf fdZde	de
j                  dz  de
j                  dz  def fd	Z x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                     t        |t              r*t        |t              r|D cg c]  }|j                   c}n
t        |      }t        |   |d       y c c}w )NT)case_sensitive)rS   r3  
issubclassr   r
  r   rN   __init__)r\   r<  rl   valuesrd   s       r(   r@  zSoftChoice.__init__  sP    *4Wd*C
SZ\`Hag&QWW&gklsgt 	 	5 's   Ar
  r   r>   c                     	 t         |   |||      S # t        j                  j                  $ r t        |      cY S w xY wr   )rN   convertrP   
exceptionsBadParameterr   )r\   r
  r   r>   rd   s       r(   rC  zSoftChoice.convert  s@    	7?5%55,, 	u:	s    (??)r   r   r   r   r   r   r3  r   r@  r	   rP   	Parameterr   rC  r   r   s   @r(   r;  r;    sb    
6T
 : 6t 6S 4)? emmVZFZ _b  r*   r;  c                       e Zd ZdZdZdZy)RepoTypemodeldatasetspaceN)r   r   r   rI  rJ  rK  r0   r*   r(   rH  rH    s    EGEr*   rH  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).rI  )r:   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                  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_hubrN  osenvironcopy)rN  extended_environr"   s      r(   _get_extended_environrU    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.
    )rR  )rU  updater   r   	read_text)rV  rW  rT  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}   r
  )ra   )r[  kvs      r(   env_map_to_key_value_listrb  8  s/    5<]]_ETQAR(EEEs   .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                 L   | syg }| D ]  }t        |      }|j                  t        |j                  j                  |j                  j
                  |j                  |j                  |j                  j                  xs d|j                  j                  xs d              |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)r3  source
mount_path	read_onlypathrevision)
r   r   r   re  r3  idrf  rg  path_in_repori  )rc  r   raw_specmounts       r(   parse_volumesrn  M  s    & F 
x(\\&&|| ++//\\..6$..6$		

 Mr*   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: rh   )rB   striprP   rE  r5   r   r;   )r
  rb   
propertiespropro  s       r(   _parse_expand_propertiesz?make_expand_properties_parser.<locals>._parse_expand_propertiesv  s    =).S)9:Aaggi:
: 	D++((06KDIIVfLgKhi 	
 9CC_d+CC ; Ds   B*B	)r   r   r;   )ro  rv  s   ` r(   make_expand_properties_parserrw  s  s/    	Dd
 	DtO7Lt7S 	D $#r*   -iz--identity-filez6Path to the SSH identity file (forwarded to `ssh -i`).z	--dry-runz,Print the SSH command instead of running it.F)portidentity_filedry_rundestinationry  rz  r{  c                   dg}||dt        |      gz  }||dt        |      gz  }|j                  |        |r)t        j                  t	        j
                  |             yt        j                  dt	        j
                  |       d       t        j                  |      }t        j                  j                  |j                        )zRun an interactive `ssh` command to `destination` (`user@host`) and exit with its return code.

    With `dry_run`, print the command instead of running it.
    sshNrx  z-pz	Running ``)code)r   r   r   textshlexr5   
subprocessrunrP   rD  Exit
returncode)r|  ry  rz  r{  r^   r   s         r(   exec_sshr    s     'C c-())c$i  JJ{C!HHyC)+,^^C F




V%6%6

77r*   library)rP  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, 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  s    r(   check_cli_updater    s2    L'" L;dKLs     11c                 P   t         j                  ry 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                          | dk(  rt!               dk(  rt#               }nt%        |       }||k(  ry | dk(  rt'               }n
t)               }d|  d	| d
 d}|#| dk(  r|dz  }n	 |ddj+                  |       z  }t-        j.                  |       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_okrP  brewzA new version of z (z&) is available! You are using version rn   z
To update, run: hf updatez
To update, run: r  )r   HF_HUB_DISABLE_UPDATE_CHECK	importlibmetadataversionr   rQ  rh  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_commandr5   r   hint)r  mtimelatest_versionupdate_commandrm   r  s        @r(   r  r    sp   ,,((009O 
;]
;; 
ww~~i::;  !E!EFIIK%9, 		-	-.55;;DSW;X	-	-.446 ##(;(=(G353G<N!B##<>9;!'"^,<<bcrbsstuG!"88/0H/IJJHHWr*   c                     	 t               j                  d|  dd      }t        |       |j                         d   d   S # t        $ r t
        j                  dd	       Y y
w xY w)zSFetch the latest version of a library from PyPI. Returns None if the request fails.zhttps://pypi.org/pypi/z/jsonr   timeoutinfor  z.Error while fetching latest version from PyPI.Tr  Nr   r   r   r   r  r  r  )r  responses     r(   r  r    sk    =$$'=gYe%LVW$XH%}}v&y11 EPTUs   ?A  A%$A%c                      	 t               j                  dd      } t        |        | j                         d   d   S # t        $ r t
        j                  dd       Y y	w xY 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  s    r(   r  r    sb    =$$%S]^$_H%}}z*844 ITXYs   ;>  A! A!c                  Z    t               } | t        d      t        j                  |       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.
    zeCannot determine how to update huggingface_hub (unknown installation method). Please update manually.)r  r   r  call)r^   s    r(   
run_updater    s2     .
/C
{s
 	
 ??3r*   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.r  )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-UrP  Nr   rQ  r_   sys
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    sL    

rww$^  mmNND%D.QQr*   r   )NN)yr   ru   importlib.metadatar  rQ  rer  r  r  r  collections.abcr   r   enumr   pathlibr   typingr   r   r	   r
   r   r   rP   rP  r   r   r   huggingface_hub.errorsr   huggingface_hub.utilsr   r   r   r   r   huggingface_hub.utils._dotenvr   
_frameworkr   r   r   r   _help_formatterr   _outputr   r   
get_loggerr  REPO_LIST_DEFAULT_LIMITr'   r!   r   r)   r4   r   r8   r   r   intFallbackHandlerTr;   r   r   rE   compilert   rG   r   r   __annotations__r   r   boolr   ry   r   r   r   rs   rY   r3  r$  r   r9  Choicer;  rH  	RepoIdArgRepoTypeOptRepoTypeOptionalOptTokenOpt
PrivateOptRevisionOptLimitOpt	AuthorOpt	FilterOpt	SearchOptEnvOpt
SecretsOpt
EnvFileOptSecretsFileOptr   rU  r]  rb  
VolumesOptrn  rw  SshIdentityFileOptSshDryRunOptr  r  r  r  r  r  r  r  r0   r*   r(   <module>r     s   1   	 	   
  .   H H  : : +  6 < < * & 
			  ,[cDj [G [ P d3i cDj C , .
!C
'T#YC13:=> +37'S4Z 'emm 'PUPcPc 'hl ' rzz+&Kag Ka\;  $uS#X"7 =%2E2E =$ =
emm  V VT#Y V4 VrT#Y 4 $8T#Y 8 8VZ 8_c 82ms m~ m@u// @ @DsTWxDY @^b @" KO&%b$uS#X*?&?@4G 
/0" "49t+; "tI "J S4Z T/=RUY=Y ev : 4sD  ]	 
A  tO
A	  $J
Y 4K
u
 $J
S 
./1
 $J
346	
 I
Z[]	
 $J
 "	 
I
>
 I
H	

 $J
7
 $J
>tCH~  !	cT	Dj 
#sTz/$FtCtO'< Fd3PS8nAUX\A\ F I
e	
#49t+ #0E #L$H_4M $( 4K
4")abd 
 
;KLN -1tej88"Tz8AE8^b8	80Lg&GH LT L,(w'HI (d (V d
 C$J  C  T#Y-= $s)d*: r*   