
import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowercase        =  get_tests_dir('''fixtures''')
lowercase        =  get_tests_dir('''fixtures/dummy_feature_extractor_config.json''')
lowercase        =  get_tests_dir('''fixtures/dummy-config.json''')





class       __A(				unittest.TestCase       ):

					def    lowercase__      (	self					:     Optional[Any]   ):
												lowerCamelCase_							  =					0

					def    lowercase__      (	self					:     Any   ):
												lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""   )
												self.assertIsInstance(_A   ,					_A   )

					def    lowercase__      (	self					:     Any   ):
												lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(_A   )
												self.assertIsInstance(_A   ,					_A   )

					def    lowercase__      (	self					:     Optional[Any]   ):

												with tempfile.TemporaryDirectory() as tmpdirname:
																			lowerCamelCase_							  =					WavaVecaConfig()

																			# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(_A   ).to_dict()

																			config_dict.pop("""feature_extractor_type"""   )
																			lowerCamelCase_							  =					WavaVecaFeatureExtractor(**_A   )

																			# save in new folder
																			model_config.save_pretrained(_A   )
																			config.save_pretrained(_A   )

																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(_A   )

																			# make sure private variable is not incorrectly saved
																			lowerCamelCase_							  =					json.loads(config.to_json_string()   )
																			self.assertTrue("""_processor_class""" not in dict_as_saved   )

												self.assertIsInstance(_A   ,					_A   )

					def    lowercase__      (	self					:     Union[str, Any]   ):
												lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(_A   )
												self.assertIsInstance(_A   ,					_A   )

					def    lowercase__      (	self					:     Optional[int]   ):

												with self.assertRaisesRegex(
												    _A   ,					"""bert-base is not a local folder and is not a valid model identifier"""   ):
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained("""bert-base"""   )

					def    lowercase__      (	self					:     Dict   ):

												with self.assertRaisesRegex(
												    _A   ,					R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""   ):
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(_A   ,					revision="""aaaaaa"""   )

					def    lowercase__      (	self					:     Tuple   ):

												with self.assertRaisesRegex(
												    _A   ,					"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""   ,					):
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""   )

					def    lowercase__      (	self					:     Tuple   ):

												with self.assertRaises(_A   ):
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(
																			    """hf-internal-testing/test_dynamic_feature_extractor"""   )
												# If remote code is disabled, we can't load this config.
												with self.assertRaises(_A   ):
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(
																			    """hf-internal-testing/test_dynamic_feature_extractor"""   ,					trust_remote_code=_A   )

												lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(
												    """hf-internal-testing/test_dynamic_feature_extractor"""   ,					trust_remote_code=_A   )
												self.assertEqual(feature_extractor.__class__.__name__   ,					"""NewFeatureExtractor"""   )

												# Test feature extractor can be reloaded.
												with tempfile.TemporaryDirectory() as tmp_dir:
																			feature_extractor.save_pretrained(_A   )
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(_A   ,					trust_remote_code=_A   )
												self.assertEqual(reloaded_feature_extractor.__class__.__name__   ,					"""NewFeatureExtractor"""   )

					def    lowercase__      (	self					:     Optional[int]   ):

												try:
																			AutoConfig.register("""custom"""   ,					_A   )
																			AutoFeatureExtractor.register(_A   ,					_A   )
																			# Trying to register something existing in the Transformers library will raise an error
																			with self.assertRaises(_A   ):
																										AutoFeatureExtractor.register(_A   ,					_A   )

																			# Now that the config is registered, it can be used as any other config with the auto-API
																			lowerCamelCase_							  =					CustomFeatureExtractor.from_pretrained(_A   )
																			with tempfile.TemporaryDirectory() as tmp_dir:
																										feature_extractor.save_pretrained(_A   )
																										lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(_A   )
																										self.assertIsInstance(_A   ,					_A   )

												finally:
																			if "custom" in CONFIG_MAPPING._extra_content:
																										del CONFIG_MAPPING._extra_content["custom"]
																			if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																										del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]



					def    lowercase__      (	self					:     str   ):





												class       __A(				a__       ):
																	SCREAMING_SNAKE_CASE			    =    True

												try:
																			AutoConfig.register("""custom"""   ,					_A   )
																			AutoFeatureExtractor.register(_A   ,					_A   )
																			# If remote code is not set, the default is to use local
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(
																			    """hf-internal-testing/test_dynamic_feature_extractor"""   )
																			self.assertEqual(feature_extractor.__class__.__name__   ,					"""NewFeatureExtractor"""   )
																			self.assertTrue(feature_extractor.is_local   )

																			# If remote code is disabled, we load the local one.
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(
																			    """hf-internal-testing/test_dynamic_feature_extractor"""   ,					trust_remote_code=_A   )
																			self.assertEqual(feature_extractor.__class__.__name__   ,					"""NewFeatureExtractor"""   )
																			self.assertTrue(feature_extractor.is_local   )

																			# If remote is enabled, we load from the Hub
																			lowerCamelCase_							  =					AutoFeatureExtractor.from_pretrained(
																			    """hf-internal-testing/test_dynamic_feature_extractor"""   ,					trust_remote_code=_A   )
																			self.assertEqual(feature_extractor.__class__.__name__   ,					"""NewFeatureExtractor"""   )
																			self.assertTrue(not hasattr(_A   ,					"""is_local"""   )   )

												finally:
																			if "custom" in CONFIG_MAPPING._extra_content:
																										del CONFIG_MAPPING._extra_content["custom"]
																			if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
																										del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]







# 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       __A(				UpperCAmelCase       ):
					SCREAMING_SNAKE_CASE			    =    '''facebook/bart-large-mnli'''
					SCREAMING_SNAKE_CASE			    =    (
					    '''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.'''
					)
					SCREAMING_SNAKE_CASE			    =    '''text_classifier'''
					SCREAMING_SNAKE_CASE			    =    AutoTokenizer
					SCREAMING_SNAKE_CASE			    =    AutoModelForSequenceClassification

					SCREAMING_SNAKE_CASE			    =    ['''text''', ['''text''']]
					SCREAMING_SNAKE_CASE			    =    ['''text''']

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

					def    lowercase__      (	self					:     Any   ,					__UpperCamelCase					:     List[Any]   ,					__UpperCamelCase					:     Optional[Any]   ):
												lowerCamelCase_							  =					labels
												return self.pre_processor(
												    [text] * len(__UpperCamelCase   )   ,					[F'''This example is {label}''' for label in labels]   ,					return_tensors="""pt"""   ,					padding="""max_length"""   ,					)



					def    lowercase__      (	self					:     List[Any]   ,					__UpperCamelCase					:     List[str]   ):
												lowerCamelCase_							  =					outputs.logits
												lowerCamelCase_							  =					torch.argmax(logits[:, 2]   ).item()
												return self._labels[label_id]





