o
    沪g8                     @  s`  d dl 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 d dlmZ d dlm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' d dl(m)Z) d dl*m+Z+ d dl,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3 erd dl4m5Z5 G dd de6eZ7d$ddZ8eG dd  d Z9G d!d" d"Z:d#S )%    )annotations)	dataclass)Enum)TYPE_CHECKINGLiteralcast)runtime)get_dg_singleton_instance)
is_in_form)AtomicImageWidthBehaviorimage_to_url)check_widget_policies)Keycompute_and_register_element_idsave_for_app_testingto_key)StreamlitAPIException)Block)	ChatInput)StringTriggerValue)RootContainer)gather_metrics)get_script_run_ctx)
WidgetArgsWidgetCallbackWidgetKwargsregister_widget)is_emojivalidate_material_icon)DeltaGeneratorc                   @  s   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 r-   r-   [/var/www/html/chatdoc2/venv/lib/python3.10/site-packages/streamlit/elements/widgets/chat.pyr!   7   s
    r!   avatarstr | AtomicImage | None
delta_pathstrreturn7tuple[BlockProto.ChatMessage.AvatarType.ValueType, str]c              
   C  s   t jj}| du r|jdfS t| tr+| dd tD v r+|j| tjtjfv r(dfS dfS t| tr9t	| r9|j
| fS t| trJ| drJ|jt| fS z|jt| tjdd	d
|dfW S  tyj } ztd|d}~w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                 S     h | ]}|j qS r-   value.0itemr-   r-   r.   	<setcomp>T       z(_process_avatar_input.<locals>.<setcomp>r#   r"   z	:materialFRGBauto)widthclampchannelsoutput_formatimage_idz5Failed to load the provided avatar value as an image.)
BlockProtoChatMessage
AvatarTypeICON
isinstancer2   r!   r+   r*   r   EMOJI
startswithr   IMAGEr   r   ORIGINAL	Exceptionr   )r/   r1   rG   exr-   r-   r.   _process_avatar_input>   s>   


rP   c                   @  s$   e Zd Z	dddd	ZdddZdS )ChatInputSerder5   ui_valueStringTriggerValueProto | None	widget_idr2   r3   
str | Nonec                 C  s   |d u s	| dsd S |jS )Ndata)HasFieldrV   )selfrR   rT   r-   r-   r.   deserializeu   s   zChatInputSerde.deserializevStringTriggerValueProtoc                 C  s
   t |dS )N)rV   )r[   )rX   rZ   r-   r-   r.   	serialize}   s   
zChatInputSerde.serializeN)r5   )rR   rS   rT   r2   r3   rU   )rZ   rU   r3   r[   )r&   r'   r(   rY   r\   r-   r-   r-   r.   rQ   s   s    rQ   c                	   @  sX   e Zd Zedddd#d
dZed	d$dddddddd%dd Zed&d!d"ZdS )'	ChatMixinchat_messageN)r/   name1Literal['user', 'assistant', 'ai', 'human'] | strr/   7Literal['user', 'assistant'] | str | AtomicImage | Noner3   r    c                C  s   |du rt d|du r| dd tD v st|r| }t|| j \}}t }||_	||_
||_t }d|_|j| | jj|d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 : Anything supported by st.image (except list), str, or None
            The avatar shown next to the message.

            If ``avatar`` is ``None`` (default), the icon will be determined
            from ``name`` as follows:

            - If ``name`` is ``"user"`` or ``"human"``, the message will have a
              default user icon.

            - If ``name`` is ``"ai"`` or ``"assistant"``, the message will have
              a default bot icon.

            - For all other values of ``name``, the message will show the first
              letter of the name.

            In addition to the types supported by |st.image|_ (except list),
            the following strings are valid:

            - A single-character emoji. For example, you can set ``avatar="🧑‍💻"``
              or ``avatar="🦖"``. Emoji short codes are not supported.

            - An icon from the Material Symbols library (rounded style) in the
              format ``":material/icon_name:"`` where "icon_name" is the name
              of the icon in snake case.

              For example, ``icon=":material/thumb_up:"`` will display the
              Thumb Up icon. Find additional icons in the `Material Symbols               <https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_
              font library.

            .. |st.image| replace:: ``st.image``
            .. _st.image: https://docs.streamlit.io/develop/api-reference/media/st.image

        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                 S  r6   r-   r7   r9   r-   r-   r.   r<      r=   z)ChatMixin.chat_message.<locals>.<setcomp>T)block_proto)r   lowerr!   r   rP   dg_get_delta_path_strrE   rF   r_   r/   avatar_typeallow_emptyr^   CopyFrom_block)rX   r_   r/   rf   converted_avatarmessage_container_protorb   r-   r-   r.   r^      s$   Z
zChatMixin.chat_message
chat_inputYour messageF)key	max_charsdisabled	on_submitargskwargsplaceholderr2   rn   
Key | Nonero   
int | Nonerp   boolrq   WidgetCallback | Nonerr   WidgetArgs | Noners   WidgetKwargs | NonerU   c             
   C  s:  d}t |}t| j|||dd t }	td|d||d}
t r)t| jr)tdt	| jj
j}| jj
jtjkr=|s=d}nd	}t }|
|_t||_|durQ||_||_t }t|j||||j|j|	d
d}||_|jrx|jdurx|j|_d|_|	rt|	|
|j |dkrt j d| n| j d| |js|jS dS )ac	  Display a chat input widget.

        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. No two widgets may have 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. Otherwise, ``None``.

        Examples
        --------
        When ``st.chat_input`` is used in the main body of an app, it will be
        pinned to the bottom of the page.

        >>> 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

        The chat input can also be used inline by nesting it inside any layout
        container (container, columns, tabs, sidebar, etc) or fragment. Create
        chat interfaces embedded next to other content or have multiple
        chatbots!

        >>> import streamlit as st
        >>>
        >>> with st.sidebar:
        >>>     messages = st.container(height=300)
        >>>     if prompt := st.chat_input("Say something"):
        >>>         messages.chat_message("user").write(prompt)
        >>>         messages.chat_message("assistant").write(f"Echo: {prompt}")

        .. output ::
            https://doc-chat-input-inline.streamlit.app/
            height: 350px
        r5   F)default_valuewrites_allowedrl   N)user_keyform_idrt   ro   z1`st.chat_input()` can't be used in a `st.form()`.bottominlinestring_trigger_value)on_change_handlerrr   rs   deserializer
serializerctx
value_typeT)!r   r   rd   r   r   r   existsr
   r   set
_active_dg_ancestor_block_types_root_containerr   MAINChatInputProtoidr2   rt   ro   defaultrQ   r   rY   r\   rp   value_changedr8   	set_valuer   r	   	bottom_dg_enqueue)rX   rt   rn   ro   rp   rq   rr   rs   r   r   
element_idancestor_block_typespositionchat_input_protoserdewidget_stater-   r-   r.   rl      sr   Q

zChatMixin.chat_inputc                 C  s
   t d| S )zGet our DeltaGenerator.r    )r   )rX   r-   r-   r.   rd     s   
zChatMixin.dg)r_   r`   r/   ra   r3   r    )rm   )rt   r2   rn   ru   ro   rv   rp   rw   rq   rx   rr   ry   rs   rz   r3   rU   )r3   r    )r&   r'   r(   r   r^   rl   propertyrd   r-   r-   r-   r.   r]      s"    q $r]   N)r/   r0   r1   r2   r3   r4   );
__future__r   dataclassesr   enumr   typingr   r   r   	streamlitr   $streamlit.delta_generator_singletonsr	   !streamlit.elements.lib.form_utilsr
   "streamlit.elements.lib.image_utilsr   r   r   streamlit.elements.lib.policiesr   streamlit.elements.lib.utilsr   r   r   r   streamlit.errorsr   streamlit.proto.Block_pb2r   rE   streamlit.proto.ChatInput_pb2r   r   streamlit.proto.Common_pb2r   r[   !streamlit.proto.RootContainer_pb2r   streamlit.runtime.metrics_utilr   7streamlit.runtime.scriptrunner_utils.script_run_contextr   streamlit.runtime.stater   r   r   r   streamlit.string_utilr   r   streamlit.delta_generatorr    r2   r!   rP   rQ   r]   r-   r-   r-   r.   <module>   s4   
5