from abc import ABC, abstractmethod
from typing import List, Optional
class     lowerCAmelCase_     (       __lowercase ):







							def __init__(   self      :     Union[str, Any]		):
												# test for the above condition
												self.test()







							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												_UpperCamelCase			     =     0
												_UpperCamelCase			     =     False
												while not completed:
																	if counter == 1:
																						self.reset()
																	_UpperCamelCase			     =     self.advance()
																	if not self.does_advance(_A		):
																						raise Exception(
																						    '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'''		)

																	_UpperCamelCase     ,    _UpperCamelCase     ,    _UpperCamelCase			     =     self.update(_A		)
																	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      :     Union[str, Any]		):
												raise NotImplementedError(
												    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""		)







							@abstractmethod
							def  UpperCamelCase_						(   self      :     Any ,			_A      :     int		):
												raise NotImplementedError(
												    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""		)







							@abstractmethod
							def  UpperCamelCase_						(   self      :     Optional[Any] ,			_A      :     int		):
												raise NotImplementedError(
												    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""		)







							@abstractmethod
							def  UpperCamelCase_						(   self      :     Optional[Any]		):
												raise NotImplementedError(
												    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""		)







							@abstractmethod
							def  UpperCamelCase_						(   self      :     str		):
												raise NotImplementedError(
												    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""		)







							@abstractmethod
							def  UpperCamelCase_						(   self      :     Optional[int] ,			_A      :     str=False		):
												raise NotImplementedError(
												    F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""		)




class     lowerCAmelCase_     (       __lowercase ):







							def __init__(   self      :     Tuple ,			_A      :     List[int]		):
												super(_A ,			self		).__init__()

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

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







							def  UpperCamelCase_						(   self      :     Optional[int]		):
												if self.completed:
																	return None
												return self.token_ids[self.fulfilled_idx + 1]







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

												if self.completed:
																	return False

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







							def  UpperCamelCase_						(   self      :     Optional[Any] ,			_A      :     int		):
												if not isinstance(_A ,			_A		):
																	raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(_A		)}"""		)

												_UpperCamelCase			     =     False
												_UpperCamelCase			     =     False
												_UpperCamelCase			     =     False

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







							def  UpperCamelCase_						(   self      :     Optional[int]		):
												_UpperCamelCase			     =     False
												_UpperCamelCase			     =     0







							def  UpperCamelCase_						(   self      :     str		):
												return self.seqlen - (self.fulfilled_idx + 1)







							def  UpperCamelCase_						(   self      :     Any ,			_A      :     Optional[int]=False		):
												_UpperCamelCase			     =     PhrasalConstraint(self.token_ids		)

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

												return new_constraint




class     lowerCAmelCase_     :







							def __init__(   self      :     Any ,			_A      :     List[List[int]] ,			_A      :     Optional[int]=True		):
												_UpperCamelCase			     =     max([len(_A		) for one in nested_token_ids]		)

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

																						_UpperCamelCase			     =     level[token_id]

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

												_UpperCamelCase			     =     root







							def  UpperCamelCase_						(   self      :     str ,			_A      :     Union[str, Any]		):
												_UpperCamelCase			     =     self.trie

												for current_token in current_seq:
																	_UpperCamelCase			     =     start[current_token]

												_UpperCamelCase			     =     list(start.keys()		)

												return next_tokens







							def  UpperCamelCase_						(   self      :     Any ,			_A      :     Optional[Any]		):
												_UpperCamelCase			     =     self.next_tokens(_A		)

												return len(_A		) == 0







							def  UpperCamelCase_						(   self      :     int ,			_A      :     List[str]		):
												_UpperCamelCase			     =     list(root.values()		)
												if len(_A		) == 0:
																	return 1
												else:
																	return sum([self.count_leaves(_A		) for nn in next_nodes]		)







							def  UpperCamelCase_						(   self      :     Optional[Any] ,			_A      :     Optional[Any] ,			_A      :     Any		):
												_UpperCamelCase			     =     self.count_leaves(_A		)
												return len(_A		) != leaf_count




class     lowerCAmelCase_     (       __lowercase ):







							def __init__(   self      :     List[Any] ,			_A      :     List[List[int]]		):
												super(_A ,			self		).__init__()

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

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







							def  UpperCamelCase_						(   self      :     List[Any]		):
												_UpperCamelCase			     =     self.trie.next_tokens(self.current_seq		)

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







							def  UpperCamelCase_						(   self      :     Optional[int] ,			_A      :     int		):
												if not isinstance(_A ,			_A		):
																	raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(_A		)}"""		)

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

												return token_id in next_tokens







							def  UpperCamelCase_						(   self      :     Union[str, Any] ,			_A      :     int		):
												if not isinstance(_A ,			_A		):
																	raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(_A		)}"""		)

												_UpperCamelCase			     =     False
												_UpperCamelCase			     =     False
												_UpperCamelCase			     =     False

												if self.does_advance(_A		):
																	self.current_seq.append(_A		)
																	_UpperCamelCase			     =     True
												else:
																	_UpperCamelCase			     =     True
																	self.reset()

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

												return stepped, completed, reset







							def  UpperCamelCase_						(   self      :     List[Any]		):
												_UpperCamelCase			     =     False
												_UpperCamelCase			     =     []







							def  UpperCamelCase_						(   self      :     int		):
												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      :     List[str] ,			_A      :     int=False		):
												_UpperCamelCase			     =     DisjunctiveConstraint(self.token_ids		)

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

												return new_constraint




class     lowerCAmelCase_     :







							def __init__(   self      :     Tuple ,			_A      :     List[Constraint]		):
												_UpperCamelCase			     =     constraints

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

												self.init_state()







							def  UpperCamelCase_						(   self      :     List[str]		):
												_UpperCamelCase			     =     []
												_UpperCamelCase			     =     None
												_UpperCamelCase			     =     [constraint.copy(stateful=_A		) for constraint in self.constraints]







							def  UpperCamelCase_						(   self      :     int		):
												_UpperCamelCase			     =     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      :     List[Any]		):
												_UpperCamelCase			     =     []
												if self.inprogress_constraint is None:
																	for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
																						_UpperCamelCase			     =     constraint.advance()
																						if isinstance(_A ,			_A		):
																											token_list.append(_A		)
																						elif isinstance(_A ,			_A		):
																											token_list.extend(_A		)
												else:
																	_UpperCamelCase			     =     self.inprogress_constraint.advance()
																	if isinstance(_A ,			_A		):
																						token_list.append(_A		)
																	elif isinstance(_A ,			_A		):
																						token_list.extend(_A		)

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







							def  UpperCamelCase_						(   self      :     Optional[int] ,			_A      :     Optional[List[int]]		):
												self.init_state()

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

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







							def  UpperCamelCase_						(   self      :     Union[str, Any] ,			_A      :     int		):
												if not isinstance(_A ,			_A		):
																	raise ValueError(F"""`token_id` should be an `int`, but is `{token_id}`."""		)

												_UpperCamelCase     ,    _UpperCamelCase			     =     False, False

												if self.completed:
																	_UpperCamelCase			     =     True
																	_UpperCamelCase			     =     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			     =     self.inprogress_constraint.update(_A		)
																	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=_A		)		)
																						_UpperCamelCase			     =     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			     =     None

																						if len(self.pending_constraints		) == 0:
																											# we're done!
																											_UpperCamelCase			     =     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(_A		):
																											_UpperCamelCase     ,    _UpperCamelCase     ,    _UpperCamelCase			     =     pending_constraint.update(_A		)

																											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(_A		)
																																_UpperCamelCase			     =     None

																											if not complete and stepped:
																																_UpperCamelCase			     =     pending_constraint

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

																																_UpperCamelCase			     =     (
																																    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			     =     True

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

												return complete, stepped







							def  UpperCamelCase_						(   self      :     str ,			_A      :     Optional[Any]=True		):
												_UpperCamelCase			     =     ConstraintListState(self.constraints		)  # we actually never though self.constraints objects
												# throughout this process. So it's at initialization state.

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

												return new_state

from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
					import tensorflow as tf

					from transformers import TFBlipTextModel
					from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST
class     lowerCAmelCase_     :







							def __init__(   self      :     Any ,			_A      :     int ,			_A      :     int=12 ,			_A      :     int=7 ,			_A      :     Tuple=True ,			_A      :     Optional[int]=True ,			_A      :     Union[str, Any]=True ,			_A      :     str=99 ,			_A      :     str=32 ,			_A      :     int=32 ,			_A      :     Optional[Any]=2 ,			_A      :     Dict=4 ,			_A      :     int=37 ,			_A      :     List[Any]=0.1 ,			_A      :     str=0.1 ,			_A      :     Any=512 ,			_A      :     int=0.02 ,			_A      :     Optional[Any]=0 ,			_A      :     Dict=None ,			):
												_UpperCamelCase			     =     parent
												_UpperCamelCase			     =     batch_size
												_UpperCamelCase			     =     seq_length
												_UpperCamelCase			     =     is_training
												_UpperCamelCase			     =     use_input_mask
												_UpperCamelCase			     =     use_labels
												_UpperCamelCase			     =     vocab_size
												_UpperCamelCase			     =     hidden_size
												_UpperCamelCase			     =     projection_dim
												_UpperCamelCase			     =     num_hidden_layers
												_UpperCamelCase			     =     num_attention_heads
												_UpperCamelCase			     =     intermediate_size
												_UpperCamelCase			     =     dropout
												_UpperCamelCase			     =     attention_dropout
												_UpperCamelCase			     =     max_position_embeddings
												_UpperCamelCase			     =     initializer_range
												_UpperCamelCase			     =     scope
												_UpperCamelCase			     =     bos_token_id







							def  UpperCamelCase_						(   self      :     List[str]		):
												_UpperCamelCase			     =     ids_tensor([self.batch_size, self.seq_length] ,			self.vocab_size		)

												_UpperCamelCase			     =     None
												if self.use_input_mask:
																	_UpperCamelCase			     =     random_attention_mask([self.batch_size, self.seq_length]		)

												if input_mask is not None:
																	_UpperCamelCase			     =     input_mask.numpy()
																	_UpperCamelCase     ,    _UpperCamelCase			     =     input_mask.shape
																	_UpperCamelCase			     =     np.random.randint(1 ,			seq_length - 1 ,			size=(batch_size,)		)
																	for batch_idx, start_index in enumerate(_A		):
																						_UpperCamelCase			     =     1
																						_UpperCamelCase			     =     0

												_UpperCamelCase			     =     self.get_config()

												return config, input_ids, tf.convert_to_tensor(_A		)







							def  UpperCamelCase_						(   self      :     str		):
												return BlipTextConfig(
												    vocab_size=self.vocab_size ,			hidden_size=self.hidden_size ,			projection_dim=self.projection_dim ,			num_hidden_layers=self.num_hidden_layers ,			num_attention_heads=self.num_attention_heads ,			intermediate_size=self.intermediate_size ,			dropout=self.dropout ,			attention_dropout=self.attention_dropout ,			max_position_embeddings=self.max_position_embeddings ,			initializer_range=self.initializer_range ,			bos_token_id=self.bos_token_id ,			)







							def  UpperCamelCase_						(   self      :     List[str] ,			_A      :     Tuple ,			_A      :     str ,			_A      :     Optional[Any]		):
												_UpperCamelCase			     =     TFBlipTextModel(config=_A		)
												_UpperCamelCase			     =     model(_A ,			attention_mask=_A ,			training=_A		)
												_UpperCamelCase			     =     model(_A ,			training=_A		)
												self.parent.assertEqual(result.last_hidden_state.shape ,			(self.batch_size, self.seq_length, self.hidden_size)		)
												self.parent.assertEqual(result.pooler_output.shape ,			(self.batch_size, self.hidden_size)		)







							def  UpperCamelCase_						(   self      :     Tuple		):
												_UpperCamelCase			     =     self.prepare_config_and_inputs()
												_UpperCamelCase     ,    _UpperCamelCase     ,    _UpperCamelCase			     =     config_and_inputs
												_UpperCamelCase			     =     {'''input_ids''': input_ids, '''attention_mask''': input_mask}
												return config, inputs_dict




@require_tf
class     lowerCAmelCase_     (       __lowercase,  unittest.TestCase ):
							UpperCAmelCase				   =     (TFBlipTextModel,) if is_tf_available() else ()
							UpperCAmelCase				   =     False
							UpperCAmelCase				   =     False
							UpperCAmelCase				   =     False







							def  UpperCamelCase_						(   self      :     Dict		):
												_UpperCamelCase			     =     BlipTextModelTester(self		)
												_UpperCamelCase			     =     ConfigTester(self ,			config_class=_A ,			hidden_size=37		)







							def  UpperCamelCase_						(   self      :     Dict		):
												self.config_tester.run_common_tests()







							def  UpperCamelCase_						(   self      :     int		):
												_UpperCamelCase			     =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_A		)







							def  UpperCamelCase_						(   self      :     List[Any]		):
												pass







							def  UpperCamelCase_						(   self      :     Tuple		):
												pass







							@unittest.skip(reason='''Blip does not use inputs_embeds'''		)
							def  UpperCamelCase_						(   self      :     Dict		):
												pass







							@unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''		)
							def  UpperCamelCase_						(   self      :     Dict		):
												pass







							@unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING'''		)
							def  UpperCamelCase_						(   self      :     List[str]		):
												pass







							@slow
							def  UpperCamelCase_						(   self      :     Optional[int]		):
												for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_UpperCamelCase			     =     TFBlipTextModel.from_pretrained(_A		)
																	self.assertIsNotNone(_A		)







							def  UpperCamelCase_						(   self      :     int ,			_A      :     Optional[int]=True		):
												super().test_pt_tf_model_equivalence(allow_missing_keys=_A		)
