
    Ng P                        d dl mZ d dlZd dlZd dlmZmZ d dlZd dl	m
Z
  ej        e          Zerd dlZd dlZ	 	 	 	 	 	 	 	 	 	 d'd(dZ	 	 	 	 	 	 	 	 	 	 d'd)d!Z	 	 d*d+d&ZdS ),    )annotationsN)TYPE_CHECKINGLiteral)Tensorfloat32
   T   Fquery_embeddings
np.ndarraycorpus_embeddingsnp.ndarray | Nonecorpus_indexfaiss.Index | Nonecorpus_precision&Literal['float32', 'uint8', 'ubinary']top_kintrangescalibration_embeddingsrescoreboolrescore_multiplierexactoutput_indexreturn=tuple[list[list[dict[str, int | float]]], float, faiss.Index]c                   ddl }|t          d          |t          d          |dv r;|	r |j        |j        d                   nc |j        |j        d         d          nF|dk    r@|	r |j        |j        d         d	z            n |j        |j        d         d	z  d                              |           d}|}| j        t          j
        t          j        fvr>|r(|d
k    r| }||z  }nt                              d           t          | |||          } n|rt                              d           t          j                    }                    | |          \  |t          j        fdD                       }|dk    r/t          j        |d                              t(                    }n|                    t(                    }t          j        d||          }t          j        |           ddd|f         }t          j        t1          |                     dddf         |f         |t          j        t1          |                     dddf         |f         t          j                    |z
  }fdt3          t1          |                     D             |f}|
rg |R }|S )a"  
    Performs semantic search using the FAISS library.

    Rescoring will be performed if:
    1. `rescore` is True
    2. The query embeddings are not quantized
    3. The corpus is quantized, i.e. the corpus precision is not float32
    Only if these conditions are true, will we search for `top_k * rescore_multiplier` samples and then rescore to only
    keep `top_k`.

    Args:
        query_embeddings: Embeddings of the query sentences. Ideally not
            quantized to allow for rescoring.
        corpus_embeddings: Embeddings of the corpus sentences. Either
            `corpus_embeddings` or `corpus_index` should be used, not
            both. The embeddings can be quantized to "int8" or "binary"
            for more efficient search.
        corpus_index: FAISS index for the corpus sentences. Either
            `corpus_embeddings` or `corpus_index` should be used, not
            both.
        corpus_precision: Precision of the corpus embeddings. The
            options are "float32", "int8", or "binary". Default is
            "float32".
        top_k: Number of top results to retrieve. Default is 10.
        ranges: Ranges for quantization of embeddings. This is only used
            for int8 quantization, where the ranges refers to the
            minimum and maximum values for each dimension. So, it's a 2D
            array with shape (2, embedding_dim). Default is None, which
            means that the ranges will be calculated from the
            calibration embeddings.
        calibration_embeddings: Embeddings used for calibration during
            quantization. This is only used for int8 quantization, where
            the calibration embeddings can be used to compute ranges,
            i.e. the minimum and maximum values for each dimension.
            Default is None, which means that the ranges will be
            calculated from the query embeddings. This is not
            recommended.
        rescore: Whether to perform rescoring. Note that rescoring still
            will only be used if the query embeddings are not quantized
            and the corpus is quantized, i.e. the corpus precision is
            not "float32". Default is True.
        rescore_multiplier: Oversampling factor for rescoring. The code
            will now search `top_k * rescore_multiplier` samples and
            then rescore to only keep `top_k`. Default is 2.
        exact: Whether to use exact search or approximate search.
            Default is True.
        output_index: Whether to output the FAISS index used for the
            search. Default is False.

    Returns:
        A tuple containing a list of search results and the time taken
        for the search. If `output_index` is True, the tuple will also
        contain the FAISS index used for the search.

    Raises:
        ValueError: If both `corpus_embeddings` and `corpus_index` are
            provided or if neither is provided.

    The list of search results is in the format: [[{"corpus_id": int, "score": float}, ...], ...]
    The time taken for the search is a float value.
    r   N@Only corpus_embeddings or corpus_index should be used, not both.8Either corpus_embeddings or corpus_index should be used.)r   uint8      ubinary   r   zRescoring is enabled but the corpus is not quantized. Either pass `rescore=False` or quantize the corpus embeddings with `quantize_embeddings(embeddings, precision="...") `and pass `corpus_precision="..."` to `semantic_search_faiss`.	precisionr   r   Rescoring is enabled but the query embeddings are quantized. Either pass `rescore=False` or don't quantize the query embeddings.c                ,    g | ]}fd |D             S )c                ^    g | ])}                     |                                          *S  )reconstructitem).0idxr   s     ^/var/www/html/ai-engine/env/lib/python3.11/site-packages/sentence_transformers/quantization.py
<listcomp>z4semantic_search_faiss.<locals>.<listcomp>.<listcomp>   s/    LLLsl&&sxxzz22LLL    r*   r-   query_indicesr   s     r/   r0   z)semantic_search_faiss.<locals>.<listcomp>   s/    jjjQ^LLLLmLLLjjjr1   axis
ij,ikj->ikc                \    g | ](}d  t          |         |                   D             )S )c                R    g | ]$\  }}t          |          t          |          d %S )	corpus_idscorer   floatr-   r<   neighbors      r/   r0   z4semantic_search_faiss.<locals>.<listcomp>.<listcomp>   @       #E8 "(mmeEllCC  r1   zipr-   query_idindicesscoress     r/   r0   z)semantic_search_faiss.<locals>.<listcomp>   V     	
 	
 	

 	 '*6(+;WX=N'O'O  	
 	
 	
r1   )faiss
ValueErrorIndexFlatIPshapeIndexHNSWFlatIndexBinaryFlatIndexBinaryHNSWadddtypenpr    int8loggerwarningquantize_embeddingstimesearcharray
unpackbitsastyper   einsumargsortarangelenrange)r
   r   r   r   r   r   r   r   r   r   r   rI   rescore_embeddingskstart_ttop_k_embeddingsrescored_scoresrescored_indicesdelta_toutputsrF   rG   s     `                 @@r/   semantic_search_faissri      sw   T LLL$)A[\\\ \%9STTT 333 S0u01B1H1KLL2u23D3J13MrRR** Y4u45F5LQ5ORS5STT4u45F5LQ5ORS5SUWXX*+++
 Abh%888 		9,,%5"''T   /&#9	
 
 
 
 
 O	
 	
 	

 ikkG"))*:A>>OFG %8jjjjbijjj
 
 y((!}-=BGGGNNsSS/66s;; )L2DFVWW:&6776E6	B")C(8$9$9::111d7CEUUV 3/?+@+@!A!A!!!T'!JL\!\]ikkG#G	
 	
 	
 	
 	

 "#&6"7"788	
 	
 	
 		G  +*G*\**Nr1   usearch.index.Index | None$Literal['float32', 'int8', 'binary']Etuple[list[list[dict[str, int | float]]], float, usearch.index.Index]c                   ddl m} ddlm} |t	          d          |t	          d          |dvrt	          d          |d	k    r ||j        d
         dd          nb|dk    r ||j        d
         dd          nB|dk    r ||j        d
         dd          n"|dk    r ||j        d
         dz  dd                              t          j        t          |                    |           d}|}| j
        t          j        t          j        fvrH|r2j
        |j        k    r| }||z  }nt                              d           t!          | |||          } n|rt                              d           t#          j                    }                    | ||	          }|j        |j        j        dk     rt          j                  j        dk     rt          j                  |t          j        fdD                       }|dv r3t          j        |                    t          j                  d          }|                    t4                    }t          j        d||          }t          j        |           ddd|f         }t          j        t          |                     dddf         |f         |t          j        t          |                     dddf         |f         t#          j                    |z
  }fd t;          t          |                     D             |f}|
rg |R }|S )!a4  
    Performs semantic search using the usearch library.

    Rescoring will be performed if:
    1. `rescore` is True
    2. The query embeddings are not quantized
    3. The corpus is quantized, i.e. the corpus precision is not float32
    Only if these conditions are true, will we search for `top_k * rescore_multiplier` samples and then rescore to only
    keep `top_k`.

    Args:
        query_embeddings: Embeddings of the query sentences. Ideally not
            quantized to allow for rescoring.
        corpus_embeddings: Embeddings of the corpus sentences. Either
            `corpus_embeddings` or `corpus_index` should be used, not
            both. The embeddings can be quantized to "int8" or "binary"
            for more efficient search.
        corpus_index: usearch index for the corpus sentences. Either
            `corpus_embeddings` or `corpus_index` should be used, not
            both.
        corpus_precision: Precision of the corpus embeddings. The
            options are "float32", "int8", "ubinary" or "binary". Default
            is "float32".
        top_k: Number of top results to retrieve. Default is 10.
        ranges: Ranges for quantization of embeddings. This is only used
            for int8 quantization, where the ranges refers to the
            minimum and maximum values for each dimension. So, it's a 2D
            array with shape (2, embedding_dim). Default is None, which
            means that the ranges will be calculated from the
            calibration embeddings.
        calibration_embeddings: Embeddings used for calibration during
            quantization. This is only used for int8 quantization, where
            the calibration embeddings can be used to compute ranges,
            i.e. the minimum and maximum values for each dimension.
            Default is None, which means that the ranges will be
            calculated from the query embeddings. This is not
            recommended.
        rescore: Whether to perform rescoring. Note that rescoring still
            will only be used if the query embeddings are not quantized
            and the corpus is quantized, i.e. the corpus precision is
            not "float32". Default is True.
        rescore_multiplier: Oversampling factor for rescoring. The code
            will now search `top_k * rescore_multiplier` samples and
            then rescore to only keep `top_k`. Default is 2.
        exact: Whether to use exact search or approximate search.
            Default is True.
        output_index: Whether to output the usearch index used for the
            search. Default is False.

    Returns:
        A tuple containing a list of search results and the time taken
        for the search. If `output_index` is True, the tuple will also
        contain the usearch index used for the search.

    Raises:
        ValueError: If both `corpus_embeddings` and `corpus_index` are
            provided or if neither is provided.

    The list of search results is in the format: [[{"corpus_id": int, "score": float}, ...], ...]
    The time taken for the search is a float value.
    r   )
ScalarKind)IndexNr   r   )r   rS   r#   binaryzKcorpus_precision must be "float32", "int8", "ubinary", "binary" for usearchr   r!   cosf32)ndimmetricrQ   rS   ipi8rp   hammingr#   r$   b1zRescoring is enabled but the corpus is not quantized. Either pass `rescore=False` or quantize the corpus embeddings with `quantize_embeddings(embeddings, precision="...") `and pass `corpus_precision="..."` to `semantic_search_usearch`.r%   r'   )countr   r	   c                :    g | ]}                     |          S r*   )getr2   s     r/   r0   z+semantic_search_usearch.<locals>.<listcomp>R  s'    $b$b$b\%5%5m%D%D$b$b$br1   )r#   rp   r4   r5   r7   c                \    g | ](}d  t          |         |                   D             )S )c                R    g | ]$\  }}t          |          t          |          d %S r:   r=   r?   s      r/   r0   z6semantic_search_usearch.<locals>.<listcomp>.<listcomp>f  rA   r1   rB   rD   s     r/   r0   z+semantic_search_usearch.<locals>.<listcomp>e  rH   r1   )usearch.compiledrn   usearch.indexro   rJ   rL   rP   rR   r^   r_   rQ   r    rS   F32rT   rU   rV   rW   rX   	distanceskeysrs   
atleast_2drY   rZ   r[   r   r\   r]   r`   )r
   r   r   r   r   r   r   r   r   r   r   rn   ro   ra   rb   rc   matchesrd   re   rf   rg   rh   rF   rG   s     `                   @@r/   semantic_search_usearchr      s7   T ,+++++######$)A[\\\ \%9STTTGGGfggg y(( 5&,Q/  LL
 '' 5&,Q/  LL
 )) 5&,Q/   LL
 ** 5&,Q/!3   L
 	3'8#9#9::<MNNN
 Abh%888 		!Z^33%5"''V   /&#9	
 
 
 
 
 O	
 	
 	

 ikkG!!"2!5!IIGFlG{Qv&&|a-(( %8$b$b$b$bZa$b$b$bcc444!}-=-D-DRX-N-NUWXXX+22377 )L2DFVWW:&6776E6	B")C(8$9$9::111d7CEUUV 3/?+@+@!A!A!!!T'!JL\!\]ikkG#G	
 	
 	
 	
 	

 "#&6"7"788	
 	
 	
 		G  +*G*\**Nr1   
embeddingsTensor | np.ndarrayr&   8Literal['float32', 'int8', 'uint8', 'binary', 'ubinary']c                   t          | t                    r'|                                                                 } nPt          | t                    r;t          | d         t                    rd | D             } t          j        |           } | j        t
          j        t
          j	        fv rt          d          |dk    r|                     t
          j                  S |                    d          r\||?t          j        t          j        |d          t          j        |d          f          }n| j        d         dk     rIt$                              d	| d
t)          |            dt)          |           dk    rdnd d| d	           t          j        t          j        | d          t          j        | d          f          }|dddf         }|dddf         |dddf         z
  dz  }|dk    r%| |z
  |z                      t
          j                  S |dk    r(| |z
  |z  dz
                      t
          j	                  S |dk    rWt          j        | dk                                  | j        d         d          dz
                      t
          j	                  S |dk    r7t          j        | dk                                  | j        d         d          S t/          d| d          )a{  
    Quantizes embeddings to a lower precision. This can be used to reduce the memory footprint and increase the
    speed of similarity search. The supported precisions are "float32", "int8", "uint8", "binary", and "ubinary".

    Args:
        embeddings: Unquantized (e.g. float) embeddings with to quantize
            to a given precision
        precision: The precision to convert to. Options are "float32",
            "int8", "uint8", "binary", "ubinary".
        ranges (Optional[np.ndarray]): Ranges for quantization of
            embeddings. This is only used for int8 quantization, where
            the ranges refers to the minimum and maximum values for each
            dimension. So, it's a 2D array with shape (2,
            embedding_dim). Default is None, which means that the ranges
            will be calculated from the calibration embeddings.
        calibration_embeddings (Optional[np.ndarray]): Embeddings used
            for calibration during quantization. This is only used for
            int8 quantization, where the calibration embeddings can be
            used to compute ranges, i.e. the minimum and maximum values
            for each dimension. Default is None, which means that the
            ranges will be calculated from the query embeddings. This is
            not recommended.

    Returns:
        Quantized embeddings with the specified precision
    r   c                Z    g | ](}|                                                                 )S r*   )cpunumpy)r-   	embeddings     r/   r0   z'quantize_embeddings.<locals>.<listcomp>  s,    NNNi)--////11NNNr1   z?Embeddings to quantize must be float rather than int8 or uint8.r   rS   Nr5   d   z
Computing z quantization buckets based on z
 embeddingr!   s z. z quantization is more stable with `ranges` calculated from more embeddings or a `calibration_embeddings` that can be used to calculate the buckets.   r       rp   r4   r#   z
Precision z is not supported)
isinstancer   r   r   listrR   rY   rQ   r    rS   	Exceptionr[   r   endswithvstackminmaxrL   rT   rU   r_   packbitsreshaperJ   )r   r&   r   r   startsstepss         r/   rV   rV   s  s/   @ *f%% *^^%%++--

	J	%	% *jmV,, 	ONN:NNNJXj))
BHbg...YZZZI  ,,,&!! I>%1BF+A$J$J$JBFSipqLrLrLr#stt#A&,,NNcY c csS] c cqtu  rA  rA  EF  rF  rFjmjm  LN c c%c c c  
 BF:A$>$>$>zXY@Z@Z@Z#[\\111111q!!!t,3&(E199"(CCC&  &(E1C7??HHHHJN++33J4DQ4GLLsRZZ[][bcccI{:>**22:3CA3FKKK
>)>>>
?
??r1   )
NNr   r   NNTr	   TF)r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r
   r   r   r   r   rj   r   rk   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rl   )NN)
r   r   r&   r   r   r   r   r   r   r   )
__future__r   loggingrW   typingr   r   r   rR   torchr   	getLogger__name__rT   rI   usearchri   r   rV   r*   r1   r/   <module>r      sD   " " " " " "   ) ) ) ) ) ) ) )          		8	$	$  LLLNNN
 ,0'+?H $04d d d d dR ,0/3=F $04w w w w wz !%04	G@ G@ G@ G@ G@ G@ G@r1   