






'''simple docstring'''





from abc import ABC, abstractmethod
from typing import List, Optional


class      lowercase__     (			lowercase__	):

	def __init__(							self       )->					Optional[Any]:







							'''simple docstring'''





							self.test()

	def 		UpperCAmelCase  (							self       )->					Any:







							'''simple docstring'''





							lowerCAmelCase__       =						0
							lowerCAmelCase__       =						False
							while not completed:
													if counter == 1:
																			self.reset()
													lowerCAmelCase__       =						self.advance()
													if not self.does_advance(__lowerCamelCase       ):
																			raise Exception(
																			    "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."       )

													lowerCAmelCase__       =						self.update(__lowerCamelCase       )
													counter += 1

													if counter > 10000:
																			raise Exception("update() does not fulfill the constraint."       )

							if self.remaining() != 0:
													raise Exception("Custom Constraint is not defined correctly."       )

	@abstractmethod
	def 		UpperCAmelCase  (							self       )->					Any:







							'''simple docstring'''





							raise NotImplementedError(
							    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."       )

	@abstractmethod
	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Optional[int]:







							'''simple docstring'''





							raise NotImplementedError(
							    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."       )

	@abstractmethod
	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Optional[int]:







							'''simple docstring'''





							raise NotImplementedError(
							    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."       )

	@abstractmethod
	def 		UpperCAmelCase  (							self       )->					Tuple:







							'''simple docstring'''





							raise NotImplementedError(
							    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."       )

	@abstractmethod
	def 		UpperCAmelCase  (							self       )->					str:







							'''simple docstring'''





							raise NotImplementedError(
							    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."       )


	@abstractmethod
	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase=False       )->					int:







							'''simple docstring'''





							raise NotImplementedError(
							    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."       )





class      lowercase__     (			lowercase__	):

	def __init__(							self		,    __UpperCAmelCase       )->					List[str]:







							'''simple docstring'''





							super(__lowerCamelCase		,    self       ).__init__()

							if not isinstance(__lowerCamelCase		,    __lowerCamelCase       ) or len(__lowerCamelCase       ) == 0:
													raise ValueError(F"`token_ids` has to be a non-empty list, but is {token_ids}."       )
							if any((not isinstance(__lowerCamelCase		,    __lowerCamelCase       ) or token_id < 0) for token_id in token_ids       ):
													raise ValueError(F"Each list in `token_ids` has to be a list of positive integers, but is {token_ids}."       )

							lowerCAmelCase__       =						token_ids

							lowerCAmelCase__       =						len(self.token_ids       )
							lowerCAmelCase__       =						-1  # the index of the currently fulfilled step
							lowerCAmelCase__       =						False

	def 		UpperCAmelCase  (							self       )->					Any:







							'''simple docstring'''





							if self.completed:
													return None
							return self.token_ids[self.fulfilled_idx + 1]

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Dict:







							'''simple docstring'''





							if not isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
													raise ValueError(F"`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase       )}"       )

							if self.completed:
													return False

							return token_id == self.token_ids[self.fulfilled_idx + 1]

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Tuple:







							'''simple docstring'''





							if not isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
													raise ValueError(F"`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase       )}"       )

							lowerCAmelCase__       =						False
							lowerCAmelCase__       =						False
							lowerCAmelCase__       =						False

							if self.does_advance(__lowerCamelCase       ):
													self.fulfilled_idx += 1
													lowerCAmelCase__       =						True
													if self.fulfilled_idx == (self.seqlen - 1):
																			lowerCAmelCase__       =						True
													lowerCAmelCase__       =						completed
							else:
													# failed to make progress.
													lowerCAmelCase__       =						True
													self.reset()
							return stepped, completed, reset

	def 		UpperCAmelCase  (							self       )->					Dict:







							'''simple docstring'''





							lowerCAmelCase__       =						False
							lowerCAmelCase__       =						0

	def 		UpperCAmelCase  (							self       )->					Optional[Any]:







							'''simple docstring'''





							return self.seqlen - (self.fulfilled_idx + 1)


	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase=False       )->					Dict:







							'''simple docstring'''





							lowerCAmelCase__       =						PhrasalConstraint(self.token_ids       )

							if stateful:
													lowerCAmelCase__       =						self.seqlen
													lowerCAmelCase__       =						self.fulfilled_idx
													lowerCAmelCase__       =						self.completed

							return new_constraint





class      lowercase__     :

	def __init__(							self		,    __UpperCAmelCase		,    __UpperCAmelCase=True       )->					Union[str, Any]:







							'''simple docstring'''





							lowerCAmelCase__       =						max([len(__lowerCamelCase       ) for one in nested_token_ids]       )

							lowerCAmelCase__       =						{}
							for token_ids in nested_token_ids:
													lowerCAmelCase__       =						root
													for tidx, token_id in enumerate(__lowerCamelCase       ):
																			if token_id not in level:
																									lowerCAmelCase__       =						{}

																			lowerCAmelCase__       =						level[token_id]

							if no_subsets and self.has_subsets(__lowerCamelCase		,    __lowerCamelCase       ):
													raise ValueError(
													    "Each list in `nested_token_ids` can't be a complete subset of another list, but is"
													    F" {nested_token_ids}."       )

							lowerCAmelCase__       =						root

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Optional[Any]:







							'''simple docstring'''





							lowerCAmelCase__       =						self.trie

							for current_token in current_seq:
													lowerCAmelCase__       =						start[current_token]

							lowerCAmelCase__       =						list(start.keys()       )

							return next_tokens

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Optional[Any]:







							'''simple docstring'''





							lowerCAmelCase__       =						self.next_tokens(__lowerCamelCase       )

							return len(__lowerCamelCase       ) == 0

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					str:







							'''simple docstring'''





							lowerCAmelCase__       =						list(root.values()       )
							if len(__lowerCamelCase       ) == 0:
													return 1
							else:
													return sum([self.count_leaves(__lowerCamelCase       ) for nn in next_nodes]       )


	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase		,    __UpperCAmelCase       )->					Any:







							'''simple docstring'''





							lowerCAmelCase__       =						self.count_leaves(__lowerCamelCase       )
							return len(__lowerCamelCase       ) != leaf_count





class      lowercase__     (			lowercase__	):

	def __init__(							self		,    __UpperCAmelCase       )->					str:







							'''simple docstring'''





							super(__lowerCamelCase		,    self       ).__init__()

							if not isinstance(__lowerCamelCase		,    __lowerCamelCase       ) or len(__lowerCamelCase       ) == 0:
													raise ValueError(F"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."       )
							if any(not isinstance(__lowerCamelCase		,    __lowerCamelCase       ) for token_ids in nested_token_ids       ):
													raise ValueError(F"`nested_token_ids` has to be a list of lists, but is {nested_token_ids}."       )
							if any(
							    any((not isinstance(__lowerCamelCase		,    __lowerCamelCase       ) or token_id < 0) for token_id in token_ids       )
							    for token_ids in nested_token_ids       ):
													raise ValueError(
													    F"Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}."       )

							lowerCAmelCase__       =						DisjunctiveTrie(__lowerCamelCase       )
							lowerCAmelCase__       =						nested_token_ids

							lowerCAmelCase__       =						self.trie.max_height
							lowerCAmelCase__       =						[]
							lowerCAmelCase__       =						False

	def 		UpperCAmelCase  (							self       )->					List[str]:







							'''simple docstring'''





							lowerCAmelCase__       =						self.trie.next_tokens(self.current_seq       )

							if len(__lowerCamelCase       ) == 0:
													return None
							else:
													return token_list

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					str:







							'''simple docstring'''





							if not isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
													raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase       )}"       )

							lowerCAmelCase__       =						self.trie.next_tokens(self.current_seq       )

							return token_id in next_tokens

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Dict:







							'''simple docstring'''





							if not isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
													raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase       )}"       )

							lowerCAmelCase__       =						False
							lowerCAmelCase__       =						False
							lowerCAmelCase__       =						False

							if self.does_advance(__lowerCamelCase       ):
													self.current_seq.append(__lowerCamelCase       )
													lowerCAmelCase__       =						True
							else:
													lowerCAmelCase__       =						True
													self.reset()

							lowerCAmelCase__       =						self.trie.reached_leaf(self.current_seq       )
							lowerCAmelCase__       =						completed

							return stepped, completed, reset

	def 		UpperCAmelCase  (							self       )->					Optional[Any]:







							'''simple docstring'''





							lowerCAmelCase__       =						False
							lowerCAmelCase__       =						[]

	def 		UpperCAmelCase  (							self       )->					List[str]:







							'''simple docstring'''





							if self.completed:
													# since this can be completed without reaching max height
													return 0
							else:
													return self.seqlen - len(self.current_seq       )


	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase=False       )->					int:







							'''simple docstring'''





							lowerCAmelCase__       =						DisjunctiveConstraint(self.token_ids       )

							if stateful:
													lowerCAmelCase__       =						self.seqlen
													lowerCAmelCase__       =						self.current_seq
													lowerCAmelCase__       =						self.completed

							return new_constraint





class      lowercase__     :

	def __init__(							self		,    __UpperCAmelCase       )->					Optional[int]:







							'''simple docstring'''





							lowerCAmelCase__       =						constraints

							# max # of steps required to fulfill a given constraint
							lowerCAmelCase__       =						max([c.seqlen for c in constraints]       )
							lowerCAmelCase__       =						len(__lowerCamelCase       )
							lowerCAmelCase__       =						False

							self.init_state()

	def 		UpperCAmelCase  (							self       )->					Dict:







							'''simple docstring'''





							lowerCAmelCase__       =						[]
							lowerCAmelCase__       =						None
							lowerCAmelCase__       =						[constraint.copy(stateful=__lowerCamelCase       ) for constraint in self.constraints]

	def 		UpperCAmelCase  (							self       )->					Tuple:







							'''simple docstring'''





							lowerCAmelCase__       =						0
							if self.inprogress_constraint:
													# extra points for having a constraint mid-fulfilled
													add += self.max_seqlen - self.inprogress_constraint.remaining()

							return (len(self.complete_constraints       ) * self.max_seqlen) + add

	def 		UpperCAmelCase  (							self       )->					int:







							'''simple docstring'''





							lowerCAmelCase__       =						[]
							if self.inprogress_constraint is None:
													for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
																			lowerCAmelCase__       =						constraint.advance()
																			if isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
																									token_list.append(__lowerCamelCase       )
																			elif isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
																									token_list.extend(__lowerCamelCase       )
							else:
													lowerCAmelCase__       =						self.inprogress_constraint.advance()
													if isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
																			token_list.append(__lowerCamelCase       )
													elif isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
																			token_list.extend(__lowerCamelCase       )

							if len(__lowerCamelCase       ) == 0:
													return None
							else:
													return token_list

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					int:







							'''simple docstring'''





							self.init_state()

							if token_ids is not None:
													for token in token_ids:
																			# completes or steps **one** constraint
																			lowerCAmelCase__       =						self.add(__lowerCamelCase       )

																			# the entire list of constraints are fulfilled
																			if self.completed:
																									break

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Dict:







							'''simple docstring'''





							if not isinstance(__lowerCamelCase		,    __lowerCamelCase       ):
													raise ValueError(F"`token_id` should be an `int`, but is `{token_id}`."       )

							lowerCAmelCase__       =						False, False

							if self.completed:
													lowerCAmelCase__       =						True
													lowerCAmelCase__       =						False
													return complete, stepped

							if self.inprogress_constraint is not None:
													# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
													# job, simply update the state

													lowerCAmelCase__       =						self.inprogress_constraint.update(__lowerCamelCase       )
													if reset:
																			# 1. If the next token breaks the progress, then we must restart.
																			#     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

																			#     But that doesn't mean we self.init_state(), since we only reset the state for this particular
																			#     constraint, not the full list of constraints.

																			self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__lowerCamelCase       )       )
																			lowerCAmelCase__       =						None

													if complete:
																			# 2. If the next token completes the constraint, move it to completed list, set
																			#     inprogress to None. If there are no pending constraints either, then this full list of constraints
																			#     is complete.

																			self.complete_constraints.append(self.inprogress_constraint       )
																			lowerCAmelCase__       =						None

																			if len(self.pending_constraints       ) == 0:
																									# we're done!
																									lowerCAmelCase__       =						True

							else:
													# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
													# of constraints?

													for cidx, pending_constraint in enumerate(self.pending_constraints       ):
																			if pending_constraint.does_advance(__lowerCamelCase       ):
																									lowerCAmelCase__       =						pending_constraint.update(__lowerCamelCase       )

																									if not stepped:
																															raise Exception(
																															    "`constraint.update(token_id)` is not yielding incremental progress, "
																															    "even though `constraint.does_advance(token_id)` is true."       )

																									if complete:
																															self.complete_constraints.append(__lowerCamelCase       )
																															lowerCAmelCase__       =						None

																									if not complete and stepped:
																															lowerCAmelCase__       =						pending_constraint

																									if complete or stepped:
																															# If we made any progress at all, then it's at least not a "pending constraint".

																															lowerCAmelCase__       =						(
																															    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
																															)

																															if len(self.pending_constraints       ) == 0 and self.inprogress_constraint is None:
																																					# If there's no longer any pending after this and no inprogress either, then we must be
																																					# complete.

																																					lowerCAmelCase__       =						True

																															break  # prevent accidentally stepping through multiple constraints with just one token.

							return complete, stepped


	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase=True       )->					Any:







							'''simple docstring'''





							lowerCAmelCase__       =						ConstraintListState(self.constraints       )  # we actually never though self.constraints objects
							# throughout this process. So it's at initialization state.

							if stateful:
													lowerCAmelCase__       =						[
													    constraint.copy(stateful=__lowerCamelCase       ) for constraint in self.complete_constraints
													]
													if self.inprogress_constraint is not None:
																			lowerCAmelCase__       =						self.inprogress_constraint.copy(stateful=__lowerCamelCase       )
													lowerCAmelCase__       =						[constraint.copy() for constraint in self.pending_constraints]

							return new_state














import unittest

from datasets import load_dataset

from transformers import BloomTokenizerFast
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin


@require_tokenizers
class      lowercase__     (			_UpperCAmelCase,					unittest.TestCase	):
	a_         =None
	a_         =BloomTokenizerFast
	a_         =BloomTokenizerFast
	a_         =True
	a_         =False
	a_         ="""tokenizer_file"""
	a_         ={"""bos_token""": """<s>""", """eos_token""": """</s>""", """unk_token""": """<unk>""", """pad_token""": """<pad>"""}

	def 		UpperCAmelCase  (							self       )->					int:







							'''simple docstring'''





							super().setUp()
							lowerCAmelCase__       =						BloomTokenizerFast.from_pretrained("bigscience/tokenizer"       )
							tokenizer.save_pretrained(self.tmpdirname       )

	def 		UpperCAmelCase  (							self		,    **__UpperCAmelCase       )->					int:







							'''simple docstring'''





							kwargs.update(self.special_tokens_map       )
							return BloomTokenizerFast.from_pretrained(self.tmpdirname		,    **__UpperCAmelCase       )

	def 		UpperCAmelCase  (							self       )->					Any:







							'''simple docstring'''





							lowerCAmelCase__       =						self.get_rust_tokenizer()

							lowerCAmelCase__       =						["The quick brown fox</s>", "jumps over the lazy dog</s>"]
							lowerCAmelCase__       =						[[2175, 23714, 73173, 144252, 2], [77, 132619, 3478, 368, 109586, 35433, 2]]

							lowerCAmelCase__       =						tokenizer.batch_encode_plus(__UpperCAmelCase       )["input_ids"]
							self.assertListEqual(__UpperCAmelCase		,    __UpperCAmelCase       )

							lowerCAmelCase__       =						tokenizer.batch_decode(__UpperCAmelCase       )
							self.assertListEqual(__UpperCAmelCase		,    __UpperCAmelCase       )

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase=6       )->					str:







							'''simple docstring'''





							for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
													with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"       ):
																			lowerCAmelCase__       =						self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase		,    **__UpperCAmelCase       )
																			# tokenizer_r.pad_token = None # Hotfixing padding = None
																			# Simple input
																			lowerCAmelCase__       =						"This is a simple input"
																			lowerCAmelCase__       =						["This is a simple input 1", "This is a simple input 2"]
																			lowerCAmelCase__       =						("This is a simple input", "This is a pair")
																			lowerCAmelCase__       =						[
																			    ("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
																			try:
																									tokenizer_r.encode(__UpperCAmelCase		,    max_length=__UpperCAmelCase       )
																									tokenizer_r.encode_plus(__UpperCAmelCase		,    max_length=__UpperCAmelCase       )

																									tokenizer_r.batch_encode_plus(__UpperCAmelCase		,    max_length=__UpperCAmelCase       )
																									tokenizer_r.encode(__UpperCAmelCase		,    max_length=__UpperCAmelCase       )
																									tokenizer_r.batch_encode_plus(__UpperCAmelCase		,    max_length=__UpperCAmelCase       )
																			except ValueError:
																									self.fail("Bloom Tokenizer should be able to deal with padding"       )

																			lowerCAmelCase__       =						None  # Hotfixing padding = None
																			self.assertRaises(__UpperCAmelCase		,    tokenizer_r.encode		,    __UpperCAmelCase		,    max_length=__UpperCAmelCase		,    padding="max_length"       )

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

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

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

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

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

	def 		UpperCAmelCase  (							self       )->					int:







							'''simple docstring'''





							lowerCAmelCase__       =						self.get_rust_tokenizer()
							lowerCAmelCase__       =						load_dataset("xnli"		,    "all_languages"		,    split="test"		,    streaming=__UpperCAmelCase       )

							lowerCAmelCase__       =						next(iter(__UpperCAmelCase       )       )["premise"]  # pick up one data
							lowerCAmelCase__       =						list(sample_data.values()       )

							lowerCAmelCase__       =						list(map(tokenizer.encode		,    __UpperCAmelCase       )       )
							lowerCAmelCase__       =						[tokenizer.decode(__UpperCAmelCase		,    clean_up_tokenization_spaces=__UpperCAmelCase       ) for x in output_tokens]
							self.assertListEqual(__UpperCAmelCase		,    __UpperCAmelCase       )


	def 		UpperCAmelCase  (							self       )->					List[str]:







							'''simple docstring'''





							self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map       )		,    1       )
							self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values()       )[0]       )		,    1       )






