L il8ddlmZddlmZmZmZddlmZddlm Z ddl m Z m Z m Z mZmZddlmZmZddlmZddlmZmZdd lmZdd lmZmZdd lmZmZm Z m!Z!dd l"m#Z#dd l$m%Z%m&Z&m'Z'm(Z(m)Z)ddl*m+Z+ddl,m-Z.ddl/m0Z1ddl2m3Z4ddl2m5Z6ddl7m8Z8ddl9m:Z:ddl;mZ>ddl?m@Z@mAZAmBZBmCZCddlDmEZEddlFmGZGmHZHddlImJZJmKZKe rddlLmMZMeGddeeNe fZ3GddeNe ZO d'd ZP d(d!ZQeGd"d#ZRGd$d%ZSy&))) annotations)IteratorMutableMappingSequence) dataclass)Enum) TYPE_CHECKINGAnyLiteralcastoverload)configruntime)get_dg_singleton_instance)enforce_filename_restrictionnormalize_upload_file_type) is_in_form) AtomicImage image_to_url) LayoutConfigWidthWidthWithoutContentvalidate_width)check_widget_policies)Keycompute_and_register_element_id&get_chat_input_accept_file_proto_valuesave_for_app_testingto_key)StreamlitAPIException)Block) ChatInput)ChatInputValue)FileUploaderState) RootContainer) WidthConfig)gather_metrics)get_script_run_ctx) WidgetArgsWidgetCallback WidgetKwargsregister_widget)get_session_state) DeletedFile UploadedFile)is_emojivalidate_material_icon)DeltaGeneratorcReZdZUded<ded<d dZd dZddZddZdd Zdd Z y )r#strtextlist[UploadedFile]filesc*tt|SN)lenvarsselfs e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/streamlit/elements/widgets/chat.py__len__zChatInputValue.__len__Ns4:c*tt|Sr9)iterr;r<s r>__iter__zChatInputValue.__iter__QsDJr@cT t||S#t$rtd|dwxYwNz Invalid key: )getattrAttributeErrorKeyError)r=items r> __getitem__zChatInputValue.__getitem__Ts7 =4& & =]4&12 < =s 'ct|||yr9)setattr)r=keyvalues r> __setitem__zChatInputValue.__setitem__Zsc5!r@cV t||y#t$rtd|dwxYwrE)delattrrGrH)r=rMs r> __delitem__zChatInputValue.__delitem__]s4 < D#  <]3%01t ; to_dictzChatInputValue.to_dictcs Dzr@N)returnint)rUz Iterator[str])rIr4rUzstr | list[UploadedFile])rMr4rNr rUNone)rMr4rUrW)rUz#dict[str, str | list[UploadedFile]]) __name__ __module__ __qualname____annotations__r?rCrJrOrRrTr@r>r#r#Is+ I  = "< r@r#ceZdZdZdZdZdZy) PresetNamesuser assistantaihumanN)rXrYrZUSER ASSISTANTAIHUMANr\r@r>r^r^gs DI B Er@r^c rtjj}||jdfSt |t rS|t Dchc]}|jc}vr3|j|t jt jfvrdfSdfSt |t rt|r|j|fSt |t r(|jdr|jt|fS |jt|t!ddd d | fScc}w#t"$r}t%d |d}~wwxYw) aDetects 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. Nr`r_z :materialcontentwidthFRGBauto) layout_configclampchannels output_formatimage_idz5Failed to load the provided avatar value as an image.) BlockProto ChatMessage AvatarTypeICON isinstancer4r^rNrerdr0EMOJI startswithr1IMAGErr Exceptionr )avatar delta_pathrurIexs r>_process_avatar_inputrns:$''22J ~""&#6[-QTdjj-Q#Q OOknnk.C.CDD     &#8F#3''&#6#4#4[#A 6v >>>  &Y7  "   !.R0 # C  sD0&D D6% D11D6cT|gSt}|gS|j}t|dk(rgS|jj |j |Dcgc]}|j c}}|Dcic]}|j |}}g}|D]}|j|j }|!t||j}|j|t|jds_|jj|j |j |Scc}wcc}w)Nr) session_idfile_ids remove_file)rfile_id) r(uploaded_file_infor:uploaded_file_mgr get_filesrrgetr/ file_urlsappendhasattrr) files_valuectxrffile_recs_list file_recscollected_filesmaybe_file_rec uploaded_files r>_pop_upload_filesrs$  C { $77 !# **44>>%78!))85N (66!A6I6*,O  "qyy1  %(EM  " "= 1s,,m<%%11"~~II2  '97s D 2D%cBeZdZUdZded<dZded< d dZd dZy) ChatInputSerdeFbool accept_filesNzSequence[str] | None allowed_typesc<||jdsy|js |jSt|j}|D]@}|j st |tr!t|j|j Bt|j|S)Ndata)r5r7) HasFieldrrrfile_uploader_staterrwr.rnamer#)r=ui_valueuploaded_filesfiles r> deserializezChatInputSerde.deserializes  8#4#4V#<  == *8+G+GH" LD!!*T;*G,TYY8J8JK L   r@ct|S)N)r)ChatInputValueProto)r=vs r> serializezChatInputSerde.serializes "**r@)rzChatInputValueProto | NonerUstr | ChatInputValue | None)r str | NonerUr)rXrYrZrr[rrrr\r@r>rrs1L$*.M'. 2 $ "+r@rc ^eZdZedddd ddZe ddddddddddd ddZe dddddddddd  dd Zed  ddddddddddd dd Zedd Zy) ChatMixin chat_messageNstretch)r|rkc| td|I|jtDchc]}|jc}vs t |r|j}t ||j j\}}t|dtj}||_ ||_ ||_ t}t|t r||_n|dk(rd|_nd|_t} d| _| j*j-|| j.j-||j j1| Scc}w)ubInsert 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. .. note:: To follow best design practices and maintain a good appearance on all screen sizes, don't nest chat message containers. 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 `_ font library. .. |st.image| replace:: ``st.image`` .. _st.image: https://docs.streamlit.io/develop/api-reference/media/st.image width : "stretch", "content", or int The width of the chat message container. This can be one of the following: - ``"stretch"`` (default): The width of the container matches the width of the parent container. - ``"content"``: The width of the container matches the width of its content, but doesn't exceed the width of the parent container. - An integer specifying the width in pixels: The container has a fixed width. If the specified width is greater than the width of the parent container, the width of the container matches the width of the parent container. 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 zWThe author name is required for a chat message, please set it via the parameter `name`.T) allow_contentri) block_proto)r lowerr^rNr0rdg_get_delta_path_strrrsrtrr| avatar_typer&rwrV pixel_width use_content use_stretch allow_emptyrCopyFrom width_config_block) r=rr|rkrIrconverted_avatarmessage_container_protorrs r>rzChatMixin.chat_messages/V <'i  > JJLK@DTZZ@ @HTNZZ\F(= DGG//1) % % uD1","8"8":'+$)9&.9+#} eS !',L $ i '+L $'+L $ l "&   ))*AB  )),7ww~~+~66;AsEF) rM max_chars accept_file file_typedisabled on_submitargskwargsrkc yr9r\ r= placeholderrMrrrrrrrrks r> chat_inputzChatMixin.chat_inputssr@)rMrrrrrrrkc yr9r\rs r>rzChatMixin.chat_inputs!$r@rc 8t|}t|j||dd|dvr tdt } t d|hd|j|||||  } |r t |}tjr t|jr td t|jjj} |jjjtjk(r| sd }nd }t!}| |_t%||_|||_d |_t-||_||ng|j0ddt3j4d |_t9|dv|}t;|j"||| |j<|j>| d}tA| tC| }||_"|jFrF|jH:|jH|_$d|_%tM}|||vr|jO|d| rtQ| | |jH|d k(r'tSjTjWd||n|jjWd|||jFs |jHSdS)a}Display a chat input widget. Parameters ---------- placeholder : str A placeholder text shown when the chat input is empty. This 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 this is ``None`` (default), there will be no maximum. accept_file : bool, "multiple", or "directory" Whether the chat input should accept files. This can be one of the following values: - ``False`` (default): No files are accepted and the user can only submit a message. - ``True``: The user can add a single file to their submission. - ``"multiple"``: The user can add multiple files to their submission. - ``"directory"``: The user can add multiple files to their submission by selecting a directory. If ``file_type`` is set, only files matching those type(s) will be uploaded. By default, uploaded files are limited to 200 MB each. You can configure this using the ``server.maxUploadSize`` config option. For more information on how to set config options, see |config.toml|_. .. |config.toml| replace:: ``config.toml`` .. _config.toml: https://docs.streamlit.io/develop/api-reference/configuration/config.toml file_type : str, Sequence[str], or None The allowed file extension(s) for uploaded files. This can be one of the following types: - ``None`` (default): All file extensions are allowed. - A string: A single file extension is allowed. For example, to only accept CSV files, use ``"csv"``. - A sequence of strings: Multiple file extensions are allowed. For example, to only accept JPG/JPEG and PNG files, use ``["jpg", "jpeg", "png"]``. .. note:: This is a best-effort check, but doesn't provide a security guarantee against users uploading files of other types or type extensions. The correct handling of uploaded files is part of the app developer's responsibility. disabled : bool Whether the chat input should be disabled. This defaults to ``False``. on_submit : callable An optional callback invoked when the chat input's value is submitted. args : list or tuple An optional list or tuple of args to pass to the callback. kwargs : dict An optional dict of kwargs to pass to the callback. width : "stretch" or int The width of the chat input widget. This can be one of the following: - ``"stretch"`` (default): The width of the widget matches the width of the parent container. - An integer specifying the width in pixels: The widget has a fixed width. If the specified width is greater than the width of the parent container, the width of the widget matches the width of the parent container. Returns ------- None, str, or dict-like The user's submission. This is one of the following types: - ``None``: If the user didn't submit a message or file in the last rerun, the widget returns ``None``. - A string: When the widget is not configured to accept files and the user submitted a message in the last rerun, the widget returns the user's message as a string. - A dict-like object: When the widget is configured to accept files and the user submitted a message and/or file(s) in the last rerun, the widget returns a dict-like object with two attributes, ``text`` and ``files``. When the widget is configured to accept files and the user submits something in the last rerun, you can access the user's submission with key or attribute notation from the dict-like object. This is shown in Example 3 below. The ``text`` attribute holds a string, which is the user's message. This is an empty string if the user only submitted one or more files. The ``files`` attribute holds a list of UploadedFile objects. The list is empty if the user only submitted a message. Unlike ``st.file_uploader``, this attribute always returns a list, even when the widget is configured to accept only one file at a time. The UploadedFile class is a subclass of BytesIO, and therefore is "file-like". This means you can pass an instance of it anywhere a file is expected. Examples -------- **Example 1: Pin the chat input widget to the bottom of your app** 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 **Example 2: Use the chat input widget inline** 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 **Example 3: Let users upload files** When you configure your chat input widget to allow file attachments, it will return a dict-like object when the user sends a submission. You can access the user's message through the ``text`` attribute of this dictionary. You can access a list of the user's submitted file(s) through the ``files`` attribute. Similar to ``st.session_state``, you can use key or attribute notation. >>> import streamlit as st >>> >>> prompt = st.chat_input( >>> "Say something and/or attach an image", >>> accept_file=True, >>> file_type=["jpg", "jpeg", "png"], >>> ) >>> if prompt and prompt.text: >>> st.markdown(prompt.text) >>> if prompt and prompt["files"]: >>> st.image(prompt["files"][0]) .. output :: https://doc-chat-input-file-uploader.streamlit.app/ height: 350px **Example 4: Programmatically set the text via session state** You can use ``st.session_state`` to set the text of the chat input widget. >>> import streamlit as st >>> >>> if st.button("Set Value"): >>> st.session_state.chat_input = "Hello, world!" >>> st.chat_input(key="chat_input") >>> st.write("Chat input value:", st.session_state.chat_input) .. output :: https://doc-chat-input-session-state.streamlit.app/ height: 350px NT) default_valuewrites_allowed>FTmultiple directoryzKThe `accept_file` parameter must be a boolean or 'multiple' or 'directory'.r>rrr)user_keykey_as_main_identityrrrrrrkz1`st.chat_input()` can't be used in a `st.form()`.bottominlinerhzserver.maxUploadSize>Trr)rrchat_input_value)on_change_handlerrr deserializer serializerr value_typerj)rn),rrrr r(rrrexistsrset _active_dg_ancestor_block_types_root_containerr%MAINChatInputProtoidr4rrdefaultrrrr get_optionmax_upload_size_mbrr,rrrrr value_changedrN set_valuer-reset_state_valuerr bottom_dg_enqueue)r=rrMrrrrrrrrkr element_idancestor_block_typespositionchat_input_protoserde widget_statern session_states r>rzChatMixin.chat_inputsXSk GG     D D'] !"4 "Kww## $ 29=I >>  477 3'C  #477#5#5#K#KL GG   . .-2D2D D(HH)+('*;'7$  )2  &$& 'M ( $6?5J PR""1%.4.?.?@V.W+$(GG# '   '**)   u$51 $,!  % %,*<*<*H&2%7%7  ")-  &-/M3-#7//T:  j,2D2D E x  & ' 1 1 : :.m ;  GG  .m  *6)C)C|!!MMr@ctd|S)zGet our DeltaGenerator.r2)r r<s r>rz ChatMixin.dgs$d++r@)rz1Literal['user', 'assistant', 'ai', 'human'] | strr|z7Literal['user', 'assistant'] | str | AtomicImage | NonerkrrUr2)z Your message)rr4rM Key | Noner int | NonerzLiteral[False]rstr | Sequence[str] | NonerrrWidgetCallback | NonerWidgetArgs | NonerWidgetKwargs | NonerkrrUr)rr4rMrrrrz&Literal[True, 'multiple', 'directory']rrrrrrrrrrrkrrUzChatInputValue | None)rr4rMrrrrz'bool | Literal['multiple', 'directory']rrrrrrrrrrrkrrUr)rUr2) rXrYrZr'rr rpropertyrr\r@r>rrsyN# KO M7?M7H M7  M7  M7$M7^*  $&+04+/"&&*%.      $ .  )   $ #    * $ $04+/"&&*%. $ $ $  $ < $. $ $) $  $$ $# $  $ $L!*HN $?D04+/"&&*%.HNHN HN  HN = HN.HNHN)HN HN$HN#HN %HN"HNT ,,r@rN)r|zstr | AtomicImage | Noner}r4rUz7tuple[BlockProto.ChatMessage.AvatarType.ValueType, str])rzFileUploaderStateProto | NonerUr6)T __future__rcollections.abcrrr dataclassesrenumrtypingr r r r r streamlitrr$streamlit.delta_generator_singletonsr*streamlit.elements.lib.file_uploader_utilsrr!streamlit.elements.lib.form_utilsr"streamlit.elements.lib.image_utilsrr#streamlit.elements.lib.layout_utilsrrrrstreamlit.elements.lib.policiesrstreamlit.elements.lib.utilsrrrrrstreamlit.errorsr streamlit.proto.Block_pb2r!rsstreamlit.proto.ChatInput_pb2r"rstreamlit.proto.Common_pb2r#rr$FileUploaderStateProto!streamlit.proto.RootContainer_pb2r%streamlit.proto.WidthConfig_pb2r&streamlit.runtime.metrics_utilr'7streamlit.runtime.scriptrunner_utils.script_run_contextr(streamlit.runtime.stater)r*r+r,+streamlit.runtime.state.session_state_proxyr-'streamlit.runtime.uploaded_file_managerr.r/streamlit.string_utilr0r1streamlit.delta_generatorr2r4r^rrrrr\r@r>rs#>>!&J9H B39ELR;79V JMB8 ^CH- :#t1 $1251<1h#.##L ++ +2,,r@