
    h//                        d dl mZ d dlZd dl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 d dlZd dlmZ d dlmZ d dlmZ  ej*                  e      Z G d d	e      Zy)
    )annotationsN)ThreadPoolExecutor)AnyIterableListOptionalTuple)Document)
Embeddings)VectorStorec                  $   e Zd ZdZ	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 d
dZ	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 ddZe	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z	e	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z
y)Clarifaia  `Clarifai AI` vector store.

    To use, you should have the ``clarifai`` python SDK package installed.

    Example:
        .. code-block:: python

                from langchain_community.vectorstores import Clarifai

                clarifai_vector_db = Clarifai(
                        user_id=USER_ID,
                        app_id=APP_ID,
                        number_of_docs=NUMBER_OF_DOCS,
                        )
    Nc                >   |xs t         j                  j                  d      }|xs t         j                  j                  d      }||t        d      || _        	 ddlm}	  |	||||||      j                  | _	        y# t        $ r}
t        d      |
d}
~
ww xY w)	a  Initialize with Clarifai client.

        Args:
            user_id (Optional[str], optional): User ID. Defaults to None.
            app_id (Optional[str], optional): App ID. Defaults to None.
            pat (Optional[str], optional): Personal access token. Defaults to None.
            token (Optional[str], optional): Session token. Defaults to None.
            number_of_docs (Optional[int], optional): Number of documents to return
            during vector search. Defaults to None.
            api_base (Optional[str], optional): API base. Defaults to None.

        Raises:
            ValueError: If user ID, app ID or personal access token is not provided.
        CLARIFAI_USER_IDCLARIFAI_APP_IDNzCould not find CLARIFAI_USER_ID or CLARIFAI_APP_ID in your environment. Please set those env variables with a valid user ID, app IDr   SearchXCould not import clarifai python package. Please install it with `pip install clarifai`.)user_idapp_idtop_kpattokenbase_url)
osenvironget
ValueError_number_of_docsclarifai.client.searchr   ImportErrorauth_helper_auth)selfr   r   number_of_docsr   r   api_base_user_id_app_idr   es              g/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/vectorstores/clarifai.py__init__zClarifai.__init__#   s    . @bjjnn-?@=BJJNN+<=wN 
  .	5  
 + 	
  	A 	s   B 	BBBc                   	 ddl m} ddlm} t        |      }t        |      }	|	dkD  sJ d       ||	t        |      k(  sJ d       |t        |      t        |      k(  sJ d       |j                  | j                  	      }
d
}g }t        d|	|      D ]  }	 ||||z    }|r||||z    nd}|>t        t        |            D cg c]   }t        j                         j                  " }}n||||z    }|2g }|D ]+  } |       }|j                  |       |j                  |       - t        |      D cg c]#  \  }}|
j!                  ||   ||r|   nd      % }}}|
j#                  |      }|j%                  |       t&        j)                  d        |S # t        $ r}t	        d      |d}~ww xY wc c}w c c}}w # t*        $ r7}t&        j-                  d|        t/        j0                          Y d}~nd}~ww xY w)a'  Add texts to the Clarifai vectorstore. This will push the text
        to a Clarifai application.
        Application use a base workflow that create and store embedding for each text.
        Make sure you are using a base workflow that is compatible with text
        (such as Language Understanding).

        Args:
            texts (Iterable[str]): Texts to add to the vectorstore.
            metadatas (Optional[List[dict]], optional): Optional list of metadatas.
            ids (Optional[List[str]], optional): Optional list of IDs.

        r   )Inputs)Structr   Nz,No texts provided to add to the vectorstore.z1Number of texts and metadatas should be the same.z7Number of text inputs and input ids should be the same.)auth    )input_idraw_textmetadata)inputszInput posted successfully.zPost inputs failed: )clarifai.client.inputr-   google.protobuf.struct_pb2r.   r!   listlenfrom_auth_helperr#   rangeuuiduuid4hexupdateappend	enumerateget_text_inputupload_inputsextendloggerdebug	Exceptionwarning	traceback	print_exc)r$   texts	metadatasidskwargsr-   r.   r)   ltextslength	input_obj
batch_sizeinput_job_idsidxbatch_textsbatch_metadatas_	batch_ids	meta_listmetameta_structitextinput_batch	result_iderrors                             r*   	add_textszClarifai.add_textsU   sU   &	49 eVzIIIz S^+ C+ ?v;#c(* I* +++<	
FJ/ 	&C&$S3+;<9BIcC*$45   ;;@[AQ;R Sa!1!1 SI S #C#
*: ;I". "I / 6&,h#**40!((56 $-[#9  4 ,,!*1!%1@1d -   &33;3G	$$Y/9:5	&@ o  	A 	< !T  &!5eW=>##%%&sN   F ,G%F<*AG7(G;G	F9(F44F9<G	H,HHc                *    	 ddl m} ddlm} ddlm |xs  j                  }|j                   j                  |      }	d|ig}
|d	|i}|	j                  |
|g
      }n|	j                  |
      }|D cg c]  }|j                  D ]  }|  }}}t        d      }d fd}|D cg c]  }|j                  ||       }}|D cg c]  }|j                          }}|S # t        $ r}t        d      |d}~ww xY wc c}}w c c}w c c}w )a  Run similarity search with score using Clarifai.

        Args:
            query (str): Query text to search for.
            k (Optional[int]): Number of results to return. If not set,
            it'll take _number_of_docs. Defaults to None.
            filter (Optional[Dict[str, str]]): Filter by metadata.
            Defaults to None.

        Returns:
            List[Document]: List of documents most similar to the query text.
        r   r   )resources_pb2)json_formatr   N)r/   r   text_rawr3   )ranksfilters)re   
   )max_workersc                8   j                  | j                  j                  j                        }t	        j
                  j                        }t        j                  | j                  j                  j                  j                  |      }|j                  |_        |j                  }t        j                  d| j                  dd| j                  j                    d| j                  j                    d|d d         t#        ||      | j                  fS )	N)headersz	Score z.2fz for annotation: z                off input: z, text: }   )page_contentr3   )MessageToDictinputdatar3   dictr#   requestsr   r\   urlapparent_encodingencodingrD   rE   score
annotationidr
   )hitr3   hrequestrequested_textrc   r$   s        r*   hit_to_documentz>Clarifai.similarity_search_with_score.<locals>.hit_to_document   s    "001H1HIHTZZ(()All399>>#6#6#:#:AFG  '88G$\\NLL399S/):3>>;L;L:M NIILL>.#2F1GI .8LciiXX    )rx   zresources_pb2.HitreturnzTuple[Document, float])r    r   clarifai_grpc.grpc.apirb   google.protobufrc   r!   r   r9   r#   queryhitsr   submitresult)r$   r   krf   rM   r   rb   r)   r   
search_objranksearch_metadatasearch_responsero   rx   r   executorr|   futuresfuturedocs_and_scoresrc   s   `                    @r*   similarity_search_with_scorez%Clarifai.similarity_search_with_score   s3   &	5<3 )T)),,$**E,J
U#$)73O(..TOCT.UO(..T.:O !0E499ECEEE%"5	Y  EIIS8???C8II9@Av6==?AAS  	A 	& F& JAs)   C( :D.DD(	D1C==Dc                b     | j                   |fd|i|}|D cg c]  \  }}|	 c}}S c c}}w )aG  Run similarity search using Clarifai.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return.
            If not set, it'll take _number_of_docs. Defaults to None.

        Returns:
            List of Documents most similar to the query and score for each
        r   )r   )r$   r   r   rM   r   docrV   s          r*   similarity_searchzClarifai.similarity_search   s8      <$;;EQQQ&Q"12Q222s   +c	           	     H     | d|||||d|	}
|
j                  ||       |
S )a  Create a Clarifai vectorstore from a list of texts.

        Args:
            user_id (str): User ID.
            app_id (str): App ID.
            texts (List[str]): List of texts to add.
            number_of_docs (Optional[int]): Number of documents
            to return during vector search. Defaults to None.
            pat (Optional[str], optional): Personal access token.
            Defaults to None.
            token (Optional[str], optional): Session token. Defaults to None.
            metadatas (Optional[List[dict]]): Optional list
            of metadatas. Defaults to None.
            kwargs: Additional keyword arguments to be passed to the Search.

        Returns:
            Clarifai: Clarifai vectorstore.
        )r   r   r%   r   r   )rJ   rK    )r`   )clsrJ   	embeddingrK   r   r   r%   r   r   rM   clarifai_vector_dbs              r*   
from_textszClarifai.from_texts   sH    > ! 
)
 
 	$$5I$F!!r}   c                    |D 	cg c]  }	|	j                    }
}	|D 	cg c]  }	|	j                   }}	 | j                  d|||
||||d|S c c}	w c c}	w )a  Create a Clarifai vectorstore from a list of documents.

        Args:
            user_id (str): User ID.
            app_id (str): App ID.
            documents (List[Document]): List of documents to add.
            number_of_docs (Optional[int]): Number of documents
            to return during vector search. Defaults to None.
            pat (Optional[str], optional): Personal access token. Defaults to None.
            token (Optional[str], optional): Session token. Defaults to None.
            kwargs: Additional keyword arguments to be passed to the Search.

        Returns:
            Clarifai: Clarifai vectorstore.
        )r   r   rJ   r%   r   rK   r   r   )rl   r3   r   )r   	documentsr   r   r   r%   r   r   rM   r   rJ   rK   s               r*   from_documentszClarifai.from_documents#  ss    6 .77c!!77-67cS\\7	7s~~ 	
)	
 	
 		
 87s
   AA)NN   NNzhttps://api.clarifai.com)r   Optional[str]r   r   r%   Optional[int]r   r   r   r   r&   r   r~   None)NN)
rJ   zIterable[str]rK   Optional[List[dict]]rL   zOptional[List[str]]rM   r   r~   	List[str])
r   strr   r   rf   zOptional[dict]rM   r   r~   zList[Tuple[Document, float]])N)r   r   r   r   rM   r   r~   List[Document])NNNNNNN)rJ   r   r   Optional[Embeddings]rK   r   r   r   r   r   r%   r   r   r   r   r   rM   r   r~   r   )NNNNNN)r   r   r   r   r   r   r   r   r%   r   r   r   r   r   rM   r   r~   r   )__name__
__module____qualname____doc__r+   r`   r   r   classmethodr   r   r   r}   r*   r   r      s+   $ "& $()!#"<00 0 &	0
 0 0  0 
0j +/#'	MM (M !	M
 M 
Md  "&	@@ @  	@
 @ 
&@J  33 3 	3
 
3&  +/*.!% $(,!#'"'" ('" (	'"
 '" '" &'" '" '" '" 
'" '"R  +/!% $(,!#%
!%
 (%
 	%

 %
 &%
 %
 %
 %
 
%
 %
r}   r   )
__future__r   loggingr   rH   r;   concurrent.futuresr   typingr   r   r   r   r	   rq   langchain_core.documentsr
   langchain_core.embeddingsr   langchain_core.vectorstoresr   	getLoggerr   rD   r   r   r}   r*   <module>r      sI    "  	   1 7 7  - 0 3			8	$w
{ w
r}   