
    Ng                    l   U 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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 d dlmZ e	rd dl Z ed	         Z! e" ee!                    Z#d
e$d<   ed         Z% e" ee%                    Z&de$d<   dZ'dZ(dZ)e)dz  Z*g dZ+g dZ,ddi gZ- ej.        e/          Z0djdZ1dkd!Z2dld#Z3dmdnd*Z4 G d+ d,e          Z5	 	 	 	 	 	 	 dodpd9Z6	 	 	 	 	 	 	 	 	 dqdrdCZ7dsdHZ8dIg dfdtdLZ9dudOZ:dvdQZ;dwdUZ<dxdXZ=dyd\Z>dzd`Z?	 	 d{d|ddZ@d}dfZAd~diZBdS )    )annotationsN)deepcopy)TYPE_CHECKINGAnyCallableDictIterableListLiteralOptionalSizedTupleTypeUnionget_args)Document)
Embeddings)VectorStore)maximal_marginal_relevance)L2IPzList[DISTANCE_METRICS]AVAILABLE_DISTANCE_METRICS)TileDBDenseTileDBSparse	FaissFlatFaissIVFFlatFlinngzList[ENGINES]AVAILABLE_ENGINES	langchain          )	_distanceidcontent)r#   r%   blobzMissing propertyxr   yx_namestry_namereturnNonec                   t          | t                    rot          |t                    rZt          |           t          |          k    r:t          | d| d| dt          |            d| dt          |                     dS )z
    Check that sizes of two variables are the same

    Args:
        x: Variable to compare
        y: Variable to compare
        x_name: Name for variable x
        y_name: Name for variable y
    z and z% expected to be equal length but len(z)=z	 and len(N)
isinstancer   len
ValueError)r'   r(   r)   r+   s       a/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/vdms.py_len_check_if_sizedr3   >   s     !U 

1e 4 4 
Q3q669I9I A AF A AA A VVA A.4A A8;AA A
 
 	
 F    resultsList[Document]c                4    d t          |           D             S )Nc                    g | ]\  }}|S  r9   .0doc_s      r2   
<listcomp>z$_results_to_docs.<locals>.<listcomp>Q   s    CCCFCCCCCr4   )_results_to_docs_and_scores)r5   s    r2   _results_to_docsr@   P   s    CC9'BBCCCCr4   List[Tuple[Document, float]]c                   g }	 | d         \  }}t          |          dk    rd|d         v rd|d         d         v r|d         d         d         }|D ]u}t          |d         d          }|d         }t          D ]	}||v r||= 
d |                                D             }	|                    t          ||	          |f           vn4# t          $ r'}
t                              d	|
            Y d }
~
nd }
~
ww xY w|S )
Nr   FindDescriptorentitiesr#   
   r%   c                ,    i | ]\  }}|t           v||S r9   )INVALID_METADATA_VALUE)r;   mkeymvals      r2   
<dictcomp>z/_results_to_docs_and_scores.<locals>.<dictcomp>e   s4       "d#999 $999r4   )page_contentmetadataz2No results returned. Error while parsing results: )	r0   roundINVALID_DOC_METADATA_KEYSitemsappendr   	Exceptionloggerwarning)r5   	final_res	responsesblobsresult_entitiesentdistancetxt_contentsppropses              r2   r?   r?   T   s`   IQ"1:	5	NNQ IaL00il+;<<<'l+;<ZHO&   [!1266"9~2 # #ACxxF &)iikk     <%HHH(S     Q Q QOAOOPPPPPPPPQs   CC	 	
C:C55C:	localhost  hostportint	vdms.vdmsc                    	 ddl }n# t          $ r t          d          w xY w |j                     }|                    | |           |S )zVDMS client for the VDMS server.

    Args:
        host: IP or hostname of VDMS server
        port: Port to connect to VDMS server
    r   NzOCould not import vdms python package. Please install it with `pip install vdms.)vdmsImportErrorconnect)r`   ra   re   clients       r2   VDMS_Clientri   s   sl    
 
 
 
8
 
 	

 TY[[F
NN4Ms    !c                     e Zd ZdZdedddddddZedd            ZddZddZ	dd!Z
dd$Zdd&Zeedfdd.Z	 	 ddd5Z	 	 ddd7Z	 	 ddd<Z	 	 	 	 dddDZ	 	 dddIZg dEfddPZ	 dddRZddUZddedVfddZZ	 	 	 	 	 ddd\Zddefdd^Zdefdd_ZddaZddbZddeZ	 	 	 dddgZ 	 	 	 dddlZ!eeddddEfddtZ"ddvZ#e$ddeefddz            Z%e$dddeefdd{            Z&ddd=gfdd~Z'eeddfddZ(eeddfddZ)eeddfddZ*eeddfddZ+ddeedddEfddZ,eedfddZ-eedfddZ.eedfddZ/eedfddZ0ddZ1ddZ2dS )VDMSa  Intel Lab's VDMS for vector-store workloads.

    To use, you should have both:
    - the ``vdms`` python package installed
    - a host (str) and port (int) associated with a deployed VDMS Server

    Visit https://github.com/IntelLabs/vdms/wiki more information.

    IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA.

    Args:
        client: VDMS Client used to connect to VDMS server
        collection_name: Name of data collection [Default: langchain]
        distance_strategy: Method used to calculate distances. VDMS supports
            "L2" (euclidean distance) or "IP" (inner product) [Default: L2]
        engine: Underlying implementation for indexing and computing distances.
            VDMS supports TileDBDense, TileDBSparse, FaissFlat, FaissIVFFlat,
            and Flinng [Default: FaissFlat]
        embedding: Any embedding function implementing
            `langchain_core.embeddings.Embeddings` interface.
        relevance_score_fn: Function for obtaining relevance score

    Example:
        .. code-block:: python

            from langchain_huggingface import HuggingFaceEmbeddings
            from langchain_community.vectorstores.vdms import VDMS, VDMS_Client

            model_name = "sentence-transformers/all-mpnet-base-v2"
            vectorstore = VDMS(
                client=VDMS_Client("localhost", 55555),
                embedding=HuggingFaceEmbeddings(model_name=model_name),
                collection_name="langchain-demo",
                distance_strategy="L2",
                engine="FaissFlat",
            )
    Nr   r   )	embeddingcollection_namedistance_strategyenginerelevance_score_fnembedding_dimensionsrh   rc   rl   Optional[Embeddings]rm   r*   rn   DISTANCE_METRICSro   ENGINESrp   "Optional[Callable[[float], float]]rq   Optional[int]r,   r-   c                   || _         || _        || _        || _        |                     ||           || _        |                     || j        | j                  | _        d S )Nro   metric)_clientsimilarity_search_enginern   rl   _check_required_inputsoverride_relevance_score_fnadd_set_collection_name)selfrh   rl   rm   rn   ro   rp   rq   s           r2   __init__zVDMS.__init__   su     (.%!2"##O5IJJJ ,>( !%0) !- !
 !
r4   c                    | j         S N)rl   r   s    r2   
embeddingszVDMS.embeddings   s
    ~r4   texts	List[str]List[List[float]]c                    t          | j        t                    r| j                            |          S d}|dz  }t	          |          )Nz*Must provide `embedding` which is expectedz to be an Embeddings object)r/   rl   r   embed_documentsr1   )r   r   p_strs      r2   _embed_documentszVDMS._embed_documents   sJ    dnj11 	$>11%888@E22EU###r4   pathskwargsr   c                    | j         )t          | j         d          r | j         j        dd|i|S t          d          )Nembed_videor   z:Must provide `embedding` which has attribute `embed_video`r9   )rl   hasattrr   r1   )r   r   r   s      r2   _embed_videozVDMS._embed_video   sP    >%'$.-*P*P%-4>-DDEDVDDDL  r4   urisc                    | j         0t          | j         d          r| j                             |          S t          d          )Nembed_imager   z:Must provide `embedding` which has attribute `embed_image`)rl   r   r   r1   )r   r   s     r2   _embed_imagezVDMS._embed_image   sI    >%'$.-*P*P%>--4-888L  r4   textList[float]c                    t          | j        t                    r| j                            |          S t	          d          )NzEMust provide `embedding` which is expected to be an Embeddings object)r/   rl   r   embed_queryr1   )r   r   s     r2   _embed_queryzVDMS._embed_query   sC    dnj11 	>--d333.  r4   Callable[[float], float]c                    | j         | j         S | j                                        dv rd S t          d| j         d          )a8  
        The 'correct' relevance function
        may differ depending on a few things, including:
        - the distance / similarity metric used by the VectorStore
        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
        - embedding dimensionality
        - etc.
        N)ipl2c                    | S r   r9   )r'   s    r2   <lambda>z1VDMS._select_relevance_score_fn.<locals>.<lambda>   s    Q r4   z=No supported normalization function for distance_strategy of z;.Consider providing relevance_score_fn to VDMS constructor.)r}   rn   lowerr1   r   s    r2   _select_relevance_score_fnzVDMS._select_relevance_score_fn   sj     +733 !''))\99;M-1-CM M M  r4   querykrb   fetch_kfilterOptional[Dict[str, Any]]rA   c                    | j         d|d<    | j        d||||d|}g }|D ]N\  }}	| j         |                    ||	f           $|                    ||                      |	          f           O|S )z?Return docs and their similarity scores on a scale from 0 to 1.NTnormalize_distance)r   r   r   r   r9   )r}   similarity_search_with_scorerP   )
r   r   r   r   r   r   docs_and_scoresdocs_and_rel_scoresr<   scores
             r2   (_similarity_search_with_relevance_scoresz-VDMS._similarity_search_with_relevance_scores  s     +3+/F'(;$; 
	
 

 
 
 *,) 	 	JC/7#**C<8888#**$::5AAB    #"r4   r   	metadatas1Optional[Union[List[None], List[Dict[str, Any]]]]idsOptional[List[str]]r
   c                   t          ||dd           ||nd |D             }t          ||dd           ||nd |D             }t          ||dd           g }g }g }t          ||||          D ]e\  }	}
}}|                     ||	|
||          \  }}|?|                    |           |                    |           |                    |           f|                     ||          \  }}|S )Nr   r   c                    g | ]}d S r   r9   r;   r=   s     r2   r>   zVDMS.add.<locals>.<listcomp>-  s    <Q<Q<QaT<Q<Q<Qr4   r   c                N    g | ]"}t          t          j                              #S r9   r*   uuiduuid4r   s     r2   r>   zVDMS.add.<locals>.<listcomp>0  &    *L*L*L3tz||+<+<*L*L*Lr4   r   rL   rl   documentr$   )r3   zip_VDMS__get_add_queryrP   _VDMS__run_vdms_query)r   rm   r   r   r   r   all_queries	all_blobsinserted_idsmetaembr<   r$   r   r&   responseresponse_arrays                    r2   addzVDMS.add#  s=    	E:wEEE!*!6II<Q<Q5<Q<Q<Q	E9g{CCC_cc*L*Le*L*L*LE3777!#!	"$"%iUC"H"H 	( 	(D#sB..$#PR /  KE4 ""5)))  &&&##B'''#'#8#8i#P#P .r4   ry   c                    t          d|| j        t          |d|          t          |d|                    }|                     |g          \  }}d|d         v rt	          d|           |S )NAddDescriptorSetvaluerx   FailedCommandr   zFailed to add collection )_add_descriptorsetembedding_dimensiongetattrr   r1   )r   rm   ro   ry   r   r   r=   s          r2   r~   zVDMS.add_setD  s     #$67F3367F33
 
 
 ++UG44!hqk))JJJKKKr4   Union[None, List[str]]constraintsUnion[None, Dict[str, Any]]boolc                r   g }g }|                      |          }d|i}|dddgi}nddg|d<   |d|d         g|d<   t          d|ddddd||		  	        }|                    |           |                     ||          \  }	}
t	          d
|d          }|                     |g|          \  }}d|	d         v S )zA
        Deletes entire collection if id is not provided
        listN	_deletion==   r   r$   rC   labelrefr\   linkk_neighborsr   r5   FindDescriptorSetT)
storeIndex)_VDMS__get_properties_add_descriptorrP   r   r   )r   rm   r   r   r   r   collection_propertiesr5   r   r   r   responseSetr=   s                r2   __deletezVDMS.__deleteY  s    "$!	 $ 5 5o F F01&q	2KK(,ayK$?!%s1vK#

 

 

 	5!!!#'#8#8i#P#P . #T
 
 
 ..w	BBQ8A;..r4   rL   Optional[Any]Union[List[float], None]r   r$   Optional[str]4Tuple[Dict[str, Dict[str, Any]], Union[bytes, None]]c                   |i }nyd|i}t          | j        ||          \  }}|rZd |d         d                                         D             }	d| d}
|
dz  }
t          |
           t          d|	            |d fS |r|                    |           |d	vr||d
<   |                                D ]%}|| j        vr| j                            |           &t          d|d d |d d d d 	  	        }t          |          }||fS )Nr$   c                &    i | ]\  }}||d          S )r9   )r;   prop_keyprop_vals      r2   rJ   z(VDMS.__get_add_query.<locals>.<dictcomp>  s2     ! ! !*( hrl! ! !r4   rC   r   z[!] Embedding with id (z) exists in DB;z#Therefore, skipped and not insertedz	Skipped values are: )N r%   AddDescriptorr   )
_check_descriptor_exists_by_idrz   rO   printupdatekeysr   rP   r   embedding2bytes)r   rm   rL   rl   r   r$   r\   	id_existsr   skipped_valuepstrr   r&   s                r2   __get_add_queryzVDMS.__get_add_query  s{    :$&EE2JE=or   Iu  #! !.34D.E%/egg	! ! ! EDDD==d>}>>???d{" 	#LL""":%%'E) 	5 	5A222*11!444

 

 

 y)) 
 	
r4   Funique_entityOptional[bool]deletionc                    t          |||          }|                     |g          \  }}t          |          dk    r)t          |d                                       d          }nt          t                    }|S )N)r   r   r   ,)_find_property_entityr   r0   
_bytes2strsplitr   DEFAULT_PROPERTIES)r   rm   r   r   
find_queryr   response_blobr   s           r2   __get_propertieszVDMS.__get_properties  s     +=8
 
 

 #'"7"7"E"E-}!!$.}Q/?$@$@$F$Fs$K$K!!$,-?$@$@!$$r4   r   
List[Dict]r   Optional[List]print_last_responseTuple[Any, Any]c                    | j                             ||          \  }}t          ||          }|r| j                                          ||fS r   )rz   r   _check_valid_responser  )r   r   r   r  r   r   r=   s          r2   __run_vdms_queryzVDMS.__run_vdms_query  sV     $(<#5#5k9#M#M .!+x88 	/L,,...''r4   	documentsc                \   t          ||dd           t          ||dd           ||nd |D             }t          ||dd           |                     |          }g }t          ||||          D ]\  }}	}
}d| j        i}dd	d
gi}|d	|g|d<   t	          d|ddddd||	  	        }|                     |g          \  }}|                     |||	|
|          \  }}|0|                     |g|g          \  }}|                    |           |                     ||| j                   dS )z
        Updates (find, delete, add) a collection based on id.
        If more than one collection returned with id, error occuers
        r   r  r   Nc                    g | ]}d S r   r9   r   s     r2   r>   z!VDMS.__update.<locals>.<listcomp>  s    <O<O<OaT<O<O<Or4   r   r   r   r   r   r$   rC   r   r   )	r3   r   r   r   r   r   r   rP   _VDMS__update_properties)r   rm   r   r  r   r   
orig_propsupdated_idsr   r   r<   r$   r5   r   r   r   r   r&   s                     r2   __updatezVDMS.__update  s    	CE;???CULAAA!*!6II<O<O3<O<O<O	CE;???**?;;
!#"%iY"L"L 	' 	'D#sBt9:G&q	2K~%)2JD!#  '
 
 
E (,'<'<eW'E'E$Hn.. /  KE4 +/+@+@%4&+Q+Q(.""2&&&  Z)C	
 	
 	
 	
 	
r4   current_collection_propertiesnew_collection_propertiesc                    |dt          |          }|D ]}||vr|                    |           ||k    r3t          |d|          \  }}|                     ||g          \  }}	d S d S d S )Nr   )command_typeall_properties)r   rP   _build_property_queryr   )
r   rm   r  r  old_collection_propertiespropr   blob_arrr   r=   s
             r2   __update_propertieszVDMS.__update_properties  s     %0(01N(O(O%1 ? ?<<<188>>>,0III(=#!)#@) ) )%X
 #33K(LL!!! 10 JIr4   TOptional[List[dict]]
batch_sizeadd_pathc           	     V     fd|D             }|r#|r!t          |          D ]\  }}	|	||         d<   n |rg }|D ]}	|                    d|	i           ||nd |D             }                     |          }
|d |D             }nd |D             }  j        d	||
|||d| |S )
a  Run more images through the embeddings and add to the vectorstore.

        Images are added as embeddings (AddDescriptor) instead of separate
        entity (AddImage) within VDMS to leverage similarity search capability

        Args:
            uris: List of paths to the images to add to the vectorstore.
            metadatas: Optional list of metadatas associated with the images.
            ids: Optional list of unique IDs.
            batch_size (int): Number of concurrent requests to send to the server.
            add_path: Bool to add image path as metadata

        Returns:
            List of ids from adding images into the vectorstore.
        c                <    g | ]}                     |           S ))
image_path)encode_image)r;   urir   s     r2   r>   z#VDMS.add_images.<locals>.<listcomp>C  s*    GGG3T&&#&66GGGr4   r#  Nc                N    g | ]"}t          t          j                              #S r9   r   r   s     r2   r>   z#VDMS.add_images.<locals>.<listcomp>N  s&    *K*K*K3tz||+<+<*K*K*Kr4   r   c                    g | ]}i S r9   r9   r   s     r2   r>   z#VDMS.add_images.<locals>.<listcomp>T  s    ******r4   c                ,    g | ]}t          |          S r9   _validate_vdms_propertiesr;   ms     r2   r>   z#VDMS.add_images.<locals>.<listcomp>V  !    III!2155IIIr4   r   r   r   r   r  r9   )	enumeraterP   r   add_from)r   r   r   r   r  r   r   	b64_textsmidxr%  r   s   `          r2   
add_imageszVDMS.add_images*  s9   2 HGGG$GGG	 	6	 	6&t__ 4 4	c03	$--4 	6I 6 6  ,!45555 _cc*K*Kd*K*K*K &&D&11
**T***IIIIyIIII 	
!!	
 	
 	
 	
 	
 
r4   r   c           	     ,   |d |D             }|r#|r!t          |          D ]\  }}	|	||         d<   n |rg }|D ]}	|                    d|	i           ||nd |D             } | j        dd|i|}
|d |D             } | j        d||
|||d| |S )	a  Run videos through the embeddings and add to the vectorstore.

        Videos are added as embeddings (AddDescriptor) instead of separate
        entity (AddVideo) within VDMS to leverage similarity search capability

        Args:
            paths: List of paths to the videos to add to the vectorstore.
            metadatas: Optional list of text associated with the videos.
            metadatas: Optional list of metadatas associated with the videos.
            ids: Optional list of unique IDs.
            batch_size (int): Number of concurrent requests to send to the server.
            add_path: Bool to add video path as metadata

        Returns:
            List of ids from adding videos into the vectorstore.
        Nc                    g | ]}d S )r   r9   r   s     r2   r>   z#VDMS.add_videos.<locals>.<listcomp>}  s    '''AR'''r4   
video_pathc                N    g | ]"}t          t          j                              #S r9   r   r   s     r2   r>   z#VDMS.add_videos.<locals>.<listcomp>  r   r4   r   c                    g | ]}i S r9   r9   r   s     r2   r>   z#VDMS.add_videos.<locals>.<listcomp>      ++++++r4   r.  r9   )r/  rP   r   r0  )r   r   r   r   r   r  r   r   r2  pathr   s              r2   
add_videoszVDMS.add_videosb  s*   4 ='''''E 	7	 	7'.. 5 5
d04	$--5 	7I 7 7  ,!56666 _cc*L*Le*L*L*L 'T&==U=f==
++U+++I 	
!!	
 	
 	
 	
 	
 
r4   Iterable[str]c           	         t          |          }|d |D             }|                     |          }|d |D             }nd |D             } | j        d|||||d|}|S )a  Run more texts through the embeddings and add to the vectorstore.

        Args:
            texts: List of strings to add to the vectorstore.
            metadatas: Optional list of metadatas associated with the texts.
            ids: Optional list of unique IDs.
            batch_size (int): Number of concurrent requests to send to the server.

        Returns:
            List of ids from adding the texts into the vectorstore.
        Nc                N    g | ]"}t          t          j                              #S r9   r   r   s     r2   r>   z"VDMS.add_texts.<locals>.<listcomp>  &    4443tz||$$444r4   c                    g | ]}i S r9   r9   r   s     r2   r>   z"VDMS.add_texts.<locals>.<listcomp>  r9  r4   c                ,    g | ]}t          |          S r9   r)  r+  s     r2   r>   z"VDMS.add_texts.<locals>.<listcomp>  r-  r4   r.  r9   )r   r   r0  )r   r   r   r   r  r   r   r   s           r2   	add_textszVDMS.add_texts  s    ( U;44e444C**511
++U+++IIIIyIIII$t} 
!!
 
 
 
 r4   c                   |                      | j                  }g }t          dt          |          |          D ]}	t	          |	|z   t          |                    }
||	|
         }||	|
         }||	|
         }|r
||	|
         }|                     | j        ||||          }|                    |           |                     | j        || j                   |S )Nr   )r   r   r   r   )	r   r   ranger0   minr   extendr  r   )r   r   r   r   r   r  r   r  r   	start_idxend_idxbatch_textsbatch_embedding_vectors	batch_idsbatch_metadatasresults                   r2   r0  zVDMS.add_from  s    **4+@AA
"$q#e**j99 	( 	(I)j0#e**==G	' 12K&071B&C#Ig-.I ?"+Ig,=">XX%2!)   F '''' 	  !:t/I	
 	
 	
 r4   Union[int, None]c                @   | j                                         st          d          | j        t          vrt          d          | j        t          vrt          d          | j        t          d          ||| _        n| j        =t          | j        d          r(t          |                     d                    | _        n| j        t          | j        d          st          | j        d          r^t          | j        d	          r:	 | j        j        j        j        | _        n,# t          $ r t          d
          w xY wt          d
          |                     |          }t          | d          r| j                            |           d S || _        d S )Nz_VDMS client must be connected to a VDMS server.Please use VDMS_Client to establish a connectionz-distance_strategy must be either 'L2' or 'IP'z]engine must be either 'TileDBDense', 'TileDBSparse', 'FaissFlat', 'FaissIVFFlat', or 'Flinng'Must provide embedding functionr   zThis is a sample sentence.r   r   modelz>Embedding dimension needed. Please define embedding_dimensionsr   )rz   is_connectedr1   rn   r   r{   r   rl   r   r   r0   r   rQ  token_embeddingembedding_dimr   r   rF  )r   rm   rq   current_propss       r2   r|   zVDMS._check_required_inputs  s    |((** 	E   !)CCCLMMM (0AAA=   >!>???+';D$$^'GDNM,R,R''*!!">??( (D$$ ^'DNM22 (t~}55 ( t~w// ,<J ,, "   $X  
 !T  
 --o>>4011 	B&--m<<<<<4AD&&&s   D* *Ec                    g }g }ddgd}t          d|d d d d d d |	  	        }|                    |           |                     ||          \  }}|d         d         d         S )Nr   r$   )countr   rC   r   r   returned)r   rP   r   )r   rm   r   r   r5   r   r   r   s           r2   rW  z
VDMS.count   s    !#!	//

 

 

 	5!!!#'#8#8i#P#P .{+,Z88r4   base64_imagebytesc                *    t          j        |          S r   )base64	b64decode)r   rY  s     r2   decode_imagezVDMS.decode_image6  s    ---r4   Optional[Dict]c                H    ||n| j         }|                     |||          S )zDelete by ID. These are the IDs in the vectorstore.

        Args:
            ids: List of ids to delete.

        Returns:
            Optional[bool]: True if deletion is successful,
            False otherwise, None if not implemented.
        N)r   r   )r   _VDMS__delete)r   r   rm   r   r   names         r2   deletezVDMS.delete9  s-      #2"=4CX}}Ts}DDDr4   setnamer5   	normalize(Tuple[List[Dict[str, Any]], List, float]c                    d}d}t          ||||          }|                     |g|          \  }	}
|r*||	d         v r |	d         |         d         d         d         }|	|
|fS )Nr   rC   )r   r5   r   rD   r   r#   )r   r   )r   rd  r   r5   r   re  max_distcommand_strr   r   r   s              r2   get_k_candidateszVDMS.get_k_candidatesL  s     &	
 
 
 $(#8#8%)#L#L . 	M33{;/
;B?LH11r4   ri  r   Optional[dict]query_embeddingOptional[List[float]]r   !Tuple[List[Dict[str, Any]], List]c	                   g }	t          |          }
|
|	                    |
           | |                     ||||	|          \  }}}n|ddgi}n0d|vrdg|d<   n%d|d         vr|d                             d           t          ||||          }|                     |g          \  }}||d         v r7|d         |         d         dk    rd |d         |         d         D             }ng g fS |                     ||||	|          \  }}}||d         vs"||d         v r|d         |         d         dk    rg g fS g }|d         |         d         D ]6}|d         |v r|                    |           t          |          |k    r n7||d         |         d<   t          |          |d         |         d<   t          |          |k     rd	}t          |           |rl|dt          j        fv rd
n|}t          |d         |         d                   D ]6\  }}|d         |z  |d<   |d         |d         |         d         |         d<   7||fS )N)re  r   r$   r   r5   r   rX  c                    g | ]
}|d          S )r$   r9   )r;   rX   s     r2   r>   z0VDMS.get_descriptor_response.<locals>.<listcomp>  s)     # # #"%CI# # #r4   rD   z4Returned items < k_neighbors; Try increasing fetch_kg      ?r#   )
r   rP   rj  r   r   r0   r   npinfr/  )r   ri  rd  r   r   r   r5   rl  r   r   r&   r   r   rh  r   ids_of_interestnew_entitiesrX   r   ent_idxs                       r2   get_descriptor_responsezVDMS.get_descriptor_responsec  s     "	//T"""151F1FgyDV 2G 2 2.Hnhh !D6*w&&#'&WV_,,&&t,,, $'	  E (,'<'<eW'E'E$Hnhqk))hqk+.Fz.RUV.V.V# #)1![)A*)M# # # 2v 261F1F'9@R 2G 2 2.Hnh (1+--x{**x{;/G
/SWX/X/X2v (*L{;/
;  t9// '',,,|$$33E 43?HQK$Z036|3D3DHQK$Z0<  ;..Ne 	&1bf+55ss8H )(1+k*B:*N O O  #&{#3h#>K MPNK(4W=kJJ ''r4   r#  c                    t          |d          5 }|                                }t          j        |                              d          cd d d            S # 1 swxY w Y   d S )Nrbzutf-8)openreadr\  	b64encodedecode)r   r#  fr&   s       r2   r$  zVDMS.encode_image  s    *d## 	:q6688D#D))0099	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	:s   ;AA Acls
Type[VDMS]r6   c           	     r    |d         }|                      |d |D             d |D             ||||          S )a  Create a VDMS vectorstore from a list of documents.

        Args:
            collection_name (str): Name of the collection to create.
            documents (List[Document]): List of documents to add to vectorstore.
            embedding (Embeddings): Embedding function. Defaults to None.
            ids (Optional[List[str]]): List of document IDs. Defaults to None.
            batch_size (int): Number of concurrent requests to send to the server.

        Returns:
            VDMS: VDMS vectorstore.
        rh   c                    g | ]	}|j         
S r9   rK   r;   r<   s     r2   r>   z'VDMS.from_documents.<locals>.<listcomp>  s    9993#999r4   c                    g | ]	}|j         
S r9   )rL   r  s     r2   r>   z'VDMS.from_documents.<locals>.<listcomp>  s    999s|999r4   )rh   r   r   rl   r   r  rm   )
from_texts)r  r  rl   r   r  rm   r   rh   s           r2   from_documentszVDMS.from_documents  sZ    , #8,~~99y99999y999!+  	
 	
 		
r4   c                    |d         } | |||          }	|d |D             }|	                     ||||           |	S )aH  Create a VDMS vectorstore from a raw documents.

        Args:
            texts (List[str]): List of texts to add to the collection.
            embedding (Embeddings): Embedding function. Defaults to None.
            metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.
            ids (Optional[List[str]]): List of document IDs. Defaults to None.
            batch_size (int): Number of concurrent requests to send to the server.
            collection_name (str): Name of the collection to create.

        Returns:
            VDMS: VDMS vectorstore.
        rh   )rm   rl   rh   Nc                N    g | ]"}t          t          j                              #S r9   r   r   s     r2   r>   z#VDMS.from_texts.<locals>.<listcomp>  r?  r4   )r   r   r   r  )rB  )
r  r   rl   r   r   r  rm   r   rh   vdms_collections
             r2   r  zVDMS.from_texts  sx    0 #8,#+
 
 
 ;44e444C!!!	 	" 	
 	
 	
 r4   limitincludec                    g }g }ddi}|||d<   d|v r|                      |          }||d<   d|v rd|d	<   t          d
|d||          }	|                    |	           |                     ||          \  }
}|
|fS )a  Gets the collection.
        Get embeddings and their associated data from the data store.
        If no constraints provided returns all embeddings up to limit.

        Args:
            constraints: A dict used to filter results by.
                   E.g. `{"color" : ["==", "red"], "price": [">", 4.00]}`. Optional.
            limit: The number of documents to return. Optional.
            include: A list of what to include in the results.
                     Can contain `"embeddings"`, `"metadatas"`, `"documents"`.
                     Ids are always included.
                     Defaults to `["metadatas", "documents"]`. Optional.
        rW  r   Nr  rL   r   r   Tr&   rC   )r   r   r5   )r   r   rP   r   )r   rm   r   r  r  r   r   r5   r   r   r   r   s               r2   getzVDMS.get   s    ( "$!	#*B-$GG   $($9$9/$J$J!3GFO 7"""GFO#
 
 
 	5!!!#'#8#8i#P#P .''r4   g      ?lambda_multfloatOptional[Dict[str, List]]c                   | j         t          d          t          j                            |          s+t          | j         d          r|                     |          }nt          j                            |          r3t          | j         d          r|                     |g          d         }nqt          j                            |          r3t          | j         d          r|                     |g          d         }nd	| d
}|dz  }|dz  }t          |          | 	                    |||||          }	|	S aR  Return docs selected using the maximal marginal relevance.
        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            query (str): Query to look up. Text or path for image or video.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.

        Returns:
            List of Documents selected by maximal marginal relevance.
        NzBFor MMR search, you must specify an embedding function oncreation.r   r   r   r   r   r   (Could not generate embedding for query ''.9If using path for image or video, verify embedding model 6has callable functions 'embed_image' or 'embed_video'.)r  r   )
rl   r1   osr:  isfiler   r   r   r   'max_marginal_relevance_search_by_vector)
r   r   r   r   r  r   r   embedding_vector	error_msgdocss
             r2   max_marginal_relevance_searchz"VDMS.max_marginal_relevance_search2  s[   4 >!W   w~~e$$ 
	()O)O 
	(#0077W^^E"" 	(wt~}'M'M 	(#00ug0>>qAW^^E"" 	(wt~}'M'M 	(#00w0??BL5LLLITTIQQIY''';;# < 
 
 r4   c                h   |                      |g||g d          }t          |d         d                   dk    rg S d |d         d         D             }t          t          j        |t          j                  |||          t          |          }	fdt          |	          D             }
|
S )	H  Return docs selected using the maximal marginal relevance.
        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.

        Returns:
            List of Documents selected by maximal marginal relevance.
        r   r  	distancesr   query_embeddings	n_resultsr   r  r   r   c                F    g | ]}t          t          |                    S r9   r   _bytes2embeddingr;   rM  s     r2   r>   z@VDMS.max_marginal_relevance_search_by_vector.<locals>.<listcomp>  6       39%f--..  r4   dtyper   r  c                "    g | ]\  }}|v 	|S r9   r9   )r;   irmmr_selecteds      r2   r>   z@VDMS.max_marginal_relevance_search_by_vector.<locals>.<listcomp>  s.          aqL7H7H7H7H7Hr4   )query_collection_embeddingsr0   r   rr  arrayfloat32r@   r/  r   rl   r   r   r  r   r   r5   embedding_list
candidatesselected_resultsr  s              @r2   r  z,VDMS.max_marginal_relevance_search_by_vectorh  s    4 22'[III	 3 
 
 wqz!}""I =DQZ]  N 6"*555'	  L *'22J       '
33      $#r4   c                   | j         t          d          t          j                            |          s+t          | j         d          r|                     |          }nt          j                            |          r3t          | j         d          r|                     |g          d         }nqt          j                            |          r3t          | j         d          r|                     |g          d         }nd	| d
}|dz  }|dz  }t          |          | 	                    |||||          }	|	S r  )
rl   r1   r  r:  r  r   r   r   r   2max_marginal_relevance_search_with_score_by_vector)
r   r   r   r   r  r   r   rl   r  r  s
             r2   (max_marginal_relevance_search_with_scorez-VDMS.max_marginal_relevance_search_with_score  sV   4 >!W   w~~e$$ 
	()O)O 
	())%00IIW^^E"" 	(wt~}'M'M 	())w)77:IIW^^E"" 	(wt~}'M'M 	()))88;IIL5LLLITTIQQIY'''FF# G 
 
 r4   c                h   |                      |g||g d          }t          |d         d                   dk    rg S d |d         d         D             }t          t          j        |t          j                  |||          t          |          }	fdt          |	          D             }
|
S )	r  r  r  r   r   c                F    g | ]}t          t          |                    S r9   r  r  s     r2   r>   zKVDMS.max_marginal_relevance_search_with_score_by_vector.<locals>.<listcomp>  r  r4   r  r  c                ,    g | ]\  }\  }}|v ||fS r9   r9   )r;   r  r  sr  s       r2   r>   zKVDMS.max_marginal_relevance_search_with_score_by_vector.<locals>.<listcomp>  s6          $1fq!lARARAARARARr4   )r  r0   r   rr  r  r  r?   r/  r  s              @r2   r  z7VDMS.max_marginal_relevance_search_with_score_by_vector  s    4 22'[III	 3 
 
 wqz!}""I =DQZ]  N 6"*555'	  L 5W==J       (1*(=(=      $#r4   r  Optional[List[List[float]]]r  !List[Tuple[Dict[str, Any], List]]c                    g }	|| j         }||	S |                    ddg          }
|d|
v r| j        d|
v d}|D ]9}|                     d|||||||          \  }}|	                    ||g           :|	S )Nr  r   r   )r   r&   rC   )r   r   r   r5   r   rl  )r   r  r   rw  rP   )r   r  rm   r  r   r   r5   r   r   all_responsesr  qembr   r   s                 r2   r  z VDMS.query_collection_embeddings
  s     $&""3O#  **Y66?{g552$/ G
 % 	= 	=D'+'C'C %"#5 $ (D 	( 	($Hn   (N!;<<<<r4   c                >     | j         |f|||d|}d |D             S )a  Run similarity search with VDMS.

        Args:
            query (str): Query to look up. Text or path for image or video.
            k (int): Number of results to return. Defaults to 3.
            fetch_k (int): Number of candidates to fetch for knn (>= k).
            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   r   c                    g | ]\  }}|S r9   r9   r:   s      r2   r>   z*VDMS.similarity_search.<locals>.<listcomp>I  s    222Q222r4   )r   )r   r   r   r   r   r   r   s          r2   similarity_searchzVDMS.similarity_search3  sJ    & <$;

 
:@
 
 32/2222r4   c                F     | j         d|g|||d|}t          |          S )a  Return docs most similar to embedding vector.
        Args:
            embedding (List[float]): Embedding to look up documents similar to.
            k (int): Number of Documents to return. Defaults to 3.
            fetch_k (int): Number of candidates to fetch for knn (>= k).
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
        Returns:
            List of Documents most similar to the query vector.
        r  r  r   r   r9   )r  r@   r   rl   r   r   r   r   r5   s          r2   similarity_search_by_vectorz VDMS.similarity_search_by_vectorK  sJ    " 3$2 
'[	
 

 
 
  (((r4   c                   | j         t          d          t          j                            |          s+t          | j         d          r|                     |          }nt          j                            |          r3t          | j         d          r|                     |g          d         }nqt          j                            |          r3t          | j         d          r|                     |g          d         }nd	| d
}|dz  }|dz  }t          |           | j	        d|g|||d|}t          |          S )aE  Run similarity search with VDMS with distance.

        Args:
            query (str): Query to look up. Text or path for image or video.
            k (int): Number of results to return. Defaults to 3.
            fetch_k (int): Number of candidates to fetch for knn (>= k).
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.

        Returns:
            List[Tuple[Document, float]]: List of documents most similar to
            the query text and cosine distance in float for each.
            Lower score represents more similarity.
        NrP  r   r   r   r   r   r  r  r  r  r  r  r9   )rl   r1   r  r:  r  r   r   r   r   r  r?   )	r   r   r   r   r   r   rl  r  r5   s	            r2   r   z!VDMS.similarity_search_with_scoref  sd   * >!>???7>>%(( 
,WT^]-S-S 
,/3/@/@/G/G&& ,74>=+Q+Q ,"&"3"3%"3"A"A!"D&& ,74>=+Q+Q ,"&"3"35'"3"B"B1"EPuPPP	XX	UU	 +++6d6 "1!2	 
  G +7333r4   c                F     | j         d|g|||d|}t          |          S )a6  
        Return docs most similar to embedding vector and similarity score.

        Args:
            embedding (List[float]): Embedding to look up documents similar to.
            k (int): Number of Documents to return. Defaults to 3.
            fetch_k (int): Number of candidates to fetch for knn (>= k).
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.

        Returns:
            List[Tuple[Document, float]]: List of documents most similar to
            the query text. Lower score represents more similarity.
        r  r9   )r  r?   r  s          r2   &similarity_search_with_score_by_vectorz+VDMS.similarity_search_with_score_by_vector  sJ    0 3$2 
'[	
 

 
 
 +7333r4   document_idr   c                4    |                      ||g|g          S )zUpdate a document in the collection.

        Args:
            document_id (str): ID of the document to update.
            document (Document): Document to update.
        )update_documents)r   rm   r  r   s       r2   update_documentzVDMS.update_document  s      $$_{mhZPPPr4   c                    d |D             }d |D             }|                      |          }|                     |||||           dS )zUpdate a document in the collection.

        Args:
            ids (List[str]): List of ids of the document to update.
            documents (List[Document]): List of documents to update.
        c                    g | ]	}|j         
S r9   r  r;   r   s     r2   r>   z)VDMS.update_documents.<locals>.<listcomp>  s    @@@(%@@@r4   c                6    g | ]}t          |j                  S r9   )r*  rL   r  s     r2   r>   z)VDMS.update_documents.<locals>.<listcomp>  s1     
 
 
=E%h&788
 
 
r4   )r   r   r  N)r   _VDMS__update)r   rm   r   r  r   rL   r   s          r2   r  zVDMS.update_documents  s     A@i@@@
 
IR
 
 
 **400
! 	 	
 	
 	
 	
 	
r4   )rh   rc   rl   rr   rm   r*   rn   rs   ro   rt   rp   ru   rq   rv   r,   r-   )r,   rr   )r   r   r,   r   )r   r   r   r   r,   r   )r   r   r,   r   )r   r*   r,   r   )r,   r   )r   r*   r   rb   r   rb   r   r   r   r   r,   rA   )NN)rm   r*   r   r   r   r   r   r   r   r   r,   r
   )r   r   )rm   r*   ro   rt   ry   rs   r,   r*   )rm   r*   r   r   r   r   r,   r   )NNNN)rm   r*   rL   r   rl   r   r   r   r$   r   r,   r   FF)rm   r*   r   r   r   r   r,   r   )r   r  r   r  r  r   r,   r	  r   )rm   r*   r   r   r  r   r   r   r   r   r,   r-   )rm   r*   r  r
   r  r  r,   r-   )r   r   r   r  r   r   r  rb   r   r   r   r   r,   r   )NNNr   T)r   r   r   r   r   r  r   r   r  rb   r   r   r   r   r,   r   )r   r<  r   r  r   r   r  rb   r   r   r,   r   )r   r   r   r   r   r   r   r  r  rb   r   r   r,   r   )rm   r*   rq   rN  r,   r-   )rm   r*   r,   rb   )rY  r*   r,   rZ  )NNN)
r   r   rm   r   r   r_  r   r   r,   r   )NNF)rd  r*   r   rv   r5   r   r   r  re  r   r,   rf  )ri  r*   rd  r*   r   rb   r   rb   r   rk  r5   r   rl  rm  r   r   r,   rn  )r#  r*   r,   r*   )r  r  r  r6   rl   rr   r   r   r  rb   rm   r*   r   r   r,   rk   )r  r  r   r   rl   rr   r   r  r   r   r  rb   rm   r*   r   r   r,   rk   )
rm   r*   r   r_  r  rv   r  r   r,   r	  )r   r*   r   rb   r   rb   r  r  r   r  r   r   r,   r6   )rl   r   r   rb   r   rb   r  r  r   r  r   r   r,   r6   )r   r*   r   rb   r   rb   r  r  r   r  r   r   r,   rA   )rl   r   r   rb   r   rb   r  r  r   r  r   r   r,   rA   )r  r  rm   r   r  rb   r   rb   r   r   r5   r   r   r   r   r   r,   r  )r   r*   r   rb   r   rb   r   r  r   r   r,   r6   )rl   r   r   rb   r   rb   r   r  r   r   r,   r6   )r   r*   r   rb   r   rb   r   r  r   r   r,   rA   )rl   r   r   rb   r   rb   r   r  r   r   r,   rA   )rm   r*   r  r*   r   r   r,   r-   )rm   r*   r   r   r  r6   r,   r-   )3__name__
__module____qualname____doc__DEFAULT_COLLECTION_NAMEr   propertyr   r   r   r   r   r   	DEFAULT_KDEFAULT_FETCH_Kr   r   r~   ra  r   r   r   r  r  DEFAULT_INSERT_BATCH_SIZEr3  r;  rB  r0  r|   rW  r^  rc  rj  rw  r$  classmethodr  r  r  r  r  r  r  r  r  r  r   r  r  r  r9   r4   r2   rk   rk      s       $ $T +/6.2%AE.2
 
 
 
 
 
8    X$ $ $ $            4 &+/# # # # #D HL#'    H &#'	    0 '+37	+/ +/ +/ +/ +/` #'.2"& 6
 6
 6
 6
 6
v ).#(	% % % % %& %'.3	( ( ( ( (& HL9
 9
 9
 9
 9
vM M M M. +/#'3#'6 6 6 6 6v &**.#'#'6 6 6 6 6v +/#'3' ' ' ' '\ +/3# # # # #J6B 6B 6B 6Bp9 9 9 9,. . . .
 $()-&*	E E E E E. -1$($)2 2 2 2 26 %&&*,015#(J( J( J( J( J(X: : : :
  +/#'36 
  
  
  
 [ 
D  +/*.#'36& & & & [&V '+#(\0( 0( 0( 0( 0(j & ,04 4 4 4 4r & ,05$ 5$ 5$ 5$ 5$t & ,02 2 2 2 2n & ,05$ 5$ 5$ 5$ 5$r 9=)-"&.2/3#(' ' ' ' 'X &,03 3 3 3 36 &,0) ) ) ) )< &,0,4 ,4 ,4 ,4 ,4b &,04 4 4 4 4B	Q 	Q 	Q 	Q
 
 
 
 
 
r4   rk   ri  rd  r   r   r   rv   r\   rk  r   r   r   Dict[str, Dict[str, Any]]c	                    d|i}	d| v r|r||	d<   |||	d<   |t           vr||	d<   d| v r|||	d<   d| v r|t          |          |	d<   d| v r|t           vr||	d	<   d| v r|t           vr||	d
<   | |	i}
|
S )NsetAddr   _ref
propertiesr   Findr   r   r5   )rG   rb   )ri  rd  r   r   r\   r   r   r   r5   entityr   s              r2   r   r     s     $W-Fw
v***$| 0v!8 #K 0 0}4J!J!J +}0F!F!F#y&!ELr4   Frb  num_dimsro   ry   r_  r   r   Dict[str, Any]c                   | dk    rHt          d ||fD                       r-||d}|||d<   |||d<   |||d<   |d i fvr||d<   |||d<   n6| d	k    rd
|i}|r||d<   |	d i fvr|	|d<   |
|
|d<   nt          d|            | |i}|S )Nr   c              3     K   | ]}|d uV  	d S r   r9   )r;   vars     r2   	<genexpr>z%_add_descriptorset.<locals>.<genexpr>  s7       1 141 1 1 1 1 1r4   )rb  
dimensionsro   ry   r  r  r   r   r  r   r   r5   zUnknown command: )allr1   )ri  rb  r  ro   ry   r   r\   r   r   r   r5   r  r   s                r2   r   r     s&    (((S 1 1$((#31 1 1 . .( ""
 "

 %F8%F8? F6Nr
""#(F< !F6N	+	+	+ 	.#-F< tRj(($/F=! 'F9 :[::;;;&!ELr4   rm   r  r
   Tuple[Dict[str, Any], bytes]c                    t          |          dk    rd                    |          nd}d}i }d|d<   d|d<   d	| i}d
|d<   ||d<   ||d<   t          |          }i }|||<   ||fS )Nr   r   r   	AddEntityr  classTr&   rb  zqueryable propertiestyper%   )r0   join
_str2bytes)rm   r  all_properties_str	querytyper  r\   	byte_datar   s           r2   _add_entity_with_blobr  8  s     695H5H15L5L.111RTIF"F7OF6N#_5E*E&M)E) F<-..IEE))r4   findr  r	  c                   g }g }g d}|                                 |vr5t          d                    d                    |                              |                                 dk    r't	          | d          }|                    |           n|                                 dk    r>t          | |          \  }}|                    |           |                    |           n{|                                 dk    rct	          | d	          }|                    |           t          | |          \  }}|                    |           |                    |           ||fS )
N)r  r   r   z"[!] Invalid type. Choices are : {}r   r  T)r   r   r   )r   )r   r1   formatr  r   rP   r  )	rm   r  r  r   r   r  choicesr   r  s	            r2   r  r  N  sq     KH'''G7**=DDSXXgEVEVWWXXXv%%%oTJJJ5!!!!						&	&0.QQy5!!!	""""						)	)%oEEE5!!! 1.QQy5!!!	"""  r4   r&   rZ  c                2    t          j        | d          }|S )Nr  r  )rr  
frombuffer)r&   r   s     r2   r  r  q  s    
-I
.
.
.CJr4   in_bytesc                *    |                                  S r   )r}  )r  s    r2   r   r   v  s    ??r4   r   r   r   c                N    t          t          d | D                                 S )Nc                @    g | ]}|                                 D ]}|S r9   )r   )r;   qr   s      r2   r>   z(_get_cmds_from_query.<locals>.<listcomp>{  s-    >>>1QVVXX>>Q>>>>r4   )r   r  )r   s    r2   _get_cmds_from_queryr
  z  s'    >>>>>??@@@r4   
List[dict]r   c                    t          |           }t          t                    ot          fd|D                       }|S )Nc              3  |   K   | ]6}|d          v o'dd          |         v od          |         d         d k    V  7dS )r   rX  Nr9   )r;   cmdr   s     r2   r  z(_check_valid_response.<locals>.<genexpr>  ss       3 3  	x{ 	-(1+c**	-QKZ(1,3 3 3 3 3 3r4   )r
  r/   r   any)r   r   cmd_list	valid_ress    `  r2   r  r  ~  s`    #K00H8T** s 3 3 3 3 	3 3 3 0 0I r4   rh   r$   Tuple[bool, Any]c                    dd|gi}t          d||dgdd          }|g}|                     |          \  }}t          ||          }||fS )Nr$   r   rC   r   )r   rW  rp  )r   r   r  )	rh   rd  r$   r   findDescriptorr   resr=   r  s	            r2   r   r     su    
 $$K$"--	  N ""K\\+&&FC%k377In$$r4   rl   r   Union[bytes, None]c                b    d}| *t          j        | d          }|                                }|S )zConvert embedding to bytes.Nr  r  )rr  r  tobytes)rl   r&   r   s      r2   r   r     s5     Dhy	222{{}}Kr4   r   r   r   c                    d}i }d|d<   |r||d<   i }d|d<   d|d<   d	g|d
<   ||d<   i }|rddg|d<   d| g|d<   ||d<   i }|||<   |S )N
FindEntityr  r  uniqueTr&   r   rW  r%   r   r5   r   r   r   rb  r   r9   )rm   r   r   r  r  r5   r   r   s           r2   r   r     s    
 IF"F7O )(x GGFOGG kGFOF9"$K -$(!9K 1K'F=EE)Lr4   in_strc                6    t                               |           S r   )r*   encode)r  s    r2   r  r    s    ::fr4   rL   r   c                    i }|                                  D ],\  }}t          |t                    s||t          |          <   -|S r   )rO   r/   r   r*   )rL   new_metadatakeyr   s       r2   r*  r*    sM    #%Lnn&& + +
U%&& 	+%*LS"r4   )
r'   r   r(   r   r)   r*   r+   r*   r,   r-   )r5   r   r,   r6   )r5   r   r,   rA   )r^   r_   )r`   r*   ra   rb   r,   rc   )NNNNNNN)ri  r*   rd  r*   r   r   r   rv   r\   rk  r   rk  r   rv   r   rk  r5   rk  r,   r  )	NNNNNNFNN)ri  r*   rb  r*   r  rv   ro   r   ry   r   r   rv   r\   r_  r   r_  r   r   r   r_  r5   r_  r,   r  )rm   r*   r  r
   r,   r  )
rm   r*   r  r*   r  r
   r   rv   r,   r	  )r&   rZ  r,   r   )r  rZ  r,   r*   )r   r   r,   r   )r   r  r   r   r,   r   )rh   rc   rd  r*   r$   r*   r,   r  )rl   r   r,   r  r  )rm   r*   r   r   r   r   r,   r  )r  r*   r,   rZ  )rL   r  r,   r   )C
__future__r   r\  loggingr  r   copyr   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   numpyrr  langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   &langchain_community.vectorstores.utilsr   re   rs   r   r   __annotations__rt   r   r  r  r  r  r  rN   rG   	getLoggerr  rR   r3   r@   r?   ri   rk   r   r   r  r  r  r   r
  r  r   r   r   r  r*  r9   r4   r2   <module>r-     s   " " " " " " "   				                                          - - - - - - 0 0 0 0 0 0 3 3 3 3 3 3 M M M M M M KKK 
  6:T((CS:T:T5U5U  U U U U
 $(4(9(9#:#:  : : : :%  	a-333 <<< ,dB7  
	8	$	$   $D D D D   >    (N
 N
 N
 N
 N
; N
 N
 N
n*   !%"&"# # # # #R #   "&"4 4 4 4 4n   0 	 !  !  !  !  !F   
   A A A A   % % % %&    %*$    8        r4   