


'''simple docstring'''



import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)


__lowercase	:						Dict       =	logging.get_logger(__name__)

__lowercase	:						Any       =	OrderedDict(
    [
        ('audio-spectrogram-transformer', 'ASTFeatureExtractor'),
        ('beit', 'BeitFeatureExtractor'),
        ('chinese_clip', 'ChineseCLIPFeatureExtractor'),
        ('clap', 'ClapFeatureExtractor'),
        ('clip', 'CLIPFeatureExtractor'),
        ('clipseg', 'ViTFeatureExtractor'),
        ('conditional_detr', 'ConditionalDetrFeatureExtractor'),
        ('convnext', 'ConvNextFeatureExtractor'),
        ('cvt', 'ConvNextFeatureExtractor'),
        ('data2vec-audio', 'Wav2Vec2FeatureExtractor'),
        ('data2vec-vision', 'BeitFeatureExtractor'),
        ('deformable_detr', 'DeformableDetrFeatureExtractor'),
        ('deit', 'DeiTFeatureExtractor'),
        ('detr', 'DetrFeatureExtractor'),
        ('dinat', 'ViTFeatureExtractor'),
        ('donut-swin', 'DonutFeatureExtractor'),
        ('dpt', 'DPTFeatureExtractor'),
        ('encodec', 'EncodecFeatureExtractor'),
        ('flava', 'FlavaFeatureExtractor'),
        ('glpn', 'GLPNFeatureExtractor'),
        ('groupvit', 'CLIPFeatureExtractor'),
        ('hubert', 'Wav2Vec2FeatureExtractor'),
        ('imagegpt', 'ImageGPTFeatureExtractor'),
        ('layoutlmv2', 'LayoutLMv2FeatureExtractor'),
        ('layoutlmv3', 'LayoutLMv3FeatureExtractor'),
        ('levit', 'LevitFeatureExtractor'),
        ('maskformer', 'MaskFormerFeatureExtractor'),
        ('mctct', 'MCTCTFeatureExtractor'),
        ('mobilenet_v1', 'MobileNetV1FeatureExtractor'),
        ('mobilenet_v2', 'MobileNetV2FeatureExtractor'),
        ('mobilevit', 'MobileViTFeatureExtractor'),
        ('nat', 'ViTFeatureExtractor'),
        ('owlvit', 'OwlViTFeatureExtractor'),
        ('perceiver', 'PerceiverFeatureExtractor'),
        ('poolformer', 'PoolFormerFeatureExtractor'),
        ('regnet', 'ConvNextFeatureExtractor'),
        ('resnet', 'ConvNextFeatureExtractor'),
        ('segformer', 'SegformerFeatureExtractor'),
        ('sew', 'Wav2Vec2FeatureExtractor'),
        ('sew-d', 'Wav2Vec2FeatureExtractor'),
        ('speech_to_text', 'Speech2TextFeatureExtractor'),
        ('speecht5', 'SpeechT5FeatureExtractor'),
        ('swiftformer', 'ViTFeatureExtractor'),
        ('swin', 'ViTFeatureExtractor'),
        ('swinv2', 'ViTFeatureExtractor'),
        ('table-transformer', 'DetrFeatureExtractor'),
        ('timesformer', 'VideoMAEFeatureExtractor'),
        ('tvlt', 'TvltFeatureExtractor'),
        ('unispeech', 'Wav2Vec2FeatureExtractor'),
        ('unispeech-sat', 'Wav2Vec2FeatureExtractor'),
        ('van', 'ConvNextFeatureExtractor'),
        ('videomae', 'VideoMAEFeatureExtractor'),
        ('vilt', 'ViltFeatureExtractor'),
        ('vit', 'ViTFeatureExtractor'),
        ('vit_mae', 'ViTFeatureExtractor'),
        ('vit_msn', 'ViTFeatureExtractor'),
        ('wav2vec2', 'Wav2Vec2FeatureExtractor'),
        ('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'),
        ('wavlm', 'Wav2Vec2FeatureExtractor'),
        ('whisper', 'WhisperFeatureExtractor'),
        ('xclip', 'CLIPFeatureExtractor'),
        ('yolos', 'YolosFeatureExtractor'),
    ]
)

__lowercase	:						Optional[Any]       =	_LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   str   ):
					for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
										if class_name in extractors:
															__a			:       str					    =  model_type_to_module_name(_SCREAMING_SNAKE_CASE   )

															__a			:       int					    =  importlib.import_module(F""".{module_name}"""						,      'transformers.models'   )
															try:
																				return getattr(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )
															except AttributeError:
																				continue

					for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
										if getattr(_SCREAMING_SNAKE_CASE						,      '__name__'						,      _SCREAMING_SNAKE_CASE   ) == class_name:
															return extractor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
					__a			:       Optional[int]					    =  importlib.import_module('transformers'   )
					if hasattr(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   ):
										return getattr(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )

					return None






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Union[str, os.PathLike]						,      _SCREAMING_SNAKE_CASE      :   Optional[Union[str, os.PathLike]] = None						,      _SCREAMING_SNAKE_CASE      :   bool = False						,      _SCREAMING_SNAKE_CASE      :   bool = False						,      _SCREAMING_SNAKE_CASE      :   Optional[Dict[str, str]] = None						,      _SCREAMING_SNAKE_CASE      :   Optional[Union[bool, str]] = None						,      _SCREAMING_SNAKE_CASE      :   Optional[str] = None						,      _SCREAMING_SNAKE_CASE      :   bool = False						,      **_SCREAMING_SNAKE_CASE      :   List[str]						,      ):
					__a			:       Optional[Any]					    =  get_file_from_repo(
					    _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      cache_dir=_SCREAMING_SNAKE_CASE						,      force_download=_SCREAMING_SNAKE_CASE						,      resume_download=_SCREAMING_SNAKE_CASE						,      proxies=_SCREAMING_SNAKE_CASE						,      use_auth_token=_SCREAMING_SNAKE_CASE						,      revision=_SCREAMING_SNAKE_CASE						,      local_files_only=_SCREAMING_SNAKE_CASE						,      )
					if resolved_config_file is None:
										logger.info(
										    'Could not locate the feature extractor configuration file, will try to use the model config instead.'   )
										return {}

					with open(_SCREAMING_SNAKE_CASE						,      encoding='utf-8'   ) as reader:
										return json.load(_SCREAMING_SNAKE_CASE   )





class 							__UpperCamelCase				:




	def __init__(   self							):

						'''simple docstring'''





						raise EnvironmentError(
						    'AutoFeatureExtractor is designed to be instantiated '
						    'using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.'							)




	@classmethod
	@replace_list_option_in_docstrings(__a							)
	def       __UpperCAmelCase							(   cls						,				__a						,				**__a							):

						'''simple docstring'''





						__a			:       List[str]					    =  kwargs.pop('config'						,				__a							)
						__a			:       Optional[Any]					    =  kwargs.pop('trust_remote_code'						,				__a							)
						__a			:       Dict					    =  True

						__a    ,				__a			:       List[Any]					    =  FeatureExtractionMixin.get_feature_extractor_dict(__a						,				**__a							)
						__a			:       Dict					    =  config_dict.get('feature_extractor_type'						,				__a							)
						__a			:       Tuple					    =  None
						if "AutoFeatureExtractor" in config_dict.get('auto_map'						,				{}							):
											__a			:       str					    =  config_dict['auto_map']['AutoFeatureExtractor']

						# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
						if feature_extractor_class is None and feature_extractor_auto_map is None:
											if not isinstance(__a						,				__a							):
																__a			:       int					    =  AutoConfig.from_pretrained(__a						,				**__a							)
											# It could be in `config.feature_extractor_type``
											__a			:       Dict					    =  getattr(__a						,				'feature_extractor_type'						,				__a							)
											if hasattr(__a						,				'auto_map'							) and "AutoFeatureExtractor" in config.auto_map:
																__a			:       Optional[Any]					    =  config.auto_map['AutoFeatureExtractor']

						if feature_extractor_class is not None:
											__a			:       List[str]					    =  feature_extractor_class_from_name(__a							)

						__a			:       int					    =  feature_extractor_auto_map is not None
						__a			:       Any					    =  feature_extractor_class is not None or type(__a							) in FEATURE_EXTRACTOR_MAPPING
						__a			:       Any					    =  resolve_trust_remote_code(
						    __a						,				__a						,				__a						,				__a							)

						if has_remote_code and trust_remote_code:
											__a			:       str					    =  get_class_from_dynamic_module(
											    __a						,				__a						,				**__a							)
											__a			:       Any					    =  kwargs.pop('code_revision'						,				__a							)
											if os.path.isdir(__a							):
																feature_extractor_class.register_for_auto_class()
											return feature_extractor_class.from_dict(__a						,				**__a							)
						elif feature_extractor_class is not None:
											return feature_extractor_class.from_dict(__a						,				**__a							)
						# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
						elif type(__a							) in FEATURE_EXTRACTOR_MAPPING:
											__a			:       Optional[Any]					    =  FEATURE_EXTRACTOR_MAPPING[type(__a							)]
											return feature_extractor_class.from_dict(__a						,				**__a							)

						raise ValueError(
						    f"""Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a """
						    f"""`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following """
						    f"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys()							)}"""							)





	@staticmethod
	def       __UpperCAmelCase							(   __a						,				__a							):

						'''simple docstring'''





						FEATURE_EXTRACTOR_MAPPING.register(__a						,				__a							)







'''simple docstring'''



import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
__lowercase	:						Tuple       =	pytest.mark.integration


__lowercase	:						Optional[int]       =	{'comet'}
__lowercase	:						List[str]       =	importlib.util.find_spec('fairseq') is not None

__lowercase	:						str       =	{'code_eval'}
__lowercase	:						List[Any]       =	os.name == 'nt'

__lowercase	:						Optional[Any]       =	{'bertscore', 'frugalscore', 'perplexity'}
__lowercase	:						Optional[Any]       =	importlib.util.find_spec('transformers') is not None






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Dict   ):
					@wraps(_SCREAMING_SNAKE_CASE   )
					def wrapper(self      :   int						,      _SCREAMING_SNAKE_CASE      :   List[Any]   ):
										if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
															self.skipTest('"test requires Fairseq"'   )
										else:
															test_case(self						,      _SCREAMING_SNAKE_CASE   )

					return wrapper






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Union[str, Any]   ):
					@wraps(_SCREAMING_SNAKE_CASE   )
					def wrapper(self      :   Dict						,      _SCREAMING_SNAKE_CASE      :   Union[str, Any]   ):
										if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
															self.skipTest('"test requires transformers"'   )
										else:
															test_case(self						,      _SCREAMING_SNAKE_CASE   )

					return wrapper






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Dict   ):
					@wraps(_SCREAMING_SNAKE_CASE   )
					def wrapper(self      :   Optional[int]						,      _SCREAMING_SNAKE_CASE      :   Optional[Any]   ):
										if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
															self.skipTest('"test not supported on Windows"'   )
										else:
															test_case(self						,      _SCREAMING_SNAKE_CASE   )

					return wrapper






def   lowerCamelCase							():
					__a			:       List[Any]					    =  [metric_dir.split(os.sep   )[-2] for metric_dir in glob.glob('./metrics/*/'   )]
					return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished





@parameterized.named_parameters(get_local_metric_names()					)
@for_all_test_methods(
    lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_					)
@local
class 							__UpperCamelCase				(		parameterized.TestCase					):
	A_				=    {}
	A_				=    None




	@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'							)
	@pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'							)
	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       int					    =  '[...]'
						__a			:       Tuple					    =  importlib.import_module(
						    datasets.load.metric_module_factory(os.path.join('metrics'						,				__a							)							).module_path							)
						__a			:       Optional[Any]					    =  datasets.load.import_main_class(metric_module.__name__						,				dataset=__a							)
						# check parameters
						__a			:       Dict					    =  inspect.signature(metric._compute							).parameters
						self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()							)							)  # no **kwargs
						# run doctest
						with self.patch_intensive_calls(__a						,				metric_module.__name__							):
											with self.use_local_metrics():
																try:
																					__a			:       str					    =  doctest.testmod(__a						,				verbose=__a						,				raise_on_error=__a							)
																except doctest.UnexpectedException as e:
																					raise e.exc_info[1]  # raise the exception that doctest caught
						self.assertEqual(results.failed						,				0							)
						self.assertGreater(results.attempted						,				1							)




	@slow
	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       Tuple					    =  '[...]'
						__a			:       Optional[Any]					    =  importlib.import_module(
						    datasets.load.metric_module_factory(os.path.join('metrics'						,				__a							)							).module_path							)
						# run doctest
						with self.use_local_metrics():
											__a			:       List[Any]					    =  doctest.testmod(__a						,				verbose=__a						,				raise_on_error=__a							)
						self.assertEqual(results.failed						,				0							)
						self.assertGreater(results.attempted						,				1							)




	@contextmanager
	def       __UpperCAmelCase							(   self						,				__a						,				__a							):

						'''simple docstring'''





						if metric_name in self.INTENSIVE_CALLS_PATCHER:
											with self.INTENSIVE_CALLS_PATCHER[metric_name](__a							):
																yield
						else:
											yield




	@contextmanager
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						def load_local_metric(__a						,				*__a						,				**__a							):
											return load_metric(os.path.join('metrics'						,				__a							)						,				*__a						,				**__a							)

						with patch('datasets.load_metric'							) as mock_load_metric:
											__a			:       Dict					    =  load_local_metric
											yield





	@classmethod
	def       __UpperCAmelCase							(   cls						,				__a							):

						'''simple docstring'''





						def wrapper(__a							):
											__a			:       Optional[Any]					    =  contextmanager(__a							)
											__a			:       str					    =  patcher
											return patcher

						return wrapper






@LocalMetricTest.register_intensive_calls_patcher('bleurt'   )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Dict   ):
					import tensorflow.compat.va as tf
					from bleurt.score import Predictor

					tf.flags.DEFINE_string('sv'						,      ''						,      ''   )  # handle pytest cli flags





					class 							__UpperCamelCase				(		lowerCAmelCase_					):




						def       __UpperCAmelCase							(   self						,				__a							):

											'''simple docstring'''





											assert len(input_dict['input_ids']							) == 2
											return np.array([1.03, 1.04]							)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
					with patch('bleurt.score._create_predictor'   ) as mock_create_predictor:
										__a			:       Dict					    =  MockedPredictor()
										yield






@LocalMetricTest.register_intensive_calls_patcher('bertscore'   )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   str   ):
					import torch

					def bert_cos_score_idf(_SCREAMING_SNAKE_CASE      :   List[str]						,      _SCREAMING_SNAKE_CASE      :   str						,      *_SCREAMING_SNAKE_CASE      :   int						,      **_SCREAMING_SNAKE_CASE      :   Optional[int]   ):
										return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE   )   )

					# mock get_model which is supposed to do download a bert model
					# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
					with patch('bert_score.scorer.get_model'   ), patch(
					    'bert_score.scorer.bert_cos_score_idf'   ) as mock_bert_cos_score_idf:
										__a			:       str					    =  bert_cos_score_idf
										yield






@LocalMetricTest.register_intensive_calls_patcher('comet'   )
def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Dict   ):
					def load_from_checkpoint(_SCREAMING_SNAKE_CASE      :   Optional[int]   ):





										class 							__UpperCamelCase				:




											def       __UpperCAmelCase							(   self						,				__a						,				*__a						,				**__a							):

																'''simple docstring'''





																assert len(__a							) == 2
																__a			:       Dict					    =  [0.19, 0.92]
																return scores, sum(__a							) / len(__a							)



										return Model()

					# mock load_from_checkpoint which is supposed to do download a bert model
					# mock load_from_checkpoint which is supposed to do download a bert model
					with patch('comet.download_model'   ) as mock_download_model:
										__a			:       str					    =  None
										with patch('comet.load_from_checkpoint'   ) as mock_load_from_checkpoint:
															__a			:       int					    =  load_from_checkpoint
															yield






def   lowerCamelCase							():
					__a			:       Optional[Any]					    =  load_metric(os.path.join('metrics'						,      'seqeval'   )   )
					__a			:       List[str]					    =  'ERROR'
					__a			:       List[str]					    =  F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
					with pytest.raises(_SCREAMING_SNAKE_CASE						,      match=re.escape(_SCREAMING_SNAKE_CASE   )   ):
										metric.compute(predictions=[]						,      references=[]						,      scheme=_SCREAMING_SNAKE_CASE   )



