


"""simple docstring"""





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   _snake_case    (    _snake_case					:      Dict			, _snake_case					:      Dict=False			, _snake_case					:      Optional[Any]=False			, _snake_case					:      Tuple=False      ):
      assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

      lowerCAmelCase       :						Dict							= []
      for i in range(image_processor_tester.batch_size      ):
            if equal_resolution:
                  lowerCAmelCase       :						Tuple							= image_processor_tester.max_resolution
            else:
                  # To avoid getting image width/height 0
                  lowerCAmelCase       :						Optional[Any]							= image_processor_tester.min_resolution
                  if getattr(_snake_case			, '''size_divisor'''			, _snake_case      ):
                        # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
                        lowerCAmelCase       :						Any							= max(image_processor_tester.size_divisor			, _snake_case      )
                  lowerCAmelCase,   lowerCAmelCase       :						str							= np.random.choice(np.arange(_snake_case			, 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
            lowerCAmelCase       :						List[Any]							= [Image.fromarray(np.moveaxis(_snake_case			, 0			, -1      )      ) for image in image_inputs]

      if torchify:
            lowerCAmelCase       :						Optional[Any]							= [torch.from_numpy(_snake_case      ) for image in image_inputs]

      return image_inputs


def   _snake_case    (    _snake_case					:      int			, _snake_case					:      Optional[int]=10			, _snake_case					:      Optional[Any]=10			, _snake_case					:      List[str]=False			, _snake_case					:      str=False      ):
      lowerCAmelCase       :						Optional[int]							= []
      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
            lowerCAmelCase       :						Tuple							= [Image.fromarray(np.moveaxis(_snake_case			, 0			, -1      )      ) for frame in video]

      if torchify:
            lowerCAmelCase       :						Optional[Any]							= [torch.from_numpy(_snake_case      ) for frame in video]

      return video


def   _snake_case    (    _snake_case					:      Optional[Any]			, _snake_case					:      Optional[int]=False			, _snake_case					:      str=False			, _snake_case					:      str=False      ):
      assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

      lowerCAmelCase       :						int							= []
      for i in range(image_processor_tester.batch_size      ):
            if equal_resolution:
                  lowerCAmelCase       :						Tuple							= image_processor_tester.max_resolution
            else:
                  lowerCAmelCase,   lowerCAmelCase       :						List[Any]							= np.random.choice(
                      np.arange(image_processor_tester.min_resolution			, image_processor_tester.max_resolution      )			, 2      )
                  lowerCAmelCase       :						Any							= prepare_video(
                      image_processor_tester=_snake_case			, width=_snake_case			, height=_snake_case			, numpify=_snake_case			, torchify=_snake_case			, )
            video_inputs.append(_snake_case      )

      return video_inputs






class 		snake_case_:
     __UpperCamelCase	=       None






     def   lowerCamelCase__  (						self	:       Any					):
           lowerCAmelCase       :						Union[str, Any]							= self.image_processing_class(**self.image_processor_dict					)
           lowerCAmelCase       :						List[Any]							= json.loads(image_processor.to_json_string()					)
           for key, value in self.image_processor_dict.items():
                 self.assertEqual(obj[key]       ,					UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       str					):
           lowerCAmelCase       :						int							= self.image_processing_class(**self.image_processor_dict					)

           with tempfile.TemporaryDirectory() as tmpdirname:
                 lowerCAmelCase       :						Optional[Any]							= os.path.join(UpperCamelCase_       ,					'''image_processor.json'''					)
                 image_processor_first.to_json_file(UpperCamelCase_					)
                 lowerCAmelCase       :						Any							= self.image_processing_class.from_json_file(UpperCamelCase_					)

           self.assertEqual(image_processor_second.to_dict()       ,					image_processor_first.to_dict()					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						Optional[int]							= self.image_processing_class(**self.image_processor_dict					)

           with tempfile.TemporaryDirectory() as tmpdirname:
                 lowerCAmelCase       :						List[str]							= image_processor_first.save_pretrained(UpperCamelCase_					)[0]
                 check_json_file_has_correct_format(UpperCamelCase_					)
                 lowerCAmelCase       :						Any							= self.image_processing_class.from_pretrained(UpperCamelCase_					)

           self.assertEqual(image_processor_second.to_dict()       ,					image_processor_first.to_dict()					)






     def   lowerCamelCase__  (						self	:       Optional[int]					):
           lowerCAmelCase       :						List[str]							= self.image_processing_class()
           self.assertIsNotNone(UpperCamelCase_					)






     @require_torch
     @require_vision
     def   lowerCamelCase__  (						self	:       Dict					):
           if self.test_cast_dtype is not None:
                 # Initialize image_processor
                 lowerCAmelCase       :						Any							= self.image_processing_class(**self.image_processor_dict					)

                 # create random PyTorch tensors
                 lowerCAmelCase       :						List[Any]							= prepare_image_inputs(self.image_processor_tester       ,					equal_resolution=UpperCamelCase_       ,					torchify=UpperCamelCase_					)

                 lowerCAmelCase       :						str							= 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					)

                 lowerCAmelCase       :						Optional[int]							= 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					)

                 lowerCAmelCase       :						List[Any]							= 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_					):
                       lowerCAmelCase       :						Union[str, Any]							= image_processor(UpperCamelCase_       ,					return_tensors='''pt'''					).to(torch.bfloataa       ,					'''cpu'''					)

                 # Try with text + image feature
                 lowerCAmelCase       :						Union[str, Any]							= image_processor(UpperCamelCase_       ,					return_tensors='''pt'''					)
                 encoding.update({'''input_ids''': torch.LongTensor([[1, 2, 3], [4, 5, 6]]					)}					)
                 lowerCAmelCase       :						str							= 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					)






"""simple docstring"""





from typing import Callable, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case__		:  Optional[Any]     					=					logging.get_logger(__name__)

snake_case__		:  str     					=					{
    '''microsoft/prophetnet-large-uncased''': (
        '''https://huggingface.co/microsoft/prophetnet-large-uncased/resolve/main/config.json'''
    ),
}



class 		snake_case_(							a__      ):
     __UpperCamelCase	=       '''prophetnet'''
     __UpperCamelCase	=       ['''past_key_values''']
     __UpperCamelCase	=       {
         '''num_attention_heads''': '''num_encoder_attention_heads''',
     }






     def __init__(						self	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[float] = 0.1       ,					UpperCamelCase_	:       Optional[Union[str, Callable]] = "gelu"       ,					UpperCamelCase_	:       Optional[int] = 3_0_5_2_2       ,					UpperCamelCase_	:       Optional[int] = 1_0_2_4       ,					UpperCamelCase_	:       Optional[int] = 4_0_9_6       ,					UpperCamelCase_	:       Optional[int] = 1_2       ,					UpperCamelCase_	:       Optional[int] = 1_6       ,					UpperCamelCase_	:       Optional[int] = 4_0_9_6       ,					UpperCamelCase_	:       Optional[int] = 1_2       ,					UpperCamelCase_	:       Optional[int] = 1_6       ,					UpperCamelCase_	:       Optional[float] = 0.1       ,					UpperCamelCase_	:       Optional[float] = 0.1       ,					UpperCamelCase_	:       Optional[int] = 5_1_2       ,					UpperCamelCase_	:       Optional[float] = 0.02       ,					UpperCamelCase_	:       Optional[bool] = True       ,					UpperCamelCase_	:       Optional[bool] = True       ,					UpperCamelCase_	:       Optional[int] = 0       ,					UpperCamelCase_	:       Optional[int] = 2       ,					UpperCamelCase_	:       Optional[int] = 3_2       ,					UpperCamelCase_	:       Optional[int] = 1_2_8       ,					UpperCamelCase_	:       Optional[bool] = False       ,					UpperCamelCase_	:       Optional[float] = 0.0       ,					UpperCamelCase_	:       Optional[bool] = True       ,					UpperCamelCase_	:       Optional[int] = 0       ,					UpperCamelCase_	:       Optional[int] = 1       ,					UpperCamelCase_	:       Optional[int] = 2       ,					**UpperCamelCase_	:       List[Any]       ,					):
           lowerCAmelCase       :						Union[str, Any]							= vocab_size
           lowerCAmelCase       :						Any							= hidden_size
           lowerCAmelCase       :						Tuple							= encoder_ffn_dim
           lowerCAmelCase       :						str							= num_encoder_layers
           lowerCAmelCase       :						int							= num_encoder_attention_heads
           lowerCAmelCase       :						Optional[Any]							= decoder_ffn_dim
           lowerCAmelCase       :						Union[str, Any]							= num_decoder_layers
           lowerCAmelCase       :						Union[str, Any]							= num_decoder_attention_heads
           lowerCAmelCase       :						List[Any]							= max_position_embeddings
           lowerCAmelCase       :						Dict							= init_std  # Normal(0, this parameter)
           lowerCAmelCase       :						Optional[int]							= activation_function

           # parameters for prophetnet
           lowerCAmelCase       :						Tuple							= ngram
           lowerCAmelCase       :						List[Any]							= num_buckets
           lowerCAmelCase       :						Optional[Any]							= relative_max_distance
           lowerCAmelCase       :						Dict							= disable_ngram_loss
           lowerCAmelCase       :						Optional[int]							= eps

           # 3 Types of Dropout
           lowerCAmelCase       :						Any							= attention_dropout
           lowerCAmelCase       :						List[Any]							= activation_dropout
           lowerCAmelCase       :						Tuple							= dropout

           lowerCAmelCase       :						Optional[int]							= use_cache

           super().__init__(
               pad_token_id=UpperCamelCase_       ,					bos_token_id=UpperCamelCase_       ,					eos_token_id=UpperCamelCase_       ,					is_encoder_decoder=UpperCamelCase_       ,					add_cross_attention=UpperCamelCase_       ,					decoder_start_token_id=UpperCamelCase_       ,					**UpperCamelCase_       ,					)






     @property
     def   lowerCamelCase__  (						self	:       str					):
           return self.num_encoder_layers + self.num_decoder_layers






     @num_hidden_layers.setter
     def   lowerCamelCase__  (						self	:       Optional[Any]       ,					UpperCamelCase_	:       int					):
           raise NotImplementedError(
               '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and'''
               ''' `num_decoder_layers`.'''					)


