o
    ,&]i$                     @  s   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rJd dlmZ eeZ	d"d#ddZd$ddZd%ddZd&ddZeG d d! d!Z dS )'    )annotationsN)	dataclass)TYPE_CHECKINGAnycast)ARROW_REF_KEY)convert_anything_to_arrow_bytesis_dataframe_like)
get_logger)BidiComponent)	MixedData)AttributeDictionarycalc_md5)BidiComponentStatedatadict[str, Any]arrow_blobsdict[str, bytes] | Nonereturnc                 C  s   |du ri }i }|   D ]>\}}t|rFzt|}t|}|||< t|i||< W q tyE } ztd|| |||< W Y d}~qd}~ww |||< q|S )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)r   r   processed_datakeyvaluearrow_bytesref_ide r   r/var/www/html/IGF-ODF-V3/venv/lib/python3.10/site-packages/streamlit/components/v2/bidi_component/serialization.py_extract_dataframes_from_dict"   s*   
r!   r   bidi_component_protoBidiComponentProtoNonec                 C  s   i }t | trt| |}n| }|rEt }zt||_W n ty-   tt||_Y nw | D ]
\}}||j	| _
q2|j| dS z	t||_W dS  ty`   tt||_Y dS 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   r"   r   r   mixed_protor   r   r   r   r    serialize_mixed_data[   s&   
r/   s
str | Nonec                 C  s2   | du rdS zt | W S  t jy   |  Y S 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)r0   r   r   r    handle_deserialize   s   r4   list[Any] | Nonec                 C  s(   t | }|du r
dS 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)r4   r%   list)r0   r   r   r   r    deserialize_trigger_list   s   
r7   c                   @  s2   e Zd ZU dZdZded< dd	d
ZdddZdS )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defaultui_valuestr | dict[str, Any] | Noner   r   c              
   C  s   t |tr|}n7t |tr=zt|}t |tr|ni }W n! tjtfy< } ztjd||d i }W Y d}~nd}~ww i }| j	durV| j	
 D ]\}}||vrU|||< qItdt|}|S )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(   r2   r3   r*   r   warningr9   r   r   r   )selfr:   deserialized_valueparsedr   default_keydefault_valuestater   r   r    deserialize   s2   



zBidiComponentSerde.deserializer   r   r+   c                 C  s
   t |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   r   r   r    	serialize  s   
zBidiComponentSerde.serialize)r:   r;   r   r   )r   r   r   r+   )__name__
__module____qualname____doc__r9   __annotations__rD   rE   r   r   r   r    r8      s
   
 
0r8   )N)r   r   r   r   r   r   )r   r   r"   r#   r   r$   )r0   r1   r   r   )r0   r1   r   r5   )!
__future__r   r(   dataclassesr   typingr   r   r   0streamlit.components.v2.bidi_component.constantsr   streamlit.dataframe_utilr   r	   streamlit.loggerr
   !streamlit.proto.BidiComponent_pb2r   r#   r   r'   streamlit.utilr   r   ,streamlit.components.v2.bidi_component.stater   rF   r   r!   r/   r4   r7   r8   r   r   r   r    <module>   s(   
9
3
