

# Lint as: python3
import os
import re
import urllib.parse
from pathlib import Path
from typing import Callable, List, Optional, Union
from zipfile import ZipFile

from ..utils.file_utils import cached_path, hf_github_url
from ..utils.logging import get_logger
from ..utils.version import Version


_a:    Optional[int] 							=			get_logger(__name__)

class 						__UpperCamelCase    :
	SCREAMING_SNAKE_CASE__    				=     'dummy_data'
	SCREAMING_SNAKE_CASE__    				=     'datasets'
	SCREAMING_SNAKE_CASE__    				=     False




	def __init__(		self	:						Any		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Union[Version, str]		,	lowerCAmelCase	:						Optional[str] = None		,	lowerCAmelCase	:						bool = False		,	lowerCAmelCase	:						bool = True		,	lowerCAmelCase	:						Optional[List[Callable]] = None		,	):


		'''simple docstring'''







		UpperCAmelCase_       				=			0
		UpperCAmelCase_       				=			dataset_name
		UpperCAmelCase_       				=			cache_dir
		UpperCAmelCase_       				=			use_local_dummy_data
		UpperCAmelCase_       				=			config
		# download_callbacks take a single url as input
		UpperCAmelCase_       				=			download_callbacks or []
		# if False, it doesn't load existing files and it returns the paths of the dummy files relative
		# to the dummy_data zip file root
		UpperCAmelCase_       				=			load_existing_dummy_data

		# TODO(PVP, QL) might need to make this more general
		UpperCAmelCase_       				=			str(lowerCAmelCase							)
		# to be downloaded
		UpperCAmelCase_       				=			None
		UpperCAmelCase_       				=			None




	@property
	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		if self._dummy_file is None:
			UpperCAmelCase_       				=			self.download_dummy_data()
		return self._dummy_file




	@property
	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		if self.config is not None:
			# structure is dummy / config_name / version_name
			return os.path.join("dummy"		,	self.config.name		,	self.version_name							)
		# structure is dummy / version_name
		return os.path.join("dummy"		,	self.version_name							)




	@property
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		return os.path.join(self.dummy_data_folder		,	"dummy_data.zip"							)




	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			(
		    self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data
		)

		UpperCAmelCase_       				=			cached_path(
		    lowerCAmelCase		,	cache_dir=self.cache_dir		,	extract_compressed_file=lowerCAmelCase		,	force_extract=lowerCAmelCase							)

		return os.path.join(lowerCAmelCase		,	self.dummy_file_name							)




	@property
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		return os.path.join(self.datasets_scripts_dir		,	self.dataset_name		,	self.dummy_zip_file							)




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


		'''simple docstring'''







		if self._bucket_url is None:
			UpperCAmelCase_       				=			hf_github_url(self.dataset_name		,	self.dummy_zip_file.replace(os.sep		,	"/"							)							)
		return self._bucket_url




	@property
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		if os.path.isdir(self.dummy_file							):
			return self.dummy_file
		# else cut off path to file -> example `xsum`.
		return "/".join(self.dummy_file.replace(os.sep		,	"/"							).split("/"							)[:-1]							)




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						int		,	*lowerCAmelCase	:						int							):


		'''simple docstring'''







		if self.load_existing_dummy_data:
			# dummy data is downloaded and tested
			UpperCAmelCase_       				=			self.dummy_file
		else:
			# dummy data cannot be downloaded and only the path to dummy file is returned
			UpperCAmelCase_       				=			self.dummy_file_name

		# special case when data_url is a dict
		if isinstance(lowerCAmelCase		,	lowerCAmelCase							):
			return self.create_dummy_data_dict(lowerCAmelCase		,	lowerCAmelCase							)
		elif isinstance(lowerCAmelCase		,	(list, tuple)							):
			return self.create_dummy_data_list(lowerCAmelCase		,	lowerCAmelCase							)
		else:
			return self.create_dummy_data_single(lowerCAmelCase		,	lowerCAmelCase							)




	def       __A					(		self	:						Optional[int]		,	lowerCAmelCase	:						Tuple		,	*lowerCAmelCase	:						Optional[int]							):


		'''simple docstring'''







		return self.download_and_extract(lowerCAmelCase							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Dict							):


		'''simple docstring'''







		return self.download_and_extract(lowerCAmelCase							)




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						List[str]		,	*lowerCAmelCase	:						List[str]		,	**lowerCAmelCase	:						List[Any]							):


		'''simple docstring'''







		return path




	def       __A					(		self	:						str							):


		'''simple docstring'''







		return {}




	def       __A					(		self	:						Tuple		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			{}
		for key, single_urls in data_url.items():
			for download_callback in self.download_callbacks:
				if isinstance(lowerCAmelCase		,	lowerCAmelCase							):
					for single_url in single_urls:
						download_callback(lowerCAmelCase							)
				else:
					UpperCAmelCase_       				=			single_urls
					download_callback(lowerCAmelCase							)
            # we force the name of each key to be the last file / folder name of the url path
            # if the url has arguments, we need to encode them with urllib.parse.quote_plus
			if isinstance(lowerCAmelCase		,	lowerCAmelCase							):
				UpperCAmelCase_       				=			[os.path.join(lowerCAmelCase		,	urllib.parse.quote_plus(Path(lowerCAmelCase							).name							)							) for x in single_urls]
			else:
				UpperCAmelCase_       				=			single_urls
				UpperCAmelCase_       				=			os.path.join(lowerCAmelCase		,	urllib.parse.quote_plus(Path(lowerCAmelCase							).name							)							)
			UpperCAmelCase_       				=			value

		# make sure that values are unique
		if all(isinstance(lowerCAmelCase		,	lowerCAmelCase							) for i in dummy_data_dict.values()							) and len(set(dummy_data_dict.values()							)							) < len(
		    dummy_data_dict.values()							):
			# append key to value to make its name unique
			UpperCAmelCase_       				=			{key: value + key for key, value in dummy_data_dict.items()}

		return dummy_data_dict




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			[]
		# trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one
		UpperCAmelCase_       				=			all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}"		,	lowerCAmelCase							)							) for url in data_url							)
		UpperCAmelCase_       				=			all(
		    url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed"							) for url in data_url							)
		if data_url and (is_tf_records or is_pubmed_records):
			UpperCAmelCase_       				=			[data_url[0]] * len(lowerCAmelCase							)
		for single_url in data_url:
			for download_callback in self.download_callbacks:
				download_callback(lowerCAmelCase							)
			# we force the name of each key to be the last file / folder name of the url path
			# if the url has arguments, we need to encode them with urllib.parse.quote_plus
			UpperCAmelCase_       				=			os.path.join(lowerCAmelCase		,	urllib.parse.quote_plus(single_url.split("/"							)[-1]							)							)
			dummy_data_list.append(lowerCAmelCase							)
		return dummy_data_list




	def       __A					(		self	:						Union[str, Any]		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						List[Any]							):


		'''simple docstring'''







		for download_callback in self.download_callbacks:
			download_callback(lowerCAmelCase							)
		# we force the name of each key to be the last file / folder name of the url path
		# if the url has arguments, we need to encode them with urllib.parse.quote_plus
		UpperCAmelCase_       				=			os.path.join(lowerCAmelCase		,	urllib.parse.quote_plus(data_url.split("/"							)[-1]							)							)
		if os.path.exists(lowerCAmelCase							) or not self.load_existing_dummy_data:
			return value
		else:
			# Backward compatibility, maybe deprecate at one point.
			# For many datasets with single url calls to dl_manager.download_and_extract,
			# the dummy_data.zip file is actually the zipped downloaded file
			# while now we expected the dummy_data.zip file to be a directory containing
			# the downloaded file.
			return path_to_dummy_data




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						str		,	lowerCAmelCase	:						Optional[int]							):


		'''simple docstring'''







		def _iter_archive_members(lowerCAmelCase	:						str							):
			# this preserves the order of the members inside the ZIP archive
			UpperCAmelCase_       				=			Path(self.dummy_file							).parent
			UpperCAmelCase_       				=			path.relative_to(lowerCAmelCase							)
			with ZipFile(self.local_path_to_dummy_data							) as zip_file:
				UpperCAmelCase_       				=			zip_file.namelist()
			for member in members:
				if member.startswith(relative_path.as_posix()							):
					yield dummy_parent_path.joinpath(lowerCAmelCase							)

		UpperCAmelCase_       				=			Path(lowerCAmelCase							)
		UpperCAmelCase_       				=			_iter_archive_members(lowerCAmelCase							) if self.use_local_dummy_data else path.rglob("*"							)
		for file_path in file_paths:
			if file_path.is_file() and not file_path.name.startswith((".", "__")							):
				yield file_path.relative_to(lowerCAmelCase							).as_posix(), file_path.open("rb"							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						List[Any]							):


		'''simple docstring'''







		if not isinstance(lowerCAmelCase		,	lowerCAmelCase							):
			UpperCAmelCase_       				=			[paths]
		for path in paths:
			if os.path.isfile(lowerCAmelCase							):
				if os.path.basename(lowerCAmelCase							).startswith((".", "__")							):
					return
				yield path
			else:
				for dirpath, dirnames, filenames in os.walk(lowerCAmelCase							):
					if os.path.basename(lowerCAmelCase							).startswith((".", "__")							):
						continue
					dirnames.sort()
					for filename in sorted(lowerCAmelCase							):
						if filename.startswith((".", "__")							):
							continue
						yield os.path.join(lowerCAmelCase		,	lowerCAmelCase							)


import json
import os
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:    List[Any] 							=			logging.get_logger(__name__)

_a:    List[str] 							=			"""▁"""

_a:    Union[str, Any] 							=			{
    """vocab_file""": """vocab.json""",
    """spm_file""": """sentencepiece.bpe.model""",
}

_a:    Tuple 							=			{
    """vocab_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json"""
        ),
    },
    """spm_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model"""
        )
    },
}

_a:    Optional[int] 							=			{
    """facebook/s2t-small-librispeech-asr""": 1024,
}

_a:    List[Any] 							=			["""pt""", """fr""", """ru""", """nl""", """ro""", """it""", """es""", """de"""]

_a:    Tuple 							=			{"""mustc""": MUSTC_LANGS}

class 						__UpperCamelCase    (					lowercase						):
	SCREAMING_SNAKE_CASE__    				=     VOCAB_FILES_NAMES
	SCREAMING_SNAKE_CASE__    				=     PRETRAINED_VOCAB_FILES_MAP
	SCREAMING_SNAKE_CASE__    				=     MAX_MODEL_INPUT_SIZES
	SCREAMING_SNAKE_CASE__    				=     ['input_ids', 'attention_mask']

	SCREAMING_SNAKE_CASE__    				=     []




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


		'''simple docstring'''







		UpperCAmelCase_       				=			{} if sp_model_kwargs is None else sp_model_kwargs

		super().__init__(
		    bos_token=lowerCAmelCase		,	eos_token=lowerCAmelCase		,	unk_token=lowerCAmelCase		,	pad_token=lowerCAmelCase		,	do_upper_case=lowerCAmelCase		,	do_lower_case=lowerCAmelCase		,	tgt_lang=lowerCAmelCase		,	lang_codes=lowerCAmelCase		,	sp_model_kwargs=self.sp_model_kwargs		,	**lowerCAmelCase		,	)
		UpperCAmelCase_       				=			do_upper_case
		UpperCAmelCase_       				=			do_lower_case

		UpperCAmelCase_       				=			load_json(lowerCAmelCase							)
		UpperCAmelCase_       				=			{v: k for k, v in self.encoder.items()}
		UpperCAmelCase_       				=			spm_file
		UpperCAmelCase_       				=			load_spm(lowerCAmelCase		,	self.sp_model_kwargs							)

		if lang_codes is not None:
			UpperCAmelCase_       				=			lang_codes
			UpperCAmelCase_       				=			LANGUAGES[lang_codes]
			UpperCAmelCase_       				=			[F"<lang:{lang}>" for lang in self.langs]
			UpperCAmelCase_       				=			{lang: self.sp_model.PieceToId(F"<lang:{lang}>"							) for lang in self.langs}

			UpperCAmelCase_       				=			self.lang_tokens
			UpperCAmelCase_       				=			tgt_lang if tgt_lang is not None else self.langs[0]

			self.set_tgt_lang_special_tokens(self._tgt_lang							)
		else:
			UpperCAmelCase_       				=			{}




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


		'''simple docstring'''







		return len(self.encoder							)




	@property
	def       __A					(		self	:						Any							):


		'''simple docstring'''







		return self._tgt_lang




	@tgt_lang.setter
	def       __A					(		self	:						int		,	lowerCAmelCase	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			new_tgt_lang
		self.set_tgt_lang_special_tokens(lowerCAmelCase							)




	def       __A					(		self	:						List[Any]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.lang_code_to_id[tgt_lang]
		UpperCAmelCase_       				=			[lang_code_id]




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		return self.sp_model.encode(lowerCAmelCase		,	out_type=lowerCAmelCase							)




	def       __A					(		self	:						str		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







		return self.encoder.get(lowerCAmelCase		,	self.encoder[self.unk_token]							)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







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




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			[]
		UpperCAmelCase_       				=			""
		for token in tokens:
			# make sure that special tokens are not decoded using sentencepiece model
			if token in self.all_special_tokens:
				UpperCAmelCase_       				=			self.sp_model.decode(lowerCAmelCase							)
				out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
				UpperCAmelCase_       				=			[]
			else:
				current_sub_tokens.append(lowerCAmelCase							)
		UpperCAmelCase_       				=			self.sp_model.decode(lowerCAmelCase							)
		out_string += decoded.upper() if self.do_upper_case else decoded
		return out_string.strip()




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Optional[int]=None							):


		'''simple docstring'''







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




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						List[int]		,	lowerCAmelCase	:						Optional[List[int]] = None		,	lowerCAmelCase	:						bool = False							):


		'''simple docstring'''







		if already_has_special_tokens:
			return super().get_special_tokens_mask(
			    token_ids_a=lowerCAmelCase		,	token_ids_a=lowerCAmelCase		,	already_has_special_tokens=lowerCAmelCase							)

		UpperCAmelCase_       				=			[1] * len(self.prefix_tokens							)
		UpperCAmelCase_       				=			[1]
		if token_ids_a is None:
			return prefix_ones + ([0] * len(lowerCAmelCase							)) + suffix_ones
		return prefix_ones + ([0] * len(lowerCAmelCase							)) + ([0] * len(lowerCAmelCase							)) + suffix_ones




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.encoder.copy()
		vocab.update(self.added_tokens_encoder							)
		return vocab




	def __getstate__(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.__dict__.copy()
		UpperCAmelCase_       				=			None
		return state




	def __setstate__(		self	:						Tuple		,	lowerCAmelCase	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			d

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

		UpperCAmelCase_       				=			load_spm(self.spm_file		,	self.sp_model_kwargs							)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Optional[str] = None							):


		'''simple docstring'''







		UpperCAmelCase_       				=			Path(lowerCAmelCase							)
		assert save_dir.is_dir(), F"{save_directory} should be a directory"
		UpperCAmelCase_       				=			save_dir / (
		    (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
		)
		UpperCAmelCase_       				=			save_dir / (
		    (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
		)

		save_json(self.encoder		,	lowerCAmelCase							)

		if os.path.abspath(self.spm_file							) != os.path.abspath(lowerCAmelCase							) and os.path.isfile(self.spm_file							):
			copyfile(self.spm_file		,	lowerCAmelCase							)
		elif not os.path.isfile(self.spm_file							):
			with open(lowerCAmelCase		,	"wb"							) as fi:
				UpperCAmelCase_       				=			self.sp_model.serialized_model_proto()
				fi.write(lowerCAmelCase							)

		return (str(lowerCAmelCase							), str(lowerCAmelCase							))



def       __lowerCAmelCase      (						A       ,     A    ):
	UpperCAmelCase_       				=			sentencepiece.SentencePieceProcessor(**A    )
	spm.Load(str(A    )    )
	return spm



def       __lowerCAmelCase      (						A    ):
	with open(A       ,     "r"    ) as f:
		return json.load(A    )




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