


import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
  import torch

  from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
  __snake_case         =					False

if is_vision_available():
  from PIL import Image

  from transformers import PixaStructImageProcessor







class _lowerCAmelCase       (   unittest.TestCase			):







   def __init__(			self		,			UpperCamelCase__		,			UpperCamelCase__=7		,			UpperCamelCase__=3		,			UpperCamelCase__=18		,			UpperCamelCase__=30		,			UpperCamelCase__=400		,			UpperCamelCase__=None		,			UpperCamelCase__=True		,			UpperCamelCase__=True		,			UpperCamelCase__=None		,			)			->	Union[str, Any]:

       '''simple docstring'''




       snake_case					:   List[str]         =					size if size is not None else {"height": 20, "width": 20}
       snake_case					:   Optional[Any]         =					parent
       snake_case					:   str         =					batch_size
       snake_case					:   Optional[int]         =					num_channels
       snake_case					:   str         =					image_size
       snake_case					:   int         =					min_resolution
       snake_case					:   str         =					max_resolution
       snake_case					:   Optional[int]         =					size
       snake_case					:   Dict         =					do_normalize
       snake_case					:   Optional[int]         =					do_convert_rgb
       snake_case					:   Union[str, Any]         =					[512, 1024, 2048, 4096]
       snake_case					:   List[Any]         =					patch_size if patch_size is not None else {"height": 16, "width": 16}







   def 				lowerCamelCase	(			self		)			->	str:

       '''simple docstring'''




       return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       snake_case					:   List[str]         =					"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"
       snake_case					:   str         =					Image.open(requests.get(UpperCamelCase__		,			stream=UpperCamelCase__		).raw		).convert("RGB"		)
       return raw_image







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11					,							reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''					,							)
@require_torch
@require_vision
class _lowerCAmelCase       (   snake_case_					,							unittest.TestCase			):
   __UpperCAmelCase				: Dict													=						PixaStructImageProcessor if is_vision_available() else None







   def 				lowerCamelCase	(			self		)			->	Tuple:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					PixaStructImageProcessingTester(self		)







   @property
   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       return self.image_processor_tester.prepare_image_processor_dict()







   def 				lowerCamelCase	(			self		)			->	int:

       '''simple docstring'''




       snake_case					:   Optional[Any]         =					self.image_processing_class(**self.image_processor_dict		)
       self.assertTrue(hasattr(UpperCamelCase__		,			"do_normalize"		)		)
       self.assertTrue(hasattr(UpperCamelCase__		,			"do_convert_rgb"		)		)







   def 				lowerCamelCase	(			self		)			->	List[Any]:

       '''simple docstring'''




       snake_case					:   Tuple         =					self.image_processor_tester.prepare_dummy_image()

       snake_case					:   Union[str, Any]         =					self.image_processing_class(**self.image_processor_dict		)
       snake_case					:   str         =					2048

       snake_case					:   Union[str, Any]         =					image_processor(UpperCamelCase__		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		)
       self.assertTrue(torch.allclose(inputs.flattened_patches.mean()		,			torch.tensor(0.0606		)		,			atol=1e-3		,			rtol=1e-3		)		)







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       snake_case					:   str         =					self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       snake_case					:   int         =					prepare_image_inputs(self.image_processor_tester		,			equal_resolution=UpperCamelCase__		)
       for image in image_inputs:
           self.assertIsInstance(UpperCamelCase__		,			Image.Image		)

       # Test not batched input
       snake_case					:   str         =					(
           (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
           # Test not batched input
           snake_case					:   Union[str, Any]         =					image_processor(
               image_inputs[0]		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(1, max_patch, expected_hidden_dim)		,			)

           # Test batched
           snake_case					:   str         =					image_processor(
               UpperCamelCase__		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)		,			)







   def 				lowerCamelCase	(			self		)			->	Tuple:

       '''simple docstring'''




       snake_case					:   int         =					self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       snake_case					:   Any         =					prepare_image_inputs(self.image_processor_tester		,			equal_resolution=UpperCamelCase__		)
       for image in image_inputs:
           self.assertIsInstance(UpperCamelCase__		,			Image.Image		)

       # Test not batched input
       snake_case					:   Optional[int]         =					(
           (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
           * self.image_processor_tester.num_channels
       ) + 2

       snake_case					:   List[Any]         =					True

       for max_patch in self.image_processor_tester.max_patches:
           # Test not batched input
           with self.assertRaises(UpperCamelCase__		):
               snake_case					:   List[str]         =					image_processor(
                   image_inputs[0]		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches

           snake_case					:   Dict         =					"Hello"

           snake_case					:   Optional[Any]         =					image_processor(
               image_inputs[0]		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		,			header_text=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(1, max_patch, expected_hidden_dim)		,			)

           # Test batched
           snake_case					:   Tuple         =					image_processor(
               UpperCamelCase__		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		,			header_text=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)		,			)







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       snake_case					:   List[str]         =					self.image_processing_class(**self.image_processor_dict		)
       # create random numpy tensors
       snake_case					:   Optional[int]         =					prepare_image_inputs(self.image_processor_tester		,			equal_resolution=UpperCamelCase__		,			numpify=UpperCamelCase__		)
       for image in image_inputs:
           self.assertIsInstance(UpperCamelCase__		,			np.ndarray		)

       snake_case					:   Any         =					(
           (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
           # Test not batched input
           snake_case					:   Optional[int]         =					image_processor(
               image_inputs[0]		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(1, max_patch, expected_hidden_dim)		,			)

           # Test batched
           snake_case					:   Tuple         =					image_processor(
               UpperCamelCase__		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)		,			)







   def 				lowerCamelCase	(			self		)			->	List[Any]:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					self.image_processing_class(**self.image_processor_dict		)
       # create random PyTorch tensors
       snake_case					:   int         =					prepare_image_inputs(self.image_processor_tester		,			equal_resolution=UpperCamelCase__		,			torchify=UpperCamelCase__		)
       for image in image_inputs:
           self.assertIsInstance(UpperCamelCase__		,			torch.Tensor		)

       # Test not batched input
       snake_case					:   List[str]         =					(
           (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
           * self.image_processor_tester.num_channels
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
           # Test not batched input
           snake_case					:   Dict         =					image_processor(
               image_inputs[0]		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(1, max_patch, expected_hidden_dim)		,			)

           # Test batched
           snake_case					:   Tuple         =					image_processor(
               UpperCamelCase__		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)		,			)







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11					,							reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''					,							)
@require_torch
@require_vision
class _lowerCAmelCase       (   snake_case_					,							unittest.TestCase			):
   __UpperCAmelCase				: Tuple													=						PixaStructImageProcessor if is_vision_available() else None







   def 				lowerCamelCase	(			self		)			->	Dict:

       '''simple docstring'''




       snake_case					:   Any         =					PixaStructImageProcessingTester(self		,			num_channels=4		)
       snake_case					:   Optional[Any]         =					3







   @property
   def 				lowerCamelCase	(			self		)			->	List[Any]:

       '''simple docstring'''




       return self.image_processor_tester.prepare_image_processor_dict()







   def 				lowerCamelCase	(			self		)			->	List[Any]:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					self.image_processing_class(**self.image_processor_dict		)
       self.assertTrue(hasattr(UpperCamelCase__		,			"do_normalize"		)		)
       self.assertTrue(hasattr(UpperCamelCase__		,			"do_convert_rgb"		)		)







   def 				lowerCamelCase	(			self		)			->	Dict:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       snake_case					:   Any         =					prepare_image_inputs(self.image_processor_tester		,			equal_resolution=UpperCamelCase__		)
       for image in image_inputs:
           self.assertIsInstance(UpperCamelCase__		,			Image.Image		)

       # Test not batched input
       snake_case					:   List[Any]         =					(
           (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
           * (self.image_processor_tester.num_channels - 1)
       ) + 2

       for max_patch in self.image_processor_tester.max_patches:
           # Test not batched input
           snake_case					:   Dict         =					image_processor(
               image_inputs[0]		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(1, max_patch, expected_hidden_dim)		,			)

           # Test batched
           snake_case					:   int         =					image_processor(
               UpperCamelCase__		,			return_tensors="pt"		,			max_patches=UpperCamelCase__		).flattened_patches
           self.assertEqual(
               encoded_images.shape		,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)		,			)









"""simple docstring"""



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         =					""""""


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







  class _lowerCAmelCase       (   tr.AbstractTransform			):







     def __init__(			self		,			UpperCamelCase__ = " "		)			->	Any:

         '''simple docstring'''




         snake_case					:   Optional[Any]         =					sentence_delimiter







     def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	Optional[Any]:

         '''simple docstring'''




         return list(UpperCamelCase__		)







     def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	List[Any]:

         '''simple docstring'''




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



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


__snake_case         =					"""\
@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         =					"""\
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         =					"""
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 _lowerCAmelCase       (   datasets.Metric			):







   def 				lowerCamelCase	(			self		)			->	Optional[int]:

       '''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		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__=False		)			->	Optional[int]:

       '''simple docstring'''




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

       snake_case					:   Optional[int]         =					0
       snake_case					:   int         =					0
       for prediction, reference in zip(UpperCamelCase__		,			UpperCamelCase__		):
           snake_case					:   Dict         =					jiwer.compute_measures(
               UpperCamelCase__		,			UpperCamelCase__		,			truth_transform=UpperCamelCase__		,			hypothesis_transform=UpperCamelCase__		,			)
           incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
           total += measures["substitutions"] + measures["deletions"] + measures["hits"]

       return incorrect / total





