
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 ChineseCLIPImageProcessor





class      lowercase__    (							unittest.TestCase  ):







  def __init__(	self    ,						_lowercase    ,						_lowercase=7    ,						_lowercase=3    ,						_lowercase=18    ,						_lowercase=30    ,						_lowercase=400    ,						_lowercase=True    ,						_lowercase=None    ,						_lowercase=True    ,						_lowercase=None    ,						_lowercase=True    ,						_lowercase=[0.4814_5466, 0.457_8275, 0.4082_1073]    ,						_lowercase=[0.2686_2954, 0.2613_0258, 0.2757_7711]    ,						_lowercase=True    ,						):
       lowerCAmelCase_					:       Optional[int]    =		size if size is not None else {"""height""": 224, """width""": 224}
       lowerCAmelCase_					:       int    =		crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
       lowerCAmelCase_					:       Optional[Any]    =		parent
       lowerCAmelCase_					:       Tuple    =		batch_size
       lowerCAmelCase_					:       Optional[Any]    =		num_channels
       lowerCAmelCase_					:       List[Any]    =		image_size
       lowerCAmelCase_					:       str    =		min_resolution
       lowerCAmelCase_					:       str    =		max_resolution
       lowerCAmelCase_					:       Optional[Any]    =		do_resize
       lowerCAmelCase_					:       Tuple    =		size
       lowerCAmelCase_					:       Any    =		do_center_crop
       lowerCAmelCase_					:       Dict    =		crop_size
       lowerCAmelCase_					:       Tuple    =		do_normalize
       lowerCAmelCase_					:       Optional[Any]    =		image_mean
       lowerCAmelCase_					:       Optional[Any]    =		image_std
       lowerCAmelCase_					:       Dict    =		do_convert_rgb







  def 	UpperCAmelCase__		(	self						):
       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,
       }







  def 	UpperCAmelCase__		(	self    ,						_lowercase=False    ,						_lowercase=False    ,						_lowercase=False						):
       assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

       if equal_resolution:
            lowerCAmelCase_					:       str    =		[]
            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_					:       Optional[int]    =		[]
            for i in range(self.batch_size						):
                 lowerCAmelCase_					:       List[Any]    =		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_					:       Tuple    =		[Image.fromarray(np.moveaxis(_lowercase    ,						0    ,						-1						)						) for x in image_inputs]

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

       return image_inputs





@require_torch
@require_vision
class      lowercase__    (							__A     ,					unittest.TestCase  ):
  __UpperCamelCase	     =  ChineseCLIPImageProcessor if is_vision_available() else None







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[Any]    =		ChineseCLIPImageProcessingTester(self    ,						do_center_crop=_lowercase						)







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







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







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[Any]    =		self.image_processing_class.from_dict(self.image_processor_dict						)
       self.assertEqual(image_processor.size    ,						{"""height""": 224, """width""": 224}						)
       self.assertEqual(image_processor.crop_size    ,						{"""height""": 18, """width""": 18}						)

       lowerCAmelCase_					:       Tuple    =		self.image_processing_class.from_dict(self.image_processor_dict    ,						size=42    ,						crop_size=84						)
       self.assertEqual(image_processor.size    ,						{"""shortest_edge""": 42}						)
       self.assertEqual(image_processor.crop_size    ,						{"""height""": 84, """width""": 84}						)







  def 	UpperCAmelCase__		(	self						):
       pass







  def 	UpperCAmelCase__		(	self						):
       # Initialize image_processing
       lowerCAmelCase_					:       int    =		self.image_processing_class(**self.image_processor_dict						)
       # create random PIL images
       lowerCAmelCase_					:       List[Any]    =		self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase						)
       for image in image_inputs:
            self.assertIsInstance(_lowercase    ,						Image.Image						)

       # Test not batched input
       lowerCAmelCase_					:       List[str]    =		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
       lowerCAmelCase_					:       Tuple    =		image_processing(_lowercase    ,						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 	UpperCAmelCase__		(	self						):
       # Initialize image_processing
       lowerCAmelCase_					:       Dict    =		self.image_processing_class(**self.image_processor_dict						)
       # create random numpy tensors
       lowerCAmelCase_					:       Tuple    =		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_					:       Optional[int]    =		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
       lowerCAmelCase_					:       int    =		image_processing(_lowercase    ,						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 	UpperCAmelCase__		(	self						):
       # Initialize image_processing
       lowerCAmelCase_					:       Optional[Any]    =		self.image_processing_class(**self.image_processor_dict						)
       # create random PyTorch tensors
       lowerCAmelCase_					:       Any    =		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_					:       Dict    =		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
       lowerCAmelCase_					:       Dict    =		image_processing(_lowercase    ,						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"""],
           )    ,						)





@require_torch
@require_vision
class      lowercase__    (							__A     ,					unittest.TestCase  ):
  __UpperCamelCase	     =  ChineseCLIPImageProcessor if is_vision_available() else None







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       int    =		ChineseCLIPImageProcessingTester(self    ,						num_channels=4    ,						do_center_crop=_lowercase						)
       lowerCAmelCase_					:       Optional[Any]    =		3







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







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







  def 	UpperCAmelCase__		(	self						):
       pass







  def 	UpperCAmelCase__		(	self						):
       # Initialize image_processing
       lowerCAmelCase_					:       Optional[int]    =		self.image_processing_class(**self.image_processor_dict						)
       # create random PIL images
       lowerCAmelCase_					:       int    =		self.image_processor_tester.prepare_inputs(equal_resolution=_lowercase						)
       for image in image_inputs:
            self.assertIsInstance(_lowercase    ,						Image.Image						)

       # Test not batched input
       lowerCAmelCase_					:       List[Any]    =		image_processing(image_inputs[0]    ,						return_tensors="""pt"""						).pixel_values
       self.assertEqual(
           encoded_images.shape    ,						(
               1,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )    ,						)

       # Test batched
       lowerCAmelCase_					:       Any    =		image_processing(_lowercase    ,						return_tensors="""pt"""						).pixel_values
       self.assertEqual(
           encoded_images.shape    ,						(
               self.image_processor_tester.batch_size,
               self.expected_encoded_image_num_channels,
               self.image_processor_tester.crop_size["""height"""],
               self.image_processor_tester.crop_size["""width"""],
           )    ,						)







import enum
import os
from hashlib import shaaaa
from typing import Optional

from .. import config
from .logging import get_logger


UpperCAmelCase_					:   int 							=						get_logger(__name__)





class      lowercase__    (							enum.Enum  ):
  __UpperCamelCase	     =  """all_checks"""
  __UpperCamelCase	     =  """basic_checks"""
  __UpperCamelCase	     =  """no_checks"""





class      lowercase__    (							__A  ):
  pass





class      lowercase__    (							__A  ):
  pass





class      lowercase__    (							__A  ):
  pass





class      lowercase__    (							__A  ):
  pass






def 							_lowerCAmelCase (  _a   :					Optional[dict]					,   _a   :					dict					,   _a   :					str=None			)	->			Optional[Any]:
     if expected_checksums is None:
          logger.info("""Unable to verify checksums."""			)
          return
     if len(set(_a			) - set(_a			)			) > 0:
          raise ExpectedMoreDownloadedFiles(str(set(_a			) - set(_a			)			)			)
     if len(set(_a			) - set(_a			)			) > 0:
          raise UnexpectedDownloadedFile(str(set(_a			) - set(_a			)			)			)
     lowerCAmelCase_					:       Union[str, Any]    =		[url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]]
     lowerCAmelCase_					:       Optional[Any]    =		""" for """ + verification_name if verification_name is not None else """"""
     if len(_a			) > 0:
          raise NonMatchingChecksumError(
              F'Checksums didn\'t match{for_verification_name}:\n'
              F'{bad_urls}\n'
              """Set `verification_mode='no_checks'` to skip checksums verification and ignore this error"""			)
     logger.info("""All the checksums matched successfully""" + for_verification_name			)





class      lowercase__    (							__A  ):
  pass





class      lowercase__    (							__A  ):
  pass





class      lowercase__    (							__A  ):
  pass





class      lowercase__    (							__A  ):
  pass






def 							_lowerCAmelCase (  _a   :					Optional[dict]					,   _a   :					dict			)	->			str:
     if expected_splits is None:
          logger.info("""Unable to verify splits sizes."""			)
          return
     if len(set(_a			) - set(_a			)			) > 0:
          raise ExpectedMoreSplits(str(set(_a			) - set(_a			)			)			)
     if len(set(_a			) - set(_a			)			) > 0:
          raise UnexpectedSplits(str(set(_a			) - set(_a			)			)			)
     lowerCAmelCase_					:       Optional[int]    =		[
         {"""expected""": expected_splits[name], """recorded""": recorded_splits[name]}
         for name in expected_splits
         if expected_splits[name].num_examples != recorded_splits[name].num_examples
     ]
     if len(_a			) > 0:
          raise NonMatchingSplitsSizesError(str(_a			)			)
     logger.info("""All the splits matched successfully."""			)






def 							_lowerCAmelCase (  _a   :					str					,   _a   :					bool = True			)	->			dict:
     if record_checksum:
          lowerCAmelCase_					:       int    =		shaaaa()
          with open(_a					,   """rb"""			) as f:
               for chunk in iter(lambda: f.read(1 << 20			)					,   B""""""			):
                    m.update(_a			)
               lowerCAmelCase_					:       List[str]    =		m.hexdigest()
     else:
          lowerCAmelCase_					:       Union[str, Any]    =		None
     return {"num_bytes": os.path.getsize(_a			), "checksum": checksum}







def 							_lowerCAmelCase (  _a   :					Tuple			)	->			Optional[int]:
     if dataset_size and config.IN_MEMORY_MAX_SIZE:
          return dataset_size < config.IN_MEMORY_MAX_SIZE
     else:
          return False
