
    hM                        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rd dlZdZ G d d	e      Zy)
    )annotationsN)TYPE_CHECKINGAnyDictIterableListOptionalTupleType)Document)
Embeddings)VectorStore   c                     e Zd ZdZdZdZdeeef	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       Ze	deeef	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z
e	ddeeef	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	       Zd
ddddddgf	 	 	 	 	 ddZ	 d	 	 	 ddZ	 d 	 	 	 	 	 	 	 d!dZd"dZe	deeef	 	 	 	 	 	 	 	 	 	 	 	 	 d#d       Zef	 	 	 	 	 	 	 d$dZef	 	 	 	 	 	 	 d%dZef	 	 	 	 	 	 	 d&dZ	 d'	 	 	 	 	 	 	 d&dZ	 d 	 	 	 	 	 d(dZ	 d 	 	 	 	 	 d)dZy)*Vearchlangchain_vearchcluster_client_db   Nstrc                   	 |rddl }nddl}|rw|t        d      |sC| j                  }|dz  }|t        t        j                               j                  d      d   z  }|| _	        || _
        j                  |      | _        n|%t        j                         j                  dd	      }	n|}	t        j                  j!                  |	      st        j"                  |	       t        j                  j%                  |	d
      }
t        j                  j!                  |
      st        j"                  |
        j&                  |	|
      | _        |	| _        |sC| j*                  }|dz  }|t        t        j                               j                  d      d   z  }|| _        || _        || _        y# t        $ r t        d      w xY w)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urlVearchClusterosgetcwdreplacepathisdirmakedirsjoinEngineusing_metapath_DEFAULT_TABLE_NAMEusing_table_nameembedding_funcflag)selfembedding_functionpath_or_url
table_namedb_namer4   kwargsr   r   metadata_pathlog_paths              e/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/vectorstores/vearch.py__init__zVearch.__init__   s   		% " !>??7733tzz|,2237;;!(D"DH(66{CDK " "		 3 3D# > +77==/M*ww||M59H77==*H%'&--x@DK"/D11J#J#djjl+11#6r::J *0	G  	Q 	s   F1 1Gc                    | j                   S N)r3   r5   s    r=   
embeddingszVearch.embeddingsN   s    """    c                    |D cg c]  }|j                    }	}|D cg c]  }|j                   }
} | j                  d|	||
||||d|S c c}w c c}w )Return Vearch VectorStore)texts	embedding	metadatasr7   r8   r9   r4    )page_contentmetadata
from_texts)cls	documentsrG   r7   r8   r9   r4   r:   drF   rH   s              r=   from_documentszVearch.from_documentsR   sq     *33A33)23AQZZ3	3s~~ 	
#!	
 	
 		
 43s
   AAc                H     | ||||||      }	|	j                  ||       |	S )rE   )r6   rG   r7   r9   r8   r4   )rF   rH   )	add_texts)
rM   rF   rG   rH   r7   r8   r9   r4   r:   	vearch_dbs
             r=   rL   zVearch.from_textsm   s;     (#!
	 	%9=rC      text)fieldtyperK   c           
        t         j                  j                  t         j                  j                  d}dddddd}|D cg c]!  }t        j                  |d   ||d	            # }}t        j
                  d
t         j                  j                  d|ddddid      }| j                   j                  || j                  ||      }|S c c}w )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
        )intr   i'  IVFPQi       )
ncentroids
nsubvector)
index_sizeretrieval_typeretrieval_paramrV   rW   text_embeddingT 
MemoryOnly
cache_sizeF)namerW   is_index	dimensionmodel_id
store_typestore_param
has_source)re   fieldsvector_field)	r   dataTypeINTSTRINGGammaFieldInfoGammaVectorInfoVECTORcreate_tabler2   )	r5   dim
field_list	type_dictengine_infofirl   rm   response_codes	            r=   _create_tablezVearch._create_table   s    " #OO//8N8NO	%.2"E
 !
 !!"W+yF/DE
 
 --!''#%u-	
 00&&%	 1 
 )
s   &Cc                    | j                   dddddddidddiddid	d
|dddd}| j                  j                  | j                  |      }|S )z
        Create VectorStore space
        Args:
            dim:dimension of vector
        Return:
            code,0 failed for ,1 for success
        r   gammaFLATmetric_typeL2)re   r^   r_   r`   rW   stringvectorTrc   )rW   indexrg   ri   )rU   rK   ra   )re   partition_numreplica_numengine
properties)r2   r   create_spacer%   )r5   ru   space_configrz   s       r=   _create_spacezVearch._create_space   s     ))"(!4$	 H H %!!$".	#
6 001C1C\RrC   c                    d}| j                   $| j                   j                  t        |            }|t        d      | j                  r| j
                  j                         }| j                  |vr2| j
                  j                  | j                        }|st        d      | j
                  j                  | j                        }| j                  |vr*| j                  t        |d               }|st        d      g }	||t        |||      D ]  \  }
}}i }|
|d<   |d   |d<   t        j                  |      }d	|t        j                   j#                  |      z  j%                         i|d
<   | j
                  j'                  | j                  | j                  |      }|d   dk(  r|	j)                  |d          | j
                  j'                  | j                  | j                  |      }|	j)                  |d           |	S t*        j,                  j/                  | j0                  | j                  dz         }t*        j,                  j3                  |      s,t        |d         }| j5                  |      }|rt        d      ||g }t        |||      D ]`  \  }
}}i }|
|d<   |d   |d<   t        j                  |      }|t        j                   j#                  |      z  |d
<   |j)                  |       b | j
                  j7                  |      }	d}t        |	      t        |      k7  r8t9        j:                  d       |dkD  rn|dz  }t        |	      t        |      k7  r8| j
                  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!!!rU   sourcerK   featurera   status   _id.schemazcreate table failed!!!g      ?   r   )r3   embed_documentslistr    r4   r   list_dbsr%   	create_dblist_spacesr2   r   lenzipnparraylinalgnormtolist
insert_oneappendr(   r+   r.   r0   existsr{   addtimesleepdump)r5   rF   rH   r:   rB   dbs_listcreate_db_code
space_listcreate_space_codedocidrU   rK   embedprofilesembed_np
insert_resretry_insert
table_pathru   rz   	doc_items
profiles_vt_times                          r=   rR   zVearch.add_texts   sX    
*,,<<T%[IJ12299{{++-H!!1!%!6!6t7I7I!J%$%:;;001C1CDJ$$J6$($6$6s:a=7I$J!($%=>>E%)*?-0	:-N !)D(E/1H'+HV$+3H+=HZ(!xxH!Hryy~~h/G$G#O#O#Q2H-. "&!7!7**D,A,A8"J "(+s2Z%67 '+{{'='= ..0E0Ex( \%%89 '!^ 5 ##T%:%:Y%FJ 77>>*-*Q-( $ 2 23 7 $%=>>%)*?	-0	:-N 1)D(E13J)-Jv&-5h-?Jz*!xxH3;biinnX>V3VJ/0$$Z01 	2%jC
O3JJsOzaKF	 %jC
O3
   "rC   c                8    | j                   j                          y)z:
        load vearch engine for standalone vearch
        N)r   loadrA   s    r=   _loadzVearch._load*  s     	rC   c                   |st        d      |st        d      t        j                  j                  ||dz         }t        j                  j	                  |      st        d       | |||||      }|j                          |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!!!r   z$vearch vectorbase table not exist!!!)r6   r7   r8   r9   r4   )r    r(   r+   r.   r   r   )	rM   rG   r7   r8   r9   r4   r:   r   rS   s	            r=   
load_localzVearch.load_local0  s     233/00WW\\+zI/EF
ww~~j)CDD(#!
	 	rC   c                    | j                   t        d      | j                   j                  |      }| j                  ||      }|S )z5
        Return docs most similar to query.

        embedding_func is None!!!)r3   r    embed_querysimilarity_search_by_vector)r5   querykr:   rB   docss         r=   similarity_searchzVearch.similarity_searchP  sI     &899((44U;
//
A>rC   c                   t        j                  |      }| j                  rvdd|t         j                  j	                  |      z  j                         dgi|ddgd}| j                  j                  | j                  | j                  |      }|d   d   }nRd|t         j                  j	                  |      z  dgg dd	d
d|d}| j                  j                  |      }|d   d   }g }|D ]S  }	d}
i }| j                  r|	d   }	|	D ]  }|dk(  r|	|   }
|dk(  s|	|   |d<    |j                  t        |
|             U |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.
        sumra   rV   r   rU   rK   r   sizerl   hitsr   InnerProduct   r   nprober   rl   is_brute_searchr`   topnr   result_itemsrb   _sourcer   rJ   rK   )r   r   r4   r   r   r   r   searchr%   r2   r   r   )r5   rG   r   r:   r   
query_dataquery_resultresr   itemcontent	meta_dataitem_keys                r=   r   z"Vearch.similarity_search_by_vector`  s    #99 %5(-		u0E(E'M'M'O !:.J  ;;--""D$9$9:L v&v.C
 "2#(299>>%+@#@ #$3AR#PJ  ;;--j9Lq/.1C 	LDGIyyI  v%"8nGz)*.x.Ih' KKg	JK	L rC   c                8   | j                   t        d      | j                   j                  |      }t        j                  |      }| j
                  rvdd|t        j                  j                  |      z  j                         dgi|g dd}| j                  j                  | j                  | j                  |      }|d   d   }nRd|t        j                  j                  |      z  dgg dd	d
d|d}| j                  j                  |      }|d   d   }g }	|D ]w  }
d}i }| j
                  r
|
d   }|
d   }
|
D ]6  }|dk(  r|
|   }|dk(  r	|
|   |d<   | j
                  dk7  s,|dk(  s2|
|   }8 t        ||      f}|	j                  |       y |	S )r   r   r   ra   r   )ra   rU   rK   r   r   r   r   r   r   r   r   r   rb   _scorer   rU   rK   r   scorer   )r3   r    r   r   r   r4   r   r   r   r   r   r%   r2   r   r   )r5   r   r   r:   rB   r   r   r   r   resultsr   r   r   r   r   tmp_ress                   r=   similarity_search_with_scorez#Vearch.similarity_search_with_score  s    &899((44U;
$99 %5(-		u0E(E'M'M'O @J  ;;--""D$9$9:L v&v.C
 "2#(299>>%+@#@ #$3AR#PJ  ;;--j9Lq/.1C02 	$DGIyyXI  	v%"8nGz)*.x.Ih'99>h'&9 NE	  WyI5QGNN7##	$$ rC   c                *     | j                   ||fi |S r@   )r   )r5   r   r   r:   s       r=   (_similarity_search_with_relevance_scoresz/Vearch._similarity_search_with_relevance_scores  s     1t00DVDDrC   c                B   d}g }||j                         dk(  r|S |D ]l  }| j                  r2| j                  j                  | j                  | j
                  |      }n| j                  j                  |      }|j                  |       n t        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              3  &   K   | ]	  }|d k(    yw)r   NrI   ).0is     r=   	<genexpr>z Vearch.delete.<locals>.<genexpr>	  s     *Q!q&*s   )	__len__r4   r   deleter%   r2   del_docr   all)r5   idsr:   retr   r   s         r=   r   zVearch.delete  s     #;#++-1,J 	 Cyykk((););T=R=RTWXkk))#.NN3	  *'**
rC   c                   i }||j                         dk(  r|S | j                  rdd|ii}| j                  j                  | j                  | j
                  |      }|D ]J  }|d   du rd}i }|d   D ]!  }	|	dk(  r	|d   |	   }|	d	k(  s|d   |	   |d
<   # t        ||      ||d   <   L |S |D ]Z  }
| j                  j                  |
      }|i k(  r$d}i }|D ]  }	|	dk(  r||	   }|	d	k(  s||	   |d
<    t        ||      ||d   <   \ |S )zReturn docs according ids.

        Args:
            ids: The ids of the embedding vectors.
        Returns:
            Documents which satisfy the input conditions.
        r   r   r   foundFrb   r   rU   rK   r   r   r   )r   r4   r   mget_by_idsr%   r2   r   get_doc_by_id)r5   r   r:   r   r   docs_detailrecordr   	meta_inforV   ids              r=   getz
Vearch.get  s    (*;#++-1,N99!E3<0J++11""D$9$9:K & '?e+	#I. !E"("3E": *,.4Y.?.F	(+ ! *2!(9*u&@ !  "kk77;"$	( !E"-e"4 *,.9%.@	(+ ! /7!(9/E*+  rC   )r6   r   r7   Optional[str]r8   r   r9   r   r4   rY   r:   r   returnNone)r   zOptional[Embeddings])rM   Type[Vearch]rN   List[Document]rG   r   r7   r   r8   r   r9   r   r4   rY   r:   r   r   r   )rM   r   rF   	List[str]rG   r   rH   Optional[List[dict]]r7   r   r8   r   r9   r   r4   rY   r:   r   r   r   )ru   rY   rv   z
List[dict]r   rY   )rT   )ru   rY   r   rY   r@   )rF   zIterable[str]rH   r   r:   r   r   r   )r   r   )rG   r   r7   r   r8   r   r9   r   r4   rY   r:   r   r   r   )r   r   r   rY   r:   r   r   r   )rG   zList[float]r   rY   r:   r   r   r   )r   r   r   rY   r:   r   r   zList[Tuple[Document, float]])r   )r   Optional[List[str]]r:   r   r   zOptional[bool])r   r   r:   r   r   zDict[str, Document])__name__
__module____qualname__r1   r!   _DEFAULT_VERSIONr>   propertyrB   classmethodrP   rL   r{   r   rR   r   r   DEFAULT_TOPNr   r   r   r   r   r   rI   rC   r=   r   r      s   ,2
 &*-/$4&4 #4 	4
 4 4 4 
4l # # 
 &*-/$

!
 
 #	

 
 
 
 
 

 
4 
 +/%)-/$  (	
 #     
 4 e, %0"
++ + 
+^ (( 
(Z +/KK (K 	K
 
KZ  &*-/$ # 	
    
 D   	
 
& >> > 	>
 
>F FF F 	F
 
&FV EE E 	E
 
&E $(   
	< $(5 5 5 
	5rC   r   )
__future__r   r(   r   r"   typingr   r   r   r   r   r	   r
   r   numpyr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   r   r  r   rI   rC   r=   <module>r     s?    " 	   R R R  - 0 3n[ nrC   