





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,
)


lowerCAmelCase_        =							logging.get_logger(__name__)

lowerCAmelCase_        =							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'''),
    ]
)

lowerCAmelCase_        =							_LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)






def 	lowerCamelCase_		(							_UpperCamelCase					)						->		Any:






				"""simple docstring"""


				for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
								if class_name in extractors:
												snake_case_		:       Union[str, Any]           =    model_type_to_module_name(_UpperCamelCase					)

												snake_case_		:       Dict           =    importlib.import_module(f'''.{module_name}'''					,							'''transformers.models'''					)
												try:
																return getattr(_UpperCamelCase					,							_UpperCamelCase					)
												except AttributeError:
																continue

				for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
								if getattr(_UpperCamelCase					,							'''__name__'''					,							_UpperCamelCase					) == 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.
				snake_case_		:       Union[str, Any]           =    importlib.import_module('''transformers'''					)
				if hasattr(_UpperCamelCase					,							_UpperCamelCase					):
								return getattr(_UpperCamelCase					,							_UpperCamelCase					)

				return None






def 	lowerCamelCase_		(							_UpperCamelCase					,							_UpperCamelCase = None					,							_UpperCamelCase = False					,							_UpperCamelCase = False					,							_UpperCamelCase = None					,							_UpperCamelCase = None					,							_UpperCamelCase = None					,							_UpperCamelCase = False					,							**_UpperCamelCase					,							)						->		Optional[Any]:






				"""simple docstring"""


				snake_case_		:       Optional[Any]           =    get_file_from_repo(
				    _UpperCamelCase					,							_UpperCamelCase					,							cache_dir=_UpperCamelCase					,							force_download=_UpperCamelCase					,							resume_download=_UpperCamelCase					,							proxies=_UpperCamelCase					,							use_auth_token=_UpperCamelCase					,							revision=_UpperCamelCase					,							local_files_only=_UpperCamelCase					,							)
				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(_UpperCamelCase					,							encoding='''utf-8'''					) as reader:
								return json.load(_UpperCamelCase					)





class    __lowerCAmelCase			:






			def __init__(self       )	->  Optional[Any]:


							'''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(__magic_name__       )
			def      lowerCamelCase    (cls   ,				__magic_name__   ,				**__magic_name__       )	->  Union[str, Any]:


							'''simple docstring'''



							snake_case_		:       Dict           =    kwargs.pop('''config'''   ,				__magic_name__       )
							snake_case_		:       Union[str, Any]           =    kwargs.pop('''trust_remote_code'''   ,				__magic_name__       )
							snake_case_		:       Tuple           =    True

							snake_case_     ,				snake_case_		:       Tuple           =    FeatureExtractionMixin.get_feature_extractor_dict(__magic_name__   ,				**__magic_name__       )
							snake_case_		:       int           =    config_dict.get('''feature_extractor_type'''   ,				__magic_name__       )
							snake_case_		:       str           =    None
							if "AutoFeatureExtractor" in config_dict.get('''auto_map'''   ,				{}       ):
											snake_case_		:       Any           =    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(__magic_name__   ,				__magic_name__       ):
															snake_case_		:       Any           =    AutoConfig.from_pretrained(__magic_name__   ,				**__magic_name__       )
											# It could be in `config.feature_extractor_type``
											snake_case_		:       List[Any]           =    getattr(__magic_name__   ,				'''feature_extractor_type'''   ,				__magic_name__       )
											if hasattr(__magic_name__   ,				'''auto_map'''       ) and "AutoFeatureExtractor" in config.auto_map:
															snake_case_		:       List[str]           =    config.auto_map['''AutoFeatureExtractor''']

							if feature_extractor_class is not None:
											snake_case_		:       List[Any]           =    feature_extractor_class_from_name(__magic_name__       )

							snake_case_		:       Optional[int]           =    feature_extractor_auto_map is not None
							snake_case_		:       Tuple           =    feature_extractor_class is not None or type(__magic_name__       ) in FEATURE_EXTRACTOR_MAPPING
							snake_case_		:       Optional[int]           =    resolve_trust_remote_code(
							    __magic_name__   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__       )

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

							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      lowerCamelCase    (__magic_name__   ,				__magic_name__       )	->  Union[str, Any]:


							'''simple docstring'''



							FEATURE_EXTRACTOR_MAPPING.register(__magic_name__   ,				__magic_name__       )








import datasets

from .evaluate import evaluate


snake_case__   :						int													=   """\
@article{hendrycks2021cuad,
      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},
      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},
      journal={arXiv preprint arXiv:2103.06268},
      year={2021}
}
"""

snake_case__   :						Union[str, Any]													=   """
This metric wrap the official scoring script for version 1 of the Contract
Understanding Atticus Dataset (CUAD).
Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510
commercial legal contracts that have been manually labeled to identify 41 categories of important
clauses that lawyers look for when reviewing contracts in connection with corporate transactions.
"""

snake_case__   :						Any													=   """
Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair as given in the references (see below)
        - 'prediction_text': list of possible texts for the answer, as a list of strings
        depending on a threshold on the confidence probability of each prediction.
    references: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair (see above),
        - 'answers': a Dict in the CUAD dataset format
            {
                'text': list of possible texts for the answer, as a list of strings
                'answer_start': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    'exact_match': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
    'aupr': Area Under the Precision-Recall curve
    'prec_at_80_recall': Precision at 80% recall
    'prec_at_90_recall': Precision at 90% recall
Examples:
    >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]
    >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]
    >>> cuad_metric = datasets.load_metric(\"cuad\")
    >>> results = cuad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0}
"""


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,							_KWARGS_DESCRIPTION     )
class     _a							(	datasets.Metric     ):






  """simple docstring"""





  def  _UpperCAmelCase  (  self			)      ->			Optional[int]:
     return datasets.MetricInfo(
         description=_DESCRIPTION		,		citation=_CITATION		,		inputs_description=_KWARGS_DESCRIPTION		,		features=datasets.Features(
             {
                 'predictions': {
                     'id': datasets.Value('string'			),
                     'prediction_text': datasets.features.Sequence(datasets.Value('string'			)			),
                 },
                 'references': {
                     'id': datasets.Value('string'			),
                     'answers': datasets.features.Sequence(
                         {
                             'text': datasets.Value('string'			),
                             'answer_start': datasets.Value('int32'			),
                         }			),
                 },
             }			)		,		codebase_urls=['https://www.atticusprojectai.org/cuad']		,		reference_urls=['https://www.atticusprojectai.org/cuad']		,		)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Dict:
     UpperCamelCase_						=  {prediction['id']: prediction['prediction_text'] for prediction in predictions}
     UpperCamelCase_						=  [
         {
             'paragraphs': [
                 {
                     'qas': [
                         {
                             'answers': [{'text': answer_text} for answer_text in ref['answers']['text']],
                             'id': ref['id'],
                         }
                         for ref in references
                     ]
                 }
             ]
         }
     ]
     UpperCamelCase_						=  evaluate(dataset=_UpperCAmelCase		,		predictions=_UpperCAmelCase			)
     return score





