

"""simple docstring"""






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







class       snake_case__  ( lowerCAmelCase_     ):







			def __init__(			self			: int  ):





								'''simple docstring'''



								self.test()







			def 			__lowerCAmelCase				(			self			: int  ):





								'''simple docstring'''



								UpperCAmelCase			:   Optional[int]      =				0
								UpperCAmelCase			:   List[str]      =				False
								while not completed:
													if counter == 1:
																		self.reset()
													UpperCAmelCase			:   str      =				self.advance()
													if not self.does_advance(lowercase  ):
																		raise Exception(
																		    "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."  )

													UpperCAmelCase      ,							UpperCAmelCase      ,							UpperCAmelCase			:   Union[str, Any]      =				self.update(lowercase  )
													counter += 1

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

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







			@abstractmethod
			def 			__lowerCAmelCase				(			self			: int  ):





								'''simple docstring'''



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







			@abstractmethod
			def 			__lowerCAmelCase				(			self			: Any			,  lowercase			: int  ):





								'''simple docstring'''



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







			@abstractmethod
			def 			__lowerCAmelCase				(			self			: int			,  lowercase			: int  ):





								'''simple docstring'''



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







			@abstractmethod
			def 			__lowerCAmelCase				(			self			: Optional[int]  ):





								'''simple docstring'''



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







			@abstractmethod
			def 			__lowerCAmelCase				(			self			: str  ):





								'''simple docstring'''



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







			@abstractmethod
			def 			__lowerCAmelCase				(			self			: str			,  lowercase			: int=False  ):





								'''simple docstring'''



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







class       snake_case__  ( lowerCAmelCase_     ):







			def __init__(			self			: str			,  lowercase			: List[int]  ):





								'''simple docstring'''



								super(lowercase			,  self  ).__init__()

								if not isinstance(lowercase			,  lowercase  ) or len(lowercase  ) == 0:
													raise ValueError(f"""`token_ids` has to be a non-empty list, but is {token_ids}."""  )
								if any((not isinstance(lowercase			,  lowercase  ) 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}."""  )

								UpperCAmelCase			:   Tuple      =				token_ids

								UpperCAmelCase			:   Union[str, Any]      =				len(self.token_ids  )
								UpperCAmelCase			:   Dict      =				-1  # the index of the currently fulfilled step
								UpperCAmelCase			:   Optional[Any]      =				False







			def 			__lowerCAmelCase				(			self			: Any  ):





								'''simple docstring'''



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







			def 			__lowerCAmelCase				(			self			: Optional[Any]			,  lowercase			: int  ):





								'''simple docstring'''



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

								if self.completed:
													return False

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







			def 			__lowerCAmelCase				(			self			: str			,  lowercase			: int  ):





								'''simple docstring'''



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

								UpperCAmelCase			:   Union[str, Any]      =				False
								UpperCAmelCase			:   Optional[int]      =				False
								UpperCAmelCase			:   Optional[Any]      =				False

								if self.does_advance(lowercase  ):
													self.fulfilled_idx += 1
													UpperCAmelCase			:   Dict      =				True
													if self.fulfilled_idx == (self.seqlen - 1):
																		UpperCAmelCase			:   Optional[Any]      =				True
													UpperCAmelCase			:   str      =				completed
								else:
													# failed to make progress.
													UpperCAmelCase			:   List[Any]      =				True
													self.reset()
								return stepped, completed, reset







			def 			__lowerCAmelCase				(			self			: Optional[Any]  ):





								'''simple docstring'''



								UpperCAmelCase			:   Any      =				False
								UpperCAmelCase			:   List[Any]      =				0







			def 			__lowerCAmelCase				(			self			: Dict  ):





								'''simple docstring'''



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







			def 			__lowerCAmelCase				(			self			: List[str]			,  lowercase			: int=False  ):





								'''simple docstring'''



								UpperCAmelCase			:   str      =				PhrasalConstraint(self.token_ids  )

								if stateful:
													UpperCAmelCase			:   str      =				self.seqlen
													UpperCAmelCase			:   List[Any]      =				self.fulfilled_idx
													UpperCAmelCase			:   List[str]      =				self.completed

								return new_constraint







class       snake_case__  :







			def __init__(			self			: Any			,  lowercase			: List[List[int]]			,  lowercase			: Any=True  ):





								'''simple docstring'''



								UpperCAmelCase			:   Optional[int]      =				max([len(lowercase  ) for one in nested_token_ids]  )

								UpperCAmelCase			:   Any      =				{}
								for token_ids in nested_token_ids:
													UpperCAmelCase			:   str      =				root
													for tidx, token_id in enumerate(lowercase  ):
																		if token_id not in level:
																							UpperCAmelCase			:   int      =				{}

																		UpperCAmelCase			:   Tuple      =				level[token_id]

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

								UpperCAmelCase			:   Optional[int]      =				root







			def 			__lowerCAmelCase				(			self			: List[str]			,  lowercase			: int  ):





								'''simple docstring'''



								UpperCAmelCase			:   List[Any]      =				self.trie

								for current_token in current_seq:
													UpperCAmelCase			:   List[Any]      =				start[current_token]

								UpperCAmelCase			:   List[str]      =				list(start.keys()  )

								return next_tokens







			def 			__lowerCAmelCase				(			self			: Any			,  lowercase			: Tuple  ):





								'''simple docstring'''



								UpperCAmelCase			:   Dict      =				self.next_tokens(lowercase  )

								return len(lowercase  ) == 0







			def 			__lowerCAmelCase				(			self			: Tuple			,  lowercase			: Tuple  ):





								'''simple docstring'''



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







			def 			__lowerCAmelCase				(			self			: Tuple			,  lowercase			: Optional[int]			,  lowercase			: str  ):





								'''simple docstring'''



								UpperCAmelCase			:   Dict      =				self.count_leaves(lowercase  )
								return len(lowercase  ) != leaf_count







class       snake_case__  ( lowerCAmelCase_     ):







			def __init__(			self			: Tuple			,  lowercase			: List[List[int]]  ):





								'''simple docstring'''



								super(lowercase			,  self  ).__init__()

								if not isinstance(lowercase			,  lowercase  ) or len(lowercase  ) == 0:
													raise ValueError(f"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."""  )
								if any(not isinstance(lowercase			,  lowercase  ) 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(lowercase			,  lowercase  ) 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}."""  )

								UpperCAmelCase			:   Tuple      =				DisjunctiveTrie(lowercase  )
								UpperCAmelCase			:   Tuple      =				nested_token_ids

								UpperCAmelCase			:   List[str]      =				self.trie.max_height
								UpperCAmelCase			:   List[str]      =				[]
								UpperCAmelCase			:   Dict      =				False







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





								'''simple docstring'''



								UpperCAmelCase			:   List[str]      =				self.trie.next_tokens(self.current_seq  )

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







			def 			__lowerCAmelCase				(			self			: Union[str, Any]			,  lowercase			: int  ):





								'''simple docstring'''



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

								UpperCAmelCase			:   List[str]      =				self.trie.next_tokens(self.current_seq  )

								return token_id in next_tokens







			def 			__lowerCAmelCase				(			self			: Optional[Any]			,  lowercase			: int  ):





								'''simple docstring'''



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

								UpperCAmelCase			:   int      =				False
								UpperCAmelCase			:   str      =				False
								UpperCAmelCase			:   Optional[Any]      =				False

								if self.does_advance(lowercase  ):
													self.current_seq.append(lowercase  )
													UpperCAmelCase			:   Tuple      =				True
								else:
													UpperCAmelCase			:   str      =				True
													self.reset()

								UpperCAmelCase			:   Optional[int]      =				self.trie.reached_leaf(self.current_seq  )
								UpperCAmelCase			:   Any      =				completed

								return stepped, completed, reset







			def 			__lowerCAmelCase				(			self			: Optional[int]  ):





								'''simple docstring'''



								UpperCAmelCase			:   List[str]      =				False
								UpperCAmelCase			:   Optional[Any]      =				[]







			def 			__lowerCAmelCase				(			self			: Tuple  ):





								'''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 			__lowerCAmelCase				(			self			: Union[str, Any]			,  lowercase			: str=False  ):





								'''simple docstring'''



								UpperCAmelCase			:   Union[str, Any]      =				DisjunctiveConstraint(self.token_ids  )

								if stateful:
													UpperCAmelCase			:   Tuple      =				self.seqlen
													UpperCAmelCase			:   str      =				self.current_seq
													UpperCAmelCase			:   Union[str, Any]      =				self.completed

								return new_constraint







class       snake_case__  :







			def __init__(			self			: int			,  lowercase			: List[Constraint]  ):





								'''simple docstring'''



								UpperCAmelCase			:   Union[str, Any]      =				constraints

								# max # of steps required to fulfill a given constraint
								UpperCAmelCase			:   Tuple      =				max([c.seqlen for c in constraints]  )
								UpperCAmelCase			:   int      =				len(lowercase  )
								UpperCAmelCase			:   Optional[Any]      =				False

								self.init_state()







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





								'''simple docstring'''



								UpperCAmelCase			:   Dict      =				[]
								UpperCAmelCase			:   Optional[int]      =				None
								UpperCAmelCase			:   Dict      =				[constraint.copy(stateful=lowercase  ) for constraint in self.constraints]







			def 			__lowerCAmelCase				(			self			: Tuple  ):





								'''simple docstring'''



								UpperCAmelCase			:   Any      =				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 			__lowerCAmelCase				(			self			: Union[str, Any]  ):





								'''simple docstring'''



								UpperCAmelCase			:   Optional[int]      =				[]
								if self.inprogress_constraint is None:
													for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
																		UpperCAmelCase			:   Dict      =				constraint.advance()
																		if isinstance(lowercase			,  lowercase  ):
																							token_list.append(lowercase  )
																		elif isinstance(lowercase			,  lowercase  ):
																							token_list.extend(lowercase  )
								else:
													UpperCAmelCase			:   Optional[Any]      =				self.inprogress_constraint.advance()
													if isinstance(lowercase			,  lowercase  ):
																		token_list.append(lowercase  )
													elif isinstance(lowercase			,  lowercase  ):
																		token_list.extend(lowercase  )

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







			def 			__lowerCAmelCase				(			self			: Tuple			,  lowercase			: Optional[List[int]]  ):





								'''simple docstring'''



								self.init_state()

								if token_ids is not None:
													for token in token_ids:
																		# completes or steps **one** constraint
																		UpperCAmelCase      ,							UpperCAmelCase			:   Tuple      =				self.add(lowercase  )

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







			def 			__lowerCAmelCase				(			self			: Optional[Any]			,  lowercase			: int  ):





								'''simple docstring'''



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

								UpperCAmelCase      ,							UpperCAmelCase			:   Tuple      =				False, False

								if self.completed:
													UpperCAmelCase			:   Any      =				True
													UpperCAmelCase			:   int      =				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

													UpperCAmelCase      ,							UpperCAmelCase      ,							UpperCAmelCase			:   Any      =				self.inprogress_constraint.update(lowercase  )
													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=lowercase  )  )
																		UpperCAmelCase			:   Tuple      =				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  )
																		UpperCAmelCase			:   int      =				None

																		if len(self.pending_constraints  ) == 0:
																							# we're done!
																							UpperCAmelCase			:   Optional[int]      =				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(lowercase  ):
																							UpperCAmelCase      ,							UpperCAmelCase      ,							UpperCAmelCase			:   int      =				pending_constraint.update(lowercase  )

																							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(lowercase  )
																												UpperCAmelCase			:   List[Any]      =				None

																							if not complete and stepped:
																												UpperCAmelCase			:   Union[str, Any]      =				pending_constraint

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

																												UpperCAmelCase			:   List[Any]      =				(
																												    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.

																																	UpperCAmelCase			:   Union[str, Any]      =				True

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

								return complete, stepped







			def 			__lowerCAmelCase				(			self			: Tuple			,  lowercase			: List[Any]=True  ):





								'''simple docstring'''



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

								if stateful:
													UpperCAmelCase			:   Dict      =				[
													    constraint.copy(stateful=lowercase  ) for constraint in self.complete_constraints
													]
													if self.inprogress_constraint is not None:
																		UpperCAmelCase			:   Optional[Any]      =				self.inprogress_constraint.copy(stateful=lowercase  )
													UpperCAmelCase			:   Tuple      =				[constraint.copy() for constraint in self.pending_constraints]

								return new_state





"""simple docstring"""






import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.text import TextDatasetReader

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases



def   lowercase_	(    _lowercase       :		Optional[int]							,      _lowercase       :		int	):




					'''simple docstring'''






					assert isinstance(_lowercase							,      _lowercase	)
					assert dataset.num_rows == 4
					assert dataset.num_columns == 1
					assert dataset.column_names == ["text"]
					for feature, expected_dtype in expected_features.items():
										assert dataset.features[feature].dtype == expected_dtype



@pytest.mark.parametrize("keep_in_memory"							,      [False, True]	)
def   lowercase_	(    _lowercase       :		Union[str, Any]							,      _lowercase       :		Optional[int]							,      _lowercase       :		Dict	):




					'''simple docstring'''






					UpperCAmelCase			:   Dict      =				tmp_path / "cache"
					UpperCAmelCase			:   str      =				{"text": "string"}
					with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
										UpperCAmelCase			:   Tuple      =				TextDatasetReader(_lowercase							,      cache_dir=_lowercase							,      keep_in_memory=_lowercase	).read()
					_check_text_dataset(_lowercase							,      _lowercase	)



@pytest.mark.parametrize(
    "features"							,      [
        None,
        {"text": "string"},
        {"text": "int32"},
        {"text": "float32"},
    ]							,      )
def   lowercase_	(    _lowercase       :		Dict							,      _lowercase       :		Union[str, Any]							,      _lowercase       :		Optional[int]	):




					'''simple docstring'''






					UpperCAmelCase			:   int      =				tmp_path / "cache"
					UpperCAmelCase			:   Any      =				{"text": "string"}
					UpperCAmelCase			:   List[str]      =				features.copy() if features else default_expected_features
					UpperCAmelCase			:   Union[str, Any]      =				(
					    Features({feature: Value(_lowercase	) for feature, dtype in features.items()}	) if features is not None else None
					)
					UpperCAmelCase			:   str      =				TextDatasetReader(_lowercase							,      features=_lowercase							,      cache_dir=_lowercase	).read()
					_check_text_dataset(_lowercase							,      _lowercase	)



@pytest.mark.parametrize("split"							,      [None, NamedSplit("train"	), "train", "test"]	)
def   lowercase_	(    _lowercase       :		int							,      _lowercase       :		Tuple							,      _lowercase       :		List[str]	):




					'''simple docstring'''






					UpperCAmelCase			:   str      =				tmp_path / "cache"
					UpperCAmelCase			:   Any      =				{"text": "string"}
					UpperCAmelCase			:   List[Any]      =				TextDatasetReader(_lowercase							,      cache_dir=_lowercase							,      split=_lowercase	).read()
					_check_text_dataset(_lowercase							,      _lowercase	)
					assert dataset.split == split if split else "train"



@pytest.mark.parametrize("path_type"							,      [str, list]	)
def   lowercase_	(    _lowercase       :		Optional[int]							,      _lowercase       :		Any							,      _lowercase       :		Union[str, Any]	):




					'''simple docstring'''






					if issubclass(_lowercase							,      _lowercase	):
										UpperCAmelCase			:   List[str]      =				text_path
					elif issubclass(_lowercase							,      _lowercase	):
										UpperCAmelCase			:   List[Any]      =				[text_path]
					UpperCAmelCase			:   Union[str, Any]      =				tmp_path / "cache"
					UpperCAmelCase			:   List[Any]      =				{"text": "string"}
					UpperCAmelCase			:   Tuple      =				TextDatasetReader(_lowercase							,      cache_dir=_lowercase	).read()
					_check_text_dataset(_lowercase							,      _lowercase	)



def   lowercase_	(    _lowercase       :		Dict							,      _lowercase       :		int							,      _lowercase       :		Optional[Any]=("train",)	):




					'''simple docstring'''






					assert isinstance(_lowercase							,      _lowercase	)
					for split in splits:
										UpperCAmelCase			:   str      =				dataset_dict[split]
										assert dataset.num_rows == 4
										assert dataset.num_columns == 1
										assert dataset.column_names == ["text"]
										for feature, expected_dtype in expected_features.items():
															assert dataset.features[feature].dtype == expected_dtype



@pytest.mark.parametrize("keep_in_memory"							,      [False, True]	)
def   lowercase_	(    _lowercase       :		Dict							,      _lowercase       :		str							,      _lowercase       :		Dict	):




					'''simple docstring'''






					UpperCAmelCase			:   str      =				tmp_path / "cache"
					UpperCAmelCase			:   Union[str, Any]      =				{"text": "string"}
					with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
										UpperCAmelCase			:   Tuple      =				TextDatasetReader({"train": text_path}							,      cache_dir=_lowercase							,      keep_in_memory=_lowercase	).read()
					_check_text_datasetdict(_lowercase							,      _lowercase	)



@pytest.mark.parametrize(
    "features"							,      [
        None,
        {"text": "string"},
        {"text": "int32"},
        {"text": "float32"},
    ]							,      )
def   lowercase_	(    _lowercase       :		List[Any]							,      _lowercase       :		Union[str, Any]							,      _lowercase       :		int	):




					'''simple docstring'''






					UpperCAmelCase			:   int      =				tmp_path / "cache"
					# CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
					UpperCAmelCase			:   List[str]      =				{"text": "string"}
					UpperCAmelCase			:   str      =				features.copy() if features else default_expected_features
					UpperCAmelCase			:   Optional[int]      =				(
					    Features({feature: Value(_lowercase	) for feature, dtype in features.items()}	) if features is not None else None
					)
					UpperCAmelCase			:   Optional[int]      =				TextDatasetReader({"train": text_path}							,      features=_lowercase							,      cache_dir=_lowercase	).read()
					_check_text_datasetdict(_lowercase							,      _lowercase	)




@pytest.mark.parametrize("split"							,      [None, NamedSplit("train"	), "train", "test"]	)
def   lowercase_	(    _lowercase       :		int							,      _lowercase       :		Tuple							,      _lowercase       :		Optional[Any]	):




					'''simple docstring'''






					if split:
										UpperCAmelCase			:   Optional[Any]      =				{split: text_path}
					else:
										UpperCAmelCase			:   str      =				"train"
										UpperCAmelCase			:   Union[str, Any]      =				{"train": text_path, "test": text_path}
					UpperCAmelCase			:   Any      =				tmp_path / "cache"
					UpperCAmelCase			:   List[Any]      =				{"text": "string"}
					UpperCAmelCase			:   Any      =				TextDatasetReader(_lowercase							,      cache_dir=_lowercase	).read()
					_check_text_datasetdict(_lowercase							,      _lowercase							,      splits=list(path.keys()	)	)
					assert all(dataset[split].split == split for split in path.keys()	)


