
    AF[i6                       d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
mZmZ ddlmZ ddlmZmZmZmZ ddlm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l1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z9 ddl7m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@mAZAmBZB  e        G d de             ZCy)z\
This file defines a useful high-level abstraction to build Gradio chatbots: ChatInterface.
    )annotationsN)AsyncGeneratorCallable	Generator)wraps)AnyLiteralUnioncast)run_sync)document)utils)Blocks)JSONBrowserStateButtonChatbot	ComponentDatasetMarkdownMultimodalTextboxStateTextboxget_component_instance)ChatMessageExampleMessageMessageMessageDictNormalizedMessageDict)MultimodalPostprocessMultimodalValue)
DependencyEditData
SelectData)ChatCSVLogger)create_examples)special_argsupdate)I18nData)	AccordionColumnGroupRowc            "          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( fdZd Zd Z	 	 	 	 	 	 	 	 d)dZd Z	 	 d*	 	 	 	 	 	 	 d+dZ	d,dZ
e	 	 	 	 d-d       Z	 	 	 	 	 	 d.dZ	 	 	 	 d/dZd Z	 	 	 	 d0dZd Zd1dZ	 	 	 	 	 	 	 	 d2dZ	 	 	 	 d3dZ	 d4	 	 	 	 	 	 	 d5dZ	 	 	 	 	 	 d6dZ	 	 	 	 	 	 d7dZ	 	 	 	 	 	 d8dZ	 	 	 	 	 	 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! xZ"S )AChatInterfacea0  
    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, 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public)!
multimodal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flagging_modeflagging_optionsflagging_diranalytics_enabled	autofocus
autoscroll
submit_btnstop_btnconcurrency_limitdelete_cacheshow_progressfill_height
fill_widthapi_nameapi_descriptionapi_visibilitysave_history	validatorc       !   
     
   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'                  |	|
|      | _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        |!| _        tA        jB                  |      D #cg c]  }#tE        |#       c}#| _#        tA        jB                  |      | _$        |tK        d      dd| _&        npt        |tN              r
d|i| _&        nVt        |tP              r%|jS                  |jU                               | _&        n!tW        d	tY        jZ                  |             d| _.        | jF                  rj| j$                  ^| j$                  D ]O  }$t        |$t^              stW        d
      ta        |$      D ]  \  }%}&|&	|%dkD  sd| _.         n | j\                  sO n |tc        jd                  dd      }|dv r|| _3        ntW        d      || _4        || _5        t        |tl        tn        f      r|jq                          t        |tr              r|jq                          | 5  tu        g d| jv                         | _<        t{        d      | _>        t{               | _?        t{               | _@        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       |g }'t        |tl        tn        f      rl|dur ||j                  k7  r|'j                  d       |dur ||j                  k7  r|'j                  d       |dur ||j6                  k7  r|'j                  d       |'r7t        j                  ddj                  d |'D               dt        d       yy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   xY w)aK#  
        Parameters:
            fn: the function to wrap the chat interface around. 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"
            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.  Note that examples are cached separately from Gradio's queue() so certain features, such as gr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio's UI for cached examples.
            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.
            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.
            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: defines how the chat endpoint appears in the API docs. Can be a string or None. If set to a string, the endpoint will be exposed in the API docs with the given name. If None, the name of the function will be used.
            api_description: Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.
            api_visibility: Controls the visibility of the chat endpoint. Can be "public" (shown in API docs and callable), "private" (hidden from API docs and not callable), or "undocumented" (hidden from API docs but callable).
            save_history: if True, will save the chat history to the browser's local storage and display previous conversations in a side panel.
            validator: a function that takes in the inputs and can optionally return a gr.validate() object for each input.
        chat_interfaceGradio)rG   moderB   rO   rP   rM   Nz chat_interface.additional_inputsF)labelopenrZ   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)manualr]   zIInvalid value for `flagging_mode` parameter.Must be: 'manual' or 'never'._saved_conversations_)storage_key   )scale   rJ   rK   rH   z>You provided a custom `textbox` component, but also specified z, c              3  (   K   | ]
  }d | d   yw)`N ).0ps     ^/var/www/html/chatbot/moweb-chatbot/venv/lib/python3.12/site-packages/gradio/chat_interface.py	<genexpr>z)ChatInterface.__init__.<locals>.<genexpr>  s      Fa1QCq Fs   a    parameter(s) on `gr.ChatInterface`. These ChatInterface parameters will be ignored. To customize these settings, pass them directly to your `gr.Textbox` or `gr.MultimodalTextbox` component instead. For example: textbox=gr.Textbox(..., submit_btn='submit')   )
stacklevel)Osuper__init__rQ   rR   rS   r5   rL   
isinstancer/   fninspectiscoroutinefunctionisasyncgenfunctionis_asyncisgeneratorfunctionis_generatorrU   provided_chatbotr<   _setup_example_messagesexamples_messagesr?   r@   rA   r;   rO   rI   rH   rB   rC   rN   rT   r   none_or_singleton_to_listr   r8   r:   r)   "additional_inputs_accordion_paramsstrr*   recover_kwargs
get_config
ValueErrorbuiltinstype_additional_inputs_in_exampleslist	enumerateosgetenvrD   rE   rF   r   r   unrenderr   r   _idsaved_conversationsr   conversation_idsaved_inputnull_componentr+   _render_headerr-   _render_history_area_render_chatbot_area_render_footer_setup_eventsrJ   appendrK   warningswarnjoinUserWarning))selfrp   r5   r6   r7   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   iexampleidxexample_for_inputconflicting_params	__class__s)                                           ri   rn   zChatInterface.__init__G   sN   V 	/!#8#!% 	 	
 %-<K,$!2b-(eeDGDG33GG
 1''0 	 $77GG
 1''0 	 # 't 3 !%!=!=nm"
 &;",$ &$"
&*( 445FG"
 #1%"
 #("A"ABT"U&.!"DE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'')*  -	!0 !#'G->#?@T)jG<N<N.N&--l;4'H8H8H,H&--j9D(Y':K:K-K&--k:!Tyy F3E FFG HPQ
    " ]"
F2 22 2* *	! 	!s[   T AU)T7T+%T	T+-T78UT(#T++T40T77U	<UUc                    | j                   rt        d| j                    d       | j                  rt        | j                         y y )Nz4<h1 style='text-align: center; margin-bottom: 1rem'>z</h1>)rB   r   rC   r   s    ri   r   zChatInterface._render_header   s@    ::FtzzlRWX T%%&     c           	         t        dd      5  t        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)Nra   d   )rb   	min_widthzchat_interface.new_chatprimarymdzplus.svg)variantsizeiconFvisibletableindex)
components
show_labellayoutr   )	r+   r   r)   r   get_icon_pathnew_chat_buttonr   r   chat_history_datasetr   s    ri   r   z"ChatInterface._render_history_area(  sn    !s+ 	#)23!((4	$D  )0#E23 	)D%	 	 	s   AA''A0c                "   |rt        t        t        |d            | _        | j                  j                  r!| j
                  rt        j                  d       | j                  s| j
                  nd | j                  _        | j                  j                          nNt        t        d      d| j                  rdnd | j                  | j                  s| j
                  nd       | _        t               5  t               5  |rSd|_        t        |d      }t!        |t"        t$        f      s!t'        d	t)        j*                  |             || _        n?| j.                  rt$        nt"        } |dd
t        d      d| j0                  ||      | _        d d d        d d d        | j,                  j2                  | _        d| j,                  _        t7        dd      | _        t;        dd      | _        t?        | j                  j@                  r| j                  j@                  ng       | _!        t?        | j                  j@                  r | j                  j@                        | _"        y g       | _"        y # 1 sw Y   xY w# 1 sw Y   xY w)NT)renderzaThe ChatInterface already has examples set. The examples provided in the chatbot will be ignored.zchat_interface.chatbotra   i  )rZ   rb   heightrI   r<   FzAExpected a gr.Textbox or gr.MultimodalTextbox component, but got  z"chat_interface.message_placeholder   )r   rZ   placeholderrb   rH   rJ   rK   zFake APIr   Response)rZ   r   )#r   r   r   r6   r<   ry   r   r   r   _setup_examplesr)   rO   rI   r,   r-   r   ro   r   r   	TypeErrorr   r   r7   r5   rH   rK   original_stop_btnr   fake_api_btnr   api_responser   valuechatbot_statechatbot_value)r   r6   r7   rJ   rK   textbox_textbox_components          ri   r   z"ChatInterface._render_chatbot_area8  s#    )?PT)UVDL||$$)?)?w
 :: && LL!
 LL((*"78"..sD??  >> **
DL W 	 ).G&5gdKH%h:K0LM'_`h`m`mnv`w_xy  $,DL .2__)' & $5#( $,-Q$R"&..#-!)$DL	2 "&!6!6 %":u= e
 #9K9K4<<#5#5QST #9K9K4<<#5#5TQSTK 	 	s%   6JBI9J9J	>JJc                f   | j                   rt        | j                   | j                  g| j                  z   | j                  | j
                  r| j                  n| j                  | j                  t        t        d   | j                        | j                  | j                  d	      | _        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lazyF)	r<   inputsoutputsrp   r@   rA   r   
preprocesspreloadc              3  6   K   | ]  }|j                      y wN)is_rendered)rg   inps     ri   rj   z/ChatInterface._render_footer.<locals>.<genexpr>  s      $
$'$
s   rf   )r<   Examplesr7   r8   r6   rv   _examples_stream_fn_examples_fnr@   r   r	   rA   r   examples_handleranyr*   r{   r   r   )r   any_unrendered_inputsinput_components      ri   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''D0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   textr   filesdisplay_textr   _typezgradio.FileData)pathurl	orig_name	mime_typemeta)r   ro   r   r|   dictgetr5   r   )	r   r<   r=   r>   ry   r   r   example_messageexample_filess	            ri   rx   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|d   D ]  }|d   dk(  r
||d   z  } &|dz  } . t        |      dkD  r|d	d d
z   }|xs t        t        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contentr   r   u   📎 (   Nz...zchat_interface.conversation)lenr|   r)   )r   conversationrB   messager   s        ri   _generate_chat_titlez"ChatInterface._generate_chat_title  s    
 # 	)Gv&(&y1 )Gv&00()	) u:?#2J&EDH%BCDDr   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   )ro   r   r   itemsr   r   )objitemkvinners       ri   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   rf   )r   r   s    @ri   serialize_componentsz"ChatInterface.serialize_components  s    	 \""r   c                    | j                   r6| j                  |      }|	|||<   ||fS |xs g }|j                  d|       d}||fS Nr   )rT   r   insert)r   r   r   r   serialized_conversations        ri   _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      ri   _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      ri   _load_chat_historyz ChatInterface._load_chat_history  sB     */R **401
 	
s   1c                $    |t        ||         fS )N)r   )r   )r   r   r  s      ri   _load_conversationz ChatInterface._load_conversation  s!     #E*
 	
r   c                p    | j                   rt        |      fd       }|S t        |      fd       }|S )zWrap the submit_fn in a way that preserves the signature of the original function.
        That way, the API page shows the same parameters as the original function.
        c                B   K    | i |2 3 d {   }| 7 
6 y wr   rf   )argskwargschunk	submit_fns      ri   _wrapperz,ChatInterface._api_wrapper.<locals>._wrapper  s.     #,d#=f#=    %K #=s   	c                 0   K    | i | d {   S 7 wr   rf   )r  r	  r  s     ri   	__wrapperz-ChatInterface._api_wrapper.<locals>.__wrapper  s     &77777s   )rv   r   )r   rp   r  r  _ChatInterface__wrappers     `  ri   _api_wrapperzChatInterface._api_wrapper
  sK     2Y    O 2Y8 8 r   c                   ddl m} | j                  r| j                  n| j                  }| j                  | j                  |      }d|_        | j                  | 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}| j0                  j3                  | j4                  | j0                  g| j0                  | j                  gdt7        | j8                        | j8                        } |j;                  | j<                  | j                  | j                  g| j                  gdd      j:                  di |}	  |	j:                  di |j;                  d d | j0                  d      j:                  di | | j>                  jA                  || j0                  | j                  g| j                  z   | jB                  | j                  g| j                  z   | jD                  | jF                  t        t$        d   | jH                        t        t         t"        t$        d   d f   | j&                        d       d }
tK        | j                  tL              r| jN                  r| jP                  s| jR                  s| jT                  rp| j                  jW                  | jX                  d | j                  | j                  gd      }
| jR                  s |
j:                  di |}
 |
j:                  di | n4| j                  jW                  | jZ                  d | j0                  gd      }
 | j                  j]                  | j^                  | j                  g| j                  | j                  gdd      j;                  | j<                  | j                  | j                  g| j                  gdd      j;                  d | j0                  gd      j:                  di |}  |j:                  di |j;                  d | j0                  gd      j:                  di | |	|g}|
|ja                  |
       | jc                  | j                  j\                  | j                  jV                  g||         | j                  je                  | j^                  | j                  g| j                  | j0                  gdd      j:                  di |j:                  di |    | j                  jg                  | jh                  | j                  g| j                  | j                  gd      j:                  di |j:                  di |j:                  di |  | j                  jj                  di |j;                  | jl                  | j,                  | j.                  g| j,                  | j.                  gdd       | jn                  r   | j                  jq                  | jr                  | j                  g| j                  | j                  | j                  gd      jt                  di |jt                  di |j:                  di | | jv                  r8| jx                  jA                  d d | j,                  | j                  gdd      j;                  d | j                  g| j                  gdd        || jz                  | j.                  j|                  g| j~                  | j.                  g| j                  gdd        | j                  jA                  d d | j                  gddd      j;                  | j                  | j                  | j.                  g| j,                  | j                  gddd      j:                  di | | j                  dk7  rpt               }|j                  | j                         | j                  | j                  _G        | j                  j                  |j                  | j                          | j                  j}                  d | j                  g| j                  gd      j:                  di | y )Nr   )on
_submit_fnc                
    | | fS r   rf   xs    ri   <lambda>z-ChatInterface._setup_events.<locals>.<lambda>,  s
    QF r   undocumentedF)rp   r   r   rS   queuer2   )fullr3   hidden)rp   r   r   rS   rL   rN   )rS   r  rU   rS   r  c                     t        d d      S )NT)r   interactiver(   rf   r   ri   r  z-ChatInterface._setup_events.<locals>.<lambda>]  s    F48 r   )rS   )r4   private)rQ   rR   rS   rL   postprocessc                     t        dd      S )NFr   r  r   r  rf   r   ri   r  z-ChatInterface._setup_events.<locals>.<lambda>  s    5bA r   )r   rS   c                     t        d      S )NT)r  r  rf   r   ri   r  z-ChatInterface._setup_events.<locals>.<lambda>  s    Ft, r   )event_triggersevents_to_cancelafter_successc                 
    d g fS r   rf   rf   r   ri   r  z-ChatInterface._setup_events.<locals>.<lambda>  s
    r
 r   c                    | S r   rf   r  s    ri   r  z-ChatInterface._setup_events.<locals>.<lambda>  s    ! r   )triggersrp   r   r   rS   r  c                     g S r   rf   rf   r   ri   r  z-ChatInterface._setup_events.<locals>.<lambda>  s     r   r  )rS   r  rN   r]   c                    | S r   rf   r  s    ri   r  z-ChatInterface._setup_events.<locals>.<lambda>  s    a r   rf   )Jgradior  rv   
_stream_fnr  r  rp   __name__r6   r   r   r   r8   r   r:   r   r
   intr	   rL   rN   r   r   r   r7   submit_clear_and_save_textboxboolrU   then_append_message_to_historyr   clickr   rQ   rR   rS   ro   r   r<   r   r@   r?   example_selectexample_clickedexample_populatedretry_pop_last_user_messager   _setup_stop_eventsundooption_selectoption_clickedclearr   r;   edit_edit_messagesuccessrT   r   loadchanger  r   r  rD   r%   setuprF   rE   feedback_optionslikeflag)r   r  r  submit_wrappedapi_fnsynchronize_chat_state_kwargssubmit_fn_kwargssave_fn_kwargsuser_submitsubmit_eventexample_select_eventretry_eventr&  flagging_callbacks                 ri   r   zChatInterface._setup_events!  sV	   '+'8'8DOOdoo	**477I>".""477I6 #||n**D,>,>?,)
% !''););<t?U?UU++T\\:T=T=TT,!%c79-t34d6L6L" "34d6H6H
 ))$$""((
 ,,d.F.FG,

 ll))((\\N\\4++,)t~~&nn * 
{''++t||,\\N) ( 
 $
 
	:9:??8LL)	 	@ 	

 $	!
  	! 	\\4--.1G1GG 2 23d6M6MM]] 00(; <d>Q>QR"c79-t34d6L6L  	  	
  $t||W-77""d&@&@'+||'B'B((\\4#3#34#1	 (C ($ **+D+?+D+D+XGW+X()$))J,IJ'+||'B'B**\\N#1	 (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                  |j                  t        j                   fd      d  j                  gdd       |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)rJ   rK   r   r   r   s   ri   r  z2ChatInterface._setup_stop_events.<locals>.<lambda>  s    )$!33 r   r  Fr  c                 ,     d j                         S rV  rW  rX  s   ri   r  z2ChatInterface._setup_stop_events.<locals>.<lambda>!  s    -#(!%!7!7 r   c                       d      S rV  rf   )original_submit_btnr   s   ri   r  z2ChatInterface._setup_stop_events.<locals>.<lambda>.  s    -#6 r   )cancelsrS   )
r5   r   r   r7   rJ   rC  r   async_lambdar4  stop)r   r%  r&  r'  event_triggerevent_to_cancelr[  r   s   `     @@ri   r<  z ChatInterface._setup_stop_events
  s    26-g"ll55 \\N) 	 	
 , 	M"" -	  0 	O  ""
 - ! 
	 	$) 	 	
r   c                B     t        | j                        ddd      |fS )Nr   Fr#  )r   r7   )r   r   s     ri   r2  z%ChatInterface._clear_and_save_textbox?  s(     Dru"E
 	
r   c                v    | j                  ||      }t        j                  |      }|j                  |       |S r   )_message_as_message_dictcopydeepcopyextend)r   r   historyr   message_dictss        ri   r5  z(ChatInterface._append_message_to_historyK  s5     55gtD--(}%r   c                   g }t        |t              s|g}|D ]U  }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                  |       |g d}|j                  dg       D ]9  }t        |t              r|j                  d      }|d   j                  d|i       ; |d   r|d   j                  |d          |j                  |       X |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_factoryr   r   r   r   r   r   r   )ro   r   r   r   
model_dumpr   r   dataclassesasdictr   rj  r|   r   r   r   )r   r   r   rh  msgmultimodal_messager  s          ri   rc  z&ChatInterface._message_as_message_dictV  sU    '4(iG 	9C#w'$$S^^%56C-$$&&s9K9KL C#y!12$$ds%CD3%)s*:"F$$S).2r%B""- FA!!T*EE&M&y188&!EF v;&y188VE$$%78/	90 r   c                \  K   ||gt        |      z   }| j                  r | j                  |  d {   }n+t        | j                  g|d| j                  i d {   }| j
                  r|^}}nd }| j                  ||d      }| j                  ||d      }|r||g|S ||fS 7 v7 LwNlimiterr   	assistant)r   rt   rp   r   rs  r:   r5  )r   r   rg  r  r   responser:   s          ri   r  zChatInterface._submit_fn|  s      7#d4j0==$TWWf--H%dggMMMMH"",4)H)!%11'7FK11(G[QW9'999   .Ms"   /B,B(+B,B*AB,*B,c                 K   ||gt        |      z   }| j                  r | j                  | }nKt        | 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rr  )r   rt   rp   r   rs  r   SyncToAsyncIteratorr5  async_iterationr:   StopIteration)
r   r   rg  r  r   	generatorr:   first_responsehistory_ru  s
             ri   r.  zChatInterface._stream_fn  sm     7#d4j0==(I&twwNNNNI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%((=+===3 O D  	 -	 	>isl   AED'9ED+ (D));D+ $E&E*E+E.:E)D+ +D>;E=D>>EEEc                Z    |j                  d|j                  d       ||j                  fS )z
        When an option is clicked, the chat history is appended with the option value.
        The saved input value is also set to option value.
        r   rk  )r   r   )r   rg  options      ri   r?  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      ri   _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   )r5   r  r   )r   r   s     ri   r9  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   )ro   r   r   tupler   )r   rg  	edit_datas      ri   rB  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)	r5  r   r  r5   r@   r   load_from_cacher   root)r   r   rg  r   s       ri   r8  zChatInterface.example_clicked  s      11'--VL--g6#'??'--f8Mw++;;GMMJ1MRRG7"" s   B"B$c                r   g }| j                   rt        t        |      }|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        |      }d|dd|dg}|S )Nr   r   r   rk  r   rt  )r5   r   r   r   ro   r   r   r|   )r   r   ru  resultfiles        ri   _process_examplezChatInterface._process_example  s     ??>73GGR0 DdD)88F+Dv4'BCD  v'&/JKMM;8DE  3(GG4$:F r   c                  K   t        | j                  |g g|d       \  }}}}| j                  r | j                  |  d {   }n+t        | j                  g|d| j                  i d {   }| j                  ||      S 7 B7 wN)r   requestrs  )r'   rp   rt   r   rs  r  )r   r   r  r   _ru  s         ri   r   zChatInterface._examples_fn  s      'GGWb040$
1a ==$TWWf--H%dggMMMMH$$Wh77 .Ms$   A B	B+B	.B/B	B	c               h  K   t        | j                  |g g|d       \  }}}}| j                  r | j                  | }nKt        | j                  g|d| j                  i d {   }t        j                  || j                        }|2 3 d {   }| j                  ||       7 E7 6 y wr  )r'   rp   rt   r   rs  r   rw  r  )r   r   r  r   r  rz  ru  s          ri   r   z!ChatInterface._examples_stream_fn  s     
 'GGWb040$
1a ==(I&twwNNNNI11)T\\JI' 	; 	;('':: O	;is6   A$B2&B,'&B2B0B.B0B2.B00B2c                   |s|| j                   sdfS dg dfS 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 ]W  }t        |t              sJ |d   dk(  s|d	   }|D ]0  }|d
   dk(  r|j	                  |d           |d
   dk(  s)||d   z  }2 Y | j                   r||dn|}	|d|dz    }
|
|	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   ra   r   r   rt  r   Nr   r   r  r   )r5   r   ro   r   r   )r   rg  r   last_messageslast_user_messager   ro  r   r   return_messager|  s              ri   r;  z$ChatInterface._pop_last_user_message!  ss    dooBTTBQS;TTTL11fF+{:FA 1fF+{:1fF+v5FA 1fF+v5A(  	:Cc4(((6{f$i.# :DF|v-T&\2f/)T&\9)	:		:  '7" 	
 7QU#''r   )Drp   r   r5   r3  r6   Chatbot | Noner7   "Textbox | MultimodalTextbox | Noner8   z.str | Component | list[str | Component] | Noner9   zstr | Accordion | Noner:   z"Component | list[Component] | Noner;   r3  r<   5list[str] | list[MultimodalValue] | list[list] | Noner=   list[str] | Noner>   r  r?   r3  r@   bool | NonerA   zLiteral['eager', 'lazy'] | NonerB   zstr | I18nData | NonerC   
str | NonerD   z!Literal['never', 'manual'] | NonerE   z"list[str] | tuple[str, ...] | NonerF   r|   rG   r  rH   r3  rI   r3  rJ   str | bool | NonerK   r  rL   zint | None | Literal['default']rM   ztuple[int, int] | NonerN   z$Literal['full', 'minimal', 'hidden']rO   r3  rP   r3  rQ   r  rR   zstr | None | Literal[False]rS   z,Literal['public', 'private', 'undocumented']rT   r3  rU   zCallable | None)r6   r  r7   r  rJ   r  rK   r  )NN)r<   r  r=   r  r>   r  r   zlist[ExampleMessage])r   list[NormalizedMessageDict]r   r|   )r   r  r   r  )r   
int | Noner   r  r   !list[list[NormalizedMessageDict]])r   r  r   r  )r   r0  r  r  )r   None)r%  zlist[Callable]r&  zlist[Dependency]r'  r"   r   r  )r   str | MultimodalPostprocessr   z?tuple[Textbox | MultimodalTextbox, str | MultimodalPostprocess])r   )r   FMessageDict | Message | str | Component | MultimodalPostprocess | listrg  list[MessageDict]r   Literal['user', 'assistant']r   r  )r   r  r   r  r   r  )r   r  rg  r  r   r  )r   r  rg  r  r   zAsyncGenerator[tuple, None])rg  r  r~  r$   r   z5tuple[list[MessageDict], str | MultimodalPostprocess])r   r$   )rg  r  r  r#   r   zHtuple[list[MessageDict], list[MessageDict], str | MultimodalPostprocess])r   r$   r   zLGenerator[tuple[list[MessageDict], str | MultimodalPostprocess], None, None])r   ExampleMessage | strru  zMessageDict | str | None)r   r  r   r  )r   r|   r   r   )rg  r  r   z?tuple[list[NormalizedMessageDict], str | MultimodalPostprocess])#r/  
__module____qualname____doc__rn   r   r   r   r   rx   r   staticmethodr   r   r   r  r  r  r   r<  r2  r5  rc  r  r.  r?  r  r9  rB  r8  r  r   r   r;  __classcell__)r   s   @ri   r/   r/   3   s   , !"&6:LP>BAEJN+/*.&*&*6:'+"&;??R-)-(,&*=F/3>G  #7;GO"%)IWW 	W
  W 4W JW &<W ?W W HW )W (W  $W $W  4!W" %#W$  %W& 9'W( =)W* +W, '-W. /W0 1W2 &3W4 $5W6 ;7W8 -9W: <;W< =W> ?W@ AWB 5CWD EEWF GWH #IWr' EUEU 4EU &	EU
 $EUN14 ,0*.	#!G#! )#! (	#!
 
#!JE$ #1#	$# #** 2* ?	* )) ?)




 9

.g0R3
&3
 +3
 "	3

 
3
j

,




  .4		W	 #	 +		
 
	$W$ +$ 
%	$L!,! #!
 
!*&>,&> #&>

&>P%(%2<%	>%)1(15=1
1#!#	U# +7O*
8+
8	
8;; 
	;"#(,#( 
I#(r   r/   )Dr  
__future__r   r   rd  rm  rq   r   r   collections.abcr   r   r   	functoolsr   typingr   r	   r
   r   anyio.to_threadr   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.eventsr"   r#   r$   gradio.flaggingr%   gradio.helpersr&   r   r'   r(   gradio.i18nr)   gradio.layoutsr*   r+   r,   r-   r/   rf   r   ri   <module>r     s    #     	  ? ?  , , $ 0        X : : ) 6 /   8 8 
P(F P( P(r   