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





class 					lowercase__						(   UpperCamelCase_):


						def __init__(       self	:				str						):





												'''simple docstring'''





												self.test()


						def        __A       (       self	:				Optional[int]						):





												'''simple docstring'''





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

																		SCREAMING_SNAKE_CASE				,  SCREAMING_SNAKE_CASE				,  SCREAMING_SNAKE_CASE							:    Optional[Any]							=							self.update(UpperCamelCase__						)
																		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        __A       (       self	:				List[str]						):





												'''simple docstring'''





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


						@abstractmethod
						def        __A       (       self	:				Tuple    ,		UpperCamelCase__	:				int						):





												'''simple docstring'''





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


						@abstractmethod
						def        __A       (       self	:				Tuple    ,		UpperCamelCase__	:				int						):





												'''simple docstring'''





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


						@abstractmethod
						def        __A       (       self	:				str						):





												'''simple docstring'''





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


						@abstractmethod
						def        __A       (       self	:				str						):





												'''simple docstring'''





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



						@abstractmethod
						def        __A       (       self	:				Optional[int]    ,		UpperCamelCase__	:				Dict=False						):





												'''simple docstring'''





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






class 					lowercase__						(   UpperCamelCase_):


						def __init__(       self	:				Any    ,		UpperCamelCase__	:				List[int]						):





												'''simple docstring'''





												super(UpperCamelCase__    ,		self						).__init__()

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

												SCREAMING_SNAKE_CASE							:    Optional[Any]							=							token_ids

												SCREAMING_SNAKE_CASE							:    int							=							len(self.token_ids						)
												SCREAMING_SNAKE_CASE							:    int							=							-1  # the index of the currently fulfilled step
												SCREAMING_SNAKE_CASE							:    str							=							False


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





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


						def        __A       (       self	:				Tuple    ,		UpperCamelCase__	:				int						):





												'''simple docstring'''





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

												if self.completed:
																		return False

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


						def        __A       (       self	:				str    ,		UpperCamelCase__	:				int						):





												'''simple docstring'''





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

												SCREAMING_SNAKE_CASE							:    Any							=							False
												SCREAMING_SNAKE_CASE							:    int							=							False
												SCREAMING_SNAKE_CASE							:    List[Any]							=							False

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


						def        __A       (       self	:				int						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Optional[Any]							=							False
												SCREAMING_SNAKE_CASE							:    Optional[int]							=							0


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





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



						def        __A       (       self	:				str    ,		UpperCamelCase__	:				Tuple=False						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							PhrasalConstraint(self.token_ids						)

												if stateful:
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							self.seqlen
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							self.fulfilled_idx
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							self.completed

												return new_constraint






class 					lowercase__						:


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





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Any							=							max([len(UpperCamelCase__						) for one in nested_token_ids]						)

												SCREAMING_SNAKE_CASE							:    Any							=							{}
												for token_ids in nested_token_ids:
																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							root
																		for tidx, token_id in enumerate(UpperCamelCase__						):
																								if token_id not in level:
																														SCREAMING_SNAKE_CASE							:    Dict							=							{}

																								SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							level[token_id]

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

												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							root


						def        __A       (       self	:				Dict    ,		UpperCamelCase__	:				Optional[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    List[Any]							=							self.trie

												for current_token in current_seq:
																		SCREAMING_SNAKE_CASE							:    Dict							=							start[current_token]

												SCREAMING_SNAKE_CASE							:    Optional[int]							=							list(start.keys()						)

												return next_tokens


						def        __A       (       self	:				Optional[int]    ,		UpperCamelCase__	:				Tuple						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    List[str]							=							self.next_tokens(UpperCamelCase__						)

												return len(UpperCamelCase__						) == 0


						def        __A       (       self	:				Dict    ,		UpperCamelCase__	:				List[Any]						):





												'''simple docstring'''





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



						def        __A       (       self	:				Any    ,		UpperCamelCase__	:				int    ,		UpperCamelCase__	:				List[str]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							self.count_leaves(UpperCamelCase__						)
												return len(UpperCamelCase__						) != leaf_count






class 					lowercase__						(   UpperCamelCase_):


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





												'''simple docstring'''





												super(UpperCamelCase__    ,		self						).__init__()

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

												SCREAMING_SNAKE_CASE							:    List[Any]							=							DisjunctiveTrie(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    List[str]							=							nested_token_ids

												SCREAMING_SNAKE_CASE							:    Dict							=							self.trie.max_height
												SCREAMING_SNAKE_CASE							:    List[Any]							=							[]
												SCREAMING_SNAKE_CASE							:    int							=							False


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





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

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


						def        __A       (       self	:				Any    ,		UpperCamelCase__	:				int						):





												'''simple docstring'''





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

												SCREAMING_SNAKE_CASE							:    Dict							=							self.trie.next_tokens(self.current_seq						)

												return token_id in next_tokens


						def        __A       (       self	:				Union[str, Any]    ,		UpperCamelCase__	:				int						):





												'''simple docstring'''





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

												SCREAMING_SNAKE_CASE							:    Any							=							False
												SCREAMING_SNAKE_CASE							:    Optional[Any]							=							False
												SCREAMING_SNAKE_CASE							:    List[Any]							=							False

												if self.does_advance(UpperCamelCase__						):
																		self.current_seq.append(UpperCamelCase__						)
																		SCREAMING_SNAKE_CASE							:    Tuple							=							True
												else:
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							True
																		self.reset()

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

												return stepped, completed, reset


						def        __A       (       self	:				Any						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    str							=							False
												SCREAMING_SNAKE_CASE							:    List[Any]							=							[]


						def        __A       (       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        __A       (       self	:				Union[str, Any]    ,		UpperCamelCase__	:				int=False						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Optional[int]							=							DisjunctiveConstraint(self.token_ids						)

												if stateful:
																		SCREAMING_SNAKE_CASE							:    Any							=							self.seqlen
																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							self.current_seq
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							self.completed

												return new_constraint






class 					lowercase__						:


						def __init__(       self	:				str    ,		UpperCamelCase__	:				List[Constraint]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    List[str]							=							constraints

												# max # of steps required to fulfill a given constraint
												SCREAMING_SNAKE_CASE							:    List[str]							=							max([c.seqlen for c in constraints]						)
												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							len(UpperCamelCase__						)
												SCREAMING_SNAKE_CASE							:    List[str]							=							False

												self.init_state()


						def        __A       (       self	:				int						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    List[Any]							=							[]
												SCREAMING_SNAKE_CASE							:    Any							=							None
												SCREAMING_SNAKE_CASE							:    List[str]							=							[constraint.copy(stateful=UpperCamelCase__						) for constraint in self.constraints]


						def        __A       (       self	:				List[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    str							=							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        __A       (       self	:				List[str]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Optional[Any]							=							[]
												if self.inprogress_constraint is None:
																		for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
																								SCREAMING_SNAKE_CASE							:    str							=							constraint.advance()
																								if isinstance(UpperCamelCase__    ,		UpperCamelCase__						):
																														token_list.append(UpperCamelCase__						)
																								elif isinstance(UpperCamelCase__    ,		UpperCamelCase__						):
																														token_list.extend(UpperCamelCase__						)
												else:
																		SCREAMING_SNAKE_CASE							:    List[str]							=							self.inprogress_constraint.advance()
																		if isinstance(UpperCamelCase__    ,		UpperCamelCase__						):
																								token_list.append(UpperCamelCase__						)
																		elif isinstance(UpperCamelCase__    ,		UpperCamelCase__						):
																								token_list.extend(UpperCamelCase__						)

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


						def        __A       (       self	:				Union[str, Any]    ,		UpperCamelCase__	:				Optional[List[int]]						):





												'''simple docstring'''





												self.init_state()

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

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


						def        __A       (       self	:				int    ,		UpperCamelCase__	:				int						):





												'''simple docstring'''





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

												SCREAMING_SNAKE_CASE				,  SCREAMING_SNAKE_CASE							:    Tuple							=							False, False

												if self.completed:
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							True
																		SCREAMING_SNAKE_CASE							:    str							=							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

																		SCREAMING_SNAKE_CASE				,  SCREAMING_SNAKE_CASE				,  SCREAMING_SNAKE_CASE							:    Tuple							=							self.inprogress_constraint.update(UpperCamelCase__						)
																		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=UpperCamelCase__						)						)
																								SCREAMING_SNAKE_CASE							:    Any							=							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						)
																								SCREAMING_SNAKE_CASE							:    Dict							=							None

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

																														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(UpperCamelCase__						)
																																				SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							None

																														if not complete and stepped:
																																				SCREAMING_SNAKE_CASE							:    Optional[int]							=							pending_constraint

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

																																				SCREAMING_SNAKE_CASE							:    Optional[int]							=							(
																																				    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.

																																										SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							True

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

												return complete, stepped



						def        __A       (       self	:				str    ,		UpperCamelCase__	:				List[Any]=True						):





												'''simple docstring'''





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

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

												return new_state






import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402





class 					lowercase__						(   unittest.TestCase):


						def        __A       (       self	:				List[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Dict							=							0


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''						)
												self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    str							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		SCREAMING_SNAKE_CASE							:    Any							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				int						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Tuple							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Dict							=							CLIPConfig()

																		# Create a dummy config file with image_proceesor_type
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    List[str]							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		# remove image_processor_type to make sure config.json alone is enough to load image processor locally
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						).to_dict()

																		config_dict.pop('''image_processor_type'''						)
																		SCREAMING_SNAKE_CASE							:    str							=							CLIPImageProcessor(**UpperCamelCase__						)

																		# save in new folder
																		model_config.save_pretrained(UpperCamelCase__						)
																		config.save_pretrained(UpperCamelCase__						)

																		SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)

																		# make sure private variable is not incorrectly saved
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							json.loads(config.to_json_string()						)
																		self.assertTrue('''_processor_class''' not in dict_as_saved						)

												self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				Tuple						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)

																		SCREAMING_SNAKE_CASE							:    Dict							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				int						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		'''clip-base is not a local folder and is not a valid model identifier'''						):
																		SCREAMING_SNAKE_CASE							:    List[str]							=							AutoImageProcessor.from_pretrained('''clip-base'''						)


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''						):
																		SCREAMING_SNAKE_CASE							:    Tuple							=							AutoImageProcessor.from_pretrained(UpperCamelCase__    ,		revision='''aaaaaa'''						)


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''    ,		):
																		SCREAMING_SNAKE_CASE							:    Dict							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''						)


						def        __A       (       self	:				List[Any]						):





												'''simple docstring'''





												with self.assertRaises(UpperCamelCase__						):
																		SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''						)
												# If remote code is disabled, we can't load this config.
												with self.assertRaises(UpperCamelCase__						):
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)

												SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(
												    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
												self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)

												# Test image processor can be reloaded.
												with tempfile.TemporaryDirectory() as tmp_dir:
																		image_processor.save_pretrained(UpperCamelCase__						)
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__    ,		trust_remote_code=UpperCamelCase__						)
												self.assertEqual(reloaded_image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)


						def        __A       (       self	:				Optional[Any]						):





												'''simple docstring'''





												try:
																		AutoConfig.register('''custom'''    ,		UpperCamelCase__						)
																		AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)
																		# Trying to register something existing in the Transformers library will raise an error
																		with self.assertRaises(UpperCamelCase__						):
																								AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)

																		with tempfile.TemporaryDirectory() as tmpdirname:
																								SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																								SCREAMING_SNAKE_CASE							:    Any							=							Path(UpperCamelCase__						) / '''config.json'''
																								json.dump(
																								    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																								json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																								SCREAMING_SNAKE_CASE							:    Tuple							=							CustomImageProcessor.from_pretrained(UpperCamelCase__						)

																		# Now that the config is registered, it can be used as any other config with the auto-API
																		with tempfile.TemporaryDirectory() as tmp_dir:
																								image_processor.save_pretrained(UpperCamelCase__						)
																								SCREAMING_SNAKE_CASE							:    Any							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																								self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)

												finally:
																		if "custom" in CONFIG_MAPPING._extra_content:
																								del CONFIG_MAPPING._extra_content["custom"]
																		if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																								del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]



						def        __A       (       self	:				Any						):





												'''simple docstring'''





												class 					lowercase__						(   UpperCamelCase_):
																		UpperCamelCase_     =		True

												try:
																		AutoConfig.register('''custom'''    ,		UpperCamelCase__						)
																		AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)
																		# If remote code is not set, the default is to use local
																		SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(image_processor.is_local						)

																		# If remote code is disabled, we load the local one.
																		SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(image_processor.is_local						)

																		# If remote is enabled, we load from the Hub
																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(not hasattr(UpperCamelCase__    ,		'''is_local'''						)						)

												finally:
																		if "custom" in CONFIG_MAPPING._extra_content:
																								del CONFIG_MAPPING._extra_content["custom"]
																		if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																								del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]





