
    ;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mZ ddlmZ ddlmZmZmZm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mZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z; ddl9m<Z<m=Z= ddl>m?Z? ddl@mAZAmBZBmCZCmDZD ddlEmFZF ddlGmHZI  e        G d de             ZJy)z\
This file defines a useful high-level abstraction to build Gradio chatbots: ChatInterface.
    )annotationsN)AsyncGeneratorCallable	GeneratorSequence)Path)AnyLiteralUnioncast)document)utils)Blocks)JSONBrowserStateButtonChatbot	ComponentDatasetMarkdownMultimodalTextboxStateTextboxget_component_instance)ChatMessageExampleMessageMessageMessageDictTupleFormat)MultimodalPostprocessMultimodalValue)get_blocks_context)
DependencyEditData
SelectData)ChatCSVLogger)create_examples)special_argsupdate)I18nData)	AccordionColumnGroupRow)Request)
ThemeClassc            &          e Zd ZdZdddddddddddddddddddddddddddddddddddd	dd
%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d* fdZd Zd Z	 	 	 	 	 	 	 	 d+dZd Z	 	 d,	 	 	 	 	 	 	 d-dZ	d.dZ
ed/d       Z	 	 	 	 	 	 d0dZ	 	 	 	 d1dZd Z	 	 	 	 d2dZd3dZ	 	 	 	 	 	 d4dZ	 	 	 	 d5dZed6d       Zed7d       Z	 d8	 	 	 	 	 	 	 d9d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	 	 	 	 dAd%Z	 	 	 	 dBd&Z 	 	 	 	 dCd'Z!	 	 	 	 dDd(Z"dE fd)Z# xZ$S )FChatInterfaceaA  
    ChatInterface is Gradio's high-level abstraction for creating chatbot UIs, and allows you to create
    a web-based demo around a chatbot model in a few lines of code. Only one parameter is required: fn, which
    takes a function that governs the response of the chatbot based on the user input and chat history. Additional
    parameters can be used to control the appearance and behavior of the demo.

    Example:
        import gradio as gr

        def echo(message, history):
            return message

        demo = gr.ChatInterface(fn=echo, type="messages", examples=[{"text": "hello", "text": "hola", "text": "merhaba"}], title="Echo Bot")
        demo.launch()
    Demos: chatinterface_random_response, chatinterface_streaming_echo, chatinterface_artifacts
    Guides: creating-a-chatbot-fast, sharing-your-app
    FNT)LikeDislikez.gradio/flaggeddefaultminimalchat)%
multimodaltypechatbottextboxadditional_inputsadditional_inputs_accordionadditional_outputseditableexamplesexample_labelsexample_iconsrun_examples_on_clickcache_examples
cache_modetitledescriptionthemeflagging_modeflagging_optionsflagging_dircss	css_pathsjshead
head_pathsanalytics_enabled	autofocus
autoscroll
submit_btnstop_btnconcurrency_limitdelete_cacheshow_progressfill_height
fill_widthapi_namesave_historyc       %        	   t         +|   |d|xs d|||||||#|$|!       |%| _        || _        || _        | | _        t        |t              r|j                  | _        n|| _        t        j                  | j                        xs t        j                  | j                        | _        t        j                  | j                        xs t        j                  | j                        | _        |du| _        |
| _        | j#                  |
||      | _        || _        || _        || _        |	| _        |#| _        || _        || _        || _        || _        |"| _        |&r|dk(  st;        d      |&| _        t?        j@                  |      D 'cg c]  }'tC        |'       c}'| _"        t?        j@                  |      | _#        |ddd	| _$        npt        |tJ              r
d
|i| _$        nVt        |tL              r%|jO                  |jQ                               | _$        n!t;        dtS        j                  |             d| _*        | jD                  rj| j                   ^| j                   D ]O  }(t        |(tV              st;        d      tY        |(      D ]  \  })}*|*	|)dkD  sd| _*         n | jT                  sO n |t[        j\                  dd      }|dv r|| _/        nt;        d      || _0        || _1        t        |td        tf        f      r|ji                          t        |tj              r|ji                          | 5  tm        g d| jn                         | _8        ts        d      | _:        ts               | _;        ts               | _<        t{               5  | j}                          | j<                  r_t        d      5  | j                          t{        d      5  | j                  ||||       | j                          ddd       ddd       n$| j                  ||||       | j                          ddd       | j                          ddd       yc c}'w # 1 sw Y   \xY w# 1 sw Y   ;xY w# 1 sw Y   ?xY w# 1 sw Y   yxY w)a(  
        Parameters:
            fn: the function to wrap the chat interface around. Normally (assuming `type` is set to "messages"), the function should accept two parameters: a `str` representing the input message and `list` of openai-style dictionaries: {"role": "user" | "assistant", "content": `str` | {"path": `str`} | `gr.Component`} representing the chat history. The function should return/yield a `str` (for a simple message), a supported Gradio component (e.g. gr.Image to return an image), a `dict` (for a complete openai-style message response), or a `list` of such messages.
            multimodal: if True, the chat interface will use a `gr.MultimodalTextbox` component for the input, which allows for the uploading of multimedia files. If False, the chat interface will use a gr.Textbox component for the input. If this is True, the first argument of `fn` should accept not a `str` message but a `dict` message with keys "text" and "files"
            type: The format of the messages passed into the chat history parameter of `fn`. If "messages", passes the history as a list of dictionaries with openai-style "role" and "content" keys. The "content" key's value should be one of the following - (1) strings in valid Markdown (2) a dictionary with a "path" key and value corresponding to the file to display or (3) an instance of a Gradio component: at the moment gr.Image, gr.Plot, gr.Video, gr.Gallery, gr.Audio, and gr.HTML are supported. The "role" key should be one of 'user' or 'assistant'. Any other roles will not be displayed in the output. If this parameter is 'tuples' (deprecated), passes the chat history as a `list[list[str | None | tuple]]`, i.e. a list of lists. The inner list should have 2 elements: the user message and the response message.
            chatbot: an instance of the gr.Chatbot component to use for the chat interface, if you would like to customize the chatbot properties. If not provided, a default gr.Chatbot component will be created.
            textbox: an instance of the gr.Textbox or gr.MultimodalTextbox component to use for the chat interface, if you would like to customize the textbox properties. If not provided, a default gr.Textbox or gr.MultimodalTextbox component will be created.
            editable: if True, users can edit past messages to regenerate responses.
            additional_inputs: an instance or list of instances of gradio components (or their string shortcuts) to use as additional inputs to the chatbot. If the components are not already rendered in a surrounding Blocks, then the components will be displayed under the chatbot, in an accordion. The values of these components will be passed into `fn` as arguments in order after the chat history.
            additional_inputs_accordion: if a string is provided, this is the label of the `gr.Accordion` to use to contain additional inputs. A `gr.Accordion` object can be provided as well to configure other properties of the container holding the additional inputs. Defaults to a `gr.Accordion(label="Additional Inputs", open=False)`. This parameter is only used if `additional_inputs` is provided.
            additional_outputs: an instance or list of instances of gradio components to use as additional outputs from the chat function. These must be components that are already defined in the same Blocks scope. If provided, the chat function should return additional values for these components. See $demo/chatinterface_artifacts.
            examples: sample inputs for the function; if provided, appear within the chatbot and can be clicked to populate the chatbot input. Should be a list of strings representing text-only examples, or a list of dictionaries (with keys `text` and `files`) representing multimodal examples. If `additional_inputs` are provided, the examples must be a list of lists, where the first element of each inner list is the string or dictionary example message and the remaining elements are the example values for the additional inputs -- in this case, the examples will appear under the chatbot.
            example_labels: labels for the examples, to be displayed instead of the examples themselves. If provided, should be a list of strings with the same length as the examples list. Only applies when examples are displayed within the chatbot (i.e. when `additional_inputs` is not provided).
            example_icons: icons for the examples, to be displayed above the examples. If provided, should be a list of string URLs or local paths with the same length as the examples list. Only applies when examples are displayed within the chatbot (i.e. when `additional_inputs` is not provided).
            cache_examples: if True, caches examples in the server for fast runtime in examples. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
            cache_mode: if "eager", all examples are cached at app launch. If "lazy", examples are cached for all users after the first use by any user of the app. If None, will use the GRADIO_CACHE_MODE environment variable if defined, or default to "eager".
            run_examples_on_click: if True, clicking on an example will run the example through the chatbot fn and the response will be displayed in the chatbot. If False, clicking on an example will only populate the chatbot input with the example message. Has no effect if `cache_examples` is True
            title: a title for the interface; if provided, appears above chatbot in large font. Also used as the tab title when opened in a browser window.
            description: a description for the interface; if provided, appears above the chatbot and beneath the title in regular font. Accepts Markdown and HTML content.
            theme: a Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None, will use the Default theme.
            flagging_mode: one of "never", "manual". If "never", users will not see a button to flag an input and output. If "manual", users will see a button to flag.
            flagging_options: a list of strings representing the options that users can choose from when flagging a message. Defaults to ["Like", "Dislike"]. These two case-sensitive strings will render as "thumbs up" and "thumbs down" icon respectively next to each bot message, but any other strings appear under a separate flag icon.
            flagging_dir: path to the the directory where flagged data is stored. If the directory does not exist, it will be created.
            css: Custom css as a code string. This css will be included in the demo webpage.
            css_paths: Custom css as a pathlib.Path to a css file or a list of such paths. This css files will be read, concatenated, and included in the demo webpage. If the `css` parameter is also set, the css from `css` will be included first.
            js: Custom js as a code string. The custom js should be in the form of a single js function. This function will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside <script> tags.
            head: Custom html code to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.
            head_paths: Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first.
            analytics_enabled: whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.
            autofocus: if True, autofocuses to the textbox when the page loads.
            autoscroll: If True, will automatically scroll to the bottom of the chatbot when a new message appears, unless the user scrolls up. If False, will not scroll to the bottom of the chatbot automatically.
            submit_btn: If True, will show a submit button with a submit icon within the textbox. If a string, will use that string as the submit button text in place of the icon. If False, will not show a submit button.
            stop_btn: If True, will show a button with a stop icon during generator executions, to stop generating. If a string, will use that string as the submit button text in place of the stop icon. If False, will not show a stop button.
            concurrency_limit: if set, this is the maximum number of chatbot submissions that can be running simultaneously. Can be set to None to mean no limit (any number of chatbot submissions can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `.queue()`, which is 1 by default).
            delete_cache: a tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur.
            show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
            fill_height: if True, the chat interface will expand to the height of window.
            fill_width: Whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width.
            api_name: the name of the API endpoint to use for the chat interface. Defaults to "chat". Set to False to disable the API endpoint.
            save_history: if True, will save the chat history to the browser's local storage and display previous conversations in a side panel.
        chat_interfaceGradio)rQ   moderF   rH   rL   rM   rN   rO   rP   rY   rZ   rW   Nmessagesz2save_history is only supported for type='messages'zAdditional InputsF)labelopenrb   zRThe `additional_inputs_accordion` parameter must be a string or gr.Accordion, not zEExamples must be a list of lists when additional inputs are provided.r   TGRADIO_CHAT_FLAGGING_MODEnever)manualre   zIInvalid value for `flagging_mode` parameter.Must be: 'manual' or 'never'._saved_conversations_)storage_key   )scale   )Dsuper__init__r[   r9   r8   rV   
isinstancer2   fninspectiscoroutinefunctionisasyncgenfunctionis_asyncisgeneratorfunctionis_generatorprovided_chatbotr@   _setup_example_messagesexamples_messagesrC   rD   rE   r?   rY   rS   rR   rF   rG   rX   
ValueErrorr\   r   none_or_singleton_to_listr   r<   r>   "additional_inputs_accordion_paramsstrr+   recover_kwargs
get_configbuiltins_additional_inputs_in_exampleslist	enumerateosgetenvrI   rJ   rK   r   r   unrenderr   r   _idsaved_conversationsr   conversation_idsaved_inputnull_componentr,   _render_headerr.   _render_history_area_render_chatbot_area_render_footer_setup_events),selfro   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   iexampleidxexample_for_input	__class__s,                                              U/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/chat_interface.pyrm   zChatInterface.__init__J   s   f 	/!#8!#!% 	 	
 !	$!2b-(eeDGDG33GG
 1''0 	 $77GG
 1''0 	 !(t 3 !%!=!=nm"
 &;",$ &$"
&*
 2QRR( 445FG"
 #1%"
 #("A"ABT"U&.,7D3 3S947D3 3Y?+::/::< 3 demerer  tO  fP  eQ  R  /4+!!dmm&?== 
!'40$_  /8.@ *C*(4q>B; 66
  II&A7KM//!.D0  !1(g):;<gw' 	!'3"7z B(D$ $);D $wD"''D *##%$$1 2113#!_ 2 55 '*h !//1	22 2 --gw
HU'')*  -	! 	!m"
F2 22 2* *	! 	!s[   QAR)Q7Q+%Q	Q+-Q79RQ($Q++Q40Q77R 	<RRc                    | j                   rt        d| j                    d       | j                  rt        | j                         y y )Nz4<h1 style='text-align: center; margin-bottom: 1rem'>z</h1>)rF   r   rG   r   s    r   r   zChatInterface._render_header  s@    ::FtzzlRWX T%%&     c           	         t        dd      5  t        dddt        j                  d            | _        t        t        d	
      gd	dd      | _        d d d        y # 1 sw Y   y xY w)Nri   d   )rj   	min_widthzNew chatprimarymdzplus.svg)variantsizeiconFvisibletableindex)
components
show_labellayoutr9   )r,   r   r   get_icon_pathnew_chat_buttonr   r   chat_history_datasetr   s    r   r   z"ChatInterface._render_history_area!  sh    !s+ 	#)!((4	$D  )0#E23 	)D%	 	 	s   AAA'c                   |rJ| j                   ro| j                   |j                   k7  rt        j                  d| j                    d       t        t        d   | j                         |_         |j                          n4t        j                  d|j                    d       |j                   | _         t        t        t        |d            | _        | j                  j                  r!| j                  rt        j                  d       | j                  s| j                  nd | j                  _	        | j                  j                          nv| j                   xs d| _         t        d	d
| j                  rdnd t        t        d   | j                         | j                  | j                  s| j                  nd       | _        t               5  t!               5  |rSd|_        t        |d      }t%        |t&        t(        f      s!t+        dt-        j                   |             || _        n6| j0                  rt(        nt&        } |dddd| j2                  ||      | _        d d d        d d d        | j.                  j4                  | _        d| j.                  _        t9        dd      | _        t=        dd      | _        tA        | j                  jB                  r| j                  jB                  ng       | _"        tA        | j                  jB                  r | j                  jB                        | _#        y g       | _#        y # 1 sw Y   xY w# 1 sw Y   xY w)NznThe type of the gr.Chatbot does not match the type of the gr.ChatInterface.The type of the gr.ChatInterface, 'z', will be used.)ra   tupleszSThe gr.ChatInterface was not provided with a type, so the type of the gr.Chatbot, 'T)renderzaThe ChatInterface already has examples set. The examples provided in the chatbot will be ignored.r   r   ri     )rb   rj   heightr9   rS   r@   FzAExpected a gr.Textbox or gr.MultimodalTextbox component, but got r   zType a message...   )r   rb   placeholderrj   rR   rT   rU   zFake APIr   Response)rb   r   )$r9   warningswarnr   r
   _setup_data_modelr   r   r:   r@   rx   r   _setup_examplesrY   rS   r-   r.   r   rn   r   r   	TypeErrorr   r;   r8   rR   rU   original_stop_btnr   fake_api_btnr   api_responser   valuechatbot_statechatbot_value)r   r:   r;   rT   rU   textbox_textbox_components          r   r   z"ChatInterface._render_chatbot_area1  s    yy99,MM>>Bii[HXZ $(0D(Etyy#QGL--/ijqjvjviw  xH  I $LL	)?PT)UVDL||$$)?)?w
 :: && LL!
 LL((*		-XDI""..sD'"67C??:: //	DL W 	 ).G&5gdKH%h:K0LM'_`h`m`mnv`w_xy  $,DL .2__)' & $5#('$7"&..#-!)$DL	2 "&!6!6 %":u= e
 #9K9K4<<#5#5QST #9K9K4<<#5#5TQSTK 	 	s%   MBM%MM	MMc                d   | j                   rt        | j                   | j                  g| j                  z   | j                  | j
                  r| j                  n| j                  | j                  t        t        d   | j                        | j                  | j                        | _        t        d | j                  D              }| j                  rQ|rNt        di | j                   5  | j                  D ]  }|j"                  r|j%                          ! 	 d d d        y y y # 1 sw Y   y xY w)N)eagerlazy)r@   inputsoutputsro   rD   rE   r   
preprocessc              3  6   K   | ]  }|j                      y wN)is_rendered).0inps     r   	<genexpr>z/ChatInterface._render_footer.<locals>.<genexpr>  s      $
$'$
s    )r@   Examplesr;   r<   r:   ru   _examples_stream_fn_examples_fnrD   r   r
   rE   r   examples_handleranyr+   r{   r   r   )r   any_unrendered_inputsinput_components      r   r   zChatInterface._render_footer  s
   ==$,~(>(>>/3/@/@4++dFWFW#22 8$//J;;>>	%D! !$ $
+/+A+A$
 !
 !!&;ETDDE 1'+'='= 1O*66'..011 1 '<!1 1s   +D&D&&D/c                   g }|rt        |      D ]  \  }}t        |t              r|d   }i }t        |t              r||d<   n:t        |t              r*|j                  dd      |d<   |j                  dg       |d<   |r||   |d<   | j                  r,|j                  d      }|s#|r	||   |d<   ndd d dddid	|d<   n
|r||   |d<   |j                  |        |S )
Nr   text filesdisplay_textr   _typezgradio.FileData)pathurl	orig_name	mime_typemeta)r   rn   r   r|   dictgetr8   append)	r   r@   rA   rB   rx   r   r   example_messageexample_filess	            r   rw   z%ChatInterface._setup_example_messages  s    "+H"5 :wgt,%ajG24gs+.5OF+..5kk&".EOF+/6{{7B/GOG,!6DU6KON3??$3$7$7$@M((6CE6JOF3 )+'+-1-3)02C(D7OF3 #.;E.BOF+!((95:6 ! r   c                    d}|D ]-  }|d   dk(  st        |d   t              r
||d   z  } n|dz  }/ t        |      dkD  r|dd dz   }|xs d	S )
u   
        Generate a title for a conversation by taking the first user message that is a string
        and truncating it to 40 characters. If files are present, add a 📎 to the title.
        r   roleusercontentu   📎 (   Nz...Conversation)rn   r|   len)r   conversationrF   messages       r   _generate_chat_titlez"ChatInterface._generate_chat_title  sw    
 # 	%Gv&(gi0#6WY//EW$E	% u:?#2J&E&&r   c                     dfd |       S )Nc                   t        | t              r| D cg c]
  } |       c}S t        | t              r*| j                         D ci c]  \  }}| |       c}}S t        | t              r| j
                  S | S c c}w c c}}w r   )rn   r   r   itemsr   r   )objitemkvinners       r   r   z1ChatInterface.serialize_components.<locals>.inner  sp    #t$034d44C&03		<158<<C+yy J 5<s   B B)r   r	   returnr	   r   )r   r   s    @r   serialize_componentsz"ChatInterface.serialize_components  s    	 \""r   c                    | j                   r6| j                  |      }|	|||<   ||fS |xs g }|j                  d|       d}||fS Nr   )r\   r   insert)r   r   r   r   serialized_conversations        r   _save_conversationz ChatInterface._save_conversation  sl     &*&?&?&M# -D#E*
 ))) ':&?R##**1.EF)))r   c                0    ||j                  |       d |fS r   )pop)r   r   r   s      r   _delete_conversationz"ChatInterface._delete_conversation  s$    
 ##E*(((r   c                l    t        |xs g D cg c]  }|r| j                  |      g c}      S c c}w )N)samples)r   r   )r   conversationsconvs      r   _load_chat_historyz ChatInterface._load_chat_history  sB     */R **401
 	
s   1c                (    |t        ||   g d      fS )Nra   )r   feedback_valuer9   )r   )r   r   r  s      r   _load_conversationz ChatInterface._load_conversation   s'     #E*!
 	
r   c                   ddl m} | j                  r| j                  n| j                  }d | j
                  g| j                  | j                  gddd}|| j                  | j                  g| j                  z   | j                  | j
                  g| j                  z   dt        t        t        t        d   d f   | j                         t        t        d   | j"                        d}| j$                  | j&                  | j                  | j(                  g| j&                  | j(                  gddd} | j*                  j-                  | j.                  | j*                  g| j*                  | j                  gdd	      j1                  | j2                  | j                  | j
                  g| j
                  gdd	      j0                  di |}  |j0                  di |j1                  d
 d | j*                  d      j0                  di | | j4                  j7                  || j*                  | j                  g| j                  z   | j8                  | j                  g| j                  z   t        t        t:        t        d   f   | j<                        t        t        t        t        d   d f   | j                         d       d }t?        | j
                  t@              r| jB                  r| jD                  s| jF                  s| jH                  rp| j
                  jK                  | jL                  d | j
                  | j                  gd      }| jF                  s |j0                  di |} |j0                  di | n4| j
                  jK                  | jN                  d | j*                  gd      } | j
                  jQ                  | jR                  | j                  g| j                  | j                  gdd	      j1                  | j2                  | j                  | j                  g| j
                  gdd	      j1                  d | j*                  gd      j0                  di |}  |j0                  di |j1                  d | j*                  gd      j0                  di | ||g}	||	jU                  |       | jW                  | j*                  j,                  | j
                  jP                  | j
                  jJ                  g|	         | j
                  jY                  | jR                  | j
                  g| j
                  | j*                  gdd	      j0                  di |j0                  di |    | j
                  j[                  | j\                  | j
                  g| j
                  | j                  gd      j0                  di |j0                  di |j0                  di |  | j
                  j^                  di |j1                  | j`                  | j&                  | j(                  g| j&                  | j(                  gdd	       | jb                  r   | j
                  je                  | jf                  | j
                  g| j
                  | j                  | j                  gd      jh                  di |jh                  di |j0                  di | | jj                  r8| jl                  j7                  d d | j&                  | j
                  gdd	      j1                  d | j
                  g| j                  gdd	        || jn                  | j(                  jp                  g| jr                  | j(                  g| jt                  gdd        | jt                  j7                  d d | j
                  gddd      j1                  | jv                  | jt                  | j(                  g| j&                  | j
                  gddd      j0                  di | | jx                  dk7  rpt{               }
|
j}                  | j~                         | j                  | j
                  _A        | j
                  j                  |
j                  | j
                          | j                  jq                  d | j                  g| j
                  gd      j0                  di | y )Nr   )onc                
    | | fS r   r   xs    r   <lambda>z-ChatInterface._setup_events.<locals>.<lambda>  s
    QF r   F)ro   r   r   show_apiqueuer5   )fullr6   hidden)ro   r   r   r  rV   rX   r  r  c                     t        d d      S )NT)r   interactiver)   r   r   r   r  z-ChatInterface._setup_events.<locals>.<lambda>D  s    F48 r   )r  )r[   rV   postprocessc                     t        dd      S )NFr   r  r   r  r   r   r   r  z-ChatInterface._setup_events.<locals>.<lambda>~  s    5bA r   )r   r  c                     t        d      S )NT)r  r  r   r   r   r  z-ChatInterface._setup_events.<locals>.<lambda>  s    Ft, r   )event_triggersevents_to_cancelc                 
    d g fS r   r   r   r   r   r  z-ChatInterface._setup_events.<locals>.<lambda>  s
    r
 r   c                    | S r   r   r  s    r   r  z-ChatInterface._setup_events.<locals>.<lambda>  s    ! r   )triggersro   r   r   r  r  c                     g S r   r   r   r   r   r  z-ChatInterface._setup_events.<locals>.<lambda>  s     r   r  )r  r  rX   re   c                    | S r   r   r  s    r   r  z-ChatInterface._setup_events.<locals>.<lambda>  s    a r   r   )Dgradior
  ru   
_stream_fn
_submit_fnr:   r   r   r   r<   r   r>   r   r   intr
   rV   rX   r   r   r   r;   submit_clear_and_save_textboxthen_append_message_to_historyr   clickr   r|   r[   rn   r   r@   r   rD   rC   example_selectexample_clickedexample_populatedretry_pop_last_user_messager   _setup_stop_eventsundooption_selectoption_clickedclearr   r?   edit_edit_messagesuccessr\   r   loadchanger  r   r  rI   r&   setuprK   rJ   feedback_optionslikeflag)r   r
  	submit_fnsynchronize_chat_state_kwargssubmit_fn_kwargssave_fn_kwargssubmit_eventexample_select_eventretry_eventr  flagging_callbacks              r   r   zChatInterface._setup_events  s	   '+'8'8DOOdoo	 #||n**D,>,>?)
% ''););<t?U?UU++T\\:T=T=TT!%c79-t34d6L6L" "34d6H6H
 ))$$""((
 ,,d.F.FG

DLL,,t//0    T//!!4<<0   T& %& 	"	:9:??8LL	 	@ 	

 $	!
  	! 	\\4--.1G1GG 2 23d6M6MM%WU^ 34dmmD"c79-t34d6L6L  	  		
  $t||W-77""d&@&@'+||'B'B((\\4#3#34"	 (C ($ **+D+?+D+D+XGW+X()$))J,IJ'+||'B'B**\\N"	 (C ($DLL++##$##T%5%56   T//!!4#5#56   TA  
 T'&& %'& 	,	989>>,\\N 	? 	
 $		!  		! )+6+##$89##""++
 . 	  	
	5 	''\\N\\4<<( 	 	
 $	0 /	0 15	G 8F	G	N 	( 	""\\N\\4++,	 	# 	

 $	#
 "	#
 $(4	I
 +H	I
 JN	
 	
 	;:;@@%%!!4#;#;<!!4#;#;< 	A 	
 ==X 2 DLL""t1143C3CD	  
 g*
 )*
 +2'S
 5RS
 TXSW !   &&"%%t||4 '  d##$   ))T%=%=%D%DE**001223D%%++& ,  d''**D,D,DE%%t||4&   d4 34  ( -##D$5$56,0,A,ADLL)LL/44dllC	!! \\N	 	" 	

 $	0
 /	0r   c                     j                   rt        nt         j                  j                  |D ]1  } |t        j                   fd      d  j                  gdd       3 |D ]:  }|j                  t        j                  fd      d  j                  gdd       <  j                  j                  d d d |d       y )Nc                 ,     d j                         S NF)rT   rU   )r   )r   r   s   r   r  z2ChatInterface._setup_stop_events.<locals>.<lambda>  s    -#(!%!7!7 r   Fr  c                       d      S rH  r   )original_submit_btnr   s   r   r  z2ChatInterface._setup_stop_events.<locals>.<lambda>  s    -#6 r   )cancelsr  )	r8   r   r   r;   rT   r   async_lambdar(  stop)r   r  r  event_triggerevent_to_cancelrJ  r   s   `    @@r   r0  z ChatInterface._setup_stop_events  s     26-g"ll55+ 	M"" 	  0 	O  ""
  ! 
	 	$ 	 	
r   c                B     t        | j                        ddd      |fS )Nr   Fr  )r9   r;   )r   r   s     r   r'  z%ChatInterface._clear_and_save_textbox  s(     Dru"E
 	
r   c                    g }| D ]R  }|d   dk(  r|j                  |d   d f       "|r|d   d   |d   d   |d   f|d<   =|j                  d |d   f       T |S )Nr   r   r   ri   r   r   )history_messageshistory_tuplesr   s      r   _messages_to_tuplesz!ChatInterface._messages_to_tuples!  s    ' 	BGv&(%%wy'94&@AN2$6q$9$A&4R&8&;WY=O%Pr"%%tWY-?&@A	B r   c                    g }| D ];  }|d   r|j                  d|d   d       |d   s%|j                  d|d   d       = |S )Nr   r   r   r   ri   	assistantrS  )rU  rT  message_tuples      r   _tuples_to_messagesz!ChatInterface._tuples_to_messages-  sc    + 	MQ ''MRSDT(UVQ ''(]15EF		  r   c                    | j                  ||      }| j                  dk(  r| j                  |      }nt        j                  |      }|j                  |       | j                  dk(  r| j                  |      }|S )Nr   )_message_as_message_dictr9   r[  copydeepcopyextendrV  )r   r   historyr   message_dictss        r   r)  z(ChatInterface._append_message_to_history9  sm     55gtD99 ..w7GmmG,G}%99 ..w7Gr   c                   g }t        |t              s|g}|D ]S  }t        |t              r |j                  |j	                                4t        |t
              r<||_        |j                  t        j                  |t        j                               t        |t        t        f      r|j                  ||d       t        |t              rd|v r||d<   |j                  |       |j                  dg       D ]8  }t        |t              r|j                  d      }|j                  ||fd       : |d   t        |d   t              s=|j                  ||d   d       V |S )z
        Converts a user message, example message, or response from the chat function to a
        list of MessageDict objects that can be appended to the chat history.
        )dict_factoryrX  r   r   r   r   r   )rn   r   r   r   
model_dumpr   r   dataclassesasdictr   rd  r|   r   r   r   )r   r   r   rb  msgr  s         r   r]  z&ChatInterface._message_as_message_dictI  sN    '4(iG 	QC#w'$$S^^%56C-$$&&s9K9KL C#y!12$$ds%CD3%)s*:"F$$S)"- JA!!T*EE&M!(($A4)HIJ v;&jVc.J!(($3v;)OP/	Q0 r   c                  K   t        | j                  ||g||      \  }}}| j                  r | j                  |  d {   }n?t        j                  j
                  | j                  g|d| j                  i d {   }| j                  r|^}}nd }| j                  ||d      }| j                  ||d      }|r||g|S ||fS 7 7 LwNr   requestlimiterr   rY  )	r(   ro   rs   anyio	to_threadrun_syncrm  r>   r)  )	r   r   ra  rl  argsr   _responser>   s	            r   r$  zChatInterface._submit_fno  s      $GGWg55w
1 ==$TWWf--H"__55 *.,, H "",4)H)!%11'7FK11(G[QW9'999   .s$   ?CC?CCACCc                 K   t        | j                  ||g||      \  }}}| j                  r | j                  | }n_t        j                  j
                  | j                  g|d| j                  i d {   }t        j                  || j                        }| j                  ||d      }d }	 t        j                  |       d {   }	| j                  r|	^}	}| j                  |	|d      }
|s|	|
f n
|	|
g| |2 3 d {   }| j                  r|^}}| j                  ||d      }
|s||
f 6||
g| A7 7 # t        $ r
 d |f Y Yw xY w7 V6 y wrj  )r(   ro   rs   rn  ro  rp  rm  r   SyncToAsyncIteratorr)  async_iterationr>   StopIteration)r   r   ra  rl  rq  r   rr  	generatorr>   first_responsehistory_rs  s               r   r#  zChatInterface._stream_fn  s     $GGWg55w
1 ==(I#oo66 *.,, I 11)T\\JI11'7FK!	 #(#8#8#CCN&&6D3!366H &$h..$hC1CCC ( 	> 	>(&&08--66x+VH%((=+===7 D  	 -	 	>isl   A7E)9E:9E)4E E;E E)
E'E%E':E)E E"E)!E""E)%E''E)c                Z    |j                  d|j                  d       ||j                  fS )a!  
        When an option is clicked, the chat history is appended with the option value.
        The saved input value is also set to option value. Note that event can only
        be called if self.type is "messages" since options are only available for this
        chatbot type.
        r   rX  )r   r   )r   ra  options      r   r3  zChatInterface.option_clicked  s(     	6<<@A$$r   c                    |j                   j                  dg       D cg c]  }|d   	 c}|j                   d<   |S c c}w )z
        Returns an example with the files flattened to just the file path.
        Also ensures that the `files` key is always present in the example.
        r   r   )r   r   )r   r   fs      r   _flatten_example_filesz$ChatInterface._flatten_example_files  s>    
 6=]]5F5FwPR5S!T!F)!Tg "Us   =c                r    | j                   r| j                  |      }|j                  S |j                  d   S )Nr   )r8   r  r   )r   r   s     r   r-  zChatInterface.example_populated  s2    ??11':G== ==((r   c                    t        |j                  t        t        f      r|d |j                  d    }n|d |j                   }|||j                  fS r   )rn   r   r   tupler   )r   ra  	edit_datas      r   r6  zChatInterface._edit_message  sN     iooe}52	 23G/	0G00r   c              #  L  K   | j                  |j                  g d      }| j                  |      }| j                  r|j                  n|j                  d   }||f | j                  r9| j
                  j                  |j                        d   j                  }||f yyw)z
        When an example is clicked, the chat history (and saved input) is initially set only
        to the example message. Then, if example caching is enabled, the cached response is loaded
        and added to the chat history as well.
        r   r   r   N)	r)  r   r  r8   rD   r   load_from_cacher   root)r   r   ra  r   s       r   r,  zChatInterface.example_clicked  s      11'--VL--g6#'??'--f8Mw++;;GMMJ1MRRG7"" s   B"B$c                X   g }| j                   rt        t        |      }| j                  dk(  rN|j	                  dg       D ]  }|j                  |d g        d|v r|j                  |d   d g       ||d   d<   |S |j	                  dg       D ]8  }t        |t              r|j	                  d      }|j                  d|fd       : d|v r|j                  d|d   d       |j                  d	|d       |S t        t        |      }| j                  dk(  r||gg}|S d|dd	|dg}|S )
Nr   r   r   rR  ri   r   r   rX  rY  )	r8   r   r   r9   r   r   rn   r   r|   )r   r   rs  resultfiles        r   _process_examplezChatInterface._process_example  sQ    ??>73GyyH$#KK4 0DMM4,/0W$MM76?D"9: (r
1$ ! $KK4 HD!$-#xx/MM6tg"FGH W$MM6gfo"NO{xHI  3(GyyH$"H-.  $8(X> r   c                <  K   t        | j                  |g g|d       \  }}}| j                  r | j                  |  d {   }n?t        j                  j
                  | j                  g|d| j                  i d {   }| j                  ||      S 7 V7 wNrk  rm  )r(   ro   rs   rn  ro  rp  rm  r  )r   r   rq  r   rr  rs  s         r   r   zChatInterface._examples_fn  s      $DGGWb4H44HRVW1==$TWWf--H"__55 *.,, H $$Wh77 .s#   ?BB?BBBBc                 K   t        | j                  |g g|d       \  }}}| j                  r | j                  | }n_t        j                  j
                  | j                  g|d| j                  i d {   }t        j                  || j                        }|2 3 d {   }| j                  ||       7 E7 6 y wr  )
r(   ro   rs   rn  ro  rp  rm  r   ru  r  )r   r   rq  r   rr  rx  rs  s          r   r   z!ChatInterface._examples_stream_fn  s     
 $DGGWb4H44HRVW1==(I#oo66 *.,, I 11)T\\JI' 	; 	;(''::	;is6   A7C9B?:&C C$C%C(CCCc                X   |s|| j                   sdfS dg dfS | j                  dk(  r| j                  |      }t        |      dz
  }|dk\  r!||   d   dk(  r|dz  }|dk\  r||   d   dk(  r|dk\  r!||   d   dk(  r|dz  }|dk\  r||   d   dk(  r||dz   d	 }d}g }|D ]I  }t	        |t
              sJ |d   dk(  s|d
   }t	        |t              r|j                  |d          H|}K | j                   r||dn|}|d	|dz    }	| j                  dk(  r| j                  |	      }	|	|fS )a1  
        Removes the message (or set of messages) that the user last sent from the chat history and returns them.
        If self.multimodal is True, returns a MultimodalPostprocess (dict) object with text and files.
        If self.multimodal is False, returns just the message text as a string.
        r   )r   r   r   ri   r   r   rY  r   Nr   )	r8   r9   r[  r   rn   r   r  r   rV  )
r   ra  r   last_messageslast_user_messager   rh  r   return_messagerz  s
             r   r/  z$ChatInterface._pop_last_user_message,  s    dooBTTBQS;TTT99 ..w7GL11fF+{:FA 1fF+{:1fF+v5FA 1fF+v5A(  	0Cc4(((6{f$i.gu-LL,(/%	0  '7" 	
 7QU#99 //9H''r   c                r    t               r+| j                  sd| j                  _        t        |           | S )Nr   )r"   rv   r:   r   rl   r   )r   r   s    r   r   zChatInterface.renderT  s,    (=(="%DLLGNr   )Lro   r   r8   boolr9   z$Literal['messages', 'tuples'] | Noner:   Chatbot | Noner;   "Textbox | MultimodalTextbox | Noner<   z.str | Component | list[str | Component] | Noner=   zstr | Accordion | Noner>   z"Component | list[Component] | Noner?   r  r@   5list[str] | list[MultimodalValue] | list[list] | NonerA   list[str] | NonerB   r  rC   r  rD   bool | NonerE   zLiteral['eager', 'lazy'] | NonerF   zstr | I18nData | NonerG   
str | NonerH   zTheme | str | NonerI   z!Literal['never', 'manual'] | NonerJ   z"list[str] | tuple[str, ...] | NonerK   r|   rL   r  rM   (str | Path | Sequence[str | Path] | NonerN   zstr | Literal[True] | NonerO   r  rP   r  rQ   r  rR   r  rS   r  rT   str | bool | NonerU   r  rV   zint | None | Literal['default']rW   ztuple[int, int] | NonerX   z$Literal['full', 'minimal', 'hidden']rY   r  rZ   r  r[   zstr | Literal[False]r\   r  )r:   r  r;   r  rT   r  rU   r  )NN)r@   r  rA   r  rB   r  r   zlist[ExampleMessage])r   list[MessageDict]r   r|   )r   r  r   r  )r   
int | Noner   r  r   list[list[MessageDict]])r   r  r   r  )r   r%  r  r  )r   None)r  zlist[Callable]r  zlist[Dependency]r   r  )r   str | MultimodalPostprocessr   z?tuple[Textbox | MultimodalTextbox, str | MultimodalPostprocess])rT  r  r   r   )rU  r   r   r  )r   )r   FMessageDict | Message | str | Component | MultimodalPostprocess | listra  list[MessageDict] | TupleFormatr   Literal['user', 'assistant']r   r  )r   r  r   r  r   r  )r   r  ra  TupleFormat | list[MessageDict]rl  r/   r   r  )r   r  ra  r  rl  r/   r   zAsyncGenerator[tuple, None])ra  r  r|  r%   r   zCtuple[TupleFormat | list[MessageDict], str | MultimodalPostprocess])r   r%   )ra  r  r  r$   r   zdtuple[list[MessageDict] | TupleFormat, list[MessageDict] | TupleFormat, str | MultimodalPostprocess])r   r%   r   zZGenerator[tuple[TupleFormat | list[MessageDict], str | MultimodalPostprocess], None, None])r   ExampleMessage | strrs  zMessageDict | str | None)r   r  r   r  )r   r|   r   r   )ra  r  r   zCtuple[list[MessageDict] | TupleFormat, str | MultimodalPostprocess])r   r2   )%__name__
__module____qualname____doc__rm   r   r   r   r   rw   r   staticmethodr   r   r   r  r  r   r0  r'  rV  r[  r)  r]  r$  r#  r3  r  r-  r6  r,  r  r   r   r/  r   __classcell__)r   s   @r   r2   r2   6   s   , !59"&6:LP>BAEJN+/*.&*&*6:'+"&$(;??R->B)-?C)-(,&*=F/3>G  )/"QM!M! 	M!
 3M!  M! 4M! JM! &<M! ?M! M! HM! )M! (M!  $M!  $!M!" 4#M!$ %%M!&  'M!( ")M!* 9+M!, =-M!. /M!0 1M!2 <3M!4 '5M!6 7M!8 =9M!: ';M!< =M!> ?M!@ &AM!B $CM!D ;EM!F -GM!H <IM!J KM!L MM!N 'OM!P QM!^' RURU 4RU &	RU
 $RUh12 ,0*.	#!G#! )#! (	#!
 
#!J'" 
# 
#** (* 5	* )) 5)


 /
_0B$
,$
@P$
	$
L

,




 	 	 	  	  .4	W 1 +	
 
) $W$ +$ 
	$L!,! 1! 	! 
!4+>,+> 1+> 	+>
+>Z
%(
%2<
%	L
%)161CK1
1#!#
#$+7O>
8+
8	(
8;; 
	;"&(0&( 
M&(P r   r2   )Kr  
__future__r   r   r^  rf  rp   r   r   collections.abcr   r   r   r   pathlibr   typingr	   r
   r   r   rn  gradio_client.documentationr   r"  r   gradio.blocksr   gradio.componentsr   r   r   r   r   r   r   r   r   r   r   gradio.components.chatbotr   r   r   r   r   $gradio.components.multimodal_textboxr    r!   gradio.contextr"   gradio.eventsr#   r$   r%   gradio.flaggingr&   gradio.helpersr'   r   r(   r)   gradio.i18nr*   gradio.layoutsr+   r,   r-   r.   gradio.routesr/   gradio.themesr0   Themer2   r   r   r   <module>r     s    #     	  I I  , ,  0        X - : : ) 6 /   8 8 ! - 
bF b br   