



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





	@slow
	def 					_lowercase(    self       )     ->     str:
								UpperCAmelCase	:						Optional[int]					=						XLMProphetNetForConditionalGeneration.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased"""       )
								model.to(A       )

								# encoder-decoder outputs
								UpperCAmelCase	:						Tuple					=						torch.tensor([[17, 96208, 103471, 2]]       ).to(A       )
								UpperCAmelCase	:						str					=						torch.tensor(
								    [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]]       ).to(A       )
								UpperCAmelCase	:						Tuple					=						model(
								    input_ids=A						,						attention_mask=A						,						encoder_outputs=A						,						decoder_input_ids=A       )
								UpperCAmelCase	:						Tuple					=						output[0]
								UpperCAmelCase	:						List[Any]					=						torch.Size((1, 14, 250012)       )
								self.assertEqual(output_predited_logis.shape						,						A       )
								UpperCAmelCase	:						Optional[int]					=						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(A       )
								self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]						,						A						,						atol=1e-4       )       )

								# encoder outputs
								UpperCAmelCase	:						List[str]					=						model.prophetnet.encoder(A       )[0]
								UpperCAmelCase	:						Optional[int]					=						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(A       )
								UpperCAmelCase	:						Optional[Any]					=						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
								UpperCAmelCase	:						Optional[Any]					=						model.prophetnet.decoder(
								    A						,						encoder_hidden_states=A						,						)
								UpperCAmelCase	:						str					=						decoder_outputs[1].view(1						,						model.config.ngram						,						14						,						-1       )
								UpperCAmelCase	:						List[str]					=						model.lm_head(A       )
								UpperCAmelCase	:						int					=						predicting_streams_logits[:, 0]
								self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]						,						A						,						atol=1e-4       )       )





	@slow
	def 					_lowercase(    self       )     ->     List[str]:
								UpperCAmelCase	:						Dict					=						XLMProphetNetForConditionalGeneration.from_pretrained(
								    """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""       )
								model.to(A       )

								UpperCAmelCase	:						Optional[int]					=						torch.tensor([[17, 96208, 103471, 2]]       ).to(A       )
								UpperCAmelCase	:						Tuple					=						torch.tensor(
								    [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]]       ).to(A       )
								UpperCAmelCase	:						List[str]					=						model(
								    input_ids=A						,						attention_mask=A						,						encoder_outputs=A						,						decoder_input_ids=A       )
								UpperCAmelCase	:						Dict					=						output[0]
								UpperCAmelCase	:						int					=						torch.Size((1, 14, 250012)       )
								self.assertEqual(output_predited_logis.shape						,						A       )
								# compare the actual values for a slice.
								UpperCAmelCase	:						Any					=						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(A       )

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






	@slow
	def 					_lowercase(    self       )     ->     int:
								UpperCAmelCase	:						Optional[Any]					=						XLMProphetNetForConditionalGeneration.from_pretrained(
								    """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""       )
								model.to(A       )
								UpperCAmelCase	:						List[Any]					=						512

								UpperCAmelCase	:						Any					=						XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""       )

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

								UpperCAmelCase	:						str					=						tokenizer(
								    [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]						,						padding=A						,						max_length=255						,						return_tensors="""pt"""       ).input_ids
								UpperCAmelCase	:						Any					=						input_ids.to(A       )

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

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






'''simple docstring'''




# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

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


a  :     Optional[Any]       =       {
    """agents""": ["""Agent""", """AzureOpenAiAgent""", """HfAgent""", """LocalAgent""", """OpenAiAgent"""],
    """base""": ["""PipelineTool""", """RemoteTool""", """Tool""", """launch_gradio_demo""", """load_tool"""],
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a  :     Dict       =       ["""DocumentQuestionAnsweringTool"""]
							a  :     List[str]       =       ["""ImageCaptioningTool"""]
							a  :     Tuple       =       ["""ImageQuestionAnsweringTool"""]
							a  :     Tuple       =       ["""ImageSegmentationTool"""]
							a  :     List[str]       =       ["""SpeechToTextTool"""]
							a  :     Dict       =       ["""TextClassificationTool"""]
							a  :     Union[str, Any]       =       ["""TextQuestionAnsweringTool"""]
							a  :     List[str]       =       ["""TextSummarizationTool"""]
							a  :     Optional[Any]       =       ["""TextToSpeechTool"""]
							a  :     str       =       ["""TranslationTool"""]

if TYPE_CHECKING:
							from .agents import Agent, AzureOpenAiAgent, HfAgent, LocalAgent, OpenAiAgent
							from .base import PipelineTool, RemoteTool, Tool, launch_gradio_demo, load_tool

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .document_question_answering import DocumentQuestionAnsweringTool
														from .image_captioning import ImageCaptioningTool
														from .image_question_answering import ImageQuestionAnsweringTool
														from .image_segmentation import ImageSegmentationTool
														from .speech_to_text import SpeechToTextTool
														from .text_classification import TextClassificationTool
														from .text_question_answering import TextQuestionAnsweringTool
														from .text_summarization import TextSummarizationTool
														from .text_to_speech import TextToSpeechTool
														from .translation import TranslationTool
else:
							import sys

							a  :     Dict       =       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

