
    ;3h$                        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	m
Z
mZmZ ddlmZ ddlmZmZ ddZddZ	 	 	 	 dd	Zdd
Zd dZd!dZd"dZd!dZd#dZd#dZd#dZd#dZd$dZd%dZd#dZ d#dZ!d Z"d Z#d&dZ$d'dZ%d(dZ&y))zCUtility function for gradio/external.py, designed for internal use.    )annotationsN)HfApi ImageClassificationOutputElementInferenceClient)
components)ErrorTooManyRequestsErrorc                    t        |      }t        d|         |j                  |       }|j                  }|j                  }||fS )N)tokenz,Fetching model from: https://huggingface.co/)r   print
model_infopipeline_tagtags)
model_namehf_tokenhf_apir   pipeliner   s         U/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/external_utils.pyget_model_infor      sJ    "F	8
EF"":.J&&H??DT>    c                f   t        j                  d|  d      }|j                  dk7  r t        j                  d|  t
               i }nt        j                  d|j                        }|i }n^t        t        j                  |j                  d |j                         d                }|j                  di       j                  di       }|st        d	|  d
      |j                         D ]A  }t        |      D ]1  \  }}t!        |t"              st%        j&                  |      s-d||<   3 C |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_examplesr8   !   s5   YY0<STUFS =j\JKXYYDfkk

 L""6;;/F1B21F#GHL (++Hb9==>NPRSL4ZL AL L
 	
 ##%  o 	 FAs#u%$**S/Q	   r   c                8    t         j                               }t         fd|D              }g }t        |      D ]Y  }g }|D ]?  } |   xs g }|t	        |      k\  r|j                  d       ,|j                  ||          A |j                  |       [ ||fS )Nc              3  B   K   | ]  }t        |   xs g         y wN)len).0headerr2   s     r   	<genexpr>zcols_to_rows.<locals>.<genexpr>C   s      GV\&)/R0Gs   r   )listkeysmaxranger<   append)r2   headersn_rowsr5   	row_indexrow_datar>   cols   `       r   cols_to_rowsrJ   ?   s     <$$&'GGwGGFD6] 	 	0Fv&,"CCH$&I/	0 	H D=r   c                    i }t        | d         D ]'  \  }}| d   D cg c]  }t        ||          c}||<   ) dd|iiS c c}w )NrE   r5   inputs)r,   str)incoming_datadata_column_wiser6   r>   rows        r   rows_to_colsrQ   Q   sa    }Y78 R	6;H;P#QCCAK#Q Rv/011 $Rs   Ac                V    | D ci c]  }|j                   |j                   c}S c c}w r;   )labelscorescorescs     r   postprocess_labelrX   ]   s#    &,-AGGQWW---s   &c                :    | D ci c]  }|d   |d    c}S c c}w )N	token_strrT    rU   s     r   postprocess_mask_tokensr\   a   s#    0671AkNAgJ&777   c                     | d   | d   | d   ifS NanswerrT   r[   )r`   s    r   postprocess_question_answeringra   e   s     (fX.w@@@r   c                :    | D ci c]  }|d   |d    c}S c c}w r_   r[   rU   s     r   %postprocess_visual_question_answeringrc   i   s#    -34AhK7#444r]   c                     d fd}|S )Nc                J    j                  | |j                  d      |      S )N,)multi_label)zero_shot_classificationsplit)inputlabelsrg   clients      r   zero_shot_classification_innerzHzero_shot_classification_wrapper.<locals>.zero_shot_classification_innern   s+    ..6<<$+ / 
 	
r   )rj   rM   rk   rM   rg   boolr[   )rl   rm   s   ` r    zero_shot_classification_wrapperro   m   s    

 *)r   c                     d fd}|S )Nc                F    j                  | |j                  d            S )N
)sentence_similarityri   )rj   	sentencesrl   s     r   sentence_similarity_innerz>sentence_similarity_wrapper.<locals>.sentence_similarity_innerw   s    ))%1FGGr   )rj   rM   rt   rM   r[   )rl   ru   s   ` r   sentence_similarity_wrapperrv   v   s    H %$r   c                     d fd}|S )Nc                ,    | j                  |       z   S r;   )text_generation)rj   rl   s    r   text_generation_innerz6text_generation_wrapper.<locals>.text_generation_inner~   s    v--e444r   rj   rM   r[   )rl   rz   s   ` r   text_generation_wrapperr|   }   s    5 ! r   c                      fd}|S )Nc              3    K   |sg }|j                  d| d       	 d}j                  |d      D ]0  }||j                  d   j                  j                  xs dz  }| 2 y # t
        $ r}t        |       Y d }~y d }~ww xY ww)Nuser)rolecontent T)messagesstreamr   )rD   chat_completionchoicesdeltar   	Exceptionhandle_hf_error)messagehistoryoutchunkerl   s        r   chat_fnz'conversational_wrapper.<locals>.chat_fn   s     G7;<	C///N u}}Q'--55;;	  	A	s/   BAA& %B&	B/A?:B?BBr[   )rl   r   s   ` r   conversational_wrapperr      s    
 Nr   c                <   t        j                  | j                        j                  d      }d}||v r|S | j                  j                  d      }|dk(  r	 | j                         d   }|d   }|d   }n	 d| d| }|S # t        $ r}t        d      |d }~ww xY w)	Nzutf-8z;base64,zcontent-typezapplication/jsonr   blobz7Cannot determine content type returned by external API.zdata:)	base64	b64encoder   decoderE   r   jsonKeyErrorr*   )rbase64_reprdata_prefixcontent_typer5   ke
new_base64s          r   encode_to_base64r      s    ""199-44W=KKk!yy}}^4--vvx{#N3"6l \N(;-@
   Ms   B 	B
BBc                    t        |      dk(  r| d fgS g }d}d}|D ]?  }|d   |d   |d   }}}|j                  | || d f       |j                  | || |f       |}A |j                  | |d  d f       |S )Nr   entity_groupstartend)r<   rD   )input_string
ner_groupsoutputr   prev_endgroupentityr   s           r   format_ner_listr      s    
:!t$%%F
CH ">2E'NE%Ls|HU3T:;|E#.78	 MM<%t,-Mr   c                     d fd}|S )Nc                >    j                  |       }t        | |      S r;   )token_classificationr   )rj   ner_listrl   s     r   token_classification_innerz@token_classification_wrapper.<locals>.token_classification_inner   s     ..u5uh//r   r{   r[   )rl   r   s   ` r   token_classification_wrapperr      s    0 &%r   c                     d fd}|S )Nc                    j                  |       }|D cg c]%  }|d   d   |d   d   |d   d   |d   d   f|d   f' }}| |fS c c}w )NboxxminyminxmaxymaxrS   )object_detection)rj   r   aformatted_annotationsrl   s       r   object_detection_innerz8object_detection_wrapper.<locals>.object_detection_inner   s    --e4 !!
  eHV$eHV$eHV$eHV$	 '
!
 !
 ,--!
s   *Ar{   r[   )rl   r   s   ` r   object_detection_wrapperr      s    .  "!r   c                2    |s| g g fS | |d   d   |d   d   fS )Nconversationgenerated_responsespast_user_inputsr[   )r%   states     r   chatbot_preprocessr      s:    R|n34n01 r   c                P    t        t        | d   d   | d   d   d            }|| fS )Nr   r   r   F)strict)r@   zip)responsechatbot_historys     r   chatbot_postprocessr      s@    ^$%78^$%:;	
O H$$r   c                      fd}|S )Nc                    dvrt        dd      j                  sJ dk(  rj                  | j                        S j                  | j                        S )N)tabular_classificationtabular_regressionzpipeline type z not supportedr   )model)	TypeErrorr   r   r   )r5   rl   r   s    r   tabular_innerz&tabular_wrapper.<locals>.tabular_inner   si    KKnXLGHH|||//00V\\0JJ,,T,FFr   r[   )rl   r   r   s   `` r   tabular_wrapperr      s    G r   c                    | d   D cg c]  }t        j                  |       c}| d<   | d   D cg c]  }t        j                  |       c}| d<   h d}|D ci c]  }|| |   
 } }| S c c}w c c}w c c}w )zGStreamlines the interface config dictionary to remove unnecessary keys.input_componentsrL   output_componentsoutputs>   titlerL   articler   descriptionflagging_options)r   get_component_instance)config	component
parametersks       r   streamline_spaces_interfacer     s       23 	)))4F8   34 	)))4F9J %//qal/F/M# 0s   A,A1A6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.)rM   r	   r   )r   s    r   r   r     sM    A"$!+	#a&9SVCGHaOCFm"r   r;   )r   rM   returnzdict[str, list[float]])r2   z#dict[str, list[float | str] | None]r   z#tuple[list[str], list[list[float]]])rN   dictr   z*dict[str, dict[str, dict[str, list[str]]]])rV   z&list[ImageClassificationOutputElement]r   r   )rV   zlist[dict[str, str | float]]r   r   )r`   r   r   ztuple[str, dict])rl   r   )r   zhttpx.Responser   rM   )r   rM   r   zlist[dict[str, str | int]])rl   r   r   rM   )r   r   r   r   )r   r   )'__doc__
__future__r   r   r/   r#   r    r   r'   huggingface_hubr   r   r   gradior   gradio.exceptionsr   r	   r   r8   rJ   rQ   rX   r\   ra   rc   ro   rv   r|   r   r   r   r   r   r   r   r   r   r   r[   r   r   <module>r      s    I "   	    T T  9<5($2.8A5*%! 4$&"(%*,#r   