


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      UpperCAmelCase_ ( unittest.TestCase   ):

   '''simple docstring'''




   @slow
   def _snake_case   (		self			):






     """simple docstring"""





     lowerCamelCase			: Dict   =    XLMProphetNetForConditionalGeneration.from_pretrained("microsoft/xprophetnet-large-wiki100-cased"			)
     model.to(_A			)

     # encoder-decoder outputs
     lowerCamelCase			: Optional[int]   =    torch.tensor([[17, 9_6208, 10_3471, 2]]			).to(_A			)
     lowerCamelCase			: Optional[int]   =    torch.tensor(
         [[2, 250, 9953, 34, 6_9489, 1620, 32, 11_8424, 624, 210, 105, 2913, 1032, 351]]			).to(_A			)
     lowerCamelCase			: Union[str, Any]   =    model(
         input_ids=_A						,    attention_mask=_A						,    encoder_outputs=_A						,    decoder_input_ids=_A			)
     lowerCamelCase			: Optional[int]   =    output[0]
     lowerCamelCase			: str   =    torch.Size((1, 14, 25_0012)			)
     self.assertEqual(output_predited_logis.shape						,    _A			)
     lowerCamelCase			: str   =    torch.tensor(
         [[[-6.3986, -8.2391, 12.5189], [-6.3289, -8.0864, 12.6211], [-6.2418, -8.0445, 12.7968]]]			).to(_A			)
     self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]						,    _A						,    atol=1e-4			)			)

     # encoder outputs
     lowerCamelCase			: List[Any]   =    model.prophetnet.encoder(_A			)[0]
     lowerCamelCase			: Tuple   =    torch.tensor(
         [[[-1.4260, -0.7628, 0.8453], [-1.4719, -0.1391, 0.7807], [-1.7678, 0.0114, 0.4646]]]			).to(_A			)
     lowerCamelCase			: Dict   =    torch.Size((1, 4, 1024)			)
     self.assertEqual(encoder_outputs.shape						,    _A			)
     self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]						,    _A						,    atol=1e-4			)			)

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






   @slow
   def _snake_case   (		self			):






     """simple docstring"""





     lowerCamelCase			: Optional[int]   =    XLMProphetNetForConditionalGeneration.from_pretrained(
         "microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"			)
     model.to(_A			)

     lowerCamelCase			: Dict   =    torch.tensor([[17, 9_6208, 10_3471, 2]]			).to(_A			)
     lowerCamelCase			: Optional[Any]   =    torch.tensor(
         [[2, 250, 9953, 34, 6_9489, 1620, 32, 11_8424, 624, 210, 105, 2913, 1032, 351]]			).to(_A			)
     lowerCamelCase			: Dict   =    model(
         input_ids=_A						,    attention_mask=_A						,    encoder_outputs=_A						,    decoder_input_ids=_A			)
     lowerCamelCase			: Union[str, Any]   =    output[0]
     lowerCamelCase			: str   =    torch.Size((1, 14, 25_0012)			)
     self.assertEqual(output_predited_logis.shape						,    _A			)
     # compare the actual values for a slice.
     lowerCamelCase			: Tuple   =    torch.tensor(
         [[[-9.2253, -9.7173, -6.3529], [-7.6701, -9.0145, -1.9382], [-8.0195, -7.0004, -0.1523]]]			).to(_A			)

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






   @slow
   def _snake_case   (		self			):






     """simple docstring"""





     lowerCamelCase			: Optional[int]   =    XLMProphetNetForConditionalGeneration.from_pretrained(
         "microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"			)
     model.to(_A			)
     lowerCamelCase			: Dict   =    512

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

     lowerCamelCase			: Dict   =    (
         '''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.'''
     )
     lowerCamelCase			: Optional[int]   =    (
         '''орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7'''
         ''' после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи'''
         ''' этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми'''
         ''' к кибератакам.'''
     )
     lowerCamelCase			: Optional[int]   =    (
         '''根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。'''
     )

     lowerCamelCase			: List[Any]   =    tokenizer(
         [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]						,    padding=_A						,    max_length=255						,    return_tensors="pt"			).input_ids
     lowerCamelCase			: Tuple   =    input_ids.to(_A			)

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

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







from typing import Optional, Union

from ...file_utils import TensorType
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TruncationStrategy
class      UpperCAmelCase_ ( UpperCamelCase   ):

   '''simple docstring'''




   __A			:				Union[str, Any]							=		"MarkupLMFeatureExtractor"
   __A			:				List[str]							=		("MarkupLMTokenizer", "MarkupLMTokenizerFast")
   __A			:				str							=		True






   def __call__(		self						,    __A=None						,    __A=None						,    __A=None						,    __A=None						,    __A=None						,    __A = True						,    __A = False						,    __A = None						,    __A = None						,    __A = 0						,    __A = None						,    __A = None						,    __A = None						,    __A = False						,    __A = False						,    __A = False						,    __A = False						,    __A = True						,    __A = None						,    **__A						,    ):






     """simple docstring"""





     if self.parse_html:
       if html_strings is None:
         raise ValueError("Make sure to pass HTML strings in case `parse_html` is set to `True`"			)

       if nodes is not None or xpaths is not None or node_labels is not None:
         raise ValueError(
             "Please don't pass nodes, xpaths nor node labels in case `parse_html` is set to `True`"			)

       lowerCamelCase			: Any   =    self.feature_extractor(__A			)
       lowerCamelCase			: Optional[int]   =    features["nodes"]
       lowerCamelCase			: Any   =    features["xpaths"]
     else:
       if html_strings is not None:
         raise ValueError("You have passed HTML strings but `parse_html` is set to `False`."			)
       if nodes is None or xpaths is None:
         raise ValueError("Make sure to pass nodes and xpaths in case `parse_html` is set to `False`"			)

        # # second, apply the tokenizer
     if questions is not None and self.parse_html:
       if isinstance(__A						,    __A			):
         lowerCamelCase			: Tuple   =    [questions]  # add batch dimension (as the feature extractor always adds a batch dimension)

     lowerCamelCase			: Tuple   =    self.tokenizer(
         text=questions if questions is not None else nodes						,    text_pair=nodes if questions is not None else None						,    xpaths=__A						,    node_labels=__A						,    add_special_tokens=__A						,    padding=__A						,    truncation=__A						,    max_length=__A						,    stride=__A						,    pad_to_multiple_of=__A						,    return_token_type_ids=__A						,    return_attention_mask=__A						,    return_overflowing_tokens=__A						,    return_special_tokens_mask=__A						,    return_offsets_mapping=__A						,    return_length=__A						,    verbose=__A						,    return_tensors=__A						,    **__A						,    )

     return encoded_inputs






   def _snake_case   (		self						,    *__A						,    **__A			):






     """simple docstring"""





     return self.tokenizer.batch_decode(*__A						,    **__A			)






   def _snake_case   (		self						,    *__A						,    **__A			):






     """simple docstring"""





     return self.tokenizer.decode(*__A						,    **__A			)






   @property
   def _snake_case   (		self			):






     """simple docstring"""





     lowerCamelCase			: Dict   =    self.tokenizer.model_input_names
     return tokenizer_input_names



