o
    ϖiR                     @   sb  d dl 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
mZmZ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mZ d dlmZ d dlmZmZ d dlmZ d d	l m!Z!m"Z" d d
l#m$Z$ d dl%m&Z& zd dl'm(Z' W n e)y   d dl'Z'Y nw erd dl*m+Z+ d dl,m-Z- d dl.m/Z/ d dl#m0Z0 G dd de"Z1G dd de!Z2G dd deZ3deee4e5f  de3fddZ6dddeee4e5f  deej7df fddZ8dddeee4e5f  de	e9ef fddZ:				d-d eee&e9f  d!ee	e9ef  d"ee9 d#ee9 d$eee9  d%ee5 de	e9ef fd&d'Z;d(d)d*e	e9ef de1fd+d,Z<dS ).    N)	dataclass)TYPE_CHECKINGAnyAsyncIteratorDictIteratorListLiteralOptionalTupleUnionoverload)NotRequired	TypedDictUnpack)
ModelErrorReplicateError)FileEncodingStrategy)async_encode_jsonencode_json)Page)	NamespaceResource)EventSource)Version)v1)Client)
Deployment)Model)ServerSentEventc                   @   s  e Zd ZU dZe Zded< eed< 	 eed< 	 eed< 	 e	d ed< 	 e
eeef  ed	< 	 e
e ed
< 	 e
e ed< 	 e
e ed< 	 e
eeef  ed< 	 e
e ed< 	 e
e ed< 	 e
e ed< 	 e
eeef  ed< 	 eG dd dZede
e fddZd.ddZd.ddZ	d/de
e ded fddZ	d/de
e ded fd d!Zd.d"d#Zd.d$d%Zd.d&d'Zd.d(d)Zdee fd*d+Zdee fd,d-ZdS )0
Predictionz;
    A prediction made by a model hosted on Replicate.
    r   _clientidmodelversion)starting
processing	succeededfailedcanceledstatusinputoutputlogserrormetrics
created_at
started_atcompleted_aturlsc                   @   sT   e Zd ZU dZeed< 	 eed< 	 eed< 	 edZ	e
deded  fdd	Zd
S )zPrediction.Progressz/
        The progress of a prediction.
        
percentagecurrenttotalzE^\s*(?P<percentage>\d+)%\s*\|.+?\|\s*(?P<current>\d+)\/(?P<total>\d+)r-   returnc           	      C   s|   | d}ttt|D ].}||  }| j|r;| j|}t|dkr;tt	|d \}}}| |d ||  S qdS )z1Parse the progress from the logs of a prediction.
   r   g      Y@N)
splitreversedrangelenstrip_patternmatchfindallmapint)	clsr-   linesidxlinematchesr4   r5   r6    rI   H/home/ubuntu/.local/lib/python3.10/site-packages/replicate/prediction.pyparseq   s   
zPrediction.Progress.parseN)__name__
__module____qualname____doc__float__annotations__rC   recompiler?   classmethodstrr
   rK   rI   rI   rI   rJ   Progress^   s   
 rV   r7   c                 C   s&   | j du s
| j dkrdS tj| j S )z?
        The progress of the prediction, if available.
        N )r-   r    rV   rK   selfrI   rI   rJ   progress   s   zPrediction.progressNc                 C   s2   | j dvrt| jj |   | j dvsdS dS )z0
        Wait for prediction to finish.
        r'   r(   r)   N)r*   timesleepr!   poll_intervalreloadrX   rI   rI   rJ   wait   s   
zPrediction.waitc                    s@   | j dvrt| jjI dH  |  I dH  | j dvsdS dS )z?
        Wait for prediction to finish asynchronously.
        r[   N)r*   asyncior]   r!   r^   async_reloadrX   rI   rI   rJ   
async_wait   s
   
zPrediction.async_waituse_file_outputr   c                 c   s    | j o
| j dd}|rt|tstdi }d|d< d|d< | jjjd||d	}t| j||d
E dH  W d   dS 1 sAw   Y  dS )z
        Stream the prediction output.

        Raises:
            ReplicateError: If the model does not support streaming.
        streamN Model does not support streamingtext/event-streamAcceptno-storeCache-ControlGETheadersrd   )r3   get
isinstancerU   r   r!   re   r   )rY   rd   urlrm   responserI   rI   rJ   re      s   "zPrediction.streamc              	   C  s   t dI dH  | jo| jdd}|rt|tstdi }d|d< d|d< | jjj	d	||d
4 I dH }t
| j||d2 z	3 dH W }|V  q?6 W d  I dH  dS 1 I dH s[w   Y  dS )z
        Stream the prediction output asynchronously.

        Raises:
            ReplicateError: If the model does not support streaming.
        r   Nre   rf   rg   rh   ri   rj   rk   rl   rn   )ra   r]   r3   ro   rp   rU   r   r!   _async_clientre   r   )rY   rd   rq   rm   rr   eventrI   rI   rJ   async_stream   s$   .zPrediction.async_streamc                 C   6   | j j| j}|  D ]
\}}t| || qdS )z/
        Cancels a running prediction.
        N)r!   predictionscancelr"   dictitemssetattrrY   r)   namevaluerI   rI   rJ   rx         zPrediction.cancelc                    >   | j j| jI dH }|  D ]
\}}t| || qdS )z>
        Cancels a running prediction asynchronously.
        N)r!   rw   async_cancelr"   ry   rz   r{   r|   rI   rI   rJ   r      
   zPrediction.async_cancelc                 C   rv   )z7
        Load this prediction from the server.
        N)r!   rw   ro   r"   ry   rz   r{   rY   updatedr}   r~   rI   rI   rJ   r_      r   zPrediction.reloadc                    r   )zF
        Load this prediction from the server asynchronously.
        N)r!   rw   	async_getr"   ry   rz   r{   r   rI   rI   rJ   rb      r   zPrediction.async_reloadc                 c   s    | j pg }| jdvr/| j pg }|t|d }|E dH  |}t| jj |   | jdvs| jdkr8t| | j p<g }|t|d }|E dH  dS )z>
        Return an iterator of the prediction output.
        r[   Nr(   )	r,   r*   r=   r\   r]   r!   r^   r_   r   )rY   previous_outputr,   
new_outputrI   rI   rJ   output_iterator   s   






zPrediction.output_iteratorc                 C  s   | j pg }| jdvr8| j pg }|t|d }|D ]}|V  q|}t| jjI dH  |  I dH  | jdvs| jdkrAt| | j pEg }|t|d }|D ]}|V  qPdS )zK
        Return an asynchronous iterator of the prediction output.
        r[   Nr(   )	r,   r*   r=   ra   r]   r!   r^   rb   r   )rY   r   r,   r   itemrI   rI   rJ   async_output_iterator  s$   




	
z Prediction.async_output_iterator)r7   NN)rL   rM   rN   rO   pydanticPrivateAttrr!   rQ   rU   r	   r
   r   r   r   rV   propertyrZ   r`   rc   boolr   re   r   ru   rx   r   r_   rb   r   r   rI   rI   rI   rJ   r    *   sj   
 !


	



	
	
		r    c                   @   s
  e Zd ZdZd*deeddf dee fddZ	d*deeddf dee fd	d
Z	dedefddZ
dedefddZG dd deZedeeef deeeef  ded defddZedeeeeef df deeeef  ded defddZedeeeeef df deeeef  ded defddZddddddeeeeeef df  deeeedf  deeeeeef df  deeeef  ded defd dZedeeef deeeef  ded defd!d"Zedeeeeef df deeeef  ded defd#d"Zedeeeeef df deeeef  ded defd$d"Zddddddeeeeeef df  deeeedf  deeeeeef df  deeeef  ded defd%d"Zdedefd&d'Zdedefd(d)ZdS )+Predictionsz:
    Namespace for operations related to predictions.
    .cursorellipsisNr7   c                    s^   |du rt d jd|du rdn|}| } fdd|d D |d< tt d	i |S )
,  
        List your predictions.

        Parameters:
            cursor: The cursor to use for pagination. Use the value of `Page.next` or `Page.previous`.
        Returns:
            Page[Prediction]: A page of of predictions.
        Raises:
            ValueError: If `cursor` is `None`.
        Ncursor cannot be Nonerk   ./v1/predictionsc                       g | ]}t  j|qS rI   _json_to_predictionr!   .0resultrX   rI   rJ   
<listcomp>?      z$Predictions.list.<locals>.<listcomp>resultsrI   )
ValueErrorr!   _requestjsonr   r    rY   r   respobjrI   rX   rJ   list+  s   

zPredictions.listc                    sf   |du r	t d jd|du rdn|I dH }| } fdd|d D |d< tt d	i |S )
r   Nr   rk   .r   c                    r   rI   r   r   rX   rI   rJ   r   \  r   z*Predictions.async_list.<locals>.<listcomp>r   rI   )r   r!   _async_requestr   r   r    r   rI   rX   rJ   
async_listE  s   


zPredictions.async_listr"   c                 C   s$   | j dd| }t| j | S )
        Get a prediction by ID.

        Args:
            id: The ID of the prediction.
        Returns:
            Prediction: The prediction object.
        rk   /v1/predictions/r!   r   r   r   rY   r"   r   rI   rI   rJ   ro   b  s   
zPredictions.getc                    s,   | j dd| I dH }t| j | S )r   rk   r   Nr!   r   r   r   r   rI   rI   rJ   r   p  s   
zPredictions.async_getc                   @   sp   e Zd ZU dZee ed< 	 ee ed< 	 eee  ed< 	 ee ed< 	 ee	e
ef  ed< 	 ee ed< dS )	"Predictions.CreatePredictionParamsz%Parameters for creating a prediction.webhookwebhook_completedwebhook_events_filterre   r`   file_encoding_strategyN)rL   rM   rN   rO   r   rU   rQ   r   r   r   rC   r   rI   rI   rI   rJ   CreatePredictionParams~  s   
 
r   r$   r+   paramsr   c                 K      d S r   rI   rY   r$   r+   r   rI   rI   rJ   create  s   zPredictions.creater#   r   c                K   r   r   rI   rY   r#   r+   r   rI   rI   rJ   r        
deploymentr   c                K   r   r   rI   rY   r   r+   r   rI   rI   rJ   r     r   )r#   r$   r   r+   r   c                O   s6  | dd}| dd}|r&t|dkr|d nd}t|dkr$|d n|}tdd |||fD dkr8td|durSdd	lm}	 |	| jjjd||pMi d
|S |durnddl	m
}
 |
| jjjd||phi d|S |durzt|| j|d}t||fi |}t|d}| jjdd|i|}t| j| S )Z
        Create a new prediction for the specified model, version, or deployment.
        r`   Nr   r   r9   c                 s       | ]}t |V  qd S r   r   r   xrI   rI   rJ   	<genexpr>      z%Predictions.create.<locals>.<genexpr>EExactly one of 'model', 'version', or 'deployment' must be specified.Modelsr#   r+   Deploymentsr   r+   clientr   r`   POSTr   r   rI   r   r   )popr=   sumr   replicate.modelr   r!   rw   r   replicate.deploymentr   r   _create_prediction_body!_create_prediction_request_paramsr   r   r   rY   r#   r$   r   r+   argsr   r`   r   r   r   bodyextrasr   rI   rI   rJ   r     sP   
c                       d S r   rI   r   rI   rI   rJ   async_create  s   zPredictions.async_createc                   r   r   rI   r   rI   rI   rJ   r        c                   r   r   rI   r   rI   rI   rJ   r     r   c                   sR  | dd}| dd}|r't|dkr|d nd}t|dkr%|d n|}tdd |||fD dkr9td|durWdd	lm}	 |	| jjjd||pNi d
|I dH S |duruddl	m
}
 |
| jjjd||pli d|I dH S |durt|| j|dI dH }t||fi |}t|d}| jj	dd|i|I dH }t| j| S )r   r`   Nr   r   r9   c                 s   r   r   r   r   rI   rI   rJ   r   "  r   z+Predictions.async_create.<locals>.<genexpr>r   r   r   r   r   r   r   r   r   r   rI   r   )r   r=   r   r   r   r   r!   rw   r   r   r   r   r   r   r   r   r   r   rI   rI   rJ   r     s^   
c                 C   s&   | j dd| d}t| j | S )
        Cancel a prediction.

        Args:
            id: The ID of the prediction to cancel.
        Returns:
            Prediction: The canceled prediction object.
        r   r   /cancelr   r   rI   rI   rJ   rx   P  s
   

zPredictions.cancelc                    s.   | j dd| dI dH }t| j | S )r   r   r   r   Nr   r   rI   rI   rJ   r   a  s   


zPredictions.async_cancel).)rL   rM   rN   rO   r   rU   r   r    r   r   ro   r   r   r   r   r   r
   r   r   r   r   r   r   rx   r   rI   rI   rI   rJ   r   &  s    "


@

Ar   c                   @   s0   e Zd ZU eee  ed< eeej  ed< dS )CreatePredictionRequestParamsrm   timeoutN)	rL   rM   rN   r   r
   ry   rQ   httpxTimeoutrI   rI   rI   rJ   r   s  s   
 r   r`   r7   c                 C   s   t | d}t| d}||dS )Nr   )rm   r   )_create_prediction_timeout_create_prediction_headers)r`   r   rm   rI   rI   rJ   r   x  s
   

r   r   c                 C   s,   | sdS t | trdn| }tjd|d dS )a  
    Returns an `httpx.Timeout` instances appropriate for the optional
    `Prefer: wait=x` header that can be provided with the request. This
    will ensure that we give the server enough time to respond with
    a partial prediction in the event that the request times out.
    Ng      N@g      @g      ?)read)rp   r   r   r   )r`   read_timeoutrI   rI   rJ   r     s   
r   c                 C   s:   i }| rt | trd|d< |S t | trd|  |d< |S )Nr`   Preferzwait=)rp   r   rC   )r`   rm   rI   rI   rJ   r     s   

r   r$   r+   r   r   r   re   c                 K   sx   i }|d ur
||d< | d urt | tr| jn| |d< |d ur"||d< |d ur*||d< |d ur2||d< |d ur:||d< |S )Nr+   r$   r   r   r   re   )rp   r   r"   )r$   r+   r   r   r   re   _kwargsr   rI   rI   rJ   r     s   	r   r   r   r   c                 C   s   t di |}| |_|S )NrI   )r    r!   )r   r   
predictionrI   rI   rJ   r     s   r   )NNNN)=ra   rR   r\   dataclassesr   typingr   r   r   r   r   r   r	   r
   r   r   r   r   typing_extensionsr   r   r   replicate.exceptionsr   r   replicate.filer   replicate.helpersr   r   replicate.paginationr   replicate.resourcer   r   replicate.streamr   replicate.versionr   r   r   ImportErrorreplicate.clientr   r   r   r   r   r   r    r   r   rC   r   r   r   r   rU   r   r   r   rI   rI   rI   rJ   <module>   s    4 }  O






" 