o
    i?]                  &   @   s  d Z ddlZddlZddl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 d
dlmZmZmZ eeZdd eD Ze	eej ddf Z!e	ee ej"ddf Z#e	ee ej"dd$e ddf Z%e	ee&e  ej"ddddf Z'e	ee&e  ej"ddddf Z(e	ee ej"dddf Z)e	ee ej"ddf Z*e	ee ej"ddf Z+e	e,ej"ddd df Z-e	ee ej"d!df Z.e	ee&e  ej"d"d#df Z/e	ee ej"d$d%d&df Z0e	ee, ej"d'df Z1e	ee, ej"d(df Z2e	eej d)df Z3e	eej d*df Z4e	ee&e  ej d+df Z5e	e&e ej d,df Z6e	eej d-df Z7e	eej d.df Z8e	ee ej"d/df Z9ed0dZ:e:j;d1d2d							3		dd4e!d5e6d6e'd7e(d8e)d9e*d:e%d;e+d<e-d=e.d>ed?dfd@dAZ<e:j;dBdCd		ddDe7d=e.d>ed?dfdEdFZ=dGe>eef dHe>eef d?e,fdIdJZ?dKe&e&eee@f   dLe&e dMee d?dfdNdOZAe:j;dPdQd	3				ddRe	e,ej"dSdTdUdf d=e.d>edVe	ee&e  ej"dWdXdYdf dZe	ee ej"d[df d?dfd\d]ZBe:j;d^d_d		dd`e	e&e ej dadf d=e.d>ed?dfdbdcZCe:j;ddded		ddDe7d=e.d>ed?dfdfdgZDedhdZEe:jFeEdidj eEj;d1dkd										3				ddle4dme5d4e#dne9d:e%d6e'd7e(d8e)d9e*d;e+d<e-d=e.d>edoe/dpe0d?df dqdrZGedsdZHe:jFeHdtdj eHj;d1dud										ddve3d4e!d5e6dwe1dxe2d6e'd7e(d8e)d9e*d:e%d;e+d=e.d>ed?dfdydzZIeHj;dPd{d	3				ddRe	e,ej"dSdTd|df d=e.d>edVe	ee&e  ej"dWdXdYdf dZe	ee ej"d}d[df d?dfd~dZJeHj;d^dd		dde	e&e ej ddf d=e.d>ed?dfddZKeHj;ddd		dde8d=e.d>ed?dfddZLeHj;dwdd		dde8d=e.d>ed?dfddZMeHj;ddd		dde8d=e.d>ed?dfddZNeddZOeHjFeOdidj eOj;d1dkd															ddve3dle4dme5dwe1dxe2d4e#dne9d:e%d6e'd7e(d8e)d9e*d;e+d=e.d>edoe/dpe0d?df$ddZPdKe&e&eee@f   dLe&e d?efddZQd?e
eef fddZRd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>

    # Run a UV script
    hf jobs uv run <script>

    # Schedule a job
    hf jobs scheduled run <schedule> <image> <command>

    # List scheduled jobs
    hf jobs scheduled ps [-a] [-f key=value] [--format TEMPLATE]

    # Inspect a scheduled job
    hf jobs scheduled inspect <scheduled_job_id>

    # Suspend a scheduled job
    hf jobs scheduled suspend <scheduled_job_id>

    # Resume a scheduled job
    hf jobs scheduled resume <scheduled_job_id>

    # Delete a scheduled job
    hf jobs scheduled delete <scheduled_job_id>

    Nasdict)Path)	AnnotatedDictOptionalUnion)SpaceHardware	get_token)HfHubHTTPError)logging)load_dotenv   )TokenOpt
get_hf_apityper_factoryc                 C   s   g | ]
}|j d kr|j qS )z	zero-a10g)value).0item r   ^/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/huggingface_hub/cli/jobs.py
<listcomp>J   s    r   zThe Docker image to use.)helpz.Use a custom Docker image with `uv` installed.zTFlavor for the hardware, as in HF Spaces. Defaults to `cpu-basic`. Possible values: , .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.zVMax duration: int/float with s (seconds, default), m (minutes), h (hours) or d (days).z-dz--detachz3Run the Job in the background and print the Job ID.zVThe namespace where the job will be running. Defaults to the current user's namespace.z--withz%Run with the given packages installedz-pz--pythonz5The Python interpreter to use for the run environmentz!Suspend (pause) the scheduled Jobz8Allow multiple instances of this Job to run concurrentlyzWOne of annually, yearly, monthly, weekly, daily, hourly, or a CRON schedule expression.z$UV script to run (local file or URL)zArguments for the scriptzThe command to run.zJob IDzScheduled Job IDzCRepository name for the script (creates ephemeral if not specified)zRun and manage Jobs on the Hub.runz	Run a JobFimagecommandenvsecretsenv_filesecrets_fileflavortimeoutdetach	namespacetokenreturnc              	   C   s   i }|r| tt| tj d |pg D ]}| t|tj d qi }t }|r;| tt| |d |p>g D ]}| t||d q?t|
d}|j	| ||||||	d}t
d|j  t
d|j  |rpd S |j|jdD ]}t
| qwd S )Nenvironr&   )r   r   r   r   r"   r#   r%   Job started with ID: 	View at: job_id)updater   r   	read_textosr)   copy_get_extended_environr   run_jobprintidurlfetch_job_logs)r   r   r   r   r    r!   r"   r#   r$   r%   r&   env_map	env_valuesecrets_mapextended_environsecretapijoblogr   r   r   jobs_run   s8    


rA   logszFetch the logs of a Jobr.   c                 C   s*   t |d}|j| |dD ]}t| qd S Nr*   r.   r%   )r   r8   r5   )r.   r%   r&   r>   r@   r   r   r   	jobs_logs  s   

rE   job_propertiesfiltersc                 C   s   |  D ]<\}}|| vr dS d|v sd|v r3|dddd}td| d| | tjs2 dS q| | |  vr@ dS qdS )	z5Check if scheduled job matches all specified filters.F*?z.*r   ^$T)itemsreplaceresearch
IGNORECASElower)rF   rG   keypatternregex_patternr   r   r   _matches_filters)  s   rU   rowsheadersfmtc           	      C   st   |r0|}| D ]'}|}t g dD ]\}}d| d}||v r(||t|| }qt| qdS tt| |d dS )z,Print output according to the chosen format.)r6   r   r   createdstatusz{{.z}})rW   N)	enumeraterM   strr5   	_tabulate)	rV   rW   rX   templaterowlineifieldplaceholderr   r   r   _print_output;  s   
	rd   psz	List Jobsallz-az--allz*Show all Jobs (default shows just running)filterz-fz--filterz>Filter output based on conditions provided (format: key=value)formatz%Format output using a custom templatec              
   C   s  zt |d}|j|d}g d}g }i }	|pg D ]}
d|
v r-|
dd\}}||	| < qtd|
 d q|D ]L}|jrA|jjnd}| sJ|d	vrJq8|j}|jpQd
}|j	pVg }|r^d
|nd
}|jri|jdnd
}||| |d}t||	szq8||||||g q8|s|	rdd
dd |	 D  nd}td|  W d S t||| W d S  ty } ztd|  W Y d }~d S d }~w tttfy } ztd|  W Y d }~d S d }~w ty } ztdt|j d|  W Y d }~d S d }~ww )Nr*   r%   )zJOB IDIMAGE/SPACECOMMANDCREATEDSTATUS=r   )Warning: Ignoring invalid filter format ''. Use key=value format.UNKNOWN)RUNNINGUPDATINGN/A %Y-%m-%d %H:%M:%S)r6   r   rZ   r    matching filters: r   c                 S      g | ]\}}| d | qS rn   r   r   kvr   r   r   r         zjobs_ps.<locals>.<listcomp> zNo jobs foundzError fetching jobs data: zError processing jobs data: Unexpected error - : )r   	list_jobssplitrQ   r5   rZ   stager6   docker_imager   join
created_atstrftimerU   appendrL   rd   r   KeyError
ValueError	TypeError	Exceptiontype__name__)rf   r%   r&   rg   rh   r>   jobstable_headersrV   rG   frR   r   r?   rZ   r.   image_or_spacecmdcommand_strr   propsfilters_msger   r   r   jobs_psL  sP   



$(r   inspectz0Display detailed information on one or more Jobsjob_idszThe jobs to inspectc                    @   t |d  fdd| D }ttjdd |D dtd d S )Nr*   c                       g | ]	} j |d qS )rD   )inspect_job)r   r.   r>   r%   r   r   r     s    z jobs_inspect.<locals>.<listcomp>c                 S      g | ]}t |qS r   r   )r   r?   r   r   r   r            indentdefaultr   r5   jsondumpsr\   )r   r%   r&   r   r   r   r   jobs_inspect  s   
"r   cancelzCancel a Jobc                 C      t |d}|j| |d d S rC   )r   
cancel_job)r.   r%   r&   r>   r   r   r   jobs_cancel     
r   zERun UV scripts (Python with inline dependencies) on HF infrastructureuv)namez8Run a UV script (local file or URL) on HF infrastructurescriptscript_argsrepowith_pythonc                 C   s  i }|r| tt| tj d |pg D ]}| t|tj d qi }t }|r;| tt| |d |p>g D ]}| t||d q?t|d}|j	| |pVg |||||||	||d}t
d|j  t
d|j  |
rvd S |j|jdD ]}t
| q}d S )Nr(   r*   )r   r   dependenciesr   r   r   r   r"   r#   r%   _repor+   r,   r-   )r/   r   r   r0   r1   r)   r2   r3   r   
run_uv_jobr5   r6   r7   r8   )r   r   r   r   r"   r   r   r    r!   r#   r$   r%   r&   r   r   r9   r:   r;   r<   r=   r>   r?   r@   r   r   r   jobs_uv_run  s@    

r   z,Create and manage scheduled Jobs on the Hub.	scheduledzSchedule a Jobschedulesuspendconcurrencyc                 C   s   i }|r| tt| tj d |pg D ]}| t|tj d qi }t }|r;| tt| |d |p>g D ]}| t||d q?t|d}|j	||| |||||	|
|d
}t
d|j  d S )Nr(   r*   )
r   r   r   r   r   r   r   r"   r#   r%   Scheduled Job created with ID: )r/   r   r   r0   r1   r)   r2   r3   r   create_scheduled_jobr5   r6   )r   r   r   r   r   r   r   r    r!   r"   r#   r%   r&   r9   r:   r;   r<   r=   r>   scheduled_jobr   r   r   scheduled_run  s2    
r   zList scheduled Jobsz1Show all scheduled Jobs (default hides suspended)z--formatc              
   C   s,  zt |d}|j|d}g d}g }i }	|pg D ]}
d|
v r-|
dd\}}||	| < qtd|
 d q|D ]_}|jp>d}| sD|rDq8|j}|jpKd	}|jj	pQd	}|jj
pWg }|r_d
|nd	}|jjrm|jjjdnd	}|jjrz|jjdnd	}||t||d}t||	sq8||||||||g q8|s|	rdddd |	 D  nd}td|  W d S t||| W d S  ty } ztd|  W Y d }~d S d }~w tttfy } ztd|  W Y d }~d S d }~w ty } ztdt|j d|  W Y d }~d S d }~ww )Nr*   ri   )IDSCHEDULErj   rk   zLAST RUNzNEXT RUNSUSPENDrn   r   ro   rp   Frt   ru   rv   )r6   r   r   r   rw   r   c                 S   rx   ry   r   rz   r   r   r   r   k  r}   z scheduled_ps.<locals>.<listcomp>r~   zNo scheduled jobs foundz$Error fetching scheduled jobs data: z&Error processing scheduled jobs data: r   r   )r   list_scheduled_jobsr   rQ   r5   r   r6   r   job_specr   r   r   rZ   last_jobatr   next_job_run_atr\   rU   r   rL   rd   r   r   r   r   r   r   r   )rf   r%   r&   rg   rh   r>   scheduled_jobsr   rV   rG   r   rR   r   r   r   sj_idr   r   r   r   last_job_atr   r   r   r   r   r   r   scheduled_ps(  s`   



$(r   z:Display detailed information on one or more scheduled Jobsscheduled_job_idszThe scheduled jobs to inspectc                    r   )Nr*   c                    r   )scheduled_job_idr%   )inspect_scheduled_job)r   r   r   r   r   r     s    z%scheduled_inspect.<locals>.<listcomp>c                 S   r   r   r   )r   r   r   r   r   r     r   r   r   r   )r   r%   r&   r   r   r   r   scheduled_inspecty  s
   
"r   deletezDelete a scheduled Jobr   c                 C   r   Nr*   r   )r   delete_scheduled_jobr   r%   r&   r>   r   r   r   scheduled_delete  r   r   zSuspend (pause) a scheduled Jobc                 C   r   r   )r   suspend_scheduled_jobr   r   r   r   scheduled_suspend  r   r   resumez Resume (unpause) a scheduled Jobc                 C   r   r   )r   resume_scheduled_jobr   r   r   r   scheduled_resume  r   r   z(Schedule UV scripts on HF infrastructurec                 C   s   i }|
r| tt|
 tj d |pg D ]}| t|tj d qi }t }|r;| tt| |d |	p>g D ]}| t||d q?t|d}|j	||pVg | |||||||||||d}t
d|j  d S )Nr(   r*   )r   r   r   r   r   r   r   r   r   r   r"   r#   r%   r   r   )r/   r   r   r0   r1   r)   r2   r3   r   create_scheduled_uv_jobr5   r6   )r   r   r   r   r   r   r   r"   r   r   r    r!   r#   r%   r&   r   r   r9   r:   r;   r<   r=   r>   r?   r   r   r   scheduled_uv_run  s:    
r   c           	      C   s&  dd t g | |R  D }tt jt|d }t|t| |krW|t|}||  d  < t|t| |krM|t| t| ||  ||< t|t| |ks$dt| j| }g }|	|j|  |	|jdd |D   | D ]}dd t ||D }|	|j|  qyd
|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 )Nlenr\   )r   xr   r   r   	<genexpr>  s    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 | ]\}}t t||krt|d |d  d nt|qS )N   z...r   )r   r   	col_widthr   r   r   r     s    .
)zipr   r1   get_terminal_sizecolumnsr   sumindexrh   r   r   )	rV   rW   
col_widthsterminal_widthcol_to_minimize
row_formatlinesr_   row_format_argsr   r   r   r]     s$    
r]   c                  C   s$   t j } t  }d ur|| d< | S )NHF_TOKEN)r1   r)   r2   r
   )r<   r&   r   r   r   r3      s   
r3   )	NNNNNNFNN)NN)FNNNN)NNNNNNNNNFNNNN)
NNNNNNNNNN)NNNNNNNNNNNNNNN)S__doc__r   r1   rN   dataclassesr   pathlibr   typingr   r   r   r   typerhuggingface_hubr	   r
   huggingface_hub.errorsr   huggingface_hub.utilsr   huggingface_hub.utils._dotenvr   
_cli_utilsr   r   r   
get_loggerr   loggerSUGGESTED_FLAVORSr\   ArgumentImageArgOptionImageOptr   	FlavorOptlistEnvOpt
SecretsOpt
EnvFileOptSecretsFileOpt
TimeoutOptbool	DetachOptNamespaceOptWithOpt	PythonOpt
SuspendOptConcurrencyOptScheduleArg	ScriptArgScriptArgsArg
CommandArgJobIdArgScheduledJobIdArgRepoOptjobs_clir   rA   rE   dictrU   intrd   r   r   r   uv_app	add_typerr   scheduled_appr   r   r   r   r   r   scheduled_uv_appr   r]   r3   r   r   r   r   <module>   s4  )

	
		
	

	
/&
2		

W	
		

5	
+		

P			
		
*6