



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 					_A (			unittest.TestCase					):



       def 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           __a		 =       0



       def 	_lowerCamelCase    (	self							:  List[str]):


           '''simple docstring'''

           __a		 =       AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''')
           self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)



       def 	_lowerCamelCase    (	self							:  Dict):


           '''simple docstring'''

           with tempfile.TemporaryDirectory() as tmpdirname:
               __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''preprocessor_config.json'''
               __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''config.json'''
               json.dump(
                   {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w''')  ,	)
               json.dump({'''model_type''': '''clip'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w'''))

               __a		 =       AutoImageProcessor.from_pretrained(__SCREAMING_SNAKE_CASE)
               self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)



       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           with tempfile.TemporaryDirectory() as tmpdirname:
               __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''preprocessor_config.json'''
               __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''config.json'''
               json.dump(
                   {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w''')  ,	)
               json.dump({'''model_type''': '''clip'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w'''))

               __a		 =       AutoImageProcessor.from_pretrained(__SCREAMING_SNAKE_CASE)
               self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)



       def 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           with tempfile.TemporaryDirectory() as tmpdirname:
               __a		 =       CLIPConfig()

               # Create a dummy config file with image_proceesor_type
               __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''preprocessor_config.json'''
               __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''config.json'''
               json.dump(
                   {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w''')  ,	)
               json.dump({'''model_type''': '''clip'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w'''))

               # remove image_processor_type to make sure config.json alone is enough to load image processor locally
               __a		 =       AutoImageProcessor.from_pretrained(__SCREAMING_SNAKE_CASE).to_dict()

               config_dict.pop('''image_processor_type''')
               __a		 =       CLIPImageProcessor(**__SCREAMING_SNAKE_CASE)

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

               __a		 =       AutoImageProcessor.from_pretrained(__SCREAMING_SNAKE_CASE)

               # make sure private variable is not incorrectly saved
               __a		 =       json.loads(config.to_json_string())
               self.assertTrue('''_processor_class''' not in dict_as_saved)

           self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)



       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           with tempfile.TemporaryDirectory() as tmpdirname:
               __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''preprocessor_config.json'''
               json.dump(
                   {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w''')  ,	)

               __a		 =       AutoImageProcessor.from_pretrained(__SCREAMING_SNAKE_CASE)
               self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)



       def 	_lowerCamelCase    (	self							:  Any):


           '''simple docstring'''

           with self.assertRaisesRegex(
               __SCREAMING_SNAKE_CASE  ,	'''clip-base is not a local folder and is not a valid model identifier'''):
               __a		 =       AutoImageProcessor.from_pretrained('''clip-base''')



       def 	_lowerCamelCase    (	self							:  int):


           '''simple docstring'''

           with self.assertRaisesRegex(
               __SCREAMING_SNAKE_CASE  ,	r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''):
               __a		 =       AutoImageProcessor.from_pretrained(__SCREAMING_SNAKE_CASE  ,	revision='''aaaaaa''')



       def 	_lowerCamelCase    (	self							:  int):


           '''simple docstring'''

           with self.assertRaisesRegex(
               __SCREAMING_SNAKE_CASE  ,	'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''  ,	):
               __a		 =       AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''')



       def 	_lowerCamelCase    (	self							:  Tuple):


           '''simple docstring'''

           with self.assertRaises(__SCREAMING_SNAKE_CASE):
               __a		 =       AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''')
           # If remote code is disabled, we can't load this config.
           with self.assertRaises(__SCREAMING_SNAKE_CASE):
               __a		 =       AutoImageProcessor.from_pretrained(
                   '''hf-internal-testing/test_dynamic_image_processor'''  ,	trust_remote_code=__SCREAMING_SNAKE_CASE)

           __a		 =       AutoImageProcessor.from_pretrained(
               '''hf-internal-testing/test_dynamic_image_processor'''  ,	trust_remote_code=__SCREAMING_SNAKE_CASE)
           self.assertEqual(image_processor.__class__.__name__  ,	'''NewImageProcessor''')

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



       def 	_lowerCamelCase    (	self							:  Any):


           '''simple docstring'''

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

               with tempfile.TemporaryDirectory() as tmpdirname:
                   __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''preprocessor_config.json'''
                   __a		 =       Path(__SCREAMING_SNAKE_CASE) / '''config.json'''
                   json.dump(
                       {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w''')  ,	)
                   json.dump({'''model_type''': '''clip'''}  ,	open(__SCREAMING_SNAKE_CASE  ,	'''w'''))

                   __a		 =       CustomImageProcessor.from_pretrained(__SCREAMING_SNAKE_CASE)

               # 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(__SCREAMING_SNAKE_CASE)
                   __a		 =       AutoImageProcessor.from_pretrained(__SCREAMING_SNAKE_CASE)
                   self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)

           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 	_lowerCamelCase    (	self							:  Optional[int]):


           '''simple docstring'''

           class 					_A (			__UpperCAmelCase					):
                  UpperCamelCase__						:					Dict		      =		True

           try:
               AutoConfig.register('''custom'''  ,	__SCREAMING_SNAKE_CASE)
               AutoImageProcessor.register(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)
               # If remote code is not set, the default is to use local
               __a		 =       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.
               __a		 =       AutoImageProcessor.from_pretrained(
                   '''hf-internal-testing/test_dynamic_image_processor'''  ,	trust_remote_code=__SCREAMING_SNAKE_CASE)
               self.assertEqual(image_processor.__class__.__name__  ,	'''NewImageProcessor''')
               self.assertTrue(image_processor.is_local)

               # If remote is enabled, we load from the Hub
               __a		 =       AutoImageProcessor.from_pretrained(
                   '''hf-internal-testing/test_dynamic_image_processor'''  ,	trust_remote_code=__SCREAMING_SNAKE_CASE)
               self.assertEqual(image_processor.__class__.__name__  ,	'''NewImageProcessor''')
               self.assertTrue(not hasattr(__SCREAMING_SNAKE_CASE  ,	'''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]










from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('''3.8'''):
 import importlib_metadata
else:
 import importlib.metadata as importlib_metadata


__snake_case		:int   	=  ''''''


if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):

 class 					_A (			tr.AbstractTransform					):



        def __init__(	self							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  str = " "):


            '''simple docstring'''

            __a		 =       sentence_delimiter



        def 	_lowerCamelCase    (	self							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  str):


            '''simple docstring'''

            return list(__SCREAMING_SNAKE_CASE)





        def 	_lowerCamelCase    (	self							:  int  ,	__SCREAMING_SNAKE_CASE							:  List[str]):


            '''simple docstring'''

            __a		 =       []
            for sent_idx, sentence in enumerate(__SCREAMING_SNAKE_CASE):
                chars.extend(self.process_string(__SCREAMING_SNAKE_CASE))
                if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__SCREAMING_SNAKE_CASE) - 1:
                    chars.append(self.sentence_delimiter)
            return chars


 __snake_case		:Any   	=  tr.Compose(
     [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
 )
else:
 __snake_case		:Optional[int]   	=  tr.Compose(
     [
         tr.RemoveMultipleSpaces(),
         tr.Strip(),
         tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
         tr.ReduceToListOfListOfChars(),
     ]
 )


__snake_case		:Optional[int]   	=  '''\
@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.}
}
'''

__snake_case		:Tuple   	=  '''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (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 characters,
N is the number of characters in the reference (N=S+D+C).

CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''

__snake_case		:Tuple   	=  '''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''

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



       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           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''',
                   '''https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates''',
               ]  ,	)





       def 	_lowerCamelCase    (	self							:  Optional[int]  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  Dict=False):


           '''simple docstring'''

           if concatenate_texts:
               return jiwer.compute_measures(
                   __SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE  ,	truth_transform=__SCREAMING_SNAKE_CASE  ,	hypothesis_transform=__SCREAMING_SNAKE_CASE  ,	)["wer"]

           __a		 =       0
           __a		 =       0
           for prediction, reference in zip(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE):
               __a		 =       jiwer.compute_measures(
                   __SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE  ,	truth_transform=__SCREAMING_SNAKE_CASE  ,	hypothesis_transform=__SCREAMING_SNAKE_CASE  ,	)
               incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
               total += measures["substitutions"] + measures["deletions"] + measures["hits"]

           return incorrect / total





