
    PigP                    j   d 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	Z	ddl
Z
ddlmZ ddlmZmZmZ ddlmZ ddlmZmZ dJdZdKdZdLdZdMdZdNdZdOdZdPdZdOdZdQd!ZdQd"ZdQd#Z dQd$Z!dRd'Z"dSd+Z#dQd,Z$dQd-Z%dQd.Z&d/ Z'd0 Z(dTd2Z)dUd4Z*dVd7Z+	 dJdWd>Z,dXdAZ-dYdDZ.dZdGZ/d[dIZ0dS )\zCUtility function for gradio/external.py, designed for internal use.    )annotationsN)encode_url_or_file_to_base64)HfApi ImageClassificationOutputElementInferenceClient)
components)ErrorTooManyRequestsErrorc                    t          |          }t          d|             |                    |           }|j        }|j        }||fS )N)tokenz,Fetching model from: https://huggingface.co/)r   print
model_infopipeline_tagtags)
model_namer   hf_apir   pipeliner   s         i/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/gradio/external_utils.pyget_model_infor      sU    F	
E
E
EFFF"":..J&H?DT>    r   strreturndict[str, list[float]]c                   t          j        d|  d          }|j        dk    r t          j        d|  t
                     i }nt          j        d|j                  }|i }npt          t          j        |j        d |                                d                                      }|                    di                               di           }|st          d	|  d
          |                                D ]E}t          |          D ]3\  }}t!          |t"                    rt%          j        |          rd||<   4F|S )Nzhttps://huggingface.co/z/resolve/main/README.md   z%Cannot load examples from README for z,(?:^|[
])---[
]+([\S\s]*?)[
]+---([
]|$)widgetstructuredDataz&No example data found in README.md of z - Cannot build gradio demo. See the README.md here: https://huggingface.co/scikit-learn/tabular-playground/blob/main/README.md for a reference on how to provide example data to your model.NaN)httpxgetstatus_codewarningswarnUserWarningresearchtextnextyamlsafe_load_allspan
ValueErrorvalues	enumerate
isinstancefloatmathisnan)r   readmeexample_data
yaml_regexexample_yamldataivals           r   get_tabular_examplesr;   $   sx   YTTTTUUFS  JjJJKXXXYDfk
 

 LL"6;/F1B1B21F/F#GHH L (++Hb99==>NPRSSL 
LZ L L L
 
 	
 ##%%    oo 	  	 FAs#u%%  $*S//  Q	  r   r5   #dict[str, list[float | str] | None]#tuple[list[str], list[list[float]]]c                    t                                                     }t           fd|D                       }g }t          |          D ]l}g }|D ]P} |         pg }|t	          |          k    r|                    d           5|                    ||                    Q|                    |           m||fS )Nc              3  F   K   | ]}t          |         pg           V  d S N)len).0headerr5   s     r   	<genexpr>zcols_to_rows.<locals>.<genexpr>F   s5      GGV\&)/R00GGGGGGr   r   )listkeysmaxrangerA   append)r5   headersn_rowsr8   	row_indexrow_datarC   cols   `       r   cols_to_rowsrO   B   s     <$$&&''GGGGGwGGGGGFD6]]  	 	0 	0Fv&,"CCHH$$&&&&I////HD=r   incoming_datadict*dict[str, dict[str, dict[str, list[str]]]]c                x    i }t          | d                   D ]\  }fd| d         D             ||<   dd|iiS )NrJ   c                :    g | ]}t          |                   S  )r   )rB   rowr9   s     r   
<listcomp>z rows_to_cols.<locals>.<listcomp>W   s#    #Q#Q#QCCAKK#Q#Q#Qr   r8   inputs)r/   )rP   data_column_wiserC   r9   s      @r   rows_to_colsrZ   T   sc    }Y788 R R	6#Q#Q#Q#Q=;P#Q#Q#Q  v/011r   scores&list[ImageClassificationOutputElement]c                    d | D             S )Nc                (    i | ]}|j         |j        S rU   )labelscorerB   cs     r   
<dictcomp>z%postprocess_label.<locals>.<dictcomp>a   s    ---AGQW---r   rU   r[   s    r   postprocess_labelre   `   s    --f----r   list[dict[str, str | float]]c                    d | D             S )Nc                ,    i | ]}|d          |d         S )	token_strr`   rU   ra   s     r   rc   z+postprocess_mask_tokens.<locals>.<dictcomp>e   s"    7771AkNAgJ777r   rU   rd   s    r   postprocess_mask_tokensrj   d   s    777777r   answertuple[str, dict]c                2    | d         | d         | d         ifS )Nrk   r`   rU   )rk   s    r   postprocess_question_answeringrn   h   s     (fX.w@@@r   c                    d | D             S )Nc                ,    i | ]}|d          |d         S )rk   r`   rU   ra   s     r   rc   z9postprocess_visual_question_answering.<locals>.<dictcomp>m   s"    444AhK7444r   rU   rd   s    r   %postprocess_visual_question_answeringrq   l   s    44V4444r   clientr   c                     d fd}|S )Ninputr   labelsmulti_labelboolc                Z                         | |                    d          |          S )N,)rv   )zero_shot_classificationsplit)rt   ru   rv   rr   s      r   zero_shot_classification_innerzHzero_shot_classification_wrapper.<locals>.zero_shot_classification_innerq   s3    ..6<<$$+ / 
 
 	
r   )rt   r   ru   r   rv   rw   rU   )rr   r|   s   ` r    zero_shot_classification_wrapperr}   p   s)    
 
 
 
 
 

 *)r   c                     d fd}|S )Nrt   r   	sentencesc                V                         | |                    d                    S )N
)sentence_similarityr{   )rt   r   rr   s     r   sentence_similarity_innerz>sentence_similarity_wrapper.<locals>.sentence_similarity_innerz   s%    ))%1F1FGGGr   )rt   r   r   r   rU   )rr   r   s   ` r   sentence_similarity_wrapperr   y   s/    H H H H H H %$r   c                     d fd}|S )Nrt   r   c                4    |                      |           z   S r@   )text_generation)rt   rr   s    r   text_generation_innerz6text_generation_wrapper.<locals>.text_generation_inner   s    v--e4444r   rt   r   rU   )rr   r   s   ` r   text_generation_wrapperr      s)    5 5 5 5 5 5 ! r   c                      fd}|S )Nc              3    K   |sg }|                     d| d           	 d}                    |d          D ]+}||j        r|j        d         j        j        pdndz  }|V  ,d S # t
          $ r}t          |           Y d }~d S d }~ww xY w)Nuserrolecontent Tmessagesstreamr   )rI   chat_completionchoicesdeltar   	Exceptionhandle_hf_error)messagehistoryoutchunkerr   s        r   chat_fnz'conversational_wrapper.<locals>.chat_fn   s       	G7;;<<<	C///NN  u}Tu}Q'-5;RTT				   	 	 	A	s   AA( (
B2BBrU   rr   r   s   ` r   conversational_wrapperr      s#    
 
 
 
 
 Nr   rhttpx.Responsec                \   t          j        | j                                      d          }d}||v r|S | j                            d          }|dk    rN	 |                                 d         }|d         }|d         }n## t          $ r}t          d          |d }~ww xY w	 d| d| }|S )	Nzutf-8z;base64,zcontent-typeapplication/jsonr   blobz7Cannot determine content type returned by external API.zdata:)	base64	b64encoder   decoderJ   r!   jsonKeyErrorr-   )r   base64_reprdata_prefixcontent_typer8   ke
new_base64s          r   encode_to_base64r      s    "19--44W==KKk!!y}}^44---vvxx{#N3"6l    M  @\@@;@@
s   *B 
B BB input_string
ner_groupslist[dict[str, str | int]]c                :   t          |          dk    r| d fgS g }d}d}|D ]Z}|d         |d         |d         }}}|                    | ||         d f           |                    | ||         |f           |}[|                    | |d          d f           |S )Nr   entity_groupstartend)rA   rI   )r   r   outputr   prev_endgroupentityr   s           r   format_ner_listr      s    
:!t$%%F
CH  ">2E'NE%Ls|HUN3T:;;;|E#I.7888
MM<%t,---Mr   c                     d fd}|S )Nrt   r   c                N                         |           }t          | |          S r@   )token_classificationr   )rt   ner_listrr   s     r   token_classification_innerz@token_classification_wrapper.<locals>.token_classification_inner   s&    ..u55uh///r   r   rU   )rr   r   s   ` r   token_classification_wrapperr      s)    0 0 0 0 0 0 &%r   c                     d fd}|S )Nrt   r   c                N                         |           }d |D             }| |fS )Nc                    g | ]@}|d          d         |d          d         |d          d         |d          d         f|d         fAS )boxxminyminxmaxymaxr_   rU   )rB   as     r   rW   zLobject_detection_wrapper.<locals>.object_detection_inner.<locals>.<listcomp>   sj     !
 !
 !
  eHV$eHV$eHV$eHV$	 '
!
 !
 !
r   )object_detection)rt   r   formatted_annotationsrr   s      r   object_detection_innerz8object_detection_wrapper.<locals>.object_detection_inner   sE    --e44!
 !
 !!
 !
 !
 ,--r   r   rU   )rr   r   s   ` r   object_detection_wrapperr      s)    . . . . . .  "!r   c                      fd}|S )Nc                R   dddt          |           idd|dgdg}	                     |d	          }|j        d
         j        j        S # t
          $ rN}	                     |           }d| d| dcY d }~S # t
          $ r t          |           Y nw xY wY d }~d S d }~ww xY w)Nr   	image_urlurl)typer   r(   )r   r(   r   Fr   r   zImage description: z

User question: zZ

Note: This model doesn't support question-answering about images, only image captioning.)r   r   r   r   r   r   image_to_textr   )imager(   r   responser   resultrr   s         r   r   z+image_text_to_text_wrapper.<locals>.chat_fn   s@     !,&+-I%-P-P%Q  $T22	 	

	#--x-NNH#A&.66 	# 	# 	##--e44 kV  k  k  k  k  k  k  k  k  k  k  k # # #"""""#""""""	#s5   -A 
B&A<6B&<BB!BB!!B&rU   r   s   ` r   image_text_to_text_wrapperr      s#    # # # # #4 Nr   c                J    |s| g g fS | |d         d         |d         d         fS )Nconversationgenerated_responsespast_user_inputsrU   )r(   states     r   chatbot_preprocessr      s?     R|n34n01 r   c                x    t          t          | d         d         | d         d         d                    }|| fS )Nr   r   r   F)strict)rE   zip)r   chatbot_historys     r   chatbot_postprocessr     sO    ^$%78^$%:;	
 	
 	
 O H$$r   r   c                      fd}|S )Nc                    dvrt          dd          j        sJ dk    r                    | j                  S                     | j                  S )N)tabular_classificationtabular_regressionzpipeline type z not supportedr   )model)	TypeErrorr   r   r   )r8   rr   r   s    r   tabular_innerz&tabular_wrapper.<locals>.tabular_inner  sx    KKKGXGGGHHH||///00V\0JJJ,,T,FFFr   rU   )rr   r   r   s   `` r   tabular_wrapperr     s0    G G G G G G r   configc                     d  d         D              d<   d  d         D              d<   h d} fd|D               S )	zGStreamlines the interface config dictionary to remove unnecessary keys.c                6    g | ]}t          j        |          S rU   r   get_component_instancerB   	components     r   rW   z/streamline_spaces_interface.<locals>.<listcomp>)  s3        	))44  r   input_componentsrX   c                6    g | ]}t          j        |          S rU   r   r   s     r   rW   z/streamline_spaces_interface.<locals>.<listcomp>-  s3        	))44  r   output_componentsoutputs>   titlerX   articler   descriptionflagging_optionsc                "    i | ]}||         S rU   rU   )rB   kr   s     r   rc   z/streamline_spaces_interface.<locals>.<dictcomp>9  s    ///qa///r   rU   )r   
parameterss   ` r   streamline_spaces_interfacer   '  s      23  F8  34  F9  J 0///J///FMr   r   r   c                    dt          |           v rt                      | dt          |           v sdt          |           v rt          d          | t          t          |                     | )N429401zYou must provide an api_keyz1Unauthorized, please make sure you are signed in.)r   r
   r	   )r   s    r   r   r   =  sd    A"$$!+	#a&&9SVVCCGHHaOCFFmm"r   endpoint_pathendpoint_methodendpoint_operationbase_url
auth_token
str | Nonec                                         di           } fd}                     dd          }                     dd          }g }	g }
                     dg           D ]}|                     dd          }|                     dd          }|                     di           }|                     d	g           }|r|d
d                    |           dz  }|
                    |           |	                    d| d|            |rC|                     dd          }|	                    d|            |
                    d           g }|s|r|                    |p|           |	r*|                    d           |                    |	           d                    |          |_        |
rg }|
D ]:}|                    t          j        |t
          j        j                             ;|                    t          j        dt
          j        j                             t          j	        |          }||_
        |S )NrequestBodyc                                         d            }ddi}rd |d<   i }i }                    dg           }                    di           }d}|D ]}|t          |           k     r||                    d	          d
k    r| |         ||d         <   nL|                    d	          dk    r3|                    d|d          dt	          | |                             }|dz  }d}	|r6|t          |           k     r#|                    di           }
|
D ]
}|dv rd}	 n|rD|t          |           k     r1|	r| |         }|rd|d<   |}nd}nt          j        | |                   }	                                 dk    rt          j        |||          }n                                dk    r"t          j	        |||	r|nd |	s|nd |          }n                                dk    r"t          j
        |||	r|nd |	s|nd |          }n|                                dk    r"t          j        |||	r|nd |	s|nd |          }nB                                dk    rt          j        |||          }nt          d           |j        dv r|                                S d|j        |j        d S # t           $ r}d!t	          |           cY d }~S d }~ww xY w)"N/zContent-Typer   zBearer Authorizationr   r  r   inquerynamepath{}   Fr   application/octet-streamzmultipart/form-dataTr  r   r!   )paramsrJ   post)r  r   r   rJ   putpatchdeletezUnsupported HTTP method: )r            error)
__status__r"   r   zError: )rstripr!   rA   replacer   r   loadslowerr    r  r  r  r  r-   r"   r(   r   )argsr   rJ   r  	body_dataoperation_paramsrequest_bodyparam_indexparamis_file_uploadr   r   	file_datar   r   r  r  r  r  r  s                  r   endpoint_fnz'create_endpoint_fn.<locals>.endpoint_fnP  s   %%6}66!#56 	>'='='=GO$	-11,CC)--mR@@% 	! 	!ESYY&&99T??g--,0,=F5=))YYt__..++&<5=&<&<&<c${BS>T>TUUCq  	K#d))33"&&y"55G '  #VVV%)NE W  		:K#d))33 : -	 $.HGN+ )II #II JtK'899	)	&$$&&%// 9SIII &&((F22 :!)7AIIT*8Bd#   !&&((E11 9!)7AIIT*8Bd#   !&&((G33 ;!)7AIIT*8Bd#   !&&((H44 <FGLLL !N_!N!NOOO#';;;}}& #*#+#7'}  
  	& 	& 	&%SVV%%%%%%%%	&s%   0D<J= -J= =
K#KK#K#summaryr   r   r   r  schemaenumz (Choices: z, )z    z: zURL of filez    request_body: r)  zParameters:r   )r  kindr&  )r   )r!   joinrI   extend__doc__inspect	ParameterPOSITIONAL_OR_KEYWORDVAR_POSITIONAL	Signature__signature__)r  r  r  r  r  r)  r.  r/  r   
param_docsparam_namesr+  
param_name
param_descparam_schema
param_enum	body_descdocstring_parts
sig_paramsr  new_sigs   `````                r   create_endpoint_fnrG  F  s    &))-<<LQ& Q& Q& Q& Q& Q& Q& Q& Q&f !$$Y33G$((;;KJK#''b99 = =YYvr**
YY}b11
yy2..!%%fb11
 	A@		*(=(=@@@@J:&&&;;;z;;<<<< + $$]MBB	:y::;;;>***O 7g 7{5g666 +}---z***))O44K ,
 	 	D!G$5$K     
 	60A0PQQQ	
 	
 	
 #z:::$+!r   
param_infocomponents.Componentc                2   dd l }|                     d          }|                     d          }|                     di           }|                    d          }|                    d          }|                    d          }||                    |||d|	          }nv|d
v r|                    |||          }nY|dk    r|                    |||          }n:|dk    r|                    | dd|          }n|                    |||          }|S )Nr   r  r   r0  r   r1  defaultF)r   r_   valueallow_custom_valueinfonumberintegerr_   rL  rN  booleanarrayz (JSON array)z[])gradior!   DropdownNumberCheckboxTextbox)	rH  grr?  param_descriptionrA  
param_typeenum_valuesdefault_valuer   s	            r   component_from_parameter_schemar_    sq   ''J"}55>>(B//L!!&))J""6**K $$Y//MKK$"   
 
		 
,	,	,II"  
 
		
 
y	 	 KK"   
 
		
 
w		JJ..."  
 
		 JJ"  
 
	 r   r0  specc                   d| v r| d         }|                     d          rY|                    d          d         }|                    di                               di                               |i           S |                     d          r<|                    d          dd	         }|}|D ]}|                    |i           }|S | S )
z*Resolve schema references in OpenAPI spec.z$refz#/components/schemas/r  r   r   schemasz#/r  N)
startswithr{   r!   )r0  r`  ref_pathschema_name
path_partscurrentparts          r   resolve_schema_refri    s    &>677 	"..--b1K88L"--11)R@@DD[RTUUU  && 	!,,QRR0JG" 0 0!++dB//NMr   r)  components.Component | Nonec                   ddl }| sdS |                     di           }|                     dd          }|                                D ]w\  }}|dv rnt          |                    di           |          }|                    d          d	k    r1|                    d
          dk    r|                    d          c S x|                    di           }|s3|                                D ]\  }}|                    d          r|} n|sdS t          |                    di           |          }|                    di           }	|	s|                    d          dk    r|                    di           }
i }	|
                                D ]\  }}t          ||          }|                    d          }|d	k    r|                    dd          |	|<   J|dv r|                    dd          |	|<   h|dk    r|                    dd          |	|<   |dk    r|                    dg           |	|<   |dk    r|                    di           |	|<   |                    dt          j        |	d          |          }|S )z>Create a Gradio component from an OpenAPI request body schema.r   Nr   r   zRequest Bodyr  r0  r   stringformatbinaryFile)r_   r   zapplication/exampleobject
propertiesr   rO  rS  FrT     )indentrR  )	rU  r!   itemsri  ro  rc  rY  r   dumps)r)  r`  rZ  r   r   r   content_schemar0  json_contentr^  rr  	prop_nameprop_schema	prop_typer   s                  r   "component_from_request_body_schemar|    s     ty"--G""=.AAK(/ - -$nNNN'(:(:8R(H(H$OOFzz&!!X--&**X2F2F(2R2RwwVw,,,,,;;1266L ,3MMOO 	 	(L.&&~66 -  t 0 02 > >EEFJJy"--M JVZZ//8;;ZZb11
&0&6&6&8&8 	J 	J"I{,[$??K#//IH$$+6??9b+I+Ii((333+6??9a+H+Hi((i''+6??9e+L+Li((g%%+6??9b+I+Ii((h&&+6??9b+I+Ii(

jq111   I r   methodc                    dddddd}|                     |                                 d          }d| d	| d
|                                  dS )Nz#61affez#49cc90z#fca130z#f93e3ez#50e3c2)GETPOSTPUTDELETEPATCHz#999z_<span style='display:inline-block;min-width:48px;padding:2px 10px;border-radius:4px;background:zh;color:white;font-weight:bold;font-family:monospace;margin-right:8px;text-align:center;border:2px solid z);box-shadow:0 1px 2px rgba(0,0,0,0.08);'>z</span>)r!   upper)r}  	color_mapcolors      r   
method_boxr  L  s~     I MM&,,..&11E	$	$ 	$ @E	$ 	$
 LLNN	$ 	$ 	$r   r@   )r   r   r   r   )r5   r<   r   r=   )rP   rQ   r   rR   )r[   r\   r   rQ   )r[   rf   r   rQ   )rk   rQ   r   rl   )rr   r   )r   r   r   r   )r   r   r   r   )rr   r   r   r   )r   rQ   r   rQ   )r   r   )
r  r   r  r   r  rQ   r  r   r  r	  )rH  rQ   r   rI  )r0  rQ   r`  rQ   r   rQ   )r)  rQ   r`  rQ   r   rj  )r}  r   r   r   )1r6  
__future__r   r   r7  r   r2   r&   r#   r    r*   gradio_client.utilsr   huggingface_hubr   r   r   rU  r   gradio.exceptionsr	   r
   r   r;   rO   rZ   re   rj   rn   rq   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   rG  r_  ri  r|  r  rU   r   r   <module>r     s   I I " " " " " "     				    < < < < < < T T T T T T T T T T       9 9 9 9 9 9 9 9      <   $2 2 2 2. . . .8 8 8 8A A A A5 5 5 5* * * *% % % %! ! ! !       4   $& & & &" " " "(   <  % % %   *   ,# # # # "K K K K K\, , , ,^    6 6 6 6r     r   