L iYzUddlmZddlZddlZddlZddlmZmZmZddl m Z m Z m Z m Z mZmZmZddlmZddlmZmZmZmZddlmZmZddlmZdd lmZdd lm Z m!Z!erdd l"m#Z#ejHejJejLejNejPfZ)d e*d <Gdde+eZ,GddZ-y)) annotationsN)ChainMapUserDictUserList)AsyncGeneratorCallable Generator ItemsViewIterableKeysView ValuesView)StringIO) TYPE_CHECKINGAnyFinalcast)dataframe_util type_util)StreamlitAPIException)gather_metrics)is_mem_address_strmax_char_sequence)DeltaGeneratorzFinal[tuple[type[Any], ...]] HELP_TYPESc eZdZy)StreamingOutputN)__name__ __module__ __qualname__^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/streamlit/elements/write.pyrr;sr!rcpeZdZeddd d dZedddd dZed d Zy) WriteMixin write_streamN)cursorc  t|tstj|rt dt |d|xsd}d d t d fd }tj|stj|r|}tj|rtj|} t||D]0}tj|r\ t!|j"dk(s|j"dj$d}n'|j"dj$j&xsd}tj*|d r |j&xsd}t|trA|sd } s|j,j/ d } |z j1 |rdn|zt3|r||||j5| j7|3| syt! dk(rt dtr dS S#t$r}t dt |d|d}~wwxYw#t($r}t d |d}~wwxYw#t($r}t d |d}~wwxYw)aStream a generator, iterable, or stream-like sequence to the app. ``st.write_stream`` iterates through the given sequences and writes all chunks to the app. String chunks will be written using a typewriter effect. Other data types will be written using ``st.write``. Parameters ---------- stream : Callable, Generator, Iterable, OpenAI Stream, or LangChain Stream The generator or iterable to stream. If you pass an async generator, Streamlit will internally convert it to a sync generator. If the generator depends on a cached object with async references, this can raise an error. .. note:: To use additional LLM libraries, you can create a wrapper to manually define a generator function and include custom output parsing. cursor : str or None A string to append to text as it's being written. If this is ``None`` (default), no cursor is shown. Otherwise, the string is rendered as Markdown and appears as a cursor at the end of the streamed text. For example, you can use an emoji, emoji shortcode, or Material icon. The first line of the cursor string can contain GitHub-flavored Markdown of the following types: Bold, Italics, Strikethroughs, Inline Code, Links, and Images. Images display like icons, with a max height equal to the font height. If you pass a multiline string, additional lines display after the text with the full Markdown rendering capabilities of ``st.markdown``. See the ``body`` parameter of |st.markdown|_ for additional, supported Markdown directives. .. |st.markdown| replace:: ``st.markdown`` .. _st.markdown: https://docs.streamlit.io/develop/api-reference/text/st.markdown Returns ------- str or list The full response. If the streamed output only contains text, this is a string. Otherwise, this is a list of all the streamed objects. The return value is fully compatible as input for ``st.write``. Example ------- You can pass an OpenAI stream as shown in our tutorial, `Build a \ basic LLM chat app `_. Alternatively, you can pass a generic generator function as input: >>> import time >>> import numpy as np >>> import pandas as pd >>> import streamlit as st >>> >>> _LOREM_IPSUM = \"\"\" >>> Lorem ipsum dolor sit amet, **consectetur adipiscing** elit, sed do eiusmod tempor >>> incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis >>> nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. >>> \"\"\" >>> >>> >>> def stream_data(): >>> for word in _LOREM_IPSUM.split(" "): >>> yield word + " " >>> time.sleep(0.02) >>> >>> yield pd.DataFrame( >>> np.random.randn(5, 10), >>> columns=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"], >>> ) >>> >>> for word in _LOREM_IPSUM.split(" "): >>> yield word + " " >>> time.sleep(0.02) >>> >>> >>> if st.button("Stream data"): >>> st.write_stream(stream_data) .. output:: https://doc-write-stream-data.streamlit.app/ height: 550px zI`st.write_stream` expects a generator or stream-like object as input not z3. Please use `st.write` instead for this data type.Nc^r*r'jjddyyy)z#Write the full response to the app.Nr()markdownappend)stream_containerstreamed_responsewritten_contentsr"flush_stream_responsez6WriteMixin.write_stream..flush_stream_responses= !%5 ))*;<&&'89#' $&! &6 r!zThe provided input (type: z^) cannot be iterated. Please make sure that it is a generator, generator function or iterable.ra8Failed to parse the OpenAI ChatCompletionChunk. The most likely cause is a change of the chunk object structure due to a recent OpenAI update. You might be able to fix this by downgrading the OpenAI library or upgrading Streamlit. Also, please report this issue to: https://github.com/streamlit/streamlit/issues.z)langchain_core.messages.ai.AIMessageChunka9Failed to parse the LangChain AIMessageChunk. The most likely cause is a change of the chunk object structure due to a recent LangChain update. You might be able to fix this by downgrading the OpenAI library or upgrading Streamlit. Also, please report this issue to: https://github.com/streamlit/streamlit/issues.FTreturnNone) isinstancestrris_dataframe_likertyperinspectisgeneratorfunctionisasyncgenfunction isasyncgenrasync_generator_to_synciter TypeErroris_openai_chunklenchoicesdeltacontentAttributeErroris_typedgemptyr*callablewriter+) selfstreamr& cursor_strr/excchunkerr first_textr,r-r.s @@@r"r%zWriteMixin.write_stream@sN fc "n&F&Fv&N'F|n%""  \r 26!#%4%6 '  & &v .'2L2LV2TXF   f %66v>F  L4 .E((/5==)Q.%--2B2H2H2P!# % a 0 6 6 > > D"  (ST !MM/RE%%" ''+ww}}$!%J!U*! ))%zzJ%%'%' 5!&&u-i4 .l   1 $OA4F)L"1% %Q ',T&\N;[[  $&/f  &/f  sI9 H, AII3, I5II I0 I++I03 J < JJ rIFunsafe_allow_htmlc t|dk(r4t|dtr!jj |dyg jj st|dkDr t dd fd }|D]t}t|tr j|&t|tr<||D]/}t|r||j|1rt|tr#|jj|tj|r#|jj|t!j"|r$|jj%|tj&|r$|jj)|Otj*|dr$|jj-|tj.|r$|jj1|tj*|dr$|jj3|tj4|r$|jj7|5tj8|r$|jj;|ntj<|r$|jj?|tj@|rIdd l!m"}||jG|}jj7|jIt|tJtLtNtPtRjTtVtXtZt\t^t`f s?tjb|s*tjd|stjf|r$|jji|tjj|r$|jjm|t|tnr2|jj |jq0tsjt|sUtsjv|s@tsjx|s+tsjz|stj*|d r|j}|t|t~stj|r$|jj|tsj|r.|jjtd |@rAtj|d r+jj|jtj|d stj|dr$|jj%|t|}t|r$|jj| d|vr9tdt|ddz} d| z} j| d|d| Jt|ddz} d| z} j| || w|y)aDisplays arguments in the app. This is the Swiss Army knife of Streamlit commands: it does different things depending on what you throw at it. Unlike other Streamlit commands, ``st.write()`` has some unique properties: - You can pass in multiple arguments, all of which will be displayed. - Its behavior depends on the input type(s). Parameters ---------- *args : any One or many objects to display in the app. .. list-table:: Each type of argument is handled as follows: :header-rows: 1 * - Type - Handling * - ``str`` - Uses ``st.markdown()``. * - dataframe-like, ``dict``, or ``list`` - Uses ``st.dataframe()``. * - ``Exception`` - Uses ``st.exception()``. * - function, module, or class - Uses ``st.help()``. * - ``DeltaGenerator`` - Uses ``st.help()``. * - Altair chart - Uses ``st.altair_chart()``. * - Bokeh figure - Uses ``st.bokeh_chart()``. * - Graphviz graph - Uses ``st.graphviz_chart()``. * - Keras model - Converts model and uses ``st.graphviz_chart()``. * - Matplotlib figure - Uses ``st.pyplot()``. * - Plotly figure - Uses ``st.plotly_chart()``. * - ``PIL.Image`` - Uses ``st.image()``. * - generator or stream (like ``openai.Stream``) - Uses ``st.write_stream()``. * - SymPy expression - Uses ``st.latex()``. * - An object with ``._repr_html()`` - Uses ``st.html()``. * - Database cursor - Displays DB API 2.0 cursor results in a table. * - Any - Displays ``str(arg)`` as inline code. unsafe_allow_html : bool Whether to render HTML within ``*args``. This only applies to strings or objects falling back on ``_repr_html_()``. If this is ``False`` (default), any HTML tags found in ``body`` will be escaped and therefore treated as raw text. If this is ``True``, any HTML expressions within ``body`` will be rendered. Adding custom HTML to your app impacts safety, styling, and maintainability. .. note:: If you only want to insert HTML or CSS without Markdown text, we recommend using ``st.html`` instead. Returns ------- None Examples -------- Its basic use case is to draw Markdown-formatted text, whenever the input is a string: >>> import streamlit as st >>> >>> st.write("Hello, *World!* :sunglasses:") .. output:: https://doc-write1.streamlit.app/ height: 150px As mentioned earlier, ``st.write()`` also accepts other data formats, such as numbers, data frames, styled data frames, and assorted objects: >>> import streamlit as st >>> import pandas as pd >>> >>> st.write(1234) >>> st.write( ... pd.DataFrame( ... { ... "first column": [1, 2, 3, 4], ... "second column": [10, 20, 30, 40], ... } ... ) ... ) .. output:: https://doc-write2.streamlit.app/ height: 350px Finally, you can pass in multiple arguments to do things like: >>> import streamlit as st >>> >>> st.write("1 + 1 = ", 2) >>> st.write("Below is a DataFrame:", data_frame, "Above is a dataframe.") .. output:: https://doc-write3.streamlit.app/ height: 410px Oh, one more thing: ``st.write`` accepts chart objects too! For example: >>> import altair as alt >>> import pandas as pd >>> import streamlit as st >>> from numpy.random import default_rng as rng >>> >>> df = pd.DataFrame(rng(0).standard_normal((200, 3)), columns=["a", "b", "c"]) >>> chart = ( ... alt.Chart(df) ... .mark_circle() ... .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"]) ... ) >>> >>> st.write(chart) .. output:: https://doc-vega-lite-chart.streamlit.app/ height: 300px r0rrQNzCannot replace a single element with multiple elements. The `write()` method only supports multiple elements when inserting elements rather than replacing. That is, only when called as `st.write()` or `st.sidebar.write()`.crDdj}jj}|j|gddyy)N rQ)joinrFrGr*) text_contenttext_containerrJ string_bufferrRs r" flush_bufferz&WriteMixin.write..flush_buffersO"xx 6 "&'' &7($& a r!zmatplotlib.figure.Figurezbokeh.plotting.figure.Figure) vis_utilsz openai.Streamr7 _repr_html_ to_pandas __dataframe__ `r1)Jr@r4r5rFr* _is_top_levelrr+rrHrI Exception exceptionris_delta_generatorhelprr6 dataframeis_altair_chart altair_chartrEpyplotis_plotly_chart plotly_chart bokeh_chartis_graphviz_chartgraphviz_chartis_sympy_expressionlatexis_pillow_imageimageis_keras_modeltensorflow.python.keras.utilsr[ model_to_dot to_stringdictlistmap enumeratetypesMappingProxyTyperrrr r r is_custom_dict is_namedtupleis_pydantic_modeljson is_pydeck pydeck_chartrgetvaluer8 isgeneratorr9r:r;r%r dataclasses is_dataclassisclassrhas_callable_attrhtmlr\rmaxr) rJrRargsrZargitemr[dotstringified_argbacktick_countbacktick_wrapperrYs `` @r"rIzWriteMixin.writes0Z t9>ja#6 GG  T!W8I  J #% ww$$TQ'G  &B C#s#$$S)C1ND~$ 4;L M N C+!!#&--c2 S!11#6!!#&**3/$$S)""3(BCs#**3/$$S)""3(FG##C(,,S1&&s+..s3 c"**3/ c"))#.,,S1&&s}}7!..   ! "  ++C0**3/..s3 S!$$S)$$S)C*  0##C(..s3--c2%%c*$$S/:!!#&C, 0H0H0M S!% T&#./"y'B'B3 'V S__./,,[,,S/B!!#&"%c(%o6 NGGLL%_,&),=os,SVW,W%XN'*^';$!((+,B.?rBRAST&7%Lq%PN'*^';$!((+,_,=>N=OPAB H r!ctd|S)zGet our DeltaGenerator.r)r)rJs r"rFz WriteMixin.dgGs$d++r!)rKzXCallable[..., Any] | Generator[Any, Any, Any] | Iterable[Any] | AsyncGenerator[Any, Any]r&z str | Noner2zlist[Any] | str)rrrRboolr2r3)r2r)rrrrr%rIpropertyrFr r!r"r$r$?suN#"P#PP P$PdG:?qqf ,,r!r$). __future__rrr8r| collectionsrrrcollections.abcrrr r r r r iortypingrrrr streamlitrrstreamlit.errorsrstreamlit.runtime.metrics_utilrstreamlit.string_utilrrstreamlit.delta_generatorrBuiltinFunctionTypeBuiltinMethodType FunctionType MethodType ModuleTyper__annotations__ryrr$r r!r"rs# 44029 8      , ( d3i K,K,r!