import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import is_speech_available, is_vision_available
from transformers.testing_utils import require_torch


if is_vision_available():
    from transformers import TvltImageProcessor

if is_speech_available():
    from transformers import TvltFeatureExtractor

from transformers import TvltProcessor


@require_torch
class 	lowerCamelCase_     (   unittest.TestCase ):






    '''simple docstring'''






    def 			UpperCamelCase__   (	self)       ->	int:
        __UpperCamelCase     :int			  =		'''ZinengTang/tvlt-base'''
        __UpperCamelCase     :str			  =		tempfile.mkdtemp()







    def 			UpperCamelCase__   (	self , **__lowercase)       ->	List[str]:
        return TvltImageProcessor.from_pretrained(self.checkpoint , **__lowercase)







    def 			UpperCamelCase__   (	self , **__lowercase)       ->	List[Any]:
        return TvltFeatureExtractor.from_pretrained(self.checkpoint , **__lowercase)







    def 			UpperCamelCase__   (	self)       ->	int:
        shutil.rmtree(self.tmpdirname)







    def 			UpperCamelCase__   (	self)       ->	Dict:
        __UpperCamelCase     :int			  =		self.get_image_processor()
        __UpperCamelCase     :Dict			  =		self.get_feature_extractor()

        __UpperCamelCase     :Optional[Any]			  =		TvltProcessor(image_processor=__lowercase , feature_extractor=__lowercase)
        processor.save_pretrained(self.tmpdirname)
        __UpperCamelCase     :Tuple			  =		TvltProcessor.from_pretrained(self.tmpdirname)

        self.assertIsInstance(processor.feature_extractor , __lowercase)
        self.assertIsInstance(processor.image_processor , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	Optional[int]:
        __UpperCamelCase     :Union[str, Any]			  =		self.get_image_processor()
        __UpperCamelCase     :List[Any]			  =		self.get_feature_extractor()

        __UpperCamelCase     :Optional[Any]			  =		TvltProcessor(image_processor=__lowercase , feature_extractor=__lowercase)

        __UpperCamelCase     :Tuple			  =		np.ones([12_000])

        __UpperCamelCase     :Union[str, Any]			  =		feature_extractor(__lowercase , return_tensors='''np''')
        __UpperCamelCase     :Tuple			  =		processor(audio=__lowercase , return_tensors='''np''')

        for key in audio_dict.keys():
            self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1E-2)







    def 			UpperCamelCase__   (	self)       ->	int:
        __UpperCamelCase     :str			  =		self.get_image_processor()
        __UpperCamelCase     :int			  =		self.get_feature_extractor()

        __UpperCamelCase     :Optional[Any]			  =		TvltProcessor(image_processor=__lowercase , feature_extractor=__lowercase)

        __UpperCamelCase     :Dict			  =		np.ones([3, 224, 224])

        __UpperCamelCase     :Optional[Any]			  =		image_processor(__lowercase , return_tensors='''np''')
        __UpperCamelCase     :Dict			  =		processor(images=__lowercase , return_tensors='''np''')

        for key in image_dict.keys():
            self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1E-2)







    def 			UpperCamelCase__   (	self)       ->	List[Any]:
        __UpperCamelCase     :Any			  =		self.get_image_processor()
        __UpperCamelCase     :Tuple			  =		self.get_feature_extractor()

        __UpperCamelCase     :str			  =		TvltProcessor(image_processor=__lowercase , feature_extractor=__lowercase)

        __UpperCamelCase     :Optional[int]			  =		np.ones([12_000])
        __UpperCamelCase     :Optional[Any]			  =		np.ones([3, 224, 224])

        __UpperCamelCase     :Optional[Any]			  =		processor(audio=__lowercase , images=__lowercase)

        self.assertListEqual(list(inputs.keys()) , ['''audio_values''', '''audio_mask''', '''pixel_values''', '''pixel_mask'''])

        # test if it raises when no input is passed
        with pytest.raises(__lowercase):
            processor()







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        __UpperCamelCase     :List[str]			  =		self.get_image_processor()
        __UpperCamelCase     :Optional[Any]			  =		self.get_feature_extractor()

        __UpperCamelCase     :int			  =		TvltProcessor(image_processor=__lowercase , feature_extractor=__lowercase)

        self.assertListEqual(
            processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg='''`processor` and `image_processor`+`feature_extractor` model input names do not match''' , )






# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool


class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    a__	:						Optional[Any]						=      """facebook/bart-large-mnli"""
    a__	:						int						=      (
        """This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which """
        """should be the text to classify, and `labels`, which should be the list of labels to use for classification. """
        """It returns the most likely label in the list of provided `labels` for the input text."""
    )
    a__	:						Optional[Any]						=      """text_classifier"""
    a__	:						Any						=      AutoTokenizer
    a__	:						str						=      AutoModelForSequenceClassification

    a__	:						str						=      ["""text""", ["""text"""]]
    a__	:						Optional[int]						=      ["""text"""]







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        super().setup()
        __UpperCamelCase     :int			  =		self.model.config
        __UpperCamelCase     :Optional[Any]			  =		-1
        for idx, label in config.idalabel.items():
            if label.lower().startswith('''entail'''):
                __UpperCamelCase     :List[Any]			  =		int(__lowercase)
        if self.entailment_id == -1:
            raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''')







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase)       ->	Union[str, Any]:
        __UpperCamelCase     :Any			  =		labels
        return self.pre_processor(
            [text] * len(__lowercase) , [f"""This example is {label}""" for label in labels] , return_tensors='''pt''' , padding='''max_length''' , )







    def 			UpperCamelCase__   (	self , __lowercase)       ->	Optional[Any]:
        __UpperCamelCase     :List[Any]			  =		outputs.logits
        __UpperCamelCase     :Any			  =		torch.argmax(logits[:, 2]).item()
        return self._labels[label_id]





