
    Nj	X                    8   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m	Z	 d dl
mZ d dlmZ d dlmZmZ d dlZd dlmZ d d	lmZmZ d d
lmZ d dlmZmZ d dlmZ eez  Z e	e       Z! G d d      Z"	 	 	 d	 	 	 	 	 	 	 	 	 ddZ#	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ$y)    )annotationsN)IteratorSequence)	getLogger)Path)TemporaryDirectory)Anyoverload)delayed)Encoding	Tokenizer)tqdm)DTypequantize_and_reduce_dim)ProgressParallelc                  t    e Zd Z	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZedd       Zedd       Zej                  dd       Zedd       Zedd       Z	dddZ
dddZe	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d d	       Ze	 	 	 	 	 	 d!	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d"d
       Ze	 	 	 	 	 d#	 	 	 	 	 	 	 	 	 	 	 	 	 d$d       Ze	 	 	 	 	 d#	 	 	 	 	 	 	 	 	 	 	 	 	 d%d       Z	 	 	 	 	 d#	 	 	 	 	 	 	 	 	 	 	 	 	 d&dZd'dZ	 	 	 	 	 d(	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d)dZd*dZd+dZed,d       Z	 d-	 	 	 	 	 	 	 	 	 d.dZ xZS )/StaticModelc	           
        t         |           t        t        |j	                         j                         d        \  }	}
|	| _        |;t        |      t        |	      k7  r$t        dt        |	       dt        |       d      || _	        || _
        || _        || _        |  t        | j                  j                  d      rW| j                  j                  j                  7|j	                         | j                  j                  j                     | _        nd| _        t#        t%        j&                  | j                  D cg c]  }t        |       c}            | _        |xs i | _        || _        || _        t        | j                  d      rd	| _        nd
| _        ||| _        y| j*                  j5                  dd
      | _        yc c}w )a  Initialize the StaticModel.

        :param vectors: The vectors to use.
        :param tokenizer: The Transformers tokenizer to use.
        :param config: Any metadata config.
        :param normalize: Whether to normalize the embeddings.
        :param base_model_name: The used base model name. Used for creating a model card.
        :param language: The language of the model. Used for creating a model card.
        :param weights: The weights to use for the embeddings. If None, no weights are used.
            We always assume the norm of the embeddings is an implicit weight anyway.
            This is only used for models that have undergone vocabulary quantization.
        :param token_mapping: A mapping from token ids to indices in the vectors.
            If None, we don't remap the tokens during inference.
            This is only used for models that have undergone vocabulary quantization.
        :raises ValueError: if the number of tokens does not match the number of vectors.
        c                    | d   S )N    )xs    `/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/model2vec/model.py<lambda>z&StaticModel.__init__.<locals>.<lambda>6   s    QqT    )keyNzNumber of tokens (z$) does not match number of vectors (z_). Please provide a token mapping or ensure the number of tokens matches the number of vectors.	unk_tokenencode_batch_fastTF	normalize)super__init__zipsorted	get_vocabitemstokenslen
ValueError	embeddingweightstoken_mapping	tokenizerhasattrmodelr   unk_token_idintnpmedianmedian_token_lengthconfigbase_model_namelanguage_can_encode_fastr   get)selfvectorsr,   r4   r   r5   r6   r*   r+   r&   _token	__class__s               r   r!   zStaticModel.__init__   s   6 		 3 3 5 ; ; =>RS	 S\S[%@$S[M1UVYZaVbUc do o 
 ! 1>"4>>''5$..:N:N:X:X:d ) 3 3 5dnn6J6J6T6T UD $D#&ryy$++1V+#e*+1V'W#X l. 4>>#67$(D!$)D! &DN![[__[%@DN 2Ws   Gc                4    | j                   j                  d   S )zGet the dimension of the model.r   )r)   shaper9   s    r   dimzStaticModel.dimZ   s     ~~##A&&r   c                    | j                   S )zHGet the normalize value.

        :return: The normalize value.
        )
_normalizer@   s    r   r   zStaticModel.normalize_   s     r   c                    | j                   j                  d      }|| _        |!||k7  rt        j	                  d| d| d       || j                   d<   y)z4Update the config if the value of normalize changes.r   NzSet normalization to `z&`, which does not match config value `z`. Updating config.)r4   r8   rC   loggerwarning)r9   valueconfig_normalizes      r   r   zStaticModel.normalizeg   s^      ;;??;7'E5E,ENN(/UVfUggz{ $)K r   c                h    t        j                  | j                  j                        j                  S )z2Get the dtype (precision) of the embedding matrix.)r1   dtyper)   namer@   s    r   embedding_dtypezStaticModel.embedding_dtyper   s#     xx,,-222r   c                    | j                   duxs+ t        | j                        t        | j                        k7  }|r"t	        | j                  j
                  d         S dS )zKGet the number of clusters used for vocabulary quantization, if applicable.Nr   )r+   r'   r)   r&   r0   r?   )r9   is_quantizeds     r   vocabulary_quantizationz#StaticModel.vocabulary_quantizationw   sU     **$6dC<OSVW[WbWbSc<c/;s4>>''*+EEr   c                    ddl m}  |t        |      | j                  | j                  | j
                  | j                  | j                  ||| j                  | j                  
       y)zSave the pretrained model.

        :param path: The path to save to.
        :param model_name: The model name to use in the Model Card.
        :param subfolder: The subfolder to save to.
        r   )save_pretrained)
folder_path
embeddingsr,   r4   r5   r6   
model_name	subfolderr*   mappingN)
model2vec.persistencerQ   r   r)   r,   r4   r5   r6   r*   r+   )r9   pathrT   rU   rQ   s        r   rQ   zStaticModel.save_pretrained}   sQ     	:T
~~nn;; 00]]!LL&&	
r   c           	        |!|| j                   z  }|D cg c]  }|d| 	 }}| j                  r| j                  j                  |d      }n| j                  j	                  |d      }|D cg c]  }|j
                   }}| j                  /|D 	cg c]"  }|D 	cg c]  }	|	| j                  k7  s|	 c}	$ }}}	||D cg c]  }|d| 	 }}|S c c}w c c}w c c}	w c c}	}w c c}w )a  Tokenize a list of sentences.

        :param sentences: The sentences to tokenize.
        :param max_length: The maximum length of the sentences in tokens. If this is None, sequences
            are not truncated.
        :return: A list of list of tokens.
        NF)add_special_tokens)r3   r7   r,   r   encode_batchidsr/   )
r9   	sentences
max_lengthmsentence	encodingsencodingencodings_ids	token_idstoken_ids
             r   tokenizezStaticModel.tokenize   s    !T555A6?@i("1iI@  (,(H(Hgl(H(mI33IRW3XI6?@i(i@( hugtZc)U)hx4CTCT7T)Ugt   !ERS]	Y{
3]MS# A A
 V Ts/   C/C	C$C3C7C$C*C$c	                *    t        | ||||||||	      S )a}  Load a StaticModel from a local path or huggingface hub path.

        NOTE: if you load a private model from the huggingface hub, you need to pass a token.

        :param path: The path to load your static model from.
        :param token: The huggingface token to use.
        :param normalize: Whether to normalize the embeddings.
        :param subfolder: The subfolder to load from.
        :param quantize_to: The dtype to quantize the model to. If None, no quantization is done.
            If a string is passed, it is converted to a DType.
        :param dimensionality: The dimensionality of the model. If this is None, use the dimensionality of the model.
            This is useful if you want to load a model with a lower dimensionality.
            Note that this only applies if you have trained your model using mrl or PCA.
        :param vocabulary_quantization: The number of clusters to use for vocabulary quantization.
        :param force_download: Whether to force the download of the model. If False, the model is only downloaded if it is not
            already present in the cache.
        :return: A StaticModel.
        	clsrX   r<   rO   quantize_todimensionalityr   rU   force_download)_loading_helper)	ri   rX   r<   r   rU   rj   rk   rO   rl   s	            r   from_pretrainedzStaticModel.from_pretrained   s,    < $;#))

 
	
r   c                b    t        j                  dt        d       t        | ||||||d|	      S )z Deprecated: use from_pretrained.zVStaticModel.from_sentence_transformers() is deprecated; use from_pretrained() instead.   )
stacklevelNrh   )warningswarnDeprecationWarningrm   )ri   rX   r<   r   rj   rk   rO   rl   s           r   from_sentence_transformersz&StaticModel.from_sentence_transformers   sC     	d	

 $;#))

 
	
r   c                     y Nr   r9   r]   r^   
batch_sizeshow_progress_baruse_multiprocessingmultiprocessing_thresholds          r   encode_as_sequencezStaticModel.encode_as_sequence   s     r   c                     y rw   r   rx   s          r   r}   zStaticModel.encode_as_sequence  s     r   c                    d}t        |t              r|g}d}t         j                  ||            }t	        j
                  t        |      |z        }	|rZt        |      |kD  rLdt        j                  d<    t        d||	       fd|D              }
g }|
D ]  }|j                  |        n7g }t        ||	|       D ]#  }|j                   j                  |             % |r|d	   S |S )
a  Encode a list of sentences as a list of numpy arrays of tokens.

        This is useful if you want to use the tokens for further processing, or if you want to do sequence
        modeling.
        Note that if you just want the mean, you should use the `encode` method.
        This is about twice as slow.
        Sentences that do not contain any tokens will be turned into an empty array.

        NOTE: the input type is currently underspecified. The actual input type is `Sequence[str] | str`, but this
            is not possible to implement in python typing currently.

        :param sentences: The list of sentences to encode.
        :param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated.
            If this is None, no truncation is done.
        :param batch_size: The batch size to use.
        :param show_progress_bar: Whether to show the progress bar.
        :param use_multiprocessing: Whether to use multiprocessing.
            By default, this is enabled for inputs > multiprocessing_threshold sentences and disabled otherwise.
        :param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing.
        :return: The encoded sentences with an embedding per token.
        FTfalseTOKENIZERS_PARALLELISMn_jobsuse_tqdmtotalc              3  V   K   | ]   } t        j                        |       " y wrw   )r   _encode_batch_as_sequence.0batchr^   r9   s     r   	<genexpr>z1StaticModel.encode_as_sequence.<locals>.<genexpr>9  s,      cXhu7667zJXh   &)r   disabler   )
isinstancestrlist_batchmathceilr'   osenvironr   extendr   r   )r9   r]   r^   ry   rz   r{   r|   
was_singlesentence_batchestotal_batchesresults	out_arrayrr   s   ` `           r   r}   zStaticModel.encode_as_sequence  s	   < 
i%"IJ  Iz BC		#i.:"=> 3y>4M#M3:BJJ/0b&b;LTab cXhc G +-I  #  I #--
   !?!?z!RS Q<r   c                    | j                  ||      }g }|D ]U  }|r!|j                  | j                  |             &|j                  t        j                  d| j
                  f             W |S )z*Encode a batch of sentences as a sequence.r]   r^   r   )rf   append_encode_helperr1   zerosrA   )r9   r]   r^   r\   outid_lists         r   r   z%StaticModel._encode_batch_as_sequenceL  sa    mmiJmG "G

4..w78

288QM23	  
r   c                    d}t        |t              r|g}d}t         j                  ||            }	t	        j
                  t        |      |z        }
|rWt        |      |kD  rIdt        j                  d<    t        d||
       fd|	D              }t        j                  |d	      }nNg }t        |	|
| 
      D ]#  }|j                   j                  |             % t        j                  |d	      }|r|d   S |S )a  Encode a list of sentences.

        This function encodes a list of sentences by averaging the word embeddings of the tokens in the sentence.
        For ease of use, we don't batch sentences together.

        NOTE: the return type is currently underspecified. In the case of a single string, this returns a 1D array,
            but in the case of a list of strings, this returns a 2D array. Not possible to implement in numpy currently.

        :param sentences: The list of sentences to encode. You can also pass a single sentence.
        :param show_progress_bar: Whether to show the progress bar.
        :param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated.
            If this is None, no truncation is done.
        :param batch_size: The batch size to use.
        :param use_multiprocessing: Whether to use multiprocessing.
            By default, this is enabled for inputs > multiprocessing_threshold sentences and disabled otherwise.
        :param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing.
        :param **kwargs: Any additional arguments. These are ignored.
        :return: The encoded sentences. If a single sentence was passed, a vector is returned.
        FTr   r   r   r   c              3  V   K   | ]   } t        j                        |       " y wrw   )r   _encode_batchr   s     r   r   z%StaticModel.encode.<locals>.<genexpr>  s,      cL\5+**+E:>L\r   r   axisr   )r   r   r   r   r   r   r'   r   r   r   r1   concatenater   r   r   )r9   r]   rz   r^   ry   r{   r|   kwargsr   r   r   r   r   
out_arraysr   s   `  `           r   encodezStaticModel.encodeX  s   : 
i%"IJ  Iz BC		#i.:"=> 3y>4M#M3:BJJ/0b&b;LTab cL\c G wQ7I ,.J #--
 !!$"4"4UJ"GH z:IQ<r   c                    | j                   |}n| j                   |   }| j                  |   }| j                  || j                  |   dddf   z  }|S )ah  Helper function to encode a list of ids.

        This function is used to deduplicate the logic in `encode` and `encode_as_sequence`.
        It retrieves the embeddings for the given list of ids, applying weights if available.

        :param id_list: A list of token ids.
        :return: The embeddings for the given ids, as a sequence of vectors.
        N)r+   r)   r*   )r9   r   id_list_remappedembs       r   r   zStaticModel._encode_helper  sa     %&#11':nn-.<<#W-ag66C
r   c                   | j                  ||      }g }|D ]e  }|r3| j                  |      }|j                  |j                  d             8|j                  t	        j
                  | j                               g t	        j                  |      }| j                  r*t        j                  j                  |dd      dz   }||z  }|S )zEncode a batch of sentences.r   r   r   r   T)r   keepdimsg3#I9)rf   r   r   meanr1   r   rA   stackr   linalgnorm)	r9   r]   r^   r\   r   r   r   r   r   s	            r   r   zStaticModel._encode_batch  s    mmiJmG "G))'2

3888+,

288DHH-.  HHSM	>>99>>)!d>CeKD!D(Ir   c                F      fdt        dt                     D        S )z%Batch the sentences into equal-sized.c              3  .   K   | ]  }||z      y wrw   r   )r   iry   r]   s     r   r   z%StaticModel._batch.<locals>.<genexpr>  s     \7[!	!a*n-7[s   r   )ranger'   )r]   ry   s   ``r   r   zStaticModel._batch  s     ]uQIPZ7[\\r   c                    ddl m} t               5 }| j                  ||        |t	        |      ||||       ddd       y# 1 sw Y   yxY w)a  Push the model to the huggingface hub.

        NOTE: you need to pass a token if you are pushing a private model.

        :param repo_id: The repo id to push to.
        :param private: Whether the repo, if created is set to private.
            If the repo already exists, this doesn't change the visibility.
        :param token: The huggingface token to use.
        :param subfolder: The subfolder to push to.
        r   )push_folder_to_hub)rT   )rU   repo_idprivater<   N)rW   r   r   rQ   r   )r9   r   r   r<   rU   r   temp_dirs          r   push_to_hubzStaticModel.push_to_hub  sD     	=!X  g >tH~G]dlqr "!!s   *AA)NNNNNN)r:   
np.ndarrayr,   r   r4   zdict[str, Any] | Noner   bool | Noner5   
str | Noner6   zlist[str] | Noner*   np.ndarray | Noner+   r   returnNone)r   r0   )r   bool)rG   r   r   r   )r   r   )r   
int | None)NN)rX   PathLikerT   r   rU   r   r   r   rw   )r]   Sequence[str]r^   r   r   zlist[list[int]])NNNNNNT)ri   type[StaticModel]rX   r   r<   r   r   r   rU   r   rj   str | DType | Nonerk   r   rO   r   rl   r   r   r   )NNNNNT)ri   r   rX   r   r<   r   r   r   rj   r   rk   r   rO   r   rl   r   r   r   )N   FT'  )r]   r   r^   r   ry   r0   rz   r   r{   r   r|   r0   r   r   )r]   z	list[str]r^   r   ry   r0   rz   r   r{   r   r|   r0   r   list[np.ndarray])r]   zstr | list[str]r^   r   ry   r0   rz   r   r{   r   r|   r0   r   zlist[np.ndarray] | np.ndarray)r]   r   r^   r   r   r   )Fi   r   Tr   )r]   r   rz   r   r^   r   ry   r0   r{   r   r|   r0   r   r	   r   r   )r   z	list[int]r   r   )r]   r   r^   r   r   r   )r]   r   ry   r0   r   zIterator[Sequence[str]])FNN)
r   r   r   r   r<   r   rU   r   r   r   )__name__
__module____qualname__r!   propertyrA   r   setterrL   rO   rQ   rf   classmethodrn   ru   r
   r}   r   r   r   r   staticmethodr   r   __classcell__)r=   s   @r   r   r      s   
 )-!%&*%)%)+/>A>A >A &	>A
 >A $>A #>A #>A )>A 
>A@ ' '   ) ) 3 3 F F

,:  !!% $*.%).2#'
'
'
 '
 	'

 '
 ('
 #'
 ",'
 '
 
'
 '
R  !!%*.%).2#


 
 	

 (
 #
 ",
 
 

 
8  "&"'$()/  	
   " $' 
   "&"'$()/  	
   " $' 
  "&"'$()/="= = 	=
  = "= $'= 
'=~
 #(!$$()/< <  < 	<
 < "< $'< < 
<|($ ] ]
 fjss%)s:DsXbs	sr   r   c           
        |`ddl m} t        | j                        t        | j                        k7  rt        d       ||| j                  | j                        \  }}}n$| j                  }| j                  }| j                  }||t        |||      }t        || j                  t        | j                        ||| j                  | j                  | j                        S )a  Quantize the model to a lower precision and possibly lower dimensionality.

    :param model: The model to quantize.
    :param vocabulary_quantization: The number of clusters to use for quantization.
    :param quantize_to: The dtype to quantize the model to.
    :param dimensionality: The desired dimensionality of the model.
        This needs to be < than the current model dimensionality.
    :return: A new StaticModel with the quantized embeddings.
    :raises ValueError: if the model is already quantized.
    r   )quantize_vocabularyzCModel already has been vocabulary quantized, cannot quantize again.)
n_clustersr*   rS   )rS   rj   rk   )r:   r,   r4   r*   r+   r   r5   r6   )!model2vec.vocabulary_quantizationr   r'   r&   r)   r(   r*   r+   r   r   r,   dictr4   r   r5   r6   )r.   rO   rj   rk   r   rS   r+   r*   s           r   quantize_modelr     s    $ *Iu||EOO 44bcc-@.RWRaRa.
*
M7 __
++--."<,!#)

 //ELL!#//--	 	r   c	                    ddl m}	  |	||||      \  }
}}}}} | |
||||||j                  d      |j                  d            }t        |||g      s|S t	        ||||      S )z1Helper function to load a model from a directory.r   )load_pretrained)folder_or_repo_pathr<   rU   rl   
base_modelr6   )r:   r,   r*   r+   r4   r   r5   r6   )r.   rO   rj   rk   )rW   r   r8   anyr   )ri   rX   r<   rO   rj   rk   r   rU   rl   r   rS   r,   r4   metadatar*   rV   r.   s                    r   rm   rm     s     6@O %	A=J	68Wg  \2j)	E 'nEF 7%	 r   )NNN)
r.   r   rO   r   rj   r   rk   r   r   r   )ri   r   rX   r   r<   r   rO   r   rj   r   rk   r   r   r   rU   r   rl   r   r   r   )%
__future__r   r   r   rr   collections.abcr   r   loggingr   pathlibr   tempfiler   typingr	   r
   numpyr1   joblibr   
tokenizersr   r   r   model2vec.quantizationr   r   model2vec.utilsr   r   r   r   rE   r   r   rm   r   r   r   <module>r      s    "  	  .   '     *  A ,#:	8	ys ys| +/&*!%	//'/ $/ 	/
 /d*	*
* * (	*
 $* * * * * *r   