L i,ddlZddlZddlmZmZddlZddlmZm Z m Z m Z ddl m Z mZmZe rddlmZe rddlmZd Zd ZGd d eZe ed dGddeZy)N)AnyUnion) ExplicitEnumadd_end_docstringsis_tf_availableis_torch_available) GenericTensorPipelinebuild_pipeline_init_args)2TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES)/MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMESc:ddtj| zz S)Ng?)npexp)_outputss p/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/transformers/pipelines/text_classification.pysigmoidrs #y)) **ctj|dd}tj||z }||jddz S)NT)axiskeepdims)rmaxrsum)rmaxes shifted_exps rsoftmaxrs? FF8"t 4E&&E)*K b4@ @@rceZdZdZdZdZy)ClassificationFunctionrrnoneN)__name__ __module__ __qualname__SIGMOIDSOFTMAXNONErrr!r!sGG Drr!T) has_tokenizeraQ return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. In case of regression tasks, will not apply any function on the output. - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output.c eZdZdZdZdZdZdZdZe jZ fdZ d dZ deeeeeeefeeeeffdedeeeefffd Zdeeeffd Zd Zdd ZxZS)TextClassificationPipelinea Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification examples](../task_summary#sequence-classification) for more information. Example: ```python >>> from transformers import pipeline >>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english") >>> classifier("This movie is disgustingly good !") [{'label': 'POSITIVE', 'score': 1.0}] >>> classifier("Director tried too much.") [{'label': 'NEGATIVE', 'score': 0.996}] ``` Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This text classification pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"sentiment-analysis"` (for classifying sequences according to positive or negative sentiments). If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression tasks (`model.config.problem_type == "regression"`), will not apply any function on the output. The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See the up-to-date list of available models on [huggingface.co/models](https://huggingface.co/models?filter=text-classification). FTc t|di||j|jdk(r tyt y)Ntfr))super__init__check_model_type frameworkrr)selfkwargs __class__s rr0z#TextClassificationPipeline.__init__Ys= "6" ~~% ? A rc |}i}t|jjdr"| |jjj}t |t s| ||d<d|d<n)|'t jdt|rd|d<nd|d<t |trt|j}|||d<|i|fS)Nreturn_all_scorestop_kF_legacyz`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.r function_to_apply) hasattrmodelconfigr7 isinstanceintwarningswarn UserWarningstrr!upper)r3r7r:r8tokenizer_kwargspreprocess_paramspostprocess_paramss r_sanitize_parametersz/TextClassificationPipeline._sanitize_parametersbs- 4::$$&9 :?P?X $ 1 1 C C  eS !U]*/ w ',1 y )  * MM_  !.2"7+./"7+ ' - 67H7N7N7P Q   (6G 2 3 "&888rinputsr4returnc d|f}t||i|}d|v}t|dtr|r|gS|S)a Classify the text(s) given as inputs. Args: inputs (`str` or `list[str]` or `dict[str]`, or `list[dict[str]]`): One or several texts to classify. In order to use text pairs for your classification, you can send a dictionary containing `{"text", "text_pair"}` keys, or a list of those. top_k (`int`, *optional*, defaults to `1`): How many results to return. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: If this argument is not specified, then it will apply the following functions according to the number of labels: - If problem type is regression, will not apply any function on the output. - If the model has a single label, will apply the sigmoid function on the output. - If the model has several labels, will apply the softmax function on the output. Possible values are: - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. Return: A list of `dict`: Each result comes as list of dictionaries with the following keys: - **label** (`str`) -- The label predicted. - **score** (`float`) -- The corresponding probability. If `top_k` is used, one such dictionary is returned per label. r8r)r/__call__r>rC)r3rIr4resultr9r5s rrLz#TextClassificationPipeline.__call__sGN!64V4' fQi %'8OMrc |j}t|tr|jdi|d|i|St|trTt |dk(rFt|dtr3t |ddk(r"|jd|dd|dd|d|St|tr t d|j|fd|i|S)Nreturn_tensorsr rr)text text_pairrOzThe pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.r))r2r>dict tokenizerlistlen ValueError)r3rIrErOs r preprocessz%TextClassificationPipeline.preprocesss fd #!4>>^F^>^M]^ ^  %#f+*:z&QR)UY?Z_bcijkcl_mqr_r!4>>AYq\VAYq\.\l  %j t~~fX^XGWXXrc|jdk(r|jjn|jj}dt j |j vrd|d<|jdi|S)Npt use_cacheFr))r2r<forwardcallinspect signature parameters)r3 model_inputs model_forwards r_forwardz#TextClassificationPipeline._forwards].2nn.D **$**// '++M:EE E(-L %tzz)L))rcv|6|jjjdk(rtj}n|jjjdk(s#|jjj dk(rtj }n|jjjdk(s#|jjj dkDrtj}nSt|jjdr#|!|jjj}ntj}|dd}|jdk(r|jj}n|j}|tj k(r t|}nC|tjk(r t|}n$|tjk(r|}ntd ||dk(r`|r^|jjj |j#j%|j'j%d St)|Dcgc]9\}}|jjj ||j%d ;} }}|s| j+d d || d|} | Scc}}w)N regressionmulti_label_classificationr single_label_classificationr:logitsrrYz+Unrecognized `function_to_apply` argument: )labelscorec |dS)Nrir))xs rz8TextClassificationPipeline.postprocess..s 1W:rT)keyreverse)r<r= problem_typer!r( num_labelsr&r'r;r:r2floatnumpyrrrVid2labelargmaxitemr enumeratesort) r3 model_outputsr:r8r9outputsscoresiri dict_scoress r postprocessz&TextClassificationPipeline.postprocesssK  $zz  --=$:$?$?!""//3OOSWS]S]SdSdSoSostSt$:$B$B!""//3PPTXT^T^TeTeTpTpstTt$:$B$B!**,?@EVE^$(JJ$5$5$G$G!$:$?$?!)!, >>T !mmo++-GmmoG  6 > > >W%F "8"@"@ @W%F "8"="= =FJK\J]^_ _ A:'!ZZ..77 8L8L8NOZ`ZdZdZfZkZkZmn n]ffl\m PXPQSXdjj''003ejjl K     !5t  D )&51  s>J5)NN)Nr T)r#r$r%__doc___load_processor_load_image_processor_load_feature_extractor_load_tokenizerr7r!r(r:r0rHrrCrTrRrrLr rWrbr} __classcell__)r5s@rr,r,"s >O!#O.33 96JJK// d38n  /bYS-=O8PY"*,rr,)r]r@typingrrrrrutilsrrrr baser r r models.auto.modeling_tf_autormodels.auto.modeling_autorrrr!r,r)rrrsyYYCCa[+A \ 40 FDDDr