
    hoP                        d 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 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  ej4                  e      ZeD  cg c]  } | j:                  dk7  s| j:                    c} Z G d de      Z G d de      Z  G d de      Z!deeee"e#f         dee"   de"fdZ$ G d de      Z% G d de      Z& G d de      Z' G d de      Z(yc c} w )a  Contains commands to interact with jobs on the Hugging Face Hub.

Usage:
    # run a job
    hf jobs run <image> <command>

    # List running or completed jobs
    hf jobs ps [-a] [-f key=value] [--format TEMPLATE]

    # Stream logs from a job
    hf jobs logs <job-id>

    # Inspect detailed information about a job
    hf jobs inspect <job-id>

    # Cancel a running job
    hf jobs cancel <job-id>
    N)	Namespace_SubParsersAction)asdict)Path)DictListOptionalUnion)HfApiSpaceHardware)logging)load_dotenv   )BaseHuggingfaceCLICommandz	zero-a10gc                   "    e Zd Zedefd       Zy)JobsCommandsparserc                 v   | j                  dd      j                  d      }j                  fd       t        j	                  |       t
        j	                  |       t        j	                  |       t        j	                  |       t        j	                  |       t        j	                  |       y )NjobszRun and manage Jobs on the Hub.helpz$huggingface.co jobs related commandsc                 $    j                         S N)
print_help)argsjobs_parsers    T/var/www/Befach/backend/env/lib/python3.12/site-packages/huggingface_hub/cli/jobs.py<lambda>z2JobsCommands.register_subcommand.<locals>.<lambda>>   s    ;3I3I3K    func)

add_parseradd_subparsersset_defaultsInspectCommandregister_subcommandLogsCommand	PsCommand
RunCommandCancelCommand	UvCommand)r   jobs_subparsersr   s     @r   r&   z JobsCommands.register_subcommand8   s    ''5V'W%44:`4a 	  &K L 	**?;''8%%o6&&7))/:%%o6r   N)__name__
__module____qualname__staticmethodr   r&    r   r   r   r   7   s    7$5 7 7r   r   c                   >    e Zd Zededdfd       ZdeddfdZddZy)	r)   r   returnNc                 z   | j                  dd      }|j                  dt        d       |j                  ddd	d
       |j                  ddd	d       |j                  dt        d       |j                  dt        d       |j                  dt        ddj                  t               d       |j                  dt        d       |j                  dddd       |j                  dt        d       |j                  dt        d        |j                  d!d"d#$       |j                  t        %       y )&Nrunz	Run a Jobr   imagezThe Docker image to use.typer   -e--envappendzSet environment variables.actionr   -s	--secretsz!Set secret environment variables.
--env-file(Read in a file of environment variables.--secrets-file/Read in a file of secret environment variables.--flavorTFlavor for the hardware, as in HF Spaces. Defaults to `cpu-basic`. Possible values: , .	--timeoutzVMax duration: int/float with s (seconds, default), m (minutes), h (hours) or d (days).-d--detach
store_truez3Run the Job in the background and print the Job ID.--namespaceVThe namespace where the Job will be created. Defaults to the current user's namespace.--tokenIA User Access Token generated from https://huggingface.co/settings/tokenscommand...zThe command to run.nargsr   r    )r"   add_argumentstrjoinSUGGESTED_FLAVORSr$   r)   r   
run_parsers     r   r&   zRunCommand.register_subcommandJ   su   &&u;&?
c8RSghEabk(Ilm3=gh 0sArsghlhqhq  sD  iE  hF  FG  H 	  	

 	i 	  	

 	F	 	  	
 	i 	  	

 	\ 	  	

 		=RSZ0r   r   c                 6   |j                   | _         |j                  | _        i | _        |j                  rE| j                  j	                  t        t        |j                        j                                      |j                  xs g D ]&  }| j                  j	                  t        |             ( i | _        |j                  rE| j                  j	                  t        t        |j                        j                                      |j                  xs g D ]&  }| j                  j	                  t        |             ( |j                  | _
        |j                  | _        |j                  | _        |j                  | _        |j                  | _        y r   )r6   rP   envenv_fileupdater   r   	read_textsecretssecrets_fileflavortimeoutdetach	namespacetokenselfr   	env_valuesecrets       r   __init__zRunCommand.__init__o   s   **
"&,,-/==HHOOKT]](;(E(E(GHIRIHHOOK	23 (13LLD1B1B,C,M,M,O PQll(b(FLLF 34 )/3{{&*ll KK(,$(JJ
r   c           	         t        | j                        }|j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                        }t        d|j                          t        d|j                          | j                  ry |j                  |j                        D ]  }t        |        y )Nre   )r6   rP   r[   r_   ra   rb   rd   Job started with ID: 	View at: job_id)r   re   run_jobr6   rP   r[   r_   ra   rb   rd   printidurlrc   fetch_job_logsrg   apijoblogs       r   r5   zRunCommand.run   s    $**%kk**LLLL;;LLnn  
 	%cffX./	#''#$;; %%SVV%4C#J 5r   r3   N	r-   r.   r/   r0   r   r&   r   rj   r5   r1   r   r   r)   r)   I   s<    "1$5 "1$ "1 "1H/Y /4 /&r   r)   c                   >    e Zd Zededdfd       ZdeddfdZddZy)	r'   r   r3   Nc                     | j                  dd      }|j                  dt        d       |j                  dt        d       |j                  d	t        d
       |j                  t               y )NlogszFetch the logs of a Jobr   rp   Job IDr7   rL   QThe namespace where the job is running. Defaults to the current user's namespace.rN   rO   r    )r"   rT   rU   r$   r'   rX   s     r   r&   zLogsCommand.register_subcommand   sy    &&v4M&N
sBd 	  	

 	C&q 	  	
 	[1r   r   c                 j    |j                   | _         |j                  | _        |j                  | _        y r   rp   rd   re   rg   r   s     r   rj   zLogsCommand.__init__   s#    ;;(,$(JJ
r   c                     t        | j                        }|j                  | j                  | j                        D ]  }t        |        y Nrl   rp   rd   )r   re   ru   rp   rd   rr   )rg   rw   ry   s      r   r5   zLogsCommand.run   s:    $**%%%T[[DNN%SC#J Tr   rz   r{   r1   r   r   r'   r'      s;    2$5 2$ 2 2/Y /4 /
r   r'   rowsheadersr3   c           
         t        g | | D cg c]  }t        d |D               }}t        t        j                         j                  t        |      dz        }t        |      t        |      z   |kD  r|j                  t        |            }||xx   dz  cc<   t        |      t        |      z   |k  r#|t        |      z
  t        |      z
  ||   z   ||<   t        |      t        |      z   |kD  r dt        |      z  j                  | }g }|j                   |j                  |        |j                   |j                  |D cg c]  }d|z  	 c}        | D ]r  }	t        |	|      D 
cg c];  \  }
}t        t        |
            |kD  rt        |
      d|dz
   dz   n
t        |
      = }}
}|j                   |j                  |        t d	j                  |      S c c}w c c}w c c}}
w )
z
    Inspired by:

    - stackoverflow.com/a/8356620/593036
    - stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
    c              3   D   K   | ]  }t        t        |              y wr   )lenrU   ).0xs     r   	<genexpr>z_tabulate.<locals>.<genexpr>   s     /ac#a&k/s          z{{:{}}} -N   rQ   
)zipmaxosget_terminal_sizecolumnsr   sumindexformatr;   rU   rV   )r   r   col
col_widthsterminal_widthcol_to_minimize
row_formatlineswrowr   	col_widthrow_format_argss                r   	_tabulater      s    <?;N;Ng;NOC#/3//OJO--/77W9JKN
g,Z
(>
9$**3z?;?#)#w<#j/)^;*83z?*JSQX\*Y\fgv\w*wJ'	 g,Z
(>
9
 4*s7|+33Z@JE	LL"""G,-	LL"""j$AS1W$ABC !$C 4
9 033q6{Y/FCF?Y]#e+CPQFR
 
 	&Z&&89  99U# P %B
s   G*G/6A G4c                   ^    e Zd Zededdfd       ZdeddfdZddZde	e
e
f   defd	Zd
 Zy)r(   r   r3   Nc                 <   | j                  dd      }|j                  dddd       |j                  d	t        d
       |j                  dt        d       |j                  dddg d       |j                  dt        d       |j                  t               y )Npsz	List Jobsr   z-az--allrK   z*Show all Jobs (default shows just running)r<   rL   zUThe namespace from where it lists the jobs. Defaults to the current user's namespace.r7   rN   rO   z-fz--filterr;   z>Filter output based on conditions provided (format: key=value))r=   defaultr   z--formatz%Format output using a custom templater    )r"   rT   rU   r$   r(   rX   s     r   r&   zPsCommand.register_subcommand   s    &&t+&>
=	 	  	
 	h 	  	

 	\ 	  	
 	Q 	  	
 	8 	  	

 	Y/r   r   c                 H   |j                   | _         |j                  | _        |j                  | _        |j                  | _        i | _        |j
                  D ]H  }d|v r3|j                  dd      \  }}|| j                  |j                         <   :t        d| d       J y )N=r   z)Warning: Ignoring invalid filter format 'z'. Use key=value format.)	allrd   re   r   filtersfiltersplitlowerrr   )rg   r   fkeyvalues        r   rj   zPsCommand.__init__   s    (,$(JJ
%)[[') AaxWWS!_
U,1SYY[)A!D\]^ r   c           
         	 t        | j                        }|j                  | j                        }g d}g }|D ]  }|j                  r|j                  j
                  nd}| j                  s|dvr8|j                  }|j                  xs d}|j                  xs g }	|	rdj                  |	      nd}
|j                  xs d}|||j                         |
d}| j                  |      s|j                  |||
||g        |sad	}| j                  rDd
dj                  | j                  j!                         D cg c]  \  }}| d|  c}}       }t#        d|        y| j%                  ||       yc c}}w # t&        j(                  $ r}t#        d|        Y d}~yd}~wt*        t,        t.        f$ r}t#        d|        Y d}~yd}~wt0        $ r.}t#        dt3        |      j4                   d|        Y d}~yd}~ww xY w)z
        Fetch and display job information for the current user.
        Uses Docker-style filtering with -f/--filter flag and key=value pairs.
        rl   )rd   )zJOB IDzIMAGE/SPACECOMMANDCREATEDSTATUSUNKNOWN)RUNNINGUPDATINGzN/A )rs   r6   statusrP    z matching filters: rF   r   zNo jobs foundNzError fetching jobs data: zError processing jobs data: zUnexpected error - z: )r   re   	list_jobsrd   r   stager   rs   docker_imagerP   rV   
created_atr   _matches_filtersr;   r   itemsrr   _print_outputrequestsRequestExceptionKeyError
ValueError	TypeError	Exceptionr8   r-   )rg   rw   r   table_headersr   rx   r   rp   image_or_spacerP   command_strr   job_propertiesfilters_msgkves                    r   r5   zPsCommand.run  s   
A	Adjj)C ==4>>=:D VM D-0ZZ))Y xxF2I$I  "%!1!1!:U +++3:chhw/ !^^4u
 !+$lln*	" ,,^< V^[*fUVE J  <<$7		Z^ZfZfZlZlZnBoRVRSUVaS!:Bo8p7q"rKk]34 t]3 Cp (( 	4.qc233*i0 	60455 	A'Q(8(8'9A3?@@	AsH   D;F  =E:F  'F  :F   H
F&&H
=GH
$HH
r   c                 P   | j                   j                         D ]  \  }}||vr yd|v sd|v rQ|j                  dd      j                  dd      }t        j                  d| d||   t        j
                        rc y|j                         ||   j                         vs y y)	z+Check if job matches all specified filters.F*?z.*rG   ^$T)r   r   replaceresearch
IGNORECASEr   )rg   r   r   patternregex_patterns        r   r   zPsCommand._matches_filtersI  s     LL..0LC.( g~ 'T : B B3 Lyy1]O1!5~c7JBMMZ s(;(A(A(CC 1 r   c           	         | j                   r_| j                   }|D ]M  }|}t        g d      D ].  \  }}d| d}||v s|j                  |t        ||               }0 t	        |       O yt	        t        ||             y)z,Print output according to the chosen format.)rs   r6   rP   createdr   z{{.z}})r   N)r   	enumerater   rU   rr   r   )	rg   r   r   templater   lineifieldplaceholders	            r   r   zPsCommand._print_output\  s    ;;{{H )*Y ZHAu$)%"5K"d*#||KSVE ![ d  #r   rz   )r-   r.   r/   r0   r   r&   r   rj   r5   r   rU   boolr   r   r1   r   r   r(   r(      sb     0$5  0$  0  0D_Y _4 _FAPtCH~ $ &r   r(   c                   >    e Zd Zededdfd       ZdeddfdZddZy)	r%   r   r3   Nc                     | j                  dd      }|j                  dt        d       |j                  dt        d       |j                  d	d
d       |j                  t               y )Ninspectz0Display detailed information on one or more Jobsr   rL   r   r7   rN   rO   job_idsrQ   zThe jobs to inspectrR   r    )r"   rT   rU   r$   r%   rX   s     r   r&   z"InspectCommand.register_subcommands  sz    &&y7i&j
d 	  	

 	C&q 	  	
 		=RS^4r   r   c                 j    |j                   | _         |j                  | _        |j                  | _        y r   )rd   re   r   r   s     r   rj   zInspectCommand.__init__  s#    (,$(JJ
"&,,r   c           
      $   t        | j                        }| j                  D cg c]  }|j                  || j                        ! }}t        t        j                  |D cg c]  }t        |       c}dt                     y c c}w c c}w )Nrl   r      )indentr   )
r   re   r   inspect_jobrd   rr   jsondumpsr   rU   )rg   rw   rp   r   rx   s        r   r5   zInspectCommand.run  sg    $**%W[WcWcdVvHdddjj6#&+6q#NO e6s   $B#Brz   r{   r1   r   r   r%   r%   r  s<    5$5 5$ 5 5/Y /4 /
Pr   r%   c                   >    e Zd Zededdfd       ZdeddfdZddZy)	r*   r   r3   Nc                     | j                  dd      }|j                  dt        d       |j                  dt        d       |j                  d	t        d
       |j                  t               y )NcancelzCancel a Jobr   rp   r   r7   rL   r   rN   rO   r    )r"   rT   rU   r$   r*   rX   s     r   r&   z!CancelCommand.register_subcommand  sx    &&xn&E
sBd 	  	

 	C&q 	  	
 	]3r   r   c                 j    |j                   | _         |j                  | _        |j                  | _        y r   r   r   s     r   rj   zCancelCommand.__init__  s#    ;;$(JJ
r   c                 ~    t        | j                        }|j                  | j                  | j                         y r   )r   re   
cancel_jobrp   rd   )rg   rw   s     r   r5   zCancelCommand.run  s(    $**%dkkT^^Dr   rz   r{   r1   r   r   r*   r*     s<    4$5 4$ 4 4/Y /4 /
Er   r*   c                   8    e Zd ZdZed        ZdeddfdZddZy)	r+   z.Run UV scripts on Hugging Face infrastructure.c                 r   | j                  dd      }|j                  ddd      }|j                  dd	      }|j                  d
d       |j                  dddg        |j                  dt        d       |j                  dd       |j                  dt        ddj	                  t
               d       |j                  dddd       |j                  dddd        |j                  d!t        d"       |j                  d#t        d$       |j                  d%t        d&       |j                  d'd(d)d*       |j                  d+t        d,       |j                  d-t        d.       |j                  d/dd0d12       |j                  d3d4t        d5       |j                  t        6       y7)8zRegister UV run subcommand.uvzERun UV scripts (Python with inline dependencies) on HF infrastructurer   
uv_commandzUV commandsT)destr   requiredr5   z8Run a UV script (local file or URL) on HF infrastructurescriptz$UV script to run (local file or URL)script_argsrQ   zArguments for the script)rS   r   r   z--imagez.Use a custom Docker image with `uv` installed.r7   z--repozCRepository name for the script (creates ephemeral if not specified)rD   rE   rF   rG   r9   r:   r;   zEnvironment variablesr<   r>   r?   zSecret environment variablesr@   rA   rB   rC   rH   z Max duration (e.g., 30s, 5m, 1h)rI   rJ   rK   zRun in backgroundrL   rM   rN   zHF tokenz--withz%Run with the given packages installedwith_)r=   r   r   z-pz--pythonz5The Python interpreter to use for the run environmentr    N)r"   r#   rT   rU   rV   rW   r$   r+   )r   	uv_parser
subparsersrY   s       r   r&   zUvCommand.register_subcommand  s    %%X & 
	
 --<m^b-c
  **K + 

 	/UVUA[egh	:jkV 	  	
 	ghlhqhq  sD  iE  hF  FG  H 	  	

 	ghE\]k(Igh3=ghB 	  	

 	#<^_jL_`i 	  	

 		*E@gnuv*3-d 	  	
 	Y/r   r   r3   Nc                    |j                   | _         |j                  | _        |j                  | _        |j                  | _        |j
                  | _        i | _        |j                  rE| j                  j                  t        t        |j                        j                                      |j                  xs g D ]&  }| j                  j                  t        |             ( i | _        |j                  rE| j                  j                  t        t        |j                        j                                      |j                  xs g D ]&  }| j                  j                  t        |             ( |j                  | _        |j                  | _        |j                   | _        |j"                  | _        |j$                  | _        |j&                  | _        y)z-Initialize the command with parsed arguments.N)r   r   r  dependenciespythonr6   r[   r\   r]   r   r   r^   r_   r`   ra   rb   rc   rd   re   repo_reporf   s       r   rj   zUvCommand.__init__  sE   kk++ JJkkZZ
-/==HHOOKT]](;(E(E(GHIRIHHOOK	23 (13LLD1B1B,C,M,M,O PQll(b(FLLF 34 )/3{{&*ll KK(,$(JJ
YY
r   c                 \   t        j                  t         j                         t        | j                        }|j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                         }t#        d|j$                          t#        d|j&                          | j(                  ry|j+                  |j$                        D ]  }t#        |        y)zExecute UV command.rl   )r   r   r  r  r6   r[   r_   ra   rb   rd   r  rm   rn   Nro   )r   set_verbosityINFOr   re   
run_uv_jobr   r   r  r  r6   r[   r_   ra   rb   rd   r  rr   rs   rt   rc   ru   rv   s       r   r5   zUvCommand.run  s    gll+$**%nn;;((**;;**LL;;LLnn**  
 	%cffX./	#''#$;; %%SVV%4C#J 5r   rz   )	r-   r.   r/   __doc__r0   r&   r   rj   r5   r1   r   r   r+   r+     s0    8/0 /0bY 4 0r   r+   ))r  r   r   r   argparser   r   dataclassesr   pathlibr   typingr   r   r	   r
   r   huggingface_hubr   r   huggingface_hub.utilsr   huggingface_hub.utils._dotenvr   r   r   
get_loggerr-   loggerr   rW   r   r)   r'   rU   intr   r(   r%   r*   r+   )items   0r   <module>r     s  &  	 	 1   . .  0 ) 5 ' 
		H	%,9WDTZZ;=VTZZW 7, 7$M* M`+ 4DeCHo./ $s)  6a) aHP. P4E- E2h) hc Xs   #C/8C/