a
    h-                     @  s   d dl mZ d dl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mZ d dlmZ d dlmZ d dlmZ d dlmZmZmZmZ erd d	lmZ eeZG d
d deZdS )    )annotationsN)TYPE_CHECKINGLiteral)pearsonr	spearmanr)SentenceEvaluator)InputExample)SimilarityFunction)pairwise_cos_simpairwise_dot_scorepairwise_euclidean_simpairwise_manhattan_sim)SentenceTransformerc                      s   e Zd ZdZd,dddd	d
ddddddd fddZdddddZeddddZd-ddd	d	ddd d!Zdd"d#d$d%d&Z	e
dd'd(d)Zd*d+ Z  ZS ).EmbeddingSimilarityEvaluatora  
    Evaluate a model based on the similarity of the embeddings by calculating the Spearman and Pearson rank correlation
    in comparison to the gold standard labels.
    The metrics are the cosine similarity as well as euclidean and Manhattan distance
    The returned score is the Spearman correlation with a specified metric.

    Args:
        sentences1 (List[str]): List with the first sentence in a pair.
        sentences2 (List[str]): List with the second sentence in a pair.
        scores (List[float]): Similarity score between sentences1[i] and sentences2[i].
        batch_size (int, optional): The batch size for processing the sentences. Defaults to 16.
        main_similarity (Optional[Union[str, SimilarityFunction]], optional): The main similarity function to use.
            Can be a string (e.g. "cosine", "dot") or a SimilarityFunction object. Defaults to None.
        similarity_fn_names (List[str], optional): List of similarity function names to use. If None, the
            ``similarity_fn_name`` attribute of the model is used. Defaults to None.
        name (str, optional): The name of the evaluator. Defaults to "".
        show_progress_bar (bool, optional): Whether to show a progress bar during evaluation. Defaults to False.
        write_csv (bool, optional): Whether to write the evaluation results to a CSV file. Defaults to True.
        precision (Optional[Literal["float32", "int8", "uint8", "binary", "ubinary"]], optional): The precision
            to use for the embeddings. Can be "float32", "int8", "uint8", "binary", or "ubinary". Defaults to None.
        truncate_dim (Optional[int], optional): The dimension to truncate sentence embeddings to. `None` uses the
            model's current truncation dimension. Defaults to None.

    Example:
        ::

            from datasets import load_dataset
            from sentence_transformers import SentenceTransformer
            from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator, SimilarityFunction

            # Load a model
            model = SentenceTransformer('all-mpnet-base-v2')

            # Load the STSB dataset (https://huggingface.co/datasets/sentence-transformers/stsb)
            eval_dataset = load_dataset("sentence-transformers/stsb", split="validation")

            # Initialize the evaluator
            dev_evaluator = EmbeddingSimilarityEvaluator(
                sentences1=eval_dataset["sentence1"],
                sentences2=eval_dataset["sentence2"],
                scores=eval_dataset["score"],
                name="sts_dev",
            )
            results = dev_evaluator(model)
            '''
            EmbeddingSimilarityEvaluator: Evaluating the model on the sts-dev dataset:
            Cosine-Similarity:  Pearson: 0.8806 Spearman: 0.8810
            '''
            print(dev_evaluator.primary_metric)
            # => "sts_dev_pearson_cosine"
            print(results[dev_evaluator.primary_metric])
            # => 0.881019449484294
       N FTz	list[str]zlist[float]intzstr | SimilarityFunction | Nonez?list[Literal['cosine', 'euclidean', 'manhattan', 'dot']] | Nonestrboolz?Literal['float32', 'int8', 'uint8', 'binary', 'ubinary'] | Nonez
int | None)
sentences1
sentences2scores
batch_sizemain_similaritysimilarity_fn_namesnameshow_progress_bar	write_csv	precisiontruncate_dimc                   s  t    || _|| _|| _|	| _|
| _|| _t| jt| jksFJ t| jt| jks^J |rjt	|nd | _
|pvg | _| jg kr| j
d ur| j
jg| _|| _|| _|d u rt tjkpt tjk}|| _d|rd| nd |
rd|
 nd d | _ddg| _| | j d S )NZsimilarity_evaluation_r   z_results.csvepochsteps)super__init__r   r   r   r   r   r   lenr	   r   r   valuer   r   loggergetEffectiveLevelloggingINFODEBUGr   csv_filecsv_headers_append_csv_headers)selfr   r   r   r   r   r   r   r   r   r   r   	__class__ y/var/www/html/assistant/venv/lib/python3.9/site-packages/sentence_transformers/evaluation/EmbeddingSimilarityEvaluator.pyr$   R   s>    

z%EmbeddingSimilarityEvaluator.__init__None)r   returnc                 C  s6   ddg}|D ]$}|D ]}| j | d|  qqd S )Npearsonspearmanr    )r-   append)r/   r   metricsvmr2   r2   r3   r.      s    z0EmbeddingSimilarityEvaluator._append_csv_headerszlist[InputExample])examplesc                 K  sV   g }g }g }|D ]0}| |jd  | |jd  | |j q| |||fi |S )Nr      )r8   Ztextslabel)clsr<   kwargsr   r   r   Zexampler2   r2   r3   from_input_examples   s    z0EmbeddingSimilarityEvaluator.from_input_examplesr   z
str | Nonezdict[str, float])modeloutput_pathr!   r"   r5   c              	     s  |dkr0|dkrd| }q4d| d| d}nd}| j d urP|d| j  d7 }td	| j d
| d | || j}| || j}| jdkr|d t	j
}|d t	j
}| jdv rt	j|dd}t	j|dd}| j}| js|jg| _| | j dd dd dd dd d}	i  | jD ]}
|
|	v r |	|
 ||   }t||\}}t||\}}| d|
 < | d|
 < t|
  d|dd|d q |d urN| jrNtj|| j}tj|}t|d|rdndddN}t|}|s|| j  |||g fd d!| jD   W d    n1 sD0    Y  t!| jdkrt" fd"d#| jD  d$< t" fd%d#| jD  d&< | j#rt$j%d't$j&d(t$j'd)t$j(d*i)| j#| _*n*t!| jdkrd&| _*nd| jd+  | _*| + | j | ,| ||  S ),NrB   z after epoch z
 in epoch z after z stepsr   z (truncated to )z:EmbeddingSimilarityEvaluator: Evaluating the model on the z dataset:binary   )ZubinaryrG   r=   )Zaxisc                 S  s
   t | |S N)r
   xyr2   r2   r3   <lambda>       z7EmbeddingSimilarityEvaluator.__call__.<locals>.<lambda>c                 S  s
   t | |S rI   )r   rJ   r2   r2   r3   rM      rN   c                 S  s
   t | |S rI   )r   rJ   r2   r2   r3   rM      rN   c                 S  s
   t | |S rI   )r   rJ   r2   r2   r3   rM      rN   )ZcosineZ	manhattanZ	euclideandotpearson_	spearman_z-Similarity:	Pearson: z.4fz	Spearman: awzutf-8)newlinemodeencodingc                   s(   g | ] }d D ]} | d|  qqS ))r6   r7   r    r2   ).0fn_nameZmetricr9   r2   r3   
<listcomp>   s   z9EmbeddingSimilarityEvaluator.__call__.<locals>.<listcomp>c                 3  s   | ]} d |  V  qdS )rP   Nr2   rW   rX   rY   r2   r3   	<genexpr>   rN   z8EmbeddingSimilarityEvaluator.__call__.<locals>.<genexpr>Zpearson_maxc                 3  s   | ]} d |  V  qdS )rQ   Nr2   r[   rY   r2   r3   r\      rN   Zspearman_maxZspearman_cosineZspearman_euclideanZspearman_manhattanZspearman_dotr   )-r   r'   infor   embed_inputsr   r   r   ZastypenpZuint8Z
unpackbitsr   r   Zsimilarity_fn_namer.   detachcpunumpyr   r   
capitalizer   ospathjoinr,   isfileopencsvwriterwriterowr-   r%   maxr   r	   ZCOSINEZ	EUCLIDEANZ	MANHATTANZDOT_PRODUCTgetZprimary_metricZprefix_name_to_metricsZ store_metrics_in_model_card_data)r/   rC   rD   r!   r"   Zout_txtZembeddings1Zembeddings2labelsZsimilarity_functionsrX   r   Zeval_pearsonr    Zeval_spearmanZcsv_pathZoutput_file_existsfrj   r2   rY   r3   __call__   s    







$z%EmbeddingSimilarityEvaluator.__call__zstr | list[str] | np.ndarrayz
np.ndarray)rC   	sentencesr5   c              	   K  s.   |j |f| j| jd| jt| j| jd|S )NT)r   r   Zconvert_to_numpyr   Znormalize_embeddingsr   )encoder   r   r   r   r   )r/   rC   rq   r@   r2   r2   r3   r^      s    z)EmbeddingSimilarityEvaluator.embed_inputs)r5   c                 C  s   dS )NzSemantic Similarityr2   )r/   r2   r2   r3   description  s    z(EmbeddingSimilarityEvaluator.descriptionc                 C  s6   i }ddg}|D ] }t | |d urt | |||< q|S )Nr   r   )getattr)r/   Zconfig_dictZconfig_dict_candidate_keyskeyr2   r2   r3   get_config_dict	  s    z,EmbeddingSimilarityEvaluator.get_config_dict)r   NNr   FTNN)NrB   rB   )__name__
__module____qualname____doc__r$   r.   classmethodrA   rp   r^   propertyrs   rv   __classcell__r2   r2   r0   r3   r      s&   ;        (4 [r   )
__future__r   ri   r)   rd   typingr   r   rb   r_   Zscipy.statsr   r   Z2sentence_transformers.evaluation.SentenceEvaluatorr   Zsentence_transformers.readersr   Z*sentence_transformers.similarity_functionsr	   Zsentence_transformers.utilr
   r   r   r   Z)sentence_transformers.SentenceTransformerr   	getLoggerrw   r'   r   r2   r2   r2   r3   <module>   s   
