
    Nj;5                    ~   d dl mZ d dlZd dl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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 d dlmZmZ d dlm Z   ejB                  d      Z"dZ# ede$e%   e$e$e%            Z& G d de%e      Z' G d d      Z(	 d	 	 	 	 	 	 	 ddZ)ddZ*ddZ+	 d	 	 	 	 	 	 	 ddZ,y)    )annotationsN)Sequence)Enum)Path)TemporaryDirectory)TypeVarcast)classification_report)MLPClassifierMLPRegressor)Pipeline)MultiLabelBinarizer)PathLikeStaticModel)create_model_cardzsklearn\..+zpipeline.skops	LabelTypec                      e Zd ZdZdZdZy)HeadType
classifier	projector
multilabelN)__name__
__module____qualname__
CLASSIFIER	PROJECTOR
MULTILABEL     j/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/model2vec/inference/model.pyr   r      s    JIJr   r   c                  
   e Zd Zd
dZe	 d	 	 	 	 	 	 	 	 	 dd       ZddZ	 d	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ		 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ
	 d	 	 	 	 	 	 	 	 	 	 	 dd	Zy)StaticModelPipelinec                   || _         || _        | j                  d   }d| _        t        |t              rt
        j                  | _        yt        |t              rR|j                  }|dk(  rt
        j                  nt
        j                  | _        | j                  j                  | _        yt
        j                  | _        y)z-Create a pipeline with a StaticModel encoder.Nlogistic)modelheadclasses_
isinstancer   r   r   classifier_typer   out_activation_r   r   )selfr&   r'   	last_head
activations        r    __init__zStaticModelPipeline.__init__"   s    
	IIbM	+/i.#+#5#5D 	=1"22J:D
:R8#6#6X`XkXkD  II..DM $,#6#6D r   Nc                |    t        |||      \  }}t        j                  |j                        |_         | ||      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 the folder containing the pipeline, or a repository on the Hugging Face Hub
        :param token: The token to use to download the pipeline from the hub.
        :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming from `sklearn`.
        :return: The loaded pipeline.
        )_load_pipelinenp
nan_to_num	embedding)clspathtokentrust_remote_coder&   r'   s         r    from_pretrainedz#StaticModelPipeline.from_pretrained3   s8     %T52CDt--85$r   c                    t        | |       y)zSave the model to a folder.N)save_pipeline)r,   r6   s     r    save_pretrainedz#StaticModelPipeline.save_pretrainedE   s    dD!r   c                    ddl m} t               5 }t        | |       | j                  j                  |        |t        |      ||||       ddd       y# 1 sw Y   yxY w)a:  Save a model to a folder, and then push that folder to the hf hub.

        :param repo_id: The id of the repository to push to.
        :param subfolder: The subfolder to push to.
        :param token: The token to use to push to the hub.
        :param private: Whether the repository should be private.
        r   )push_folder_to_hubN)model2vec.persistencer>   r   r;   r&   r<   r   )r,   repo_id	subfolderr7   privater>   temp_dirs          r    push_to_hubzStaticModelPipeline.push_to_hubI   sK     	=!X$)JJ&&x0tH~y'7ER "!!s   =AA c                    | j                   j                  ||||||      }t        j                  |      dk(  r	|dddf   }|S )z7Encode the instances and coerce the output to a matrix.show_progress_bar
max_length
batch_sizeuse_multiprocessingmultiprocessing_threshold   N)r&   encoder2   ndimr,   XrG   rH   rI   rJ   rK   encodeds           r    _encode_and_coerce_to_2dz,StaticModelPipeline._encode_and_coerce_to_2dZ   sU     **##/!! 3&? $ 
 777q dAg&Gr   c                |   | j                  ||||||      }| j                  t        j                  k(  rn| j                  J g }	| j
                  j                  |      }
|
D ]#  }|	j                  | j                  ||kD            % t        j                  |	t              S | j
                  j                  |      S )a  Predict the labels of the input.

        :param X: The input data to predict. Can be a list of strings or a single string.
        :param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
        :param max_length: The maximum length of the input sequences. Defaults to 512.
        :param batch_size: The batch size for prediction. Defaults to 1024.
        :param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
        :param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
        :param threshold: The threshold for multilabel classification. Defaults to 0.5. Ignored if not multilabel.
        :return: The predicted labels or probabilities.
        rF   )dtype)rR   r*   r   r   r(   r'   predict_probaappendr2   asarrayobjectpredict)r,   rP   rG   rH   rI   rJ   rK   	thresholdrQ   
out_labelsprobavectors               r    rY   zStaticModelPipeline.predictq   s    * ///!! 3&? 0 
 8#6#66==,,,JII++G4E!!$--0B"CD  ::j77yy  ))r   c                    | j                   t        j                  k(  rt        d      | j	                  ||||||      }| j
                  j                  |      S )a  Predict the labels of the input.

        :param X: The input data to predict. Can be a list of strings or a single string.
        :param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False.
        :param max_length: The maximum length of the input sequences. Defaults to 512.
        :param batch_size: The batch size for prediction. Defaults to 1024.
        :param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True.
        :param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000.
        :return: The predicted labels or probabilities.
        :raises ValueError: If the classifier type is projector.
        CYou are using evaluate on a projector model. This is not supported.rF   )r*   r   r   
ValueErrorrR   r'   rU   rO   s           r    rU   z!StaticModelPipeline.predict_proba   sb    ( 8#5#55bcc///!! 3&? 0 
 yy&&w//r   c                    | j                   t        j                  k(  rt        d      | j	                  |d||      }t        |||      }|S )a  Evaluate the classifier on a given dataset using scikit-learn's classification report.

        :param X: The texts to predict on.
        :param y: The ground truth labels.
        :param batch_size: The batch size.
        :param threshold: The threshold for multilabel classification.
        :param output_dict: Whether to output the classification report as a dictionary.
        :return: A classification report.
        :raises ValueError: If the classifier type is projector.
        r_   T)rG   rI   rZ   )predictionsyoutput_dict)r*   r   r   r`   rY   evaluate_single_or_multi_label)r,   rP   rc   rI   rZ   rd   rb   reports           r    evaluatezStaticModelPipeline.evaluate   sO     8#5#55bccll1_hli/K1Zefr   )r&   r   r'   r   returnNoneNF)
r5   ztype[StaticModelPipeline]r6   r   r7   
str | Noner8   boolrh   r"   )r6   strrh   ri   )NNF)
r@   rm   rA   rk   r7   rk   rB   rl   rh   ri   )rP   Sequence[str]rG   rl   rH   
int | NonerI   intrJ   rl   rK   rp   rh   
np.ndarray)F      T'        ?)rP   rn   rG   rl   rH   ro   rI   rp   rJ   rl   rK   rp   rZ   floatrh   rq   )Frr   rs   Trt   )rs   ru   F)rP   rn   rc   r   rI   rp   rZ   rv   rd   rl   rh   !str | dict[str, dict[str, float]])r   r   r   r/   classmethodr9   r<   rD   rR   rY   rU   rg   r   r   r    r"   r"   !   s   7" lq & .6 ?I ei 	   ""
 ejSS'1SAKS]aS	S"   	
  " $' 
4 #(!$$()/&*&*  &* 	&*
 &* "&* $'&* &* 
&*V #(!$$()/00  0 	0
 0 "0 $'0 
0D sx#,:=QVko	*r   r"   c                   t        |       } t        }| j                         r#| |z  }|j                         s4t        d|        t	        j
                  | j                         ||      }t        j                  |       }t        j                  j                  |      }|s+|D ]&  }t        j                  |      rt        d| d       t        j                  j                  ||      }||fS )a  Load a model and an sklearn pipeline.

    This assumes the following files are present in the repo:
    - `pipeline.skops`: The head of the pipeline.
    - `config.json`: The configuration of the model.
    - `model.safetensors`: The weights of the model.
    - `tokenizer.json`: The tokenizer of the model.

    :param folder_or_repo_path: The path to the folder containing the pipeline.
    :param token: The token to use to download the pipeline from the hub. If this is None, you will only
        be able to load the pipeline from a local folder, public repository, or a repository that you have access to
        because you are logged in.
    :param trust_remote_code: Whether to trust the remote code. If this is False,
        we will only load components coming from `sklearn`. If this is True, we will load all components.
        If you set this to True, you are responsible for whatever happens.
    :return: The encoder model and the loaded head
    :raises FileNotFoundError: If the pipeline file does not exist in the folder.
    :raises ValueError: If an untrusted type is found in the pipeline, and `trust_remote_code` is False.
    z Pipeline file does not exist in )r7   )filezUntrusted type .)trusted)r   _DEFAULT_MODEL_FILENAMEexistsFileNotFoundErrorhuggingface_hubhf_hub_downloadas_posixr   r9   skopsioget_untrusted_types_DEFAULT_TRUST_PATTERNmatchr`   load)	folder_or_repo_pathr7   r8   model_filenamehead_pipeline_pathr&   unknown_typestr'   s	            r    r1   r1      s    , 23,N!!#0>A!((*#&FGZF[$\]],<<((*N%
 ''(;<EHH006H0IM A)//2 ?1#Q!788  88==+]=CD$;r   c                   t        |      }|j                  dd       t        }||z  }t        j                  j                  | j                  |       | j                  j                  |       | j                  j                  }t        |t              r|r|d   }nt        |t              r|}nd}t        ||| j                  j                  d       y)zSave a pipeline to a folder.

    :param pipeline: The pipeline to save.
    :param folder_path: The path to the folder to save the pipeline to.
    T)parentsexist_okr   unknownzclassifier_template.md)base_model_namelanguagetemplate_pathN)r   mkdirr}   r   r   dumpr'   r&   r<   r   r)   listrm   r   r   )pipelinefolder_pathr   r   r   names         r    r;   r;      s     {#KdT2,N$~5	HHMM(--!34NN"";/nn44O/4(_q!	OS	)((.	r   c                    t        | t        t        f      xr. t        |       dkD  xr t        | d   t        t        t        f      S )z/Check if the labels are in a multi-label shape.r   )r)   r   tuplelenset)rc   s    r    _is_multi_label_shapedr     s9    a$'_CFQJ_:adTSXZ]L^;__r   c           
     J   t        |      rt        t        t        t              t        t        t              z  |      }t        t        |D cg c]  }|D ]  }|  c}}            }t        |      }|j                  |      }|j                  |       }nut        d |D              r9t        t        t           t        t           z  |      }t        t        |            }t        j                  |      }t        j                  |       }t        |||d      }	|	S c c}}w )a'  Evaluate the classifier on a given dataset using scikit-learn's classification report.

    :param predictions: The predictions.
    :param y: The ground truth labels.
    :param output_dict: Whether to output the classification report as a dictionary.
    :return: A classification report.
    )classesc              3  H   K   | ]  }t        |t        t        f        y w)N)r)   rm   rp   ).0labels     r    	<genexpr>z1evaluate_single_or_multi_label.<locals>.<genexpr>3  s     <!z%#s,!s    "r   )rd   zero_division)r   r	   r   rm   rp   sortedr   r   fit_transform	transformallr2   arrayr
   )
rb   rc   rd   labelsr   r   mlby_transformedpredictions_transformedrf   s
             r    re   re     s     a d3i4S	?2A6!H!ee!HIJ!'2))!,"%--"<<!<<T#Yc*A.ASVnG"$((;"7"	F M% Is   Drj   )r   r   r7   rk   r8   rl   rh   ztuple[StaticModel, Pipeline])r   r"   r   z
str | Pathrh   ri   )rc   9list[int] | list[str] | list[list[int]] | list[list[str]]rh   rl   )F)rb   rq   rc   r   rd   rl   rh   rw   )-
__future__r   recollections.abcr   enumr   pathlibr   tempfiler   typingr   r	   r   numpyr2   skops.ior   sklearn.metricsr
   sklearn.neural_networkr   r   sklearn.pipeliner   sklearn.preprocessingr   model2vec.modelr   r   model2vec.modelcardsr   compiler   r}   r   rm   r   r   r"   r1   r;   r   re   r   r   r    <module>r      s    " 	 $   '      1 > % 5 1 2#N3 * KcDcO<	sD k k^ X]-!-*4-PT-!-`6` !!@! ! '	!r   