
'''simple docstring'''
import unittest

import numpy as np

from transformers.testing_utils import is_flaky, 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

if is_vision_available():
						from PIL import Image

						from transformers import DonutImageProcessor


class 			SCREAMING_SNAKE_CASE__      (     unittest.TestCase):







				def __init__(       self						,				A_						,				A_=7						,				A_=3						,				A_=18						,				A_=30						,				A_=400						,				A_=True						,				A_=None						,				A_=True						,				A_=False						,				A_=True						,				A_=True						,				A_=[0.5, 0.5, 0.5]						,				A_=[0.5, 0.5, 0.5]						,				)->		Dict:







											'''simple docstring'''






											UpperCamelCase   			=     parent
											UpperCamelCase   			=     batch_size
											UpperCamelCase   			=     num_channels
											UpperCamelCase   			=     image_size
											UpperCamelCase   			=     min_resolution
											UpperCamelCase   			=     max_resolution
											UpperCamelCase   			=     do_resize
											UpperCamelCase   			=     size if size is not None else {'height': 18, 'width': 20}
											UpperCamelCase   			=     do_thumbnail
											UpperCamelCase   			=     do_align_axis
											UpperCamelCase   			=     do_pad
											UpperCamelCase   			=     do_normalize
											UpperCamelCase   			=     image_mean
											UpperCamelCase   			=     image_std







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







											'''simple docstring'''






											return {
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "do_thumbnail": self.do_thumbnail,
											    "do_align_long_axis": self.do_align_axis,
											    "do_pad": self.do_pad,
											    "do_normalize": self.do_normalize,
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											}


@require_torch
@require_vision
class 			SCREAMING_SNAKE_CASE__      (     snake_case_							,       unittest.TestCase):
				lowerCAmelCase_     			=							DonutImageProcessor if is_vision_available() else None







				def 						UpperCAmelCase_    (       self     )->		str:







											'''simple docstring'''






											UpperCamelCase   			=     DonutImageProcessingTester(self     )







				@property
				def 						UpperCAmelCase_    (       self     )->		str:







											'''simple docstring'''






											return self.image_processor_tester.prepare_image_processor_dict()







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







											'''simple docstring'''






											UpperCamelCase   			=     self.image_processing_class(**self.image_processor_dict     )
											self.assertTrue(hasattr(A_						,				'do_resize'     )     )
											self.assertTrue(hasattr(A_						,				'size'     )     )
											self.assertTrue(hasattr(A_						,				'do_thumbnail'     )     )
											self.assertTrue(hasattr(A_						,				'do_align_long_axis'     )     )
											self.assertTrue(hasattr(A_						,				'do_pad'     )     )
											self.assertTrue(hasattr(A_						,				'do_normalize'     )     )
											self.assertTrue(hasattr(A_						,				'image_mean'     )     )
											self.assertTrue(hasattr(A_						,				'image_std'     )     )







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







											'''simple docstring'''






											UpperCamelCase   			=     self.image_processing_class.from_dict(self.image_processor_dict     )
											self.assertEqual(image_processor.size						,				{'height': 18, 'width': 20}     )

											UpperCamelCase   			=     self.image_processing_class.from_dict(self.image_processor_dict						,				size=42     )
											self.assertEqual(image_processor.size						,				{'height': 42, 'width': 42}     )

											# Previous config had dimensions in (width, height) order
											UpperCamelCase   			=     self.image_processing_class.from_dict(self.image_processor_dict						,				size=(42, 84)     )
											self.assertEqual(image_processor.size						,				{'height': 84, 'width': 42}     )







				def 						UpperCAmelCase_    (       self     )->		Tuple:







											'''simple docstring'''






											pass







				@is_flaky()
				def 						UpperCAmelCase_    (       self     )->		Any:







											'''simple docstring'''






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

											# Test not batched input
											UpperCamelCase   			=     image_processing(image_inputs[0]						,				return_tensors='pt'     ).pixel_values
											self.assertEqual(
											    encoded_images.shape						,				(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size['height'],
											        self.image_processor_tester.size['width'],
											    )						,				)

											# Test batched
											UpperCamelCase   			=     image_processing(A_						,				return_tensors='pt'     ).pixel_values
											self.assertEqual(
											    encoded_images.shape						,				(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size['height'],
											        self.image_processor_tester.size['width'],
											    )						,				)







				@is_flaky()
				def 						UpperCAmelCase_    (       self     )->		Optional[int]:







											'''simple docstring'''






											UpperCamelCase   			=     self.image_processing_class(**self.image_processor_dict     )
											# create random numpy tensors
											UpperCamelCase   			=     prepare_image_inputs(self.image_processor_tester						,				equal_resolution=A_						,				numpify=A_     )
											for image in image_inputs:
																		self.assertIsInstance(A_						,				np.ndarray     )

											# Test not batched input
											UpperCamelCase   			=     image_processing(image_inputs[0]						,				return_tensors='pt'     ).pixel_values
											self.assertEqual(
											    encoded_images.shape						,				(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size['height'],
											        self.image_processor_tester.size['width'],
											    )						,				)

											# Test batched
											UpperCamelCase   			=     image_processing(A_						,				return_tensors='pt'     ).pixel_values
											self.assertEqual(
											    encoded_images.shape						,				(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size['height'],
											        self.image_processor_tester.size['width'],
											    )						,				)







				@is_flaky()
				def 						UpperCAmelCase_    (       self     )->		Dict:







											'''simple docstring'''






											UpperCamelCase   			=     self.image_processing_class(**self.image_processor_dict     )
											# create random PyTorch tensors
											UpperCamelCase   			=     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
											UpperCamelCase   			=     image_processing(image_inputs[0]						,				return_tensors='pt'     ).pixel_values
											self.assertEqual(
											    encoded_images.shape						,				(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size['height'],
											        self.image_processor_tester.size['width'],
											    )						,				)

											# Test batched
											UpperCamelCase   			=     image_processing(A_						,				return_tensors='pt'     ).pixel_values
											self.assertEqual(
											    encoded_images.shape						,				(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size['height'],
											        self.image_processor_tester.size['width'],
											    )						,				)








"""simple docstring"""




import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


__magic_name__						: Tuple    =				'hf-internal-testing/tiny-random-bert'
__magic_name__						: Dict    =				os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert')
__magic_name__						: Optional[Any]    =				'9b8c223d42b2188cb49d29af482996f9d0f3e5a6'




class 			__snake_case   (unittest.TestCase  ):




							def   __a   (     self:    List[Any]   ):
										__lowerCamelCase          =      cached_file(A_     ,							A_   )
										# Should have downloaded the file in here
										self.assertTrue(os.path.isdir(A_   )   )
										# Cache should contain at least those three subfolders:
										for subfolder in ["blobs", "refs", "snapshots"]:
													self.assertTrue(os.path.isdir(os.path.join(A_     ,							A_   )   )   )
										with open(os.path.join(A_     ,							"""refs"""     ,							"""main"""   )   ) as f:
													__lowerCamelCase          =      f.read()
										self.assertEqual(A_     ,							os.path.join(A_     ,							"""snapshots"""     ,							A_     ,							A_   )   )
										self.assertTrue(os.path.isfile(A_   )   )

										# File is cached at the same place the second time.
										__lowerCamelCase          =      cached_file(A_     ,							A_   )
										self.assertEqual(A_     ,							A_   )

										# Using a specific revision to test the full commit hash.
										__lowerCamelCase          =      cached_file(A_     ,							A_     ,							revision="""9b8c223"""   )
										self.assertEqual(A_     ,							os.path.join(A_     ,							"""snapshots"""     ,							A_     ,							A_   )   )




							def   __a   (     self:    int   ):
										with self.assertRaisesRegex(A_     ,							"""is not a valid model identifier"""   ):
													__lowerCamelCase          =      cached_file("""tiny-random-bert"""     ,							A_   )

										with self.assertRaisesRegex(A_     ,							"""is not a valid git identifier"""   ):
													__lowerCamelCase          =      cached_file(A_     ,							A_     ,							revision="""aaaa"""   )

										with self.assertRaisesRegex(A_     ,							"""does not appear to have a file named"""   ):
													__lowerCamelCase          =      cached_file(A_     ,							"""conf"""   )




							def   __a   (     self:    Optional[int]   ):
										with self.assertRaisesRegex(A_     ,							"""does not appear to have a file named"""   ):
													__lowerCamelCase          =      cached_file(A_     ,							"""conf"""   )

										with open(os.path.join(A_     ,							"""refs"""     ,							"""main"""   )   ) as f:
													__lowerCamelCase          =      f.read()
										self.assertTrue(os.path.isfile(os.path.join(A_     ,							""".no_exist"""     ,							A_     ,							"""conf"""   )   )   )

										__lowerCamelCase          =      cached_file(A_     ,							"""conf"""     ,							_raise_exceptions_for_missing_entries=A_   )
										self.assertIsNone(A_   )

										__lowerCamelCase          =      cached_file(A_     ,							"""conf"""     ,							local_files_only=A_     ,							_raise_exceptions_for_missing_entries=A_   )
										self.assertIsNone(A_   )

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

										# Under the mock environment we get a 500 error when trying to reach the tokenizer.
										with mock.patch("""requests.Session.request"""     ,							return_value=A_   ) as mock_head:
													__lowerCamelCase          =      cached_file(A_     ,							"""conf"""     ,							_raise_exceptions_for_connection_errors=A_   )
													self.assertIsNone(A_   )
													# This check we did call the fake head request
													mock_head.assert_called()




							def   __a   (     self:    str   ):
										self.assertTrue(has_file("""hf-internal-testing/tiny-bert-pt-only"""     ,							A_   )   )
										self.assertFalse(has_file("""hf-internal-testing/tiny-bert-pt-only"""     ,							A_   )   )
										self.assertFalse(has_file("""hf-internal-testing/tiny-bert-pt-only"""     ,							A_   )   )




							def   __a   (     self:    str   ):
										# `get_file_from_repo` returns None if the file does not exist
										self.assertIsNone(get_file_from_repo("""bert-base-cased"""     ,							"""ahah.txt"""   )   )

										# The function raises if the repository does not exist.
										with self.assertRaisesRegex(A_     ,							"""is not a valid model identifier"""   ):
													get_file_from_repo("""bert-base-case"""     ,							A_   )

										# The function raises if the revision does not exist.
										with self.assertRaisesRegex(A_     ,							"""is not a valid git identifier"""   ):
													get_file_from_repo("""bert-base-cased"""     ,							A_     ,							revision="""ahaha"""   )

										__lowerCamelCase          =      get_file_from_repo("""bert-base-cased"""     ,							A_   )
										# The name is the cached name which is not very easy to test, so instead we load the content.
										__lowerCamelCase          =      json.loads(open(A_     ,							"""r"""   ).read()   )
										self.assertEqual(config["""hidden_size"""]     ,							7_68   )




							def   __a   (     self:    Union[str, Any]   ):
										with tempfile.TemporaryDirectory() as tmp_dir:
													__lowerCamelCase          =      Path(A_   ) / """a.txt"""
													filename.touch()
													self.assertEqual(get_file_from_repo(A_     ,							"""a.txt"""   )     ,							str(A_   )   )

													self.assertIsNone(get_file_from_repo(A_     ,							"""b.txt"""   )   )




