
    Ng6                    2   d dl mZ d dlZd dlZd dlZd dl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 d dlmZmZmZmZmZ d dlZd dlZd dlZd dlmZmZ d dlmZmZ d dlmZ d d	l mZ d d
l!m"Z"  ej#        e$          Z%erd dl&m'Z' d dl(m)Z) d dl*m+Z+ ddZ,ddZ-ddZ.ddZ/ddZ0ddZ1ddZ2ddZ3ddZ4ddZ5ddZ6ddZ7dd!Z8dd#Z9edd'            Z:edd)            Z:dd+Z:d,d-d.d/d0d1e0fdd?Z;d.d/d0d1e0fdd@Z<ddBZ=d1d0dCe0fddFZ>	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dddcZ?ddhZ@ddmZAddnZBddqZC	 	 	 	 dddyZD G dz d{e          ZEeejF        fd|            ZG	 	 	 	 dddZH	 	 	 	 dddZI	 	 	 	 dddZJd ZKddZLddZMddZNddZOddZPed             ZQdS )    )annotationsN)contextmanager)PackageNotFoundErrormetadata)TYPE_CHECKINGAnyCallableLiteraloverload)hf_hub_downloadsnapshot_download)Tensordevice)trange)tqdm)is_torch_npu_availableDataset)CrossEncoder)SentenceTransformeralist | np.ndarray | Tensorreturnr   c                X    t          | t                    st          j        |           } | S )z
    Converts the input `a` to a PyTorch tensor if it is not already a tensor.

    Args:
        a (Union[list, np.ndarray, Tensor]): The input array or tensor.

    Returns:
        Tensor: The converted tensor.
    )
isinstancer   torchtensorr   s    V/var/www/html/ai-engine/env/lib/python3.11/site-packages/sentence_transformers/util.py_convert_to_tensorr    !   s(     a   LOOH    c                `    |                                  dk    r|                     d          } | S )z
    If the tensor `a` is 1-dimensional, it is unsqueezed to add a batch dimension.

    Args:
        a (Tensor): The input tensor.

    Returns:
        Tensor: The tensor with a batch dimension.
       r   )dim	unsqueezer   s    r   _convert_to_batchr&   0   s)     	uuww!||KKNNHr!   c                B    t          |           } t          |           } | S )z
    Converts the input data to a tensor with a batch dimension.

    Args:
        a (Union[list, np.ndarray, Tensor]): The input data to be converted.

    Returns:
        Tensor: The converted tensor with a batch dimension.
    )r    r&   r   s    r   _convert_to_batch_tensorr(   ?   s#     	1A!AHr!   bc                "    t          | |          S )  
    Computes the cosine similarity between two tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Matrix with res[i][j] = cos_sim(a[i], b[j])
    )cos_simr   r)   s     r   pytorch_cos_simr.   N   s     1a==r!   c                    t          |           } t          |          }t          |           }t          |          }t          j        ||                    dd                    S )r+   r   r#   )r(   normalize_embeddingsr   mm	transpose)r   r)   a_normb_norms       r   r,   r,   \   sZ     	!##A ##A!!$$F!!$$F8FF,,Q22333r!   c                    t          |           } t          |          }t          t          |           t          |                    S )a  
    Computes the pairwise cosine similarity cos_sim(a[i], b[i]).

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Vector with res[i] = cos_sim(a[i], b[i])
    )r    pairwise_dot_scorer0   r-   s     r   pairwise_cos_simr7   o   s@     	1A1A21557KA7N7NOOOr!   c                    t          |           } t          |          }t          j        | |                    dd                    S )a  
    Computes the dot-product dot_prod(a[i], b[j]) for all i and j.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Matrix with res[i][j] = dot_prod(a[i], b[j])
    r   r#   )r(   r   r1   r2   r-   s     r   	dot_scorer9      s>     	!##A ##A8Aq{{1a(()))r!   c                p    t          |           } t          |          }| |z                      d          S )a  
    Computes the pairwise dot-product dot_prod(a[i], b[i]).

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Vector with res[i] = dot_prod(a[i], b[i])
    r$   )r    sumr-   s     r   r6   r6      s6     	1A1AE;;2;r!   c                n    t          |           } t          |          }t          j        | |d           S )a:  
    Computes the manhattan similarity (i.e., negative distance) between two tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Matrix with res[i][j] = -manhattan_distance(a[i], b[j])
    g      ?pr(   r   cdistr-   s     r   manhattan_simrC      8     	!##A ##AK1$$$$$r!   c                    t          |           } t          |          }t          j        t          j        | |z
            d           S )a<  
    Computes the manhattan similarity (i.e., negative distance) between pairs of tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Vector with res[i] = -manhattan_distance(a[i], b[i])
    r;   r<   )r    r   r=   absr-   s     r   pairwise_manhattan_simrG      sD     	1A1AIeiA&&B/////r!   c                n    t          |           } t          |          }t          j        | |d           S )a:  
    Computes the euclidean similarity (i.e., negative distance) between two tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Matrix with res[i][j] = -euclidean_distance(a[i], b[j])
    g       @r?   rA   r-   s     r   euclidean_simrI      rD   r!   c                    t          |           } t          |          }t          j        t          j        | |z
  dz  d                     S )a:  
    Computes the euclidean distance (i.e., negative distance) between pairs of tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Vector with res[i] = -euclidean_distance(a[i], b[i])
       r;   r<   )r    r   sqrtr=   r-   s     r   pairwise_euclidean_simrM      sH     	1A1AJuy!a%A26667777r!   xyc                J   t          |           } t          |          }t          j        | dd          \  }}t          j        |dd          \  }}t          j        |dz  |dz  z   dd          }||z  ||z  z   |z  }||z  ||z  z
  |z  }t          j        |dz  |dz  z   dd          dz  }	t          j        |dz  |dz  z   dd          dz  }
||	|
z  z  }||	|
z  z  }t          j        t          j        ||fd          d          }t          j        |          S )aP  
    Computes the absolute normalized angle distance. See :class:`~sentence_transformers.losses.AnglELoss`
    or https://arxiv.org/abs/2309.12871v1 for more information.

    Args:
        x (Tensor): The first tensor.
        y (Tensor): The second tensor.

    Returns:
        Tensor: Vector with res[i] = angle_sim(a[i], b[i])
    rK   r#   r<   T)r$   keepdim      ?)r    r   chunkr=   concatrF   )rN   rO   r   r)   cdzreimdzdw
norm_angles               r   pairwise_angle_simr]      sA    	1A1A ;q!###DAq;q!###DAq	!Q$A+1d333A
a%!a%-1	B
a%!a%-1	B	1a4!Q$;At	4	4	4	;B	1a4!Q$;At	4	4	4	;B"r'MB"r'MB5<Ra888a@@@J9Z   r!   
embeddingsc                P    t           j        j                            | dd          S )z
    Normalizes the embeddings matrix, so that each sentence embedding has unit length.

    Args:
        embeddings (Tensor): The input embeddings matrix.

    Returns:
        Tensor: The normalized embeddings matrix.
    rK   r#   )r@   r$   )r   nn
functional	normalize)r^   s    r   r0   r0     s$     8((qa(@@@r!   
np.ndarraytruncate_dim
int | Nonec                    d S N r^   rd   s     r   truncate_embeddingsrj     s    Y\Y\r!   torch.Tensorc                    d S rg   rh   ri   s     r   rj   rj     s    ]`]`r!   np.ndarray | torch.Tensorc                    | dd|f         S )a  
    Truncates the embeddings matrix.

    Args:
        embeddings (Union[np.ndarray, torch.Tensor]): Embeddings to truncate.
        truncate_dim (Optional[int]): The dimension to truncate sentence embeddings to. `None` does no truncation.

    Example:
        >>> from sentence_transformers import SentenceTransformer
        >>> from sentence_transformers.util import truncate_embeddings
        >>> model = SentenceTransformer("tomaarsen/mpnet-base-nli-matryoshka")
        >>> embeddings = model.encode(["It's so nice outside!", "Today is a beautiful day.", "He drove to work earlier"])
        >>> embeddings.shape
        (3, 768)
        >>> model.similarity(embeddings, embeddings)
        tensor([[1.0000, 0.8100, 0.1426],
                [0.8100, 1.0000, 0.2121],
                [0.1426, 0.2121, 1.0000]])
        >>> truncated_embeddings = truncate_embeddings(embeddings, 128)
        >>> truncated_embeddings.shape
        >>> model.similarity(truncated_embeddings, truncated_embeddings)
        tensor([[1.0000, 0.8092, 0.1987],
                [0.8092, 1.0000, 0.2716],
                [0.1987, 0.2716, 1.0000]])

    Returns:
        Union[np.ndarray, torch.Tensor]: Truncated embeddings.
    .Nrh   ri   s     r   rj   rj     s    : c=L=())r!   F    i  i i  d   	sentences	list[str]show_progress_barbool
batch_sizeintquery_chunk_sizecorpus_chunk_size	max_pairstop_kscore_function"Callable[[Tensor, Tensor], Tensor]list[list[float | int]]c	                ^    |                      |||d          }	t          |	|||||          S )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.

    Returns:
        List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
    T)rs   ru   convert_to_tensor)rw   rx   ry   rz   r{   )encodeparaphrase_mining_embeddings)
modelrq   rs   ru   rw   rx   ry   rz   r{   r^   s
             r   paraphrase_miningr   =  sR    > %6:ae   J ()+%   r!   c                   |dz  }t          j                    }d}d}t          dt          |           |          D ]x}	t          dt          |           |          D ]U}
 || |
|
|z            | |	|	|z                      }t	          j        |t          |t          |d                             ddd          \  }}|                                                                }|                                                                }t          t          |                    D ]}t          ||                   D ]r\  }}|
|z   }|	|z   }||k    r]||         |         |k    rK|
                    ||         |         ||f           |dz  }||k    r|                                }|d         }sWzt                      }g }|                                s{|                                \  }}}t          ||g          \  }}||k    r5||f|vr/|                    ||f           |                    |||g           |                                {t          |d d          }|S )	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;   r   TFr$   largestsortedc                    | d         S )Nr   rh   rN   s    r   <lambda>z.paraphrase_mining_embeddings.<locals>.<lambda>  s
    !A$ r!   keyreverse)queuePriorityQueuerangelenr   topkmincputolist	enumerateputgetsetemptyr   addappend)r^   rw   rx   ry   rz   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   j  s   0 
QJE !!EII!!S__6GHH 1 1$QJ9IJJ 	1 	1O#^?_?O-OOP+.>AR.RRS F
 5:JE3vay>>224PU5 5 51!1 #6"9"9";";"B"B"D"D/3355<<>>"3v;;// 1 1	-67G	7R-S-S 
1 
1)Iz')3A(:5AAvv"5i"@"Ki"W"W		#6y#A)#LaQR"STTT!Q	$	11$)IIKKE(-aI
11	14 %%KJkkmm ;iikkq!#QF^^(xXx$8$K$KOOXx0111uh9::: kkmm ; 
EEEJr!   "list[list[dict[str, int | float]]]c                     t          | i |S )z8This function is deprecated. Use semantic_search instead)semantic_search)argskwargss     r   information_retrievalr     s    D+F+++r!   
   query_embeddingscorpus_embeddingsc                   t          | t          j        t          j        f          rt	          j        |           } n)t          | t                    rt	          j        |           } t          | j	                  dk    r| 
                    d          } t          |t          j        t          j        f          rt	          j        |          }n)t          |t                    rt	          j        |          }|j        | j        k    r|                     |j                  } d t          t          |                     D             }t          dt          |           |          D ]p}t          dt          |          |          D ]M} || |||z            ||||z                      }	t	          j        |	t          |t          |	d                             ddd          \  }
}|
                                                                }
|                                                                }t          t          |	                    D ]}t%          ||         |
|                   D ]c\  }}||z   }||z   }t          ||                   |k     rt'          j        ||         ||f           Ft'          j        ||         ||f           dOrt          t          |                    D ]b}t          t          ||                             D ]!}||         |         \  }}||d||         |<   "t-          ||         d d	          ||<   c|S )
a  
    This function performs 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 (Tensor): A 2 dimensional tensor with the query embeddings.
        corpus_embeddings (Tensor): A 2 dimensional tensor with the corpus embeddings.
        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[[Tensor, Tensor], 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   c                    g | ]}g S rh   rh   .0_s     r   
<listcomp>z#semantic_search.<locals>.<listcomp>  s    DDD!2DDDr!   TFr   )	corpus_idr   c                    | d         S )Nr   rh   r   s    r   r   z!semantic_search.<locals>.<lambda>  s    \]^e\f r!   r   )r   npndarraygenericr   
from_numpyliststackr   shaper%   r   tor   r   r   r   r   zipheapqheappushheappushpopr   )r   r   rw   rx   rz   r{   queries_result_listr   r   
cos_scorescos_scores_top_k_valuescos_scores_top_k_idxr   sub_corpus_idr   r   query_iddoc_itrs                     r   r   r     s   0 "RZ$<== 9 +,<==	$d	+	+ 9 ;'788
!""a''+55a88#bj"*%=>> ;!,->??	%t	,	, ;!K(9:: #3#:::+../@/GHHDDuS1A-B-B'C'CDDD C(8$9$9;KLL ] ] %a->)?)?AR S S 	] 	]' ?EU3U!UV!"25EHY5Y"YZ J =BJCs:a='9'9::4X]= = =9#%9 '>&A&A&C&C&J&J&L&L##7#;#;#=#=#D#D#F#F "3z??33 	] 	]	,/0DY0OQhirQs,t,t ] ](M5 0= @I.:H.x899EAA/9E9;M    )*=h*G%QZI[\\\\]	]	]4 #12233 v vS!4X!>??@@ 	^ 	^G28<WEE9CLW\5]5])'22(./B8/LRfRfpt(u(u(uH%%r!      topT @  datasetr   r   r   anchor_column_name
str | Nonepositive_column_namecorpuslist[str] | Nonecross_encoderCrossEncoder | None	range_min	range_max	max_scorefloat | Noner   marginnum_negativessampling_strategyLiteral['random', 'top']as_tripletsfaiss_batch_size	use_faissverbosec                  LMNOPQR t                      st          d          ddlm} | j        }|r||vr|d         }|r||vr|d         }|s$|s"t          |          dk    rt          d          t          |                                 	                    |          
                                                                |                                                   }t          |          }|H|
||dz  z   |z   }n|z   |z   }|d	k    r|rd	}|rt          d
           |rt          d| d           i }| |         }| |         Rdu}|sRt          t                    t          R          z            d t!                    D             }|                                Lt          t          |                    }d t!          |          D             }t          |          }t%          j        |                              d          }|j        M|t          L          k    r%|r#t          d| dt          L           d           |dk    r(t-          j        |          }t          d|dd           |rddl}|                    |                                          }	 |                                } d| _        d| _        |                    ||           }n# t>          $ r Y nw xY w|                     |ddd          }!|                     ||ddd          }"|!                    |!           g }#g }$tE          dt          |"          |d          D ]V}%|"|%|%|z            }&|#                    |&|dz             \  }'N|#$                    |'           |$$                    N           Wt%          j%        t-          j&        |#d                    '                    M          }'t%          j%        t-          j&        |$d                    '                    M          Nnz|                     |ddd          }!|                     ||ddd          }"|(                    |"|!          '                    M          }'t%          j)        |'||z   d          \  }'Nd tU          |          D             QtW          LR          D ].\  }(})||(         }*Q|*         $                    ||)                    /d QD             Og Rg LtU          |          D ]N}+R,                    fd Q|+         D                        L,                    ||+         gO|+         z             OMfd!QD             Q|"Ofd"tU          |          D                      }"|!t%          j-        Q          .                                         },|/                    |"|,          '                    M          }-~"~,~!||
|ta          t!          N          d#t          N          $          D ]Z\  }+}.||+         }(fd%|.D             }/|1                    t          tW          |(g|dz   z  |/                    |d&          }0|0|'|+<   [|1                    t          tW          LR                    |d&          }-t%          j2        NQfd'tU          |          D                       }1tg          d(           |'|1<   |'4                                }2|
t%          j5        ||-j        |-j6        )          }3d}4tU          |          D ]8}5t%          j7        |-|4|4O|5         z                      |3|5<   |4O|5dz
           z  }49|'|
z   |38                    |'9                    d          d          j:        k    }6tg          d(           |'|6<   |6;                                <                                }7|7r|7|7|2z  d*|d+<   |2|7z  }2|L|'|k    }6tg          d(           |'|6<   |6;                                <                                }7|7r|7|7|2z  d*|d,<   |	L|'|	k     }6tg          d(           |'|6<   |6;                                <                                }7|7r|7|7|2z  d*|d-<   t%          j)        |'|d          \  P}8N||8f         N|rNdd|df         NPdd|df         P|d.k    rNdddf         NPdddf         Pn|d/k    rN9                    d          P=                                ;                    d          z
  }9|9>                    0          }9fd1|9D             }:N||:f         NP||:f         PP?                    dd2          \  P}8N||8f         Nt%          j-        NOfd3tU          |          D                       Nt%          j-        OPfd4tU          |          D                       P|rPtg          d(           k    };t%          j@        N          }<t%          j@        N          }=N|;         NP|;         Pd}4tU          |          D ]x}5t%          jA        |5          8                    O|5                   |<|4|4O|5         z   <   Q|5         8                    d          j:        |=|4|4O|5         z   <   |4O|5         z  }4y|<|;         }<|=|;         Q|g |g d5g i}>tW          |<NQ          D ]i\  }?}@}A|>|         $                    ||?                    |>|         $                    |A                    |>d5         $                    |@                    j|-8                    d          j:        |;         Pz
  }Bn܉Ptg          d(           k    B                    d6          };P|;         PN|;         N|Lfd7t!          |;          D             |Rfd8t!          |;          D             ifd9t!          Nj:        d:          D             }>PC                                P|-8                    d          j:        |;         C                                Pz
  }Bt          |>          dk    rt          d;           |jD        |>          }C|rd<}Dd= }Et          |DE                    d>d?d@dA                     t          |DE                    dB |Et          |-                     |Et          P                    dC                     dDt$          j        fdEt$          jF        fdFt$          jG        fdGdH fdIdJ fdKdL fdMdN fdOdP ffD ]r\  }F}Gt          |DE                    |FH                                 |E |G|-                     |E |GP                     |E |G|B                                         sd+|v r2t          dQ|d+         dR          dS|d+         dT         dUdV|
 dW           d,|v r2t          dQ|d,         dR          dS|d,         dT         dUdX| dW           d-|v r2t          dQ|d-         dR          dS|d-         dT         dUdY|	 dW           t          |           z  t          P          z
  }H|Hdk    rdZg}I|dk    r|I$                    d[           |
|I$                    d+           ||I$                    d,           d\I                    |Idd                   }Jt          |I          dk    r|Jd]|Id         z   z  }J|Ht          |           z  z  }Kt          d^|H d_|KdUd`|J dat          |I          dk    rdbndC dc	           |CS )du'  
    Add hard negatives to a dataset of (anchor, positive) pairs to create (anchor, positive, negative) triplets or
    (anchor, positive, negative_1, ..., negative_n) tuples.

    Hard negative mining is a technique to improve the quality of a dataset by adding hard negatives, which are
    texts that may appear similar to the anchor, but are not. Using hard negatives can improve the performance of
    models trained on the dataset.

    This function uses a SentenceTransformer model to embed the sentences in the dataset, and then finds the closest
    matches to each anchor sentence in the dataset. It then samples negatives from the closest matches, optionally
    using a CrossEncoder model to rescore the candidates.

    You can influence the candidate negative selection in various ways:

    - **range_min**: Minimum rank of the closest matches to consider as negatives: useful to skip the most similar texts to
      avoid marking texts as negative that are actually positives.
    - **range_max**: Maximum rank of the closest matches to consider as negatives: useful to limit the number of candidates
      to sample negatives from. A lower value makes processing faster, but may result in less candidate negatives that
      satisfy the margin or max_score conditions.
    - **max_score**: Maximum score to consider as a negative: useful to skip candidates that are too similar to the anchor.
    - **min_score**: Minimum score to consider as a negative: useful to skip candidates that are too dissimilar to the anchor.
    - **margin**: Margin for hard negative mining: useful to skip candidates negatives whose similarity to the anchor is
      within a certain margin of the positive pair. A value of 0 can be used to enforce that the negative is always
      further away from the anchor than the positive.
    - **sampling_strategy**: Sampling strategy for negatives: "top" or "random". "top" will always sample the top n
      candidates as negatives, while "random" will sample n negatives randomly from the candidates that satisfy the
      margin or max_score conditions.

    Example:

        >>> from sentence_transformers.util import mine_hard_negatives
        >>> from sentence_transformers import SentenceTransformer
        >>> from datasets import load_dataset
        >>> # Load a Sentence Transformer model
        >>> model = SentenceTransformer("all-MiniLM-L6-v2")
        >>>
        >>> # Load a dataset to mine hard negatives from
        >>> dataset = load_dataset("sentence-transformers/natural-questions", split="train")
        >>> dataset
        Dataset({
            features: ['query', 'answer'],
            num_rows: 100231
        })
        >>> dataset = mine_hard_negatives(
        ...     dataset=dataset,
        ...     model=model,
        ...     range_min=10,
        ...     range_max=50,
        ...     max_score=0.8,
        ...     margin=0.1,
        ...     num_negatives=5,
        ...     sampling_strategy="random",
        ...     batch_size=128,
        ...     use_faiss=True,
        ... )
        Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 784/784 [00:43<00:00, 17.83it/s]
        Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 784/784 [00:07<00:00, 99.60it/s]
        Querying FAISS index: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████| 784/784 [00:00<00:00, 884.99it/s]
        Metric       Positive       Negative     Difference
        Count         100,231        431,255        431,255
        Mean           0.6866         0.4289         0.2804
        Median         0.7010         0.4193         0.2740
        Std            0.1125         0.0754         0.0999
        Min            0.0303         0.1720         0.1001
        25%            0.6221         0.3747         0.1991
        50%            0.7010         0.4193         0.2740
        75%            0.7667         0.4751         0.3530
        Max            0.9584         0.7743         0.7003
        Skipped 1289492 potential negatives (25.23%) due to the margin of 0.1.
        Skipped 39 potential negatives (0.00%) due to the maximum score of 0.8.
        Could not find enough negatives for 69900 samples (13.95%). Consider adjusting the range_max, range_min, margin and max_score parameters if you'd like to find more valid negatives.
        >>> # Note: The minimum similarity difference is 0.1001 due to our margin of 0.1
        >>> dataset
        Dataset({
            features: ['query', 'answer', 'negative'],
            num_rows: 431255
        })
        >>> dataset[0]
        {
            'query': 'when did richmond last play in a preliminary final',
            'answer': "Richmond Football Club Richmond began 2017 with 5 straight wins, a feat it had not achieved since 1995. A series of close losses hampered the Tigers throughout the middle of the season, including a 5-point loss to the Western Bulldogs, 2-point loss to Fremantle, and a 3-point loss to the Giants. Richmond ended the season strongly with convincing victories over Fremantle and St Kilda in the final two rounds, elevating the club to 3rd on the ladder. Richmond's first final of the season against the Cats at the MCG attracted a record qualifying final crowd of 95,028; the Tigers won by 51 points. Having advanced to the first preliminary finals for the first time since 2001, Richmond defeated Greater Western Sydney by 36 points in front of a crowd of 94,258 to progress to the Grand Final against Adelaide, their first Grand Final appearance since 1982. The attendance was 100,021, the largest crowd to a grand final since 1986. The Crows led at quarter time and led by as many as 13, but the Tigers took over the game as it progressed and scored seven straight goals at one point. They eventually would win by 48 points – 16.12 (108) to Adelaide's 8.12 (60) – to end their 37-year flag drought.[22] Dustin Martin also became the first player to win a Premiership medal, the Brownlow Medal and the Norm Smith Medal in the same season, while Damien Hardwick was named AFL Coaches Association Coach of the Year. Richmond's jump from 13th to premiers also marked the biggest jump from one AFL season to the next.",
            'negative': "2018 NRL Grand Final The 2018 NRL Grand Final was the conclusive and premiership-deciding game of the 2018 National Rugby League season and was played on Sunday September 30 at Sydney's ANZ Stadium.[1] The match was contested between minor premiers the Sydney Roosters and defending premiers the Melbourne Storm. In front of a crowd of 82,688, Sydney won the match 21â€“6 to claim their 14th premiership title and their first since 2013. Roosters five-eighth Luke Keary was awarded the Clive Churchill Medal as the game's official man of the match."
        }
        >>> dataset.push_to_hub("natural-questions-hard-negatives", "triplet-all")

    Args:
        dataset (Dataset): A dataset containing (anchor, positive) pairs.
        model (SentenceTransformer): A SentenceTransformer model to use for embedding the sentences.
        anchor_column_name (str, optional): The column name in `dataset` that contains the anchor/query. Defaults to None, in which case the first column in `dataset` will be used.
        positive_column_name (str, optional): The column name in `dataset` that contains the positive candidates. Defaults to None, in which case the second column in `dataset` will be used.
        corpus (List[str], optional): A list containing documents as strings that will be used as candidate negatives
            in addition to the second column in `dataset`. Defaults to None, in which case the second column in
            `dataset` will exclusively be used as the negative candidate corpus.
        cross_encoder (CrossEncoder, optional): A CrossEncoder model to use for rescoring the candidates. Defaults to None.
        range_min (int): Minimum rank of the closest matches to consider as negatives. Defaults to 0.
        range_max (int, optional): Maximum rank of the closest matches to consider as negatives. Defaults to None.
        max_score (float, optional): Maximum score to consider as a negative. Defaults to None.
        min_score (float, optional): Minimum score to consider as a negative. Defaults to None.
        margin (float, optional): Margin for hard negative mining. Defaults to None.
        num_negatives (int): Number of negatives to sample. Defaults to 3.
        sampling_strategy (Literal["random", "top"]): Sampling strategy for negatives: "top" or "random". Defaults to "top".
        as_triplets (bool): If True, returns up to `num_negatives` (anchor, positive, negative) triplets for each input sample.
            If False, returns 1 (anchor, positive, negative_1, ..., negative_n) tuple for each input sample. Defaults to True.
        batch_size (int): Batch size for encoding the dataset. Defaults to 32.
        faiss_batch_size (int): Batch size for FAISS top-k search. Defaults to 16384.
        use_faiss (bool): Whether to use FAISS for similarity search. May be recommended for large datasets. Defaults to False.
        verbose (bool): Whether to print statistics and logging. Defaults to True.

    Returns:
        Dataset: A dataset containing (anchor, positive, negative) triplets or (anchor, positive, negative_1, ..., negative_n) tuples.
    zGPlease install `datasets` to use this function: `pip install datasets`.r   r   r#   rK   z)Dataset must contain exactly two columns.Nr   i   z\Using FAISS, we can only retrieve up to 2048 documents per query. Setting range_max to 2048.zSetting range_max to z" based on the provided parameters.c                    i | ]\  }}||	S rh   rh   )r   idxtexts      r   
<dictcomp>z'mine_hard_negatives.<locals>.<dictcomp>  s    ???	T$???r!   c                    i | ]\  }}||	S rh   rh   )r   r   querys      r   r   z'mine_hard_negatives.<locals>.<dictcomp>  s    CCC*#u5#CCCr!   r;   zFound z unique queries out of z total queries.zFound an average of z.3fz positives per query.T)co)ru   r0   convert_to_numpyrs   zQuerying FAISS index)desck)axis)r   r$   c                    g | ]}g S rh   rh   r   s     r   r   z'mine_hard_negatives.<locals>.<listcomp>   s    555q555r!   c                ,    g | ]}t          |          S rh   r   )r   r@   s     r   r   z'mine_hard_negatives.<locals>.<listcomp>  s    444a3q66444r!   c                     g | ]
}|         S rh   rh   )r   doc_idxr   s     r   r   z'mine_hard_negatives.<locals>.<listcomp>  s    OOOg&/OOOr!   c                <    g | ]}t          j        |           S )r   )r   r   )r   r@   r   s     r   r   z'mine_hard_negatives.<locals>.<listcomp>  s(    QQQ1Qv666QQQr!   c                D    g | ]}t          |                   D ]}|S rh   )r   )r   r   r   n_positivess      r   r   z'mine_hard_negatives.<locals>.<listcomp>  s6    (j(j(jRWXcdgXhRiRi(j(jQ(j(j(j(jr!   zRescoring with CrossEncoder)r   totalc                     g | ]
}|         S rh   rh   )r   _idxr   s     r   r   z'mine_hard_negatives.<locals>.<listcomp>  s    !I!I!I4&,!I!I!Ir!   )ru   r   c                R    g | ]#}t          j        |         |                   $S rh   )r   isin)r   q_idxindicespositive_indicess     r   r   z'mine_hard_negatives.<locals>.<listcomp>,  s0     s s sY^GEN<LU<S!T!T s s sr!   inf)r   dtype)skippedratior   r   r   r   random)r   c                V    g | ]%}t          j        t          |                     &S )r   )r  sampler   )r   optionsr   s     r   r   z'mine_hard_negatives.<locals>.<listcomp>t  s.    aaa'v}U7^^}EEEaaar!   )r$   
descendingc                T    g | ]$}|                              |         d           %S r#   repeat)r   r   r  r   s     r   r   z'mine_hard_negatives.<locals>.<listcomp>|  s2    ^^^c,,[-=qAA^^^r!   c                T    g | ]$}|                              |         d           %S r  r  )r   r   r   negative_scoress     r   r   z'mine_hard_negatives.<locals>.<listcomp>}  s4     n n nVY!5!<!<[=Mq!Q!Q n n nr!   negativer<   c                *    g | ]\  }}||         S rh   rh   )r   r   keepall_queriess      r   r   z'mine_hard_negatives.<locals>.<listcomp>  s(     f f fic4ae fS!1 f f fr!   c                *    g | ]\  }}||         S rh   rh   )r   r   r  	positivess      r   r   z'mine_hard_negatives.<locals>.<listcomp>  s'    "f"f"fic4ae"f9S>"f"f"fr!   c                :    i | ]\  }}d | fd|D             S )	negative_c                     g | ]
}|         S rh   rh   )r   neg_idxr   s     r   r   z2mine_hard_negatives.<locals>.<dictcomp>.<listcomp>  s    !M!M!Mg&/!M!M!Mr!   rh   )r   r   neg_indicesr   s      r   r   z'mine_hard_negatives.<locals>.<dictcomp>  sJ       "A{  A!M!M!M!M!M!M!M  r!   )startzHNo triplets could be generated. Please check the parameters and dataset.z{:<6} {:>14} {:>14} {:>14}c                j    t          | t          j                  r|                                 dn| dS )Nz.4f,)r   r   r   item)values    r   r   z%mine_hard_negatives.<locals>.<lambda>  s1    Juel<[<[#mejjll#8#8#8diamam r!   MetricPositiveNegative
DifferenceCount meanmedianstdr   c                x    |                                  dk    rt          j        |           nt          d          S )Nr   r	  )numelr   r   floatr   s    r   r   z%mine_hard_negatives.<locals>.<lambda>  s1    8J8J59V#4#4#4PUV[P\P\ r!   z25%c                    |                                  dk    r(t          j        |                                 d          nt          d          S )Nr   g      ?qr	  r2  r   quantiler3  r4  s    r   r   z%mine_hard_negatives.<locals>.<lambda>  ?    V\\^^^_M_M_5>&,,..D#I#I#I#Iejkpeqeq r!   z50%c                    |                                  dk    r(t          j        |                                 d          nt          d          S )Nr   rR   r6  r	  r8  r4  s    r   r   z%mine_hard_negatives.<locals>.<lambda>  s?    FLLNN]^L^L^5>&,,..C#H#H#H#Hdijodpdp r!   z75%c                    |                                  dk    r(t          j        |                                 d          nt          d          S )Nr         ?r6  r	  r8  r4  s    r   r   z%mine_hard_negatives.<locals>.<lambda>  r:  r!   maxc                x    |                                  dk    rt          j        |           nt          d          S )Nr   z-inf)r2  r   r>  r3  r4  s    r   r   z%mine_hard_negatives.<locals>.<lambda>  s1    8J8J59V#4#4#4PUV\P]P] r!   zSkipped r  z potential negatives (r  z.2%z) due to the margin of .z) due to the maximum score of z) due to the minimum score of r   r   z, z and z$Could not find enough negatives for z
 samples (z). Consider adjusting the z
 parametersz, if you'd like to find more valid negatives.)Jis_datasets_availableImportErrordatasetsr   column_namesr   
ValueErrorr   	to_pandasgroupbycountto_dictvaluesr>  printr   r   copyr   aranger%   r   r   r.  faissIndexFlatIP get_sentence_embedding_dimensionGpuMultipleClonerOptionsshard
useFloat16index_cpu_to_all_gpus	Exceptionr   r   r   searchr   r   concatenater   
similarityr   r   r   extendcatr   similarity_pairwiser   predictr   r3  r2  r   r
  r   r  sizeTr=   r&  isinfclampsort
empty_liker   allflatten	from_dictformatr/  r0  
capitalizejoin)Sr   r   r   r   r   r   r   r   r   r   r   r   r   r   ru   r   r   r   r   columnspositives_per_querymax_positiveslog_countersqueriesseparate_corpus
corpus_idxqueries_idx	n_queries	batch_idxavg_positives_per_queryrO  indexr   r   r   scores_listindices_listr   query_chunkr   r   positive	query_idxr   positive_embeddingspositive_scorescandidate_idxcandidate_passagespred_scorespositive_masknum_candidatesmax_positive_scores	start_idxr  removed_indicesnum_skippedlocal_indicesnum_optionssampled_idxindices_to_keepanchor_indicespos_indicestriplets_data
anchor_idxnegative_idxpositive_idxdifference_scorestriplets_dataset
row_format	formattermetricfunctionmissing_negatives	solutionsconsiderationsmissing_negatives_ratior  r   r  r   r  r  r  sS       `      `                                                                @@@@@@@r   mine_hard_negativesr    s   F !"" ecddd       "G (!37!B!B$QZ *#7w#F#F&qz F&: Fs7||q?P?PDEEE ##$677==??GGIIJ^_ffhh  +,,M!6!]R%78=HII "M1MAIt	I vtuuu 	YW)WWWXXXL()G,-ID(O  #f++I.//F @?Yv->->???J ,,..K3w<<  GCC	'0B0BCCCKGIY''11"55I\FC$$$$$ZyZZ[9I9IZZZ[[[q"$'*=">">W%<WWWWXXX +Q!!%"H"H"J"JKK	//11BBH BM','B'B5R'B'P'PEE 	 	 	D	 "LLzW[os ) 
 
 !<<
X\pt ( 
 
 			#$$$3/002BI_``` 	) 	)A*1q3C/C+CDK#ll;)a-lHHOFGv&&&((((!".1"E"E"EFFII&QQ"2>,Q#G#G#GHHKKFSS "LLzW[os ) 
 
 !<<
X\pt ( 
 
 !!"24EFFII&QQ  *Vy=/HaPPP
 65E)$4$4555{I66 A Ax&	#**:h+?@@@@44#3444K IKY > >OOOO9I#9NOOOPPPGCL>K,<<====QQQQ@PQQQ ((j(j(j(ji8H8H(j(j(jk+EI6F,G,G,N,N,P,PQ//0@BUVVYYZ`aaO  f&8I<Q"&y'9'9@]ehipeqeq"r"r"r 	& 	&CCLE!I!I!I!I=!I!I!I'//S%IM24FGGHH%"& 0  K
 &F3KK'//[),,--!" 0 
 
 K s s s s sbghqbrbr s s sttM #5\\MF=\\^^N  $k)O<RZiZoppp	9%% 	0 	0E).?9y[fgl[mOmCm3n)o)o&UQY//II 6/,?,F,Fv{{ST~~WX,Y,Y,[[#(<<-%))++0022 	*&$~5& &L" k)N  9,#(<<-%))++0022 	&$~5) )L%  9,#(<<-%))++0022 	&$~5) )L% &+Z)%K%K%K"O]i./G 9!!!YZZ-()!!!YZZ-8 E!!!!!^m^+,)!!!^m^*;<	h	&	&ll1oo(=(=(?(?(C(CA(F(FF!''M'::aaaaU`aaa)[01))[*@A)8)=)=!PT)=)U)U&)]23 i^^^^^US\M]M]^^^__Gi n n n n n]bcl]m]m n n nooO 2t)eEll]:)'22&w///*)/: 	9%% 	, 	,EINV[I\I\IcIcE"MJ JN9y;u3E'EEF !'..}a@@B 	IE0B$BBC U++II'8&7  "
 7:.'Sc6d6d 	C 	C2Jl,-44WZ5HIII./66vl7KLLL*%,,VL-ABBBB+22=!DDFWZii +uU||m;@@Q@GG)/:/*  f f f f9_C]C] f f f "f"f"f"f9_C]C]"f"f"f
   &/	&C&C&C  
 *1133+22=!DDFW__aadss
=Qcddd(w(77  <1
nn	j*j,OOPPP	#o..//	#o..//	 	
 	
 	
 UZ u|$EI\\]qqrppqqqr]]^	!
 	 	FH !!%%''Ihh7788Ihh7788Ihh'899::	     |## Z<1)<  Z  ZT`aiTjkrTs  Z  Z  Z  QW  Z  Z  Z   ,&& j<4Y?  j  jWcdoWpqxWy  j  j  j  ^g  j  j  j   ,&& j<4Y?  j  jWcdoWpqxWy  j  j  j  ^g  j  j  j   +S\\9S=Q=QQq  $I1}}  ---!  ***$  ---!YYy"~66N9~~!!'IbM"99&7=3w<<;W&X#U7H U UTks U U+9U ULOPYNN]^L^L^SSdfU U U  
 s   99K3 3
L ?L urlstrpathNonec                <   t           j                            |          dk    r3t          j        t           j                            |          d           t	          j        | d          }|j        dk    r<t          d|  d|j         t          j	                   |
                                 d	S |d
z   }t          |d          5 }|j                            d          }|t          |          nd	}t          d|d          }|                    d          D ];}|r7|                    t#          |                     |                    |           <	 d	d	d	           n# 1 swxY w Y   t          j        ||           |                                 d	S )a  
    Downloads a URL to a given path on disk.

    Args:
        url (str): The URL to download.
        path (str): The path to save the downloaded file.

    Raises:
        requests.HTTPError: If the HTTP request returns a non-200 status code.

    Returns:
        None
    r-  T)exist_ok)stream   z"Exception when trying to download z. Response )fileN_partwbzContent-LengthB)unitr  
unit_scale   )
chunk_size)osr  dirnamemakedirsrequestsr   status_coderL  sysstderrraise_for_statusopenheadersrv   r   iter_contentupdater   writerenameclose)	r  r  reqdownload_filepathfile_binarycontent_lengthr  progressrS   s	            r   http_getr    s    
wt""
BGOOD))D9999
,s4
(
(
(C
#T3TT3?TT[^[effffw		&	& )+)9::'5'AN###tS$???%%%66 	) 	)E )E

+++!!%(((	)	) ) ) ) ) ) ) ) ) ) ) ) ) ) ) I&&&NNs   	BE((E,/E,batchdict[str, Any]target_devicer   c                    | D ];}t          | |         t                    r| |                             |          | |<   <| S )au  
    Send a PyTorch batch (i.e., a dictionary of string keys to Tensors) to a device (e.g. "cpu", "cuda", "mps").

    Args:
        batch (Dict[str, Tensor]): The batch to send to the device.
        target_device (torch.device): The target device (e.g. "cpu", "cuda", "mps").

    Returns:
        Dict[str, Tensor]: The batch with tensors sent to the target device.
    )r   r   r   )r  r  r   s      r   batch_to_devicer    sH      6 6eCj&)) 	6s}55E#JLr!   c                    | j         j        }||t          j         j        k    r| j         j        S |dz   | j         j        z   S )a  
    Gives a full name (package_name.class_name) for a class / object in Python. Will
    be used to load the correct classes from JSON files

    Args:
        o: The object for which to get the full name.

    Returns:
        str: The full name of the object.

    Example:
        >>> from sentence_transformers.losses import MultipleNegativesRankingLoss
        >>> from sentence_transformers import SentenceTransformer
        >>> from sentence_transformers.util import fullname
        >>> model = SentenceTransformer('all-MiniLM-L6-v2')
        >>> loss = MultipleNegativesRankingLoss(model)
        >>> fullname(loss)
        'sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss'
    Nr@  )	__class__
__module__r  __name__)omodules     r   fullnamer  /  sA    * [#F~3=#;;;{##|ak222r!   dotted_pathtypec                ^   	 |                      dd          \  }}n"# t          $ r |  d}t          |          w xY w	 t          j        |           }n$# t
          $ r t          j        |          }Y nw xY w	 t          ||          S # t          $ r d| d| d}t          |          w xY w)a:  
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImportError if the import failed.

    Args:
        dotted_path (str): The dotted module path.

    Returns:
        Any: The attribute/class designated by the last name in the path.

    Raises:
        ImportError: If the import failed.

    Example:
        >>> import_from_string('sentence_transformers.losses.MultipleNegativesRankingLoss')
        <class 'sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss'>
    r@  r#   z  doesn't look like a module pathzModule "z" does not define a "z" attribute/class)rsplitrF  rC  	importlibimport_modulerV  getattrAttributeError)r  module_path
class_namemsgr  s        r   import_from_stringr  K  s    $"-"4"4S!"<"<ZZ   >>>#6(55 6 6 6(556vz***   XXX:XXX#s%    ;A A54A59B	 	#B,r=  r  torch.Tensor | np.ndarray	thresholdr3  min_community_sizelist[list[int]]c                   t          | t          j                  st          j        |           } t          j        || j                  }t          |           } g }t          |t          |                     }t          t          d|z  d          t          |                     }t          t          dt          |           |          d|           D ]}| |||z            | j        z  }| j        j        dv r||k    }	|	                    d          }
|
|k    }|                                s\|
|         }
||         }|
                                }|                    |d	
          \  }}t!          |
|          D ]4\  }}|                    |d|                                                    5|                    |d	
          \  }}t          t          |                    D ]}||         d         |k    r||                             |d	
          \  }}|d         |k    rr|t          |           k     r_t          d|z  t          |                     }||                             |d	
          \  }}|d         |k    r|t          |           k     _|                    |||k                                                        t'          |d d	          }g }t)                      }t+          |          D ]b\  }}g }|D ]}||vr|                    |           t          |          |k    r*|                    |           |                    |           ct'          |d d	          }|S )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   rK   2   r   zFinding clusters)r   disable)cudanpur#   T)r   r   Nr;   c                     t          |           S rg   r   r   s    r   r   z%community_detection.<locals>.<lambda>  s    A r!   r   c                     t          |           S rg   r   r   s    r   r   z%community_detection.<locals>.<lambda>  s    #a&& r!   )r   r   r   r   r   r0   r   r   r>  r   r   r_  r  r=   anyr   r   r   r   r   r   r   r  )r^   r  r  ru   rs   extracted_communitiessort_max_sizer  r   threshold_maskrow_wise_countlarge_enough_maskr   r   top_k_indicesrI  r  top_k_valuesr   top_val_largetop_idx_largeunique_communitiesextracted_ids
cluster_id	communitynon_overlapped_communityr   s                              r   community_detectionr  o  s   0 j%,// .\*--
Yz/@AAAI%j11J /ZAAA 22B77ZIIMaZ*--4FTePe   *e *e	  	I
,B BCjlR
 !_44'94N+//22N !/2D D$((** +,=>N#$56J ""$$A)DAAA} #&nm"D"D G Gw%,,WVeV_-C-C-E-EFFFFG )oo0BDoQQOL! 3|,,-- 
e 
e?2&)333=a=3E3E_c3E3d3d0M= (+i77MCPZOO<[<[(+A,=s:(O(O7A!}7I7IMcg7I7h7h4} (+i77MCPZOO<[<[ *00}PY?Y1Z1a1a1c1cddd
e ##8>N>NX\]]] EEM!*+@!A!A ; ;
I#%  	5 	5C-''(//444'((,>>>%%&>???  !9::: 28H8HRVWWWr!   c                  .     e Zd ZdZ fdZd fdZ xZS )	disabled_tqdmz
    Class to override `disable` argument in case progress bars are globally disabled.

    Taken from https://github.com/tqdm/tqdm/issues/619#issuecomment-619639324.
    c                D    d|d<    t                      j        |i | d S )NTr  )super__init__)selfr   r   r  s      r   r  zdisabled_tqdm.__init__  s/     y$)&)))))r!   attrr  r   r  c                |    	 t                                          |           dS # t          $ r |dk    r Y dS w xY w)zBFix for https://github.com/huggingface/huggingface_hub/issues/1603_lockN)r  __delattr__r  )r  r  r  s     r   r  zdisabled_tqdm.__delattr__  sV    	GG%%%%% 	 	 	w 	s   !& ;;)r  r  r   r  )r  r  __qualname____doc__r  r  __classcell__)r  s   @r   r  r    s`         * * * * *         r!   r  c              #     K   t           j        j        j        }t          j        |            	 dV  t          j        |           dS # t          j        |           w xY w)z
    A context manager that will prevent any logging messages
    triggered during the body from being processed.

    Args:
        highest_level: the maximum logging level allowed.
    N)loggingrootmanagerr  )highest_levelprevious_levels     r   disable_loggingr    s_       \)1NOM"""('''''''''s   A Amodel_name_or_pathtokenbool | str | Nonecache_folderrevisionlocal_files_onlyc           
     F    t          t          | d||||                    S )a}  
    Checks if the given model name or path corresponds to a SentenceTransformer model.

    Args:
        model_name_or_path (str): The name or path of the model.
        token (Optional[Union[bool, str]]): The token to be used for authentication. Defaults to None.
        cache_folder (Optional[str]): The folder to cache the model files. Defaults to None.
        revision (Optional[str]): The revision of the model. Defaults to None.
        local_files_only (bool): Whether to only use local files for the model. Defaults to False.

    Returns:
        bool: True if the model is a SentenceTransformer model, False otherwise.
    zmodules.json)r  r
  r  r  )rt   load_file_path)r  r  r
  r  r  s        r   is_sentence_transformer_modelr    s:    ( %-	
 	
 	
	 	 	r!   filenamec           	         t           j                            | |          }t           j                            |          r|S 	 t	          | ||d|||          S # t
          $ r Y dS w xY w)a  
    Loads a file from a local or remote location.

    Args:
        model_name_or_path (str): The model name or path.
        filename (str): The name of the file to load.
        token (Optional[Union[bool, str]]): The token to access the remote file (if applicable).
        cache_folder (Optional[str]): The folder to cache the downloaded file (if applicable).
        revision (Optional[str], optional): The revision of the file (if applicable). Defaults to None.
        local_files_only (bool, optional): Whether to only consider local files. Defaults to False.

    Returns:
        Optional[str]: The path to the loaded file, or None if the file could not be found or loaded.
    sentence-transformers)r  r  library_namer  	cache_dirr  N)r  r  ri  existsr   rV  )r  r  r  r
  r  r  	file_paths          r   r  r  "  s    . /::I	w~~i   0"-
 
 
 	
    tts   A 
A'&A'	directoryc           	     H   t           j                            | |          }t           j                            |          r|S | || dd|||t          d}	 t          di |}n!# t          $ r d|d<   t          di |}Y nw xY wt           j                            ||          S )af  
    Loads the directory path for a given model name or path.

    Args:
        model_name_or_path (str): The name or path of the model.
        directory (str): The directory to load.
        token (Optional[Union[bool, str]]): The token for authentication.
        cache_folder (Optional[str]): The folder to cache the downloaded files.
        revision (Optional[str], optional): The revision of the model. Defaults to None.
        local_files_only (bool, optional): Whether to only use local files. Defaults to False.

    Returns:
        Optional[str]: The directory path if it exists, otherwise None.
    z/**r  )repo_idr  allow_patternsr  r  r  r  
tqdm_classTr  rh   )r  r  ri  r  r  r   rV  )	r  r  r  r
  r  r  dir_pathdownload_kwargs	repo_paths	            r   load_dir_pathr  L  s    . w||.	::H	w~~h  &&+++/!,#	 	O9%8888		 9 9 9.2*+%8888			9 7<<	9---s   A# #B Bc                F     t          j                    fd            }|S )Nc                    |                     dd           }|r#d|vrt                              d           ||d<   t          |          dk    rg |d d         d |dd          R } | g|R i |S )N	repo_namer  zfProviding a `repo_name` keyword argument to `save_to_hub` is deprecated, please use `repo_id` instead.rK   )poploggerwarningr   )r  r   r   r"  funcs       r   wrapperz+save_to_hub_args_decorator.<locals>.wrapper|  s     JJ{D11	 	*&00NNx   !*F9 t99>>/T"1"X/t/d122h//DtD*4***6***r!   )	functoolswraps)r&  r'  s   ` r   save_to_hub_args_decoratorr*  {  s8    _T+ + + + + Nr!   +Literal['mps', 'cuda', 'npu', 'hpu', 'cpu']c                 ,   t           j                                        rdS t           j        j                                        rdS t                      rdS t          j                            d          ddl	m c m
}  |                                 rdS dS )	aH  
    Returns the name of the device where this module is running on.

    It's a simple implementation that doesn't cover cases when more powerful GPUs are available and
    not a primary device ('cuda:0') or MPS device is available, but not configured properly.

    Returns:
        str: Device name, like 'cuda' or 'cpu'
    r  mpsr  habana_frameworksNr   hpur   )r   r  is_availablebackendsr-  r   r  util	find_spechabana_frameworks.torch.hpur/  )hthpus    r   get_device_namer6    s     z   
v			(	(	*	* u		!	! u		!	!"5	6	6	B333333333 	55r!   package_nameownerc                p    	 t          |           }|d         | k    o	||d         v S # t          $ r Y dS w xY w)zB
    Checks if a package is available from the correct owner.
    Namez	Home-pageF)r   r   )r7  r8  metas      r   check_package_availabilityr<    sT    %%F||+Jk9J0JJ   uus   $' 
55c                 "    t          dd          S )zJ
    Returns True if the Huggingface accelerate library is available.
    
acceleratehuggingfacer<  rh   r!   r   is_accelerate_availablerA    s     &lMBBBr!   c                 "    t          dd          S )zH
    Returns True if the Huggingface datasets library is available.
    rD  r?  r@  rh   r!   r   rB  rB    s     &j-@@@r!   c                 :    t                      ot                      S )z
    Returns True if we have the required dependencies for training Sentence
    Transformers models, i.e. Huggingface datasets and Huggingface accelerate.
    )rA  rB  rh   r!   r   is_training_availablerD    s    
 #$$@)>)@)@@r!   c               #     K   ddl m} m}m}  |            }	 |r
 |              dV  |r |             dS dS # |r |             w w xY w)zN
    A context manager that will disable caching in the datasets library.
    r   )disable_cachingenable_cachingis_caching_enabledN)rD  rF  rG  rH  )rF  rG  rH  is_originally_enableds       r   disable_datasets_cachingrJ    s      
 MLLLLLLLLL..00  	O  	N	 	  	N	s	   8 A)r   r   r   r   )r   r   r   r   )r   r   r)   r   r   r   )r   r   r)   r   r   r   )r   r   r)   r   )rN   r   rO   r   r   r   )r^   r   r   r   )r^   rc   rd   re   r   rc   )r^   rk   rd   re   r   rk   )r^   rm   rd   re   r   rm   )rq   rr   rs   rt   ru   rv   rw   rv   rx   rv   ry   rv   rz   rv   r{   r|   r   r}   )r^   r   rw   rv   rx   rv   ry   rv   rz   rv   r{   r|   r   r}   )r   r   )r   r   r   r   rw   rv   rx   rv   rz   rv   r{   r|   r   r   )NNNNr   NNNNr   r   Tro   r   FT)&r   r   r   r   r   r   r   r   r   r   r   r   r   rv   r   re   r   r   r   r   r   r   r   rv   r   r   r   rt   ru   rv   r   rv   r   rt   r   rt   r   r   )r  r  r  r  r   r  )r  r  r  r   r   r  )r   r  )r  r  r   r  )r=  r   r  F)r^   r  r  r3  r  rv   ru   rv   rs   rt   r   r  )NNNF)r  r  r  r	  r
  r   r  r   r  rt   r   rt   )r  r  r  r  r  r	  r
  r   r  r   r  rt   r   r   )r  r  r  r  r  r	  r
  r   r  r   r  rt   r   r   )r   r+  )r7  r  r8  r  r   rt   )r   rt   )R
__future__r   r(  r   r  r  r  r   r  r  
contextlibr   importlib.metadatar   r   typingr   r   r	   r
   r   numpyr   r  r   huggingface_hubr   r   r   r   r   r   tqdm.autonotebooktransformersr   	getLoggerr  r$  rD  r   0sentence_transformers.cross_encoder.CrossEncoderr   )sentence_transformers.SentenceTransformerr   r    r&   r(   r.   r,   r7   r9   r6   rC   rG   rI   rM   r]   r0   rj   r   r   r   r   r  r  r  r  r  r  r  CRITICALr  r  r  r  r*  r6  r<  rA  rB  rD  rJ  rh   r!   r   <module>rW     s   " " " " " "           				   



 % % % % % % = = = = = = = = B B B B B B B B B B B B B B       > > > > > > > >                       " " " " " " / / / / / /		8	$	$ N      MMMMMMMMMMMM            4 4 4 4&P P P P"* * * *"   "% % % %"0 0 0 0"% % % %"8 8 8 8"! ! ! !D
A 
A 
A 
A 
 \ \ \ 
 \ 
 ` ` ` 
 `* * * *F $ #9@* * * * *^ !#9@F F F F FR, , , ,  #9@M M M M Mf &*'+#)- ""27!%n n n n nb" " " "J   "3 3 3 38! ! ! !L  #c c c c cV    D   ( ")"2 ( ( ( (*  $#"    F  $#"' ' ' ' 'Z  $#",. ,. ,. ,. ,.^  (   0   C C C CA A A AA A A A     r!   