
    Āi                       d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
Z
d dlZd dl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mZ d dlmZm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$ d d	l%m&Z& d dl'Z'd dl(Z(d d
l)m*Z*m+Z+ d dl,m-Z-m.Z.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 e rd dl9m:Z: d dl;m<Z<  ejz                  e>      Z?e rd dl@mAZA eeBef   ZCde/ dZDde. dZEde/ dZFdZGdZHdZIdZJej                  j                  d      ZMe G d d             ZN G d d      ZO G d d      ZPdZQd ZRd!ZS G d" d#      ZT G d$ d%      ZU G d& d'eV      ZWe G d( d)eW             ZXe G d* d+eWeY             ZZdpd,Z[e G d- d.             Z\e G d/ d0e\             Z]e G d1 d2e\             Z^e G d3 d4e\             Z_ ed56       G d7 d8             Z`d9d:gZadqd;Zb ed56       G d< d=             Zcd>Zdd?Zed@ZfdrdAZgdsdBZhdCddD	 	 	 	 	 	 	 	 	 dtdEZidFdG	 	 	 	 	 	 	 	 	 dudHZjdvdIZk G dJ dKel      ZmdwdLZndxdMZo	 	 	 	 	 	 dydNZp	 	 	 	 	 	 dzdOZqe G dP dQ             Zre G dR dS             Zse	 d{	 	 	 	 	 d|dT       Zte	 d{	 	 	 	 	 d}dU       Zu	 	 	 	 	 	 	 	 	 	 d~dVZv	 	 	 	 	 	 	 	 	 	 ddWZwd!ZxdXZydYZzg dZZ{g d[Z|dd\Z}g f	 	 	 	 	 dd]Z~g fdd^Z	 	 d	 	 	 	 	 	 	 	 	 	 	 dd_Zg d`	 	 	 	 	 	 	 	 	 	 	 ddaZg d`	 	 	 	 	 	 	 	 	 	 	 ddbZdddZddfZ ed56       G dg dce`             Z ed56       G dh dee`             Z ed56       G di dj             Z ed56       G dk dl             ZddmZddnZdddoZy)    )annotationsN)Path)asynccontextmanagercontextmanager)datetimetimezone)	dataclassfield)cached_property)	AnyAsyncIteratorDictIteratorTYPE_CHECKINGOptionalLiteralCallableUnion)	urlencode)aconnect_sseconnect_sse)AuthCredentialsFAL_QUEUE_RUN_HOSTFAL_RUN_HOSTMissingCredentialsErrorfetch_auth_credentials)Priorityadd_priority_headeradd_timeout_headeradd_hint_headerREQUEST_TIMEOUT_TYPE_HEADERREQUEST_TIMEOUT_HEADER)WebSocketClientProtocol)
Connection)Imagezhttps:///zwss://zhttps://rest.alpha.fal.aizhttps://v3.fal.mediazfal-client/0.2.2 (python)   FAL_CLIENT_EXECUTOR)thread_name_prefixc                  >    e Zd ZU ded<   ded<   ded<   ded<   d	dZy)
CDNTokenstrtoken
token_typebase_upload_urlr   
expires_atc                b    t        j                  t        j                        | j                  k\  S N)r   nowr   utcr0   selfs    U/var/www/html/content-pipeline/venv/lib/python3.12/site-packages/fal_client/client.py
is_expiredzCDNToken.is_expiredV   s    ||HLL)T__<<    N)returnbool)__name__
__module____qualname____annotations__r8    r9   r7   r+   r+   O   s    JO=r9   r+   c                  $    e Zd ZddZddZddZy)CDNTokenManagerc                   || _         t        dddt        j                  j	                  t
        j                              | _        t        j                         | _
        t         d| _        | j                   j                  ddd| _        y N )tzinfor-   r.   r/   r0   z+/storage/auth/token?storage_type=fal-cdn-v3application/json)AuthorizationAcceptContent-Type)_authr+   r   minreplacer   r4   _token	threadingLock_lockREST_URL_urlheader_value_headersr6   auths     r7   __init__zCDNTokenManager.__init__[   sr    
 (||++8<<+@	!
 &/^^%5
j KL	!ZZ44(.
r9   c           	     @   t        j                         5 }|j                  | j                  | j                  i       }|j                          |j                         }d d d        t        d   |d   |d   t        j                  |d               S # 1 sw Y   7xY wNheadersjsonr-   r.   base_urlr0   rG   )
httpxClientpostrT   rV   raise_for_statusr^   r+   r   fromisoformatr6   clientresponsedatas       r7   _refresh_tokenzCDNTokenManager._refresh_tokenk   s    \\^ 	#v{{499dmm"{MH%%'==?D	#
 w-L) ,--d<.@A	
 	
	# 	#s   A	BBc                    | j                   5  | j                  j                         r| j                         | _        | j                  cd d d        S # 1 sw Y   y xY wr2   rR   rO   r8   ri   r5   s    r7   	get_tokenzCDNTokenManager.get_tokenx   sE    ZZ 	{{%%'"113;;	 	 	s   ;AANrX   r   r:   Noner:   r+   r<   r=   r>   rY   ri   rl   r@   r9   r7   rB   rB   Z       
 
r9   rB   c                  $    e Zd ZddZddZddZy)AsyncCDNTokenManagerc                   || _         t        dddt        j                  j	                  t
        j                              | _        t        j                         | _
        t         d| _        | j                   j                  ddd| _        y rD   )rL   r+   r   rM   rN   r   r4   rO   asynciorQ   rR   rS   rT   rU   rV   rW   s     r7   rY   zAsyncCDNTokenManager.__init__   sq    
 (||++8<<+@	!
 $+<<>
j KL	!ZZ44(.
r9   c           	       K   t        j                         4 d {   }|j                  | j                  | j                  i        d {   }|j                          |j                         }d d d       d {    t        d   |d   |d   t        j                  |d               S 7 7 d7 6# 1 d {  7  sw Y   FxY wwr[   )
r`   AsyncClientrb   rT   rV   rc   r^   r+   r   rd   re   s       r7   ri   z#AsyncCDNTokenManager._refresh_token   s     $$& 	# 	#&#[[DMMPR[SSH%%'==?D	# 	#
 w-L) ,--d<.@A	
 	
	#S	# 	# 	# 	#sV   C	B.C	,B4B0$B40C	;B2<3C	0B42C	4C:B=;CC	c                  K   | j                   4 d {    | j                  j                         r| j                          d {   | _        | j                  cd d d       d {    S 7 X7 (7 	# 1 d {  7  sw Y   y xY wwr2   rk   r5   s    r7   rl   zAsyncCDNTokenManager.get_token   sj     :: 	 	{{%%'$($7$7$99;;	 	 	9	 	 	 	sV   BA,B.A2A.A2B&A0'B.A20B2B8A;9B BNrm   ro   rp   r@   r9   r7   rs   rs      rq   r9   rs   i  @i   
   c                      e Zd Zdddd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       Zedd       Zedd       Zd ZddZ	dd	Z
edddd
	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Zedddd	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Zy)MultipartUploadN
chunk_sizecontent_typemax_concurrencyc                   || _         || _        || _        |xs t        | _        |xs d| _        |xs t        | _        d | _        d | _	        g | _
        y Napplication/octet-stream	file_name_client_token_managerMULTIPART_CHUNK_SIZEr}   r~   MULTIPART_MAX_CONCURRENCYr   _access_url
_upload_id_partsr6   r   rf   token_managerr}   r~   r   s          r7   rY   zMultipartUpload.__init__   Y     #+$<(<(F,F.K2K'+&*"$r9   c                H    | j                   st        d      | j                   S NzUpload not initiatedr   
ValueErrorr5   s    r7   
access_urlzMultipartUpload.access_url   #    344r9   c                H    | j                   st        d      | j                   S r   r   r   r5   s    r7   	upload_idzMultipartUpload.upload_id       344r9   c                r    | j                   j                         }|j                   d|j                   ddS N z	fal/0.1.0rI   z
User-Agentr   rl   r.   r-   r6   r-   s     r7   auth_headerszMultipartUpload.auth_headers   s<    ##--/ % 0 015;;-@%
 	
r9   c           
        | j                   j                         }|j                   d}t        | j                  d|i | j
                  d| j                  | j                  d      }|j                         }|d   | _	        |d   | _
        y Nz/files/upload/multipartPOSTrH   )rJ   rK   X-Fal-File-Namer]   r   uploadId)r   rl   r/   _maybe_retry_requestr   r   r~   r   r^   r   r   )r6   r-   urlrg   results        r7   createzMultipartUpload.create   s    ##--/&&''>?'LL##, $ 1 1#'>>		

 !,/ ,r9   c           	        | j                    d| j                   d| }t        | j                  d|i | j                  | j
                  dd|d       }|j                  d   }| j                  j                  ||d       y 	N/multipart/r&   PUTidentity)rK   zAccept-Encoding)r]   contenttimeoutetag)
partNumberr   )	r   r   _requestr   r   r~   r]   r   append)r6   part_numberrh   r   rg   r   s         r7   upload_partzMultipartUpload.upload_part   s    !T^^,<Ak]KLL## $ 1 1#-
 
 ')	
r9   c                    | j                    d| j                   d}t        | j                  d|| j                  d| j
                  i       | j                   S Nr   z	/completer   partsr\   )r   r   r   r   r   r   )r6   r   s     r7   completezMultipartUpload.complete   sT    !T^^,<IFLL%%4;;'	
 r9   r~   r}   r   c          	     ~   dd l } | ||||||      }	|	j                          t        j                  t	        |      |	j
                  z        }
|j                  j                  |	j                        5 }g }t        d|
dz         D ]R  }|dz
  |	j
                  z  }||||	j
                  z    }|j                  |j                  |	j                  ||             T |j                  j                  |      D ]  }|j                           	 d d d        |	j                         S # 1 sw Y   |	j                         S xY w)Nr   r   rf   r   r}   r~   r   max_workersr'   )concurrent.futuresr   mathceillenr}   futuresThreadPoolExecutorr   ranger   submitr   as_completedr   r   )clsrf   r   r   rh   r~   r}   r   
concurrent	multipartr   executorr   r   startfutures                   r7   savezMultipartUpload.save  s<    	"'!%+
	 			#d)i&:&::;22!11 3 
 	 G$Q	2 $qI,@,@@EEI,@,@$@AOOI$9$9;M %,,99'B   	  !!##	  !!##s   4BD$$D<c                  dd l }t        j                  j                        }t        j                  j	                        }	 | ||||||      j                          t        j                  |	j                  z        }
|j                  j                  j                        5 }g }t        d|
dz         D ]*  }dfd}|j                  |j                  ||             , |j                  j                  |      D ]  }|j!                           	 d d d        j#                         S # 1 sw Y   j#                         S xY w)Nr   r   r   r'   c                    t        d      5 }| dz
  j                  z  }|j                  |       |j                  j                        }j	                  | |       d d d        y # 1 sw Y   y xY wNrbr'   openr}   seekreadr   )pnfr   rh   	file_pathr   s       r7   _upload_partz/MultipartUpload.save_file.<locals>._upload_partL  sg    i. 8!!#a9+?+? ?u vvi&:&:;!--b$7	8 8 8s   AA((A1)r   intr:   rn   )r   ospathbasenamegetsizer   r   r   r}   r   r   r   r   r   r   r   r   r   )r   rf   r   r   r}   r~   r   r   r   sizer   r   r   r   r   r   r   s      `            @r7   	save_filezMultipartUpload.save_file-  s2    	"GG$$Y/	wwy)'!%+
	 			$!5!55622!11 3 
 	 G$Q	2 	K8 x|[IJ	K %,,99'B   	   !!##!	   !!##s   +A/D33E)r   r,   rf   httpx.Clientr   rB   r}   
int | Noner~   
str | Noner   r   r:   rn   r:   r,   r:   dict[str, str]r   r   rh   bytesr:   rn   )rf   r   r   rB   r   r,   rh   r   r~   r   r}   r   r   r   )rf   r   r   rB   r   
str | Pathr}   r   r~   r   r   r   r:   r,   r<   r=   r>   rY   propertyr   r   r   r   r   r   classmethodr   r   r@   r9   r7   r{   r{      sn    "&#'&*% % 	%
 '% % !% $% 
%(    
  
 
 
-$
0	  $(!%&*#$ #$ '	#$
 #$ #$ !#$ #$ $#$ #$J  "&#'&*($ ($ '	($
 ($ ($ !($ $($ 
($ ($r9   r{   c                      e Zd Zdddd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       Zedd       Zedd       Zd ZddZ	dd	Z
edddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Zedddd	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Zy)AsyncMultipartUploadNr|   c                   || _         || _        || _        |xs t        | _        |xs d| _        |xs t        | _        d | _        d | _	        g | _
        y r   r   r   s          r7   rY   zAsyncMultipartUpload.__init__Z  r   r9   c                H    | j                   st        d      | j                   S r   r   r5   s    r7   r   zAsyncMultipartUpload.access_urln  r   r9   c                H    | j                   st        d      | j                   S r   r   r5   s    r7   r   zAsyncMultipartUpload.upload_idt  r   r9   c                   K   | j                   j                          d {   }|j                   d|j                   ddS 7 "wr   r   r   s     r7   r   z!AsyncMultipartUpload.auth_headersz  sH     ))3355 % 0 015;;-@%
 	
 6s   AA#Ac           
     d  K   | j                   j                          d {   }|j                   d}| j                   d {   }t	        | j
                  d|i |d| j                  | j                  d       d {   }|j                         }|d   | _	        |d   | _
        y 7 7 h7 -wr   )r   rl   r/   r   _async_maybe_retry_requestr   r~   r   r^   r   r   )r6   r-   r   r]   rg   r   s         r7   r   zAsyncMultipartUpload.create  s     ))3355&&''>?)))3LL, $ 1 1#'>>		

 

 !,/ ,! 6)

s3   B0B*"B0B,<B0 B.*B0,B0.B0c           	     :  K   | j                    d| j                   d| }| j                   d {   }t        | j                  d|i || j
                  dd|d        d {   }|j                  d   }| j                  j                  ||d       y 7 f7 4wr   )	r   r   r   _async_requestr   r~   r]   r   r   )r6   r   rh   r   r]   rg   r   s          r7   r   z AsyncMultipartUpload.upload_part  s     !T^^,<Ak]K)))'LL $ 1 1#-
 
 
 ')	
! *
s!   .BB3B$B%3BBc                   K   | j                    d| j                   d}| j                   d {   }t        | j                  d||d| j
                  i       d {    | j                   S 7 >7 wr   )r   r   r   r   r   r   )r6   r   r]   s      r7   r   zAsyncMultipartUpload.complete  su     !T^^,<IF)))(LL4;;'
 	
 	
  *	
s!   ,A1A--A1A/A1/A1r   c                 K    | ||||||      j                          d {    t        j                  t              j                  z        }dfd}	t        d|dz         D 
cg c]  }
t        j                   |	|
             }}
t        j                  j                        fd}t        j                  |D cg c]
  } ||       c}  d {    j                          d {   S 7 c c}
w c c}w 7 (7 w)Nr   c                   K   | dz
  j                   z  }||j                   z    }j                  | |       d {    y 7 w)Nr'   )r}   r   )r   r   chunkrh   r   s      r7   r   z.AsyncMultipartUpload.save.<locals>.upload_part  sH      1_	(<(<<E)=)=!=>E''U;;;s   :AAAr'   c                   K   4 d {    |  d {    d d d       d {    y 7 7 7 	# 1 d {  7  sw Y   y xY wwr2   r@   tasksems    r7   bounded_uploadz1AsyncMultipartUpload.save.<locals>.bounded_upload  D       

     D   A*A0,0A.A0AA9AAr   r   r:   rn   )r   r   r   r   r}   r   ru   create_task	Semaphorer   gatherr   )r   rf   r   r   rh   r~   r}   r   r   r   r   tasksr  r   r   r   s       `         @@r7   r   zAsyncMultipartUpload.save  s      '!%+
	    		#d)i&:&::;	<  %Q	2
 K 89
 
 	 9 9:	 nnF~d3FGGG'')))+ 	!
 GG)sL   "DC=AD/"C?9D
DD D	!D8D9D?DDc                 K   t         j                  j                        }t         j                  j                        } | ||||||      j	                          d {    t        j                  |j                  z        }	dfd}
t        d|	dz         D cg c]  }t        j                   |
|             }}t        j                  j                        fd}t        j                  |D cg c]
  } ||       c}  d {    j                          d {   S 7 c c}w c c}w 7 (7 w)Nr   c                  K   t        d      5 }| dz
  j                  z  }|j                  |       |j                  j                        }j	                  | |       d {    d d d        y 7 # 1 sw Y   y xY wwr   r   )r   r   r   rh   r   r   s       r7   r   z3AsyncMultipartUpload.save_file.<locals>.upload_part  s{     i& ?!$qI,@,@@uvvi223++K>>>	? ? ?	? ?s/   B AA4$A2%A4)	B 2A44A=9B r'   c                   K   4 d {    |  d {    d d d       d {    y 7 7 7 	# 1 d {  7  sw Y   y xY wwr2   r@   r   s    r7   r  z6AsyncMultipartUpload.save_file.<locals>.bounded_upload  r  r  r  )r   r   r   r   r   r   r   r}   r   ru   r  r  r   r  r   )r   rf   r   r   r}   r~   r   r   r   r   r   r   r  r  r   r   r   s      `           @@r7   r   zAsyncMultipartUpload.save_file  s!     GG$$Y/	wwy)'!%+
	    		$!5!556	?  %Q	2
 K 89
 
 	 9 9:	 nnF~d3FGGG'')))/ 	!
 GG)sN   A E%D2&>E$"D49E?D9ED>E-E .E4E E)r   r,   rf   httpx.AsyncClientr   rs   r}   r   r~   r   r   r   r:   rn   r   r   r   )rf   r  r   rs   r   r,   rh   r   r~   r   r}   r   r   r   r:   r,   )rf   r  r   rs   r   r   r}   r   r~   r   r   r   r:   r,   r   r@   r9   r7   r   r   Y  sx    "&#'&*% % "	%
 ,% % !% $% 
%(    
  
 
 
-&
2
  $(!%&*(* "(* ,	(*
 (* (* !(* (* $(* 
(* (*T  "&#'&*+* "+* ,	+*
 +* +* !+* $+* 
+* +*r9   r   c                      e Zd Zy)FalClientErrorNr<   r=   r>   r@   r9   r7   r  r    s    r9   r  c                  >    e Zd ZU ded<   ded<   ded<   ded<   dd	Zy
)FalClientHTTPErrorr,   messager   status_coder   response_headershttpx.Responserg   c                    | j                    S r2   )r  r5   s    r7   __str__zFalClientHTTPError.__str__  s    ,, r9   Nr   )r<   r=   r>   r?   r  r@   r9   r7   r  r    s    L$$!r9   r  c                  .    e Zd ZU ded<   dZded<   ddZy)FalClientTimeoutErrorfloatr   NOptional[str]
request_idc                t    | j                   d| j                   dS d| j                    d| j                   dS )NzRequest timed out after z secondszRequest z timed out after )r  r   r5   s    r7   r  zFalClientTimeoutError.__str__(  s>    ??"-dll^8DDdoo..?~XVVr9   r   )r<   r=   r>   r?   r  r  r@   r9   r7   r  r  #  s    N $J$Wr9   r  c                "   	 | j                          y # t        j                  $ rh}	 | j                         d   }n!# t        t
        f$ r | j                  }Y nw xY wt        || j                  t        | j                        |       |d }~ww xY w)Ndetailrg   )rc   r`   HTTPStatusErrorr^   r   KeyErrortextr  r  dictr]   )rg   excmsgs      r7   _raise_for_statusr'  /  s    !!#   	 --/(+CH% 	 --C	  !   !!"
 	s/    B;B	AB	A0B		Bc                      e Zd Zy)StatusNr  r@   r9   r7   r)  r)  B  s    r9   r)  c                      e Zd ZU dZded<   y)QueuedzIndicates the request is enqueued and waiting to be processed. The position
    field indicates the relative position in the queue (0-indexed).r   positionN)r<   r=   r>   __doc__r?   r@   r9   r7   r+  r+  F  s    G Mr9   r+  c                  *    e Zd ZU dZ e       Zded<   y)
InProgresszIndicates the request is currently being processed. If the status operation called
    with the `with_logs` parameter set to True, the logs field will be a list of
    log objects.list[dict[str, Any]] | NonelogsN)r<   r=   r>   r-  r
   r1  r?   r@   r9   r7   r/  r/  N  s    
 ).D
%/r9   r/  c                  B    e Zd ZU dZ e       Zded<    e       Zded<   y)	Completeda2  Indicates the request has been completed and the result can be gathered. The logs field will
    contain the logs if the status operation was called with the `with_logs` parameter set to True. Metrics
    might contain the inference time, and other internal metadata (number of tokens
    processed, etc.).r0  r1  dict[str, Any]metricsN)r<   r=   r>   r-  r
   r1  r?   r5  r@   r9   r7   r3  r3  X  s"    
 ).D
%/#gG^%r9   r3  T)frozenc                  t    e Zd ZU ded<    ed      Zded<    ed      Zded<    ed      Zded<   d
dZy	)_BaseRequestHandler,   r  Freprresponse_url
status_url
cancel_urlc                    |d   dk(  rt        |d         S |d   dk(  rt        |d         S |d   dk(  r"|j                  d	i       }t        |d   |
      S t	        d|d          )NstatusIN_QUEUEqueue_position)r,  IN_PROGRESSr1  )r1  	COMPLETEDr5  )r1  r5  zUnknown status: )r+  r/  getr3  r   )r6   rh   r5  s      r7   _parse_statusz _BaseRequestHandle._parse_statusj  s    >Z'4(8#9::(^},4<00(^{*hhy"-G$v,@@/X/?@AAr9   N)rh   AnyJSONr:   r)  )	r<   r=   r>   r?   r
   r;  r<  r=  rE  r@   r9   r7   r8  r8  c  s:    O5)L#)'J''J'
Br9   r8  	workflowscomfyc                    dd l }| j                  d      }t        |      dkD  r| S |j                  d|       }|r|j	                         \  }}| d| S t        d|  d      )Nr   r&   r'   z^([0-9]+)-([a-zA-Z0-9-]+)$zInvalid app id: z*. Must be in the format <appOwner>/<appId>)resplitr   matchgroupsr   )idrJ  r   rL  	app_ownerapp_ids         r7   _ensure_app_id_formatrQ  z  sm    HHSME
5zA~	HH2B7E!LLN	6AfX&&
't+UV
WWr9   c                  H    e Zd ZU ded<   ded<   ded<   ded<   ed	d       Zy)
AppIdr,   owneraliasr  r   	namespacec           	         t        |      }|j                  d      }|d   t        v r+ | |d   |d   dj                  |dd        xs d |d         S  | |d   |d   dj                  |dd        xs d d       S )Nr&   r   r'         )rT  rU  r   rV  )rQ  rK  APP_NAMESPACESjoin)r   endpoint_idnormalized_idr   s       r7   from_endpoint_idzAppId.from_endpoint_id  s    -k:##C(8~%AhAhXXeABi(0D(	  ((%)$,	
 	
r9   N)r\  r,   r:   rS  )r<   r=   r>   r?   r   r^  r@   r9   r7   rS  rS    s*    JJ

 
r9   rS  x   g     V@)r'   <   c                    | j                   r| j                    dnd}| j                  rd| j                   nd}| | j                   d| j                   | S )Nr&   rE   )rV  r   rT  rU  )rP  prefixsuffixs      r7   _format_app_pathrd    sX    '-'7'7  !#RF"(++q2FXfll^1V\\N6(;;r9   c                n    | y t         \  }}|| cxk  r|k  sn t        d| d| d      t        |       S )Nzmax_buffering must be between z and z (inclusive))REALTIME_MAX_BUFFERINGr   r,   )value	min_value	max_values      r7   _serialize_max_bufferingrj    sL    }1Iy+)+,YKuYK|T
 	
 u:r9   rE   r   max_bufferingc                   t         j                  |       }t        |      }t         | }|r|d|j	                  d      z   z  }i }|r||d<   t        |      }|||d<   |r| dt        |       S |S )Nr&   fal_jwt_tokenrl  ?)rS  r^  rd  REALTIME_URL_FORMATlstriprj  r   )	applicationr-   r   rl  rP  app_pathr   queryserialized_bufferings	            r7   _build_runner_ws_urlrv    s     ##K0F'H !(
,CsT[[%%%E!&o3MB'!5oa	%()**Jr9   realtimer   c                    t        | |||      S )Nrk  )rv  )rr  r-   rl  r   s       r7   _build_realtime_urlrz    s      #	 r9   c                    t        | t              r| S t        | t              rHt        | j                  d      t              r| d   S t        | j                  d      t              r| d   S t	        d      )Nr-   r  z)Unexpected realtime token response format)
isinstancer,   r$  rD  RuntimeError)rh   s    r7   _parse_token_responser~    sa    $$dhhw'-= dhhx(#.>!
B
CCr9   c                  4     e Zd ZdZ	 	 d	 	 	 	 	 d fdZ xZS )RealtimeErrorz9Raised when the realtime endpoint sends an error payload.c                    || _         |xs d| _        |xs i | _        | j                  s|n| d| j                   }t        |   |       y )NrE   z: )errorreasonpayloadsuperrY   )r6   r  r  r  r  	__class__s        r7   rY   zRealtimeError.__init__  sK     
l}"#{{%5'DKK=0I!r9   )NN)r  r,   r  r   r  zOptional[dict[str, Any]])r<   r=   r>   r-  rY   __classcell__)r  s   @r7   r  r    s4    C
 ",0	
"
" 
" *	
" 
"r9   r  c                0    dd l }|j                  | d      S )Nr   F)raw)msgpackunpackbr  r  s     r7   msgpack_decode_messager    s    ??7?..r9   c                0    dd l }|j                  | d      S )Nr   T)use_bin_type)r  packbr  s     r7   msgpack_encode_messager    s    ==t=44r9   c                   t        | t              r| j                         } t        | t        t        f      r|xs t
        } ||       S t        | t              r`	 t        j                  |       }|j                  d      }|dk(  r,t        |j                  dd      |j                  d      |      |dk(  ry |S d	| iS # t        j                  $ r d| dcY S w xY w)
Nr#  )typer  r  zx-fal-errorr  UNKNOWN_ERRORr  zx-fal-messager  )r|  
memoryviewtobytesr   	bytearrayr  r,   r^   loadsJSONDecodeErrorrD  r  )r  decode_messagedecoder  msg_types        r7   _decode_realtime_messager  	  s     ':&//#'E9-.9#9g'3	8jj)G ;;v&}$G_5H% 
 &w ## 	8"w77	8s   B= =CCc                &    |xs t         } ||       S r2   )r  )r  encode_messageencodes      r7   _encode_realtime_messager  (  s     55F'?r9   c                  `    e Zd ZU dZded<   dZded<   dZded<   dd	Zdd
ZddZ	ddZ
ddZy)RealtimeConnectionz(Synchronous realtime connection wrapper.z'Connection'_wsNCallable[[Any], bytes] | None_encode_messageCallable[[bytes], Any] | None_decode_messagec                f    t        || j                        }| j                  j                  |       y r2   r  r  r  sendr6   	argumentsr  s      r7   r  zRealtimeConnection.send8  s$    *9d6J6JKgr9   c                n    	 | j                   j                         }t        || j                        }|4|S r2   r  recvr  r  r6   rg   decodeds      r7   r  zRealtimeConnection.recv<  s3    xx}}H.x9M9MNGNr9   c                X    t        | j                  dd       }t        |      r |        y y Nclosegetattrr  callabler6   r  s     r7   r  zRealtimeConnection.closeD  s%    '40E?G r9   c                    | S r2   r@   r5   s    r7   	__enter__zRealtimeConnection.__enter__I  s    r9   c                $    | j                          y r2   r  r6   exc_typer%  tbs       r7   __exit__zRealtimeConnection.__exit__L  s    

r9   r  r4  r:   rn   r:   r4  r:   rn   )r:   r  )r<   r=   r>   r-  r?   r  r  r  r  r  r  r  r@   r9   r7   r  r  0  s:    2	59O2959O29
r9   r  c                  `    e Zd ZU dZded<   dZded<   dZded<   dd	Zdd
ZddZ	ddZ
ddZy)AsyncRealtimeConnectionz)Asynchronous realtime connection wrapper.z'WebSocketClientProtocol'r  Nr  r  r  r  c                   K   t        || j                        }| j                  j                  |       d {    y 7 wr2   r  r  s      r7   r  zAsyncRealtimeConnection.sendX  s.     *9d6J6JKhhmmG$$$s   5?=?c                   K   	 | j                   j                          d {   }t        || j                        }|<|S 7 wr2   r  r  s      r7   r  zAsyncRealtimeConnection.recv\  s?     !XX]]_,H.x9M9MNGN	 -s   AA Ac                t   K   t        | j                  dd       }t        |      r |        d {    y y 7 wr  r  r  s     r7   r  zAsyncRealtimeConnection.closed  s0     '40E?'MM s   -868c                   K   | S wr2   r@   r5   s    r7   
__aenter__z"AsyncRealtimeConnection.__aenter__i  s     s   c                @   K   | j                          d {    y 7 wr2   r  r  s       r7   	__aexit__z!AsyncRealtimeConnection.__aexit__l  s     jjls   r  r  r  )r:   r  )r<   r=   r>   r-  r?   r  r  r  r  r  r  r  r@   r9   r7   r  r  P  s:    3	""59O2959O29%
r9   r  c              #  |   K   ddl m} |j                  | |t        d       5 }| d d d        y # 1 sw Y   y xY ww)Nr   )rf   )additional_headersopen_timeoutmax_size)websockets.syncrf   connectREALTIME_OPEN_TIMEOUT)r   r]   rf   wss       r7   _connect_sync_wsr  p  sF      '	"*	 
 
 
 
  s    <0	<9<c                  K   dd l }|j                  | |t        d       4 d {   }| d d d       d {    y 7 7 # 1 d {  7  sw Y   y xY ww)Nr   )extra_headersr  r  )
websocketsr  r  )r   r]   r  r  s       r7   _connect_async_wsr    sc      !!*	 "   
 
      s@   "A?AAAAAAA	A
AAc                D     | j                   ||fi |}t        |       |S r2   requestr'  rf   methodr   kwargsrg   s        r7   r   r     s(     v~~fc4V4HhOr9   c                `   K    | j                   ||fi | d {   }t        |       |S 7 wr2   r  r  s        r7   r   r     s4      $V^^FC:6::HhO ;s   .,.皙?   )i  i  i  )i  i    c                f    | j                   t        vryd| j                  v ryd| j                  v ryy)z-Tell apart ingress errors from client errors.Fzx-fal-request-idnginxT)r  INGRESS_ERROR_CODESr]   r#  r   s    r7   _is_ingress_errorr    s;     #66X--- (--r9   c                    | j                   dk(  r | j                  j                  t              ryt	        |       ry| j                   t
        v s| j                   |v ryy)Nr  FT)r  r]   rD  r!   r  RETRY_CODES)rg   extra_retry_codess     r7   _should_retry_responser    sZ    
 s"x'7'7';';#( "{*h.B.BFW.Wr9   c                n   t        | t        j                        r;	 | j                  }t        |t        j                        rt
        |j                  v ryyt        | t        j                        ryt        | t        j                  t        f      rt        | j                  |      S y# t        $ r Y yw xY w)NFT)r|  r`   TimeoutExceptionr  Requestr"   r]   r}  TransportErrorr!  r  r  rg   )r%  r  r  s      r7   _should_retryr    s    #u--.	kkG'5==1)W__<  #u++,#--/ABC%cll4EFF  		s   8B( (	B43B4c                    |dk(  rt        |d| dz
  z  z  |      }nt        ||      }|r|t        j                  dd      z  }t        ||      S )NexponentialrX  r'   g      ?g      ?)rM   randomuniform)	num_retry
base_delay	max_delaybackoff_typejitterdelays         r7   _get_retry_delayr    sW     }$J!	A"67CJ	*S))ui  r9   )r  c                  t        dt        dz         D ]  }	 t        | ||fi |c S  t        d      # t        j                  t
        f$ rr}t        ||      r`|t        k  rWt        |t        t        dd      }t        j                  d| d| dt        |z
   d       t        j                  |       Y d }~ d }~ww xY w)	Nr'   r  TRetrying request to  due to  ( attempts left)Failed to perform request)r   MAX_ATTEMPTSr   r`   	HTTPErrorr  r  r  
BASE_DELAY	MAX_DELAYloggerdebugtimesleepr}  rf   r  r   r  r  attemptr%  r  s           r7   r   r     s     L1,- 	FFC:6:: 2
33 !34 
	S"34<9O(ZM4 *3%xuB|g?U>VVef 

5!
	s   4B?A'B:9B::B?c                 K   t        dt        dz         D ]  }	 t        | ||fi | d {   c S  t        d
      7 # t        j                  t
        f$ rs}t        ||      ra|t        k  rXt        |dddd      }t        j                  d| d| dt        |z
   d	       t        j                  |       d {  7   Y d }~ d }~ww xY ww)Nr'   r  ry   r  Tr  r  r   r  r  )r   r  r   r`   r  r  r  r  r  r  ru   r
  r}  r  s           r7   r   r     s      L1,- 
	'FvFFF 2
33 G!34 	S"34<9O(#r=$O*3%xuB|g?U>VVef mmE***	sN   CA >A CA  CA"C;B><CCCCCSyncRequestHandlec                D    	 | j                          y # t        $ r Y y w xY wr2   cancel	Exceptionhandles    r7   _maybe_cancel_requestr  #  s"     s    	AsyncRequestHandlec                `   K   	 | j                          d {    y 7 # t        $ r Y y w xY wwr2   r  r  s    r7   _async_maybe_cancel_requestr  *  s+     mmo s(   .  . 	+.+.c                      e Zd ZU  ed      Zded<   e	 	 	 	 	 	 	 	 dd       ZddddZddd		 	 	 	 	 dd
Z	ddZ
ddZy)r  Fr9  r   rf   c                    t         j                  |      }|j                  r|j                   dnd}t         | |j                   d|j
                   d| } | |||dz   |dz   |      S Nr&   rE   z
/requests/z/statusz/cancelr  r;  r<  r=  rf   rS  r^  rV  QUEUE_URL_FORMATrT  rU  r   rf   rr  r  rP  rb  r_   s          r7   from_request_idz!SyncRequestHandle.from_request_id5       ''4+1+;+;F$$%Q'&'x~Qv||nJWaVbc!!)+)+
 	
r9   	with_logsc                   t        | j                  d| j                  d|i      }t        |       | j	                  |j                               S )Returns the status of the request (which can be one of the following:
        Queued, InProgress, Completed). If `with_logs` is True, logs will be included
        for InProgress and Completed statuses.GETr1  params)r   rf   r<  r'  rE  r^   r6   r#  rg   s      r7   r?  zSyncRequestHandle.statusG  sJ    
 (KKOO		
 	(#!!(--/22r9   r  r#  intervalc             #     K   	 | j                  |      }| t        |t              ryt        j                  |       =wzContinuously poll for the status of the request and yield it at each interval till
        the request is completed. If `with_logs` is True, logs will be included in the response.
        r"  N)r?  r|  r3  r	  r
  r6   r#  r+  r?  s       r7   iter_eventszSyncRequestHandle.iter_eventsX  s>      [[9[5FL&),JJx  s   ?Ac                    | j                  d      D ]  } t        | j                  d| j                        }t	        |       |j                         S )zOWait till the request is completed and return the result of the inference call.Fr"  r&  )r/  r   rf   r;  r'  r^   r6   _rg   s      r7   rD  zSyncRequestHandle.getg  sP    !!E!2 	A	 (UD<M<MN(#}}r9   c                \    t        | j                  d| j                        }t        |       yzCancel the request.r   N)r   rf   r=  r'  r6   rg   s     r7   r  zSyncRequestHandle.cancelp  s'    'KKOO

 	(#r9   N)rf   r   rr  r,   r  r,   r:   r  r#  r;   r:   r)  )r#  r;   r+  r  r:   zIterator[Status]r:   rF  r  r<   r=   r>   r
   rf   r?   r   r   r?  r/  rD  r  r@   r9   r7   r  r  1  s     e,FL,

 
 	

 

 
" +0 3$ $)C! !49!	!$r9   c                      e Zd ZU  ed      Zded<   e	 	 	 	 	 	 	 	 dd       ZddddZddd		 	 	 	 	 dd
Z	ddZ
ddZy)r  Fr9  r  rf   c                    t         j                  |      }|j                  r|j                   dnd}t         | |j                   d|j
                   d| } | |||dz   |dz   |      S r  r  r  s          r7   r   z"AsyncRequestHandle.from_request_id~  r!  r9   r"  c                  K   t        | j                  d| j                  d|i       d{   }t        |       | j	                  |j                               S 7 .w)r%  r&  r1  r'  N)r   rf   r<  r'  rE  r^   r)  s      r7   r?  zAsyncRequestHandle.status  sX     
 4KKOO		
 
 	(#!!(--/22
s   )AA/Ar  r*  c                 K   	 | j                  |       d{   }| t        |t              ryt        j                  |       d{    N7 87 wr-  )r?  r|  r3  ru   r
  r.  s       r7   r/  zAsyncRequestHandle.iter_events  sP      ;;;;;FL&),--))) ;
 *s!   AA2AAAAc                   K   | j                  d      2 3 d{   }
7 6 t        | j                  d| j                         d{  7  }t	        |       |j                         S w)z9Wait till the request is completed and return the result.Fr"  Nr&  )r/  r   rf   r;  r'  r^   r1  s      r7   rD  zAsyncRequestHandle.get  sn     ''%'8 	 	!	8 4KK
 
 

 	(#}}s+   A'!!A'!%A'A	 A'c                x   K   t        | j                  d| j                         d{   }t        |       y7 wr4  )r   rf   r=  r'  r5  s     r7   r  zAsyncRequestHandle.cancel  s5     3KKOO
 

 	(#
s   %:8:N)rf   r  rr  r,   r  r,   r:   r  r6  )r#  r;   r+  r  r:   zAsyncIterator[Status]r7  r  r8  r@   r9   r7   r  r  z  s     %5 1F1
!
 
 	

 

 
" 16 3$ $)C* *49*	*$r9   c            
      P   e Zd ZU  edd      Zded<   dZded<   ed)d	       Zd)d
Z	d*dZ
ed+d       Zed,d       Zd,dZed	 	 	 	 	 d-dZddddi d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d.dZddddi dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d/dZddddddi ddd		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d0dZd1dZdd	 	 	 	 	 	 	 d2dZd3dZd4dZddd	 	 	 	 	 	 	 	 	 d5dZ	 d6	 	 	 	 	 	 	 d7d Zd8d!Zd9d:d"Zed#d$deddd%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d;d&       Zed#dded'	 	 	 	 	 	 	 	 	 	 	 d<d(       Zy)=rw   NFdefaultr:  r   key      ^@r  default_timeoutc                Z    | j                   
t               S t        d| j                         S NKeyrB  r   r   r5   s    r7   rL   zAsyncClient._auth  &    88)++udhh//r9   c                    | j                   S r2   rL   r5   s    r7   	_get_authzAsyncClient._get_auth      zzr9   c                    | j                         }|j                  j                         dk7  rt        d      |j                  S NrB  zZKey credentials are required for this operation. Set FAL_KEY or FAL_KEY_ID/FAL_KEY_SECRET.rL  schemelowerr   r-   rW   s     r7   _get_keyzAsyncClient._get_key  ?    ~~;;%')l  zzr9   c                4    t        | j                               S r2   )rs   rL  r5   s    r7   r   zAsyncClient._token_manager  s    #DNN$455r9   c                    | j                         }t        j                  |j                  t        d| j
                        S )Nr   r]   r   )rL  r`   rw   rU   
USER_AGENTrD  rW   s     r7   r   zAsyncClient._client  s=    ~~  !%!2!2( ((
 	
r9   c                   K   | j                   j                          d {   }t        j                  |j                   d|j
                   t        d| j                        S 7 EwNr   r   rW  )r   rl   r`   rw   r.   r-   rX  rD  r   s     r7   _get_cdn_clientzAsyncClient._get_cdn_client  sa     ))3355  $)$4$4#5Qu{{m!D( ((
 	
 6s   A(A&AA(token_expirationc                  K   t         j                  |      j                  g|d}t        | j                  dt
         d|       d {   }t        |j                               S 7 wN)allowed_appsr]  r   z/tokens/)r^   )rS  r^  rU  r   r   rS   r~  r^   r6   rr  r]  r  rg   s        r7   _get_realtime_tokenzAsyncClient._get_realtime_token  si      #33K@FFG 0
 4LLj!	
 
 %X]]_55
s   AA)	A'
A)rE   r   r   start_timeouthintr]   c                 K   t         |z   }|r|d|j                  d      z   z  }i |}	|t        ||	       |t        ||	       t	        | j
                  d||||	       d{   }
t        |
       |
j                         S 7 w)ad  Run an application with the given arguments (which will be JSON serialized). The path parameter can be used to
        specify a subpath when applicable. This method will return the result of the inference call directly.

        Args:
            timeout: Client-side HTTP timeout in seconds. Controls how long the HTTP
                client waits for a response. Defaults to the client's default_timeout.
            start_timeout: Server-side request timeout in seconds. Limits total time spent
                waiting before processing starts. Does not apply once the application begins processing.
        r&   Nr   r^   r   r]   )RUN_URL_FORMATrq  r    r   r   r   r'  r^   r6   rr  r  r   r   rd  re  r]   r   rV   rg   s              r7   runzAsyncClient.run  s     * {*3S)))C#.g; D(+$}h73LL
 
 	(#}}
s   A!B#B$ Br   re  webhook_urlpriorityr]   rd  c                 K   t         |z   }	|r|	d|j                  d      z   z  }	||	dt        d|i      z   z  }	i |}
|t        ||
       |t	        ||
       |t        ||
       t        | j                  d|	|| j                  |
       d{   }t        |       |j                         }t        |d   |d   |d	   |d
   | j                        S 7 Ew)aP  Submit an application with the given arguments (which will be JSON serialized). The path parameter can be used to
        specify a subpath when applicable. This method will return a handle to the request that can be used to check the status
        and retrieve the result of the inference call when it is done.

        Args:
            start_timeout: Server-side request timeout in seconds. Limits total time spent
                waiting before processing starts (includes queue wait, retries, and
                routing). Does not apply once the application begins processing.
        r&   Nro  fal_webhookr   rg  r  r;  r<  r=  r  )r  rq  r   r    r   r   r   r   rD  r'  r^   r  r6   rr  r  r   re  rl  rm  r]   rd  r   rV   rg   rh   s                r7   r   zAsyncClient.submit6  s     , ,3S)))C"3M;#?@@@C#.g; D(+(3$}h73LL((
 
 	(#}}!L)n-L)L)<<
 	

s   BCCAC	r   re  r#  
on_enqueueon_queue_updaterm  r]   rd  client_timeoutc       	           	
K   |-
|
n(
|kD  r#t        j                  d
 d| dt        d       dgd	 
fd}| |        d{   S 	 t        j                   |       |       d{   S 7 )7 # t        j
                  $ r<}d}d	   }| |j                  }t        |       d{  7   t        ||
      |d}~ww xY ww)<  Subscribe to an application and wait for the result.

        Args:
            start_timeout: Server-side request timeout in seconds. Limits total time spent
                waiting before processing starts (includes queue wait, retries, and
                routing). Does not apply once the application begins processing.
            client_timeout: Client-side total timeout in seconds. Limits the total time
                spent waiting for the entire request to complete (including queue wait
                and processing). If not set, waits indefinitely.
        Nstart_timeout ("s) is larger than client_timeout (Ts). The request may timeout on the client before the server-side timeout is reached.rX  
stacklevelc            	     
  K   j                  	
       d {   } | d<    | j                         $| j                        2 3 d {   } |       | j                          d {   S 7 [7 '6 7 
wN)r   re  rm  r]   rd  r   r"  r   r  r/  rD  r  eventrr  r  
handle_refr]   re  rr  rs  r   rm  r6   rd  r#  s     r7   _do_subscribez,AsyncClient.subscribe.<locals>._do_subscribe  s     ;;!+ '  F #JqM%6,,-*#)#5#5	#5#J + +%#E*%%%+#J &sE   BA;1BA?A=A?B6B7B=A??BBr   r   r   r  r7  )	warningswarnUserWarningru   wait_forTimeoutErrorr  r  r  )r6   rr  r  r   re  r#  rr  rs  rm  r]   rd  rt  r  er  r  r  s   ```````````     @r7   	subscribezAsyncClient.subscriber  s     2 %$ ./%m_4VWeVf gg g 	 ;?
	& 	& 	&* !&((	 ))-/>RRR ) S## 
	J]F!#..
1&999'&% 
	sT   ACBC$B B
B C
B C#CCCCCc                D    t         j                  | j                  ||      S r2   )r  r   r   r6   rr  r  s      r7   
get_handlezAsyncClient.get_handle  s    !11$,,ZXXr9   r"  c               f   K   | j                  ||      }|j                  |       d {   S 7 wNr"  r  r?  r6   rr  r  r#  r  s        r7   r?  zAsyncClient.status  s/      j9]]Y]7777s   (1/1c                b   K   | j                  ||      }|j                          d {   S 7 wr2   r  rD  r6   rr  r  r  s       r7   r   zAsyncClient.result  s(     j9ZZ\!!!s   &/-/c                d   K   | j                  ||      }|j                          d {    y 7 wr2   r  r  r  s       r7   r  zAsyncClient.cancel  s%     j9mmos   &0.0/streamr   r   c              F  K   t         |z   }|r|d|j                  d      z   z  }t        | j                  d|||      4 d{   }|j	                         2 3 d{   }|j                          7 17 6 ddd      d{  7   y# 1 d{  7  sw Y   yxY wway  Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported
        at a few select applications at the moment, so be sure to first consult with the documentation of individual applications
        to see if this is supported.

        The function will iterate over each event that is streamed from the server.
        r&   r   )r^   r   N)rh  rq  r   r   	aiter_sser^   r6   rr  r  r   r   r   eventsr  s           r7   streamzAsyncClient.stream  s      {*3S)))CLL
 	# 	# %//1 # #ejjl"	##1	# 	# 	# 	# 	#sl   AB!A5B!BA9A7A9 B5B!7A99B:B!BB!BBBB!c                  K   | j                          d{   }t        |t              r|j                  d      }t	        |      t
        kD  r0|d}t        j                  || j                  |||       d{   S d|i}|||d<   |j                  t        dz   ||       d{   }t        |       |j                         d	   S 7 7 R7 &w)
Upload the given data blob to the CDN and return the access URL. The content type should be specified
        as the second argument. Use upload_file or upload_image for convenience.Nutf-8
upload.binrf   r   r   rh   r~   rK   r   /files/uploadr   r]   r   )r[  r|  r,   r  r   MULTIPART_THRESHOLDr   r   r   rb   CDN_URLr'  r^   r6   rh   r~   r   rf   r]   rg   s          r7   uploadzAsyncClient.upload  s      ++--dC ;;w'Dt9** (	-22"11#) 3    "<0 )2G%&o% % 
 

 	(#}}|,,7 .
s4   CC
A"C9C:-C'C(#CCCc                  K   t        j                  |      \  }}|d}t        j                  j	                  |      t
        kD  rL| j                          d{   }t        j                  t        |      || j                  |       d{   S t        |d      5 }| j                  |j                         |t        j                  j                  |             d{   cddd       S 7 7 c7 # 1 sw Y   yxY wwzMUpload a file from the local filesystem to the CDN and return the access URL.Nr   )r   rf   r   r~   r   )r   )	mimetypes
guess_typer   r   r   r  r[  r   r   r,   r   r   r  r   r   r6   r   	mime_typer2  rf   files         r7   upload_filezAsyncClient.upload_file  s      !++D1	12I77??4 #66//11F-77d)"11&	 8    $ 			Y"''2B2B42H %  	 	 2	 	sO   AD C.3D C0D AC4 C2!C4$D 0D 2C44C=9D c                   K   t        j                         5 }|j                  ||       | j                  |j	                         d|        d{   cddd       S 7 # 1 sw Y   yxY wwzBUpload a pillow image object to the CDN and return the access URL.formatimage/NioBytesIOr   r  getvaluer6   imager  buffers       r7   upload_imagezAsyncClient.upload_image$  sd      ZZ\ 	KVJJvfJ-V__%6&8IJJ	K 	KJ	K 	Ks.   A-:A!AA!
A-A!!A*&A-T	/realtimeuse_jwtr   rl  r]  r  r  c              X  K   d }d }	|r| j                  ||       d {   }	n#| j                         }
|
j                  t        d}t	        ||	||      }t        ||      4 d {   }t        |||       d d d       d {    y 7 o7 (7 	# 1 d {  7  sw Y   y xY wwNr\  r   rx  r   )r  r  )rb  rL  rU   rX  rz  r  r  r6   rr  r  r   rl  r]  r  r  r]   r-   rX   r   r  s                r7   rw  zAsyncClient.realtime+  s      *. 22.> 3  E >>#D(,(9(9TG!+um$O$S': 	 	b)NN 	 	 		 	 	 	 	sX   B*BAB*(B)B*,B>B*	B
B*B*B*B'BB'#B*r  r   rl  r]  c              @  K   d }d }|r| j                  ||       d {   }n#| j                         }|j                  t        d}t	        ||||      }	t        |	|      4 d {   }
|
 d d d       d {    y 7 c7 7 	# 1 d {  7  sw Y   y xY wwNr\  r   rk  r   )rb  rL  rU   rX  rv  r  r6   rr  r  r   rl  r]  r]   r-   rX   r   r  s              r7   
ws_connectzAsyncClient.ws_connectG  s      *. 22.> 3  E >>#D(,(9(9TG"'	
 %S': 	 	bH	 	 		 	 	 	 	sX   BBAB(B)B,B	2B=B>BBB	BBBBr:   r   r   )r:   rs   )r:   r  rr  r,   r]  r   r:   r,   rr  r,   r  rF  r   r,   r   Optional[Union[int, float]]rd  r  re  r   r]   r   r:   rF  )rr  r,   r  rF  r   r,   re  r   rl  r   rm  Optional[Priority]r]   r   rd  r  r:   r  rr  r,   r  rF  r   r,   re  r   r#  r;   rr  zOptional[Callable[[str], None]]rs  z"Optional[Callable[[Status], None]]rm  r  r]   r   rd  r  rt  r  r:   rF  )rr  r,   r  r,   r:   r  rr  r,   r  r,   r#  r;   r:   r)  rr  r,   r  r,   r:   rF  rr  r,   r  r,   r:   rn   )
rr  r,   r  rF  r   r,   r   float | Noner:   zAsyncIterator[dict[str, Any]]r2   rh   str | bytesr~   r,   r   r   r:   r,   r   zos.PathLiker:   r,   jpegr  zImage.Imager  r,   r:   r,   )rr  r,   r  r;   r   r,   rl  r   r]  r   r  r  r  r  r:   z&AsyncIterator[AsyncRealtimeConnection])rr  r,   r  r;   r   r,   rl  r   r]  r   r:   (AsyncIterator['WebSocketClientProtocol'])r<   r=   r>   r
   rB  r?   rD  r   rL   rL  rS  r   r   r[  !REALTIME_TOKEN_EXPIRATION_SECONDSrb  rj  r   r  r  r?  r   r  r  r  r  r  r   rw  r  r@   r9   r7   rw   rw     s   Du5C5"OU"0 0
 6 6 
 

 !B	66 	6
 
6. /359"$,, ,
 , -, 3, ,  , 
,f "&'+"$59:
:
 :

 :
 :
  :
 %:
  :
 3:
 
:
B 6:>B'+"$596:JJ J
 J J J 4J <J %J  J 3J 4J 
JXY GL88,/8?C8	8"  $## #
 # # 
'#< MQ!-!-/2!-?I!-	!-F*K 
 $( A8<8< 	
  "  6 6 
0 6 
 $( A 	
  "  
2 r9   rw   c            
      b   e Zd ZU  edd      Zded<   dZded<   ed*d	       Zd*d
Z	d+dZ
ed,d       Zed-d       Zed.d       Zd,dZed	 	 	 	 	 d/dZddddi d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d0dZddddi dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d1dZddddddi ddd		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d2dZd3dZdd	 	 	 	 	 	 	 d4dZd5dZd6dZddd	 	 	 	 	 	 	 	 	 d7d Z	 d8	 	 	 	 	 	 	 d9d!Zd:d"Zd;d<d#Zed$d%deddd&	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d=d'       Zed$dded(	 	 	 	 	 	 	 	 	 	 	 d>d)       Zy)?
SyncClientNFr@  r   rB  rC  r  rD  c                Z    | j                   
t               S t        d| j                         S rF  rH  r5   s    r7   rL   zSyncClient._authj  rI  r9   c                    | j                   S r2   rK  r5   s    r7   rL  zSyncClient._get_authp  rM  r9   c                    | j                         }|j                  j                         dk7  rt        d      |j                  S rO  rP  rW   s     r7   rS  zSyncClient._get_keys  rT  r9   c                    | j                         }t        j                  |j                  t        d| j
                  d      S )Nr   T)r]   r   follow_redirects)rL  r`   ra   rU   rX  rD  rW   s     r7   r   zSyncClient._client{  s>    ~~||!%!2!2( ((!
 	
r9   c                4    t        | j                               S r2   )rB   rL  r5   s    r7   r   zSyncClient._token_manager  s    t~~/00r9   c                    t         S r2   )EXECUTORr5   s    r7   	_executorzSyncClient._executor  s    r9   c                    | j                   j                         }t        j                  |j                   d|j
                   t        d| j                        S rZ  )r   rl   r`   ra   r.   r-   rX  rD  r   s     r7   r[  zSyncClient._get_cdn_client  sS    ##--/||$)$4$4#5Qu{{m!D( ((
 	
r9   r\  c                   t         j                  |      j                  g|d}t        | j                  dt
         d|      }t        |j                               S r_  )rS  r^  rU  r   r   rS   r~  r^   ra  s        r7   rb  zSyncClient._get_realtime_token  s[     #33K@FFG 0
 (LLj!	
 %X]]_55r9   rE   rc  c                   t         |z   }|r|d|j                  d      z   z  }i |}	|t        ||	       |t        ||	       t	        | j
                  d||||	      }
t        |
       |
j                         S )a  Run an application with the given arguments (which will be JSON serialized).

        Args:
            timeout: Client-side HTTP timeout in seconds. Controls how long the HTTP
                client waits for a response. Defaults to the client's default_timeout.
            start_timeout: Server-side request timeout in seconds. Limits total time spent
                waiting before processing starts. Does not apply once the application begins processing.
        r&   r   rg  )rh  rq  r    r   r   r   r'  r^   ri  s              r7   rj  zSyncClient.run  s    ( {*3S)))C#.g;D(+$}h7'LL
 	(#}}r9   rk  c                  t         |z   }	|r|	d|j                  d      z   z  }	||	dt        d|i      z   z  }	i |}
|t        ||
       |t	        ||
       |t        ||
       t        | j                  d|	|| j                  |
      }t        |       |j                         }t        |d   |d   |d   |d	   | j                  
      S )ag  Submit an application with the given arguments (which will be JSON serialized).

        Args:
            start_timeout: Server-side request timeout in seconds. Limits total time spent
                waiting before processing starts (includes queue wait, retries, and
                routing). Does not apply once the application begins processing.
        r&   ro  ro  r   rg  r  r;  r<  r=  r  )r  rq  r   r    r   r   r   r   rD  r'  r^   r  rp  s                r7   r   zSyncClient.submit  s    ( ,3S)))C"3M;#?@@@C#.g;D(+(3$}h7'LL((
 	(#}} L)n-L)L)<<
 	
r9   rq  c       	           	
 |-
|
n(
|kD  r#t        j                  d
 d| dt        d       dgd	 
fd}| |       S  j                  j	                  |      }	 |j                  |      S # t        j                  j                  $ r3}d}d	   }||j                  }t        |       t        ||
      |d}~ww xY w)rv  Nrw  rx  ry  rX  rz  c            	         j                  	
      } | d<    | j                         | j                        D ]
  } |        | j                         S r}  r~  r  s     r7   r  z+SyncClient.subscribe.<locals>._do_subscribe4  s    [[!+ ! F #JqM%6,,-*#//)/D +E#E*+ ::<r9   r  r   r  r7  )r  r  r  r  r   r   r   r   r  r  r  r  )r6   rr  r  r   re  r#  rr  rs  rm  r]   rd  rt  r  r   r  r  r  r  s   ```````````      @r7   r  zSyncClient.subscribe  s    2 %$ ./%m_4VWeVf gg g 	 :>
	  	  	 * ! ?"&&}5	===88!!.. 
	J]F!#..
%f-'&% 
	s   5B C$.CCc                D    t         j                  | j                  ||      S r2   )r  r   r   r  s      r7   r  zSyncClient.get_handle[  s     00{JWWr9   r"  c               J    | j                  ||      }|j                  |      S r  r  r  s        r7   r?  zSyncClient.status^  s%     j9}}y}11r9   c                F    | j                  ||      }|j                         S r2   r  r  s       r7   r   zSyncClient.resultd  s    j9zz|r9   c                H    | j                  ||      }|j                          y r2   r  r  s       r7   r  zSyncClient.cancelh  s    j9r9   r  r  c             #     K   t         |z   }|r|d|j                  d      z   z  }t        | j                  d|||      5 }|j	                         D ]  }|j                           	 ddd       y# 1 sw Y   yxY wwr  )rh  rq  r   r   iter_sser^   r  s           r7   r  zSyncClient.streaml  s}      {*3S)))CLL&#Iw
 	#* #jjl"#	# 	# 	#s   =A=(A1(	A=1A:6A=c                `   | j                         }t        |t              r|j                  d      }t	        |      t
        kD  r(|d}t        j                  || j                  |||      S d|i}|||d<   |j                  t        dz   ||      }t        |       |j                         d   S )	r  r  r  r  rK   r   r  r  r   )r[  r|  r,   r  r   r  r{   r   r   rb   r  r'  r^   r  s          r7   r  zSyncClient.upload  s     %%'dC ;;w'Dt9** (	"''"11#) (   "<0 )2G%&;;o%  

 	(#}}|,,r9   c                   t        j                  |      \  }}|d}t        j                  j	                  |      t
        kD  r<| j                         }t        j                  t        |      || j                  |      S t        |d      5 }| j                  |j                         |t        j                  j                  |            cddd       S # 1 sw Y   yxY wr  )r  r  r   r   r   r  r[  r{   r   r,   r   r   r  r   r   r  s         r7   r  zSyncClient.upload_file  s     !++D1	12I77??4 #66))+F",,d)"11&	 -   $ 	Y;;tyy{IAQAQRVAW;X	Y 	Y 	Ys   ?CCc                    t        j                         5 }|j                  ||       | j                  |j	                         d|       cddd       S # 1 sw Y   yxY wr  r  r  s       r7   r  zSyncClient.upload_image  sT     ZZ\ 	EVJJvfJ-;;v0F6(2CD	E 	E 	Es   6AATr  r  c             #    K   d }d }	|r| j                  ||      }	n#| j                         }
|
j                  t        d}t	        ||	||      }t        ||      5 }t        |||       d d d        y # 1 sw Y   y xY wwr  )rb  rL  rU   rX  rz  r  r  r  s                r7   rw  zSyncClient.realtime  s      *. ,,.> - E >>#D(,(9(9TG!+um$Oc73 	r$NN 	 	 	s   ABA6-	B6A?;Br  c             #     K   d }d }|r| j                  ||      }n#| j                         }|j                  t        d}t	        ||||      }	t        |	|      5 }
|
 d d d        y # 1 sw Y   y xY wwr  )rb  rL  rU   rX  rv  r  r  s              r7   r  zSyncClient.ws_connect  s      *. ,,.> - E >>#D(,(9(9TG"'	
 c73 	rH	 	 	s   AA6A*!	A6*A3/A6r  r   )r:   r   )r:   rB   )r:   z%concurrent.futures.ThreadPoolExecutorr  r  )rr  r,   r  rF  r   r,   re  r   rl  r   rm  r  r]   r   rd  r  r:   r  r  )rr  r,   r  r,   r:   r  r  r  r  )
rr  r,   r  rF  r   r,   r   r  r:   zIterator[dict[str, Any]]r2   r  r  r  r  )rr  r,   r  r;   r   r,   rl  r   r]  r   r  r  r  r  r:   zIterator[RealtimeConnection])rr  r,   r  r;   r   r,   rl  r   r]  r   r:   Iterator['Connection']) r<   r=   r>   r
   rB  r?   rD  r   rL   rL  rS  r   r   r   r  r[  r  rb  rj  r   r  r  r?  r   r  r  r  r  r  r   rw  r  r@   r9   r7   r  r  e  s   Du5C5"OU"0 0
 	
 	
 1 1  
 !B	66 	6
 
6. /359"$(( (
 ( -( 3( (  ( 
(^ "&'+"$597
7
 7

 7
 7
  7
 %7
  7
 37
 
7
| 6:>B'+"$596:KK K
 K K K 4K <K %K  K 3K 4K 
KZX GL22,/2?C2	2  $## #
 # # 
"#4 MQ!-!-/2!-?I!-	!-FY&E 
 $( A8<8< 	
  "  6 6 
& 6 
 $( A 	
  "  
  r9   r  c                    t        | t              r| j                  d      } d| dt        j                  |       j                          S )zIEncode the given data blob to a data URL with the specified content type.r  zdata:z;base64,)r|  r,   r  base64	b64encoder  )rh   r~   s     r7   r  r    sB    ${{7#<.)9)9$)?)F)F)H(IJJr9   c                    t        j                  |       \  }}|d}t        | d      5 }t        |j	                         |      cddd       S # 1 sw Y   yxY w)zUEncode a file from the local filesystem to a data URL with the inferred content type.Nr   r   )r  r  r   r  r   )r   r  r2  r  s       r7   encode_filer    sR    ''-LIq.		dD	 .Tdiik9-. . .s   AAc                    t        j                         5 }| j                  ||       t        |j	                         d|       cddd       S # 1 sw Y   yxY w)zEEncode a pillow image object to a data URL with the specified format.r  r  N)r  r  r   r  r  )r  r  r  s      r7   encode_imager     sJ    	 <

6&
)foo'6&):;< < <s   0AA)rg   r  r:   rn   )rN  r,   r:   r,   )rP  rS  r:   r,   )rg  r   r:   r   )
rr  r,   r-   r   r   r,   rl  r   r:   r,   )
rr  r,   r-   r   rl  r   r   r,   r:   r,   )rh   r   r:   r,   )r  r   r:   r   )r  r   r:   r   )r  r   r  r  r:   zdict[str, Any] | None)r  r4  r  r  r:   r   r2   )r   r,   r]   dict[str, str] | Noner:   r  )r   r,   r]   r  r:   r  )
rf   r   r  r,   r   r,   r  r   r:   r  )
rf   r  r  r,   r   r,   r  r   r:   r  )rg   r  r:   r;   )rg   r  r  	list[int]r:   r;   )r%  r  r  r  r:   r;   )r  F)r  r   r  r  r  r  r  zLiteral['exponential', 'fixed']r  r;   r:   r  )rf   r   r  r,   r   r,   r  r  r  r   r:   r  )rf   r  r  r,   r   r,   r  r  r  r   r:   r  )r  r  r:   rn   )r  r  r:   rn   )rh   r  r~   r,   r:   r,   r  r  r  )
__future__r   r  r^   r   r   r  ru   pathlibr   r  r	  r  rP   loggingr   r   
contextlibr   r   r   r   dataclassesr	   r
   	functoolsr   typingr   r   r   r   r   r   r   r   r   urllib.parser   r  r`   	httpx_sser   r   fal_client.authr   r   r   r   r   fal_client._headersr   r   r   r    r!   r"   websockets.clientr#   websockets.sync.connectionr$   	getLoggerr<   r  PILr%   r,   rF  rh  r  rp  rS   r  rX  MIN_REQUEST_TIMEOUT_SECONDSr   r   r  r+   rB   rs   r  r   r   r{   r   r  r  r  r  r  r'  r)  r+  r/  r3  r8  rZ  rQ  rS  r  r  rf  rd  rj  rv  rz  r~  r}  r  r  r  r  r  r  r  r  r  r   r   r  r  r  r  r  r  r  r  r  r   r   r  r  r  r  rw   r  r  r  r   r@   r9   r7   <module>r     s   " 	   	          : ' ( %
 
 
 #   /   95			8	$
sCx.L>+013 |nA. &
 (
  00, 1 
 = = =" "J" "J ( '  m$ m$`x* x*v	Y 	 ! ! ! WNL W W&      V   0 0 0 & & & $B B B& w'X $
 
 
6 %( !   <	   $ 	
  	8  
  	D"L " /5  "?  >1    >   > /3	,  /3	,- "%,/;>'*14@C 
	% & $&  
& BD 4 5B!!! ! 2	!
 ! !. $&444 
4
 !4 4 4> $&444 
4
 !4 4 40 $E$* E$ E$P $I$+ I$ I$X $Z Z Zz $S S SlK.<r9   