Ë
    µŒjj"  ã                   ór   — d dl Z d dlmZ d dlmZ d dlmZmZmZm	Z	m
Z
mZ d dlmZ d dlmZ  G d„ de«      Zy)	é    N)ÚPathLike)ÚPath)ÚAnyÚCallableÚDictÚIteratorÚOptionalÚUnion)ÚDocument)Ú
BaseLoaderc                   óÞ   — e Zd ZdZ	 	 	 	 	 ddeeef   dedee   dee   dee	e
e
ge
f      ded	efd
„Zdee   fd„Zdededee   fd„Zdedefd„Zde
eef   dede
eef   fd„Zdeddfd„Zy)Ú
JSONLoadera…  
    Load a `JSON` file using a `jq` schema.

    Setup:
        .. code-block:: bash

            pip install -U jq

    Instantiate:
        .. code-block:: python

            from langchain_community.document_loaders import JSONLoader
            import json
            from pathlib import Path

            file_path='./sample_quiz.json'
            data = json.loads(Path(file_path).read_text())
            loader = JSONLoader(
                     file_path=file_path,
                     jq_schema='.quiz',
                     text_content=False)

    Load:
        .. code-block:: python

            docs = loader.load()
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        .. code-block:: python

            {"sport": {"q1": {"question": "Which one is correct team name in
            NBA?", "options": ["New York Bulls"
            {'source': '/sample_quiz
            .json', 'seq_num': 1}

    Async load:
        .. code-block:: python

            docs = await loader.aload()
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        .. code-block:: python

            {"sport": {"q1": {"question": "Which one is correct team name in
            NBA?", "options": ["New York Bulls"
            {'source': '/sample_quizg
            .json', 'seq_num': 1}

    Lazy load:
        .. code-block:: python

            docs = []
            docs_lazy = loader.lazy_load()

            # async variant:
            # docs_lazy = await loader.alazy_load()

            for doc in docs_lazy:
                docs.append(doc)
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        .. code-block:: python

            {"sport": {"q1": {"question": "Which one is correct team name in
            NBA?", "options": ["New York Bulls"
            {'source': '/sample_quiz
            .json', 'seq_num': 1}
    NÚ	file_pathÚ	jq_schemaÚcontent_keyÚis_content_key_jq_parsableÚmetadata_funcÚtext_contentÚ
json_linesc                 óú   — 	 ddl }|| _         t        |«      j                  «       | _        |j                  |«      | _        || _        || _        || _	        || _
        || _        y# t        $ r t        d«      ‚w xY w)a~  Initialize the JSONLoader.

        Args:
            file_path (Union[str, PathLike]): The path to the JSON or JSON Lines file.
            jq_schema (str): The jq schema to use to extract the data or text from
                the JSON.
            content_key (str): The key to use to extract the content from
                the JSON if the jq_schema results to a list of objects (dict).
                If is_content_key_jq_parsable is True, this has to be a jq compatible
                schema. If is_content_key_jq_parsable is False, this should be a simple
                string key.
            is_content_key_jq_parsable (bool): A flag to determine if
                content_key is parsable by jq or not. If True, content_key is
                treated as a jq schema and compiled accordingly. If False or if
                content_key is None, content_key is used as a simple string.
                Default is False.
            metadata_func (Callable[Dict, Dict]): A function that takes in the JSON
                object extracted by the jq_schema and the default metadata and returns
                a dict of the updated metadata.
            text_content (bool): Boolean flag to indicate whether the content is in
                string format, default to True.
            json_lines (bool): Boolean flag to indicate whether the input is in
                JSON Lines format.
        r   Nz=jq package not found, please install it with `pip install jq`)ÚjqÚImportErrorr   Úresolver   ÚcompileÚ
_jq_schemaÚ_is_content_key_jq_parsableÚ_content_keyÚ_metadata_funcÚ_text_contentÚ_json_lines)	Úselfr   r   r   r   r   r   r   r   s	            úz/var/www/html/Fitness-lenito-AI-main/venv/lib/python3.12/site-packages/langchain_community/document_loaders/json_loader.pyÚ__init__zJSONLoader.__init__T   s�   € ðD	ÛàˆDŒGô ˜i›×0Ñ0Ó2ˆŒØŸ*™* YÓ/ˆŒØ+EˆÔ(Ø'ˆÔØ+ˆÔØ)ˆÔØ%ˆÕøô ò 	ÜØOóð ð	ús   ‚A% Á%A:Úreturnc              #   óv  K  — d}| j                   ra| j                  j                  d¬«      5 }|D ]5  }|j                  «       }|sŒ| j	                  ||«      D ]  }|–— |dz  }Œ Œ7 	 ddd«       y| j	                  | j                  j                  d¬«      |«      D ]  }|–— |dz  }Œ y# 1 sw Y   yxY w­w)z-Load and return documents from the JSON file.r   z	utf-8-sig)Úencodingé   N)r    r   ÚopenÚstripÚ_parseÚ	read_text)r!   ÚindexÚfÚlineÚdocs        r"   Ú	lazy_loadzJSONLoader.lazy_load‡   s²   è ø€ àˆØ×ÒØ—‘×$Ñ$¨kÐ$Ô:¸aÛ�DØŸ:™:›<�DÚØ#'§;¡;¨t°UÖ#;˜CØ"%šIØ! Q™J™Eñ $<ñ ÷ ;Ð:ð —{‘{Ø—‘×(Ñ(°+Ð(Ó>Àö�ð ’	Ø˜‘
‘ñ	÷ ;Ð:üs#   ‚+B9­B-Á"B-Á)AB9Â-B6Â2B9Úcontentr,   c              #   ó`  K  — | j                   j                  t        j                  |«      «      }| j                  �| j                  |«       t        ||dz   «      D ]M  \  }}| j                  |¬«      }| j                  |t        | j                  «      |¬«      }t        ||¬«      –— ŒO y­w)z#Convert given content to documents.Nr'   )Úsample)r3   ÚsourceÚseq_num)Úpage_contentÚmetadata)r   ÚinputÚjsonÚloadsr   Ú_validate_content_keyÚ	enumerateÚ	_get_textÚ_get_metadataÚstrr   r   )r!   r1   r,   ÚdataÚir3   Útextr7   s           r"   r*   zJSONLoader._parse™   sœ   è ø€ à�‰×$Ñ$¤T§Z¡Z°Ó%8Ó9ˆð
 ×ÑÐ(Ø×&Ñ& tÔ,ä" 4¨°©Ö3‰IˆAˆvØ—>‘>¨�>Ó0ˆDØ×)Ñ)Ø¤c¨$¯.©.Ó&9À1ð *ó ˆHô ¨°xÔ@Ó@ñ 4ùs   ‚B,B.r3   c                 óì  — | j                   �a| j                  rE| j                  j                  | j                   «      }|j	                  |«      j                  «       }n|| j                      }n|}| j                  r*t        |t        «      s|�t        dt        |«      › d�«      ‚t        |t        «      r|S t        |t        t        f«      r|rt        j                  |«      S dS |�t        |«      S dS )zConvert sample to string formatz%Expected page_content is string, got z‚ instead.                     Set `text_content=False` if the desired input for                     `page_content` is not a stringÚ )r   r   r   r   r8   Úfirstr   Ú
isinstancer?   Ú
ValueErrorÚtypeÚdictÚlistr9   Údumps)r!   r3   Úcompiled_content_keyr1   s       r"   r=   zJSONLoader._get_textª   sá   € à×ÑÐ(Ø×/Ò/Ø'+§w¡w§¡°t×7HÑ7HÓ'IÐ$Ø.×4Ñ4°VÓ<×BÑBÓD‘à  ×!2Ñ!2Ñ3‘àˆGà×Ò¤j°¼#Ô&>À7ÐCVÜØ7¼¸W»°ð G3ð 4óð ô ˜¤Ô%ØˆNÜ˜¤$¬ Ô.Ù*1”4—:‘:˜gÓ&Ð9°rÐ9à#*Ð#6”3�w“<Ð>¸BÐ>ó    Úadditional_fieldsc                 ó–   — | j                   �<| j                  ||«      }t        |t        «      st        dt	        |«      › d�«      ‚|S |S )zå
        Return a metadata dictionary base on the existence of metadata_func
        :param sample: single data payload
        :param additional_fields: key-word arguments to be added as metadata values
        :return:
        zUExpected the metadata_func to return a dict but got                                 `Ú`)r   rF   rI   rG   rH   )r!   r3   rN   Úresults       r"   r>   zJSONLoader._get_metadataÄ   s\   € ð ×ÑÐ*Ø×(Ñ(¨Ð1BÓCˆFÜ˜f¤dÔ+Ü ð"Ü"& v£, ¨qð2óð ð ˆMà$Ð$rM   r@   c                 óÄ  — |j                  «       }t        |t        «      st        dt	        |«      › d�«      ‚| j
                  s4|j                  | j                  «      €t        d| j                  › d�«      ‚| j
                  r\| j                  j                  | j                  «      j                  |«      j                  «       €t        d| j                  › d�«      ‚yy)zCheck if a content key is validztExpected the jq schema to result in a list of objects (dict),                     so sample must be a dict but got `rP   Nz_Expected the jq schema to result in a list of objects (dict)                     with the key `z ` which should be parsable by jq)rE   rF   rI   rG   rH   r   Úgetr   r   r   r8   rB   )r!   r@   r3   s      r"   r;   z JSONLoader._validate_content_keyØ   së   € ð —‘“ˆÜ˜&¤$Ô'Üð7Ü7;¸F³|°nÀAðGóð ð ×0Ò0Ø—
‘
˜4×,Ñ,Ó-Ð5äð#Ø#'×#4Ñ#4Ð"5°Qð8óð ð
 ×,Ò,Ø—‘—‘ × 1Ñ 1Ó2×8Ñ8¸Ó@×EÑEÓGÐOäð#Ø#'×#4Ñ#4Ð"5Ð5UðWóð ð Pð -rM   )NFNTF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r
   r?   r   r	   Úboolr   r   r#   r   r   r0   Úintr*   r   r=   r>   r;   © rM   r"   r   r      s  „ ñFðX &*Ø5:Ø@DØ!Ø ñ1&à˜˜h˜Ñ'ð1&ð ð1&ð ˜c‘]ð	1&ð
 %-¨T¡Nð1&ð   ¨$°¨°tÐ);Ñ <Ñ=ð1&ð ð1&ð ó1&ðf˜8 HÑ-ó ð$A˜cð A¨#ð A°(¸8Ñ2Dó Að"? ð ?¨ó ?ð4%Ø˜3 ˜8‘nð%Ø;>ð%à	ˆc�3ˆh‰ó%ð(¨#ð °$ô rM   r   )r9   Úosr   Úpathlibr   Útypingr   r   r   r   r	   r
   Úlangchain_core.documentsr   Ú)langchain_community.document_loaders.baser   r   rZ   rM   r"   Ú<module>r`      s(   ðÛ Ý Ý ß A× Aå -å @ôf�õ frM   