a
    bgM                     @  s   d dl mZ d dlZd dlZd dlZd dlmZmZmZ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rd dlZdZG dd	 d	eZdS )
    )annotationsN)TYPE_CHECKINGAnyDictIterableListOptionalTupleType)Document)
Embeddings)VectorStore   c                   @  s  e Zd ZdZdZdZdeeefdddddd	d
dddZeddddZe	deeefdddddddd	d d	ddZ
e	ddeeefddddddddd	d d
ddZdddddddgfdd dd!d"d#ZdEddd$d%d&ZdFd'dd	dd(d)d*Zd
dd+d,Ze	deeefdddddd	d d-d.d/Zefddd	dd0d1d2Zefd3dd	dd4d5d6Zefddd	d7d0d8d9ZdGddd	d7d0d;d<ZdHd=d	d>d?d@dAZdId=d	dBd?dCdDZdS )JVearchZlangchain_vearchZcluster_client_db   Nr   zOptional[str]strintr   None)embedding_functionpath_or_url
table_namedb_nameflagkwargsreturnc                 K  s@  z|rddl }nddl}W n ty4   tdY n0 |r|du rJtd|sv| j}|d7 }|tt dd 7 }|| _	|| _
||| _nl|du rt dd	}	n|}	tj|	st|	 tj|	d
}
tj|
st|
 ||	|
| _|	| _|s*| j}|d7 }|tt dd 7 }|| _|| _|| _dS )zSInitialize vearch vector store
        flag 1 for cluster,0 for standalone
        r   NzhCould not import suitable python package. Please install it with `pip install vearch or vearch_cluster`.zPlease input url of cluster_-\/log)vearch_clustervearchImportError
ValueError_DEFAULT_CLUSTER_DB_NAMEr   uuiduuid4splitusing_db_nameurlZVearchClusterosgetcwdreplacepathisdirmakedirsjoinZEngineusing_metapath_DEFAULT_TABLE_NAMEusing_table_nameembedding_funcr   )selfr   r   r   r   r   r   r!   r"   Zmetadata_pathlog_path r8   u/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/vectorstores/vearch.py__init__   sF    



zVearch.__init__zOptional[Embeddings])r   c                 C  s   | j S N)r5   r6   r8   r8   r9   
embeddingsN   s    zVearch.embeddingszType[Vearch]zList[Document])	cls	documents	embeddingr   r   r   r   r   r   c           
   
   K  s<   dd |D }dd |D }	| j f |||	||||d|S )Return Vearch VectorStorec                 S  s   g | ]
}|j qS r8   )page_content.0dr8   r8   r9   
<listcomp>_       z)Vearch.from_documents.<locals>.<listcomp>c                 S  s   g | ]
}|j qS r8   )metadatarC   r8   r8   r9   rF   `   rG   )textsr@   	metadatasr   r   r   r   )
from_texts)
r>   r?   r@   r   r   r   r   r   rI   rJ   r8   r8   r9   from_documentsR   s    zVearch.from_documentsz	List[str]zOptional[List[dict]])
r>   rI   r@   rJ   r   r   r   r   r   r   c           
      K  s&   | ||||||d}	|	j ||d |	S )rA   )r   r@   r   r   r   r   )rI   rJ   )	add_texts)
r>   rI   r@   rJ   r   r   r   r   r   	vearch_dbr8   r8   r9   rK   m   s    zVearch.from_texts   textfieldtyperH   z
List[dict])dim
field_listr   c              
     sr   t jjt jjd dddddd} fdd	|D }t jd
t jjd|ddddidd}| j j|| j||d}|S )z
        Create VectorStore Table
        Args:
            dim:dimension of vector
            fields_list: the field you want to store
        Return:
            code,0 for success,1 for failed
        )r   r   i'  ZIVFPQi       )Z
ncentroidsZ
nsubvector)
index_sizeretrieval_typeretrieval_paramc                   s$   g | ]}t |d   |d  qS rQ   )r"   ZGammaFieldInfo)rD   fiZ	type_dictr8   r9   rF      s   z(Vearch._create_table.<locals>.<listcomp>text_embeddingT 
MemoryOnlyZ
cache_sizeF)namerS   Zis_index	dimensionZmodel_id
store_typeZstore_paramZ
has_source)r_   fieldsvector_field)r"   ZdataTypeINTSTRINGZGammaVectorInfoZVECTORZcreate_tabler4   )r6   rT   rU   Zengine_inforb   rc   response_coder8   r[   r9   _create_table   s2    

zVearch._create_table)rT   r   c                 C  sN   | j dddddddidddiddid	d
|dddd}| j| j|}|S )z
        Create VectorStore space
        Args:
            dim:dimension of vector
        Return:
            code,0 failed for ,1 for success
        r   gammaZFLATmetric_typeZL2)r_   rW   rX   rY   rS   stringvectorTr^   )rS   indexr`   ra   )rP   rH   r\   )r_   Zpartition_numZreplica_numZengine
properties)r4   r"   Zcreate_spacer)   )r6   rT   Zspace_configrf   r8   r8   r9   _create_space   s,    
zVearch._create_spacezIterable[str])rI   rJ   r   r   c                 K  sr  d}| j dur| j t|}|du r.td| jrd| j }| j|vrd| j| j}|sdtd| j	| j}| j
|vr| t|d }|stdg }	|durn|durnt|||D ]\}
}}i }|
|d< |d |d< t|}d	|tj|  i|d
< | j| j| j
|}|d dkr:|	|d  qq| j| j| j
|}|	|d  qqn
tj| j| j
d }tj|st|d }| |}|rtd|durn|durng }t|||D ]L\}
}}i }|
|d< |d |d< t|}|tj| |d
< || q| j|}	d}t|	t|krdtd |dkrXqd|d7 }q.| j  |	S )z^
        Returns:
            List of ids from adding the texts into the vectorstore.
        Nzembeddings is Nonezcreate db failed!!!r   zcreate space failed!!!rP   sourcerH   featurer\   status   _id.schemazcreate table failed!!!g      ?   r   )r5   Zembed_documentslistr$   r   r"   Zlist_dbsr)   Z	create_dbZlist_spacesr4   rn   lenzipnparraylinalgnormtolistZ
insert_oneappendr+   r.   r1   r2   existsrg   addtimesleepdump)r6   rI   rJ   r   r=   Zdbs_listZcreate_db_codeZ
space_listZcreate_space_codeZdocidrP   rH   embedZprofilesZembed_npZ
insert_resZretry_insert
table_pathrT   rf   Z	doc_itemsZ
profiles_vZt_timer8   r8   r9   rM      s|    












zVearch.add_textsc                 C  s   | j   dS )z:
        load vearch engine for standalone vearch
        N)r"   loadr<   r8   r8   r9   _load*  s    zVearch._load)r@   r   r   r   r   r   r   c           	      K  s\   |st d|st dtj||d }tj|s>t d| |||||d}|  |S )zLoad the local specified table of standalone vearch.
        Returns:
            Success or failure of loading the local specified table
        zNo metadata path!!!zNo table name!!!rt   z$vearch vectorbase table not exist!!!)r   r   r   r   r   )r$   r+   r.   r1   r   r   )	r>   r@   r   r   r   r   r   r   rN   r8   r8   r9   
load_local0  s     zVearch.load_local)querykr   r   c                 K  s.   | j du rtd| j |}| ||}|S )z5
        Return docs most similar to query.

        Nembedding_func is None!!!)r5   r$   embed_querysimilarity_search_by_vector)r6   r   r   r   r=   docsr8   r8   r9   similarity_searchP  s
    

zVearch.similarity_searchzList[float])r@   r   r   r   c                 K  s  t |}| jr^dd|t j|  dgi|ddgd}| j| j| j	|}|d d }nBd|t j| dgg dd	d
d|d}| j|}|d d }g }|D ]^}	d}
i }| jr|	d }	|	D ],}|dkr|	| }
q|dkr|	| |d< qq|
t|
|d q|S )  The most k similar documents and scores of the specified query.
        Args:
            embeddings: embedding vector of the query.
            k: The k most similar documents to the text query.
            min_score: the score of similar documents to the text query
        Returns:
            The k most similar documents to the specified text query.
            0 is dissimilar, 1 is the most similar.
        sumr\   rR   rp   rP   rH   r   sizerb   hitsr   InnerProduct   ri   Znproberk   rb   Zis_brute_searchrY   Ztopnr   result_itemsr]   _sourcero   rB   rH   )ry   rz   r   r{   r|   r}   r"   searchr)   r4   r~   r   )r6   r@   r   r   r   
query_dataquery_resultresr   itemcontent	meta_dataitem_keyr8   r8   r9   r   `  sR    

z"Vearch.similarity_search_by_vectorzList[Tuple[Document, float]]c                 K  sZ  | j du rtd| j |}t|}| jr|dd|tj|  dgi|g dd}| j	
| j| j|}|d d }nBd|tj| dgg d	d
dd|d}| j	
|}|d d }g }	|D ]}
d}i }| jr|
d }|
d }
|
D ]L}|dkr|
| }q|dkr|
| |d< q| jd	kr|dkr|
| }qqt||d|f}|	| q|	S )r   Nr   r   r\   r   )r\   rP   rH   r   r   r   r   r   r   r   r   r   r]   Z_scorer   rP   rH   ro   scorer   )r5   r$   r   ry   rz   r   r{   r|   r}   r"   r   r)   r4   r   r~   )r6   r   r   r   r=   r   r   r   r   resultsr   r   r   r   r   tmp_resr8   r8   r9   similarity_search_with_score  sb    




z#Vearch.similarity_search_with_scorer   c                 K  s   | j ||fi |S r;   )r   )r6   r   r   r   r8   r8   r9   (_similarity_search_with_relevance_scores  s    z/Vearch._similarity_search_with_relevance_scoreszOptional[List[str]]zOptional[bool])idsr   r   c                 K  sr   d}g }|du s|  dkr |S |D ]6}| jrD| j| j| j|}n| j|}|| q$tdd |D }|S )aI  Delete the documents which have the specified ids.

        Args:
            ids: The ids of the embedding vectors.
            **kwargs: Other keyword arguments that subclasses might use.
        Returns:
            Optional[bool]: True if deletion is successful.
            False otherwise, None if not implemented.
        Nr   c                 s  s   | ]}|d kV  qdS )r   Nr8   )rD   ir8   r8   r9   	<genexpr>	  rG   z Vearch.delete.<locals>.<genexpr>)	__len__r   r"   deleter)   r4   Zdel_docr~   all)r6   r   r   retr   rs   r8   r8   r9   r     s    zVearch.deletezDict[str, Document]c                 K  s,  i }|du s|  dkr|S | jrdd|ii}| j| j| j|}|D ]n}|d du rXqFd}i }|d D ]6}	|	d	kr|d |	 }qhqh|	d
krh|d |	 |d< qhqht||d||d < qFnp|D ]j}
| j|
}|i krqd}i }|D ].}	|	d	kr||	 }qq|	d
kr||	 |d< qqt||d||d < q|S )zReturn docs according ids.

        Args:
            ids: The ids of the embedding vectors.
        Returns:
            Documents which satisfy the input conditions.
        Nr   r   r   foundFr]   r   rP   rH   ro   r   rs   )r   r   r"   Zmget_by_idsr)   r4   r   Zget_doc_by_id)r6   r   r   r   r   Zdocs_detailrecordr   Z	meta_inforR   idr8   r8   r9   get  sP    
z
Vearch.get)rO   )N)r   )N)N)__name__
__module____qualname__r3   r%   Z_DEFAULT_VERSIONr:   propertyr=   classmethodrL   rK   rg   rn   rM   r   r   DEFAULT_TOPNr   r   r   r   r   r   r8   r8   r8   r9   r      sf   6"$/ - M"CK 
  r   )
__future__r   r+   r   r&   typingr   r   r   r   r   r   r	   r
   numpyry   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.vectorstoresr   r"   r   r   r8   r8   r8   r9   <module>   s   (