






'''simple docstring'''







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:
					__lowerCAmelCase       		=      False

if is_vision_available():
					from PIL import Image

					from transformers import PixaStructImageProcessor





class 	SCREAMING_SNAKE_CASE					(					unittest.TestCase       ):






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






			def 			SCREAMING_SNAKE_CASE      ( self      :			int					)			->			List[Any]:
							return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}







			def 			SCREAMING_SNAKE_CASE      ( self      :			Dict					)			->			Any:
							a_		:  Tuple											=      '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
							a_		:  List[str]											=      Image.open(requests.get(__SCREAMING_SNAKE_CASE  ,						stream=__SCREAMING_SNAKE_CASE					).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					(					SCREAMING_SNAKE_CASE_	,   unittest.TestCase       ):
			snake_case__  =				PixaStructImageProcessor if is_vision_available() else None






			def 			SCREAMING_SNAKE_CASE      ( self      :			int					)			->			Dict:
							a_		:  List[str]											=      PixaStructImageProcessingTester(self					)






			@property
			def 			SCREAMING_SNAKE_CASE      ( self      :			str					)			->			Optional[Any]:
							return self.image_processor_tester.prepare_image_processor_dict()






			def 			SCREAMING_SNAKE_CASE      ( self      :			List[Any]					)			->			List[str]:
							a_		:  Union[str, Any]											=      self.image_processing_class(**self.image_processor_dict					)
							self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,						'''do_normalize'''					)					)
							self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,						'''do_convert_rgb'''					)					)






			def 			SCREAMING_SNAKE_CASE      ( self      :			Optional[int]					)			->			Tuple:
							a_		:  Union[str, Any]											=      self.image_processor_tester.prepare_dummy_image()

							a_		:  Tuple											=      self.image_processing_class(**self.image_processor_dict					)
							a_		:  int											=      2048

							a_		:  Tuple											=      image_processor(__SCREAMING_SNAKE_CASE  ,						return_tensors='''pt'''  ,						max_patches=__SCREAMING_SNAKE_CASE					)
							self.assertTrue(torch.allclose(inputs.flattened_patches.mean()  ,						torch.tensor(0.0606					)  ,						atol=1e-3  ,						rtol=1e-3					)					)






			def 			SCREAMING_SNAKE_CASE      ( self      :			Optional[int]					)			->			Tuple:
							# Initialize image_processor
							a_		:  str											=      self.image_processing_class(**self.image_processor_dict					)
							# create random PIL images
							a_		:  Optional[Any]											=      prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=__SCREAMING_SNAKE_CASE					)
							for image in image_inputs:
											self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,						Image.Image					)

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

											# Test batched
											a_		:  List[Any]											=      image_processor(
											    __SCREAMING_SNAKE_CASE  ,						return_tensors='''pt'''  ,						max_patches=__SCREAMING_SNAKE_CASE					).flattened_patches
											self.assertEqual(
											    encoded_images.shape  ,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)  ,						)






			def 			SCREAMING_SNAKE_CASE      ( self      :			Union[str, Any]					)			->			str:
							# Initialize image_processor
							a_		:  List[str]											=      self.image_processing_class(**self.image_processor_dict					)
							# create random PIL images
							a_		:  Optional[int]											=      prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=__SCREAMING_SNAKE_CASE					)
							for image in image_inputs:
											self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,						Image.Image					)

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

							a_		:  Any											=      True

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

											a_		:  str											=      '''Hello'''

											a_		:  Optional[int]											=      image_processor(
											    image_inputs[0]  ,						return_tensors='''pt'''  ,						max_patches=__SCREAMING_SNAKE_CASE  ,						header_text=__SCREAMING_SNAKE_CASE					).flattened_patches
											self.assertEqual(
											    encoded_images.shape  ,						(1, max_patch, expected_hidden_dim)  ,						)

											# Test batched
											a_		:  str											=      image_processor(
											    __SCREAMING_SNAKE_CASE  ,						return_tensors='''pt'''  ,						max_patches=__SCREAMING_SNAKE_CASE  ,						header_text=__SCREAMING_SNAKE_CASE					).flattened_patches
											self.assertEqual(
											    encoded_images.shape  ,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)  ,						)






			def 			SCREAMING_SNAKE_CASE      ( self      :			Dict					)			->			Optional[int]:
							# Initialize image_processor
							a_		:  Optional[int]											=      self.image_processing_class(**self.image_processor_dict					)
							# create random numpy tensors
							a_		:  List[Any]											=      prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=__SCREAMING_SNAKE_CASE  ,						numpify=__SCREAMING_SNAKE_CASE					)
							for image in image_inputs:
											self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,						np.ndarray					)

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

											# Test batched
											a_		:  Union[str, Any]											=      image_processor(
											    __SCREAMING_SNAKE_CASE  ,						return_tensors='''pt'''  ,						max_patches=__SCREAMING_SNAKE_CASE					).flattened_patches
											self.assertEqual(
											    encoded_images.shape  ,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)  ,						)







			def 			SCREAMING_SNAKE_CASE      ( self      :			int					)			->			List[str]:
							# Initialize image_processor
							a_		:  Any											=      self.image_processing_class(**self.image_processor_dict					)
							# create random PyTorch tensors
							a_		:  Optional[Any]											=      prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=__SCREAMING_SNAKE_CASE  ,						torchify=__SCREAMING_SNAKE_CASE					)
							for image in image_inputs:
											self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,						torch.Tensor					)

							# 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_		:  Union[str, Any]											=      image_processor(
											    image_inputs[0]  ,						return_tensors='''pt'''  ,						max_patches=__SCREAMING_SNAKE_CASE					).flattened_patches
											self.assertEqual(
											    encoded_images.shape  ,						(1, max_patch, expected_hidden_dim)  ,						)

											# Test batched
											a_		:  Tuple											=      image_processor(
											    __SCREAMING_SNAKE_CASE  ,						return_tensors='''pt'''  ,						max_patches=__SCREAMING_SNAKE_CASE					).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					(					SCREAMING_SNAKE_CASE_	,   unittest.TestCase       ):
			snake_case__  =				PixaStructImageProcessor if is_vision_available() else None






			def 			SCREAMING_SNAKE_CASE      ( self      :			Tuple					)			->			Any:
							a_		:  Optional[Any]											=      PixaStructImageProcessingTester(self  ,						num_channels=4					)
							a_		:  Tuple											=      3






			@property
			def 			SCREAMING_SNAKE_CASE      ( self      :			Optional[int]					)			->			Optional[int]:
							return self.image_processor_tester.prepare_image_processor_dict()






			def 			SCREAMING_SNAKE_CASE      ( self      :			Optional[Any]					)			->			Optional[int]:
							a_		:  Optional[int]											=      self.image_processing_class(**self.image_processor_dict					)
							self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,						'''do_normalize'''					)					)
							self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE  ,						'''do_convert_rgb'''					)					)







			def 			SCREAMING_SNAKE_CASE      ( self      :			Optional[int]					)			->			Optional[Any]:
							# 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=__SCREAMING_SNAKE_CASE					)
							for image in image_inputs:
											self.assertIsInstance(__SCREAMING_SNAKE_CASE  ,						Image.Image					)

							# 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 - 1)
							) + 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=__SCREAMING_SNAKE_CASE					).flattened_patches
											self.assertEqual(
											    encoded_images.shape  ,						(1, max_patch, expected_hidden_dim)  ,						)

											# Test batched
											a_		:  Dict											=      image_processor(
											    __SCREAMING_SNAKE_CASE  ,						return_tensors='''pt'''  ,						max_patches=__SCREAMING_SNAKE_CASE					).flattened_patches
											self.assertEqual(
											    encoded_images.shape  ,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)  ,						)












'''simple docstring'''







from unittest.mock import patch

import pyspark

from datasets.packaged_modules.spark.spark import (
    Spark,
    SparkExamplesIterable,
    _generate_iterable_examples,
)

from ..utils import (
    require_dill_gt_0_3_2,
    require_not_windows,
)





def 		_UpperCAmelCase   (							__A							:   List[str]						,		__A							:   List[Any]      ):
				a_		:  Any											=      []
				for part_id in partition_order:
								a_		:  str											=      df.where(f'SPARK_PARTITION_ID() = {part_id}'      ).collect()
								for row_idx, row in enumerate(__A      ):
												expected_row_ids_and_row_dicts.append((f'{part_id}_{row_idx}', row.asDict())      )
				return expected_row_ids_and_row_dicts





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  List[str]											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  Union[str, Any]											=      spark.range(1_00      ).repartition(1      )
				a_		:  Any											=      Spark(__A      )
				# The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means
				# that each partition can hold 2 rows.
				spark_builder._repartition_df_if_needed(max_shard_size=16      )
				# Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions.
				assert spark_builder.df.rdd.getNumPartitions() == 50





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  List[Any]											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  int											=      spark.range(10      ).repartition(2      )
				a_		:  Tuple											=      [1, 0]
				a_		:  List[str]											=      _generate_iterable_examples(__A						,		__A      )  # Reverse the partitions.
				a_		:  int											=      _get_expected_row_ids_and_row_dicts_for_partition_order(__A						,		__A      )

				for i, (row_id, row_dict) in enumerate(generate_fn()      ):
								a_				,			a_		:  List[Any]											=      expected_row_ids_and_row_dicts[i]
								assert row_id == expected_row_id
								assert row_dict == expected_row_dict





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  int											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  str											=      spark.range(10      ).repartition(1      )
				a_		:  Tuple											=      SparkExamplesIterable(__A      )
				assert it.n_shards == 1
				for i, (row_id, row_dict) in enumerate(__A      ):
								assert row_id == f'0_{i}'
								assert row_dict == {"id": i}





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  Tuple											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  str											=      spark.range(30      ).repartition(3      )
				# Mock the generator so that shuffle reverses the partition indices.
				with patch('''numpy.random.Generator'''      ) as generator_mock:
								a_		:  Union[str, Any]											=      lambda __A      : x.reverse()
								a_		:  Any											=      _get_expected_row_ids_and_row_dicts_for_partition_order(__A						,		[2, 1, 0]      )

								a_		:  str											=      SparkExamplesIterable(__A      ).shuffle_data_sources(__A      )
								assert shuffled_it.n_shards == 3
								for i, (row_id, row_dict) in enumerate(__A      ):
												a_				,			a_		:  Optional[Any]											=      expected_row_ids_and_row_dicts[i]
												assert row_id == expected_row_id
												assert row_dict == expected_row_dict





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  int											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  List[str]											=      spark.range(20      ).repartition(4      )

				# Partitions 0 and 2
				a_		:  Dict											=      SparkExamplesIterable(__A      ).shard_data_sources(worker_id=0						,		num_workers=2      )
				assert shard_it_a.n_shards == 2
				a_		:  Optional[Any]											=      _get_expected_row_ids_and_row_dicts_for_partition_order(__A						,		[0, 2]      )
				for i, (row_id, row_dict) in enumerate(__A      ):
								a_				,			a_		:  Tuple											=      expected_row_ids_and_row_dicts_a[i]
								assert row_id == expected_row_id
								assert row_dict == expected_row_dict

				# Partitions 1 and 3
				a_		:  List[Any]											=      SparkExamplesIterable(__A      ).shard_data_sources(worker_id=1						,		num_workers=2      )
				assert shard_it_a.n_shards == 2
				a_		:  Optional[int]											=      _get_expected_row_ids_and_row_dicts_for_partition_order(__A						,		[1, 3]      )
				for i, (row_id, row_dict) in enumerate(__A      ):
								a_				,			a_		:  Any											=      expected_row_ids_and_row_dicts_a[i]
								assert row_id == expected_row_id
								assert row_dict == expected_row_dict





@require_not_windows
@require_dill_gt_0_3_2
def 		_UpperCAmelCase   (							):
				a_		:  Any											=      pyspark.sql.SparkSession.builder.master('''local[*]'''      ).appName('''pyspark'''      ).getOrCreate()
				a_		:  List[Any]											=      spark.range(1_00      ).repartition(1      )
				a_		:  Optional[Any]											=      Spark(__A      )
				# Choose a small max_shard_size for maximum partitioning.
				spark_builder._repartition_df_if_needed(max_shard_size=1      )
				# The new number of partitions should not be greater than the number of rows.
				assert spark_builder.df.rdd.getNumPartitions() == 1_00




