a
    h"T                     @   sd  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eZdd eD ZG dd deZG dd deZ G dd deZ!eeee"e#f   ee" e"dddZ$G dd deZ%G dd deZ&G dd deZ'G dd deZ(ee"e"f dd d!Z)dS )"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   )BaseHuggingfaceCLICommandc                 C   s   g | ]}|j d kr|j qS )z	zero-a10g)value).0item r   T/var/www/html/assistant/venv/lib/python3.9/site-packages/huggingface_hub/cli/jobs.py
<listcomp>4       r   c                   @   s   e Zd ZeedddZdS )JobsCommands)parserc                    sn   | j ddd  jdd} j fddd t| t| t| t| t| t	| d S )NjobszRun and manage Jobs on the Hub.helpz$huggingface.co jobs related commandsc                    s      S N)
print_help)argsZjobs_parserr   r   <lambda>>   r   z2JobsCommands.register_subcommand.<locals>.<lambda>func)

add_parseradd_subparsersset_defaultsInspectCommandregister_subcommandLogsCommand	PsCommand
RunCommandCancelCommand	UvCommand)r   Zjobs_subparsersr   r!   r   r)   8   s    




z JobsCommands.register_subcommandN)__name__
__module____qualname__staticmethodr   r)   r   r   r   r   r   7   s   r   c                   @   s>   e Zd ZeeddddZeddddZddd	d
ZdS )r,   Nr   returnc                 C   s   | j ddd}|jdtdd |jddd	d
d |jddd	dd |jdtdd |jdtdd |jdtddt dd |jdtdd |jddddd |jdtdd |jdtd d |jd!d"d#d$ |jtd% d S )&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_parserr   r   r   r)   J   sN    	zRunCommand.register_subcommandr    r4   c                 C   s   |j | _ |j| _i | _|jr@| jtt|j tj	
 d |jpHg D ]}| jt|tj	
 d qJi | _t }|jr| jtt|j |d |jpg D ]}| jt||d q|j| _|j| _|j| _|j| _|j| _d S )Nenviron)r6   rQ   envenv_fileupdater   r   	read_textosr]   copysecrets_get_extended_environsecrets_fileflavortimeoutdetach	namespacetokenselfr    Z	env_valueextended_environsecretr   r   r   __init__w   s$    $zRunCommand.__init__r4   c              	   C   s|   t | jd}|j| j| j| j| j| j| j| j	d}t
d|j  t
d|j  | jr\d S |j|jdD ]}t
| qjd S )Nrk   )r6   rQ   r^   rd   rg   rh   rj   Job started with ID: 	View at: job_id)r   rk   Zrun_jobr6   rQ   r^   rd   rg   rh   rj   printidurlri   fetch_job_logsrm   apijoblogr   r   r   r5      s     
zRunCommand.run	r/   r0   r1   r2   r   r)   r   rp   r5   r   r   r   r   r,   I   s   ,r,   c                   @   s>   e Zd ZeeddddZeddddZddd	d
ZdS )r*   Nr3   c                 C   sN   | j ddd}|jdtdd |jdtdd |jd	td
d |jtd d S )NZlogszFetch the logs of a Jobr   rv   Job IDr7   rM   QThe namespace where the job is running. Defaults to the current user's namespace.rO   rP   r#   )r%   rU   rV   r'   r*   rY   r   r   r   r)      s    zLogsCommand.register_subcommandr[   c                 C   s   |j | _ |j| _|j| _d S r   rv   rj   rk   rm   r    r   r   r   rp      s    zLogsCommand.__init__rq   c                 C   s0   t | jd}|j| j| jdD ]}t| qd S Nrr   rv   rj   )r   rk   rz   rv   rj   rw   )rm   r|   r~   r   r   r   r5      s    zLogsCommand.runr   r   r   r   r   r*      s   r*   )rowsheadersr4   c           	      C   s  dd t g | |R  D }tt jt|d }t|t| |kr|t|}||  d  < t|t| |kr4|t| t| ||  ||< q4dt| j| }g }|	|j|  |	|jdd |D   | D ](}dd t ||D }|	|j|  qd
|S )	z
    Inspired by:

    - stackoverflow.com/a/8356620/593036
    - stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
    c                 S   s   g | ]}t d d |D qS )c                 s   s   | ]}t t|V  qd S r   lenrV   )r   xr   r   r   	<genexpr>   r   z'_tabulate.<locals>.<listcomp>.<genexpr>)max)r   colr   r   r   r      r   z_tabulate.<locals>.<listcomp>      z{{:{}}} c                 S   s   g | ]}d | qS )-r   )r   wr   r   r   r      r   c                 S   s@   g | ]8\}}t t||kr4t|d |d  d nt|qS )N   rR   r   )r   r   Z	col_widthr   r   r   r      s   
)zipr   rb   get_terminal_sizecolumnsr   sumindexformatr;   rW   )	r   r   Z
col_widthsterminal_widthZcol_to_minimizeZ
row_formatlinesrowZrow_format_argsr   r   r   	_tabulate   s"    "r   c                   @   s^   e Zd ZeeddddZeddddZddd	d
Ze	e
e
f edddZdd ZdS )r+   Nr3   c                 C   st   | j ddd}|jddddd |jd	td
d |jdtdd |jdddg dd |jdtdd |jtd d S )NZpsz	List Jobsr   z-az--allrL   z*Show all Jobs (default shows just running)r<   rM   zUThe namespace from where it lists the jobs. Defaults to the current user's namespace.r7   rO   rP   z-fz--filterr;   z>Filter output based on conditions provided (format: key=value))r=   defaultr   z--formatz%Format output using a custom templater#   )r%   rU   rV   r'   r+   rY   r   r   r   r)      s<    zPsCommand.register_subcommandr[   c                 C   sn   |j | _ |j| _|j| _|j| _i | _|jD ]<}d|v rX|dd\}}|| j| < q,td| d q,d S )N=r   z)Warning: Ignoring invalid filter format 'z'. Use key=value format.)	allrj   rk   r   filtersfiltersplitlowerrw   )rm   r    fkeyr   r   r   r   rp      s    
zPsCommand.__init__rq   c              
   C   s  zt | jd}|j| jd}g d}g }|D ]}|jr@|jjnd}| jsT|dvrTq.|j}|jpbd}|j	plg }	|	r|d
|	nd}
|jpd}||| |
d}| |sq.||||
||g q.|sd	}| jrd
d
dd | j D  }td|  W dS | || W n tjyF } ztd|  W Y d}~nd}~0  tttfy~ } ztd|  W Y d}~nHd}~0  ty } z&tdt|j d|  W Y d}~n
d}~0 0 dS )z
        Fetch and display job information for the current user.
        Uses Docker-style filtering with -f/--filter flag and key=value pairs.
        rr   )rj   )zJOB IDzIMAGE/SPACEZCOMMANDCREATEDZSTATUSUNKNOWN)ZRUNNINGZUPDATINGzN/A )rx   r6   statusrQ    z matching filters: rG   c                 S   s   g | ]\}}| d | qS )r   r   )r   kvr   r   r   r   C  r   z!PsCommand.run.<locals>.<listcomp>zNo jobs foundNzError fetching jobs data: zError processing jobs data: zUnexpected error - z: )r   rk   Z	list_jobsrj   r   Zstager   rx   Zdocker_imagerQ   rW   
created_atr   _matches_filtersr;   r   itemsrw   _print_outputrequestsRequestExceptionKeyError
ValueError	TypeError	Exceptionr8   r/   )rm   r|   r   Ztable_headersr   r}   r   rv   Zimage_or_spacerQ   Zcommand_strr   job_propertiesZfilters_msger   r   r   r5   
  sF    



 ""zPsCommand.run)r   r4   c                 C   s   | j  D ]x\}}||vr  dS d|v s0d|v rh|dddd}td| d|| tjs dS q
| ||  vr
 dS q
dS )	z+Check if job matches all specified filters.F*?z.*rH   ^$T)r   r   replaceresearch
IGNORECASEr   )rm   r   r   patternZregex_patternr   r   r   r   R  s    zPsCommand._matches_filtersc           	      C   sv   | j rb| j }|D ]N}|}tg dD ]0\}}d| d}||v r$||t|| }q$t| qntt||d dS )z,Print output according to the chosen format.)rx   r6   rQ   createdr   z{{.z}})r   N)r   	enumerater   rV   rw   r   )	rm   r   r   templater   lineifieldplaceholderr   r   r   r   e  s    zPsCommand._print_output)r/   r0   r1   r2   r   r)   r   rp   r5   r   rV   boolr   r   r   r   r   r   r+      s   "Hr+   c                   @   s>   e Zd ZeeddddZeddddZddd	d
ZdS )r(   Nr3   c                 C   sN   | j ddd}|jdtdd |jdtdd |jd	d
dd |jtd d S )Ninspectz0Display detailed information on one or more Jobsr   rM   r   r7   rO   rP   job_idsrR   zThe jobs to inspectrS   r#   )r%   rU   rV   r'   r(   rY   r   r   r   r)   |  s    z"InspectCommand.register_subcommandr[   c                 C   s   |j | _ |j| _|j| _d S r   )rj   rk   r   r   r   r   r   rp     s    zInspectCommand.__init__rq   c                    sD   t jd  fddjD }ttjdd |D dtd d S )Nrr   c                    s   g | ]} j |jd qS )r   )Zinspect_jobrj   )r   rv   r|   rm   r   r   r     r   z&InspectCommand.run.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   r   )r   r}   r   r   r   r     r      )indentr   )r   rk   r   rw   jsondumpsrV   )rm   r   r   r   r   r5     s    zInspectCommand.runr   r   r   r   r   r(   {  s   r(   c                   @   s>   e Zd ZeeddddZeddddZddd	d
ZdS )r-   Nr3   c                 C   sN   | j ddd}|jdtdd |jdtdd |jd	td
d |jtd d S )NcancelzCancel a Jobr   rv   r   r7   rM   r   rO   rP   r#   )r%   rU   rV   r'   r-   rY   r   r   r   r)     s    z!CancelCommand.register_subcommandr[   c                 C   s   |j | _ |j| _|j| _d S r   r   r   r   r   r   rp     s    zCancelCommand.__init__rq   c                 C   s"   t | jd}|j| j| jd d S r   )r   rk   Z
cancel_jobrv   rj   )rm   r|   r   r   r   r5     s    zCancelCommand.runr   r   r   r   r   r-     s   r-   c                   @   s:   e Zd ZdZedd ZeddddZddd	d
ZdS )r.   z.Run UV scripts on Hugging Face infrastructure.c                 C   sB  | j ddd}|jdddd}|j dd	d}|jd
dd |jdddg d |jdtdd |jddd |jdtddt dd |jddddd |jdddd d |jd!td"d |jd#td$d |jd%td&d |jd'd(d)d*d |jd+td,d |jd-td.d |jd/dd0d1d2 |jd3d4td5d |jtd6 d7S )8zRegister UV run subcommand.ZuvzERun UV scripts (Python with inline dependencies) on HF infrastructurer   Z
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_argsrR   zArguments for the script)rT   r   r   z--imagez.Use a custom Docker image with `uv` installed.r7   z--repozCRepository name for the script (creates ephemeral if not specified)rE   rF   rG   rH   r9   r:   r;   zEnvironment variablesr<   r>   r?   r@   rA   rB   rC   rD   rI   z Max duration (e.g., 30s, 5m, 1h)rJ   rK   rL   zRun in backgroundrM   rN   rO   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&   rU   rV   rW   rX   r'   r.   )r   Z	uv_parserZ
subparsersrZ   r   r   r   r)     s^    	zUvCommand.register_subcommandNr[   c                 C   s
  |j | _ |j| _|j| _|j| _|j| _i | _|jrX| jt	t
|j tj d |jp`g D ]}| jt	|tj d qbi | _t }|jr| jt	t
|j |d |jpg D ]}| jt	||d q|j| _|j| _|j| _|j| _|j| _|j| _dS )z-Initialize the command with parsed arguments.r\   N)r   r   r   dependenciespythonr6   r^   r_   r`   r   r   ra   rb   r]   rc   rd   re   rf   rg   rh   ri   rj   rk   repo_reporl   r   r   r   rp     s,    $zUvCommand.__init__rq   c                 C   s   t t j t| jd}|j| j| j| j| j	| j
| j| j| j| j| j| jd}td|j  td|j  | jrxdS |j|jdD ]}t| qdS )zExecute UV command.rr   )r   r   r   r   r6   r^   rd   rg   rh   rj   r   rs   rt   Nru   )r   set_verbosityINFOr   rk   Z
run_uv_jobr   r   r   r   r6   r^   rd   rg   rh   rj   r   rw   rx   ry   ri   rz   r{   r   r   r   r5     s*    zUvCommand.run)	r/   r0   r1   __doc__r2   r)   r   rp   r5   r   r   r   r   r.     s
   
9r.   rq   c                  C   s$   t j } t  }d ur || d< | S )NZHF_TOKEN)rb   r]   rc   r   )rn   rk   r   r   r   re   "  s    
re   )*r   r   rb   r   argparser   r   dataclassesr   pathlibr   typingr   r   r	   r
   r   Zhuggingface_hubr   r   r   Zhuggingface_hub.utilsr   Zhuggingface_hub.utils._dotenvr   r   r   Z
get_loggerr/   loggerrX   r   r,   r*   rV   intr   r+   r(   r-   r.   re   r   r   r   r   <module>   s0   
Y& %t