




import unittest

import numpy as np

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


if is_torch_available():
	import torch

if is_vision_available():
	from PIL import Image

	from transformers import SwinaSRImageProcessor
	from transformers.image_transforms import get_image_size

class 		lowercase_       (	unittest.TestCase				):




					def __init__(   self:		List[str],     _lowercase:		Any,     _lowercase:		Optional[int]=7,     _lowercase:		int=3,     _lowercase:		List[str]=18,     _lowercase:		Any=30,     _lowercase:		Optional[Any]=400,     _lowercase:		Union[str, Any]=True,     _lowercase:		List[Any]=1 / 255,     _lowercase:		Union[str, Any]=True,     _lowercase:		Tuple=8,     ):


									'''simple docstring'''


									__lowerCAmelCase					=  parent
									__lowerCAmelCase					=  batch_size
									__lowerCAmelCase					=  num_channels
									__lowerCAmelCase					=  image_size
									__lowerCAmelCase					=  min_resolution
									__lowerCAmelCase					=  max_resolution
									__lowerCAmelCase					=  do_rescale
									__lowerCAmelCase					=  rescale_factor
									__lowerCAmelCase					=  do_pad
									__lowerCAmelCase					=  pad_size




					def     _lowercase						(   self:		Optional[int]):


									'''simple docstring'''


									return {
									    "do_rescale": self.do_rescale,
									    "rescale_factor": self.rescale_factor,
									    "do_pad": self.do_pad,
									    "pad_size": self.pad_size,
									}







					def     _lowercase						(   self:		Union[str, Any],     _lowercase:		str=False,     _lowercase:		Union[str, Any]=False,     _lowercase:		Any=False):


									'''simple docstring'''


									assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

									if equal_resolution:
													__lowerCAmelCase					=  []
													for i in range(self.batch_size):
																	image_inputs.append(
																	    np.random.randint(
																	        255,     size=(self.num_channels, self.max_resolution, self.max_resolution),     dtype=np.uinta))
									else:
													__lowerCAmelCase					=  []
													for i in range(self.batch_size):
																	__lowerCAmelCase	,				__lowerCAmelCase					=  np.random.choice(np.arange(self.min_resolution,     self.max_resolution),     2)
																	image_inputs.append(np.random.randint(255,     size=(self.num_channels, width, height),     dtype=np.uinta))

									if not numpify and not torchify:
													# PIL expects the channel dimension as last dimension
													__lowerCAmelCase					=  [Image.fromarray(np.moveaxis(_lowercase,     0,     -1)) for x in image_inputs]

									if torchify:
													__lowerCAmelCase					=  [torch.from_numpy(_lowercase) for x in image_inputs]

									return image_inputs





@require_torch
@require_vision
class 		lowercase_       (	lowerCAmelCase__						,							unittest.TestCase				):
					__UpperCamelCase     	= SwinaSRImageProcessor if is_vision_available() else None




					def     _lowercase						(   self:		Optional[Any]):


									'''simple docstring'''


									__lowerCAmelCase					=  SwinaSRImageProcessingTester(self)




					@property
					def     _lowercase						(   self:		Tuple):


									'''simple docstring'''


									return self.image_processor_tester.prepare_image_processor_dict()




					def     _lowercase						(   self:		List[str]):


									'''simple docstring'''


									__lowerCAmelCase					=  self.image_processing_class(**self.image_processor_dict)
									self.assertTrue(hasattr(_lowercase,     """do_rescale"""))
									self.assertTrue(hasattr(_lowercase,     """rescale_factor"""))
									self.assertTrue(hasattr(_lowercase,     """do_pad"""))
									self.assertTrue(hasattr(_lowercase,     """pad_size"""))




					def     _lowercase						(   self:		int):


									'''simple docstring'''


									pass




					def     _lowercase						(   self:		List[str],     _lowercase:		Optional[Any]):


									'''simple docstring'''


									__lowerCAmelCase	,				__lowerCAmelCase					=  get_image_size(_lowercase)
									__lowerCAmelCase					=  self.image_processor_tester.pad_size

									__lowerCAmelCase					=  (old_height // size + 1) * size - old_height
									__lowerCAmelCase					=  (old_width // size + 1) * size - old_width
									return old_height + pad_height, old_width + pad_width




					def     _lowercase						(   self:		Optional[int]):


									'''simple docstring'''


									__lowerCAmelCase					=  self.image_processing_class(**self.image_processor_dict)
									# create random PIL images
									__lowerCAmelCase					=  self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase)
									for image in image_inputs:
													self.assertIsInstance(_lowercase,     Image.Image)

									# Test not batched input
									__lowerCAmelCase					=  image_processor(image_inputs[0],     return_tensors="""pt""").pixel_values
									__lowerCAmelCase	,				__lowerCAmelCase					=  self.calculate_expected_size(np.array(image_inputs[0]))
									self.assertEqual(
									    encoded_images.shape,     (
									        1,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    ),     )




					def     _lowercase						(   self:		Tuple):


									'''simple docstring'''


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

									# Test not batched input
									__lowerCAmelCase					=  image_processor(image_inputs[0],     return_tensors="""pt""").pixel_values
									__lowerCAmelCase	,				__lowerCAmelCase					=  self.calculate_expected_size(image_inputs[0])
									self.assertEqual(
									    encoded_images.shape,     (
									        1,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    ),     )







					def     _lowercase						(   self:		Any):


									'''simple docstring'''


									__lowerCAmelCase					=  self.image_processing_class(**self.image_processor_dict)
									# create random PyTorch tensors
									__lowerCAmelCase					=  self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase,     torchify=_lowercase)
									for image in image_inputs:
													self.assertIsInstance(_lowercase,     torch.Tensor)

									# Test not batched input
									__lowerCAmelCase					=  image_processor(image_inputs[0],     return_tensors="""pt""").pixel_values
									__lowerCAmelCase	,				__lowerCAmelCase					=  self.calculate_expected_size(image_inputs[0])
									self.assertEqual(
									    encoded_images.shape,     (
									        1,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    ),     )











import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata





def      UpperCAmelCase  (						UpperCamelCase__   )     ->     str:







				'''simple docstring'''


				__lowerCAmelCase					=  min(re.search("""^ +"""						,			UpperCamelCase__   ).end() if t.startswith(""" """   ) else 0 for t in string.splitlines()   )
				return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(UpperCamelCase__   )]   )


__A						:		str          =						"\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n"

__A						:		int          =						"\\n---\n---\n# Begin of markdown\n\nSome cool dataset card\n"


__A						:		Any          =						"\\n# Begin of markdown\n\nSome cool dataset card\n"

class 		lowercase_       (	unittest.TestCase				):




					def     _lowercase						(   self:		List[str]):


									'''simple docstring'''


									with tempfile.TemporaryDirectory() as tmp_dir:
													__lowerCAmelCase					=  Path(_lowercase) / """README.md"""
													with open(_lowercase,     """w+""") as readme_file:
																	readme_file.write(_lowercase)
													__lowerCAmelCase					=  DatasetMetadata.from_readme(_lowercase)
													self.assertDictEqual(_lowercase,     {"""language""": ["""zh""", """en"""], """task_ids""": ["""sentiment-classification"""]})

													with open(_lowercase,     """w+""") as readme_file:
																	readme_file.write(_lowercase)
													__lowerCAmelCase					=  DatasetMetadata.from_readme(_lowercase)
													self.assertDictEqual(_lowercase,     {})

													with open(_lowercase,     """w+""") as readme_file:
																	readme_file.write(_lowercase)
													__lowerCAmelCase					=  DatasetMetadata.from_readme(_lowercase)
													self.assertEqual(_lowercase,     {})







					def     _lowercase						(   self:		Optional[Any]):


									'''simple docstring'''


									__lowerCAmelCase					=  _dedent(
									    """\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            """)
									assert DatasetMetadata.from_yaml_string(_lowercase)

									__lowerCAmelCase					=  _dedent(
									    """\
            annotations_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            task_ids:
            - open-domain-qa
            """)
									with self.assertRaises(_lowercase):
													DatasetMetadata.from_yaml_string(_lowercase)

									__lowerCAmelCase					=  _dedent(
									    """\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - text-classification
            task_ids:
            - multi-class-classification
            paperswithcode_id:
            - squad
            configs:
            - en
            train-eval-index:
            - config: en
              task: text-classification
              task_id: multi_class_classification
              splits:
                train_split: train
                eval_split: test
              col_mapping:
                text: text
                label: target
              metrics:
                - type: accuracy
                  name: Accuracy
            extra_gated_prompt: |
              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:
              [RESEARCHER_FULLNAME] (the \"Researcher\") has requested permission to use the ImageNet database (the \"Database\") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:
              1. Researcher shall use the Database only for non-commercial research and educational purposes.
            extra_gated_fields:
              Company: text
              Country: text
              I agree to use this model for non-commerical use ONLY: checkbox
            """)
									assert DatasetMetadata.from_yaml_string(_lowercase)





