





"""simple docstring"""



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






class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





 """simple docstring"""


 def __init__(   self  ):



     '''simple docstring'''




     self.test()

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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

         __A   :						str									=					self.update(__lowerCamelCase  )
         counter += 1

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

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

 @abstractmethod
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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

 @abstractmethod
 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




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

 @abstractmethod
 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




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

 @abstractmethod
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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

 @abstractmethod
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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







 @abstractmethod
 def  UpperCamelCase__(   self ,						__lowerCamelCase=False  ):



     '''simple docstring'''




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






class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





 """simple docstring"""


 def __init__(   self ,						__lowerCamelCase  ):



     '''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}."""  )

     __A   :						str									=					token_ids

     __A   :						List[Any]									=					len(self.token_ids  )
     __A   :						int									=					-1  # the index of the currently fulfilled step
     __A   :						Optional[Any]									=					False

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''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 ,						__lowerCamelCase  ):



     '''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  )}"""  )

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

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

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					False
     __A   :						Optional[Any]									=					0

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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







 def  UpperCamelCase__(   self ,						__lowerCamelCase=False  ):



     '''simple docstring'''




     __A   :						Any									=					PhrasalConstraint(self.token_ids  )

     if stateful:
         __A   :						int									=					self.seqlen
         __A   :						Dict									=					self.fulfilled_idx
         __A   :						Tuple									=					self.completed

     return new_constraint






class 		__snake_case :





 """simple docstring"""


 def __init__(   self ,						__lowerCamelCase ,						__lowerCamelCase=True  ):



     '''simple docstring'''




     __A   :						Optional[Any]									=					max([len(__lowerCamelCase  ) for one in nested_token_ids]  )

     __A   :						List[Any]									=					{}
     for token_ids in nested_token_ids:
         __A   :						Dict									=					root
         for tidx, token_id in enumerate(__lowerCamelCase  ):
             if token_id not in level:
                 __A   :						Tuple									=					{}

             __A   :						int									=					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}."""  )

     __A   :						Tuple									=					root

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					self.trie

     for current_token in current_seq:
         __A   :						Tuple									=					start[current_token]

     __A   :						Any									=					list(start.keys()  )

     return next_tokens

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Optional[Any]									=					self.next_tokens(__lowerCamelCase  )

     return len(__lowerCamelCase  ) == 0

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




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







 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Tuple									=					self.count_leaves(__lowerCamelCase  )
     return len(__lowerCamelCase  ) != leaf_count






class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





 """simple docstring"""


 def __init__(   self ,						__lowerCamelCase  ):



     '''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}."""  )

     __A   :						Union[str, Any]									=					DisjunctiveTrie(__lowerCamelCase  )
     __A   :						Tuple									=					nested_token_ids

     __A   :						List[Any]									=					self.trie.max_height
     __A   :						Union[str, Any]									=					[]
     __A   :						Dict									=					False

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					self.trie.next_tokens(self.current_seq  )

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

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''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  )}"""  )

     __A   :						int									=					self.trie.next_tokens(self.current_seq  )

     return token_id in next_tokens

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''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  )}"""  )

     __A   :						Tuple									=					False
     __A   :						List[str]									=					False
     __A   :						Optional[Any]									=					False

     if self.does_advance(__lowerCamelCase  ):
         self.current_seq.append(__lowerCamelCase  )
         __A   :						Dict									=					True
     else:
         __A   :						Optional[Any]									=					True
         self.reset()

     __A   :						Dict									=					self.trie.reached_leaf(self.current_seq  )
     __A   :						List[Any]									=					completed

     return stepped, completed, reset

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Tuple									=					False
     __A   :						List[str]									=					[]

 def  UpperCamelCase__(   self  ):



     '''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 ,						__lowerCamelCase=False  ):



     '''simple docstring'''




     __A   :						Optional[Any]									=					DisjunctiveConstraint(self.token_ids  )

     if stateful:
         __A   :						Union[str, Any]									=					self.seqlen
         __A   :						Dict									=					self.current_seq
         __A   :						str									=					self.completed

     return new_constraint






class 		__snake_case :





 """simple docstring"""


 def __init__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Dict									=					constraints

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

     self.init_state()

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[str]									=					[]
     __A   :						Union[str, Any]									=					None
     __A   :						Optional[int]									=					[constraint.copy(stateful=__lowerCamelCase  ) for constraint in self.constraints]

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					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  ):



     '''simple docstring'''




     __A   :						List[str]									=					[]
     if self.inprogress_constraint is None:
         for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
             __A   :						Tuple									=					constraint.advance()
             if isinstance(__lowerCamelCase ,						__lowerCamelCase  ):
                 token_list.append(__lowerCamelCase  )
             elif isinstance(__lowerCamelCase ,						__lowerCamelCase  ):
                 token_list.extend(__lowerCamelCase  )
     else:
         __A   :						Tuple									=					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 ,						__lowerCamelCase  ):



     '''simple docstring'''




     self.init_state()

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

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

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




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

     __A   :						Optional[Any]									=					False, False

     if self.completed:
         __A   :						Dict									=					True
         __A   :						Optional[Any]									=					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

         __A   :						List[str]									=					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  )  )
             __A   :						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  )
             __A   :						List[Any]									=					None

             if len(self.pending_constraints  ) == 0:
                 # we're done!
                 __A   :						Optional[Any]									=					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  ):
                 __A   :						int									=					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  )
                     __A   :						Tuple									=					None

                 if not complete and stepped:
                     __A   :						List[str]									=					pending_constraint

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

                     __A   :						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.

                         __A   :						Any									=					True

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

     return complete, stepped







 def  UpperCamelCase__(   self ,						__lowerCamelCase=True  ):



     '''simple docstring'''




     __A   :						Optional[Any]									=					ConstraintListState(self.constraints  )  # we actually never though self.constraints objects
     # throughout this process. So it's at initialization state.

     if stateful:
         __A   :						Union[str, Any]									=					[
             constraint.copy(stateful=__lowerCamelCase  ) for constraint in self.complete_constraints
         ]
         if self.inprogress_constraint is not None:
             __A   :						Union[str, Any]									=					self.inprogress_constraint.copy(stateful=__lowerCamelCase  )
         __A   :						Optional[Any]									=					[constraint.copy() for constraint in self.pending_constraints]

     return new_state











"""simple docstring"""



import json
import os
import unittest

from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str 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"""


 _lowerCamelCase				=					MgpstrTokenizer
 _lowerCamelCase				=					False
 _lowerCamelCase				=					{}
 _lowerCamelCase				=					False

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     super().setUp()

     # fmt: off
     __A   :						int									=					['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z''']
     # fmt: on
     __A   :						Dict									=					dict(zip(__lowerCamelCase ,						range(len(__lowerCamelCase  )  )  )  )

     __A   :						Optional[Any]									=					os.path.join(self.tmpdirname ,						VOCAB_FILES_NAMES['''vocab_file''']  )
     with open(self.vocab_file ,						'''w''' ,						encoding='''utf-8'''  ) as fp:
         fp.write(json.dumps(__lowerCamelCase  ) + '''\n'''  )

 def  UpperCamelCase__(   self ,						**__lowerCamelCase  ):



     '''simple docstring'''




     return MgpstrTokenizer.from_pretrained(self.tmpdirname ,						**__lowerCamelCase  )

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						List[str]									=					'''tester'''
     __A   :						Dict									=					'''tester'''
     return input_text, output_text

 @unittest.skip('''MGP-STR always lower cases letters.'''  )
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     pass

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					self.get_tokenizers(do_lower_case=__lowerCamelCase  )
     for tokenizer in tokenizers:
         with self.subTest(F"""{tokenizer.__class__.__name__}"""  ):
             __A   :						Union[str, Any]									=					'''[SPECIAL_TOKEN]'''

             tokenizer.add_special_tokens({'''cls_token''': special_token}  )
             __A   :						Optional[Any]									=					tokenizer.encode([special_token] ,						add_special_tokens=__lowerCamelCase  )
             self.assertEqual(len(__lowerCamelCase  ) ,						1  )

             __A   :						List[Any]									=					tokenizer.decode(__lowerCamelCase ,						skip_special_tokens=__lowerCamelCase  )
             self.assertTrue(special_token not in decoded  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Tuple									=					self.get_tokenizers()
     for tokenizer in tokenizers:
         with self.subTest(F"""{tokenizer.__class__.__name__}"""  ):
             __A			,	__A   :						str									=					self.get_input_output_texts(__lowerCamelCase  )

             __A   :						Union[str, Any]									=					tokenizer.tokenize(__lowerCamelCase  )
             __A   :						Union[str, Any]									=					tokenizer.convert_tokens_to_ids(__lowerCamelCase  )
             __A   :						Union[str, Any]									=					tokenizer.encode(__lowerCamelCase ,						add_special_tokens=__lowerCamelCase  )
             self.assertListEqual(__lowerCamelCase ,						__lowerCamelCase  )

             __A   :						Optional[Any]									=					tokenizer.convert_ids_to_tokens(__lowerCamelCase  )
             self.assertNotEqual(len(__lowerCamelCase  ) ,						0  )
             __A   :						Union[str, Any]									=					tokenizer.decode(__lowerCamelCase  )
             self.assertIsInstance(__lowerCamelCase ,						__lowerCamelCase  )

             self.assertEqual(text_a.replace(''' ''' ,						''''''  ) ,						__lowerCamelCase  )

 @unittest.skip('''MGP-STR tokenizer only handles one sequence.'''  )
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     pass







 @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer'''  )
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     pass




