a
    `g                     @  sR   d dl mZ d dlZd dlZd dlmZmZmZmZ d dl	m
Z
 G dd dZdS )    )annotationsN)AnyDictListOptional)Documentc                      s   e Zd ZdZd*ddd fddZed	dd
ddZed	ddddddZddd
ddZd+dddddddZ	d,dddddd Z
d-ddddd"d#d$Zd.dddd%d&d'd(d)Z  ZS )/RecursiveJsonSplittera  Splits JSON data into smaller, structured chunks while preserving hierarchy.

    This class provides methods to split JSON data into smaller dictionaries or
    JSON-formatted strings based on configurable maximum and minimum chunk sizes.
    It supports nested JSON structures, optionally converts lists into dictionaries
    for better chunking, and allows the creation of document objects for further use.

    Attributes:
        max_chunk_size (int): The maximum size for each chunk. Defaults to 2000.
        min_chunk_size (int): The minimum size for each chunk, derived from
            `max_chunk_size` if not explicitly provided.
      NintzOptional[int])max_chunk_sizemin_chunk_sizec                   s0   t    || _|dur|nt|d d| _dS )a!  Initialize the chunk size configuration for text processing.

        This constructor sets up the maximum and minimum chunk sizes, ensuring that
        the `min_chunk_size` defaults to a value slightly smaller than the
        `max_chunk_size` if not explicitly provided.

        Args:
            max_chunk_size (int): The maximum size for a chunk. Defaults to 2000.
            min_chunk_size (Optional[int]): The minimum size for a chunk. If None,
                defaults to the maximum chunk size minus 200, with a lower bound of 50.

        Attributes:
            max_chunk_size (int): The configured maximum size for each chunk.
            min_chunk_size (int): The configured minimum size for each chunk, derived
                from `max_chunk_size` if not explicitly provided.
        N   2   )super__init__r   maxr   )selfr   r   	__class__ k/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_text_splitters/json.pyr      s    
zRecursiveJsonSplitter.__init__r   )datareturnc                 C  s   t t| S )z1Calculate the size of the serialized JSON object.)lenjsondumps)r   r   r   r   
_json_size3   s    z RecursiveJsonSplitter._json_sizez	List[str]r   None)dpathvaluer   c                 C  s.   |dd D ]}|  |i } q|| |d < dS )z;Set a value in a nested dictionary based on the given path.N)
setdefault)r   r   r    keyr   r   r   _set_nested_dict8   s    z&RecursiveJsonSplitter._set_nested_dictc                   sH   t |tr  fdd| D S t |tr@ fddt|D S |S d S )Nc                   s   i | ]\}}|  |qS r   )_list_to_dict_preprocessing).0kvr   r   r   
<dictcomp>B       zERecursiveJsonSplitter._list_to_dict_preprocessing.<locals>.<dictcomp>c                   s    i | ]\}}t | |qS r   )strr%   )r&   iitemr)   r   r   r*   E   s   )
isinstancedictitemslist	enumerate)r   r   r   r)   r   r%   ?   s    


z1RecursiveJsonSplitter._list_to_dict_preprocessingzDict[str, Any]zOptional[List[str]]zOptional[List[Dict]]z
List[Dict])r   current_pathchunksr   c           
      C  s   |pg }|dur|ni g}t |tr| D ]v\}}||g }| |d }| ||i}| j| }	||	k r| |d || q,|| jkr|i  | ||| q,n| |d || |S )zESplit json into maximum size dictionaries while preserving structure.Nr!   )	r/   r0   r1   r   r   r$   r   append_json_split)
r   r   r4   r5   r#   r    new_path
chunk_sizesize	remainingr   r   r   r7   M   s    




z!RecursiveJsonSplitter._json_splitFbool)	json_dataconvert_listsr   c                 C  s4   |r|  | |}n
|  |}|d s0|  |S )z'Splits JSON into a list of JSON chunks.r!   )r7   r%   pop)r   r=   r>   r5   r   r   r   
split_jsonl   s    
z RecursiveJsonSplitter.split_jsonT)r=   r>   ensure_asciir   c                   s    | j ||d} fdd|D S )z2Splits JSON into a list of JSON formatted strings.)r=   r>   c                   s   g | ]}t j| d qS )rA   )r   r   )r&   chunkrB   r   r   
<listcomp>   r+   z4RecursiveJsonSplitter.split_text.<locals>.<listcomp>)r@   )r   r=   r>   rA   r5   r   rB   r   
split_text|   s    z RecursiveJsonSplitter.split_textzOptional[List[dict]]zList[Document])textsr>   rA   	metadatasr   c                 C  sf   |pi gt | }g }t|D ]B\}}| j|||dD ](}	t|| }
t|	|
d}|| q6q|S )z4Create documents from a list of json objects (Dict).)r=   r>   rA   )Zpage_contentmetadata)r   r3   rE   copydeepcopyr   r6   )r   rF   r>   rA   rG   Z
_metadatasZ	documentsr-   textrC   rH   Znew_docr   r   r   create_documents   s    
z&RecursiveJsonSplitter.create_documents)r	   N)NN)F)FT)FTN)__name__
__module____qualname____doc__r   staticmethodr   r$   r%   r7   r@   rE   rL   __classcell__r   r   r   r   r   
   s(      "      r   )
__future__r   rI   r   typingr   r   r   r   Zlangchain_core.documentsr   r   r   r   r   r   <module>   s
   