
    &eb0                       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
 d dlmZ d dlmZ d dlmZmZmZ d dl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" d dl#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l0m1Z1m2Z2 erd dl3m4Z4  G d de5e          Z6d$dZ7dZ8e G d d                       Z9 G d! d"          Z:d#S )%    )annotations)	dataclass)Enum)TYPE_CHECKINGOptionalTuplecast)Literal)runtime)AtomicImageWidthBehaviourimage_to_url)check_callback_rulescheck_session_state_rules)StreamlitAPIException)Block)	ChatInput)StringTriggerValue)RootContainer)gather_metrics)get_script_run_ctx)
WidgetArgsWidgetCallbackWidgetKwargsregister_widget)compute_widget_id)is_emoji)Keyto_key)DeltaGeneratorc                      e Zd ZdZdZdZdZdS )PresetNamesuser	assistantaihumanN)__name__
__module____qualname__USER	ASSISTANTAIHUMAN     ?lib/python3.11/site-packages/streamlit/elements/widgets/chat.pyr"   r"   .   s"        DI	BEEEr/   r"   avatarstr | AtomicImage | None
delta_pathstrreturn7Tuple[BlockProto.ChatMessage.AvatarType.ValueType, str]c           	        t           j        j        }| 	|j        dfS t	          | t
                    r8| d t          D             v r%|j        | t          j        t          j        fv rdndfS t	          | t
                    rt          |           r	|j
        | fS 	 |j        t          | t          j        ddd|	          fS # t          $ r}t!          d
          |d}~ww xY w)a  Detects the avatar type and prepares the avatar data for the frontend.

    Parameters
    ----------
    avatar :
        The avatar that was provided by the user.
    delta_path : str
        The delta path is used as media ID when a local image is served via the media
        file manager.

    Returns
    -------
    Tuple[AvatarType, str]
        The detected avatar type and the prepared avatar data.
    N c                    h | ]	}|j         
S r.   value.0items     r0   	<setcomp>z(_process_avatar_input.<locals>.<setcomp>K   s    /S/S/St
/S/S/Sr/   r$   r#   FRGBauto)widthclampchannelsoutput_formatimage_idz5Failed to load the provided avatar value as an image.)
BlockProtoChatMessage
AvatarTypeICON
isinstancer4   r"   r,   r+   r   EMOJIIMAGEr   r   ORIGINAL	Exceptionr   )r1   r3   rI   exs       r0   _process_avatar_inputrQ   5   s!   $ '2J~""	FC	 	  V/S/S{/S/S/S%S%S O+.+*?@@@ K	
 	
 
FC	 	  Xf%5%5 ''	#\$-$#& & &    	 	 	'G 	s   %B> >
CCCzm`st.chat_input()` can't be used inside an `st.expander`, `st.form`, `st.tabs`, `st.columns`, or `st.sidebar`.c                  "    e Zd Z	 dddZddZdS )ChatInputSerder8   ui_value!Optional[StringTriggerValueProto]	widget_idr4   r5   
str | Nonec                B    ||                     d          sd S |j        S )Ndata)HasFieldrY   )selfrT   rV   s      r0   deserializezChatInputSerde.deserializej   s*     8#4#4V#<#<4}r/   vStringTriggerValueProtoc                "    t          |          S )N)rY   )r^   )r[   r]   s     r0   	serializezChatInputSerde.serializer   s    &A....r/   N)r8   )rT   rU   rV   r4   r5   rW   )r]   rW   r5   r^   )r'   r(   r)   r\   r`   r.   r/   r0   rS   rS   h   sH         MO    / / / / / /r/   rS   c            	          e Zd Z ed          ddd d
            Z ed          	 d!dddddddd"d            Zed#d            ZdS )$	ChatMixinchat_messageN)r1   name1Literal['user', 'assistant', 'ai', 'human'] | strr1   7Literal['user', 'assistant'] | str | AtomicImage | Noner5   'DeltaGenerator'c                  |t          d          |H|                                d t          D             v st          |          r|                                }t	          || j                                                  \  }}t          j                    }||_	        ||_
        ||_        t                      }d|_        |j                            |           | j                            |          S )u  Insert a chat message container.

        To add elements to the returned container, you can use ``with`` notation
        (preferred) or just call methods directly on the returned object. See the
        examples below.

        Parameters
        ----------
        name : "user", "assistant", "ai", "human", or str
            The name of the message author. Can be "human"/"user" or
            "ai"/"assistant" to enable preset styling and avatars.

            Currently, the name is not shown in the UI but is only set as an
            accessibility label. For accessibility reasons, you should not use
            an empty string.

        avatar : str, numpy.ndarray, or BytesIO
            The avatar shown next to the message. Can be one of:

            * A single emoji, e.g. "🧑‍💻", "🤖", "🦖". Shortcodes are not supported.

            * An image using one of the formats allowed for ``st.image``: path of a local
                image file; URL to fetch the image from; an SVG image; array of shape
                (w,h) or (w,h,1) for a monochrome image, (w,h,3) for a color image,
                or (w,h,4) for an RGBA image.

            If None (default), uses default icons if ``name`` is "user",
            "assistant", "ai", "human" or the first letter of the ``name`` value.

        Returns
        -------
        Container
            A single container that can hold multiple elements.

        Examples
        --------
        You can use ``with`` notation to insert any element into an expander

        >>> import streamlit as st
        >>> import numpy as np
        >>>
        >>> with st.chat_message("user"):
        ...     st.write("Hello 👋")
        ...     st.line_chart(np.random.randn(30, 3))

        .. output ::
            https://doc-chat-message-user.streamlit.app/
            height: 450px

        Or you can just call methods directly in the returned objects:

        >>> import streamlit as st
        >>> import numpy as np
        >>>
        >>> message = st.chat_message("assistant")
        >>> message.write("Hello human")
        >>> message.bar_chart(np.random.randn(30, 3))

        .. output ::
            https://doc-chat-message-user1.streamlit.app/
            height: 450px

        NzWThe author name is required for a chat message, please set it via the parameter `name`.c                    h | ]	}|j         
S r.   r:   r<   s     r0   r?   z)ChatMixin.chat_message.<locals>.<setcomp>   s    @@@DTZ@@@r/   T)block_proto)r   lowerr"   r   rQ   dg_get_delta_path_strrG   rH   rd   r1   avatar_typeallow_emptyrc   CopyFrom_block)r[   rd   r1   rn   converted_avatarmessage_container_protorj   s          r0   rc   zChatMixin.chat_messagew   s    L <'i   >JJLL@@K@@@@@HTNN@ ZZ\\F(=DG//11)
 )
%% #-"8":":'+$)9&.9+ ll"& ))*ABBBw~~+~666r/   
chat_inputYour messageF)key	max_charsdisabled	on_submitargskwargsplaceholderr4   rv   
Key | Nonerw   
int | Nonerx   boolry   WidgetCallback | Nonerz   WidgetArgs | Noner{   WidgetKwargs | NonerW   c               X   d}t          |          }t          | j        |           t          ||d           t	                      }	t          d|||||	r|	j        nd          }
t          j                    rbt          t          | j        j        j                            dk    s| j        j        j        t          j        k    rt!          t"                    t%                      }|
|_        t)          |          |_        |||_        ||_        t$          j        j        |_        t7                      }t9          d||||||j        |j        |		  	        }||_        |j         r|j!        |j!        |_!        d	|_"        | j        #                    d|           |j         s|j!        ndS )
a?  Display a chat input widget.

        .. warning::
            Chat input can only be used once per app page and inside the main area of the app.
            It cannot be used in the sidebar, columns, expanders, forms or tabs.
            We plan to support this in the future.

        Parameters
        ----------
        placeholder : str
            A placeholder text shown when the chat input is empty. Defaults to
            "Your message". For accessibility reasons, you should not use an
            empty string.

        key : str or int
            An optional string or integer to use as the unique key for the widget.
            If this is omitted, a key will be generated for the widget based on
            its content. Multiple widgets of the same type may not share the same key.

        max_chars : int or None
            The maximum number of characters that can be entered. If None
            (default), there will be no maximum.

        disabled : bool
            Whether the chat input should be disabled. Defaults to False.

        on_submit : callable
            An optional callback invoked when the chat input's value is submitted.

        args : tuple
            An optional tuple of args to pass to the callback.

        kwargs : dict
            An optional dict of kwargs to pass to the callback.

        Returns
        -------
        str or None
            The current (non-empty) value of the text input widget on the last
            run of the app, None otherwise.

        Examples
        --------
        >>> import streamlit as st
        >>>
        >>> prompt = st.chat_input("Say something")
        >>> if prompt:
        ...     st.write(f"User has sent the following prompt: {prompt}")

        .. output ::
            https://doc-chat-input.streamlit.app/
            height: 350px

        r8   F)default_valuerv   writes_allowedrt   N)user_keyrv   r|   rw   pager   )r   on_change_handlerrz   r{   deserializer
serializerctxT)$r   r   rl   r   r   r   page_script_hashr   existslenlist
_active_dg_parent_block_types_root_containerr   SIDEBARr    DISALLOWED_CONTAINERS_ERROR_TEXTChatInputProtoidr4   r|   rw   defaultPositionBOTTOMpositionrS   r   r\   r`   rx   value_changedr;   	set_value_enqueue)r[   r|   rv   rw   rx   ry   rz   r{   r   r   r   chat_input_protoserdewidget_states                 r0   rt   zChatMixin.chat_input   s   F SkkTWi000!SQVWWWW ""#),6%%$
 
 
 > 	ND+?@@AAAEE7%59NNN ,,LMMM)++ '*;'7'7$ )2&#* $2$;$B!  &'*

 

 

 %-!% 	.,*<*H%1%7")-&'7888)5)CM|!!Mr/   c                "    t          d|           S )zGet our DeltaGenerator.r    )r	   )r[   s    r0   rl   zChatMixin.dgU  s     $d+++r/   )rd   re   r1   rf   r5   rg   )ru   )r|   r4   rv   r}   rw   r~   rx   r   ry   r   rz   r   r{   r   r5   rW   )r5   rg   )r'   r(   r)   r   rc   rt   propertyrl   r.   r/   r0   rb   rb   v   s        ^N##
 KO	[7 [7 [7 [7 [7 $#[7z ^L!! *}N  $+/"&&*}N }N }N }N }N "!}N~ , , , X, , ,r/   rb   N)r1   r2   r3   r4   r5   r6   );
__future__r   dataclassesr   enumr   typingr   r   r   r	   typing_extensionsr
   	streamlitr   streamlit.elements.imager   r   r   streamlit.elements.utilsr   r   streamlit.errorsr   streamlit.proto.Block_pb2r   rG   streamlit.proto.ChatInput_pb2r   r   streamlit.proto.Common_pb2r   r^   !streamlit.proto.RootContainer_pb2r   streamlit.runtime.metrics_utilr   streamlit.runtime.scriptrunnerr   streamlit.runtime.stater   r   r   r   streamlit.runtime.state.commonr   streamlit.string_utilr   streamlit.type_utilr   r   streamlit.delta_generatorr    r4   r"   rQ   r   rS   rb   r.   r/   r0   <module>r      s   # " " " " " ! ! ! ! ! !       7 7 7 7 7 7 7 7 7 7 7 7 % % % % % %       N N N N N N N N N N T T T T T T T T 2 2 2 2 2 2 9 9 9 9 9 9 E E E E E E T T T T T T ; ; ; ; ; ; 9 9 9 9 9 9 = = = = = =            = < < < < < * * * * * * + + + + + + + + 9888888    #t   - - - -` $S   
/ 
/ 
/ 
/ 
/ 
/ 
/ 
/b, b, b, b, b, b, b, b, b, b,r/   