Ë
    µŒj$  ã                  óª   — d dl mZ d dl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 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mZ  G d
„ de«      Zy)é    )ÚannotationsN)ÚPath)ÚAnyÚDictÚListÚOptionalÚTupleÚUnion)ÚCallbackManagerForRetrieverRun)ÚDocument)ÚBaseRetriever)Úconvert_to_secret_strÚget_from_dict_or_envÚpre_init)Ú
ConfigDictÚ	SecretStrc                  ó  — e Zd ZU dZded<   	 dZded<   	  ed¬«      Zeddd	„«       Z	e
	 d	 	 	 	 	 dd
„«       Ze
	 d	 	 	 	 	 dd„«       Zedd„«       Z	 	 d	 	 	 	 	 	 	 	 	 dd„Zdd„Zdd„Zdd„Zdd„Zd d„Z	 	 	 	 	 	 	 	 d!d„Zd"d„Zy)#ÚNeuralDBRetrieverz0Document retriever that uses ThirdAI's NeuralDB.r   Úthirdai_keyNr   ÚdbÚforbid)Úextrac                óÐ   — 	 ddl m} t        j                  j	                  d«       |j                  | xs t        j                  d«      «       y # t        $ r t        d«      ‚w xY w)Nr   )Ú	licensingzthirdai.neural_dbÚTHIRDAI_KEYz{Could not import thirdai python package and neuraldb dependencies. Please install it with `pip install thirdai[neural_db]`.)	Úthirdair   Ú	importlibÚutilÚ	find_specÚactivateÚosÚgetenvÚImportError)r   r   s     úy/var/www/html/Fitness-lenito-AI-main/venv/lib/python3.12/site-packages/langchain_community/retrievers/thirdai_neuraldb.pyÚ_verify_thirdai_libraryz)NeuralDBRetriever._verify_thirdai_library   s[   € ð
	Ý)ä�N‰N×$Ñ$Ð%8Ô9à×Ñ˜{ÒF¬b¯i©i¸Ó.FÕGøÜò 	ÜðKóð ð	ús   ‚AA ÁA%c                ól   — t         j                  |«       ddlm}  | | |j                  di |¤Ž¬«      S )aÈ  
        Create a NeuralDBRetriever from scratch.

        To use, set the ``THIRDAI_KEY`` environment variable with your ThirdAI
        API key, or pass ``thirdai_key`` as a named parameter.

        Example:
            .. code-block:: python

                from langchain_community.retrievers import NeuralDBRetriever

                retriever = NeuralDBRetriever.from_scratch(
                    thirdai_key="your-thirdai-key",
                )

                retriever.insert([
                    "/path/to/doc.pdf",
                    "/path/to/doc.docx",
                    "/path/to/doc.csv",
                ])

                documents = retriever.invoke("AI-driven music therapy")
        r   ©Ú	neural_db©r   r   © )r   r%   r   r(   ÚNeuralDB)Úclsr   Úmodel_kwargsÚndbs       r$   Úfrom_scratchzNeuralDBRetriever.from_scratch*   s0   € ô: 	×1Ñ1°+Ô>Ý,á˜{¨|¨s¯|©|Ñ/K¸lÑ/KÔLÐLó    c                ó~   — t         j                  |«       ddlm}  | ||j                  j                  |«      ¬«      S )a!  
        Create a NeuralDBRetriever with a base model from a saved checkpoint

        To use, set the ``THIRDAI_KEY`` environment variable with your ThirdAI
        API key, or pass ``thirdai_key`` as a named parameter.

        Example:
            .. code-block:: python

                from langchain_community.retrievers import NeuralDBRetriever

                retriever = NeuralDBRetriever.from_checkpoint(
                    checkpoint="/path/to/checkpoint.ndb",
                    thirdai_key="your-thirdai-key",
                )

                retriever.insert([
                    "/path/to/doc.pdf",
                    "/path/to/doc.docx",
                    "/path/to/doc.csv",
                ])

                documents = retriever.invoke("AI-driven music therapy")
        r   r'   r)   )r   r%   r   r(   r+   Úfrom_checkpoint)r,   Ú
checkpointr   r.   s       r$   r2   z!NeuralDBRetriever.from_checkpointL   s1   € ô< 	×1Ñ1°+Ô>Ý,á˜{¨s¯|©|×/KÑ/KÈJÓ/WÔXÐXr0   c                ó8   — t        t        |dd«      «      |d<   |S )z'Validate ThirdAI environment variables.r   r   )r   r   )r,   Úvaluess     r$   Úvalidate_environmentsz'NeuralDBRetriever.validate_environmentso   s+   € ô !6Ü ØØØóó!
ˆˆ}Ñð ˆr0   c                óf   — | j                  |«      } | j                  j                  d|||dœ|¤Ž y)as  Inserts files / document sources into the retriever.

        Args:
            train: When True this means that the underlying model in the
            NeuralDB will undergo unsupervised pretraining on the inserted files.
            Defaults to True.
            fast_mode: Much faster insertion with a slight drop in performance.
            Defaults to True.
        )ÚsourcesÚtrainÚfast_approximationNr*   )Ú_preprocess_sourcesr   Úinsert)Úselfr8   r9   Ú	fast_modeÚkwargss        r$   r<   zNeuralDBRetriever.insert{   s>   € ð  ×*Ñ*¨7Ó3ˆØˆ�‰�‰ð 	
ØØØ(ñ	
ð ó		
r0   c                ó  — ddl m} |s|S g }|D ]ò  }t        |t        «      s|j	                  |«       Œ%|j                  «       j                  d«      r!|j	                  |j                  |«      «       Œe|j                  «       j                  d«      r!|j	                  |j                  |«      «       Œ¥|j                  «       j                  d«      r!|j	                  |j                  |«      «       Œåt        d|› d�«      ‚ |S )zùChecks if the provided sources are string paths. If they are, convert
        to NeuralDB document objects.

        Args:
            sources: list of either string paths to PDF, DOCX or CSV files, or
            NeuralDB document objects.
        r   r'   z.pdfz.docxz.csvzCould not automatically load z¦. Only files with .pdf, .docx, or .csv extensions can be loaded automatically. For other formats, please use the appropriate document object from the ThirdAI library.)r   r(   Ú
isinstanceÚstrÚappendÚlowerÚendswithÚPDFÚDOCXÚCSVÚRuntimeError)r=   r8   r.   Úpreprocessed_sourcesÚdocs        r$   r;   z%NeuralDBRetriever._preprocess_sources“   sÝ   € õ 	-áØˆNØ!ÐÛˆCÜ˜c¤3Ô'Ø$×+Ñ+¨CÕ0à—9‘9“;×'Ñ'¨Ô/Ø(×/Ñ/°·±¸³Õ=Ø—Y‘Y“[×)Ñ)¨'Ô2Ø(×/Ñ/°·±¸³Õ>Ø—Y‘Y“[×)Ñ)¨&Ô1Ø(×/Ñ/°·±¸³Õ=ä&Ø7¸°uð =Pð Póð ð ð" $Ð#r0   c                ó<   — | j                   j                  ||«       y)a!  The retriever upweights the score of a document for a specific query.
        This is useful for fine-tuning the retriever to user behavior.

        Args:
            query: text to associate with `document_id`
            document_id: id of the document to associate query with.
        N)r   Útext_to_result)r=   ÚqueryÚdocument_ids      r$   ÚupvotezNeuralDBRetriever.upvote³   s   € ð 	�‰×Ñ˜u kÕ2r0   c                ó:   — | j                   j                  |«       y)a„  Given a batch of (query, document id) pairs, the retriever upweights
        the scores of the document for the corresponding queries.
        This is useful for fine-tuning the retriever to user behavior.

        Args:
            query_id_pairs: list of (query, document id) pairs. For each pair in
            this list, the model will upweight the document id for the query.
        N)r   Útext_to_result_batch)r=   Úquery_id_pairss     r$   Úupvote_batchzNeuralDBRetriever.upvote_batch½   s   € ð 	�‰×$Ñ$ ^Õ4r0   c                ó<   — | j                   j                  ||«       y)a=  The retriever associates a source phrase with a target phrase.
        When the retriever sees the source phrase, it will also consider results
        that are relevant to the target phrase.

        Args:
            source: text to associate to `target`.
            target: text to associate `source` to.
        N)r   Ú	associate)r=   ÚsourceÚtargets      r$   rV   zNeuralDBRetriever.associateÈ   s   € ð 	�‰×Ñ˜& &Õ)r0   c                ó:   — | j                   j                  |«       y)a.  Given a batch of (source, target) pairs, the retriever associates
        each source phrase with the corresponding target phrase.

        Args:
            text_pairs: list of (source, target) text pairs. For each pair in
            this list, the source will be associated with the target.
        N)r   Úassociate_batch)r=   Ú
text_pairss     r$   rZ   z!NeuralDBRetriever.associate_batchÓ   s   € ð 	�‰×Ñ 
Õ+r0   c                óv  — 	 d|vrd|d<    | j                   j                  d	d|i|¤Ž}|D �cg c]a  }t        |j                  |j                  |j
                  |j                  |j                  |j                  |j                  d«      dœ¬«      ‘Œc c}S c c}w # t        $ r}t        d|› �«      |‚d}~ww xY w)
zÙRetrieve {top_k} contexts with your retriever for a given query

        Args:
            query: Query to submit to the model
            top_k: The max number of context results to retrieve. Defaults to 10.
        Útop_ké
   rN   é   )ÚidÚ
upvote_idsrW   ÚmetadataÚscoreÚcontext)Úpage_contentrb   z"Error while retrieving documents: Nr*   )r   Úsearchr   Útextr`   ra   rW   rb   rc   rd   Ú	ExceptionÚ
ValueError)r=   rN   Úrun_managerr?   Ú
referencesÚrefÚes          r$   Ú_get_relevant_documentsz)NeuralDBRetriever._get_relevant_documentsÝ   sÈ   € ð	NØ˜fÑ$Ø"$��w‘Ø'˜Ÿ™Ÿ™Ñ>¨eÐ>°vÑ>ˆJñ &óñ &�Cô Ø!$§¡à!Ÿf™fØ&)§n¡nØ"%§*¡*Ø$'§L¡LØ!$§¡Ø#&§;¡;¨q£>ñö
ð &ñð ùò øô ò 	NÜÐAÀ!ÀÐEÓFÈAÐMûð	Nús)   ‚+B ­A&BÂB ÂB Â	B8Â$B3Â3B8c                ó:   — | j                   j                  |«       y)zÇSaves a NeuralDB instance to disk. Can be loaded into memory by
        calling NeuralDB.from_checkpoint(path)

        Args:
            path: path on disk to save the NeuralDB instance to.
        N)r   Úsave)r=   Úpaths     r$   rp   zNeuralDBRetriever.saveû   s   € ð 	�‰�‰�TÕr0   )N)r   úOptional[str]ÚreturnÚNone)r   rr   r-   Údictrs   r   )r3   zUnion[str, Path]r   rr   rs   r   )r5   r   rs   r   )TT)
r8   z	List[Any]r9   Úboolr>   rv   r?   ru   rs   rt   )r8   Úlistrs   rw   )rN   rB   rO   Úintrs   rt   )rS   zList[Tuple[str, int]]rs   rt   )rW   rB   rX   rB   rs   rt   )r[   zList[Tuple[str, str]]rs   rt   )rN   rB   rj   r   r?   r   rs   zList[Document])rq   rB   rs   rt   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   Úmodel_configÚstaticmethodr%   Úclassmethodr/   r2   r   r6   r<   r;   rP   rT   rV   rZ   rn   rp   r*   r0   r$   r   r      sK  … Ù:àÓØà€BˆƒNØáØô€Lð óó ðð ð &*ðMà"ðMð ðMð 
ò	Mó ðMðB ð &*ð Yà$ð Yð #ð Yð 
ò	 Yó ð YðD ò	ó ð	ð Øð	
àð
ð ð
ð ð	
ð
 ð
ð 
ó
ó0$ó@3ó	5ó	*ó,ðNØðNØ'EðNØQTðNà	óNô<r0   r   )Ú
__future__r   r   r!   Úpathlibr   Útypingr   r   r   r   r	   r
   Úlangchain_core.callbacksr   Úlangchain_core.documentsr   Úlangchain_core.retrieversr   Úlangchain_core.utilsr   r   r   Úpydanticr   r   r   r*   r0   r$   Ú<module>r‰      s7   ðÝ "ã Û 	Ý ß :× :å CÝ -Ý 3ß VÑ Vß *ôs˜õ sr0   