"""simple docstring"""




import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata



def 				__a       (			_lowercase						):







					"""simple docstring"""





					lowerCamelCase__		:   Optional[Any]  				=					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_						)]						)


UpperCAmelCase       :    List[Any]									=			"\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n"

UpperCAmelCase       :    Tuple									=			"\\n---\n---\n# Begin of markdown\n\nSome cool dataset card\n"


UpperCAmelCase       :    List[str]									=			"\\n# Begin of markdown\n\nSome cool dataset card\n"





class        __SCREAMING_SNAKE_CASE     (   unittest.TestCase							):







				def   lowercase_		(    self    :Optional[int]  )      ->					Union[str, Any]:




									"""simple docstring"""



									with tempfile.TemporaryDirectory() as tmp_dir:
														lowerCamelCase__		:   Union[str, Any]  				=					Path(UpperCAmelCase__  ) / '''README.md'''
														with open(UpperCAmelCase__      ,'''w+'''  ) as readme_file:
																			readme_file.write(UpperCAmelCase__  )
														lowerCamelCase__		:   Dict  				=					DatasetMetadata.from_readme(UpperCAmelCase__  )
														self.assertDictEqual(UpperCAmelCase__      ,{'''language''': ['''zh''', '''en'''], '''task_ids''': ['''sentiment-classification''']}  )

														with open(UpperCAmelCase__      ,'''w+'''  ) as readme_file:
																			readme_file.write(UpperCAmelCase__  )
														lowerCamelCase__		:   Any  				=					DatasetMetadata.from_readme(UpperCAmelCase__  )
														self.assertDictEqual(UpperCAmelCase__      ,{}  )

														with open(UpperCAmelCase__      ,'''w+'''  ) as readme_file:
																			readme_file.write(UpperCAmelCase__  )
														lowerCamelCase__		:   int  				=					DatasetMetadata.from_readme(UpperCAmelCase__  )
														self.assertEqual(UpperCAmelCase__      ,{}  )







				def   lowercase_		(    self    :Optional[Any]  )      ->					List[str]:




									"""simple docstring"""



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

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

									lowerCamelCase__		:   Tuple  				=					_dedent(
									    '''\\n            annotations_creators:\n            - found\n            language_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - text-classification\n            task_ids:\n            - multi-class-classification\n            paperswithcode_id:\n            - squad\n            configs:\n            - en\n            train-eval-index:\n            - config: en\n              task: text-classification\n              task_id: multi_class_classification\n              splits:\n                train_split: train\n                eval_split: test\n              col_mapping:\n                text: text\n                label: target\n              metrics:\n                - type: accuracy\n                  name: Accuracy\n            extra_gated_prompt: |\n              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:\n              [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:\n              1. Researcher shall use the Database only for non-commercial research and educational purposes.\n            extra_gated_fields:\n              Company: text\n              Country: text\n              I agree to use this model for non-commerical use ONLY: checkbox\n            '''  )
									assert DatasetMetadata.from_yaml_string(UpperCAmelCase__  )









"""simple docstring"""





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, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import OwlViTImageProcessor




class    _lowerCAmelCase    (      unittest.TestCase  ):







 """simple docstring"""







 def __init__(     self				:     Union[str, Any],   UpperCAmelCase__				:     Dict,   UpperCAmelCase__				:     Optional[int]=7,   UpperCAmelCase__				:     List[str]=3,   UpperCAmelCase__				:     List[Any]=1_8,   UpperCAmelCase__				:     Any=3_0,   UpperCAmelCase__				:     str=4_0_0,   UpperCAmelCase__				:     Union[str, Any]=True,   UpperCAmelCase__				:     Dict=None,   UpperCAmelCase__				:     int=True,   UpperCAmelCase__				:     str=None,   UpperCAmelCase__				:     Dict=True,   UpperCAmelCase__				:     str=[0.48_145_466, 0.4_578_275, 0.40_821_073],   UpperCAmelCase__				:     Dict=[0.26_862_954, 0.26_130_258, 0.27_577_711],   UpperCAmelCase__				:     Any=True,   ):
    __lowercase								=		parent
    __lowercase								=		batch_size
    __lowercase								=		num_channels
    __lowercase								=		image_size
    __lowercase								=		min_resolution
    __lowercase								=		max_resolution
    __lowercase								=		do_resize
    __lowercase								=		size if size is not None else {"height": 1_8, "width": 1_8}
    __lowercase								=		do_center_crop
    __lowercase								=		crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
    __lowercase								=		do_normalize
    __lowercase								=		image_mean
    __lowercase								=		image_std
    __lowercase								=		do_convert_rgb



 def    _lowercase					(     self				:     List[str]      ):
    return {
        "do_resize": self.do_resize,
        "size": self.size,
        "do_center_crop": self.do_center_crop,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
        "do_convert_rgb": self.do_convert_rgb,
    }







@require_torch
@require_vision
class    _lowerCAmelCase    (      lowercase	,unittest.TestCase  ):







 """simple docstring"""







 __UpperCAmelCase      :   List[str]  						=      OwlViTImageProcessor if is_vision_available() else None


 def    _lowercase					(     self				:     Dict      ):
    __lowercase								=		OwlViTImageProcessingTester(self      )


 @property
 def    _lowercase					(     self				:     int      ):
    return self.image_processor_tester.prepare_image_processor_dict()


 def    _lowercase					(     self				:     Tuple      ):
    __lowercase								=		self.image_processing_class(**self.image_processor_dict      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "do_resize"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "size"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "do_center_crop"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "center_crop"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "do_normalize"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "image_mean"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "image_std"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "do_convert_rgb"      )      )


 def    _lowercase					(     self				:     Dict      ):
    __lowercase								=		self.image_processing_class.from_dict(self.image_processor_dict      )
    self.assertEqual(image_processor.size,   {"height": 1_8, "width": 1_8}      )
    self.assertEqual(image_processor.crop_size,   {"height": 1_8, "width": 1_8}      )

    __lowercase								=		self.image_processing_class.from_dict(self.image_processor_dict,   size=4_2,   crop_size=8_4      )
    self.assertEqual(image_processor.size,   {"height": 4_2, "width": 4_2}      )
    self.assertEqual(image_processor.crop_size,   {"height": 8_4, "width": 8_4}      )


 def    _lowercase					(     self				:     Any      ):
    # Initialize image_processing
    __lowercase								=		self.image_processing_class(**self.image_processor_dict      )
    # create random PIL images
    __lowercase								=		prepare_image_inputs(self.image_processor_tester,   equal_resolution=UpperCAmelCase__      )

    for image in image_inputs:
       self.assertIsInstance(UpperCAmelCase__,   Image.Image      )

    # Test not batched input
    __lowercase								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )

    # Test batched
    __lowercase								=		image_processing(UpperCAmelCase__,   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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )


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

    # Test not batched input
    __lowercase								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )

    # Test batched
    __lowercase								=		image_processing(UpperCAmelCase__,   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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )



 def    _lowercase					(     self				:     List[str]      ):
    # Initialize image_processing
    __lowercase								=		self.image_processing_class(**self.image_processor_dict      )
    # create random PyTorch tensors
    __lowercase								=		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
    __lowercase								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )

    # Test batched
    __lowercase								=		image_processing(UpperCAmelCase__,   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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )




