





"""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			,	__A			,	__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			,	__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			,	__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			,	__A			,	__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			,	__A			,	__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.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer
from transformers.testing_utils import slow

from ...test_tokenization_common import TokenizerTesterMixin






class 		__snake_case (		SCREAMING_SNAKE_CASE__							,							unittest.TestCase					):





 """simple docstring"""


 _lowerCamelCase				=					XLMTokenizer
 _lowerCamelCase				=					False

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     super().setUp()

     # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
     __A   :						Tuple									=					[
         '''l''',
         '''o''',
         '''w''',
         '''e''',
         '''r''',
         '''s''',
         '''t''',
         '''i''',
         '''d''',
         '''n''',
         '''w</w>''',
         '''r</w>''',
         '''t</w>''',
         '''lo''',
         '''low''',
         '''er</w>''',
         '''low</w>''',
         '''lowest</w>''',
         '''newer</w>''',
         '''wider</w>''',
         '''<unk>''',
     ]
     __A   :						Dict									=					dict(zip(__lowerCamelCase ,						range(len(__lowerCamelCase  )  )  )  )
     __A   :						Union[str, Any]									=					['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', '''''']

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

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					'''lower newer'''
     __A   :						int									=					'''lower newer'''
     return input_text, output_text

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Union[str, Any]									=					XLMTokenizer(self.vocab_file ,						self.merges_file  )

     __A   :						Optional[Any]									=					'''lower'''
     __A   :						Any									=					['''low''', '''er</w>''']
     __A   :						Tuple									=					tokenizer.tokenize(__lowerCamelCase  )
     self.assertListEqual(__lowerCamelCase ,						__lowerCamelCase  )

     __A   :						str									=					tokens + ['''<unk>''']
     __A   :						List[str]									=					[14, 15, 20]
     self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase  ) ,						__lowerCamelCase  )







 @slow
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					XLMTokenizer.from_pretrained('''xlm-mlm-en-2048'''  )

     __A   :						Union[str, Any]									=					tokenizer.encode('''sequence builders''' ,						add_special_tokens=__lowerCamelCase  )
     __A   :						int									=					tokenizer.encode('''multi-sequence build''' ,						add_special_tokens=__lowerCamelCase  )

     __A   :						int									=					tokenizer.build_inputs_with_special_tokens(__lowerCamelCase  )
     __A   :						List[Any]									=					tokenizer.build_inputs_with_special_tokens(__lowerCamelCase ,						__lowerCamelCase  )

     assert encoded_sentence == [0] + text + [1]
     assert encoded_pair == [0] + text + [1] + text_a + [1]




