



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:
     SCREAMING_SNAKE_CASE_:Any					=						False

if is_vision_available():
     from PIL import Image

     from transformers import PixaStructImageProcessor






class SCREAMING_SNAKE_CASE__					(		unittest.TestCase   ):




    '''simple docstring'''






    def __init__(	self,		lowerCamelCase__,		lowerCamelCase__=7,		lowerCamelCase__=3,		lowerCamelCase__=18,		lowerCamelCase__=30,		lowerCamelCase__=400,		lowerCamelCase__=None,		lowerCamelCase__=True,		lowerCamelCase__=True,		lowerCamelCase__=None,		):
        A			:	Any										=       size if size is not None else {"""height""": 20, """width""": 20}
        A			:	Optional[int]										=       parent
        A			:	List[str]										=       batch_size
        A			:	str										=       num_channels
        A			:	str										=       image_size
        A			:	int										=       min_resolution
        A			:	int										=       max_resolution
        A			:	List[Any]										=       size
        A			:	List[Any]										=       do_normalize
        A			:	List[str]										=       do_convert_rgb
        A			:	Optional[int]										=       [512, 1024, 2048, 4096]
        A			:	Any										=       patch_size if patch_size is not None else {"""height""": 16, """width""": 16}






    def       _lowerCAmelCase (	self		):
        return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}






    def       _lowerCAmelCase (	self		):
        A			:	int										=       """https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"""
        A			:	str										=       Image.open(requests.get(a__,		stream=a__		).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 SCREAMING_SNAKE_CASE__					(		lowerCAmelCase__			,						unittest.TestCase   ):




    '''simple docstring'''






    __lowerCamelCase      :			Tuple =				PixaStructImageProcessor if is_vision_available() else None






    def       _lowerCAmelCase (	self		):
        A			:	Union[str, Any]										=       PixaStructImageProcessingTester(self		)






    @property
    def       _lowerCAmelCase (	self		):
        return self.image_processor_tester.prepare_image_processor_dict()






    def       _lowerCAmelCase (	self		):
        A			:	Union[str, Any]										=       self.image_processing_class(**self.image_processor_dict		)
        self.assertTrue(hasattr(a__,		"""do_normalize"""		)		)
        self.assertTrue(hasattr(a__,		"""do_convert_rgb"""		)		)






    def       _lowerCAmelCase (	self		):
        A			:	int										=       self.image_processor_tester.prepare_dummy_image()

        A			:	Tuple										=       self.image_processing_class(**self.image_processor_dict		)
        A			:	Optional[Any]										=       2048

        A			:	Any										=       image_processor(a__,		return_tensors="""pt""",		max_patches=a__		)
        self.assertTrue(torch.allclose(inputs.flattened_patches.mean(),		torch.tensor(0.0606		),		atol=1e-3,		rtol=1e-3		)		)






    def       _lowerCAmelCase (	self		):
        # Initialize image_processor
        A			:	int										=       self.image_processing_class(**self.image_processor_dict		)
        # create random PIL images
        A			:	Any										=       prepare_image_inputs(self.image_processor_tester,		equal_resolution=a__		)
        for image in image_inputs:
            self.assertIsInstance(a__,		Image.Image		)

        # Test not batched input
        A			:	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
            A			:	Tuple										=       image_processor(
                image_inputs[0],		return_tensors="""pt""",		max_patches=a__		).flattened_patches
            self.assertEqual(
                encoded_images.shape,		(1, max_patch, expected_hidden_dim),		)

            # Test batched
            A			:	Dict										=       image_processor(
                a__,		return_tensors="""pt""",		max_patches=a__		).flattened_patches
            self.assertEqual(
                encoded_images.shape,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),		)






    def       _lowerCAmelCase (	self		):
        # Initialize image_processor
        A			:	Tuple										=       self.image_processing_class(**self.image_processor_dict		)
        # create random PIL images
        A			:	Optional[int]										=       prepare_image_inputs(self.image_processor_tester,		equal_resolution=a__		)
        for image in image_inputs:
            self.assertIsInstance(a__,		Image.Image		)

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

        A			:	List[Any]										=       True

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

            A			:	Optional[int]										=       """Hello"""

            A			:	Union[str, Any]										=       image_processor(
                image_inputs[0],		return_tensors="""pt""",		max_patches=a__,		header_text=a__		).flattened_patches
            self.assertEqual(
                encoded_images.shape,		(1, max_patch, expected_hidden_dim),		)

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






    def       _lowerCAmelCase (	self		):
        # Initialize image_processor
        A			:	Any										=       self.image_processing_class(**self.image_processor_dict		)
        # create random numpy tensors
        A			:	Optional[Any]										=       prepare_image_inputs(self.image_processor_tester,		equal_resolution=a__,		numpify=a__		)
        for image in image_inputs:
            self.assertIsInstance(a__,		np.ndarray		)

        A			:	Optional[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
            A			:	Any										=       image_processor(
                image_inputs[0],		return_tensors="""pt""",		max_patches=a__		).flattened_patches
            self.assertEqual(
                encoded_images.shape,		(1, max_patch, expected_hidden_dim),		)

            # Test batched
            A			:	Dict										=       image_processor(
                a__,		return_tensors="""pt""",		max_patches=a__		).flattened_patches
            self.assertEqual(
                encoded_images.shape,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),		)






    def       _lowerCAmelCase (	self		):
        # Initialize image_processor
        A			:	List[Any]										=       self.image_processing_class(**self.image_processor_dict		)
        # create random PyTorch tensors
        A			:	Tuple										=       prepare_image_inputs(self.image_processor_tester,		equal_resolution=a__,		torchify=a__		)
        for image in image_inputs:
            self.assertIsInstance(a__,		torch.Tensor		)

        # Test not batched input
        A			:	int										=       (
            (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
            A			:	List[Any]										=       image_processor(
                image_inputs[0],		return_tensors="""pt""",		max_patches=a__		).flattened_patches
            self.assertEqual(
                encoded_images.shape,		(1, max_patch, expected_hidden_dim),		)

            # Test batched
            A			:	int										=       image_processor(
                a__,		return_tensors="""pt""",		max_patches=a__		).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 SCREAMING_SNAKE_CASE__					(		lowerCAmelCase__			,						unittest.TestCase   ):




    '''simple docstring'''






    __lowerCamelCase      :			str =				PixaStructImageProcessor if is_vision_available() else None






    def       _lowerCAmelCase (	self		):
        A			:	int										=       PixaStructImageProcessingTester(self,		num_channels=4		)
        A			:	List[str]										=       3






    @property
    def       _lowerCAmelCase (	self		):
        return self.image_processor_tester.prepare_image_processor_dict()






    def       _lowerCAmelCase (	self		):
        A			:	List[str]										=       self.image_processing_class(**self.image_processor_dict		)
        self.assertTrue(hasattr(a__,		"""do_normalize"""		)		)
        self.assertTrue(hasattr(a__,		"""do_convert_rgb"""		)		)






    def       _lowerCAmelCase (	self		):
        # Initialize image_processor
        A			:	Optional[int]										=       self.image_processing_class(**self.image_processor_dict		)
        # create random PIL images
        A			:	Dict										=       prepare_image_inputs(self.image_processor_tester,		equal_resolution=a__		)
        for image in image_inputs:
            self.assertIsInstance(a__,		Image.Image		)

        # Test not batched input
        A			:	Optional[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
            A			:	int										=       image_processor(
                image_inputs[0],		return_tensors="""pt""",		max_patches=a__		).flattened_patches
            self.assertEqual(
                encoded_images.shape,		(1, max_patch, expected_hidden_dim),		)

            # Test batched
            A			:	List[str]										=       image_processor(
                a__,		return_tensors="""pt""",		max_patches=a__		).flattened_patches
            self.assertEqual(
                encoded_images.shape,		(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),		)







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


