






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


A_     =				logging.get_logger(__name__)

A_     =				{
    'source_spm': 'source.spm',
    'target_spm': 'target.spm',
    'vocab': 'vocab.json',
    'target_vocab_file': 'target_vocab.json',
    'tokenizer_config_file': 'tokenizer_config.json',
}

A_     =				{
    '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'
        )
    },
}

A_     =				{'Helsinki-NLP/opus-mt-en-de': 512}
A_     =				{}






class 				__SCREAMING_SNAKE_CASE    (					UpperCAmelCase__		):
							snake_case_  =				VOCAB_FILES_NAMES
							snake_case_  =				PRETRAINED_VOCAB_FILES_MAP
							snake_case_  =				PRETRAINED_INIT_CONFIGURATION
							snake_case_  =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							snake_case_  =				["input_ids", "attention_mask"]
							snake_case_  =				re.compile('>>.+<<'		)  # type: re.Pattern


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





													A__    :	Tuple			=	{} 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=snake_case__      ,     target_lang=snake_case__      ,     unk_token=snake_case__      ,     eos_token=snake_case__      ,     pad_token=snake_case__      ,     model_max_length=snake_case__      ,     sp_model_kwargs=self.sp_model_kwargs      ,     target_vocab_file=snake_case__      ,     separate_vocabs=snake_case__      ,     **snake_case__      ,     )
													assert Path(snake_case__				).exists(), F'cannot find spm source {source_spm}'

													A__    :	Union[str, Any]			=	separate_vocabs
													A__    :	Tuple			=	load_json(snake_case__				)
													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:
																			A__    :	Optional[int]			=	load_json(snake_case__				)
																			A__    :	int			=	{v: k for k, v in self.target_encoder.items()}
																			A__    :	Union[str, Any]			=	[]
													else:
																			A__    :	Optional[int]			=	{v: k for k, v in self.encoder.items()}
																			A__    :	List[Any]			=	[k for k in self.encoder if k.startswith(""">>"""				) and k.endswith("""<<"""				)]

													A__    :	Any			=	source_lang
													A__    :	str			=	target_lang
													A__    :	int			=	[source_spm, target_spm]

													# load SentencePiece model for pre-processing
													A__    :	str			=	load_spm(snake_case__      ,     self.sp_model_kwargs				)
													A__    :	Any			=	load_spm(snake_case__      ,     self.sp_model_kwargs				)
													A__    :	Tuple			=	self.spm_source
													A__    :	List[Any]			=	self.encoder

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

													self._setup_normalizer()


							def     _UpperCamelCase							(      self   :    int				):
													'''simple docstring'''





													try:
																			from sacremoses import MosesPunctNormalizer

																			A__    :	int			=	MosesPunctNormalizer(self.source_lang				).normalize
													except (ImportError, FileNotFoundError):
																			warnings.warn("""Recommended: pip install sacremoses."""				)
																			A__    :	Tuple			=	lambda snake_case				: x


							def     _UpperCamelCase							(      self   :    List[Any]      ,     snake_case   :    str				):
													'''simple docstring'''





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


							def     _UpperCamelCase							(      self   :    str      ,     snake_case   :    Tuple				):
													'''simple docstring'''





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


							def     _UpperCamelCase							(      self   :    int      ,     snake_case   :    str				):
													'''simple docstring'''





													A__    :	Union[str, Any]			=	self.language_code_re.match(snake_case__				)
													A__    :	Any			=	[match.group(0				)] if match else []
													return code, self.language_code_re.sub(""""""      ,     snake_case__				)


							def     _UpperCamelCase							(      self   :    Optional[int]      ,     snake_case   :    str				):
													'''simple docstring'''





													A__	,	A__    :	Dict			=	self.remove_language_code(snake_case__				)
													A__    :	int			=	self.current_spm.encode(snake_case__      ,     out_type=snake_case__				)
													return code + pieces


							def     _UpperCamelCase							(      self   :    List[Any]      ,     snake_case   :    int				):
													'''simple docstring'''





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


							def     _UpperCamelCase							(      self   :    Union[str, Any]      ,     snake_case   :    Union[str, Any]      ,     **snake_case   :    Union[str, Any]				):
													'''simple docstring'''





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


							def     _UpperCamelCase							(      self   :    List[str]      ,     snake_case   :    Tuple      ,     **snake_case   :    List[Any]				):
													'''simple docstring'''





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


							def     _UpperCamelCase							(      self   :    Union[str, Any]      ,     snake_case   :    List[str]				):
													'''simple docstring'''





													A__    :	Tuple			=	self.spm_source if self._decode_use_source_tokenizer else self.spm_target
													A__    :	Tuple			=	[]
													A__    :	List[str]			=	""""""
													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(snake_case__				) + token + " "
																									A__    :	List[str]			=	[]
																			else:
																									current_sub_tokens.append(snake_case__				)
													out_string += sp_model.decode_pieces(snake_case__				)
													return out_string.strip()


							def     _UpperCamelCase							(      self   :    Optional[Any]      ,     snake_case   :    Union[str, Any]      ,     snake_case   :    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     _UpperCamelCase							(      self   :    Union[str, Any]				):
													'''simple docstring'''





													A__    :	Dict			=	self.spm_source
													A__    :	Any			=	self.encoder


							def     _UpperCamelCase							(      self   :    Optional[Any]				):
													'''simple docstring'''





													A__    :	Dict			=	self.spm_target
													if self.separate_vocabs:
																			A__    :	List[str]			=	self.target_encoder


							@property
							def     _UpperCamelCase							(      self   :    int				):
													'''simple docstring'''





													return len(self.encoder				)


							def     _UpperCamelCase							(      self   :    Any      ,     snake_case   :    str      ,     snake_case   :    Optional[str] = None				):
													'''simple docstring'''





													if not os.path.isdir(snake_case__				):
																			logger.error(F'Vocabulary path ({save_directory}) should be a directory'				)
																			return
													A__    :	int			=	[]

													if self.separate_vocabs:
																			A__    :	int			=	os.path.join(
																			    snake_case__      ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab"""]      ,     )
																			A__    :	Tuple			=	os.path.join(
																			    snake_case__      ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""target_vocab_file"""]      ,     )
																			save_json(self.encoder      ,     snake_case__				)
																			save_json(self.target_encoder      ,     snake_case__				)
																			saved_files.append(snake_case__				)
																			saved_files.append(snake_case__				)
													else:
																			A__    :	List[Any]			=	os.path.join(
																			    snake_case__      ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab"""]				)
																			save_json(self.encoder      ,     snake_case__				)
																			saved_files.append(snake_case__				)

													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]      ,     ):
																			A__    :	Optional[Any]			=	os.path.join(
																			    snake_case__      ,     (filename_prefix + """-""" if filename_prefix else """""") + spm_save_filename				)
																			if os.path.abspath(snake_case__				) != os.path.abspath(snake_case__				) and os.path.isfile(snake_case__				):
																									copyfile(snake_case__      ,     snake_case__				)
																									saved_files.append(snake_case__				)
																			elif not os.path.isfile(snake_case__				):
																									with open(snake_case__      ,     """wb"""				) as fi:
																															A__    :	Dict			=	spm_model.serialized_model_proto()
																															fi.write(snake_case__				)
																									saved_files.append(snake_case__				)

													return tuple(snake_case__				)


							def     _UpperCamelCase							(      self   :    Tuple				):
													'''simple docstring'''





													return self.get_src_vocab()


							def     _UpperCamelCase							(      self   :    List[Any]				):
													'''simple docstring'''





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


							def     _UpperCamelCase							(      self   :    Dict				):
													'''simple docstring'''





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


							def __getstate__(      self   :    Optional[Any]				):
													'''simple docstring'''





													A__    :	Optional[int]			=	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      ,     snake_case   :    Dict				):
													'''simple docstring'''





													A__    :	Any			=	d

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

													A__	,	A__    :	Dict			=	(load_spm(snake_case__      ,     self.sp_model_kwargs				) for f in self.spm_files)
													A__    :	Union[str, Any]			=	self.spm_source
													self._setup_normalizer()


							def     _UpperCamelCase							(      self   :    Tuple      ,     *snake_case   :    int      ,     **snake_case   :    Optional[int]				):
													'''simple docstring'''





													return 1


							def     _UpperCamelCase							(      self   :    str      ,     snake_case   :    Dict				):
													'''simple docstring'''





													A__    :	List[str]			=	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     _UpperCamelCase							(      self   :    Optional[int]      ,     snake_case   :    List      ,     snake_case   :    Optional[List] = None      ,     snake_case   :    bool = False				):
													'''simple docstring'''





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




def   _lowerCAmelCase		(				UpperCAmelCase__							:       List[str],    UpperCAmelCase__							:       Any   )		->Union[str, Any]:
						A__    :	List[str]			=	sentencepiece.SentencePieceProcessor(**snake_case_   )
						spm.Load(snake_case_   )
						return spm




def   _lowerCAmelCase		(				UpperCAmelCase__							:       Optional[int],    UpperCAmelCase__							:       str   )		->str:


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




def   _lowerCAmelCase		(				UpperCAmelCase__							:       str   )		->str:


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












import enum
import inspect
import warnings
from functools import wraps
from typing import Callable, Optional

from .logging import get_logger


lowercase_      :							Optional[int]    							=					set()
lowercase_      :							List[Any]    							=					get_logger(__name__)


def 				__SCREAMING_SNAKE_CASE    (     snake_case_ = None		):

						'''simple docstring'''


						def decorator(snake_case_		):
												global _emitted_deprecation_warnings

												if inspect.isclass(snake_case_		):
																		_UpperCAmelCase						=	deprecated_class_or_function.__init__
																		_UpperCAmelCase						=	deprecated_class_or_function.__name__
												else:
																		_UpperCAmelCase						=	deprecated_class_or_function
																		_UpperCAmelCase						=	deprecated_function.__name__
																		# Support deprecating __init__ class method: class name instead
																		_UpperCAmelCase						=	name if name != "__init__" else deprecated_function.__qualname__.split("."		)[-2]

												_UpperCAmelCase						=	(
												    f"""{name} is deprecated and will be removed in the next major version of datasets.""" + f""" {help_message}"""
												    if help_message
												    else ""
												)

												@wraps(snake_case_		)
												def wrapper(*snake_case_      ,       **snake_case_		):
																		_UpperCAmelCase						=	hash(snake_case_		)
																		if func_hash not in _emitted_deprecation_warnings:
																								warnings.warn(snake_case_      ,       category=snake_case_      ,       stacklevel=2		)
																								_emitted_deprecation_warnings.add(snake_case_		)
																		return deprecated_function(*snake_case_      ,       **snake_case_		)

												_UpperCAmelCase						=	"deprecated"

												if inspect.isclass(snake_case_		):
																		_UpperCAmelCase						=	wrapper
																		return deprecated_class_or_function
												else:
																		return wrapper

						return decorator






class        __lowerCAmelCase					(			enum.EnumMeta					):







			def __getattribute__(			cls       :     str       ,       snake_case__       :     Optional[Any] ):




									"""simple docstring"""


									_UpperCAmelCase						=	super().__getattribute__(snake_case__ )
									if isinstance(snake_case__       ,       enum.Enum ) and obj._on_access:
															obj._on_access()
									return obj







			def __getitem__(			cls       :     str       ,       snake_case__       :     Union[str, Any] ):




									"""simple docstring"""


									_UpperCAmelCase						=	super().__getitem__(snake_case__ )
									if member._on_access:
															member._on_access()
									return member







			def __call__(			cls       :     Dict       ,       snake_case__       :     Any       ,       snake_case__       :     List[str]=None       ,       *, snake_case__       :     Optional[int]=None       ,       snake_case__       :     List[Any]=None       ,       snake_case__       :     Tuple=None       ,       snake_case__       :     List[Any]=1 ):




									"""simple docstring"""


									_UpperCAmelCase						=	super().__call__(snake_case__       ,       snake_case__       ,       module=snake_case__       ,       qualname=snake_case__       ,       type=snake_case__       ,       start=snake_case__ )
									if isinstance(snake_case__       ,       enum.Enum ) and obj._on_access:
															obj._on_access()
									return obj






class        __lowerCAmelCase					(			enum.Enum   ,						metaclass=UpperCAmelCase__					):







			def __new__(			cls       :     Any       ,       snake_case__       :     Dict ):




									"""simple docstring"""


									_UpperCAmelCase						=	object.__new__(cls )
									_UpperCAmelCase						=	value
									_UpperCAmelCase						=	member.deprecate
									return member







			@property
			def UpperCamelCase     (			self       :     str ):




									"""simple docstring"""


									return ""







			def UpperCamelCase     (			self       :     Optional[int] ):




									"""simple docstring"""


									_UpperCAmelCase						=	F""" {self.help_message}""" if self.help_message else ""
									warnings.warn(
									    F"""'{self.__objclass__.__name__}' is deprecated and will be removed in the next major version of datasets."""
									    + help_message       ,       snake_case__       ,       stacklevel=3       ,       )




