
    rh"T                        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mZ ddlmZ dd	lmZ d
dlmZ  ej6                  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)dee#e#f   fd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	get_token)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    k/var/www/html/ai-insurance-compliance-backend/venv/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. E.g. --env ENV=valueactionr   -s	--secretsvSet secret environment variables. E.g. --secrets SECRET=value or `--secrets HF_TOKEN` to pass your Hugging Face token.
--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   s   &&u;&?
c8RSghEvwK 	  	
 	3=gh 0sArsghlhqhq  sD  iE  hF  FG  H 	  	

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

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

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

 		=RSZ0r    r   c                    |j                   | _         |j                  | _        i | _        |j                  rc| j                  j	                  t        t        |j                        j                         t        j                  j                                      |j                  xs g D ]D  }| j                  j	                  t        |t        j                  j                                      F i | _        t               }|j                  rG| j                  j	                  t        t        |j                        j                         |             |j                  xs g D ](  }| j                  j	                  t        ||             * |j                  | _        |j                  | _        |j                   | _        |j"                  | _        |j$                  | _        y )Nenviron)r7   rR   envenv_fileupdater   r   	read_textosr^   copysecrets_get_extended_environsecrets_fileflavortimeoutdetach	namespacetokenselfr   	env_valueextended_environsecrets        r   __init__zRunCommand.__init__w   sL   **
"&,,-/==HHOOKT]](;(E(E(GQSQ[Q[Q`Q`QbcdR 	OIHHOOK	2::??;LMN	O1302LLD1B1B,C,M,M,OYi jkll(b 	OFLLF<L MN	O/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rl   )r7   rR   r_   re   rh   ri   rk   Job started with ID: 	View at: job_id)r   rl   run_jobr7   rR   r_   re   rh   ri   rk   printidurlrj   fetch_job_logsrn   apijoblogs       r   r6   zRunCommand.run   s    $**%kk**LLLL;;LLnn  
 	%cffX./	#''#$;; %%SVV%4 	C#J	r    r4   N	r.   r/   r0   r1   r   r'   r   rr   r6   r2   r    r   r*   r*   I   s<    *1$5 *1$ *1 *1X/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   r4   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   rx   Job IDr8   rN   QThe namespace where the job is running. Defaults to the current user's namespace.rP   rQ   r!   )r#   rV   rW   r%   r(   rZ   s     r   r'   zLogsCommand.register_subcommand   sy    &&v4M&N
sBd 	  	

 	C&q 	  	
 	[1r    r   c                 j    |j                   | _         |j                  | _        |j                  | _        y r   rx   rk   rl   rn   r   s     r   rr   zLogsCommand.__init__   s#    ;;(,$(JJ
r    c                     t        | j                        }|j                  | j                  | j                        D ]  }t        |        y Nrt   rx   rk   )r   rl   r}   rx   rk   rz   )rn   r   r   s      r   r6   zLogsCommand.run   s>    $**%%%T[[DNN%S 	C#J	r    r   r   r2   r    r   r(   r(      s;    2$5 2$ 2 2/Y /4 /
r    r(   rowsheadersr4   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   )lenrW   ).0xs     r   	<genexpr>z_tabulate.<locals>.<genexpr>   s     /ac#a&k/s          z{{:{}}} -N   rS   
)zipmaxrc   get_terminal_sizecolumnsr   sumindexformatr<   rW   rX   )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   r4   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--allrM   z*Show all Jobs (default shows just running)r=   rN   zUThe namespace from where it lists the jobs. Defaults to the current user's namespace.r8   rP   rQ   z-fz--filterr<   z>Filter output based on conditions provided (format: key=value))r>   defaultr   z--formatz%Format output using a custom templater!   )r#   rV   rW   r%   r)   rZ   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.)	allrk   rl   r   filtersfiltersplitlowerrz   )rn   r   fkeyvalues        r   rr   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.
        rt   )rk   )zJOB IDzIMAGE/SPACECOMMANDCREATEDSTATUSUNKNOWN)RUNNINGUPDATINGzN/A )r{   r7   statusrR    z matching filters: rH   r   zNo jobs foundNzError fetching jobs data: zError processing jobs data: zUnexpected error - z: )r   rl   	list_jobsrk   r   stager   r{   docker_imagerR   rX   
created_atr   _matches_filtersr<   r   itemsrz   _print_outputrequestsRequestExceptionKeyError
ValueError	TypeError	Exceptionr9   r.   )rn   r   r   table_headersr   r   r   rx   image_or_spacerR   command_strr   job_propertiesfilters_msgkves                    r   r6   zPsCommand.run
  s   
A	Adjj)C ==4>>=:D VM D "W-0ZZ))Y xxF2I$I  "%!1!1!:U +++3:chhw/ !^^4u
 !+$lln*	" ,,^< V^[*fUVE"W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.*rI   ^$T)r   r   replaceresearch
IGNORECASEr   )rn   r   r   patternregex_patterns        r   r   zPsCommand._matches_filtersR  s     LL..0 	LC.( g~ 'T : B B3 Lyy1]O1!5~c7JBMMZ s(;(A(A(CC	 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.)r{   r7   rR   createdr   z{{.z}})r   N)r   	enumerater   rW   rz   r   )	rn   r   r   templater   lineifieldplaceholders	            r   r   zPsCommand._print_outpute  s    ;;{{H  )*Y Z FHAu$)%"5K"d*#||KSVEF d #r    r   )r.   r/   r0   r1   r   r'   r   rr   r6   r   rW   boolr   r   r2   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   r4   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   rN   r   r8   rP   rQ   job_idsrS   zThe jobs to inspectrT   r!   )r#   rV   rW   r%   r&   rZ   s     r   r'   z"InspectCommand.register_subcommand|  sz    &&y7i&j
d 	  	

 	C&q 	  	
 		=RS^4r    r   c                 j    |j                   | _         |j                  | _        |j                  | _        y r   )rk   rl   r   r   s     r   rr   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 )Nrt   r      )indentr   )
r   rl   r   inspect_jobrk   rz   jsondumpsr   rW   )rn   r   rx   r   r   s        r   r6   zInspectCommand.run  sg    $**%W[WcWcdVvHdddjj6#&+6q#NO e6s   $B#Br   r   r2   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   r4   Nc                     | j                  dd      }|j                  dt        d       |j                  dt        d       |j                  d	t        d
       |j                  t               y )NcancelzCancel a Jobr   rx   r   r8   rN   r   rP   rQ   r!   )r#   rV   rW   r%   r+   rZ   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   rr   zCancelCommand.__init__  s#    ;;$(JJ
r    c                 ~    t        | j                        }|j                  | j                  | j                         y r   )r   rl   
cancel_jobrx   rk   )rn   r   s     r   r6   zCancelCommand.run  s(    $**%dkkT^^Dr    r   r   r2   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   requiredr6   z8Run a UV script (local file or URL) on HF infrastructurescriptz$UV script to run (local file or URL)script_argsrS   zArguments for the script)rU   r   r   z--imagez.Use a custom Docker image with `uv` installed.r8   z--repozCRepository name for the script (creates ephemeral if not specified)rF   rG   rH   rI   r:   r;   r<   zEnvironment variablesr=   r?   r@   rA   rB   rC   rD   rE   rJ   z Max duration (e.g., 30s, 5m, 1h)rK   rL   rM   zRun in backgroundrN   rO   rP   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$   rV   rW   rX   rY   r%   r,   )r   	uv_parser
subparsersr[   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 	  	
 	3=ghB 	  	

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

 		*E@gnuv*3-d 	  	
 	Y/r    r   r4   Nc                 R   |j                   | _         |j                  | _        |j                  | _        |j                  | _        |j
                  | _        i | _        |j                  rc| j                  j                  t        t        |j                        j                         t        j                  j                                      |j                  xs g D ]D  }| j                  j                  t        |t        j                  j                                      F i | _        t!               }|j"                  rG| 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.r]   N)r  r  r  dependenciespythonr7   r_   r`   ra   r   r   rb   rc   r^   rd   re   rf   rg   rh   ri   rj   rk   rl   repo_reporm   s        r   rr   zUvCommand.__init__  s|   kk++ JJkkZZ
-/==HHOOKT]](;(E(E(GQSQ[Q[Q`Q`QbcdR 	OIHHOOK	2::??;LMN	O1302LLD1B1B,C,M,M,OYi jkll(b 	OFLLF<L MN	O/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.rt   )r  r  r  r  r7   r_   re   rh   ri   rk   r  ru   rv   Nrw   )r   set_verbosityINFOr   rl   
run_uv_jobr  r  r  r  r7   r_   re   rh   ri   rk   r  rz   r{   r|   rj   r}   r~   s       r   r6   zUvCommand.run  s    gll+$**%nn;;((**;;**LL;;LLnn**  
 	%cffX./	#''#$;; %%SVV%4 	C#J	r    r   )	r.   r/   r0   __doc__r1   r'   r   rr   r6   r2   r    r   r,   r,     s0    870 70rY 4 2r    r,   c                  d    t         j                  j                         } t               x}|| d<   | S )NHF_TOKEN)rc   r^   rd   r   )rp   rl   s     r   rf   rf   "  s1    zz()',$r    )+r  r   rc   r   argparser   r   dataclassesr   pathlibr   typingr   r   r	   r
   r   huggingface_hubr   r   r   huggingface_hub.utilsr   huggingface_hub.utils._dotenvr   r   r   
get_loggerr.   loggerr   rY   r   r*   r(   rW   intr   r)   r&   r+   r,   rf   )items   0r   <module>r"     s  &  	 	 1   . .  ; ; ) 5 ' 
		H	%,9WDTZZ;=VTZZW 7, 7$V* Vr+ 4DeCHo./ $s)  6a) aHP. P4E- E2q) qhtCH~ ] Xs   %C<:C<