
    8P[i                       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m	Z	m
Z
 ddlmZ ddlmZmZ ddlZddlZddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddlZddlmZm Z m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z*m+Z+ er$ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7  e       	 	 	 	 d'	 	 	 	 	 	 	 	 	 	 	 d(d       Z8	 	 	 d)	 	 	 	 	 	 	 	 	 	 	 d*dZ9	 d+	 	 	 	 	 	 	 	 	 d,dZ:	 d+	 	 	 	 	 	 	 	 	 d-dZ;d Z<d.dZ=	 	 	 	 	 	 	 	 	 	 	 	 d/dZ>dZ?dZ@	 	 	 	 	 	 d0d ZA e       	 d+d!dd"d#	 	 	 	 	 	 	 	 	 	 	 	 	 d1d$       ZB e       ddddd%	 	 	 	 	 	 	 	 	 	 	 	 	 d2d&       ZCy)3zThis module should not be used directly as its API is subject to change. Instead,
use the `gr.Blocks.load()` or `gr.load()` functions.    )annotationsN)Callable	Generator)Path)TYPE_CHECKINGLiteral)Client)Endpoint)document)encode_url_or_file_to_base64is_http_url_like)version)
componentsexternal_utilsutils)MultimodalValue)Context)GradioVersionIncompatibleErrorTooManyRequestsError)save_base64_to_cache	to_binary)
PROVIDER_T)BlocksChatInterface)NormalizedMessageDict)LoginButton)	Interfacec                    C j                  d      }t        |      dk  rt        d      |d   dj                  |dd        J t	        t
              sdvrt        d      |Bdv r>t        j                  j                  d	      t        j                  j                  d	      }t	        t
              r
  |fi S |st        d |d
S t	        |t        j                        rjt        j                  d      5 }|j                  s|j                          t        j                  |j                  g      d fd       }ddd       |S t        j                  d      5 }t        j                   d      5 }	t        j"                  ddd      }
t        j$                  ddd      }t        j&                         }ddd       t        j(                  
j*                  g	      d        }t        j(                  |
j*                  j,                  g|
|g|g      d        }t        j(                  |j                  |g|
|g      d        }t        j                  |
g|
j*                  g       fd       }ddd       |S # 1 sw Y   S xY w# 1 sw Y   xY w# 1 sw Y   S xY w)a	  
    Constructs a Gradio app automatically from a Hugging Face model/Space repo name or a 3rd-party API provider. Note that if a Space repo is loaded, certain high-level attributes of the Blocks (e.g. custom `css`, `js`, and `head` attributes) will not be loaded.
    Parameters:
        name: the name of the model (e.g. "google/vit-base-patch16-224") or Space (e.g. "flax-community/spanish-gpt2"). This is the first parameter passed into the `src` function. Can also be formatted as {src}/{repo name} (e.g. "models/google/vit-base-patch16-224") if `src` is not provided.
        src: function that accepts a string model `name` and a string or None `token` and returns a Gradio app. Alternatively, this parameter takes one of two strings for convenience: "models" (for loading a Hugging Face model through the Inference API) or "spaces" (for loading a Hugging Face Space). If None, uses the prefix of the `name` parameter to determine `src`.
        token: optional token that is passed as the second parameter to the `src` function. If not explicitly provided, will use the HF_TOKEN environment variable or fallback to the locally-saved HF token when loading models but not Spaces (when loading Spaces, only provide a token if you are loading a trusted private Space as the token can be read by the Space you are loading). Find your HF tokens here: https://huggingface.co/settings/tokens.
        accept_token: if True, a Textbox component is first rendered to allow the user to provide a token, which will be used instead of the `token` parameter when calling the loaded model or Space. Can also provide an instance of a gr.LoginButton in the same Blocks scope, which allows the user to login with a Hugging Face account whose token will be used instead of the `token` parameter when calling the loaded model or Space.
        kwargs: additional keyword parameters to pass into the `src` function. If `src` is "models" or "Spaces", these parameters are passed into the `gr.Interface` or `gr.ChatInterface` constructor.
        provider: the name of the third-party (non-Hugging Face) providers to use for model inference (e.g. "replicate", "sambanova", "fal-ai", etc). Should be one of the providers supported by `huggingface_hub.InferenceClient`. This parameter is only used when `src` is "models"
    Returns:
        a Gradio Blocks app for the given model
    Example:
        import gradio as gr
        demo = gr.load("gradio/question-answering", src="spaces")
        demo.launch()
    N/   zYEither `src` parameter must be provided, or `name` must be formatted as {src}/{repo name}r   )modelsspaceshuggingfacezThe `src` parameter must be one of 'huggingface', 'models', 'spaces', or a function that accepts a model name (and optionally, a token), and returns a Gradio app.)r"   r$   HF_TOKENnamesrctokenproviderT)fill_height)triggersc                D    | d n| j                   }t        d|dS Nr&    )r)   load_blocks_from_huggingface)oauth_tokentoken_valuekwargsr'   r*   r(   s     ]/var/www/html/chatbot/Makanify-Chatbot-2/venv/lib/python3.12/site-packages/gradio/external.pycreate_blockszload.<locals>.create_blocksk   s=    &1&9d{?P?P3 %%	
      z Enter your token and press enterpasswordF)type
show_label	containerRemember me on this device)labelvaluer:   )outputsc                 0    t        j                  dd      S )NzToken settingsF)open)gr	Accordionr/   r6   r4   hide_accordionzload.<locals>.hide_accordion   s    ||$45AAr6   )inputsr>   c                l    |r| r| t        j                  dd      fS dt        j                  d      fS )Nz#Remember me on this device (saved!)T)r<   r=    r;   r<   )rA   Checkbox)r2   remember_token_values     r4   
save_tokenzload.<locals>.save_token   s=     (K&C4)   r{{1MNNNr6   c                    | r| dfS y)NT)rF   Fr/   )r2   s    r4   
load_tokenzload.<locals>.load_token   s    &,,$r6   )rD   r,   c                $    t        d| dS r.   )r0   )r2   r3   r'   r*   r(   s    r4   createzload.<locals>.create   s+    3 %%	
  r6   r/   )r1   zgr.OAuthToken | None)splitlen
ValueErrorjoin
isinstancer   osenvirongetr0   rA   r   r   is_renderedrenderloadrB   TextboxrH   BrowserStateonsubmitchange)r'   r(   r)   accept_tokenr*   r3   partsdemor5   	accordiontextboxremember_tokenbrowser_staterC   rJ   rL   rN   s   ``  ``           r4   rY   rY   +   s   6 {

3u:?k  Ahxxab	"??c8$4W)W q
 	
 	,,JJNN:&2

z*#x 4)&))+ 
	

 
 	
 
L"..	1YY4( 	D++##%YY, -	 YY4( ,	D@A 	2Y**#$#
 "$6eu" !# 1	2 UUGNN#Y7B 8B UU!6!670&7
O
O UU499m_w>WX% Y% YYwi7>>2BC DK,	\ 	 	2 	2,	\ s3   A
J7J6AJ*CJ6J'*J3	/J66K c                    |Ct         j                  (t         j                  |k7  rt        j                  d       |t         _        |dk(  rt	        | f|||d|}|S t        | f|||d|}|S )zNCreates and returns a Blocks instance from a Hugging Face model or Space repo.zYou are loading a model/Space with a different access token than the one you used to load a previous model/Space. This is not recommended, as it may cause unexpected behavior.r#   )r)   aliasr*   )r   r)   warningswarnfrom_spaces
from_model)r'   r(   r)   rg   r*   r3   blockss          r4   r0   r0      s     ==$%)?MM F 
h
UX
AG

 M DXUXXQWXMr6   c           
        ddit        j                  | ||      }t        j                  | |      \  }}d|  t        j
                  j                  d      xs) t        t        t        j                               dz        fd}d d d }	|dk(  rNt        j                  d	d
      }
t        j                  d      }t        j                  dg}	|j                  n|dk(  r4t        j                  d	d
      }
t        j                  d      }dg}	|n|dk(  rAt        j                  d	d
      }
t        j                   d      }dg}	|j"                  d n|dk(  rJt        j                   d
      }
t        j$                  d      }|j&                  t(        j*                  nM|dk(  rMt        j                   d
      }
t        j                  d      }dg}	t        j,                  |j.                  n|dk(  rNt        j0                  d	d      }
t        j                  d      }t        j                  dg}	|j2                  n|dk(  r|t        j                   d      t        j                   dd      g}
t        j                   d      t        j                  d       g}d!d"gg}	t        j4                  |j6                  n'|d#k(  rAt        j                   d
      }
t        j                   d$      }d%gg}	d& |j8                  n|d'k(  rMt        j                   d
      }
t        j                  d      }d(g}	t        j                  |j:                  n|d)k(  r|rNd*|v rJd+d,lm} d+d-l m!} t        jD                  |      g d.}	d/|	i}tG        |fi |} |d0d12      } |fd3|i|S t        j                   d4      }
|
}d5g}	t        jH                  |      n|d6k(  r=t        j                   d
      }
t        j                   d7      }d8g}	|jJ                  n|d9k(  r@t        j                   d
      }
t        j                   d:      }d; d<g}	|jL                  n|d=k(  rt        j                   d
      t        j                   d>      t        jN                  d?      g}
t        j                  d      }t        j                  g d@g}	t        jP                  |      n|dAk(  rat        j                   dBdCD      t        j                   ddEdFG      g}
t        jR                  dH      }dIdJgg}	t        jT                  |      n|dKk(  r=t        j                   d
      }
t        j                  dL      }d<g}	|jV                  nQ|dMk(  r=t        j                   d
      }
t        j0                  d      }dNg}	|jX                  n|dOk(  rFt        j                   d
      }
t        jZ                  d      }dPg}	t        j\                  |      n|dQk(  rat        j0                  d	dR      t        j                   d      g}
t        j                  t        j                  dS      }|j^                  n^|dTk(  rft        j0                  d	d      t        j                   d      g}
t        j                  dS      }t        j`                  ddUgg}	|jb                  n|dVk(  r>t        j0                  d	d      }
t        j                   d7      }dg}	|jd                  n|dWv rt        jf                  |       }	t        jh                  |	      \  }}	|	r|	ggnd }	t        j$                  dXdY|tk        |      tk        |      tk        |      fdZ[      }
t        j$                  d\d]d^g_      }t        jl                  n|d`k(  rCt        j0                  d	d      }
t        jn                  da      }t        jp                  |      n|dbk(  rUt        j0                  d	d      t        j                   d
      g}
t        j0                  d      }ddcgg}	|jr                  nr|ddk(  r_t        j0                  d	d      t        j                   dedfD      g}
t        j                   d7      }ddUgg}	t        jt                  |      ntw        dg|       fdh}|xs | |_<        ||
|| |	dZdi}tG        |fi |}|j{                  djd       |j{                  dkd       }
|j{                  dld       }t}        j~                  |
|fi |dmdni}|S )oNzX-Wait-For-Modeltrue)modelheadersr)   r*   z,https://api-inference.huggingface.co/models/GRADIO_TEMP_DIRgradioc                    t        d| i      } t        j                  d|       }t        t	        j
                  |            S )NpathPOST)rp   content)	cache_dir)r   httpxrequestr   r   encode_to_base64)dataresponseGRADIO_CACHEapi_urlrp   s     r4   custom_post_binaryz&from_model.<locals>.custom_post_binary   sB    &$(=='4P#++H5
 	
r6   zaudio-classificationfilepathInput)r8   r<   ClassrG   zBhttps://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wavzaudio-to-audioOutputzautomatic-speech-recognitionc                    | j                   S N)textxs    r4   <lambda>zfrom_model.<locals>.<lambda>   s
     r6   zfeature-extractionz	fill-maskClassificationzIHugging Face is the AI community, working together, to [MASK] the future.zimage-classificationzInput ImagezAhttps://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpgzquestion-answeringQuestion   r   )linesr<   AnswerScorez3What entity was responsible for the Apollo program?zThe Apollo program, also known as Project Apollo, was the third United States human spaceflight program carried out by the National Aeronautics and Space Administration (NASA), which accomplished landing the first humans on the Moon from 1969 to 1972.summarizationSummarya  The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest man-made structure in the world, a title it held for 41 years until the Chrysler Building in New York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second tallest free-standing structure in France after the Millau Viaduct.c                    | j                   S r   )summary_textr   s    r4   r   zfrom_model.<locals>.<lambda>-  s
     r6   ztext-classificationI feel greatztext-generationconversationalr   r   Chatbot)z What is the capital of Pakistan?zTell me a joke about calculus.z Explain gravity to a 5-year-old.z)What were the main causes of World War I?examplesr!   Tscale
allow_tagschatbotTextzOnce upon a timeztext2text-generationzGenerated Textz)Translate English to Arabic: How are you?translationTranslationc                    | j                   S r   )translation_textr   s    r4   r   zfrom_model.<locals>.<lambda>X  s     2 2 r6   zHello, how are you?zzero-shot-classificationz&Possible class names (comma-separated)zAllow multiple true classes)r   z
happy, sadFzsentence-similarityzSource SentencezEnter an original sentence)r<   placeholderz>Sentences to compare to -- separate each sentence by a newlinezSentences to compare to)r   r   r<   zSimilarity scoreszThat is a happy personzThat person is very happyztext-to-speechAudioztext-to-imagezA beautiful sunsetztoken-classificationzXHugging Face is a company based in Paris and New York City that acquired Gradio in 2021.zdocument-question-answeringzInput DocumentLabelzvisual-question-answeringzWhat animal is in the image?zimage-to-text)ztabular-classificationztabular-regressionz
Input RowspandasF)r<   r8   rp   column_countcolumn_limitsrX   Predictionsarray
prediction)r<   r8   rp   zobject-detectionAnnotationszimage-to-imagez"Photo of a cheetah with green eyeszimage-text-to-textz
Input TextzAsk a question about the imagezUnsupported pipeline type: c                      |  } 	  |  }  |       } | S # t         $ r}t        j                  |       Y d }~/d }~ww xY wr   )	Exceptionr   handle_hf_error)r{   efnpostprocess
preprocesss     r4   %query_huggingface_inference_endpointsz9from_model.<locals>.query_huggingface_inference_endpoints  s[    !t$D	.t9D "t$D  	.**1--	.s    	A>A)r   rD   r>   titler   cache_examplesr   rD   r>   api_namepredict)@huggingface_hubInferenceClientr   get_model_inforT   rU   rV   strr   tempfile
gettempdirr   r   r   postprocess_labelaudio_classificationrZ   automatic_speech_recognition	Dataframefeature_extractionr   resolve_singletonpostprocess_mask_tokens	fill_maskImageimage_classificationpostprocess_question_answeringquestion_answeringr   text_classificationrr   r   gradio.componentsr   conversational_wrapperdicttext_generation_wrappertext_generationr   rH    zero_shot_classification_wrapperJSONsentence_similarity_wrappertext_to_speechtext_to_imageHighlightedTexttoken_classification_wrapperdocument_question_answering%postprocess_visual_question_answeringvisual_question_answeringimage_to_textget_tabular_examplescols_to_rowsrP   tabular_wrapperAnnotatedImageobject_detection_wrapperimage_to_imageimage_text_to_text_wrapperrQ   __name__poprA   r   )
model_namer)   rg   r*   r3   clientptagsr   r   rD   r>   r   r   chat_interface_kwargsr   	col_namesr   interface_info	interfacer}   r~   r   rp   r   r   s                       @@@@@@r4   rk   rk      sV	    "6*G,,'F ++J>GAt =ZLIG::>>"34 X  "#h.9L
 JKH 	""!!zA""1$66P
 ((	
	!!zA""2P
  	
,	,!!zA$$84P
 00&	
"	"##'2&&X6&&--	
k	##'2"")9:W
 %<<	
$	$!!zG"")9:$66WX((	
"	"Z0Qi8

 X.7+
 FK
 %CC&&	
o	##'2$$95 z

 /!!	
#	###'2"")9:"#$66''	
	$,,166v>BH H%! /:6:FA$7G ?W???##&1&'33F;	
$	$##'2$$+;<?@##	
m	##'2$$=92)*	
(	(W-%MN&CD

 "")9:$669:<<VD	
#	#'8 \/

 //(;<-/JKL77?	
	##'2""1)*""	
o	##'2""2()!!	
$	$##'2,,8<f
 88@	
+	+*4DEZ0
 %66""1//	
)	)*MBZ0
 ""1$JJ T.
 --	
o	!!zG$$+;<WX!!	
>	>!66zB,99(C	8#+XJ<%%Yy>3y>:
 &&g~
 ++	
 	 !!zG++-@44V<	
	*MBW-
 ""2 T4
 ""	
"	"*MB"0P
 $$+;< T.
 66v>6qc:;;
 6;5Hj)2 4N .+F+F	D$	BZZ$'FjjD)GROFOYOIr6   c                   |t        j                  d       d|  }t        d|        i }|dvrd| |d<   t        j                  d|  d|	      j                         j	                  d
      }|t        d|  d      t        j                  |dz   |	      }|j                  dk(  r]t        j                  ||	      }	t        j                  d|	j                        }
	 t        j                  |
j                  d            }n/|j                  dk(  r|j                         }nt        d|  d      d|v rt        | ||||fi |S |rt        j                  d       t        | |      S # t        $ r}t        d|        |d }~ww xY w)NzRThe `provider` parameter is not supported when loading Spaces. It will be ignored.zhttps://huggingface.co/spaces/zFetching Space from: FNBearer Authorizationz"https://huggingface.co/api/spaces/z/host)rp   hostzCould not find Space: z. If it is a private or gated Space, please provide your Hugging Face access token (https://huggingface.co/settings/tokens) as the argument for the `token` parameter.z/configi  z+window.gradio_config = (.*?);[\s]*</script>r!   zCould not load the Space:    z) because the config could not be fetched.allow_flaggingzYou cannot override parameters for this Space by passing in kwargs. Instead, please load the Space as a function and use it to create a Blocks or Interface locally. You may find this Guide helpful: https://gradio.app/using_blocks_like_functions/)spacer)   )rh   ri   printrx   rV   jsonrQ   status_coderesearchr   loadsgroupAttributeErrorfrom_spaces_interfacefrom_spaces_blocks)
space_namer)   rg   r*   r3   	space_urlrp   
iframe_urlconfig_requestrresultconfigaes                r4   rj   rj      s    `	
 1=I	!)
-.GM!%,UG#4 		0EBG	
 
	V  $ZL  1W  X
 	
 YYzI5wGN!!S(IIj'2:AFF
	PZZQ0F 
	#	#s	*$$&(4]^
 	
 6!$uj
<B
 	
 MMB "
%@@)  	P9*FGRO	Ps   #$E/ /	F8FFc                N    | j                  j                        dfd}|S )zCreate a function that accepts EventData.
    The event_data_fn has to be created in this closure so that the value of endpoint
    is correctly captured.c                J    j                        } ||d| j                  iS )N
event_data)make_end_to_end_fn_data)r  argsr   endpointhelpers      r4   event_data_fnz)make_event_data_fn.<locals>.event_data_fnF  s)    ((045J$4$455r6   )r  zgr.EventData)
new_helperfn_index)r   r  r  r  s    ` @r4   make_event_data_fnr  @  s(     x001F6 r6   c                L  	 t        | |dd      j                  t        j                  d      k  rt	        dj                   d      g }j
                  j                         D ]  	t        	t              st        dt        	             	j                  rt        	fdj                  d   D        i       }|j                  d	      rt        	      }|j!                  |       j#                  	j$                        }	j'                  |      }|j!                  |       |j!                  d         t(        j*                  j-                  j                  |j.                        }|5  |j1                  fd
d d        d d d        |S # 1 sw Y   |S xY w)NF)r)   download_files_skip_componentsz4.0.0b14zCGradio version 4.x cannot load spaces with versions less than 4.x (z3).Please downgrade to version 3 to load this space.z-Expected endpoint to be an Endpoint, but got c              3  ^   K   | ]$  }|j                  d       j                  k(  r| & yw)idN)rV   r  ).0dr  s     r4   	<genexpr>z%from_spaces_blocks.<locals>.<genexpr>f  s/      uuT{h&7&77 s   *-dependenciescollects_event_datac                 $     j                         S r   )reset_session)r   s   r4   r   z$from_spaces_blocks.<locals>.<lambda>y  s    F002 r6   )r	   app_versionr   Versionr   	endpointsvaluesrS   r
   	TypeErrorr8   
backend_fnnextr  rV   r  appendr  r  r	  rA   r   from_configr(   rY   )
r   r)   predict_fns
dep_configr  r  r   rl   r   r  s
           @@r4   r   r   M  s   	F GOOJ77,QRXRdRdQe f@ @
 	
 K$$++- %(H-?X?OP  #]]>:
 J ~~34 268 D""=1**8+<+<=008""2&t$-%. YY""6==+vzzJF	 @2D$?@ M@ Ms   8FF#c                L  
 t        j                        | d
ddi|dvrd| d<   
fd}||n| |_        |d<   t        fi |}d	|d
<   |j	                  dd       }|j	                  dd       }|j	                  dd       }t        j                  |||fi |}	|	S )Nz/api/predict/zContent-Typezapplication/jsonr   r   r   c                    t        j                  d| i      } t        j                  |       }t        j                  |j
                  j                  d            }d|v rd|d   v rt        d      	 |d   }t        d         d	k(  r|d
   }t        d         d	k(  rt        |t              r|d
   }|S # t        $ r}t        d|       |d }~ww xY w)Nr{   )rp   r{   zutf-8error429z)Too many requests to the Hugging Face APIzNCould not find 'data' key in response from external Space. Response received: r>   r!   r   )r   dumpsrx   postr   rv   decoder   KeyErrorrP   rS   list)r{   r|   r  outputker~   r  rp   s        r4   r   z!from_spaces_interface.<locals>.fn  s    zz64.)::gwTBH,,33G<=f&/!9&'RSS	F^F y!"a'AYFy!"a'Jvt,DAYF  	`ag`hi	s   6B9 9	CCCr   T	_api_moderD   r>   )r   streamline_spaces_interfacer   r   r   rA   r   )r   r  rg   r)   r   r3   r   rD   r>   r   r~   rp   s    `        @@r4   r   r   }  s     77?FM*G12GM!%,UG#4 , "-%JBKF4L&#F#FF;	D$	BZZ$'FjjD)GR;F;Ir6   )=z.docz.docxz.rtfz.epubz.odtz.odpz.pptxz.txtz.mdz.pyz.ipynbz.jsz.jsxz.htmlz.cssz.javaz.csz.phpz.cz.ccz.cppz.cxxz.ctsz.hz.hhz.hppz.rsz.Rz.Rmdz.swiftz.goz.rbz.ktz.ktsz.tsz.tsxz.mz.mmz.mtsz.scalaz.dartz.luaz.plz.pmz.tz.shz.bashz.zshz.batz.coffeez.csvz.logz.iniz.cfgz.configz.jsonz.protoz.yamlz.ymlz.tomlz.sql)z.pngz.jpgz.jpegz.gifz.webpc                `   g }| D ]y  }g }|d   D ]W  }d|vrt        d|d    d      |d   dk(  r&|j                  ddt        |d   d         id	       G|j                  |       Y ||d<   |j                  |       { t        |t              r|}g }n$|j                  d
d       }|j                  dg       }g g }	}|D ]H  }
|
j                         j                  t              r|	j                  |
       8|j                  |
       J |D ]%  }|j                  dddt        |      id	gd       ' |s|	rp|xs d}|dj                  |	D 
cg c]4  }
dt        |
      j                   dt        |
      j                          6 c}
      z  }|j                  dd
|dgd       |S c c}
w )Nrv   r8   zInvalid message format: z$. Each element must have a type key.file	image_urlurlrt   )r8   r8  r   filesuserrolerv   rF   
z
## )r8   r   )rQ   r%  r   rS   r   rV   lowerendswithTEXT_FILE_EXTENSIONSrR   r   r'   	read_text)historynew_messageconversationmessagenew_contentrv   r   r:  image_filestext_encodedr7  images               r4   format_conversationrK    s    L %y) 	,GW$ .wy/A.BBfg  F*"" +!#?PV@W#X& ""7+	,  )	G$'%( +s#vt,, "BK %::<  !56%t$	%  
 !,&+-I%-P%Q
	

 |zr		 ) T
(4:+?+?+A*BC
 	
 	&$)G(HI	
 s   9F+
rI  T)
file_typessystem_message	streamingc                  	 ddl m} ddlm}	  ||xs d|       |rd|d	gng t        j                  |      }dfd
}
	 	 	 	 	 	 dfd}g }|D ].  }|dk(  r
|t        z  }|dk(  r
|t        z  }!t        d| d       d|vrddl
m}  |dd      |d<   |j                  dd      }||}n|rt        j                  |      nd} |	|r|n|
ft        |      |d|S # t        $ r}t        d      |d}~ww xY w)aN  
    Load a chat interface from an OpenAI API chat compatible endpoint.
    Parameters:
        base_url: The base URL of the endpoint, e.g. "http://localhost:11434/v1/"
        model: The name of the model you are loading, e.g. "llama3.2"
        token: The API token or a placeholder string if you are using a local model, e.g. "ollama"
        file_types: The file types allowed to be uploaded by the user. "text_encoded" allows uploading any text-encoded file (which is simply appended to the prompt), and "image" adds image upload support. Set to None to disable file uploads.
        system_message: The system message to use for the conversation, if any.
        streaming: Whether the response should be streamed.
        kwargs: Additional keyword arguments to pass into ChatInterface for customization.
    Example:
        import gradio as gr
        gr.load_chat(
            "http://localhost:11434/v1/",
            model="qwen2.5",
            token="***",
            file_types=["text_encoded", "image"],
            system_message="You are a silly assistant.",
        ).launch()
    r   )OpenAIznTo use OpenAI API Client, you must install the `openai` package. You can install it with `pip install openai`.Nr   z***)api_keybase_urlsystemr<  c                    |xs }t        ||       }j                  j                  j                  |      j                  d   j
                  j                  S )N)ro   messagesr   )rK  chatcompletionsrN   choicesrF  rv   )rF  rC  rE  r   ro   start_messages      r4   open_apizload_chat.<locals>.open_api`  sZ    *]*7G<KK##**% +  WQ	
 WWW	
r6   c              3  J  K   |xs }t        ||       }j                  j                  j                  |d      }d}|D ]]  }|j                  s|j                  d   j
                  j                  4||j                  d   j
                  j                  z  }| _ y w)NT)ro   rU  streamrF   r   )rK  rV  rW  rN   rX  deltarv   )	rF  rC  rE  r\  r|   chunkr   ro   rY  s	         r4   open_api_streamz"load_chat.<locals>.open_api_streaml  s      *]*7G<((//! 0 

  	E}}q!1!7!7!?!?!KEMM!,22:::	s   AB##B#6-B#rI  rJ  zInvalid file type: z$. Must be 'text_encoded' or 'image'.r   r   r!   Tr   rc   )rL  )
multimodalrc   )rF  str | MultimodalValuerC  list | Nonereturn
str | None)rF  ra  rC  rb  rc  zGenerator[str, None, None])openairP  ImportErrorgradio.chat_interfacer   r   none_or_singleton_to_listrA  IMAGE_FILE_EXTENSIONSrQ   r   r   r   rA   MultimodalTextboxbool)rR  ro   r)   rL  rM  rN  r3   rP  r   r   rZ  r_  supported_extensions	file_typer   textbox_argrc   r   rY  s    `               @@r4   	load_chatro  1  so   B!
 4ENUX>F;I(~	67r  00<J

&1<	#   	& $88 '! $99 %i[0TU  -#!=y**Y-K    ,@A 	 $(
# 	 E  |
	s   C* *	D3C??D)pathsexclude_pathsmethods
auth_tokenc               J
   t        | t              r| }nt        | t              rxt        |       r2t	        j
                  |       }|j                          |j                  }	n$t        |       5 }
|
j                         }	ddd       	 t        j                  	      }nt        d      |j                  di       }||ei }|D ]\  }|r&d}|D ]  }t        j                  ||      sd} n |r+|(|D ]"  }t        j                  ||      s||   ||<    S U||   ||<   ^ |}|st        d      t!        dt#        |       d	       g }|j%                         D ]b  \  }}|j%                         D ]J  \  }}|r/|j'                         |D cg c]  }|j'                          c}vr7|j)                  |||f       L d t+        j,                  |j                  d
i       j                  dd            5 }t+        j.                         5  t+        j0                  d|j                  d
i       j                  dd              t+        j0                  |j                  d
i       j                  dd             t+        j0                  d       d}|D ]d  \  }}}|d|j3                          d|j5                  dd      j5                  dd      j5                  dd       d|j3                          d| d	z  }f |dz  }t+        j0                  |       ddd       |D ]  \  }}}g }|j                  dg       D ](  }t7        j8                  |      }|j)                  |       * |j                  d      }|r)t7        j:                  ||      }|r|j)                  |       t7        j<                  |||||      }| d|j5                  dd      j5                  dd      j5                  dd       |_        t+        j0                  d|j3                          d|j5                  dd      j5                  dd      j5                  dd       dt7        j@                  |       d | d!	       |j                  d"      rt+        j0                  |d"          |r|ng } t+        jB                  d#$      }!t+        jD                  d&|| |!d%|  	 ddd       |S # 1 sw Y   WxY w# t        j                  $ r}t        d      |d}~ww xY wc c}w # 1 sw Y   xY w# 1 sw Y   S xY w)'a  
    Load a Gradio app from an OpenAPI v3 specification.

    Parameters:
        openapi_spec: URL, file path, or dictionary containing the OpenAPI specification (v3, JSON format only)
        base_url: Base URL for the API endpoints, e.g. "https://api.example.com/v1". This is used to construct the full URL for each endpoint.
        paths: Optional list of specific API paths to create Gradio endpoints from. Supports regex patterns, e.g. ["/api/v1/books", ".*user.*"]. If None, all paths in the OpenAPI spec will be included.
        exclude_paths: Optional list of API paths to exclude from the Gradio endpoints. Supports regex patterns and takes precedence over `paths`. For example, [".*internal.*"] will exclude all paths containing "internal".
        methods: Optional list of HTTP methods to include in the Gradio endpoints. If None, all methods will be included.
        auth_token: Optional authentication token to be sent as a Bearer token in the Authorization header for all API requests.
        interface_kwargs: Additional keyword arguments to pass to each generated gr.Interface instance (e.g., title, description, article, examples_per_page, etc.)
    Returns:
        A Gradio Blocks app with endpoints generated from the OpenAPI spec
    Nz0openapi_spec must be a JSON string or dictionaryz;openapi_spec must be a string (URL/file path) or dictionaryrp  FTz1No valid paths found in the OpenAPI specificationz	* Loaded z% paths from the OpenAPI specificationinfor   zOpenAPI Interface)r   z## descriptionrF   z### API EndpointszH<div style='overflow-x: auto; overflow-y: auto; max-height: 500px;'><ul>z+<li style='white-space: nowrap;'><a href='#_r    {}z' style='white-space: nowrap;'>z8 <code style='font-size: inherit; white-space: nowrap;'>z</code></a></li>
z</ul></div>
parametersrequestBodyz<h2 id='z'>z# <code style='font-size: inherit;'>z</code></h2>summaryResponserG   )r   rD   r>   r/   )#rS   r   r   r   rx   rV   raise_for_statusr   r@   readr   r   JSONDecodeErrorrQ   r   matchr   rP   itemsr?  r%  rA   r   SidebarMarkdownupperreplacer   component_from_parameter_schema"component_from_request_body_schemacreate_endpoint_fnr   
method_boxr   r   )"openapi_specrR  rp  rq  rr  rs  interface_kwargsspecr|   rv   fr   	api_pathsfiltered_pathsrt   excludedexclude_patternpatternvalid_api_paths	path_itemmethod	operationmra   api_path_strrw  components_listparam	componentrequest_bodybody_componentendpoint_fnrD   r2  s"                                     r4   load_openapir    s.   2 ,%	L#	&L)yy.H%%'mmGl# #q&&(#	X::g&D VWW"%IM5 	7D '4 Oxx6#'  $ Gxx./8t,
 (1t$!	7$ #	LMM	#i.))NOPO$??, >i!*!2 	>FI6<<>W1M!'')1MM""D&)#<=	>> 
hhvr"&&w0CD
 7	ZZ\ 	&KK#dhhvr266w@STUVWKK,00CDKK+,eL#2 fa!!' 0$,,sC2H2P2PQTVX2Y2a2abegi2j1k  lK||~&&^_c^d e"# M)LKK%	& (7 %	#D&) O"|R8 2*JJ5Q	&&y12 %==7L!/!R!R $" "#**>:(;;fi:K (!DLLc2::3CKKCQSTUV   KK6<<>*!DLLc,B,J,J3PR,S,[,[\_ac,d+eeg!,,V455XY]X^^jl }}Y'Ii01(7_RFWW:.FLL  #	A%	%7r KO# #
 ## 	XOPVWW	XJ 2N	& 	&7r KsP   ,SS 
T
4T	DTF6TST2S>>TT	TT")NNFN)r'   r   r(   zWCallable[[str, str | None], Blocks] | Literal['models', 'spaces', 'huggingface'] | Noner)   rd  r_   zbool | LoginButtonr*   PROVIDER_T | Nonerc  r   )NNN)r'   r   r(   r   r)   rd  rg   rd  r*   r  rc  r   r   )
r   r   r)   rd  rg   rd  r*   r  rc  r   )
r   r   r)   rd  rg   rd  r*   r  rc  r   )r   r   r)   rd  rc  r   )r   r   r  r   rg   rd  r)   rd  r   r   rc  r   )rC  zlist[NormalizedMessageDict]rD  ra  rc  z
list[dict])rR  r   ro   r   r)   rd  rL  zPLiteral['text_encoded', 'image'] | list[Literal['text_encoded', 'image']] | NonerM  rd  rN  rk  rc  r   )r  z
str | dictrR  r   rp  list[str] | Nonerq  r  rr  z=list[Literal['get', 'post', 'put', 'patch', 'delete']] | Noners  rd  rc  r   )D__doc__
__future__r   r   rT   r   r   rh   collections.abcr   r   pathlibr   typingr   r   rx   r   gradio_clientr	   gradio_client.clientr
   gradio_client.documentationr   gradio_client.utilsr   r   	packagingr   rr   rA   r   r   r   $gradio.components.multimodal_textboxr   gradio.contextr   gradio.exceptionsr   r   gradio.processing_utilsr   r   $huggingface_hub.inference._providersr   gradio.blocksr   rg  r   gradio.components.chatbotr   gradio.components.login_buttonr   gradio.interfacer   rY   r0   rk   rj   r  r   r   rA  ri  rK  ro  r  r/   r6   r4   <module>r     s  8 #  	 	   /  )     ) 0 N   4 4 @ " D?$3?:* 

 ',"&z
z
z
 z %z  z z z@ "&
	  	
   : #'	{{{ {  	{ {D
 #'	=A=A=A =A  	=A =A@
-`000 0 	0
 0 0f> ~ C <(<7L<<~ 
 i !%iii i
i i i i iX 

 #&*MQ!GGG 	G
 $G KG G G Gr6   