'''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  							=    logging.get_logger(__name__)

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

__UpperCAmelCase  							=    {
    "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  							=    {"Helsinki-NLP/opus-mt-en-de": 5_1_2}
__UpperCAmelCase  							=    {}




class 					a__   (     UpperCAmelCase__				):
     lowerCamelCase						:  str							=VOCAB_FILES_NAMES
     lowerCamelCase						:  Union[str, Any]							=PRETRAINED_VOCAB_FILES_MAP
     lowerCamelCase						:  Optional[int]							=PRETRAINED_INIT_CONFIGURATION
     lowerCamelCase						:  str							=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowerCamelCase						:  Union[str, Any]							=["input_ids", "attention_mask"]
     lowerCamelCase						:  List[Any]							=re.compile(">>.+<<"				)  # type: re.Pattern






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





         """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=a						,       target_lang=a						,       unk_token=a						,       eos_token=a						,       pad_token=a						,       model_max_length=a						,       sp_model_kwargs=self.sp_model_kwargs						,       target_vocab_file=a						,       separate_vocabs=a						,       **a						,       )
         assert Path(a					).exists(), f"""cannot find spm source {source_spm}"""

         __lowerCamelCase						=						separate_vocabs
         __lowerCamelCase						=						load_json(a					)
         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(a					)
             __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(a						,       self.sp_model_kwargs					)
         __lowerCamelCase						=						load_spm(a						,       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 a					: x






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	str					):





         """simple docstring"""



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






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	Any					):





         """simple docstring"""



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






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	str					):





         """simple docstring"""



         __lowerCamelCase						=						self.language_code_re.match(a					)
         __lowerCamelCase						=						[match.group(0					)] if match else []
         return code, self.language_code_re.sub(''''''						,       a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict						,       a	:	str					):





         """simple docstring"""



         __lowerCamelCase			,						__lowerCamelCase						=						self.remove_language_code(a					)
         __lowerCamelCase						=						self.current_spm.encode(a						,       out_type=a					)
         return code + pieces






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict						,       a	:	int					):





         """simple docstring"""



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






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]						,       a	:	Optional[Any]						,       **a	:	Dict					):





         """simple docstring"""



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






     def      SCREAMING_SNAKE_CASE__     (				self	:	Union[str, Any]						,       a	:	int						,       **a	:	int					):





         """simple docstring"""



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






     def      SCREAMING_SNAKE_CASE__     (				self	:	Any						,       a	:	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(a					) + token + " "
                 __lowerCamelCase						=						[]
             else:
                 current_sub_tokens.append(a					)
         out_string += sp_model.decode_pieces(a					)
         return out_string.strip()






     def      SCREAMING_SNAKE_CASE__     (				self	:	Any						,       a	:	Union[str, Any]						,       a	:	Tuple=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	:	List[Any]					):





         """simple docstring"""



         __lowerCamelCase						=						self.spm_source
         __lowerCamelCase						=						self.encoder






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[str]					):





         """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	:	Any						,       a	:	str						,       a	:	Optional[str] = None					):





         """simple docstring"""



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

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

         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(
                 a						,       (filename_prefix + '''-''' if filename_prefix else '''''') + spm_save_filename					)
             if os.path.abspath(a					) != os.path.abspath(a					) and os.path.isfile(a					):
                 copyfile(a						,       a					)
                 saved_files.append(a					)
             elif not os.path.isfile(a					):
                 with open(a						,       '''wb'''					) as fi:
                     __lowerCamelCase						=						spm_model.serialized_model_proto()
                     fi.write(a					)
                 saved_files.append(a					)

         return tuple(a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]					):





         """simple docstring"""



         return self.get_src_vocab()






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]					):





         """simple docstring"""



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






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict					):





         """simple docstring"""



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






     def __getstate__(				self	:	str					):





         """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	:	Tuple						,       a	:	Dict					):





         """simple docstring"""



         __lowerCamelCase						=						d

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

         __lowerCamelCase			,						__lowerCamelCase						=						(load_spm(a						,       self.sp_model_kwargs					) for f in self.spm_files)
         __lowerCamelCase						=						self.spm_source
         self._setup_normalizer()






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]						,       *a	:	Tuple						,       **a	:	int					):





         """simple docstring"""



         return 1






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	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	:	List[str]						,       a	:	List						,       a	:	Optional[List] = None						,       a	:	bool = False					):





         """simple docstring"""



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






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					sentencepiece.SentencePieceProcessor:
    __lowerCamelCase						=						sentencepiece.SentencePieceProcessor(**UpperCamelCase__       )
    spm.Load(UpperCamelCase__       )
    return spm






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					None:
    with open(UpperCamelCase__       ,						'''w'''       ) as f:
        json.dump(UpperCamelCase__       ,						UpperCamelCase__       ,						indent=2       )






def __lowerCAmelCase				(							UpperCamelCase__       )			->					Union[Dict, List]:
    with open(UpperCamelCase__       ,						'''r'''       ) as f:
        return json.load(UpperCamelCase__       )

'''simple docstring'''




from __future__ import annotations






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					list:
    __lowerCamelCase						=						[None] * (len(UpperCamelCase__       ) + len(UpperCamelCase__       ))

    __lowerCamelCase						=						0  # pointer to current index for left Half
    __lowerCamelCase						=						0  # pointer to current index for the right Half
    __lowerCamelCase						=						0  # pointer to current index for the sorted array Half

    while pointera < len(UpperCamelCase__       ) and pointera < len(UpperCamelCase__       ):
        if left_half[pointera] < right_half[pointera]:
            __lowerCamelCase						=						left_half[pointera]
            pointera += 1
            index += 1
        else:
            __lowerCamelCase						=						right_half[pointera]
            pointera += 1
            index += 1
    while pointera < len(UpperCamelCase__       ):
        __lowerCamelCase						=						left_half[pointera]
        pointera += 1
        index += 1

    while pointera < len(UpperCamelCase__       ):
        __lowerCamelCase						=						right_half[pointera]
        pointera += 1
        index += 1

    return sorted_array






def __lowerCAmelCase				(							UpperCamelCase__       )			->					list:
    if len(UpperCamelCase__       ) <= 1:
        return array
    # the actual formula to calculate the middle element = left + (right - left) // 2
    # this avoids integer overflow in case of large N
    __lowerCamelCase						=						0 + (len(UpperCamelCase__       ) - 0) // 2

    # Split the array into halves till the array length becomes equal to One
    # merge the arrays of single length returned by mergeSort function and
    # pass them into the merge arrays function which merges the array
    __lowerCamelCase						=						array[:middle]
    __lowerCamelCase						=						array[middle:]

    return merge(merge_sort(UpperCamelCase__       )       ,						merge_sort(UpperCamelCase__       )       )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
