






"""simple docstring"""



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

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402







class        snake_case__      (							unittest.TestCase       ):


			def      UpperCAmelCase__						(				self					:  int ):
										lowerCamelCase_	:							Union[str, Any]									=0


			def      UpperCAmelCase__						(				self					:  str ):
										lowerCamelCase_	:							Optional[int]									=AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" )
										self.assertIsInstance(_a       ,	_a )


			def      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										with tempfile.TemporaryDirectory() as tmpdirname:
																	lowerCamelCase_	:							Dict									=Path(_a ) / "preprocessor_config.json"
																	lowerCamelCase_	:							int									=Path(_a ) / "config.json"
																	json.dump(
																	    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}       ,	open(_a       ,	"w" )       ,	)
																	json.dump({"model_type": "clip"}       ,	open(_a       ,	"w" ) )

																	lowerCamelCase_	:							Optional[Any]									=AutoImageProcessor.from_pretrained(_a )
																	self.assertIsInstance(_a       ,	_a )


			def      UpperCAmelCase__						(				self					:  List[str] ):
										# Ensure we can load the image processor from the feature extractor config
										with tempfile.TemporaryDirectory() as tmpdirname:
																	lowerCamelCase_	:							int									=Path(_a ) / "preprocessor_config.json"
																	lowerCamelCase_	:							Union[str, Any]									=Path(_a ) / "config.json"
																	json.dump(
																	    {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}       ,	open(_a       ,	"w" )       ,	)
																	json.dump({"model_type": "clip"}       ,	open(_a       ,	"w" ) )

																	lowerCamelCase_	:							Union[str, Any]									=AutoImageProcessor.from_pretrained(_a )
																	self.assertIsInstance(_a       ,	_a )


			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										with tempfile.TemporaryDirectory() as tmpdirname:
																	lowerCamelCase_	:							List[str]									=CLIPConfig()

																	# Create a dummy config file with image_proceesor_type
																	lowerCamelCase_	:							Optional[Any]									=Path(_a ) / "preprocessor_config.json"
																	lowerCamelCase_	:							Optional[int]									=Path(_a ) / "config.json"
																	json.dump(
																	    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}       ,	open(_a       ,	"w" )       ,	)
																	json.dump({"model_type": "clip"}       ,	open(_a       ,	"w" ) )

																	# remove image_processor_type to make sure config.json alone is enough to load image processor locally
																	lowerCamelCase_	:							Optional[int]									=AutoImageProcessor.from_pretrained(_a ).to_dict()

																	config_dict.pop("image_processor_type" )
																	lowerCamelCase_	:							Optional[int]									=CLIPImageProcessor(**_a )

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

																	lowerCamelCase_	:							List[str]									=AutoImageProcessor.from_pretrained(_a )

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

										self.assertIsInstance(_a       ,	_a )


			def      UpperCAmelCase__						(				self					:  Optional[Any] ):
										with tempfile.TemporaryDirectory() as tmpdirname:
																	lowerCamelCase_	:							Union[str, Any]									=Path(_a ) / "preprocessor_config.json"
																	json.dump(
																	    {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}       ,	open(_a       ,	"w" )       ,	)

																	lowerCamelCase_	:							Any									=AutoImageProcessor.from_pretrained(_a )
																	self.assertIsInstance(_a       ,	_a )


			def      UpperCAmelCase__						(				self					:  Dict ):
										with self.assertRaisesRegex(
										    _a       ,	"clip-base is not a local folder and is not a valid model identifier" ):
																	lowerCamelCase_	:							Union[str, Any]									=AutoImageProcessor.from_pretrained("clip-base" )


			def      UpperCAmelCase__						(				self					:  List[Any] ):
										with self.assertRaisesRegex(
										    _a       ,	r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
																	lowerCamelCase_	:							Dict									=AutoImageProcessor.from_pretrained(_a       ,	revision="aaaaaa" )


			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										with self.assertRaisesRegex(
										    _a       ,	"hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."       ,	):
																	lowerCamelCase_	:							str									=AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" )


			def      UpperCAmelCase__						(				self					:  int ):
										# If remote code is not set, we will time out when asking whether to load the model.
										with self.assertRaises(_a ):
																	lowerCamelCase_	:							int									=AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" )
										# If remote code is disabled, we can't load this config.
										with self.assertRaises(_a ):
																	lowerCamelCase_	:							Optional[int]									=AutoImageProcessor.from_pretrained(
																	    "hf-internal-testing/test_dynamic_image_processor"       ,	trust_remote_code=_a )

										lowerCamelCase_	:							str									=AutoImageProcessor.from_pretrained(
										    "hf-internal-testing/test_dynamic_image_processor"       ,	trust_remote_code=_a )
										self.assertEqual(image_processor.__class__.__name__       ,	"NewImageProcessor" )

										# Test image processor can be reloaded.
										with tempfile.TemporaryDirectory() as tmp_dir:
																	image_processor.save_pretrained(_a )
																	lowerCamelCase_	:							Any									=AutoImageProcessor.from_pretrained(_a       ,	trust_remote_code=_a )
										self.assertEqual(reloaded_image_processor.__class__.__name__       ,	"NewImageProcessor" )


			def      UpperCAmelCase__						(				self					:  Any ):
										try:
																	AutoConfig.register("custom"       ,	_a )
																	AutoImageProcessor.register(_a       ,	_a )
																	# Trying to register something existing in the Transformers library will raise an error
																	with self.assertRaises(_a ):
																								AutoImageProcessor.register(_a       ,	_a )

																	with tempfile.TemporaryDirectory() as tmpdirname:
																								lowerCamelCase_	:							Optional[Any]									=Path(_a ) / "preprocessor_config.json"
																								lowerCamelCase_	:							Union[str, Any]									=Path(_a ) / "config.json"
																								json.dump(
																								    {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}       ,	open(_a       ,	"w" )       ,	)
																								json.dump({"model_type": "clip"}       ,	open(_a       ,	"w" ) )

																								lowerCamelCase_	:							Tuple									=CustomImageProcessor.from_pretrained(_a )

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

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


			def      UpperCAmelCase__						(				self					:  Any ):







										class        snake_case__      (							snake_case__       ):
													_UpperCAmelCase		:Optional[Any]             =			True

										try:
																	AutoConfig.register("custom"       ,	_a )
																	AutoImageProcessor.register(_a       ,	_a )
																	# If remote code is not set, the default is to use local
																	lowerCamelCase_	:							List[Any]									=AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" )
																	self.assertEqual(image_processor.__class__.__name__       ,	"NewImageProcessor" )
																	self.assertTrue(image_processor.is_local )

																	# If remote code is disabled, we load the local one.
																	lowerCamelCase_	:							int									=AutoImageProcessor.from_pretrained(
																	    "hf-internal-testing/test_dynamic_image_processor"       ,	trust_remote_code=_a )
																	self.assertEqual(image_processor.__class__.__name__       ,	"NewImageProcessor" )
																	self.assertTrue(image_processor.is_local )

																	# If remote is enabled, we load from the Hub
																	lowerCamelCase_	:							Tuple									=AutoImageProcessor.from_pretrained(
																	    "hf-internal-testing/test_dynamic_image_processor"       ,	trust_remote_code=_a )
																	self.assertEqual(image_processor.__class__.__name__       ,	"NewImageProcessor" )
																	self.assertTrue(not hasattr(_a       ,	"is_local" ) )

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











"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_tf_available,
    is_torch_available,
)


A__	:    Optional[int]			 = {
    'configuration_speech_to_text': ['SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Speech2TextConfig'],
    'processing_speech_to_text': ['Speech2TextProcessor'],
}

try:
						if not is_sentencepiece_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						A__	:    Dict			 = ['Speech2TextTokenizer']

try:
						if not is_speech_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						A__	:    Optional[Any]			 = ['Speech2TextFeatureExtractor']

try:
						if not is_tf_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						A__	:    Dict			 = [
						    'TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST',
						    'TFSpeech2TextForConditionalGeneration',
						    'TFSpeech2TextModel',
						    'TFSpeech2TextPreTrainedModel',
						]

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						A__	:    Optional[int]			 = [
						    'SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST',
						    'Speech2TextForConditionalGeneration',
						    'Speech2TextModel',
						    'Speech2TextPreTrainedModel',
						]


if TYPE_CHECKING:
						from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig
						from .processing_speech_to_text import SpeechaTextProcessor

						try:
												if not is_sentencepiece_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .tokenization_speech_to_text import SpeechaTextTokenizer

						try:
												if not is_speech_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor

						try:
												if not is_tf_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_tf_speech_to_text import (
												    TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
												    TFSpeechaTextForConditionalGeneration,
												    TFSpeechaTextModel,
												    TFSpeechaTextPreTrainedModel,
												)

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_speech_to_text import (
												    SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
												    SpeechaTextForConditionalGeneration,
												    SpeechaTextModel,
												    SpeechaTextPreTrainedModel,
												)

else:
						import sys

						A__	:    List[Any]			 = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



