a
    dDI                     @  s   d dl m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
 d dlZd dl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 G d
d dZG dd dZdS )    )annotationsN)TimeoutError)deque)Any)Literal)
Estimation
LogMessagePredictBodyProgressProgressUnit)TrackedIterable)AsyncRequestrun_coro_in_backgroundset_task_namec                   @  s.   e Zd ZddddddZdddd	d
ZdS )Eventfastapi.WebSocketstrint)	websocketsession_hashfn_indexc                 C  sP   || _ || _|| _| j d| j | _d | _d | _d | _d | _d| _t	 | _
d S )N_F)r   r   r   _iddataZlost_connection_timetokenprogressprogress_pendingr   log_messages)selfr   r   r    r   X/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gradio/queueing.py__init__   s    zEvent.__init__  codec                   s   | j j|dI d H  d S )Nr#   )r   close)r   r$   r   r   r    
disconnect+   s    zEvent.disconnectN)r"   )__name__
__module____qualname__r!   r&   r   r   r   r    r      s   r   c                   @  s  e Zd ZddddddddZd^d
dZdd Zdd ZddddZddddZddddZ	ddddZ
ddddZddd d!Zd"dd#d$d%Zdd&d'd(d)Zddd*d+d,d-Zd"dd#d.d/Zd"dd#d0d1Zddd2d3Zd_d"dd#d5d6Zddd7d8Zddd9d:Zd"d;dd;d<d=d>Zddd?d@dAZd;ddBdCZdDdEdFdGdHZdIddJdKdLZdIdddMdNdOZd`dQdRddSdTdUZdadWddXdYZdddZd[d\Zd]S )bQueueboolr   floatz
int | Nonelist)live_updatesconcurrency_countupdate_intervalsmax_sizeblocks_dependenciesc                 C  s   t  | _g | _d| _|| _|| _d g| | _t | _	d | _
d| _d| _d| _d | _d| _|| _d| _d| _|| _|| _d| _d | _g | _d S )NFr      g?g? )r   event_queueZevents_pending_reconnectionstoppedmax_thread_countr0   active_jobsasyncioLockdelete_lockserver_pathduration_history_totalduration_history_countavg_process_timeavg_concurrent_process_timequeue_durationr.   sleep_when_freeprogress_update_sleep_when_freer1   r2   access_tokenqueue_clientcontinuous_tasks)r   r.   r/   r0   r1   r2   r   r   r    r!   0   s*    
zQueue.__init__Tc                   s6   t j|d| _t| j t| j | js2t| j d S )N)verify)httpxZAsyncClientrE   r   start_processingstart_log_and_progress_updatesr.   notify_clients)r   Z
ssl_verifyr   r   r    startN   s
    

zQueue.startc                 C  s
   d| _ d S )NTr6   r   r   r   r    r%   W   s    zQueue.closec                 C  s
   d| _ d S NFrM   rN   r   r   r    resumeZ   s    zQueue.resumer   )urlc                 C  s
   || _ d S N)r<   )r   rQ   r   r   r    set_url]   s    zQueue.set_url)r   c                 C  s
   || _ d S rR   )rD   )r   r   r   r   r    set_access_token`   s    zQueue.set_access_token)returnc                 C  s$   d}| j D ]}|d ur
|d7 }q
|S )Nr   r3   )r8   )r   countZworkerr   r   r    get_active_worker_countc   s
    

zQueue.get_active_worker_countztuple[list[Event] | None, bool]c                   s   j s
dS j  }|g}|j j  d }|r|j  d } fddj D d |d  }|| fdd|D  ||fS )NrO   batchZmax_batch_sizec                   s   g | ]}|j  kr|qS r   )r   .0event)event_fn_indexr   r    
<listcomp>v   s   z-Queue.get_events_in_batch.<locals>.<listcomp>r3   c                   s   g | ]} j |qS r   )r5   removerY   rN   r   r    r]   z       )r5   popleftr   r2   extend)r   Zfirst_eventeventsrX   Z
batch_sizeZrest_of_batchr   )r\   r   r    get_events_in_batchj   s     



zQueue.get_events_in_batchNonec              	     s   | j s| js t| jI d H  q d | jvr>t| jI d H  q | j4 I d H " |  \}}W d   I d H  q1 I d H sz0    Y  |r || j| jd < t	| j
||}t	| j t||d j|d j| q d S )Nr   )r6   r5   r9   sleeprB   r8   r;   rc   indexr   process_eventsbroadcast_live_estimationsr   r   r   )r   rb   rX   Ztaskr   r   r    rI   ~   s    
6
zQueue.start_processingc                   s   | j sdd | jD | j }t|dkr<t| jI d H  q |D ]R}|jr|jrd|_| 	||j
 I d H }|s| |I d H  | |I d H  q@t| jI d H  q d S )Nc                 S  s"   g | ]}|d ur|D ]}|qqS rR   r   rZ   jobevtr   r   r    r]      s   z8Queue.start_log_and_progress_updates.<locals>.<listcomp>r   F)r6   r8   rF   lenr9   re   rC   r   r   send_messagedictclean_eventsend_log_updates_for_event)r   rb   r[   client_awaker   r   r    rJ      s"    z$Queue.start_log_and_progress_updatesr   )r[   rU   c                   sV   z|j  }W n ty$   Y qRY n0 | || I d H }|s | |I d H  q d S rR   )r   r`   
IndexErrorrm   rn   ro   )r   r[   messagerq   r   r   r    rp      s    
z Queue.send_log_updates_for_eventzlist[TrackedIterable] | None)event_id	iterablesc              
   C  s   |d u rd S | j D ]h}|d u r q|D ]T}|j|kr$g }|D ]*}t|j|j|j|j|jd}|| q:t	|d|_d|_
q$qd S )N)rf   lengthunitr   desc)progress_dataT)r8   r   r   rf   rv   rw   r   rx   appendr
   r   )r   rt   ru   rj   rk   ry   iterableZprogress_unitr   r   r    set_progress   s&    

zQueue.set_progresszLiteral['info', 'warning'])rt   loglevelc                 C  sF   dd | j D | j }|D ]&}|j|krt||d}|j| qd S )Nc                 S  s"   g | ]}|d ur|D ]}|qqS rR   r   ri   r   r   r    r]      s   z%Queue.log_message.<locals>.<listcomp>)r}   r~   )r8   rF   r   r   r   rz   )r   rt   r}   r~   rb   r[   log_messager   r   r    r      s    
zQueue.log_messagec                 C  s2   t | j}| jdur"|| jkr"dS | j| |S )z
        Add event to queue, or return None if Queue is full
        Parameters:
            event: Event to add to Queue
        Returns:
            rank of submitted Event
        N)rl   r5   r1   rz   )r   r[   Z	queue_lenr   r   r    push   s
    
z
Queue.pushc              	     sT   || j v rP| j4 I d H " | j | W d   I d H  qP1 I d H sF0    Y  d S rR   )r5   r;   r^   )r   r[   r   r   r    ro      s    
zQueue.clean_eventc                   s   | j r|  I dH  dS )z
        Runs 2 functions sequentially instead of concurrently. Otherwise dced clients are tried to get deleted twice.
        N)r.   broadcast_estimationsrN   r   r   r    rh      s    z Queue.broadcast_live_estimations<   c                   sl   |j sh| |ddiI dH }|s$dS | j||dI dH \}}|sb| |dddidd	I dH  dS ||_ d
S )z
        Gather data for the event
        Parameters:
            event: the Event to gather data for
            receive_timeout: how long to wait for data to be received from frontend
        msgZ	send_dataNFtimeoutprocess_completederrorz!Time out uploading data to serverr   outputsuccessT)r   rm   get_message)r   r[   Zreceive_timeoutrq   r   r   r   r    gather_event_data   s     
zQueue.gather_event_datac                   s2   | j s.t| jI dH  | jr |  I dH  q dS )zQ
        Notify clients about events statuses in the queue periodically.
        N)r6   r9   re   r0   r5   r   rN   r   r   r    rK     s    zQueue.notify_clientsc                   s2      tj fddtjD  I d H  d S )Nc                   s   g | ]\}} | |qS r   )send_estimation)rZ   rankr[   
estimationr   r   r    r]     s   z/Queue.broadcast_estimations.<locals>.<listcomp>)get_estimationr9   Zgather	enumerater5   rN   r   r   r    r     s    zQueue.broadcast_estimationsr   )r[   r   r   rU   c                   sl   ||_ | jdur>|j | j | j |_d| jvr>| j| j7  _| || I dH }|sh| |I dH  |S )z
        Send estimation about ETA to the client.

        Parameters:
            event:
            estimation:
            rank:
        N)r   r@   r?   Zrank_etar8   rm   rn   ro   )r   r[   r   r   rq   r   r   r    r   !  s    


zQueue.send_estimation)durationrU   c                 C  sV   |  j |7  _ |  jd7  _| j | j | _| jt| j| j | _| jt| j | _dS )zt
        Update estimation by last x element's average duration.

        Parameters:
            duration:
        r3   N)	r=   r>   r?   minr7   r@   rl   r5   rA   )r   r   r   r   r    update_estimation;  s    
zQueue.update_estimationc                 C  s   t t| j| j| j| jdS )N)Z
queue_sizeZavg_event_process_timeZ!avg_event_concurrent_process_timeZ	queue_eta)r   rl   r5   r?   r@   rA   rN   r   r   r    r   L  s    zQueue.get_estimationr   zdict[str, Any])r   rU   c                 C  s\   t |jt|jt|jt|j|jj|jjdd}z|j	|d< W n t
yV   Y n0 |S )N)hostport)rQ   headersquery_paramspath_paramsclientsession)r   rQ   rn   r   r   r   r   r   r   r   	Exception)r   r   paramsr   r   r    get_request_paramsT  s    zQueue.get_request_paramszlist[Event])rb   rX   c                   s   |d j }|d usJ d|d j}|s2|d jnd |_z |d j|_W n ty`   Y n0 |rtt	dd |D  |_  fdd|D |_d|_
ttjj j dt|dd	 j i|d urd
|ind  jdI d H }|S )Nr   zNo event datac                 S  s   g | ]}|j r|j j qS r   r   rY   r   r   r    r]   o  r_   z)Queue.call_prediction.<locals>.<listcomp>c                   s   g | ]}|j r |jqS r   )r   r   r   rY   rN   r   r    r]   p  s   Tzapi/predictAuthorizationzBearer zaccess-token)methodrQ   jsonr   cookiesr   )r   r   r   rt   r   r   request
ValueErrorr-   zipZbatchedr   MethodPOSTr<   rn   rD   rE   )r   rb   rX   r   r   responser   rN   r    call_predictiond  s.    



zQueue.call_prediction)rb   rX   rU   c                   sT  g }zΐz |D ]<}|  |I d H }|r>| |ddiI d H }|r|| q|sW W |D ]*}z| I d H  W qZ ty   Y qZ0 qZd | j| j|< |D ]*}| |I d H  | |j	|j
I d H  qd S t }| ||I d H }|jr |D ](}| |ddt|jiddI d H  qn|jddr|}|jddr4|}g }	|D ]2}| |d|j|jd	kdI d H }
|	|
 qPd
d t||	D }|sW W |D ].}z| I d H  W n ty   Y n0 qd | j| j|< |D ],}| |I d H  | |j	|j
I d H  qd S | ||I d H }q4|D ]N}|jd	krN|}n|}| |I d H  | |d|j|jd	kdI d H  q8n|t|j}t|D ]f\}}|rd|v rtt|jd | |d< | |I d H  | |d||jd	kdI d H  qt }|jd	kr(| ||  W n. tyX } zt| W Y d }~n
d }~0 0 W |D ].}z| I d H  W n ty   Y n0 q`d | j| j|< |D ],}| |I d H  | |j	|j
I d H  qnz|D ].}z| I d H  W n ty   Y n0 qd | j| j|< |D ],}| |I d H  | |j	|j
I d H  q 0 d S )Nr   Zprocess_startsr   r   Fr   Zis_generatingZprocess_generating   c                 S  s   g | ]\}}|r|qS r   r   )rZ   eZis_openr   r   r    r]     s   z(Queue.process_events.<locals>.<listcomp>r   )r   rm   rz   r&   r   r8   rf   ro   reset_iteratorsr   r   timer   has_exceptionr   	exceptionr   getstatusr   rp   copydeepcopyr   r-   r   print)r   rb   rX   Zawake_eventsr[   rq   Z
begin_timer   Zold_responseZopen_wsopenZrelevant_responser   r   Zend_timer   r   r    rg     s    
F
&
	
 

zQueue.process_eventsr3   rn   zfloat | int)r   r   rU   c                   sN   z$t j|jj|d|dI d H  W dS  tyH   | |I d H  Y dS 0 d S )Nr   r   TF)r9   wait_forr   Z	send_jsonr   ro   )r   r[   r   r   r   r   r    rm     s    zQueue.send_message   ztuple[PredictBody | None, bool]c                   sX   z.t j|j |dI d H }tf i |dfW S  tyR   | |I d H  Y dS 0 d S )Nr   TrO   )r9   r   r   Zreceive_jsonr	   AsyncTimeOutErrorro   )r   r[   r   r   r   r   r    r     s    
zQueue.get_messager   r   c                   s.   t t jj| j d||d| jdI d H  d S )Nresetr   )r   rQ   r   r   )r   r   r   r<   rE   )r   r   r   r   r   r    r     s    
zQueue.reset_iteratorsN)T)r   )r3   )r   )r'   r(   r)   r!   rL   r%   rP   rS   rT   rW   rc   rI   rJ   rp   r|   r   r   ro   rh   r   rK   r   r   r   r   r   r   rg   rm   r   r   r   r   r   r    r*   /   s8   
	
	
`

r*   )
__future__r   r9   r   r   r   r   collectionsr   typingr   ZfastapirH   Ztyping_extensionsr   Zgradio.data_classesr   r   r	   r
   r   Zgradio.helpersr   Zgradio.utilsr   r   r   r   r*   r   r   r   r    <module>   s   