o
    ॵi                     @   s   d dl mZmZ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 d dlmZ d d	lmZ d d
lmZmZ dgZejejejdG dd deZdS )    )AnyDictUnionN)softmax)	Pipelines)Model)
OutputKeys)Pipeline)	PIPELINES)Preprocessor)	ModelFileTasksZeroShotClassificationPipeline)module_namec                	       s   e Zd Z					ddeeef dededef fd	d
Zdd Zdd Z	de
eef de
eef fddZ	dde
eef de
eef fddZ  ZS )r   NgpuT   modelpreprocessorconfig_filedevicec                    s   t  j||||||dd|di d d| _d| _t| jts)J dtj	 |du rA|d	d
}t
j| jjfd	|i|| _| j  dS )u  Use `model` and `preprocessor` to create a nlp zero shot classifiction for prediction.

        A zero-shot classification task is used to classify texts by prompts.
        In a normal classification task, model may produce a positive label by the input text
        like 'The ice cream is made of the high quality milk, it is so delicious'
        In a zero-shot task, the sentence is converted to:
        ['The ice cream is made of the high quality milk, it is so delicious', 'This means it is good']
        And:
        ['The ice cream is made of the high quality milk, it is so delicious', 'This means it is bad']
        Then feed these sentences into the model and turn the task to a NLI task(entailment, contradiction),
        and compare the output logits to give the original classification label.


        Args:
            model (str or Model): Supply either a local model dir which supported the task,
            or a model id from the model hub, or a torch model instance.
            preprocessor (Preprocessor): An optional preprocessor instance, please make sure the preprocessor fits for
            the model if supplied.
            kwargs (dict, `optional`):
                Extra kwargs passed into the preprocessor's constructor.

        Examples:
            >>> from modelscope.pipelines import pipeline
            >>> pipeline_ins = pipeline(task='zero-shot-classification',
            >>>    model='damo/nlp_structbert_zero-shot-classification_chinese-base')
            >>> sentence1 = '全新突破 解放军运20版空中加油机曝光'
            >>> labels = ['文化', '体育', '娱乐', '财经', '家居', '汽车', '教育', '科技', '军事']
            >>> template = '这篇文章的标题是{}'
            >>> print(pipeline_ins(sentence1, candidate_labels=labels, hypothesis_template=template))

            To view other examples plese check tests/pipelines/test_zero_shot_classification.py.
        compileFcompile_options)r   r   r   r   auto_collater   r   r      z,please check whether model config exists in Nsequence_lengthr   )super__init__popentailment_idcontradiction_id
isinstancer   r   r   CONFIGURATIONr   from_pretrained	model_dirr   eval)selfr   r   r   r   r   r   kwargs	__class__ n/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/pipelines/nlp/zero_shot_classification_pipeline.pyr      s0   (


z'ZeroShotClassificationPipeline.__init__c                 K   sd   i }i }d|v r|  |d}||d< ||d< ntd|dd|d< |dd|d< |i |fS )Ncandidate_labelsz$You must include at least one label.hypothesis_templatez{}multi_labelF)_parse_labelsr   
ValueError)r%   r&   preprocess_paramspostprocess_paramsr+   r)   r)   r*   _sanitize_parametersV   s   

z3ZeroShotClassificationPipeline._sanitize_parametersc                 C   s.   t |tr|dd}dd |dD }|S )Nu   ，,c                 S   s   g | ]
}|  r|  qS r)   )strip).0labelr)   r)   r*   
<listcomp>h   s
    z@ZeroShotClassificationPipeline._parse_labels.<locals>.<listcomp>)r    strreplacesplit)r%   labelsr)   r)   r*   r.   e   s   
z,ZeroShotClassificationPipeline._parse_labelsinputsreturnc                 K   s   | j di ||S )Nr)   )r   )r%   r<   forward_paramsr)   r)   r*   forwardm   s   z&ZeroShotClassificationPipeline.forwardFc                    s   |t j   }|st dkr$|d| j| jgf }t|ddd n|d| jf }t|ddtt	
 }t j fdd|D t jfdd|D i}|S )	zprocess the prediction results
        Args:
            inputs (Dict[str, Any]): _description_
        Returns:
            Dict[str, Any]: the prediction results
           .)axis).r@   c                    s   g | ]} | qS r)   r)   r5   i)r+   r)   r*   r7      s    z>ZeroShotClassificationPipeline.postprocess.<locals>.<listcomp>c                    s   g | ]} |   qS r)   )itemrC   )scoresr)   r*   r7      s    )r   LOGITScpunumpylenr   r   r   listreversedargsortLABELSSCORES)r%   r<   r+   r-   logitsreversed_indexresultr)   )r+   rF   r*   postprocessq   s   
z*ZeroShotClassificationPipeline.postprocess)NNr   Tr   )F)__name__
__module____qualname__r   r   r8   r   r   r2   r.   r   r   r?   rS   __classcell__r)   r)   r'   r*   r      s4    
>



)typingr   r   r   torchscipy.specialr   modelscope.metainfor   modelscope.modelsr   modelscope.outputsr   modelscope.pipelines.baser	   modelscope.pipelines.builderr
   modelscope.preprocessorsr   modelscope.utils.constantr   r   __all__register_modulezero_shot_classificationr   r)   r)   r)   r*   <module>   s    