



'''simple docstring'''





import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


SCREAMING_SNAKE_CASE__      					=     "\\n@INPROCEEDINGS{Papineni02bleu:a,\n    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n    booktitle = {},\n    year = {2002},\n    pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n    author = \"Lin, Chin-Yew  and\n      Och, Franz Josef\",\n    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n    month = \"aug 23{--}aug 27\",\n    year = \"2004\",\n    address = \"Geneva, Switzerland\",\n    publisher = \"COLING\",\n    url = \"https://www.aclweb.org/anthology/C04-1072\",\n    pages = \"501--507\",\n}\n"

SCREAMING_SNAKE_CASE__      					=     "\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n"

SCREAMING_SNAKE_CASE__      					=     "\nComputes BLEU score of translated segments against one or more references.\nArgs:\n    predictions: list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    max_order: Maximum n-gram order to use when computing BLEU score.\n    smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n    'bleu': bleu score,\n    'precisions': geometric mean of n-gram precisions,\n    'brevity_penalty': brevity penalty,\n    'length_ratio': ratio of lengths,\n    'translation_length': translation_length,\n    'reference_length': reference_length\nExamples:\n\n    >>> predictions = [\n    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample\n    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample\n    ... ]\n    >>> references = [\n    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)\n    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)\n    ... ]\n    >>> bleu = datasets.load_metric(\"bleu\")\n    >>> results = bleu.compute(predictions=predictions, references=references)\n    >>> print(results[\"bleu\"])\n    1.0\n"


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



       def 							_a      (				self      )  ->							List[Any]:
           return datasets.MetricInfo(
               description=_DESCRIPTION     ,citation=_CITATION     ,inputs_description=_KWARGS_DESCRIPTION     ,features=datasets.Features(
                   {
                       "predictions": datasets.Sequence(datasets.Value("string"     ,id="token"      )     ,id="sequence"      ),
                       "references": datasets.Sequence(
                           datasets.Sequence(datasets.Value("string"     ,id="token"      )     ,id="sequence"      )     ,id="references"      ),
                   }      )     ,codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"]     ,reference_urls=[
                   "https://en.wikipedia.org/wiki/BLEU",
                   "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
               ]     ,)







       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_=4     ,UpperCAmelCase_=False      )  ->							Optional[int]:
           lowercase__		       =						compute_bleu(
               reference_corpus=UpperCAmelCase_     ,translation_corpus=UpperCAmelCase_     ,max_order=UpperCAmelCase_     ,smooth=UpperCAmelCase_      )
           ((lowercase__)       ,       (lowercase__)       ,       (lowercase__)       ,       (lowercase__)       ,       (lowercase__)       ,       (lowercase__))		       =						score
           return {
               "bleu": bleu,
               "precisions": precisions,
               "brevity_penalty": bp,
               "length_ratio": ratio,
               "translation_length": translation_length,
               "reference_length": reference_length,
           }









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


SCREAMING_SNAKE_CASE__      					=     logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__      					=     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"),
    ]
)

SCREAMING_SNAKE_CASE__      					=     _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)




def        lowerCamelCase  (				_snake_case  :						str       ):





    '''simple docstring'''


    for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
        if class_name in extractors:
            lowercase__		       =						model_type_to_module_name(_snake_case       )

            lowercase__		       =						importlib.import_module(f'''.{module_name}'''     ,"transformers.models"       )
            try:
                return getattr(_snake_case     ,_snake_case       )
            except AttributeError:
                continue

    for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
        if getattr(_snake_case     ,"__name__"     ,_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.
    lowercase__		       =						importlib.import_module("transformers"       )
    if hasattr(_snake_case     ,_snake_case       ):
        return getattr(_snake_case     ,_snake_case       )

    return None




def        lowerCamelCase  (				_snake_case  :						Union[str, os.PathLike]     ,_snake_case  :						Optional[Union[str, os.PathLike]] = None     ,_snake_case  :						bool = False     ,_snake_case  :						bool = False     ,_snake_case  :						Optional[Dict[str, str]] = None     ,_snake_case  :						Optional[Union[bool, str]] = None     ,_snake_case  :						Optional[str] = None     ,_snake_case  :						bool = False     ,**_snake_case  :						Union[str, Any]     ,):





    '''simple docstring'''


    lowercase__		       =						get_file_from_repo(
        _snake_case     ,_snake_case     ,cache_dir=_snake_case     ,force_download=_snake_case     ,resume_download=_snake_case     ,proxies=_snake_case     ,use_auth_token=_snake_case     ,revision=_snake_case     ,local_files_only=_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(_snake_case     ,encoding="utf-8"       ) as reader:
        return json.load(_snake_case       )



class 				snake_case :



       def __init__(				self      )  ->							List[str]:
           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(UpperCAmelCase_      )
       def 							_a      (				cls     ,UpperCAmelCase_     ,**UpperCAmelCase_      )  ->							Tuple:
           lowercase__		       =						kwargs.pop("config"     ,UpperCAmelCase_      )
           lowercase__		       =						kwargs.pop("trust_remote_code"     ,UpperCAmelCase_      )
           lowercase__		       =						True

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

           if feature_extractor_class is not None:
               lowercase__		       =						feature_extractor_class_from_name(UpperCAmelCase_      )

           lowercase__		       =						feature_extractor_auto_map is not None
           lowercase__		       =						feature_extractor_class is not None or type(UpperCAmelCase_      ) in FEATURE_EXTRACTOR_MAPPING
           lowercase__		       =						resolve_trust_remote_code(
               UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )

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

           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 							_a      (				UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Any:
           FEATURE_EXTRACTOR_MAPPING.register(UpperCAmelCase_     ,UpperCAmelCase_      )




