
    gL                    "   U d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	m
Z
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  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, erddl-m.Z. ddl/Z/ddl0m1Z2 ddl3m4Z4 ddl5m6Z6  e        ed   Z7de8d<   ee7e9e7   e:e;e7f   ddf   Z<de8d<   e
d   Z=de8d<   h dZ>de8d <    G d! d"ed#$      Z? G d% d&ed#$      Z@e G d' d(             ZA	 	 	 	 d,d)ZB G d* d+      ZCy)-z$Streamlit support for Plotly charts.    )annotationsN)	dataclass)TYPE_CHECKINGAnyFinalLiteral	TypedDictUnioncastoverload)	TypeAlias)	type_util)show_deprecation_warning)AttributeDictionary)current_form_id)check_widget_policies) configure_streamlit_plotly_theme)Keycompute_and_register_element_idto_key)StreamlitAPIException)PlotlyChart)gather_metrics)get_script_run_ctx)WidgetCallbackregister_widget)Iterable)
BaseFigure)DeltaGenerator)z	go.Figurezgo.Datar   _AtomicFigureOrDatar   matplotlib.figure.FigureFigureOrData)lassopointsboxSelectionMode>   r%   r#   r$   zFinal[set[SelectionMode]]_SELECTION_MODESc                  :    e Zd ZU dZded<   ded<   ded<   ded<   y)	PlotlySelectionStateat	  
    The schema for the Plotly chart selection state.

    The selection state is stored in a dictionary-like object that supports both
    key and attribute notation. Selection states cannot be programmatically
    changed or set through Session State.

    Attributes
    ----------
    points : list[dict[str, Any]]
        The selected data points in the chart, including the data points
        selected by the box and lasso mode. The data includes the values
        associated to each point and a point index used to populate
        ``point_indices``. If additional information has been assigned to your
        points, such as size or legend group, this is also included.

    point_indices : list[int]
        The numerical indices of all selected data points in the chart. The
        details of each identified point are included in ``points``.

    box : list[dict[str, Any]]
        The metadata related to the box selection. This includes the
        coordinates of the selected area.

    lasso : list[dict[str, Any]]
        The metadata related to the lasso selection. This includes the
        coordinates of the selected area.

    Example
    -------
    When working with more complicated graphs, the ``points`` attribute
    displays additional information. Try selecting points in the following
    example:

    >>> import streamlit as st
    >>> import plotly.express as px
    >>>
    >>> df = px.data.iris()
    >>> fig = px.scatter(
    ...     df,
    ...     x="sepal_width",
    ...     y="sepal_length",
    ...     color="species",
    ...     size="petal_length",
    ...     hover_data=["petal_width"],
    ... )
    >>>
    >>> event = st.plotly_chart(fig, key="iris", on_select="rerun")
    >>>
    >>> event.selection

    .. output::
        https://doc-chart-events-plotly-selection-state.streamlit.app
        height: 600px

    This is an example of the selection state when selecting a single point:

    >>> {
    >>>   "points": [
    >>>     {
    >>>       "curve_number": 2,
    >>>       "point_number": 9,
    >>>       "point_index": 9,
    >>>       "x": 3.6,
    >>>       "y": 7.2,
    >>>       "customdata": [
    >>>         2.5
    >>>       ],
    >>>       "marker_size": 6.1,
    >>>       "legendgroup": "virginica"
    >>>     }
    >>>   ],
    >>>   "point_indices": [
    >>>     9
    >>>   ],
    >>>   "box": [],
    >>>   "lasso": []
    >>> }

    zlist[dict[str, Any]]r$   z	list[int]point_indicesr%   r#   N__name__
__module____qualname____doc____annotations__     T/var/www/openai/venv/lib/python3.12/site-packages/streamlit/elements/plotly_chart.pyr)   r)   P   s#    Ob ! 	r2   r)   F)totalc                      e Zd ZU dZded<   y)PlotlyStatea  
    The schema for the Plotly chart event state.

    The event state is stored in a dictionary-like object that supports both
    key and attribute notation. Event states cannot be programmatically
    changed or set through Session State.

    Only selection events are supported at this time.

    Attributes
    ----------
    selection : dict
        The state of the ``on_select`` event. This attribute returns a
        dictionary-like object that supports both key and attribute notation.
        The attributes are described by the ``PlotlySelectionState`` dictionary
        schema.

    Example
    -------
    Try selecting points by any of the three available methods (direct click,
    box, or lasso). The current selection state is available through Session
    State or as the output of the chart function.

    >>> import streamlit as st
    >>> import plotly.express as px
    >>>
    >>> df = px.data.iris()  # iris is a pandas DataFrame
    >>> fig = px.scatter(df, x="sepal_width", y="sepal_length")
    >>>
    >>> event = st.plotly_chart(fig, key="iris", on_select="rerun")
    >>>
    >>> event

    .. output::
        https://doc-chart-events-plotly-state.streamlit.app
        height: 600px

    r)   	selectionNr+   r1   r2   r3   r6   r6      s    %N $#r2   r6   c                  "    e Zd ZdZdddZddZy)PlotlyChartSelectionSerdeziPlotlyChartSelectionSerde is used to serialize and deserialize the Plotly Chart
    selection state.
    c                    dg g g g di}||n+t        t        t        t        j                  |                  }d|vr|}t        t        t        |            S )Nr7   )r$   r*   r%   r#   )r   r6   r   jsonloads)selfui_value	widget_idempty_selection_stateselection_states        r3   deserializez%PlotlyChartSelectionSerde.deserialize   sk    !#	.
  "k#6tzz(7K#LM 	 o-3OK!4_!EFFr2   c                8    t        j                  |t              S )N)default)r;   dumpsstr)r=   rA   s     r3   	serializez#PlotlyChartSelectionSerde.serialize   s    zz/377r2   N) )r>   z
str | Noner?   rF   returnr6   )rA   r6   rI   rF   )r,   r-   r.   r/   rB   rG   r1   r2   r3   r9   r9      s    G*8r2   r9   c                   t        | t              r| h}nt        |       }|j                  t              st        d|  dt               g }|D ]  } | dk(  r*|j                  t        j                  j                         2| dk(  r*|j                  t        j                  j                         a| dk(  sg|j                  t        j                  j                          t        |      S )z2Parse and check the user provided selection modes.zInvalid selection mode: z. Valid options are: r$   r#   r%   )
isinstancerF   setissubsetr'   r   appendPlotlyChartProtor&   POINTSLASSOBOX)selection_modeselection_mode_setparsed_selection_modess      r3   parse_selection_moderV      s     .#&,- !0&&'78#&~&6 7""2!35
 	

  ,X%"))*:*H*H*O*OPw&"))*:*H*H*N*NOu$"))*:*H*H*L*LM - %&&r2   c                      e Zd Ze	 ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Ze	 dddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z ed	      	 dddd
dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Zedd       Zy)PlotlyMixin	streamlitN)r$   r%   r#   )themekeyrS   c                    y Nr1   r=   figure_or_datause_container_widthrZ   r[   	on_selectrS   kwargss           r3   plotly_chartzPlotlyMixin.plotly_chart  s     r2   rerun)rZ   r[   ra   rS   c                    y r]   r1   r^   s           r3   rc   zPlotlyMixin.plotly_chart   s     r2   rc   ignorec               d   ddl }ddl}d|v rt        d       |dvrt        d| d      |dvrt	        |      st        d	| d
      t        |      }|dk7  }	|	r8t	        |      }
t        | j                  ||
rt        t        |      nddd|
       t        j                  |d      r|j                  j                  |      }n|j                  j                  |d      }t               }||_        |xs d|_        t%        | j                        |_        t)        |j+                  di             }|j-                  d|j+                  dd             |j-                  d|j+                  dd             |j.                  j1                  |d      |_        t5        j6                  |      |_        t;               }t=        d||j&                  |j2                  |j8                  ||	||	      |_        |	r|j@                  jC                  tE        |             tG               }tI        |j>                  t	        |      r|nd|jJ                  |jL                  |d      }| j                  jO                  d|       t        tP        |jR                        S | j                  jO                  d|      S )a  Display an interactive Plotly chart.

        `Plotly <https://plot.ly/python>`_ is a charting library for Python.
        The arguments to this function closely follow the ones for Plotly's
        ``plot()`` function.

        To show Plotly charts in Streamlit, call ``st.plotly_chart`` wherever
        you would call Plotly's ``py.plot`` or ``py.iplot``.

        .. Important::
            You must install ``plotly`` to use this command. Your app's
            performance may be enhanced by installing ``orjson`` as well.

        Parameters
        ----------
        figure_or_data : plotly.graph_objs.Figure, plotly.graph_objs.Data,            or dict/list of plotly.graph_objs.Figure/Data

            The Plotly ``Figure`` or ``Data`` object to render. See
            https://plot.ly/python/ for examples of graph descriptions.

        use_container_width : bool
            Whether to override the figure's native width with the width of
            the parent container. If ``use_container_width`` is ``True`` (default),
            Streamlit sets the width of the figure to match the width of the parent
            container. If ``use_container_width`` is ``False``, Streamlit sets the
            width of the chart to fit its contents according to the plotting library,
            up to the width of the parent container.

        theme : "streamlit" or None
            The theme of the chart. If ``theme`` is ``"streamlit"`` (default),
            Streamlit uses its own design default. If ``theme`` is ``None``,
            Streamlit falls back to the default behavior of the library.

        key : str
            An optional string to use for giving this element a stable
            identity. If ``key`` is ``None`` (default), this element's identity
            will be determined based on the values of the other parameters.

            Additionally, if selections are activated and ``key`` is provided,
            Streamlit will register the key in Session State to store the
            selection state. The selection state is read-only.

        on_select : "ignore" or "rerun" or callable
            How the figure should respond to user selection events. This
            controls whether or not the figure behaves like an input widget.
            ``on_select`` can be one of the following:

            - ``"ignore"`` (default): Streamlit will not react to any selection
              events in the chart. The figure will not behave like an input
              widget.

            - ``"rerun"``: Streamlit will rerun the app when the user selects
              data in the chart. In this case, ``st.plotly_chart`` will return
              the selection data as a dictionary.

            - A ``callable``: Streamlit will rerun the app and execute the
              ``callable`` as a callback function before the rest of the app.
              In this case, ``st.plotly_chart`` will return the selection data
              as a dictionary.

        selection_mode : "points", "box", "lasso" or an Iterable of these
            The selection mode of the chart. This can be one of the following:

            - ``"points"``: The chart will allow selections based on individual
              data points.
            - ``"box"``: The chart will allow selections based on rectangular
              areas.
            - ``"lasso"``: The chart will allow selections based on freeform
              areas.
            - An ``Iterable`` of the above options: The chart will allow
              selections based on the modes specified.

            All selections modes are activated by default.

        **kwargs
            Any argument accepted by Plotly's ``plot()`` function.

        Returns
        -------
        element or dict
            If ``on_select`` is ``"ignore"`` (default), this command returns an
            internal placeholder for the chart element. Otherwise, this command
            returns a dictionary-like object that supports both key and
            attribute notation. The attributes are described by the
            ``PlotlyState`` dictionary schema.

        Example
        -------
        The example below comes straight from the examples at
        https://plot.ly/python. Note that ``plotly.figure_factory`` requires
        ``scipy`` to run.

        >>> import streamlit as st
        >>> import numpy as np
        >>> import plotly.figure_factory as ff
        >>>
        >>> # Add histogram data
        >>> x1 = np.random.randn(200) - 2
        >>> x2 = np.random.randn(200)
        >>> x3 = np.random.randn(200) + 2
        >>>
        >>> # Group data together
        >>> hist_data = [x1, x2, x3]
        >>>
        >>> group_labels = ['Group 1', 'Group 2', 'Group 3']
        >>>
        >>> # Create distplot with custom bin_size
        >>> fig = ff.create_distplot(
        ...         hist_data, group_labels, bin_size=[.1, .25, .5])
        >>>
        >>> # Plot!
        >>> st.plotly_chart(fig)

        .. output::
           https://doc-plotly-chart.streamlit.app/
           height: 550px

        r   NsharingzThe `sharing` parameter has been deprecated and will be removed in a future release. Plotly charts will always be rendered using Streamlit's offline mode.)rY   NzYou set theme="us   " while Streamlit charts only support theme=”streamlit” or theme=None to fallback to the default library theme.)rf   rd   zYou have passed zH to `on_select`. But only 'ignore', 'rerun', or a callable is supported.rf   F)	on_changedefault_valuewrites_allowedenable_check_callback_rulesr!   T)validate_figurerH   configshowLink	show_linklinkText	link_text)validaterc   )user_keyform_idplotly_specplotly_configrS   is_selection_activatedrZ   r`   string_value)on_change_handlerdeserializer
serializerctx
value_type)*	plotly.ioplotly.toolsr   r   callabler   r   dgr   r   r   is_typetoolsmpl_to_plotly!return_figure_from_figure_or_datarO   r`   rZ   r   ru   dictget
setdefaultioto_jsonspecr;   rE   rn   r   r   idrS   extendrV   r9   r   rB   rG   _enqueuer6   value)r=   r_   r`   rZ   r[   ra   rS   rb   plotlyrx   is_callbackfigureplotly_chart_protorn   r}   serdewidget_states                    r3   rc   zPlotlyMixin.plotly_chart1  s   N 	 $, ++'!% )! !  //8K'"9+ .7 7 
 Sk!*h!6! #9-K!=H$~y9d"$,7 ^-GH\\//?F\\CC D F ./1D.#(;B %4TWW%="fjj2./*fjje&DE*fjje&DE"())"3"3FU"3"K$(JJv$6! "
 !@&..*//,33)#9 3
!
 "--44$^4 ./E*"%%/7	/B)".. ??)L GG^-?@\%7%78877##N4FGGr2   c                    t        d|       S )zGet our DeltaGenerator.r   )r   )r=   s    r3   r   zPlotlyMixin.dg  s     $d++r2   )T)r_   r"   r`   boolrZ   Literal['streamlit'] | Noner[   
Key | Nonera   zLiteral['ignore']rS   'SelectionMode | Iterable[SelectionMode]rb   r   rI   r   )r_   r"   r`   r   rZ   r   r[   r   ra   z!Literal['rerun'] | WidgetCallbackrS   r   rb   r   rI   r6   )r_   r"   r`   r   rZ   r   r[   r   ra   z+Literal['rerun', 'ignore'] | WidgetCallbackrS   r   rb   r   rI   zDeltaGenerator | PlotlyState)rI   r   )r,   r-   r.   r   rc   r   propertyr   r1   r2   r3   rX   rX     s    %)
 .9C
$ "
 +  % @  
    %)
 .97>C
$ "
 +  5 @  
   N# %)kH
 .9AIC
kH$kH "kH
 +kH kH ?kH @kH kH 
&kH $kHZ , ,r2   rX   )rS   r   rI   z-set[PlotlyChartProto.SelectionMode.ValueType])Dr/   
__future__r   r;   dataclassesr   typingr   r   r   r   r	   r
   r   r   typing_extensionsr   rY   r   streamlit.deprecation_utilr   "streamlit.elements.lib.event_utilsr   !streamlit.elements.lib.form_utilsr   streamlit.elements.lib.policiesr   -streamlit.elements.lib.streamlit_plotly_themer   streamlit.elements.lib.utilsr   r   r   streamlit.errorsr   streamlit.proto.PlotlyChart_pb2r   rO   streamlit.runtime.metrics_utilr   7streamlit.runtime.scriptrunner_utils.script_run_contextr   streamlit.runtime.stater   r   collections.abcr   
matplotlibplotly.graph_objs
graph_objsgoplotly.basedatatypesr   streamlit.delta_generatorr   r    r0   listr   rF   r"   r&   r'   r)   r6   r9   rV   rX   r1   r2   r3   <module>r      s6   + "  !	 	 	 (  ? B = A V U 2 K 9 V C("/8 ! "!&" Y   	 	!	!" 	i 	 ##;<y <.H + HU 9E U p($)5 ($V 8 8 8<';'2'8T, T,r2   