



import json
import os
import unittest

from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast
from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class  __snake_case      (   SCREAMING_SNAKE_CASE			,unittest.TestCase):







							'''simple docstring'''






							UpperCamelCase__				:      str         =					GPTaTokenizer
							UpperCamelCase__				:      Dict         =					GPTaTokenizerFast
							UpperCamelCase__				:      List[Any]         =					True
							UpperCamelCase__				:      int         =					{"""add_prefix_space""": True}
							UpperCamelCase__				:      Optional[Any]         =					False


							def _a      (							self		):
											super().setUp()

											# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
											a__				      =		[
											    """l""",
											    """o""",
											    """w""",
											    """e""",
											    """r""",
											    """s""",
											    """t""",
											    """i""",
											    """d""",
											    """n""",
											    """\u0120""",
											    """\u0120l""",
											    """\u0120n""",
											    """\u0120lo""",
											    """\u0120low""",
											    """er""",
											    """\u0120lowest""",
											    """\u0120newer""",
											    """\u0120wider""",
											    """<unk>""",
											    """<|endoftext|>""",
											]
											a__				      =		dict(zip(a_  ,  range(len(a_		)		)		)		)
											a__				      =		["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
											a__				      =		{"""unk_token""": """<unk>"""}

											a__				      =		os.path.join(self.tmpdirname  ,  VOCAB_FILES_NAMES["""vocab_file"""]		)
											a__				      =		os.path.join(self.tmpdirname  ,  VOCAB_FILES_NAMES["""merges_file"""]		)
											with open(self.vocab_file  ,  """w"""  ,  encoding="""utf-8"""		) as fp:
															fp.write(json.dumps(a_		) + """\n"""		)
											with open(self.merges_file  ,  """w"""  ,  encoding="""utf-8"""		) as fp:
															fp.write("""\n""".join(a_		)		)


							def _a      (							self  ,  **a_		):
											kwargs.update(self.special_tokens_map		)
											return GPTaTokenizer.from_pretrained(self.tmpdirname  ,  **a_		)


							def _a      (							self  ,  **a_		):
											kwargs.update(self.special_tokens_map		)
											return GPTaTokenizerFast.from_pretrained(self.tmpdirname  ,  **a_		)


							def _a      (							self  ,  a_		):
											a__				      =		"""lower newer"""
											a__				      =		"""lower newer"""
											return input_text, output_text


							def _a      (							self		):
											a__				      =		GPTaTokenizer(self.vocab_file  ,  self.merges_file  ,  **self.special_tokens_map		)
											a__				      =		"""lower newer"""
											a__				      =		["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""]
											a__				      =		tokenizer.tokenize(a_  ,  add_prefix_space=a_		)
											self.assertListEqual(a_  ,  a_		)

											a__				      =		tokens + [tokenizer.unk_token]
											a__				      =		[14, 15, 10, 9, 3, 2, 15, 19]
											self.assertListEqual(tokenizer.convert_tokens_to_ids(a_		)  ,  a_		)


							def _a      (							self		):
											if not self.test_rust_tokenizer:
															return

											a__				      =		self.get_tokenizer()
											a__				      =		self.get_rust_tokenizer(add_prefix_space=a_		)

											a__				      =		"""lower newer"""

											# Testing tokenization
											a__				      =		tokenizer.tokenize(a_  ,  add_prefix_space=a_		)
											a__				      =		rust_tokenizer.tokenize(a_		)
											self.assertListEqual(a_  ,  a_		)

											# Testing conversion to ids without special tokens
											a__				      =		tokenizer.encode(a_  ,  add_special_tokens=a_  ,  add_prefix_space=a_		)
											a__				      =		rust_tokenizer.encode(a_  ,  add_special_tokens=a_		)
											self.assertListEqual(a_  ,  a_		)

											# Testing conversion to ids with special tokens
											a__				      =		self.get_rust_tokenizer(add_prefix_space=a_		)
											a__				      =		tokenizer.encode(a_  ,  add_prefix_space=a_		)
											a__				      =		rust_tokenizer.encode(a_		)
											self.assertListEqual(a_  ,  a_		)

											# Testing the unknown token
											a__				      =		tokens + [rust_tokenizer.unk_token]
											a__				      =		[14, 15, 10, 9, 3, 2, 15, 19]
											self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a_		)  ,  a_		)


							def _a      (							self  ,  *a_  ,  **a_		):
											# It's very difficult to mix/test pretokenization with byte-level
											# And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string)
											pass


							def _a      (							self  ,  a_=15		):
											for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''		):
																			a__				      =		self.rust_tokenizer_class.from_pretrained(a_  ,  **a_		)

																			# Simple input
																			a__				      =		"""This is a simple input"""
																			a__				      =		["""This is a simple input 1""", """This is a simple input 2"""]
																			a__				      =		("""This is a simple input""", """This is a pair""")
																			a__				      =		[
																			    ("""This is a simple input 1""", """This is a simple input 2"""),
																			    ("""This is a simple pair 1""", """This is a simple pair 2"""),
																			]

																			# Simple input tests
																			self.assertRaises(a_  ,  tokenizer_r.encode  ,  a_  ,  max_length=a_  ,  padding="""max_length"""		)

																			# Simple input
																			self.assertRaises(a_  ,  tokenizer_r.encode_plus  ,  a_  ,  max_length=a_  ,  padding="""max_length"""		)

																			# Simple input
																			self.assertRaises(
																			    a_  ,  tokenizer_r.batch_encode_plus  ,  a_  ,  max_length=a_  ,  padding="""max_length"""  ,  )

																			# Pair input
																			self.assertRaises(a_  ,  tokenizer_r.encode  ,  a_  ,  max_length=a_  ,  padding="""max_length"""		)

																			# Pair input
																			self.assertRaises(a_  ,  tokenizer_r.encode_plus  ,  a_  ,  max_length=a_  ,  padding="""max_length"""		)

																			# Pair input
																			self.assertRaises(
																			    a_  ,  tokenizer_r.batch_encode_plus  ,  a_  ,  max_length=a_  ,  padding="""max_length"""  ,  )


							def _a      (							self		):
											a__				      =		GPTaTokenizer.from_pretrained(self.tmpdirname  ,  pad_token="""<pad>"""		)

											# Simple input
											a__				      =		"""This is a simple input"""
											a__				      =		["""This is a simple input looooooooong""", """This is a simple input"""]
											a__				      =		("""This is a simple input""", """This is a pair""")
											a__				      =		[
											    ("""This is a simple input loooooong""", """This is a simple input"""),
											    ("""This is a simple pair loooooong""", """This is a simple pair"""),
											]

											a__				      =		tokenizer.pad_token_id

											a__				      =		tokenizer(a_  ,  padding="""max_length"""  ,  max_length=30  ,  return_tensors="""np"""		)
											a__				      =		tokenizer(a_  ,  padding=a_  ,  truncate=a_  ,  return_tensors="""np"""		)
											a__				      =		tokenizer(*a_  ,  padding="""max_length"""  ,  max_length=60  ,  return_tensors="""np"""		)
											a__				      =		tokenizer(a_  ,  padding=a_  ,  truncate=a_  ,  return_tensors="""np"""		)

											# s
											# test single string max_length padding
											self.assertEqual(out_s["""input_ids"""].shape[-1]  ,  30		)
											self.assertTrue(pad_token_id in out_s["""input_ids"""]		)
											self.assertTrue(0 in out_s["""attention_mask"""]		)

											# s2
											# test automatic padding
											self.assertEqual(out_sa["""input_ids"""].shape[-1]  ,  33		)
											# long slice doesn't have padding
											self.assertFalse(pad_token_id in out_sa["""input_ids"""][0]		)
											self.assertFalse(0 in out_sa["""attention_mask"""][0]		)
											# short slice does have padding
											self.assertTrue(pad_token_id in out_sa["""input_ids"""][1]		)
											self.assertTrue(0 in out_sa["""attention_mask"""][1]		)

											# p
											# test single pair max_length padding
											self.assertEqual(out_p["""input_ids"""].shape[-1]  ,  60		)
											self.assertTrue(pad_token_id in out_p["""input_ids"""]		)
											self.assertTrue(0 in out_p["""attention_mask"""]		)

											# p2
											# test automatic padding pair
											self.assertEqual(out_pa["""input_ids"""].shape[-1]  ,  52		)
											# long slice pair doesn't have padding
											self.assertFalse(pad_token_id in out_pa["""input_ids"""][0]		)
											self.assertFalse(0 in out_pa["""attention_mask"""][0]		)
											# short slice pair does have padding
											self.assertTrue(pad_token_id in out_pa["""input_ids"""][1]		)
											self.assertTrue(0 in out_pa["""attention_mask"""][1]		)


							def _a      (							self		):
											a__				      =		"""$$$"""
											a__				      =		GPTaTokenizer.from_pretrained(self.tmpdirname  ,  bos_token=a_  ,  add_bos_token=a_		)

											a__				      =		"""This is a simple input"""
											a__				      =		["""This is a simple input 1""", """This is a simple input 2"""]

											a__				      =		tokenizer.bos_token_id

											a__				      =		tokenizer(a_		)
											a__				      =		tokenizer(a_		)

											self.assertEqual(out_s.input_ids[0]  ,  a_		)
											self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids		)		)

											a__				      =		tokenizer.decode(out_s.input_ids		)
											a__				      =		tokenizer.batch_decode(out_sa.input_ids		)

											self.assertEqual(decode_s.split()[0]  ,  a_		)
											self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa		)		)


							def _a      (							self		):
											pass







							def _a      (							self		):
											# TODO: change to self.get_tokenizers() when the fast version is implemented
											a__				      =		[self.get_tokenizer(do_lower_case=a_  ,  add_bos_token=a_		)]
											for tokenizer in tokenizers:
															with self.subTest(F'''{tokenizer.__class__.__name__}'''		):
																			a__				      =		"""Encode this."""
																			a__				      =		"""This one too please."""
																			a__				      =		tokenizer.encode(a_  ,  add_special_tokens=a_		)
																			encoded_sequence += tokenizer.encode(a_  ,  add_special_tokens=a_		)
																			a__				      =		tokenizer.encode_plus(
																			    a_  ,  a_  ,  add_special_tokens=a_  ,  return_special_tokens_mask=a_  ,  )
																			a__				      =		encoded_sequence_dict["""input_ids"""]
																			a__				      =		encoded_sequence_dict["""special_tokens_mask"""]
																			self.assertEqual(len(a_		)  ,  len(a_		)		)

																			a__				      =		[
																			    (x if not special_tokens_mask[i] else None) for i, x in enumerate(a_		)
																			]
																			a__				      =		[x for x in filtered_sequence if x is not None]
																			self.assertEqual(a_  ,  a_		)




@require_tokenizers
class  __snake_case      (   unittest.TestCase):







							'''simple docstring'''






							def _a      (							self		):
											# More context:
											# https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1
											# https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519
											# https://github.com/huggingface/transformers/pull/17088#discussion_r871246439

											a__				      =		AutoTokenizer.from_pretrained("""facebook/opt-350m"""  ,  from_slow=a_		)
											a__				      =		"""A photo of a cat"""

											a__				      =		tokenizer.encode(
											    a_  ,  )
											self.assertEqual(a_  ,  [2, 250, 1_345, 9, 10, 4_758]		)
											tokenizer.save_pretrained("""test_opt"""		)

											a__				      =		AutoTokenizer.from_pretrained("""./test_opt"""		)
											a__				      =		tokenizer.encode(
											    a_  ,  )
											self.assertEqual(a_  ,  [2, 250, 1_345, 9, 10, 4_758]		)


							def _a      (							self		):
											a__				      =		AutoTokenizer.from_pretrained("""facebook/opt-350m"""  ,  use_slow=a_		)
											a__				      =		"""A photo of a cat"""

											a__				      =		tokenizer.encode(
											    a_  ,  )
											# Same as above
											self.assertEqual(a_  ,  [2, 250, 1_345, 9, 10, 4_758]		)







							@unittest.skip("""This test is failing because of a bug in the fast tokenizer"""		)
							def _a      (							self		):
											a__				      =		AutoTokenizer.from_pretrained("""facebook/opt-350m"""  ,  from_slow=a_		)

											a__				      =		"""bos"""
											a__				      =		tokenizer.get_vocab()["""bos"""]

											a__				      =		"""A photo of a cat"""
											a__				      =		tokenizer.encode(
											    a_  ,  )
											# We changed the bos token
											self.assertEqual(a_  ,  [31_957, 250, 1_345, 9, 10, 4_758]		)
											tokenizer.save_pretrained("""./tok"""		)
											a__				      =		AutoTokenizer.from_pretrained("""./tok"""		)
											self.assertTrue(tokenizer.is_fast		)
											a__				      =		tokenizer.encode(
											    a_  ,  )
											self.assertEqual(a_  ,  [31_957, 250, 1_345, 9, 10, 4_758]		)







import os
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union

import numpy as np
import pyarrow as pa

from .. import config
from ..download.streaming_download_manager import xopen, xsplitext
from ..table import array_cast
from ..utils.py_utils import no_op_if_value_is_null, string_to_dict


if TYPE_CHECKING:
	from .features import FeatureType


UpperCAmelCase ,       UpperCAmelCase ,       UpperCAmelCase							 =					False, False, False

@dataclass
class  __snake_case      :







							'''simple docstring'''






							UpperCamelCase__				:      Optional[int]         =					None
							UpperCamelCase__				:      bool         =					True
							UpperCamelCase__				:      bool         =					True
							UpperCamelCase__				:      Optional[str]         =					None
							# Automatically constructed
							UpperCamelCase__				:      ClassVar[str]         =					"dict"
							UpperCamelCase__				:      ClassVar[Any]         =					pa.struct({"""bytes""": pa.binary(), """path""": pa.string()})
							UpperCamelCase__				:      str         =					field(default="""Audio"""			,init=SCREAMING_SNAKE_CASE			,repr=SCREAMING_SNAKE_CASE)


							def __call__(							self		):
											return self.pa_type


							def _a      (							self  ,  a_		):
											try:
															import soundfile as sf  # soundfile is a dependency of librosa, needed to decode audio files.
											except ImportError as err:
															raise ImportError("""To support encoding audio data, please install 'soundfile'."""		) from err
											if isinstance(a_  ,  a_		):
															return {"bytes": None, "path": value}
											elif isinstance(a_  ,  a_		):
															return {"bytes": value, "path": None}
											elif "array" in value:
															# convert the audio array to wav bytes
															a__				      =		BytesIO()
															sf.write(a_  ,  value["""array"""]  ,  value["""sampling_rate"""]  ,  format="""wav"""		)
															return {"bytes": buffer.getvalue(), "path": None}
											elif value.get("""path"""		) is not None and os.path.isfile(value["""path"""]		):
															# we set "bytes": None to not duplicate the data if they're already available locally
															if value["path"].endswith("""pcm"""		):
																			# "PCM" only has raw audio bytes
																			if value.get("""sampling_rate"""		) is None:
																							# At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate
																							raise KeyError("""To use PCM files, please specify a 'sampling_rate' in Audio object"""		)
																			if value.get("""bytes"""		):
																							# If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!)
																							a__				      =		np.frombuffer(value["""bytes"""]  ,  dtype=np.intaa		).astype(np.floataa		) / 32_767
																			else:
																							a__				      =		np.memmap(value["""path"""]  ,  dtype="""h"""  ,  mode="""r"""		).astype(np.floataa		) / 32_767

																			a__				      =		BytesIO(bytes()		)
																			sf.write(a_  ,  a_  ,  value["""sampling_rate"""]  ,  format="""wav"""		)
																			return {"bytes": buffer.getvalue(), "path": None}
															else:
																			return {"bytes": None, "path": value.get("""path"""		)}
											elif value.get("""bytes"""		) is not None or value.get("""path"""		) is not None:
															# store the audio bytes, and path is used to infer the audio format using the file extension
															return {"bytes": value.get("""bytes"""		), "path": value.get("""path"""		)}
											else:
															raise ValueError(
															    F'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.'''		)


							def _a      (							self  ,  a_  ,  a_ = None		):
											if not self.decode:
															raise RuntimeError("""Decoding is disabled for this feature. Please use Audio(decode=True) instead."""		)

											a__      ,			a__				      =		(value["""path"""], BytesIO(value["""bytes"""]		)) if value["""bytes"""] is not None else (value["""path"""], None)
											if path is None and file is None:
															raise ValueError(F'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.'''		)

											try:
															import librosa
															import soundfile as sf
											except ImportError as err:
															raise ImportError("""To support decoding audio files, please install 'librosa' and 'soundfile'."""		) from err

											a__				      =		xsplitext(a_		)[1][1:].lower() if path is not None else None
											if not config.IS_OPUS_SUPPORTED and audio_format == "opus":
															raise RuntimeError(
															    """Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, """
															    """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """		)
											elif not config.IS_MP3_SUPPORTED and audio_format == "mp3":
															raise RuntimeError(
															    """Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, """
															    """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """		)

											if file is None:
															a__				      =		token_per_repo_id or {}
															a__				      =		path.split("""::"""		)[-1]
															try:
																			a__				      =		string_to_dict(a_  ,  config.HUB_DATASETS_URL		)["""repo_id"""]
																			a__				      =		token_per_repo_id[repo_id]
															except (ValueError, KeyError):
																			a__				      =		None

															with xopen(a_  ,  """rb"""  ,  use_auth_token=a_		) as f:
																			a__      ,			a__				      =		sf.read(a_		)

											else:
															a__      ,			a__				      =		sf.read(a_		)

											a__				      =		array.T
											if self.mono:
															a__				      =		librosa.to_mono(a_		)
											if self.sampling_rate and self.sampling_rate != sampling_rate:
															a__				      =		librosa.resample(a_  ,  orig_sr=a_  ,  target_sr=self.sampling_rate		)
															a__				      =		self.sampling_rate

											return {"path": path, "array": array, "sampling_rate": sampling_rate}


							def _a      (							self		):
											from .features import Value

											if self.decode:
															raise ValueError("""Cannot flatten a decoded Audio feature."""		)
											return {
											    "bytes": Value("""binary"""		),
											    "path": Value("""string"""		),
											}


							def _a      (							self  ,  a_		):
											if pa.types.is_string(storage.type		):
															a__				      =		pa.array([None] * len(a_		)  ,  type=pa.binary()		)
															a__				      =		pa.StructArray.from_arrays([bytes_array, storage]  ,  ["""bytes""", """path"""]  ,  mask=storage.is_null()		)
											elif pa.types.is_binary(storage.type		):
															a__				      =		pa.array([None] * len(a_		)  ,  type=pa.string()		)
															a__				      =		pa.StructArray.from_arrays([storage, path_array]  ,  ["""bytes""", """path"""]  ,  mask=storage.is_null()		)
											elif pa.types.is_struct(storage.type		) and storage.type.get_all_field_indices("""array"""		):
															a__				      =		pa.array([Audio().encode_example(a_		) if x is not None else None for x in storage.to_pylist()]		)
											elif pa.types.is_struct(storage.type		):
															if storage.type.get_field_index("""bytes"""		) >= 0:
																			a__				      =		storage.field("""bytes"""		)
															else:
																			a__				      =		pa.array([None] * len(a_		)  ,  type=pa.binary()		)
															if storage.type.get_field_index("""path"""		) >= 0:
																			a__				      =		storage.field("""path"""		)
															else:
																			a__				      =		pa.array([None] * len(a_		)  ,  type=pa.string()		)
															a__				      =		pa.StructArray.from_arrays([bytes_array, path_array]  ,  ["""bytes""", """path"""]  ,  mask=storage.is_null()		)
											return array_cast(a_  ,  self.pa_type		)







							def _a      (							self  ,  a_		):

											@no_op_if_value_is_null
											def path_to_bytes(a_		):
															with xopen(a_  ,  """rb"""		) as f:
																			a__				      =		f.read()
															return bytes_

											a__				      =		pa.array(
											    [
											        (path_to_bytes(x["""path"""]		) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None
											        for x in storage.to_pylist()
											    ]  ,  type=pa.binary()  ,  )
											a__				      =		pa.array(
											    [os.path.basename(a_		) if path is not None else None for path in storage.field("""path"""		).to_pylist()]  ,  type=pa.string()  ,  )
											a__				      =		pa.StructArray.from_arrays([bytes_array, path_array]  ,  ["""bytes""", """path"""]  ,  mask=bytes_array.is_null()		)
											return array_cast(a_  ,  self.pa_type		)

