





"""simple docstring"""



import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device


if is_torch_available():
       import torch

       from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer






@require_torch
class 	__snake_case      (	unittest.TestCase  ):





 """simple docstring"""


 @slow
 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		List[str]						=  XLMProphetNetForConditionalGeneration.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased'''						)
     model.to(__lowerCamelCase						)

     # encoder-decoder outputs
     __A					:		str						=  torch.tensor([[17, 9_6208, 10_3471, 2]]						).to(__lowerCamelCase						)
     __A					:		List[Any]						=  torch.tensor(
         [[2, 250, 9953, 34, 6_9489, 1620, 32, 11_8424, 624, 210, 105, 2913, 1032, 351]]						).to(__lowerCamelCase						)
     __A					:		Optional[int]						=  model(
         input_ids=__lowerCamelCase      ,		attention_mask=__lowerCamelCase      ,		encoder_outputs=__lowerCamelCase      ,		decoder_input_ids=__lowerCamelCase						)
     __A					:		int						=  output[0]
     __A					:		Union[str, Any]						=  torch.Size((1, 14, 25_0012)						)
     self.assertEqual(output_predited_logis.shape      ,		__lowerCamelCase						)
     __A					:		Dict						=  torch.tensor(
         [[[-6.3_9_8_6, -8.2_3_9_1, 1_2.5_1_8_9], [-6.3_2_8_9, -8.0_8_6_4, 1_2.6_2_1_1], [-6.2_4_1_8, -8.0_4_4_5, 1_2.7_9_6_8]]]						).to(__lowerCamelCase						)
     self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]      ,		__lowerCamelCase      ,		atol=1e-4						)						)

     # encoder outputs
     __A					:		Optional[int]						=  model.prophetnet.encoder(__lowerCamelCase						)[0]
     __A					:		Any						=  torch.tensor(
         [[[-1.4_2_6_0, -0.7_6_2_8, 0.8_4_5_3], [-1.4_7_1_9, -0.1_3_9_1, 0.7_8_0_7], [-1.7_6_7_8, 0.0_1_1_4, 0.4_6_4_6]]]						).to(__lowerCamelCase						)
     __A					:		List[Any]						=  torch.Size((1, 4, 1024)						)
     self.assertEqual(encoder_outputs.shape      ,		__lowerCamelCase						)
     self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]      ,		__lowerCamelCase      ,		atol=1e-4						)						)

     # decoder outputs
     __A					:		int						=  model.prophetnet.decoder(
         __lowerCamelCase      ,		encoder_hidden_states=__lowerCamelCase      ,		)
     __A					:		Union[str, Any]						=  decoder_outputs[1].view(1      ,		model.config.ngram      ,		14      ,		-1						)
     __A					:		List[str]						=  model.lm_head(__lowerCamelCase						)
     __A					:		Tuple						=  predicting_streams_logits[:, 0]
     self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]      ,		__lowerCamelCase      ,		atol=1e-4						)						)

 @slow
 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		List[Any]						=  XLMProphetNetForConditionalGeneration.from_pretrained(
         '''microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'''						)
     model.to(__lowerCamelCase						)

     __A					:		Optional[int]						=  torch.tensor([[17, 9_6208, 10_3471, 2]]						).to(__lowerCamelCase						)
     __A					:		int						=  torch.tensor(
         [[2, 250, 9953, 34, 6_9489, 1620, 32, 11_8424, 624, 210, 105, 2913, 1032, 351]]						).to(__lowerCamelCase						)
     __A					:		List[Any]						=  model(
         input_ids=__lowerCamelCase      ,		attention_mask=__lowerCamelCase      ,		encoder_outputs=__lowerCamelCase      ,		decoder_input_ids=__lowerCamelCase						)
     __A					:		List[str]						=  output[0]
     __A					:		Optional[Any]						=  torch.Size((1, 14, 25_0012)						)
     self.assertEqual(output_predited_logis.shape      ,		__lowerCamelCase						)
     # compare the actual values for a slice.
     __A					:		Dict						=  torch.tensor(
         [[[-9.2_2_5_3, -9.7_1_7_3, -6.3_5_2_9], [-7.6_7_0_1, -9.0_1_4_5, -1.9_3_8_2], [-8.0_1_9_5, -7.0_0_0_4, -0.1_5_2_3]]]						).to(__lowerCamelCase						)

     self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]      ,		__lowerCamelCase      ,		atol=1e-4						)						)







 @slow
 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		Any						=  XLMProphetNetForConditionalGeneration.from_pretrained(
         '''microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'''						)
     model.to(__lowerCamelCase						)
     __A					:		Dict						=  512

     __A					:		Optional[Any]						=  XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'''						)

     __A					:		List[Any]						=  (
         '''Microsoft Corporation intends to officially end free support for the Windows 7 operating system after'''
         ''' January 14, 2020, according to the official portal of the organization. From that day, users of this'''
         ''' system will not be able to receive security updates, which could make their computers vulnerable to'''
         ''' cyber attacks.'''
     )
     __A					:		Optional[int]						=  (
         '''орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7'''
         ''' после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи'''
         ''' этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми'''
         ''' к кибератакам.'''
     )
     __A					:		Dict						=  (
         '''根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。'''
     )

     __A					:		Dict						=  tokenizer(
         [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]      ,		padding=__lowerCamelCase      ,		max_length=255      ,		return_tensors='''pt'''						).input_ids
     __A					:		Any						=  input_ids.to(__lowerCamelCase						)

     __A					:		Optional[Any]						=  model.generate(
         __lowerCamelCase      ,		num_beams=10      ,		length_penalty=1.0      ,		no_repeat_ngram_size=3      ,		early_stopping=__lowerCamelCase						)
     __A					:		Optional[int]						=  [tokenizer.decode(__lowerCamelCase      ,		skip_special_tokens=__lowerCamelCase						) for g in summary_ids]
     __A					:		Optional[Any]						=  '''Microsoft to end Windows 7 free support after January 14, 2020'''
     __A					:		Optional[Any]						=  '''Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года'''
     __A					:		Optional[int]						=  '''微软打算终止对Windows 7操作系统的免费支持'''
     self.assertListEqual(
         [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]      ,		__lowerCamelCase      ,		)

     __A					:		Optional[int]						=  model.generate(
         __lowerCamelCase      ,		num_beams=1      ,		length_penalty=1.0      ,		no_repeat_ngram_size=3      ,		early_stopping=__lowerCamelCase						)
     __A					:		Optional[Any]						=  [
         tokenizer.convert_ids_to_tokens(__lowerCamelCase      ,		skip_special_tokens=__lowerCamelCase						) for g in summary_ids_beama
     ]
     __A					:		int						=  '''▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7'''.split(''' '''						)
     __A					:		Optional[Any]						=  '''▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года'''.split(
         ''' '''						)
     __A					:		int						=  '''微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持'''.split(''' '''						)
     self.assertListEqual(
         [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]      ,		__lowerCamelCase      ,		)











"""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_video_inputs


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import VideoMAEImageProcessor






class 	__snake_case      (	unittest.TestCase  ):





 """simple docstring"""


 def __init__(					self      ,		__lowerCamelCase      ,		__lowerCamelCase=7      ,		__lowerCamelCase=3      ,		__lowerCamelCase=10      ,		__lowerCamelCase=18      ,		__lowerCamelCase=30      ,		__lowerCamelCase=400      ,		__lowerCamelCase=True      ,		__lowerCamelCase=None      ,		__lowerCamelCase=True      ,		__lowerCamelCase=[0.5, 0.5, 0.5]      ,		__lowerCamelCase=[0.5, 0.5, 0.5]      ,		__lowerCamelCase=None      ,		):



     '''simple docstring'''




     __A					:		Optional[Any]						=  size if size is not None else {'''shortest_edge''': 18}
     __A					:		Optional[int]						=  crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

     __A					:		Any						=  parent
     __A					:		Union[str, Any]						=  batch_size
     __A					:		Optional[int]						=  num_channels
     __A					:		int						=  num_frames
     __A					:		Optional[int]						=  image_size
     __A					:		Union[str, Any]						=  min_resolution
     __A					:		int						=  max_resolution
     __A					:		Tuple						=  do_resize
     __A					:		str						=  size
     __A					:		Any						=  do_normalize
     __A					:		Union[str, Any]						=  image_mean
     __A					:		List[str]						=  image_std
     __A					:		Union[str, Any]						=  crop_size







 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     return {
         "image_mean": self.image_mean,
         "image_std": self.image_std,
         "do_normalize": self.do_normalize,
         "do_resize": self.do_resize,
         "size": self.size,
         "crop_size": self.crop_size,
     }






@require_torch
@require_vision
class 	__snake_case      (	SCREAMING_SNAKE_CASE__							,							unittest.TestCase  ):





 """simple docstring"""


 _lowerCamelCase				 =  VideoMAEImageProcessor if is_vision_available() else None

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		List[str]						=  VideoMAEImageProcessingTester(self						)

 @property
 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     return self.image_processor_tester.prepare_image_processor_dict()

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		Dict						=  self.image_processing_class(**self.image_processor_dict						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''image_mean'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''image_std'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''do_normalize'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''do_resize'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''do_center_crop'''						)						)
     self.assertTrue(hasattr(__lowerCamelCase      ,		'''size'''						)						)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		Optional[int]						=  self.image_processing_class.from_dict(self.image_processor_dict						)
     self.assertEqual(image_processor.size      ,		{'''shortest_edge''': 18}						)
     self.assertEqual(image_processor.crop_size      ,		{'''height''': 18, '''width''': 18}						)

     __A					:		Dict						=  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						):



     '''simple docstring'''




     pass

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		List[Any]						=  self.image_processing_class(**self.image_processor_dict						)
     # create random PIL videos
     __A					:		Optional[int]						=  prepare_video_inputs(self.image_processor_tester      ,		equal_resolution=__lowerCamelCase						)
     for video in video_inputs:
         self.assertIsInstance(__lowerCamelCase      ,		__lowerCamelCase						)
         self.assertIsInstance(video[0]      ,		Image.Image						)

     # Test not batched input
     __A					:		Any						=  image_processing(video_inputs[0]      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             1,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)

     # Test batched
     __A					:		int						=  image_processing(__lowerCamelCase      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)

 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		List[Any]						=  self.image_processing_class(**self.image_processor_dict						)
     # create random numpy tensors
     __A					:		List[str]						=  prepare_video_inputs(self.image_processor_tester      ,		equal_resolution=__lowerCamelCase      ,		numpify=__lowerCamelCase						)
     for video in video_inputs:
         self.assertIsInstance(__lowerCamelCase      ,		__lowerCamelCase						)
         self.assertIsInstance(video[0]      ,		np.ndarray						)

     # Test not batched input
     __A					:		List[str]						=  image_processing(video_inputs[0]      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             1,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)

     # Test batched
     __A					:		int						=  image_processing(__lowerCamelCase      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)







 def       UpperCamelCase__(					self						):



     '''simple docstring'''




     __A					:		Optional[int]						=  self.image_processing_class(**self.image_processor_dict						)
     # create random PyTorch tensors
     __A					:		int						=  prepare_video_inputs(self.image_processor_tester      ,		equal_resolution=__lowerCamelCase      ,		torchify=__lowerCamelCase						)
     for video in video_inputs:
         self.assertIsInstance(__lowerCamelCase      ,		__lowerCamelCase						)
         self.assertIsInstance(video[0]      ,		torch.Tensor						)

     # Test not batched input
     __A					:		Optional[int]						=  image_processing(video_inputs[0]      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             1,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)

     # Test batched
     __A					:		str						=  image_processing(__lowerCamelCase      ,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_videos.shape      ,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_frames,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         )      ,		)




