




import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    SummarizationPipeline,
    TFPreTrainedModel,
    pipeline,
)
from transformers.testing_utils import get_gpu_count, is_pipeline_test, require_tf, require_torch, slow, torch_device
from transformers.tokenization_utils import TruncationStrategy

from .test_pipelines_common import ANY


lowercase__    :					Optional[Any]					=						-1 if torch_device == "cpu" else 0
@is_pipeline_test
class 		UpperCAmelCase       (    unittest.TestCase      ):







						'''simple docstring'''





						lowerCAmelCase_							=       MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
						lowerCAmelCase_							=       TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING






						def 	snake_case__						(						self							:					Optional[int]	,     __lowercase							:					Dict	,     __lowercase							:					List[str]	,     __lowercase							:					Tuple						):






							"""simple docstring"""






							snake_case_		   =					SummarizationPipeline(model=__lowercase	,     tokenizer=__lowercase						)
							return summarizer, ["(CNN)The Palestinian Authority officially became", "Some other text"]






						def 	snake_case__						(						self							:					Any	,     __lowercase							:					List[str]	,     __lowercase							:					List[str]						):






							"""simple docstring"""






							snake_case_		   =					summarizer.model

							snake_case_		   =					summarizer("(CNN)The Palestinian Authority officially became"						)
							self.assertEqual(__lowercase	,     [{"summary_text": ANY(__lowercase						)}]						)

							snake_case_		   =					summarizer(
							    "(CNN)The Palestinian Authority officially became "	,     num_beams=2	,     min_length=2	,     max_length=5	,     )
							self.assertEqual(__lowercase	,     [{"summary_text": ANY(__lowercase						)}]						)

							# Some models (Switch Transformers, LED, T5, LongT5, etc) can handle long sequences.
							snake_case_		   =					[
							    "SwitchTransformersConfig",
							    "T5Config",
							    "LongT5Config",
							    "LEDConfig",
							    "PegasusXConfig",
							    "FSMTConfig",
							    "M2M100Config",
							    "ProphetNetConfig",  # positional embeddings up to a fixed maximum size (otherwise clamping the values)
							]
							if model.config.__class__.__name__ not in model_can_handle_longer_seq:
								# Too long and exception is expected.
								# For TF models, if the weights are initialized in GPU context, we won't get expected index error from
								# the embedding layer.
								if not (
								    isinstance(__lowercase	,     __lowercase						)
								    and get_gpu_count() > 0
								    and len(summarizer.model.trainable_weights						) > 0
								):
									with self.assertRaises(__lowercase						):
										snake_case_		   =					summarizer("This " * 10_00						)
							snake_case_		   =					summarizer("This " * 10_00	,     truncation=TruncationStrategy.ONLY_FIRST						)






						@require_torch
						def 	snake_case__						(						self							:					Optional[Any]						):






							"""simple docstring"""






							snake_case_		   =					pipeline(task="summarization"	,     model="sshleifer/tiny-mbart"	,     framework="pt"						)
							snake_case_		   =					summarizer("This is a small test"						)
							self.assertEqual(
							    __lowercase	,     [
							        {
							            "summary_text": "เข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไป"
							        }
							    ]	,     )






						@require_tf
						def 	snake_case__						(						self							:					List[str]						):






							"""simple docstring"""






							snake_case_		   =					pipeline(task="summarization"	,     model="sshleifer/tiny-mbart"	,     framework="tf"						)
							snake_case_		   =					summarizer("This is a small test"						)
							self.assertEqual(
							    __lowercase	,     [
							        {
							            "summary_text": "เข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไป"
							        }
							    ]	,     )






						@require_torch
						@slow
						def 	snake_case__						(						self							:					Optional[Any]						):






							"""simple docstring"""






							snake_case_		   =					pipeline(task="summarization"	,     device=__lowercase						)
							snake_case_		   =					(
							    " (CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
							    " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The"
							    " formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based."
							    " The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its"
							    " jurisdiction over alleged crimes committed \"in the occupied Palestinian territory, including East"
							    " Jerusalem, since June 13, 2014.\" Later that month, the ICC opened a preliminary examination into the"
							    " situation in Palestinian territories, paving the way for possible war crimes investigations against"
							    " Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and"
							    " the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the"
							    " body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony, said it was a"
							    " move toward greater justice. \"As Palestine formally becomes a State Party to the Rome Statute today, the"
							    " world is also a step closer to ending a long era of impunity and injustice,\" he said, according to an"
							    " ICC news release. \"Indeed, today brings us closer to our shared goals of justice and peace.\" Judge"
							    " Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the"
							    " Palestinians. \"As the Rome Statute today enters into force for the State of Palestine, Palestine"
							    " acquires all the rights as well as responsibilities that come with being a State Party to the Statute."
							    " These are substantive commitments, which cannot be taken lightly,\" she said. Rights group Human Rights"
							    " Watch welcomed the development. \"Governments seeking to penalize Palestine for joining the ICC should"
							    " immediately end their pressure, and countries that support universal acceptance of the court's treaty"
							    " should speak out to welcome its membership,\" said Balkees Jarrah, international justice counsel for the"
							    " group. \"What's objectionable is the attempts to undermine international justice, not Palestine's"
							    " decision to join a treaty to which over 100 countries around the world are members.\" In January, when"
							    " the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an"
							    " outrage, saying the court was overstepping its boundaries. The United States also said it \"strongly\""
							    " disagreed with the court's decision. \"As we have said repeatedly, we do not believe that Palestine is a"
							    " state and therefore we do not believe that it is eligible to join the ICC,\" the State Department said in"
							    " a statement. It urged the warring sides to resolve their differences through direct negotiations. \"We"
							    " will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,\""
							    " it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the"
							    " territories as \"Palestine.\" While a preliminary examination is not a formal investigation, it allows the"
							    " court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou"
							    " Bensouda said her office would \"conduct its analysis in full independence and impartiality.\" The war"
							    " between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry"
							    " will include alleged war crimes committed since June. The International Criminal Court was set up in"
							    " 2002 to prosecute genocide, crimes against humanity and war crimes. CNN's Vasco Cotovio, Kareem Khadder"
							    " and Faith Karimi contributed to this report."
							)
							snake_case_		   =					(
							    " The Palestinian Authority becomes the 123rd member of the International Criminal Court . The move gives"
							    " the court jurisdiction over alleged crimes in Palestinian territories . Israel and the United States"
							    " opposed the Palestinians' efforts to join the court . Rights group Human Rights Watch welcomes the move,"
							    " says governments seeking to penalize Palestine should end pressure ."
							)
							snake_case_		   =					summarizer(__lowercase						)
							self.assertEqual(result[0]["summary_text"]	,     __lowercase						)






import json
import os
import re
import unicodedata
from typing import Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
from ...utils import logging


lowercase__    :					List[str]					=						logging.get_logger(__name__)

lowercase__    :					Tuple					=						{
    "vocab_file": "vocab.json",
    "merges_file": "merges.txt",
}

lowercase__    :					Any					=						{
    "vocab_file": {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/vocab.json"},
    "merges_file": {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/merges.txt"},
}

lowercase__    :					Tuple					=						{
    "openai-gpt": 512,
}


def 						lowerCamelCase__   (		_A							):







	'''simple docstring'''





	snake_case_		   =					text.strip()
	if not text:
		return []
	snake_case_		   =					text.split()
	return tokens
class 		UpperCAmelCase       (    UpperCAmelCase__      ):







						'''simple docstring'''





						def __init__(						self							:					Dict	,     __lowercase							:					str=True	,     __lowercase							:					Union[str, Any]=None	,     __lowercase							:					str=True	,     __lowercase							:					Dict=None	,     __lowercase							:					str=True	,     ):






							"""simple docstring"""






							if never_split is None:
								snake_case_		   =					[]
							snake_case_		   =					do_lower_case
							snake_case_		   =					set(__lowercase						)
							snake_case_		   =					tokenize_chinese_chars
							snake_case_		   =					strip_accents
							snake_case_		   =					do_split_on_punc






						def 	snake_case__						(						self							:					Any	,     __lowercase							:					Any	,     __lowercase							:					Optional[int]=None						):






							"""simple docstring"""






							snake_case_		   =					self.never_split.union(set(__lowercase						)						) if never_split else self.never_split
							snake_case_		   =					self._clean_text(__lowercase						)

							# This was added on November 1st, 2018 for the multilingual and Chinese
							# models. This is also applied to the English models now, but it doesn't
							# matter since the English models were not trained on any Chinese data
							# and generally don't have any Chinese data in them (there are Chinese
							# characters in the vocabulary because Wikipedia does have some Chinese
							# words in the English Wikipedia.).
							if self.tokenize_chinese_chars:
								snake_case_		   =					self._tokenize_chinese_chars(__lowercase						)
							# prevents treating the same character with different unicode codepoints as different characters
							snake_case_		   =					unicodedata.normalize("NFC"	,     __lowercase						)
							snake_case_		   =					whitespace_tokenize(__lowercase						)
							snake_case_		   =					[]
							for token in orig_tokens:
								if token not in never_split:
									if self.do_lower_case:
										snake_case_		   =					token.lower()
										if self.strip_accents is not False:
											snake_case_		   =					self._run_strip_accents(__lowercase						)
									elif self.strip_accents:
										snake_case_		   =					self._run_strip_accents(__lowercase						)
								split_tokens.extend(self._run_split_on_punc(__lowercase	,     __lowercase						)						)

							snake_case_		   =					whitespace_tokenize(" ".join(__lowercase						)						)
							return output_tokens






						def 	snake_case__						(						self							:					str	,     __lowercase							:					List[str]						):






							"""simple docstring"""






							snake_case_		   =					unicodedata.normalize("NFD"	,     __lowercase						)
							snake_case_		   =					[]
							for char in text:
								snake_case_		   =					unicodedata.category(__lowercase						)
								if cat == "Mn":
									continue
								output.append(__lowercase						)
							return "".join(__lowercase						)






						def 	snake_case__						(						self							:					Tuple	,     __lowercase							:					Union[str, Any]	,     __lowercase							:					Optional[int]=None						):






							"""simple docstring"""






							if not self.do_split_on_punc or (never_split is not None and text in never_split):
								return [text]
							snake_case_		   =					list(__lowercase						)
							snake_case_		   =					0
							snake_case_		   =					True
							snake_case_		   =					[]
							while i < len(__lowercase						):
								snake_case_		   =					chars[i]
								if _is_punctuation(__lowercase						):
									output.append([char]						)
									snake_case_		   =					True
								else:
									if start_new_word:
										output.append([]						)
									snake_case_		   =					False
									output[-1].append(__lowercase						)
								i += 1

							return ["".join(__lowercase						) for x in output]






						def 	snake_case__						(						self							:					Optional[int]	,     __lowercase							:					str						):






							"""simple docstring"""






							snake_case_		   =					[]
							for char in text:
								snake_case_		   =					ord(__lowercase						)
								if self._is_chinese_char(__lowercase						):
									output.append(" "						)
									output.append(__lowercase						)
									output.append(" "						)
								else:
									output.append(__lowercase						)
							return "".join(__lowercase						)






						def 	snake_case__						(						self							:					Union[str, Any]	,     __lowercase							:					str						):






							"""simple docstring"""






							if (
							    (cp >= 0X4_e00 and cp <= 0X9_fff)
							    or (cp >= 0X3_400 and cp <= 0X4_dbf)  #
							    or (cp >= 0X20_000 and cp <= 0X2a_6df)  #
							    or (cp >= 0X2a_700 and cp <= 0X2b_73f)  #
							    or (cp >= 0X2b_740 and cp <= 0X2b_81f)  #
							    or (cp >= 0X2b_820 and cp <= 0X2c_eaf)  #
							    or (cp >= 0Xf_900 and cp <= 0Xf_aff)
							    or (cp >= 0X2f_800 and cp <= 0X2f_a1f)  #
							):  #
								return True

							return False






						def 	snake_case__						(						self							:					int	,     __lowercase							:					Dict						):






							"""simple docstring"""






							snake_case_		   =					[]
							for char in text:
								snake_case_		   =					ord(__lowercase						)
								if cp == 0 or cp == 0Xf_ffd or _is_control(__lowercase						):
									continue
								if _is_whitespace(__lowercase						):
									output.append(" "						)
								else:
									output.append(__lowercase						)
							return "".join(__lowercase						)







def 						lowerCamelCase__   (		_A							):







	'''simple docstring'''





	snake_case_		   =					set()
	snake_case_		   =					word[0]
	for char in word[1:]:
		pairs.add((prev_char, char)							)
		snake_case_		   =					char
	return pairs


def 						lowerCamelCase__   (		_A							):







	'''simple docstring'''





	snake_case_		   =					text.replace("—"					,     "-"							)
	snake_case_		   =					text.replace("–"					,     "-"							)
	snake_case_		   =					text.replace("―"					,     "-"							)
	snake_case_		   =					text.replace("…"					,     "..."							)
	snake_case_		   =					text.replace("´"					,     "'"							)
	snake_case_		   =					re.sub(R"(-+|~+|!+|\"+|;+|\?+|\++|,+|\)+|\(+|\\+|\/+|\*+|\[+|\]+|}+|{+|\|+|_+)"					,     R" \1 "					,     _A							)
	snake_case_		   =					re.sub(R"\s*\n\s*"					,     " \n "					,     _A							)
	snake_case_		   =					re.sub(R"[^\S\n]+"					,     " "					,     _A							)
	return text.strip()






class 		UpperCAmelCase       (    UpperCAmelCase__      ):







						'''simple docstring'''





						lowerCAmelCase_							=       VOCAB_FILES_NAMES
						lowerCAmelCase_							=       PRETRAINED_VOCAB_FILES_MAP
						lowerCAmelCase_							=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						lowerCAmelCase_							=       ['''input_ids''', '''attention_mask''']






						def __init__(						self							:					Dict	,     __lowercase							:					Union[str, Any]	,     __lowercase							:					Tuple	,     __lowercase							:					Any="<unk>"	,     **__lowercase							:					List[Any]						):






							"""simple docstring"""






							super().__init__(unk_token=__lowercase	,     **__lowercase						)

							try:
								import ftfy
								from spacy.lang.en import English

								snake_case_		   =					English()
								snake_case_		   =					_nlp.tokenizer
								snake_case_		   =					ftfy.fix_text
							except ImportError:
								logger.warning("ftfy or spacy is not installed using BERT BasicTokenizer instead of SpaCy & ftfy."						)
								snake_case_		   =					BasicTokenizer(do_lower_case=__lowercase						)
								snake_case_		   =					None

							with open(__lowercase	,     encoding="utf-8"						) as vocab_handle:
								snake_case_		   =					json.load(__lowercase						)
							snake_case_		   =					{v: k for k, v in self.encoder.items()}
							with open(__lowercase	,     encoding="utf-8"						) as merges_handle:
								snake_case_		   =					merges_handle.read().split("\n"						)[1:-1]
							snake_case_		   =					[tuple(merge.split()						) for merge in merges]
							snake_case_		   =					dict(zip(__lowercase	,     range(len(__lowercase						)						)						)						)
							snake_case_		   =					{}






						@property
						def 	snake_case__						(						self							:					List[Any]						):






							"""simple docstring"""






							return True






						@property
						def 	snake_case__						(						self							:					Union[str, Any]						):






							"""simple docstring"""






							return len(self.encoder						)






						def 	snake_case__						(						self							:					str						):






							"""simple docstring"""






							return dict(self.encoder	,     **self.added_tokens_encoder						)






						def 	snake_case__						(						self							:					Optional[Any]	,     __lowercase							:					int						):






							"""simple docstring"""






							snake_case_		   =					tuple(token[:-1]						) + (token[-1] + "</w>",)
							if token in self.cache:
								return self.cache[token]
							snake_case_		   =					get_pairs(__lowercase						)

							if not pairs:
								return token + "</w>"

							while True:
								snake_case_		   =					min(__lowercase	,     key=lambda __lowercase						: self.bpe_ranks.get(__lowercase	,     float("inf"						)						)						)
								if bigram not in self.bpe_ranks:
									break
								snake_case_   ,				snake_case_		   =					bigram
								snake_case_		   =					[]
								snake_case_		   =					0
								while i < len(__lowercase						):
									try:
										snake_case_		   =					word.index(__lowercase	,     __lowercase						)
									except ValueError:
										new_word.extend(word[i:]						)
										break
									else:
										new_word.extend(word[i:j]						)
										snake_case_		   =					j

									if word[i] == first and i < len(__lowercase						) - 1 and word[i + 1] == second:
										new_word.append(first + second						)
										i += 2
									else:
										new_word.append(word[i]						)
										i += 1
								snake_case_		   =					tuple(__lowercase						)
								snake_case_		   =					new_word
								if len(__lowercase						) == 1:
									break
								else:
									snake_case_		   =					get_pairs(__lowercase						)
							snake_case_		   =					" ".join(__lowercase						)
							if word == "\n  </w>":
								snake_case_		   =					"\n</w>"
							snake_case_		   =					word
							return word






						def 	snake_case__						(						self							:					List[str]	,     __lowercase							:					Tuple						):






							"""simple docstring"""






							snake_case_		   =					[]
							if self.fix_text is None:
								# Using BERT's BasicTokenizer
								snake_case_		   =					self.nlp.tokenize(__lowercase						)
								for token in text:
									split_tokens.extend(list(self.bpe(__lowercase						).split(" "						)						)						)
							else:
								# Using SpaCy & ftfy (original tokenization process of OpenAI GPT)
								snake_case_		   =					self.nlp(text_standardize(self.fix_text(__lowercase						)						)						)
								for token in text:
									split_tokens.extend(list(self.bpe(token.text.lower()						).split(" "						)						)						)
							return split_tokens






						def 	snake_case__						(						self							:					int	,     __lowercase							:					Tuple						):






							"""simple docstring"""






							return self.encoder.get(__lowercase	,     self.encoder.get(self.unk_token						)						)






						def 	snake_case__						(						self							:					Tuple	,     __lowercase							:					Any						):






							"""simple docstring"""






							return self.decoder.get(__lowercase	,     self.unk_token						)






						def 	snake_case__						(						self							:					str	,     __lowercase							:					List[Any]						):






							"""simple docstring"""






							snake_case_		   =					"".join(__lowercase						).replace("</w>"	,     " "						).strip()
							return out_string






						def 	snake_case__						(						self							:					int	,     __lowercase							:					str	,     __lowercase							:					Optional[str] = None						):






							"""simple docstring"""






							if not os.path.isdir(__lowercase						):
								logger.error(f"Vocabulary path ({save_directory}) should be a directory"						)
								return
							snake_case_		   =					os.path.join(
							    __lowercase	,     (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]						)
							snake_case_		   =					os.path.join(
							    __lowercase	,     (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]						)

							with open(__lowercase	,     "w"	,     encoding="utf-8"						) as f:
								f.write(json.dumps(self.encoder	,     indent=2	,     sort_keys=__lowercase	,     ensure_ascii=__lowercase						) + "\n"						)

							snake_case_		   =					0
							with open(__lowercase	,     "w"	,     encoding="utf-8"						) as writer:
								writer.write("#version: 0.2\n"						)
								for bpe_tokens, token_index in sorted(self.bpe_ranks.items()	,     key=lambda __lowercase						: kv[1]						):
									if index != token_index:
										logger.warning(
										    f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
										    " Please check that the tokenizer is not corrupted!"						)
										snake_case_		   =					token_index
									writer.write(" ".join(__lowercase						) + "\n"						)
									index += 1

							return vocab_file, merge_file
