ó
    >:jØC  ã            
      óª  • S SK Jr  S SKrS SKrS SKrS SKJr  S SKJr  S SK	r
S SKrS SKJr  S SKJr  SSKJr  SS	KJr  \R&                  " \5      r\(       a  S S
KJr  SSSSSS\SSS4
                         SS jjrSSSS\4             SS jjrSS jrSSS\4             SS jjr    S           SS jjrg)é    )ÚannotationsN)ÚCallable)ÚTYPE_CHECKING)ÚTensor)Útqdmé   )Úcos_sim)Únormalize_embeddings)ÚSentenceTransformerFé    iˆ  i † i ¡ éd   c           
     óH   • U R                  UUUSU	U
US9n[        UUUUUUS9$ )aà  
Given a list of sentences / texts, this function performs paraphrase mining. It compares all sentences against all
other sentences and returns a list with the pairs that have the highest cosine similarity score.

Args:
    model (SentenceTransformer): SentenceTransformer model for embedding computation
    sentences (List[str]): A list of strings (texts or sentences)
    show_progress_bar (bool, optional): Plotting of a progress bar. Defaults to False.
    batch_size (int, optional): Number of texts that are encoded simultaneously by the model. Defaults to 32.
    query_chunk_size (int, optional): Search for most similar pairs for #query_chunk_size at the same time. Decrease, to lower memory footprint (increases run-time). Defaults to 5000.
    corpus_chunk_size (int, optional): Compare a sentence simultaneously against #corpus_chunk_size other sentences. Decrease, to lower memory footprint (increases run-time). Defaults to 100000.
    max_pairs (int, optional): Maximal number of text pairs returned. Defaults to 500000.
    top_k (int, optional): For each sentence, we retrieve up to top_k other sentences. Defaults to 100.
    score_function (Callable[[Tensor, Tensor], Tensor], optional): Function for computing scores. By default, cosine similarity. Defaults to cos_sim.
    truncate_dim (int, optional): The dimension to truncate sentence embeddings to. If None, uses the model's ones. Defaults to None.
    prompt_name (Optional[str], optional): The name of a predefined prompt to use when encoding the sentence.
        It must match a key in the model `prompts` dictionary, which can be set during model initialization
        or loaded from the model configuration.

        Ignored if `prompt` is provided. Defaults to None.

    prompt (Optional[str], optional): A raw prompt string to prepend directly to the input sentence during encoding.

        For instance, `prompt="query: "` transforms the sentence "What is the capital of France?" into:
        "query: What is the capital of France?". Use this to override the prompt logic entirely and supply your own prefix.
        This takes precedence over `prompt_name`. Defaults to None.

Returns:
    List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
T)Úshow_progress_barÚ
batch_sizeÚconvert_to_tensorÚtruncate_dimÚprompt_nameÚprompt)Úquery_chunk_sizeÚcorpus_chunk_sizeÚ	max_pairsÚtop_kÚscore_function)ÚencodeÚparaphrase_mining_embeddings)ÚmodelÚ	sentencesr   r   r   r   r   r   r   r   r   r   Ú
embeddingss                Úa/home/mande/repo/quber/.venv/lib/python3.13/site-packages/sentence_transformers/util/retrieval.pyÚparaphrase_miningr       sN   € ð\ —‘ØØ+ØØØ!ØØð ð €Jô (ØØ)Ø+ØØØ%ñð ó    c                ó  • US-  n[         R                  " 5       nSnSn[        S[        U 5      U5       GH*  n	[        S[        U 5      U5       GH  n
U" X
X¡-    X	X’-    5      n[        R
                  " U[        U[        US   5      5      SSSS9u  pÍUR                  5       R                  5       nUR                  5       R                  5       n[        [        U5      5       Hr  n[        XÞ   5       H^  u  nnX®-   nU	U-   nUU:w  d  M  XÎ   U   U:”  d  M$  UR                  XÎ   U   UU45        US-  nXƒ:¼  d  MI  UR                  5       nUS   nM`     Mt     GM     GM-     [        5       n/ nUR                  5       (       dp  UR                  5       u  nnn[        UU/5      u  nnUU:w  a/  UU4U;  a'  UR                  UU45        UR!                  UUU/5        UR                  5       (       d  Mp  [        US SS9nU$ )	a¼  
Given a list of sentences / texts, this function performs paraphrase mining. It compares all sentences against all
other sentences and returns a list with the pairs that have the highest cosine similarity score.

Args:
    embeddings (Tensor): A tensor with the embeddings
    query_chunk_size (int): Search for most similar pairs for #query_chunk_size at the same time. Decrease, to lower memory footprint (increases run-time).
    corpus_chunk_size (int): Compare a sentence simultaneously against #corpus_chunk_size other sentences. Decrease, to lower memory footprint (increases run-time).
    max_pairs (int): Maximal number of text pairs returned.
    top_k (int): For each sentence, we retrieve up to top_k other sentences
    score_function (Callable[[Tensor, Tensor], Tensor]): Function for computing scores. By default, cosine similarity.

Returns:
    List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
r   éÿÿÿÿr   TF©ÚdimÚlargestÚsortedc                ó   • U S   $ )Nr   © ©Úxs    r   Ú<lambda>Ú.paraphrase_mining_embeddings.<locals>.<lambda>ž   s   € °!°A²$r!   ©ÚkeyÚreverse)ÚqueueÚPriorityQueueÚrangeÚlenÚtorchÚtopkÚminÚcpuÚtolistÚ	enumerateÚputÚgetÚsetÚemptyr'   ÚaddÚappend)r   r   r   r   r   r   ÚpairsÚ	min_scoreÚ	num_addedÚcorpus_start_idxÚquery_start_idxÚscoresÚscores_top_k_valuesÚscores_top_k_idxÚ	query_itrÚ	top_k_idxÚ
corpus_itrÚiÚjÚentryÚadded_pairsÚ
pairs_listÚscoreÚsorted_iÚsorted_js                            r   r   r   Y   s
  € ð0 
ˆQ�J€Eô ×ÒÓ!€EØ€IØ€Iä! !¤S¨£_Ð6G×HÐÜ$ Q¬¨J«Ð9I×JˆOÙ#Ø¨_Ñ-OÐPØÐ.>Ñ.RÐSóˆFô
 5:·J²JØœ˜E¤3 v¨a¡y£>Ó2¸À4ÐPUñ5Ñ1Ðð #6×"9Ñ"9Ó";×"BÑ"BÓ"DÐØ/×3Ñ3Ó5×<Ñ<Ó>Ðä"¤3 v£;Ö/�	Ü-6Ð7GÑ7RÖ-SÑ)�I˜zØ'Ñ3�AØ(¨:Ñ5�Aà˜A•vÐ"5Ñ"@ÀÑ"KÈiÕ"WØŸ	™	Ð#6Ñ#AÀ)Ñ#LÈaÐQRÐ"SÔTØ! Q™˜	à$Õ1Ø$)§I¡I£K˜EØ(-¨a©šIó .Tô 0ô  Kñ Iô6 “%€KØ€JØ�k‰k�m‰mØ—i‘i“k‰ˆˆq�!Ü# Q¨ F›^Ñˆ�(à�xÓ X¨xÐ$8ÀÓ$KØ�O‰O˜X xÐ0Ô1Ø×Ñ˜u h°Ð9Ô:ð �k‰k�m‹mô ˜
©ÀÑE€JØÐr!   c                 ó   • [        U 0 UD6$ )z8This function is deprecated. Use semantic_search instead)Úsemantic_search)ÚargsÚkwargss     r   Úinformation_retrievalrX   ¢   s   € ä˜DÐ+ FÑ+Ð+r!   é
   c                ó”  • [        U [        R                  [        R                  45      (       a  [        R
                  " U 5      n O+[        U [        5      (       a  [        R                  " U 5      n [        U R                  5      S:X  a  U R                  S5      n [        U[        R                  [        R                  45      (       a  [        R
                  " U5      nO+[        U[        5      (       a  [        R                  " U5      nUR                  U R                  :w  a  U R                  UR                  5      n [        [        U 5      5       Vs/ s H  n/ PM     nn[        S[        U 5      U5       GHá  n[        X‚-   [        U 5      5      n	U R                  (       a2  [        R                   " X‰U R                  S9n
U R#                  SU
5      nOXU	 n[        S[        U5      U5       GHd  n[        XÃ-   [        U5      5      nUR                  (       a2  [        R                   " XÍUR                  S9n
UR#                  SU
5      nOXU nU" X¾5      n[        R$                  " U[        U[        US   5      5      SSSS9u  nnUR'                  5       R)                  5       nUR'                  5       R)                  5       n[        [        U5      5       Hu  n[+        UU   UU   5       H\  u  nnUU-   nUU-   n[        UU   5      U:  a  [,        R.                  " UU   UU45        M@  [,        R0                  " UU   UU45        M^     Mw     GMg     GMä     [        [        U5      5       HI  n[        [        UU   5      5       H  nUU   U   u  nnUUS.UU   U'   M     [3        UU   S SS	9UU'   MK     U$ s  snf )
a  
This function performs by default a cosine similarity search between a list of query embeddings  and a list of corpus embeddings.
It can be used for Information Retrieval / Semantic Search for corpora up to about 1 Million entries.

Args:
    query_embeddings (:class:`~torch.Tensor`): A 2 dimensional tensor with the query embeddings. Can be a sparse tensor.
    corpus_embeddings (:class:`~torch.Tensor`): A 2 dimensional tensor with the corpus embeddings. Can be a sparse tensor.
    query_chunk_size (int, optional): Process 100 queries simultaneously. Increasing that value increases the speed, but requires more memory. Defaults to 100.
    corpus_chunk_size (int, optional): Scans the corpus 100k entries at a time. Increasing that value increases the speed, but requires more memory. Defaults to 500000.
    top_k (int, optional): Retrieve top k matching entries. Defaults to 10.
    score_function (Callable[[:class:`~torch.Tensor`, :class:`~torch.Tensor`], :class:`~torch.Tensor`], optional): Function for computing scores. By default, cosine similarity.

Returns:
    List[List[Dict[str, Union[int, float]]]]: A list with one entry for each query. Each entry is a list of dictionaries with the keys 'corpus_id' and 'score', sorted by decreasing cosine similarity scores.
r   r   ©ÚdeviceTFr$   )Ú	corpus_idrQ   c                ó   • U S   $ )NrQ   r)   r*   s    r   r,   Ú!semantic_search.<locals>.<lambda>ý   s   € Ð\]Ð^eÒ\fr!   r.   )Ú
isinstanceÚnpÚndarrayÚgenericr5   Ú
from_numpyÚlistÚstackr4   ÚshapeÚ	unsqueezer\   Útor3   r7   Ú	is_sparseÚarangeÚindex_selectr6   r8   r9   ÚzipÚheapqÚheappushÚheappushpopr'   )Úquery_embeddingsÚcorpus_embeddingsr   r   r   r   Ú_Úqueries_result_listrE   Úquery_end_idxÚindicesÚquery_chunkrD   Úcorpus_end_idxÚcorpus_chunkÚ
cos_scoresÚcos_scores_top_k_valuesÚcos_scores_top_k_idxrI   Úsub_corpus_idrQ   r]   Úquery_idÚdoc_itrs                           r   rU   rU   §   s€  € ô0 Ð"¤R§Z¡Z´·±Ð$<×=Ñ=Ü ×+Ò+Ð,<Ó=ÑÜ	Ð$¤d×	+Ñ	+Ü Ÿ;š;Ð'7Ó8Ðä
Ð×!Ñ!Ó" aÓ'Ø+×5Ñ5°aÓ8ÐäÐ#¤b§j¡j´"·*±*Ð%=×>Ñ>Ü!×,Ò,Ð->Ó?ÑÜ	Ð%¤t×	,Ñ	,Ü!ŸKšKÐ(9Ó:Ðð ×ÑÐ#3×#:Ñ#:Ó:Ø+×.Ñ.Ð/@×/GÑ/GÓHÐä',¬SÐ1AÓ-BÔ'CÓDÒ'C !›2Ñ'CÐÐDä  ¤CÐ(8Ó$9Ð;K×LˆÜ˜OÑ>ÄÐDTÓ@UÓVˆØ×%×%Ü—l’l ?ÐJZ×JaÑJaÑbˆGØ*×7Ñ7¸¸7ÓC‰Kà*¸=ÐIˆKô !& a¬Ð->Ó)?ÐAR× SÐÜ Ð!1Ñ!EÄsÐK\ÓG]Ó^ˆNØ ×*×*ÜŸ,š,Ð'7ÐPa×PhÑPhÑi�Ø0×=Ñ=¸aÀÓI‘à0À.ÐQ�ñ (¨ÓBˆJô =B¿JºJØœC ¤s¨:°a©=Ó'9Ó:ÀÈ4ÐX]ñ=Ñ9Ð#Ð%9ð '>×&AÑ&AÓ&C×&JÑ&JÓ&LÐ#Ø#7×#;Ñ#;Ó#=×#DÑ#DÓ#FÐ ä"¤3 z£?Ö3�	Ü,/Ð0DÀYÑ0OÐQhÐirÑQsÖ,tÑ(�M 5Ø 0°=Ñ @�IØ.°Ñ:�HÜÐ.¨xÑ8Ó9¸EÓAÜŸšØ/°Ñ9¸EÀ9Ð;Möô ×)Ò)Ð*=¸hÑ*GÈ%ÐQZÐI[Ö\ó -uô 4ô% !Tñ MôN œ#Ð1Ó2Ö3ˆÜœSÐ!4°XÑ!>Ó?Ö@ˆGØ2°8Ñ<¸WÑEÑˆE�9ØCLÐW\Ñ5]Ð Ñ)¨'Ó2ñ Aô )/Ð/BÀ8Ñ/LÑRfÐptÑ(uÐ˜HÓ%ñ	 4ð Ðùò_ Es   ÅOc                óÜ  • [        U [        R                  5      (       d  [        R                  " U 5      n [        R                  " XR                  S9n[        U 5      n / n[        U[        U 5      5      n[        [        SU-  S5      [        U 5      5      n[        [        S[        U 5      U5      SU(       + S9 GH›  nXXs-    U R                  -  nU R                  R                  S;   a“  X�:¬  n	U	R                  S5      n
X¢:¬  nUR                  5       (       d  Ma  X«   n
X‹   nU
R                  5       nUR                  US	S
9u  pÞ[!        X®5       H(  u  nnUR#                  USU R%                  5       5        M*     MÄ  UR                  US	S
9u  nn[        [        U5      5       H¬  nUU   S   U:¼  d  M  UU   R                  US	S
9u  nnUS   U:”  aW  U[        U 5      :  aH  [        SU-  [        U 5      5      nUU   R                  US	S
9u  nnUS   U:”  a  U[        U 5      :  a  MH  UR#                  UUU:¬     R%                  5       5        M®     GMž     ['        US S	S9n/ n[)        5       n[+        U5       H]  u  nn/ nU H  nUU;  d  M  UR#                  U5        M     [        U5      U:¼  d  M;  UR#                  U5        UR-                  U5        M_     ['        US S	S9nU$ )aˆ  
Function for Fast Community Detection.

Finds in the embeddings all communities, i.e. embeddings that are close (closer than threshold).
Returns only communities that are larger than min_community_size. The communities are returned
in decreasing order. The first element in each list is the central point in the community.

Args:
    embeddings (torch.Tensor or numpy.ndarray): The input embeddings.
    threshold (float): The threshold for determining if two embeddings are close. Defaults to 0.75.
    min_community_size (int): The minimum size of a community to be considered. Defaults to 10.
    batch_size (int): The batch size for computing cosine similarity scores. Defaults to 1024.
    show_progress_bar (bool): Whether to show a progress bar during computation. Defaults to False.

Returns:
    List[List[int]]: A list of communities, where each community is represented as a list of indices.
r[   é   é2   r   zFinding clusters)ÚdescÚdisable)ÚcudaÚnpur   T)Úkr&   Nr#   c                ó   • [        U 5      $ ©N©r4   r*   s    r   r,   Ú%community_detection.<locals>.<lambda>S  s   € ÌÈAÌr!   r.   c                ó   • [        U 5      $ r‰   rŠ   r*   s    r   r,   r‹   c  s   € Ä#ÀaÄ&r!   )r`   r5   r   Útensorr\   r
   r7   r4   Úmaxr   r3   ÚTÚtypeÚsumÚanyr6   rm   r@   r9   r'   r=   r:   Úupdate)r   Ú	thresholdÚmin_community_sizer   r   Úextracted_communitiesÚsort_max_sizeÚ	start_idxrz   Úthreshold_maskÚrow_wise_countÚlarge_enough_maskr‡   rs   Útop_k_indicesÚcountrv   Útop_k_valuesrL   Útop_val_largeÚtop_idx_largeÚunique_communitiesÚextracted_idsÚ
cluster_idÚ	communityÚnon_overlapped_communityÚidxs                              r   Úcommunity_detectionr§     s  € ô0 �j¤%§,¡,×/Ñ/Ü—\’\ *Ó-ˆ
ä—’˜Y×/@Ñ/@ÑA€IÜ% jÓ1€JàÐô Ð/´°Z³ÓAÐÜœ˜AÐ 2Ñ2°BÓ7¼¸Z»ÓI€MäÜˆa”�Z“ *Ó-Ð4FÐTeÔPeõˆ	ð  ¨IÑ,BÐCÀjÇlÁlÑRˆ
ð ×Ñ×!Ñ! _Ó4à'Ñ4ˆNØ+×/Ñ/°Ó2ˆNð !/Ñ DÐØ$×(Ñ(×*Ñ*Ùà+Ñ>ˆNØ#Ñ6ˆJð ×"Ñ"Ó$ˆAØ)Ÿ™°¸D˜ÐAÑˆAô #& nÖ"D‘��wØ%×,Ñ,¨W°V°e¨_×-CÑ-CÓ-EÖFó #Eð )Ÿo™oÐ0BÈD˜oÐQ‰OˆL˜!ô œ3˜|Ó,Ö-�Ø ‘? 2Ñ&¨)Õ3à3=¸a±=×3EÑ3EÈÐ_cÐ3EÐ3dÑ0�M =ð (¨Ñ+¨iÓ7¸MÌCÐPZËOÓ<[Ü(+¨A°Ñ,=¼sÀ:»Ó(O˜Ø7AÀ!±}×7IÑ7IÈMÐcgÐ7IÐ7hÑ4˜ }ð (¨Ñ+¨iÓ7¸MÌCÐPZËOÕ<[ð *×0Ñ0°¸}ÐPYÑ?YÑ1Z×1aÑ1aÓ1cÖdô .ñAôZ #Ð#8Ñ>NÐX\Ñ]Ðð ÐÜ“E€Mä!*Ð+@Ö!AÑˆ
�IØ#%Ð ÛˆCØ˜-Õ'Ø(×/Ñ/°Ö4ñ ô Ð'Ó(Ð,>Õ>Ø×%Ñ%Ð&>Ô?Ø× Ñ Ð!9Ö:ñ "Bô  Ð 2Ñ8HÐRVÑWÐàÐr!   )r   r   r   z	list[str]r   Úboolr   Úintr   r©   r   r©   r   r©   r   r©   r   ú"Callable[[Tensor, Tensor], Tensor]r   z
int | Noner   ú
str | Noner   r«   Úreturnúlist[list[float | int]])r   r   r   r©   r   r©   r   r©   r   r©   r   rª   r¬   r­   )r¬   ú"list[list[dict[str, int | float]]])rq   r   rr   r   r   r©   r   r©   r   r©   r   rª   r¬   r®   )g      è?rY   i   F)r   ztorch.Tensor | np.ndarrayr”   Úfloatr•   r©   r   r©   r   r¨   r¬   zlist[list[int]])Ú
__future__r   rn   Úloggingr1   Úcollections.abcr   Útypingr   Únumpyra   r5   r   Útqdm.autonotebookr   Ú
similarityr	   r�   r
   Ú	getLoggerÚ__name__ÚloggerÚ0sentence_transformers.sentence_transformer.modelr   r    r   rX   rU   r§   r)   r!   r   Ú<module>r»      sù  ðÝ "ã Û Û Ý $Ý  ã Û Ý Ý "å Ý (à	×	Ò	˜8Ó	$€æÝTð $ØØ Ø#ØØØ9@Ø#Ø"Øð?Øð?àð?ð ð?ð ð	?ð
 ð?ð ð?ð ð?ð ð?ð 7ð?ð ð?ð ð?ð ð?ð õ?ðH !Ø#ØØØ9@ðFØðFàðFð ðFð ð	Fð
 ðFð 7ðFð õFôR,ð  Ø#ØØ9@ðXØðXàðXð ðXð ð	Xð
 ðXð 7ðXð (õXðz Ø ØØ#ðcØ)ðcàðcð ðcð ð	cð
 ðcð öcr!   