
    4i$                        d dl mZ d dl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 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  ee      Z	 d	 	 	 	 	 ddZddZddZddZe G d d             Z y)    )annotationsN)	dataclass)TYPE_CHECKINGAnycast)ARROW_REF_KEY)convert_anything_to_arrow_bytesis_dataframe_like)
get_logger)BidiComponent)	MixedData)AttributeDictionarycalc_md5)BidiComponentStatec                   |i }i }| j                         D ]=  \  }}t        |      r(	 t        |      }t        |      }|||<   t        |i||<   9|||<   ? |S # t
        $ r&}t        j                  d||       |||<   Y d}~ld}~ww xY w)a  Extract dataframe-like objects from a dictionary and replace them with
    placeholders.

    This function traverses the first level of a dictionary, detects any
    dataframe-like objects, stores their Arrow bytes representation in the
    `arrow_blobs` dictionary, and replaces them with JSON-serializable
    placeholder objects.

    Parameters
    ----------
    data
        The dictionary to process. Only the first level is checked for
        dataframe-like objects.
    arrow_blobs
        The dictionary to store the extracted Arrow bytes in, keyed by a unique
        reference ID.

    Returns
    -------
    dict[str, Any]
        A new dictionary with dataframe-like objects replaced by placeholders.
    NzAArrow serialization failed for key %r, keeping original value: %s)itemsr
   r	   r   r   	Exception_LOGGERdebug)dataarrow_blobsprocessed_datakeyvaluearrow_bytesref_ides           ~/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/streamlit/components/v2/bidi_component/serialization.py_extract_dataframes_from_dictr   "   s    2 Njjl (
UU#,=eD "+.&1F#'4f&=s# #(N3-(0   , W
 ',s#,s   &A	B"BBc                "   i }t        | t              rt        | |      }n| }|rmt               }	 t	        j
                  |      |_        |j                         D ]  \  }}||j                  |   _
         |j                  j                  |       y	 t	        j
                  |      |_        y# t        $ r& t	        j
                  t        |            |_        Y w xY w# t        $ r& t	        j
                  t        |            |_        Y yw xY w)a4  Serialize mixed data with automatic dataframe detection into a protobuf message.

    This function detects dataframe-like objects in the first level of a dictionary,
    extracts them into separate Arrow blobs, and populates a `MixedDataProto`
    protobuf message for efficient serialization.

    Parameters
    ----------
    data
        The data structure to serialize. If it is a dictionary, its first
        level will be scanned for dataframe-like objects.
    bidi_component_proto
        The protobuf message to populate with the serialized data.

    N)
isinstancedictr   MixedDataProtojsondumps	TypeErrorstrr   r   r   mixedCopyFrom)r   bidi_component_protor   r   mixed_protor   r   s          r   serialize_mixed_datar,   [   s      %'K $6t[I $&	?#zz.9K $/#4#4#6 	?FK3>K##F+0	? 	""++K8	H(,

>(B %  	?  $zz#n*=>K	?  	H )-

3~3F(G %	Hs#   B- C -,CC,DDc                j    | y	 t        j                  |       S # t         j                  $ r | cY S w xY w)a;  Deserialize a JSON string, returning the string itself if it's not valid JSON.

    Parameters
    ----------
    s
        The string to deserialize.

    Returns
    -------
    Any
        The deserialized JSON object, or the original string if parsing fails.
        Returns `None` if the input is `None`.

    N)r$   loadsJSONDecodeError)ss    r   handle_deserializer1      s9     	yzz!} s    22c                H    t        |       }|yt        |t              r|S |gS )a  Deserialize trigger aggregator payloads as a list.

    For bidirectional components, the frontend always sends a JSON array of payload
    objects. This deserializer normalizes older or singular payloads into a list
    while preserving ``None`` for cleared values.

    Parameters
    ----------
    s
        The JSON string to deserialize, hopefully representing a list of payloads.

    Returns
    -------
    list[Any] or None
        A list of payloads, or `None` if the input was `None`.

    N)r1   r!   list)r0   r   s     r   deserialize_trigger_listr4      s,    $ q!E}%7N    c                  0    e Zd ZU dZdZded<   ddZddZy)	BidiComponentSerdea  Serialization and deserialization logic for a bidirectional component.

    This class handles the conversion of component state between the frontend
    (JSON strings) and the backend (Python objects).

    The canonical shape is a flat mapping of state keys to values.

    Parameters
    ----------
    default
        A dictionary of default values to be applied to the state when
        deserializing, if the corresponding keys are not already present.

    Nzdict[str, Any] | Nonedefaultc                   t        |t              r|}n=t        |t              r+	 t        j                  |      }t        |t              r|ni }ni }| j                  ,| j                  j                         D ]  \  }}||vs|||<    t        dt        |            }|S # t        j
                  t        f$ r$}t        j                  d||       i }Y d}~d}~ww xY w)a_  Deserialize the component's state from a frontend value.

        Parameters
        ----------
        ui_value
            The value received from the frontend, which can be a JSON string,
            a dictionary, or `None`.

        Returns
        -------
        BidiComponentState
            The deserialized state as a flat mapping.

        z7Failed to deserialize component state from frontend: %s)exc_infoNr   )r!   r"   r'   r$   r.   r/   r&   r   warningr8   r   r   r   )selfui_valuedeserialized_valueparsedr   default_keydefault_valuestates           r   deserializezBidiComponentSerde.deserialize   s    * h%!)#&	(H-/9&$/GVR" "$ <<#.2ll.@.@.B D*]&886C&{3D %) "56H"I%
 ' (()4 (M   
 &("(s   )B   C9CCc                ,    t        j                  |      S )a  Serialize the component's state into a JSON string for the frontend.

        Parameters
        ----------
        value
            The component state to serialize.

        Returns
        -------
        str
            A JSON string representation of the value.

        )r$   r%   )r<   r   s     r   	serializezBidiComponentSerde.serialize  s     zz%  r5   )r=   zstr | dict[str, Any] | Nonereturnr   )r   r   rF   r'   )__name__
__module____qualname____doc__r8   __annotations__rC   rE    r5   r   r7   r7      s     &*G").`!r5   r7   )N)r   dict[str, Any]r   zdict[str, bytes] | NonerF   rM   )r   r   r*   BidiComponentProtorF   None)r0   
str | NonerF   r   )r0   rP   rF   zlist[Any] | None)!
__future__r   r$   dataclassesr   typingr   r   r   0streamlit.components.v2.bidi_component.constantsr   streamlit.dataframe_utilr	   r
   streamlit.loggerr   !streamlit.proto.BidiComponent_pb2r   rN   r   r#   streamlit.utilr   r   ,streamlit.components.v2.bidi_component.stater   rG   r   r   r,   r1   r4   r7   rL   r5   r   <module>rZ      s    #  ! + + J W ' Q I 8O
X
 BF6
6'>66r0Hf.4 P! P! P!r5   