



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


SCREAMING_SNAKE_CASE_:Tuple					=						get_tests_dir("""fixtures""")
SCREAMING_SNAKE_CASE_:Any					=						get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
SCREAMING_SNAKE_CASE_:List[str]					=						get_tests_dir("""fixtures/dummy-config.json""")






class SCREAMING_SNAKE_CASE__					(		unittest.TestCase   ):




    '''simple docstring'''






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       0






    def       _lowerCAmelCase (	self		):
        A			:	int										=       AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""		)
        self.assertIsInstance(lowercase_,		lowercase_		)






    def       _lowerCAmelCase (	self		):
        A			:	Optional[int]										=       AutoFeatureExtractor.from_pretrained(lowercase_		)
        self.assertIsInstance(lowercase_,		lowercase_		)






    def       _lowerCAmelCase (	self		):

        with tempfile.TemporaryDirectory() as tmpdirname:
            A			:	List[Any]										=       WavaVecaConfig()

            # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
            A			:	Any										=       AutoFeatureExtractor.from_pretrained(lowercase_		).to_dict()

            config_dict.pop("""feature_extractor_type"""		)
            A			:	Union[str, Any]										=       WavaVecaFeatureExtractor(**lowercase_		)

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

            A			:	Any										=       AutoFeatureExtractor.from_pretrained(lowercase_		)

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

        self.assertIsInstance(lowercase_,		lowercase_		)






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       AutoFeatureExtractor.from_pretrained(lowercase_		)
        self.assertIsInstance(lowercase_,		lowercase_		)






    def       _lowerCAmelCase (	self		):

        with self.assertRaisesRegex(
            lowercase_,		"""bert-base is not a local folder and is not a valid model identifier"""		):
            A			:	Optional[int]										=       AutoFeatureExtractor.from_pretrained("""bert-base"""		)






    def       _lowerCAmelCase (	self		):

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






    def       _lowerCAmelCase (	self		):

        with self.assertRaisesRegex(
            lowercase_,		"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""",		):
            A			:	Optional[int]										=       AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""		)






    def       _lowerCAmelCase (	self		):

        with self.assertRaises(lowercase_		):
            A			:	Tuple										=       AutoFeatureExtractor.from_pretrained(
                """hf-internal-testing/test_dynamic_feature_extractor"""		)
        # If remote code is disabled, we can't load this config.
        with self.assertRaises(lowercase_		):
            A			:	Optional[int]										=       AutoFeatureExtractor.from_pretrained(
                """hf-internal-testing/test_dynamic_feature_extractor""",		trust_remote_code=lowercase_		)

        A			:	Tuple										=       AutoFeatureExtractor.from_pretrained(
            """hf-internal-testing/test_dynamic_feature_extractor""",		trust_remote_code=lowercase_		)
        self.assertEqual(feature_extractor.__class__.__name__,		"""NewFeatureExtractor"""		)

        # Test feature extractor can be reloaded.
        with tempfile.TemporaryDirectory() as tmp_dir:
            feature_extractor.save_pretrained(lowercase_		)
            A			:	List[Any]										=       AutoFeatureExtractor.from_pretrained(lowercase_,		trust_remote_code=lowercase_		)
        self.assertEqual(reloaded_feature_extractor.__class__.__name__,		"""NewFeatureExtractor"""		)






    def       _lowerCAmelCase (	self		):

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

            # Now that the config is registered, it can be used as any other config with the auto-API
            A			:	Union[str, Any]										=       CustomFeatureExtractor.from_pretrained(lowercase_		)
            with tempfile.TemporaryDirectory() as tmp_dir:
                feature_extractor.save_pretrained(lowercase_		)
                A			:	Union[str, Any]										=       AutoFeatureExtractor.from_pretrained(lowercase_		)
                self.assertIsInstance(lowercase_,		lowercase_		)

        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       _lowerCAmelCase (	self		):






        class SCREAMING_SNAKE_CASE__					(		a_   ):




            '''simple docstring'''






            __lowerCamelCase      :			str =				True

        try:
            AutoConfig.register("""custom""",		lowercase_		)
            AutoFeatureExtractor.register(lowercase_,		lowercase_		)
            # If remote code is not set, the default is to use local
            A			:	List[Any]										=       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.
            A			:	Dict										=       AutoFeatureExtractor.from_pretrained(
                """hf-internal-testing/test_dynamic_feature_extractor""",		trust_remote_code=lowercase_		)
            self.assertEqual(feature_extractor.__class__.__name__,		"""NewFeatureExtractor"""		)
            self.assertTrue(feature_extractor.is_local		)

            # If remote is enabled, we load from the Hub
            A			:	Optional[int]										=       AutoFeatureExtractor.from_pretrained(
                """hf-internal-testing/test_dynamic_feature_extractor""",		trust_remote_code=lowercase_		)
            self.assertEqual(feature_extractor.__class__.__name__,		"""NewFeatureExtractor"""		)
            self.assertTrue(not hasattr(lowercase_,		"""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]







from jiwer import compute_measures

import datasets


SCREAMING_SNAKE_CASE_:str					=						"""\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
"""

SCREAMING_SNAKE_CASE_:Union[str, Any]					=						"""\
Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.

The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.

This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.

Word error rate can then be computed as:

WER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct words,
N is the number of words in the reference (N=S+D+C).

This value indicates the average number of errors per reference word. The lower the value, the better the
performance of the ASR system with a WER of 0 being a perfect score.
"""

SCREAMING_SNAKE_CASE_:List[Any]					=						"""
Compute WER score of transcribed segments against references.

Args:
    references: List of references for each speech input.
    predictions: List of transcriptions to score.
    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.

Returns:
    (float): the word error rate

Examples:

    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]
    >>> references = [\"this is the reference\", \"there is another one\"]
    >>> wer = datasets.load_metric(\"wer\")
    >>> wer_score = wer.compute(predictions=predictions, references=references)
    >>> print(wer_score)
    0.5
"""






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




    '''simple docstring'''






    def       _lowerCAmelCase (	self		):
        return datasets.MetricInfo(
            description=_DESCRIPTION,		citation=_CITATION,		inputs_description=_KWARGS_DESCRIPTION,		features=datasets.Features(
                {
                    """predictions""": datasets.Value("""string""",		id="""sequence"""		),
                    """references""": datasets.Value("""string""",		id="""sequence"""		),
                }		),		codebase_urls=["""https://github.com/jitsi/jiwer/"""],		reference_urls=[
                """https://en.wikipedia.org/wiki/Word_error_rate""",
            ],		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__=None,		lowerCamelCase__=None,		lowerCamelCase__=False		):
        if concatenate_texts:
            return compute_measures(lowerCamelCase__,		lowerCamelCase__		)["wer"]
        else:
            A			:	str										=       0
            A			:	int										=       0
            for prediction, reference in zip(lowerCamelCase__,		lowerCamelCase__		):
                A			:	Tuple										=       compute_measures(lowerCamelCase__,		lowerCamelCase__		)
                incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                total += measures["substitutions"] + measures["deletions"] + measures["hits"]
            return incorrect / total


