

import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


A									=  get_tests_dir('fixtures')


class SCREAMING_SNAKE_CASE	(		unittest.TestCase				):






			"""simple docstring"""




			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			mock.Mock()
				snake_case_   		=			5_00
				snake_case_   		=			{}
				snake_case_   		=			HTTPError
				snake_case_   		=			{}

				# Download this model to make sure it's in the cache.
				snake_case_   		=			ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'				)
				# Under the mock environment we get a 500 error when trying to reach the model.
				with mock.patch('requests.Session.request'			,					return_value=__UpperCamelCase				) as mock_head:
					snake_case_   		=			ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'				)
					# This check we did call the fake head request
					mock_head.assert_called()


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			ViTImageProcessor.from_pretrained(
				    'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'				)







			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				with self.assertRaises(__UpperCamelCase				):
					# config is in subfolder, the following should not work without specifying the subfolder
					snake_case_   		=			AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants'				)

				snake_case_   		=			AutoImageProcessor.from_pretrained(
				    'hf-internal-testing/stable-diffusion-all-variants'			,					subfolder='feature_extractor'				)

				self.assertIsNotNone(__UpperCamelCase				)







@is_staging_test
class SCREAMING_SNAKE_CASE	(		unittest.TestCase				):






			"""simple docstring"""




			@classmethod
			def       __lowerCAmelCase			(     cls				):

				"""simple docstring"""


				snake_case_   		=			TOKEN
				HfFolder.save_token(__UpperCamelCase				)


			@classmethod
			def       __lowerCAmelCase			(     cls				):

				"""simple docstring"""


				try:
					delete_repo(token=cls._token			,					repo_id='test-image-processor'				)
				except HTTPError:
					pass

				try:
					delete_repo(token=cls._token			,					repo_id='valid_org/test-image-processor-org'				)
				except HTTPError:
					pass

				try:
					delete_repo(token=cls._token			,					repo_id='test-dynamic-image-processor'				)
				except HTTPError:
					pass


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			ViTImageProcessor.from_pretrained(__UpperCamelCase				)
				image_processor.push_to_hub('test-image-processor'			,					use_auth_token=self._token				)

				snake_case_   		=			ViTImageProcessor.from_pretrained(f"""{USER}/test-image-processor"""				)
				for k, v in image_processor.__dict__.items():
					self.assertEqual(__UpperCamelCase			,					getattr(__UpperCamelCase			,					__UpperCamelCase				)				)

				# Reset repo
				delete_repo(token=self._token			,					repo_id='test-image-processor'				)

				# Push to hub via save_pretrained
				with tempfile.TemporaryDirectory() as tmp_dir:
					image_processor.save_pretrained(
					    __UpperCamelCase			,					repo_id='test-image-processor'			,					push_to_hub=__UpperCamelCase			,					use_auth_token=self._token				)

				snake_case_   		=			ViTImageProcessor.from_pretrained(f"""{USER}/test-image-processor"""				)
				for k, v in image_processor.__dict__.items():
					self.assertEqual(__UpperCamelCase			,					getattr(__UpperCamelCase			,					__UpperCamelCase				)				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			ViTImageProcessor.from_pretrained(__UpperCamelCase				)
				image_processor.push_to_hub('valid_org/test-image-processor'			,					use_auth_token=self._token				)

				snake_case_   		=			ViTImageProcessor.from_pretrained('valid_org/test-image-processor'				)
				for k, v in image_processor.__dict__.items():
					self.assertEqual(__UpperCamelCase			,					getattr(__UpperCamelCase			,					__UpperCamelCase				)				)

				# Reset repo
				delete_repo(token=self._token			,					repo_id='valid_org/test-image-processor'				)

				# Push to hub via save_pretrained
				with tempfile.TemporaryDirectory() as tmp_dir:
					image_processor.save_pretrained(
					    __UpperCamelCase			,					repo_id='valid_org/test-image-processor-org'			,					push_to_hub=__UpperCamelCase			,					use_auth_token=self._token				)

				snake_case_   		=			ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org'				)
				for k, v in image_processor.__dict__.items():
					self.assertEqual(__UpperCamelCase			,					getattr(__UpperCamelCase			,					__UpperCamelCase				)				)







			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				CustomImageProcessor.register_for_auto_class()
				snake_case_   		=			CustomImageProcessor.from_pretrained(__UpperCamelCase				)

				image_processor.push_to_hub('test-dynamic-image-processor'			,					use_auth_token=self._token				)

				# This has added the proper auto_map field to the config
				self.assertDictEqual(
				    image_processor.auto_map			,					{'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'}			,					)

				snake_case_   		=			AutoImageProcessor.from_pretrained(
				    f"""{USER}/test-dynamic-image-processor"""			,					trust_remote_code=__UpperCamelCase				)
				# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
				self.assertEqual(new_image_processor.__class__.__name__			,					'CustomImageProcessor'				)



from jiwer import compute_measures

import datasets


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

A									=  '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe 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.\n\nThis 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.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n'

A									=  '\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word error rate\n\nExamples:\n\n    >>> predictions = ["this is the prediction", "there is an other sample"]\n    >>> references = ["this is the reference", "there is another one"]\n    >>> wer = datasets.load_metric("wer")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n'


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






			"""simple docstring"""




			def       __lowerCAmelCase			(     self				):

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







			def       __lowerCAmelCase			(     self			,					__UpperCamelCase=None			,					__UpperCamelCase=None			,					__UpperCamelCase=False				):

				"""simple docstring"""


				if concatenate_texts:
					return compute_measures(__UpperCamelCase			,					__UpperCamelCase				)["wer"]
				else:
					snake_case_   		=			0
					snake_case_   		=			0
					for prediction, reference in zip(__UpperCamelCase			,					__UpperCamelCase				):
						snake_case_   		=			compute_measures(__UpperCamelCase			,					__UpperCamelCase				)
						incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
						total += measures["substitutions"] + measures["deletions"] + measures["hits"]
					return incorrect / total
