
'''simple docstring'''

import argparse
import logging
import os
import sys
from collections import namedtuple

import torch
from modeling_bertabs import BertAbs, build_predictor
from torch.utils.data import DataLoader, SequentialSampler
from tqdm import tqdm

from transformers import BertTokenizer

from .utils_summarization import (
    CNNDMDataset,
    build_mask,
    compute_token_type_ids,
    encode_for_summarization,
    truncate_or_pad,
)


UpperCAmelCase__				:	List[Any]					=						logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.INFO)


UpperCAmelCase__				:	Optional[Any]					=						namedtuple("Batch", ["document_names", "batch_size", "src", "segs", "mask_src", "tgt_str"])







def 					A       ( UpperCamelCase_   :       str )   ->    Dict:







			'''simple docstring'''



			lowerCAmelCase__									=							BertTokenizer.from_pretrained("bert-base-uncased"  ,		do_lower_case=UpperCamelCase_ )
			lowerCAmelCase__									=							BertAbs.from_pretrained("remi/bertabs-finetuned-extractive-abstractive-summarization" )
			model.to(args.device )
			model.eval()

			lowerCAmelCase__									=							{
			    "BOS": tokenizer.vocab["[unused0]"],
			    "EOS": tokenizer.vocab["[unused1]"],
			    "PAD": tokenizer.vocab["[PAD]"],
			}

			if args.compute_rouge:
						lowerCAmelCase__									=							[]
						lowerCAmelCase__									=							[]

						import nltk
						import rouge

						nltk.download("punkt" )
						lowerCAmelCase__									=							rouge.Rouge(
						    metrics=["rouge-n", "rouge-l"]  ,		max_n=2  ,		limit_length=UpperCamelCase_  ,		length_limit=args.beam_size  ,		length_limit_type="words"  ,		apply_avg=UpperCamelCase_  ,		apply_best=UpperCamelCase_  ,		alpha=0.5  ,		weight_factor=1.2  ,		stemming=UpperCamelCase_  ,		)

			# these (unused) arguments are defined to keep the compatibility
			# with the legacy code and will be deleted in a next iteration.
			lowerCAmelCase__									=							""
			lowerCAmelCase__									=							""

			lowerCAmelCase__									=							build_data_iterator(UpperCamelCase_  ,		UpperCamelCase_ )
			lowerCAmelCase__									=							build_predictor(UpperCamelCase_  ,		UpperCamelCase_  ,		UpperCamelCase_  ,		UpperCamelCase_ )

			logger.info("***** Running evaluation *****" )
			logger.info("  Number examples = %d"  ,		len(data_iterator.dataset ) )
			logger.info("  Batch size = %d"  ,		args.batch_size )
			logger.info("" )
			logger.info("***** Beam Search parameters *****" )
			logger.info("  Beam size = %d"  ,		args.beam_size )
			logger.info("  Minimum length = %d"  ,		args.min_length )
			logger.info("  Maximum length = %d"  ,		args.max_length )
			logger.info("  Alpha (length penalty) = %.2f"  ,		args.alpha )
			logger.info("  Trigrams %s be blocked"  ,		("will" if args.block_trigram else "will NOT") )

			for batch in tqdm(UpperCamelCase_ ):
						lowerCAmelCase__									=							predictor.translate_batch(UpperCamelCase_ )
						lowerCAmelCase__									=							predictor.from_batch(UpperCamelCase_ )
						lowerCAmelCase__									=							[format_summary(UpperCamelCase_ ) for t in translations]
						save_summaries(UpperCamelCase_  ,		args.summaries_output_dir  ,		batch.document_names )

						if args.compute_rouge:
									reference_summaries += batch.tgt_str
									generated_summaries += summaries

			if args.compute_rouge:
						lowerCAmelCase__									=							rouge_evaluator.get_scores(UpperCamelCase_  ,		UpperCamelCase_ )
						lowerCAmelCase__									=							format_rouge_scores(UpperCamelCase_ )
						save_rouge_scores(UpperCamelCase_ )
						print(UpperCamelCase_ )







def 					A       ( UpperCamelCase_   :       List[Any]  ,		UpperCamelCase_   :       int  ,		UpperCamelCase_   :       Union[str, Any] )   ->    str:







			'''simple docstring'''



			for summary, document_name in zip(UpperCamelCase_  ,		UpperCamelCase_ ):
						# Prepare the summary file's name
						if "." in document_name:
									lowerCAmelCase__									=							".".join(document_name.split("." )[:-1] )
									lowerCAmelCase__									=							document_name.split("." )[-1]
									lowerCAmelCase__									=							bare_document_name + "_summary." + extension
						else:
									lowerCAmelCase__									=							document_name + "_summary"

						lowerCAmelCase__									=							os.path.join(UpperCamelCase_  ,		UpperCamelCase_ )
						with open(UpperCamelCase_  ,		"w" ) as output:
									output.write(UpperCamelCase_ )







def 					A       ( UpperCamelCase_   :       Any )   ->    List[Any]:







			'''simple docstring'''



			lowerCAmelCase__		,lowerCAmelCase__		,lowerCAmelCase__									=							translation
			lowerCAmelCase__									=							(
			    raw_summary.replace("[unused0]"  ,		"" )
			    .replace("[unused3]"  ,		"" )
			    .replace("[PAD]"  ,		"" )
			    .replace("[unused1]"  ,		"" )
			    .replace(r" +"  ,		" " )
			    .replace(" [unused2] "  ,		". " )
			    .replace("[unused2]"  ,		"" )
			    .strip()
			)

			return summary







def 					A       ( UpperCamelCase_   :       int )   ->    List[str]:







			'''simple docstring'''



			return """\n
****** ROUGE SCORES ******

** ROUGE 1
F1        >> {:.3f}
Precision >> {:.3f}
Recall    >> {:.3f}

** ROUGE 2
F1        >> {:.3f}
Precision >> {:.3f}
Recall    >> {:.3f}

** ROUGE L
F1        >> {:.3f}
Precision >> {:.3f}
Recall    >> {:.3f}""".format(
			    scores["rouge-1"]["f"]  ,		scores["rouge-1"]["p"]  ,		scores["rouge-1"]["r"]  ,		scores["rouge-2"]["f"]  ,		scores["rouge-2"]["p"]  ,		scores["rouge-2"]["r"]  ,		scores["rouge-l"]["f"]  ,		scores["rouge-l"]["p"]  ,		scores["rouge-l"]["r"]  ,		)







def 					A       ( UpperCamelCase_   :       Union[str, Any] )   ->    Union[str, Any]:







			'''simple docstring'''



			with open("rouge_scores.txt"  ,		"w" ) as output:
						output.write(UpperCamelCase_ )







def 					A       ( UpperCamelCase_   :       Tuple  ,		UpperCamelCase_   :       Tuple )   ->    Optional[int]:







			'''simple docstring'''



			lowerCAmelCase__									=							load_and_cache_examples(UpperCamelCase_  ,		UpperCamelCase_ )
			lowerCAmelCase__									=							SequentialSampler(UpperCamelCase_ )

			def collate_fn(UpperCamelCase_   :       Tuple ):
						return collate(UpperCamelCase_  ,		UpperCamelCase_  ,		block_size=5_12  ,		device=args.device )

			lowerCAmelCase__									=							DataLoader(
			    UpperCamelCase_  ,		sampler=UpperCamelCase_  ,		batch_size=args.batch_size  ,		collate_fn=UpperCamelCase_  ,		)

			return iterator







def 					A       ( UpperCamelCase_   :       Optional[int]  ,		UpperCamelCase_   :       Dict )   ->    str:







			'''simple docstring'''



			lowerCAmelCase__									=							CNNDMDataset(args.documents_dir )
			return dataset







def 					A       ( UpperCamelCase_   :       List[Any]  ,		UpperCamelCase_   :       Optional[int]  ,		UpperCamelCase_   :       Union[str, Any]  ,		UpperCamelCase_   :       Tuple )   ->    List[str]:







			'''simple docstring'''



			lowerCAmelCase__									=							[x for x in data if not len(x[1] ) == 0]  # remove empty_files
			lowerCAmelCase__									=							[name for name, _, _ in data]
			lowerCAmelCase__									=							[" ".join(UpperCamelCase_ ) for _, _, summary_list in data]

			lowerCAmelCase__									=							[encode_for_summarization(UpperCamelCase_  ,		UpperCamelCase_  ,		UpperCamelCase_ ) for _, story, summary in data]
			lowerCAmelCase__									=							torch.tensor(
			    [truncate_or_pad(UpperCamelCase_  ,		UpperCamelCase_  ,		tokenizer.pad_token_id ) for story, _ in encoded_text] )
			lowerCAmelCase__									=							compute_token_type_ids(UpperCamelCase_  ,		tokenizer.cls_token_id )
			lowerCAmelCase__									=							build_mask(UpperCamelCase_  ,		tokenizer.pad_token_id )

			lowerCAmelCase__									=							Batch(
			    document_names=UpperCamelCase_  ,		batch_size=len(UpperCamelCase_ )  ,		src=encoded_stories.to(UpperCamelCase_ )  ,		segs=encoder_token_type_ids.to(UpperCamelCase_ )  ,		mask_src=encoder_mask.to(UpperCamelCase_ )  ,		tgt_str=UpperCamelCase_  ,		)

			return batch







def 					A       ( UpperCamelCase_   :       Tuple  ,		UpperCamelCase_   :       Tuple )   ->    Optional[Any]:







			'''simple docstring'''



			lowerCAmelCase__									=							summary_tokens.to("cpu" ).numpy()
			lowerCAmelCase__									=							tokenizer.decode(UpperCamelCase_ )
			lowerCAmelCase__									=							summary.split("." )
			lowerCAmelCase__									=							[s + "." for s in sentences]
			return sentences







def 					A       ( )   ->    Optional[int]:







			'''simple docstring'''



			lowerCAmelCase__									=							argparse.ArgumentParser()
			parser.add_argument(
			    "--documents_dir"  ,		default=UpperCamelCase_  ,		type=UpperCamelCase_  ,		required=UpperCamelCase_  ,		help="The folder where the documents to summarize are located."  ,		)
			parser.add_argument(
			    "--summaries_output_dir"  ,		default=UpperCamelCase_  ,		type=UpperCamelCase_  ,		required=UpperCamelCase_  ,		help="The folder in wich the summaries should be written. Defaults to the folder where the documents are"  ,		)
			parser.add_argument(
			    "--compute_rouge"  ,		default=UpperCamelCase_  ,		type=UpperCamelCase_  ,		required=UpperCamelCase_  ,		help="Compute the ROUGE metrics during evaluation. Only available for the CNN/DailyMail dataset."  ,		)
			# EVALUATION options
			parser.add_argument(
			    "--no_cuda"  ,		default=UpperCamelCase_  ,		type=UpperCamelCase_  ,		help="Whether to force the execution on CPU."  ,		)
			parser.add_argument(
			    "--batch_size"  ,		default=4  ,		type=UpperCamelCase_  ,		help="Batch size per GPU/CPU for training."  ,		)
			# BEAM SEARCH arguments
			parser.add_argument(
			    "--min_length"  ,		default=50  ,		type=UpperCamelCase_  ,		help="Minimum number of tokens for the summaries."  ,		)
			parser.add_argument(
			    "--max_length"  ,		default=2_00  ,		type=UpperCamelCase_  ,		help="Maixmum number of tokens for the summaries."  ,		)
			parser.add_argument(
			    "--beam_size"  ,		default=5  ,		type=UpperCamelCase_  ,		help="The number of beams to start with for each example."  ,		)
			parser.add_argument(
			    "--alpha"  ,		default=0.95  ,		type=UpperCamelCase_  ,		help="The value of alpha for the length penalty in the beam search."  ,		)
			parser.add_argument(
			    "--block_trigram"  ,		default=UpperCamelCase_  ,		type=UpperCamelCase_  ,		help="Whether to block the existence of repeating trigrams in the text generated by beam search."  ,		)
			lowerCAmelCase__									=							parser.parse_args()

			# Select device (distibuted not available)
			lowerCAmelCase__									=							torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu" )

			# Check the existence of directories
			if not args.summaries_output_dir:
						lowerCAmelCase__									=							args.documents_dir

			if not documents_dir_is_valid(args.documents_dir ):
						raise FileNotFoundError(
						    "We could not find the directory you specified for the documents to summarize, or it was empty. Please"
						    " specify a valid path." )
			os.makedirs(args.summaries_output_dir  ,		exist_ok=UpperCamelCase_ )

			evaluate(UpperCamelCase_ )







def 					A       ( UpperCamelCase_   :       Union[str, Any] )   ->    int:







			'''simple docstring'''



			if not os.path.exists(UpperCamelCase_ ):
						return False

			lowerCAmelCase__									=							os.listdir(UpperCamelCase_ )
			if len(UpperCamelCase_ ) == 0:
						return False

			return True


if __name__ == "__main__":
		main()


'''simple docstring'''

import json
import os
import re
import warnings
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase__				:	Tuple					=						logging.get_logger(__name__)

UpperCAmelCase__				:	int					=						{
    "source_spm": "source.spm",
    "target_spm": "target.spm",
    "vocab": "vocab.json",
    "target_vocab_file": "target_vocab.json",
    "tokenizer_config_file": "tokenizer_config.json",
}

UpperCAmelCase__				:	Dict					=						{
    "source_spm": {
        "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/source.spm"
    },
    "target_spm": {
        "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/target.spm"
    },
    "vocab": {
        "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json"
    },
    "tokenizer_config_file": {
        "Helsinki-NLP/opus-mt-en-de": (
            "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/tokenizer_config.json"
        )
    },
}

UpperCAmelCase__				:	Union[str, Any]					=						{"Helsinki-NLP/opus-mt-en-de": 5_12}
UpperCAmelCase__				:	str					=						{}






class 				A       (		SCREAMING_SNAKE_CASE__      ):
	snake_case__ :Union[str, Any]				       =       VOCAB_FILES_NAMES
	snake_case__ :Optional[int]				       =       PRETRAINED_VOCAB_FILES_MAP
	snake_case__ :Dict				       =       PRETRAINED_INIT_CONFIGURATION
	snake_case__ :List[str]				       =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	snake_case__ :str				       =       ['input_ids', 'attention_mask']
	snake_case__ :Optional[int]				       =       re.compile('>>.+<<'      )  # type: re.Pattern





	def __init__(   self     :    Tuple ,							__magic_name__     :    str ,							__magic_name__     :    Tuple ,							__magic_name__     :    Optional[int] ,							__magic_name__     :    Optional[Any]=None ,							__magic_name__     :    Optional[Any]=None ,							__magic_name__     :    str=None ,							__magic_name__     :    str="<unk>" ,							__magic_name__     :    Dict="</s>" ,							__magic_name__     :    List[str]="<pad>" ,							__magic_name__     :    str=512 ,							__magic_name__     :    Optional[Dict[str, Any]] = None ,							__magic_name__     :    Union[str, Any]=False ,							**__magic_name__     :    int ,							):


				"""simple docstring"""

				lowerCAmelCase__									=							{} if sp_model_kwargs is None else sp_model_kwargs

				super().__init__(
				    # bos_token=bos_token,  unused. Start decoding with config.decoder_start_token_id
				    source_lang=__magic_name__ ,							target_lang=__magic_name__ ,							unk_token=__magic_name__ ,							eos_token=__magic_name__ ,							pad_token=__magic_name__ ,							model_max_length=__magic_name__ ,							sp_model_kwargs=self.sp_model_kwargs ,							target_vocab_file=__magic_name__ ,							separate_vocabs=__magic_name__ ,							**__magic_name__ ,							)
				assert Path(__magic_name__							).exists(), f"""cannot find spm source {source_spm}"""

				lowerCAmelCase__									=							separate_vocabs
				lowerCAmelCase__									=							load_json(__magic_name__							)
				if self.unk_token not in self.encoder:
							raise KeyError("<unk> token must be in vocab"							)
				assert self.pad_token in self.encoder

				if separate_vocabs:
							lowerCAmelCase__									=							load_json(__magic_name__							)
							lowerCAmelCase__									=							{v: k for k, v in self.target_encoder.items()}
							lowerCAmelCase__									=							[]
				else:
							lowerCAmelCase__									=							{v: k for k, v in self.encoder.items()}
							lowerCAmelCase__									=							[k for k in self.encoder if k.startswith(">>"							) and k.endswith("<<"							)]

				lowerCAmelCase__									=							source_lang
				lowerCAmelCase__									=							target_lang
				lowerCAmelCase__									=							[source_spm, target_spm]

				# load SentencePiece model for pre-processing
				lowerCAmelCase__									=							load_spm(__magic_name__ ,							self.sp_model_kwargs							)
				lowerCAmelCase__									=							load_spm(__magic_name__ ,							self.sp_model_kwargs							)
				lowerCAmelCase__									=							self.spm_source
				lowerCAmelCase__									=							self.encoder

				# Multilingual target side: default to using first supported language code.

				self._setup_normalizer()





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Dict							):


				"""simple docstring"""

				try:
							from sacremoses import MosesPunctNormalizer

							lowerCAmelCase__									=							MosesPunctNormalizer(self.source_lang							).normalize
				except (ImportError, FileNotFoundError):
							warnings.warn("Recommended: pip install sacremoses."							)
							lowerCAmelCase__									=							lambda __magic_name__							: x





	def 							__SCREAMING_SNAKE_CASE					(   self     :    int ,							__magic_name__     :    str							):


				"""simple docstring"""

				return self.punc_normalizer(__magic_name__							) if x else ""





	def 							__SCREAMING_SNAKE_CASE					(   self     :    List[str] ,							__magic_name__     :    List[str]							):


				"""simple docstring"""

				return self.current_encoder.get(__magic_name__ ,							self.current_encoder[self.unk_token]							)





	def 							__SCREAMING_SNAKE_CASE					(   self     :    int ,							__magic_name__     :    str							):


				"""simple docstring"""

				lowerCAmelCase__									=							self.language_code_re.match(__magic_name__							)
				lowerCAmelCase__									=							[match.group(0							)] if match else []
				return code, self.language_code_re.sub("" ,							__magic_name__							)





	def 							__SCREAMING_SNAKE_CASE					(   self     :    str ,							__magic_name__     :    str							):


				"""simple docstring"""

				lowerCAmelCase__		,lowerCAmelCase__									=							self.remove_language_code(__magic_name__							)
				lowerCAmelCase__									=							self.current_spm.encode(__magic_name__ ,							out_type=__magic_name__							)
				return code + pieces





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Tuple ,							__magic_name__     :    int							):


				"""simple docstring"""

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





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Tuple ,							__magic_name__     :    Optional[int] ,							**__magic_name__     :    Union[str, Any]							):


				"""simple docstring"""

				return super().batch_decode(__magic_name__ ,							**__magic_name__							)





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Dict ,							__magic_name__     :    Union[str, Any] ,							**__magic_name__     :    Optional[int]							):


				"""simple docstring"""

				return super().decode(__magic_name__ ,							**__magic_name__							)





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Optional[Any] ,							__magic_name__     :    List[str]							):


				"""simple docstring"""

				lowerCAmelCase__									=							self.spm_source if self._decode_use_source_tokenizer else self.spm_target
				lowerCAmelCase__									=							[]
				lowerCAmelCase__									=							""
				for token in tokens:
							# make sure that special tokens are not decoded using sentencepiece model
							if token in self.all_special_tokens:
										out_string += sp_model.decode_pieces(__magic_name__							) + token + " "
										lowerCAmelCase__									=							[]
							else:
										current_sub_tokens.append(__magic_name__							)
				out_string += sp_model.decode_pieces(__magic_name__							)
				return out_string.strip()





	def 							__SCREAMING_SNAKE_CASE					(   self     :    int ,							__magic_name__     :    Dict ,							__magic_name__     :    Union[str, Any]=None							):


				"""simple docstring"""

				if token_ids_a is None:
							return token_ids_a + [self.eos_token_id]
				# We don't expect to process pairs, but leave the pair logic for API consistency
				return token_ids_a + token_ids_a + [self.eos_token_id]





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Optional[int]							):


				"""simple docstring"""

				lowerCAmelCase__									=							self.spm_source
				lowerCAmelCase__									=							self.encoder





	def 							__SCREAMING_SNAKE_CASE					(   self     :    List[Any]							):


				"""simple docstring"""

				lowerCAmelCase__									=							self.spm_target
				if self.separate_vocabs:
							lowerCAmelCase__									=							self.target_encoder





	@property
	def 							__SCREAMING_SNAKE_CASE					(   self     :    int							):


				"""simple docstring"""

				return len(self.encoder							)





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Optional[int] ,							__magic_name__     :    str ,							__magic_name__     :    Optional[str] = None							):


				"""simple docstring"""

				if not os.path.isdir(__magic_name__							):
							logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""							)
							return
				lowerCAmelCase__									=							[]

				if self.separate_vocabs:
							lowerCAmelCase__									=							os.path.join(
							    __magic_name__ ,							(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"] ,							)
							lowerCAmelCase__									=							os.path.join(
							    __magic_name__ ,							(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["target_vocab_file"] ,							)
							save_json(self.encoder ,							__magic_name__							)
							save_json(self.target_encoder ,							__magic_name__							)
							saved_files.append(__magic_name__							)
							saved_files.append(__magic_name__							)
				else:
							lowerCAmelCase__									=							os.path.join(
							    __magic_name__ ,							(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"]							)
							save_json(self.encoder ,							__magic_name__							)
							saved_files.append(__magic_name__							)

				for spm_save_filename, spm_orig_path, spm_model in zip(
				    [VOCAB_FILES_NAMES["source_spm"], VOCAB_FILES_NAMES["target_spm"]] ,							self.spm_files ,							[self.spm_source, self.spm_target] ,							):
							lowerCAmelCase__									=							os.path.join(
							    __magic_name__ ,							(filename_prefix + "-" if filename_prefix else "") + spm_save_filename							)
							if os.path.abspath(__magic_name__							) != os.path.abspath(__magic_name__							) and os.path.isfile(__magic_name__							):
										copyfile(__magic_name__ ,							__magic_name__							)
										saved_files.append(__magic_name__							)
							elif not os.path.isfile(__magic_name__							):
										with open(__magic_name__ ,							"wb"							) as fi:
													lowerCAmelCase__									=							spm_model.serialized_model_proto()
													fi.write(__magic_name__							)
										saved_files.append(__magic_name__							)

				return tuple(__magic_name__							)





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Any							):


				"""simple docstring"""

				return self.get_src_vocab()





	def 							__SCREAMING_SNAKE_CASE					(   self     :    Tuple							):


				"""simple docstring"""

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





	def 							__SCREAMING_SNAKE_CASE					(   self     :    List[Any]							):


				"""simple docstring"""

				return dict(self.target_encoder ,							**self.added_tokens_decoder							)





	def __getstate__(   self     :    List[Any]							):


				"""simple docstring"""

				lowerCAmelCase__									=							self.__dict__.copy()
				state.update(
				    {k: None for k in ["spm_source", "spm_target", "current_spm", "punc_normalizer", "target_vocab_file"]}							)
				return state





	def __setstate__(   self     :    Dict ,							__magic_name__     :    Dict							):


				"""simple docstring"""

				lowerCAmelCase__									=							d

				# for backward compatibility
				if not hasattr(self ,							"sp_model_kwargs"							):
							lowerCAmelCase__									=							{}

				lowerCAmelCase__		,lowerCAmelCase__									=							(load_spm(__magic_name__ ,							self.sp_model_kwargs							) for f in self.spm_files)
				lowerCAmelCase__									=							self.spm_source
				self._setup_normalizer()





	def 							__SCREAMING_SNAKE_CASE					(   self     :    List[str] ,							*__magic_name__     :    Any ,							**__magic_name__     :    Tuple							):


				"""simple docstring"""

				return 1





	def 							__SCREAMING_SNAKE_CASE					(   self     :    str ,							__magic_name__     :    Optional[Any]							):


				"""simple docstring"""

				lowerCAmelCase__									=							set(self.all_special_ids							)  # call it once instead of inside list comp
				all_special_ids.remove(self.unk_token_id							)  # <unk> is only sometimes special
				return [1 if x in all_special_ids else 0 for x in seq]







	def 							__SCREAMING_SNAKE_CASE					(   self     :    Optional[int] ,							__magic_name__     :    List ,							__magic_name__     :    Optional[List] = None ,							__magic_name__     :    bool = False							):


				"""simple docstring"""

				if already_has_special_tokens:
							return self._special_token_mask(__magic_name__							)
				elif token_ids_a is None:
							return self._special_token_mask(__magic_name__							) + [1]
				else:
							return self._special_token_mask(token_ids_a + token_ids_a							) + [1]







def 					A       ( UpperCamelCase_   :       str  ,		UpperCamelCase_   :       Dict[str, Any] )   ->    sentencepiece.SentencePieceProcessor:







			'''simple docstring'''



			lowerCAmelCase__									=							sentencepiece.SentencePieceProcessor(**UpperCamelCase_ )
			spm.Load(UpperCamelCase_ )
			return spm







def 					A       ( UpperCamelCase_   :       Optional[Any]  ,		UpperCamelCase_   :       str )   ->    None:







			'''simple docstring'''



			with open(UpperCamelCase_  ,		"w" ) as f:
						json.dump(UpperCamelCase_  ,		UpperCamelCase_  ,		indent=2 )







def 					A       ( UpperCamelCase_   :       str )   ->    Union[Dict, List]:







			'''simple docstring'''



			with open(UpperCamelCase_  ,		"r" ) as f:
						return json.load(UpperCamelCase_ )





