






import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available


if is_torch_available():
							import numpy as np
							import torch

if is_vision_available():
							from PIL import Image
def        a_	( _A ,				_A=False ,				_A=False ,				_A=False					)     ->     Dict:







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

				snake_case__													=       []
				for i in range(image_processor_tester.batch_size					):
								if equal_resolution:
												snake_case__													=       snake_case__													=       image_processor_tester.max_resolution
								else:
												# To avoid getting image width/height 0
												snake_case__													=       image_processor_tester.min_resolution
												if getattr(_A ,				'size_divisor' ,				_A					):
																# If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
																snake_case__													=       max(image_processor_tester.size_divisor ,				_A					)
												snake_case__							,  snake_case__													=       np.random.choice(np.arange(_A ,				image_processor_tester.max_resolution					) ,				2					)
								image_inputs.append(
								    np.random.randint(255 ,				size=(image_processor_tester.num_channels, width, height) ,				dtype=np.uinta					)					)

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

				if torchify:
								snake_case__													=       [torch.from_numpy(_A					) for image in image_inputs]

				return image_inputs
def        a_	( _A ,				_A=10 ,				_A=10 ,				_A=False ,				_A=False					)     ->     str:







				"""simple docstring"""
				snake_case__													=       []
				for i in range(image_processor_tester.num_frames					):
								video.append(np.random.randint(255 ,				size=(image_processor_tester.num_channels, width, height) ,				dtype=np.uinta					)					)

				if not numpify and not torchify:
								# PIL expects the channel dimension as last dimension
								snake_case__													=       [Image.fromarray(np.moveaxis(_A ,				0 ,				-1					)					) for frame in video]

				if torchify:
								snake_case__													=       [torch.from_numpy(_A					) for frame in video]

				return video
def        a_	( _A ,				_A=False ,				_A=False ,				_A=False					)     ->     List[Any]:







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

				snake_case__													=       []
				for i in range(image_processor_tester.batch_size					):
								if equal_resolution:
												snake_case__													=       snake_case__													=       image_processor_tester.max_resolution
								else:
												snake_case__							,  snake_case__													=       np.random.choice(
												    np.arange(image_processor_tester.min_resolution ,				image_processor_tester.max_resolution					) ,				2					)
												snake_case__													=       prepare_video(
												    image_processor_tester=_A ,				width=_A ,				height=_A ,				numpify=_A ,				torchify=_A ,				)
								video_inputs.append(_A					)

				return video_inputs


class 					__SCREAMING_SNAKE_CASE:
							_UpperCAmelCase	      =    None
							def lowerCAmelCase_	(       self: Tuple  )						->						str:
											snake_case__													=       self.image_processing_class(**self.image_processor_dict  )
											snake_case__													=       json.loads(image_processor.to_json_string()  )
											for key, value in self.image_processor_dict.items():
															self.assertEqual(obj[key]    ,		UpperCamelCase  )
							def lowerCAmelCase_	(       self: Union[str, Any]  )						->						Union[str, Any]:
											snake_case__													=       self.image_processing_class(**self.image_processor_dict  )

											with tempfile.TemporaryDirectory() as tmpdirname:
															snake_case__													=       os.path.join(UpperCamelCase    ,		'image_processor.json'  )
															image_processor_first.to_json_file(UpperCamelCase  )
															snake_case__													=       self.image_processing_class.from_json_file(UpperCamelCase  )

											self.assertEqual(image_processor_second.to_dict()    ,		image_processor_first.to_dict()  )
							def lowerCAmelCase_	(       self: Optional[Any]  )						->						int:
											snake_case__													=       self.image_processing_class(**self.image_processor_dict  )

											with tempfile.TemporaryDirectory() as tmpdirname:
															snake_case__													=       image_processor_first.save_pretrained(UpperCamelCase  )[0]
															check_json_file_has_correct_format(UpperCamelCase  )
															snake_case__													=       self.image_processing_class.from_pretrained(UpperCamelCase  )

											self.assertEqual(image_processor_second.to_dict()    ,		image_processor_first.to_dict()  )
							def lowerCAmelCase_	(       self: Optional[int]  )						->						Dict:
											snake_case__													=       self.image_processing_class()
											self.assertIsNotNone(UpperCamelCase  )


							@require_torch
							@require_vision
							def lowerCAmelCase_	(       self: Dict  )						->						List[Any]:
											if self.test_cast_dtype is not None:
															# Initialize image_processor
															snake_case__													=       self.image_processing_class(**self.image_processor_dict  )

															# create random PyTorch tensors
															snake_case__													=       prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=UpperCamelCase    ,		torchify=UpperCamelCase  )

															snake_case__													=       image_processor(UpperCamelCase    ,		return_tensors='pt'  )
															# for layoutLM compatiblity
															self.assertEqual(encoding.pixel_values.device    ,		torch.device('cpu'  )  )
															self.assertEqual(encoding.pixel_values.dtype    ,		torch.floataa  )

															snake_case__													=       image_processor(UpperCamelCase    ,		return_tensors='pt'  ).to(torch.floataa  )
															self.assertEqual(encoding.pixel_values.device    ,		torch.device('cpu'  )  )
															self.assertEqual(encoding.pixel_values.dtype    ,		torch.floataa  )

															snake_case__													=       image_processor(UpperCamelCase    ,		return_tensors='pt'  ).to('cpu'    ,		torch.bfloataa  )
															self.assertEqual(encoding.pixel_values.device    ,		torch.device('cpu'  )  )
															self.assertEqual(encoding.pixel_values.dtype    ,		torch.bfloataa  )

															with self.assertRaises(UpperCamelCase  ):
																			snake_case__													=       image_processor(UpperCamelCase    ,		return_tensors='pt'  ).to(torch.bfloataa    ,		'cpu'  )

															# Try with text + image feature
															snake_case__													=       image_processor(UpperCamelCase    ,		return_tensors='pt'  )
															encoding.update({'input_ids': torch.LongTensor([[1, 2, 3], [4, 5, 6]]  )}  )
															snake_case__													=       encoding.to(torch.floataa  )

															self.assertEqual(encoding.pixel_values.device    ,		torch.device('cpu'  )  )
															self.assertEqual(encoding.pixel_values.dtype    ,		torch.floataa  )
															self.assertEqual(encoding.input_ids.dtype    ,		torch.long  )












from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


__UpperCamelCase   :						int							=  {
    """configuration_openai""": ["""OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OpenAIGPTConfig"""],
    """tokenization_openai""": ["""OpenAIGPTTokenizer"""],
}

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__UpperCamelCase   :						Optional[Any]							=  ["""OpenAIGPTTokenizerFast"""]

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__UpperCamelCase   :						List[str]							=  [
							    """OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """OpenAIGPTDoubleHeadsModel""",
							    """OpenAIGPTForSequenceClassification""",
							    """OpenAIGPTLMHeadModel""",
							    """OpenAIGPTModel""",
							    """OpenAIGPTPreTrainedModel""",
							    """load_tf_weights_in_openai_gpt""",
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__UpperCamelCase   :						Dict							=  [
							    """TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """TFOpenAIGPTDoubleHeadsModel""",
							    """TFOpenAIGPTForSequenceClassification""",
							    """TFOpenAIGPTLMHeadModel""",
							    """TFOpenAIGPTMainLayer""",
							    """TFOpenAIGPTModel""",
							    """TFOpenAIGPTPreTrainedModel""",
							]


if TYPE_CHECKING:
							from .configuration_openai import OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OpenAIGPTConfig
							from .tokenization_openai import OpenAIGPTTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_openai_fast import OpenAIGPTTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_openai import (
														    OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
														    OpenAIGPTDoubleHeadsModel,
														    OpenAIGPTForSequenceClassification,
														    OpenAIGPTLMHeadModel,
														    OpenAIGPTModel,
														    OpenAIGPTPreTrainedModel,
														    load_tf_weights_in_openai_gpt,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_tf_openai import (
														    TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
														    TFOpenAIGPTDoubleHeadsModel,
														    TFOpenAIGPTForSequenceClassification,
														    TFOpenAIGPTLMHeadModel,
														    TFOpenAIGPTMainLayer,
														    TFOpenAIGPTModel,
														    TFOpenAIGPTPreTrainedModel,
														)

else:
							import sys

							__UpperCamelCase   :						List[Any]							=  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




