o
    eS                     @  s   d Z ddlmZ ddlZddlmZmZ ddlZddlm	Z
 ddlmZmZ ddlmZ ddlmZmZmZmZmZmZmZ dd	l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'm(Z( ed e G dd deZ)dS )z\
This file defines a useful high-level abstraction to build Gradio chatbots: ChatInterface.
    )annotationsN)AsyncGeneratorCallable)utils)documentset_documentation_group)Blocks)ButtonChatbotIOComponentMarkdownStateTextboxget_component_instance)
DependencyEventListenerMethod)create_examples)	AccordionColumnGroupRow)
ThemeClass)SyncToAsyncIteratorasync_iterationZchatinterfacec                      s   e Zd ZdZddddddddddddddddd	d
dQ fd(d)ZdRd,d-ZdSd2d3ZdRd4d5ZdTd8d9ZdUd=d>Z	dVd@dAZ
dWdCdDZdXdFdGZdYdHdIZdZdJdKZd[dLdMZd\dOdPZ  ZS )]ChatInterfacea  
    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=["hello", "hola", "merhaba"], title="Echo Bot")
        demo.launch()
    Demos: chatinterface_random_response, chatinterface_streaming_echo
    Guides: creating-a-chatbot-fast, sharing-your-app
    NzAdditional InputsZSubmitZStopu   🔄  Retryu   ↩️ Undou   🗑️  ClearT)chatbottextboxadditional_inputs additional_inputs_accordion_nameexamplescache_examplestitledescriptionthemecssanalytics_enabled
submit_btnstop_btn	retry_btnundo_btn	clear_btn	autofocusfnr   r   Chatbot | Noner   Textbox | Noner   2str | IOComponent | list[str | IOComponent] | Noner   strr   list[str] | Noner    bool | Noner!   
str | Noner"   r#   Theme | str | Noner$   r%   r&   str | None | Buttonr'   r(   r)   r*   r+   boolc                  s  t  j|d||p	d|
d || _t| jpt| j| _t| jp(t| j| _|| _	| j
r8|du r8d| _n|p;d| _g | _|rSt|tsJ|g}dd |D | _ng | _|| _|  |rhtd	| j d
 |	rnt|	 tdd |r}| | _ntdd| _t  t s |rd|_d|_| | _ntddddd|d| _|rt|tr|  nt|trt|dddd}n	tdt | |rt|trd|_!|  nt|trt|ddddd}n	tdt | | j"||g W d   n	1 sw   Y  W d   n	1 sw   Y  t V |||fD ]-}|rEt|tr/|  nt|tr<t|dd}n	tdt | | j#| qtddd| _$tddd | _%| j\| _&| _'| _(| _)| _*W d   n	1 ssw   Y  W d   n	1 sw   Y  |r| jr| j+}n| j,}t-|| jg| j | j|d!| _.t/d"d# | jD }| jr|rt0| jdd$ | jD ]}|j1s|  qW d   n	1 sw   Y  |rt23| j.j4 t5 | _6t5g | _7| 8  | 9  W d   dS 1 sw   Y  dS )%a  
        Parameters:
            fn: the function to wrap the chat interface around. Should accept two parameters: a string input message and list of two-element lists of the form [[user_message, bot_message], ...] representing the chat history, and return a string response. See the Chatbot documentation for more information on the chat history format.
            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 component to use for the chat interface, if you would like to customize the textbox properties. If not provided, a default gr.Textbox component will be created.
            additional_inputs: an instance or list of instances of gradio components (or their string shortcuts) to use as additional inputs to the chatbot. If components are not already rendered in a surrounding Blocks, then the components will be displayed under the chatbot, in an accordion.
            additional_inputs_accordion_name: the label of the accordion to use for additional inputs, only used if additional_inputs is provided.
            examples: sample inputs for the function; if provided, appear below the chatbot and can be clicked to populate the chatbot input.
            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.
            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: Theme to use, loaded from gradio.themes.
            css: custom css or path to custom css file to use with interface.
            analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.
            submit_btn: Text to display on the submit button. If None, no button will be displayed. If a Button object, that button will be used.
            stop_btn: Text to display on the stop button, which replaces the submit_btn when the submit_btn or retry_btn is clicked and response is streaming. Clicking on the stop_btn will halt the chatbot response. If set to None, stop button functionality does not appear in the chatbot. If a Button object, that button will be used as the stop button.
            retry_btn: Text to display on the retry button. If None, no button will be displayed. If a Button object, that button will be used.
            undo_btn: Text to display on the delete last button. If None, no button will be displayed. If a Button object, that button will be used.
            clear_btn: Text to display on the clear button. If None, no button will be displayed. If a Button object, that button will be used.
            autofocus: If True, autofocuses to the textbox when the page loads.
        Zchat_interfaceZGradio)r%   moder$   r!   r#   NTFc                 S  s   g | ]}t |d dqS )F)render)r   ).0i r;   ED:\Projects\ConvertPro\env\Lib\site-packages\gradio/chat_interface.py
<listcomp>y   s    z*ChatInterface.__init__.<locals>.<listcomp>z4<h1 style='text-align: center; margin-bottom: 1rem'>z</h1>panel)variantr
   )labelMessagezType a message...   )	container
show_labelr@   placeholderscaler+   primary      )r?   rF   	min_widthzCThe submit_btn parameter must be a gr.Button, string, or None, not stop)r?   visiblerF   rJ   zAThe stop_btn parameter must be a gr.Button, string, or None, not Z	secondaryzBAll the _btn parameters must be a gr.Button, string, or None, not zFake APIrL   Response)r@   rL   )r   ZinputsZoutputsr,   c                 s  s    | ]}|j  V  qd S N)is_rendered)r9   inpr;   r;   r<   	<genexpr>   s    
z)ChatInterface.__init__.<locals>.<genexpr>)open):super__init__r,   inspectiscoroutinefunctionisasyncgenfunctionis_asyncisgeneratorfunctionis_generatorr   Zspace_idr    Zbuttons
isinstancelistr   r   r   r!   r   r8   r   r
   r   r   rC   rD   r   r   r	   r0   
ValueErrortyperL   extendappendfake_api_btnZfake_response_textboxr&   r'   r(   r)   r*   _examples_stream_fn_examples_fnExamplesZexamples_handleranyr   rP   client_utilsZsynchronize_asynccacher   saved_inputchatbot_state_setup_events
_setup_api)selfr,   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   ZbtnZexamples_fnZany_unrendered_inputsZinput_component	__class__r;   r<   rU   6   s  +










/
	N


$zChatInterface.__init__returnNonec                 C  s  | j r| jn| j}| jj| j| jg| j| jgdddj| j| j| j	g| j
| j	gdddj|| j| j	g| j | j
| j	gdd}| | jj| | jr| jj| j| jg| j| jgdddj| j| j| j	g| j
| j	gdddj|| j| j	g| j | j
| j	gdd}| | jj| | jr| jj| j| j	g| j
| j| j	gdddj| j| j| j	g| j
| j	gdddj|| j| j	g| j | j
| j	gdd}| | jj| | jr| jj| j| j	g| j
| j| j	gdddjdd | jg| jgddd | jr| jjdd d | j
| j	| jgddd d S d S )NFapi_namequeuers   c                 S  s   | S rO   r;   )xr;   r;   r<   <lambda>J  s    z-ChatInterface._setup_events.<locals>.<lambda>c                   S  s
   g g d fS rO   r;   r;   r;   r;   r<   rw   S  s   
 )rt   rs   )r[   
_stream_fn
_submit_fnr   submit_clear_and_save_textboxri   then_display_inputrj   r   r   _setup_stop_eventsr&   clickr(   _delete_prev_fnr)   r*   )rm   Z	submit_fnZsubmit_eventZclick_eventZretry_eventr;   r;   r<   rk      s   











zChatInterface._setup_eventsevent_triggerr   event_to_cancelr   c                 C  s   | j rQ| jrS| jr)|dd d | j| j gddd |jdd d | j| j gddd n|dd d | j gddd |jdd d | j gddd | j jd d d |dd d S d S d S )	Nc                   S     t jddt jddfS )NFrM   Tr	   updater;   r;   r;   r<   rw   `      z2ChatInterface._setup_stop_events.<locals>.<lambda>Frr   c                   S  r   )NTrM   Fr   r;   r;   r;   r<   rw   g  r   c                   S     t jddS )NTrM   r   r;   r;   r;   r<   rw   o      c                   S  r   )NFrM   r   r;   r;   r;   r<   rw   v  r   )Zcancelsrs   )r'   r[   r&   r|   r   )rm   r   r   r;   r;   r<   r~   Z  sL   


z ChatInterface._setup_stop_eventsc                 C  s@   | j r| jn| j}| jj|| j| jg| j | j| jgdd d S )NZchatru   )r[   _api_stream_fn_api_submit_fnrb   r   r   rj   r   )rm   Zapi_fnr;   r;   r<   rl     s   

zChatInterface._setup_apimessagetuple[str, str]c                 C  s   d|fS N r;   )rm   r   r;   r;   r<   r{     s   z%ChatInterface._clear_and_save_textboxhistorylist[list[str | None]]5tuple[list[list[str | None]], list[list[str | None]]]c                 C  s   | |d g ||fS rO   )ra   )rm   r   r   r;   r;   r<   r}     s   zChatInterface._display_inputhistory_with_inputc                   sn   |d d }| j r| j||g|R  I d H }ntjj| j||g|R d| jiI d H }|||g ||fS NlimiterrY   r,   anyio	to_threadrun_syncr   ra   )rm   r   r   argsr   responser;   r;   r<   ry     s   zChatInterface._submit_fnr   c           	      G s   |d d }| j r| j||g|R  }ntjj| j||g|R d| jiI d H }t|| j}zt|I d H }|||gg }||fV  W n tyY   ||d gg }||fV  Y nw |2 z3 d H W }|||gg }||fV  q\6 d S r   	rY   r,   r   r   r   r   r   r   StopIteration)	rm   r   r   r   r   	generatorfirst_responser   r   r;   r;   r<   rx     s0   zChatInterface._stream_fn"tuple[str, list[list[str | None]]]c                   sb   | j r| j||g|R  I d H }ntjj| j||g|R d| jiI d H }|||g ||fS Nr   r   )rm   r   r   r   r   r;   r;   r<   r     s   zChatInterface._api_submit_fnc                 G s   | j r| j||g|R  }ntjj| j||g|R d| jiI d H }t|| j}zt|I d H }||||gg fV  W n tyO   d ||d gg fV  Y nw |2 z3 d H W }||||gg fV  qR6 d S r   r   )rm   r   r   r   r   r   r   r;   r;   r<   r     s(   zChatInterface._api_stream_fnc                   sV   | j r| j|g g|R  I d H }ntjj| j|g g|R d| jiI d H }||ggS r   )rY   r,   r   r   r   r   )rm   r   r   r   r;   r;   r<   rd     s   
zChatInterface._examples_fnc                 G sv   | j r| j|g g|R  }ntjj| j|g g|R d| jiI d H }t|| j}|2 z3 d H W }||ggV  q+6 d S r   )rY   r,   r   r   r   r   r   )rm   r   r   r   r   r;   r;   r<   rc     s   z!ChatInterface._examples_stream_fn:tuple[list[list[str | None]], str, list[list[str | None]]]c                 C  s6   z|  \}}W n ty   d}Y nw ||pd|fS r   )pop
IndexError)rm   r   r   _r;   r;   r<   r     s   zChatInterface._delete_prev_fn)$r,   r   r   r-   r   r.   r   r/   r   r0   r   r1   r    r2   r!   r3   r"   r3   r#   r4   r$   r3   r%   r2   r&   r5   r'   r5   r(   r5   r)   r5   r*   r5   r+   r6   )rp   rq   )r   r   r   r   rp   rq   )r   r0   rp   r   )r   r0   r   r   rp   r   )r   r0   r   r   rp   r   )r   r0   r   r   rp   r   )r   r0   r   r   rp   r   )r   r0   r   r   rp   r   )r   r0   rp   r   )r   r0   rp   r   )r   r   rp   r   )__name__
__module____qualname____doc__rU   rk   r~   rl   r{   r}   ry   rx   r   r   rd   rc   r   __classcell__r;   r;   rn   r<   r   "   sB     
A
d
*








	r   )*r   
__future__r   rV   typingr   r   r   Zgradio_clientr   rg   Zgradio_client.documentationr   r   Zgradio.blocksr   Zgradio.componentsr	   r
   r   r   r   r   r   Zgradio.eventsr   r   Zgradio.helpersr   re   Zgradio.layoutsr   r   r   r   Zgradio.themesr   ThemeZgradio.utilsr   r   r   r;   r;   r;   r<   <module>   s"    $	