import argparse
import os
import re

import packaging.version


SCREAMING_SNAKE_CASE		:     Optional[Any]         =	"examples/"
SCREAMING_SNAKE_CASE		:     List[Any]         =	{
    "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"),
    "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"),
    "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","),
    "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"),
}
SCREAMING_SNAKE_CASE		:     List[str]         =	{
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
SCREAMING_SNAKE_CASE		:     str         =	"README.md"






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				Dict		, _SCREAMING_SNAKE_CASE     :				Optional[int]		, _SCREAMING_SNAKE_CASE     :				Optional[Any]			):
						with open(_SCREAMING_SNAKE_CASE		, """r"""		, encoding="""utf-8"""		, newline="""\n"""			) as f:
												UpperCamelCase_		:							Any  =		f.read()
						UpperCamelCase_,UpperCamelCase_		:							Optional[int]  =		REPLACE_PATTERNS[pattern]
						UpperCamelCase_		:							Dict  =		replace.replace("""VERSION"""		, _SCREAMING_SNAKE_CASE			)
						UpperCamelCase_		:							List[Any]  =		re_pattern.sub(_SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE			)
						with open(_SCREAMING_SNAKE_CASE		, """w"""		, encoding="""utf-8"""		, newline="""\n"""			) as f:
												f.write(_SCREAMING_SNAKE_CASE			)






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				Optional[int]			):
						for folder, directories, fnames in os.walk(_SCREAMING_SNAKE_CASE			):
												# Removing some of the folders with non-actively maintained examples from the walk
												if "research_projects" in directories:
																		directories.remove("""research_projects"""			)
												if "legacy" in directories:
																		directories.remove("""legacy"""			)
												for fname in fnames:
																		if fname.endswith(""".py"""			):
																								update_version_in_file(os.path.join(_SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE			)		, _SCREAMING_SNAKE_CASE		, pattern="""examples"""			)






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				Tuple		, _SCREAMING_SNAKE_CASE     :				Dict=False			):
						for pattern, fname in REPLACE_FILES.items():
												update_version_in_file(_SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE			)
						if not patch:
												update_version_in_examples(_SCREAMING_SNAKE_CASE			)






def     lowerCAmelCase_			(   ):
						UpperCamelCase_		:							Optional[Any]  =		"""🤗 Transformers currently provides the following architectures"""
						UpperCamelCase_		:							Optional[Any]  =		"""1. Want to contribute a new model?"""
						with open(_SCREAMING_SNAKE_CASE		, """r"""		, encoding="""utf-8"""		, newline="""\n"""			) as f:
												UpperCamelCase_		:							Any  =		f.readlines()

						# Find the start of the list.
						UpperCamelCase_		:							Tuple  =		0
						while not lines[start_index].startswith(_start_prompt			):
												start_index += 1
						start_index += 1

						UpperCamelCase_		:							Optional[int]  =		start_index
						# Update the lines in the model list.
						while not lines[index].startswith(_end_prompt			):
												if lines[index].startswith("""1."""			):
																		UpperCamelCase_		:							List[Any]  =		lines[index].replace(
																		    """https://huggingface.co/docs/transformers/main/model_doc"""		, """https://huggingface.co/docs/transformers/model_doc"""		, )
												index += 1

						with open(_SCREAMING_SNAKE_CASE		, """w"""		, encoding="""utf-8"""		, newline="""\n"""			) as f:
												f.writelines(_SCREAMING_SNAKE_CASE			)






def     lowerCAmelCase_			(   ):
						with open(REPLACE_FILES["""init"""]		, """r"""			) as f:
												UpperCamelCase_		:							int  =		f.read()
						UpperCamelCase_		:							int  =		REPLACE_PATTERNS["""init"""][0].search(_SCREAMING_SNAKE_CASE			).groups()[0]
						return packaging.version.parse(_SCREAMING_SNAKE_CASE			)






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				List[Any]=False			):
						UpperCamelCase_		:							List[str]  =		get_version()
						if patch and default_version.is_devrelease:
												raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!"""			)
						if default_version.is_devrelease:
												UpperCamelCase_		:							Optional[Any]  =		default_version.base_version
						elif patch:
												UpperCamelCase_		:							int  =		f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
						else:
												UpperCamelCase_		:							Optional[int]  =		f'''{default_version.major}.{default_version.minor + 1}.0'''

						# Now let's ask nicely if that's the right one.
						UpperCamelCase_		:							List[Any]  =		input(f'''Which version are you releasing? [{default_version}]'''			)
						if len(_SCREAMING_SNAKE_CASE			) == 0:
												UpperCamelCase_		:							Optional[Any]  =		default_version

						print(f'''Updating version to {version}.'''			)
						global_version_update(_SCREAMING_SNAKE_CASE		, patch=_SCREAMING_SNAKE_CASE			)
						if not patch:
												print("""Cleaning main README, don't forget to run `make fix-copies`."""			)
												clean_main_ref_in_model_list()






def     lowerCAmelCase_			(   ):
						UpperCamelCase_		:							str  =		get_version()
						UpperCamelCase_		:							int  =		f'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
						UpperCamelCase_		:							Tuple  =		current_version.base_version

						# Check with the user we got that right.
						UpperCamelCase_		:							List[Any]  =		input(f'''Which version are we developing now? [{dev_version}]'''			)
						if len(_SCREAMING_SNAKE_CASE			) == 0:
												UpperCamelCase_		:							Optional[Any]  =		dev_version

						print(f'''Updating version to {version}.'''			)
						global_version_update(_SCREAMING_SNAKE_CASE			)
						print("""Cleaning main README, don't forget to run `make fix-copies`."""			)
						clean_main_ref_in_model_list()


if __name__ == "__main__":
	SCREAMING_SNAKE_CASE		:     Union[str, Any]         =	argparse.ArgumentParser()
	parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
	parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
	SCREAMING_SNAKE_CASE		:     List[str]         =	parser.parse_args()
	if not args.post_release:
		pre_release_work(patch=args.patch)
	elif args.patch:
		print("Nothing to do after a patch :-)")
	else:
		post_release_work()







from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
	import torch

if is_tf_available():
	import tensorflow as tf

class        UpperCamelCase						(				__a				):
						a__		:str      =			['''image_processor''']
						a__		:str      =			'''SamImageProcessor'''





						def __init__(self			,     __UpperCamelCase						)				->				int:
												super().__init__(__UpperCamelCase						)
												UpperCamelCase_		:							Any  =		self.image_processor
												UpperCamelCase_		:							int  =		-10
												UpperCamelCase_		:							Dict  =		self.image_processor.size["""longest_edge"""]





						def __call__(self			,     __UpperCamelCase=None			,     __UpperCamelCase=None			,     __UpperCamelCase=None			,     __UpperCamelCase=None			,     __UpperCamelCase = None			,     **__UpperCamelCase			,     )				->				BatchEncoding:
												UpperCamelCase_		:							int  =		self.image_processor(
												    __UpperCamelCase			,     return_tensors=__UpperCamelCase			,     **__UpperCamelCase			,     )

												# pop arguments that are not used in the foward but used nevertheless
												UpperCamelCase_		:							Optional[int]  =		encoding_image_processor["""original_sizes"""]

												if hasattr(__UpperCamelCase			,     """numpy"""						):  # Checks if Torch or TF tensor
																		UpperCamelCase_		:							Dict  =		original_sizes.numpy()

												UpperCamelCase_,UpperCamelCase_,UpperCamelCase_		:							str  =		self._check_and_preprocess_points(
												    input_points=__UpperCamelCase			,     input_labels=__UpperCamelCase			,     input_boxes=__UpperCamelCase			,     )

												UpperCamelCase_		:							List[str]  =		self._normalize_and_convert(
												    __UpperCamelCase			,     __UpperCamelCase			,     input_points=__UpperCamelCase			,     input_labels=__UpperCamelCase			,     input_boxes=__UpperCamelCase			,     return_tensors=__UpperCamelCase			,     )

												return encoding_image_processor





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase=None			,     __UpperCamelCase=None			,     __UpperCamelCase=None			,     __UpperCamelCase="pt"			,     )				->				Tuple:
												if input_points is not None:
																		if len(__UpperCamelCase						) != len(__UpperCamelCase						):
																								UpperCamelCase_		:							str  =		[
																								    self._normalize_coordinates(self.target_size			,     __UpperCamelCase			,     original_sizes[0]						) for point in input_points
																								]
																		else:
																								UpperCamelCase_		:							List[str]  =		[
																								    self._normalize_coordinates(self.target_size			,     __UpperCamelCase			,     __UpperCamelCase						)
																								    for point, original_size in zip(__UpperCamelCase			,     __UpperCamelCase						)
																								]
																		# check that all arrays have the same shape
																		if not all(point.shape == input_points[0].shape for point in input_points						):
																								if input_labels is not None:
																														UpperCamelCase_,UpperCamelCase_		:							Optional[Any]  =		self._pad_points_and_labels(__UpperCamelCase			,     __UpperCamelCase						)

																		UpperCamelCase_		:							Dict  =		np.array(__UpperCamelCase						)

												if input_labels is not None:
																		UpperCamelCase_		:							Optional[Any]  =		np.array(__UpperCamelCase						)

												if input_boxes is not None:
																		if len(__UpperCamelCase						) != len(__UpperCamelCase						):
																								UpperCamelCase_		:							Tuple  =		[
																								    self._normalize_coordinates(self.target_size			,     __UpperCamelCase			,     original_sizes[0]			,     is_bounding_box=__UpperCamelCase						)
																								    for box in input_boxes
																								]
																		else:
																								UpperCamelCase_		:							Any  =		[
																								    self._normalize_coordinates(self.target_size			,     __UpperCamelCase			,     __UpperCamelCase			,     is_bounding_box=__UpperCamelCase						)
																								    for box, original_size in zip(__UpperCamelCase			,     __UpperCamelCase						)
																								]
																		UpperCamelCase_		:							int  =		np.array(__UpperCamelCase						)

												if input_boxes is not None:
																		if return_tensors == "pt":
																								UpperCamelCase_		:							Union[str, Any]  =		torch.from_numpy(__UpperCamelCase						)
																								# boxes batch size of 1 by default
																								UpperCamelCase_		:							Any  =		input_boxes.unsqueeze(1						) if len(input_boxes.shape						) != 3 else input_boxes
																		elif return_tensors == "tf":
																								UpperCamelCase_		:							List[str]  =		tf.convert_to_tensor(__UpperCamelCase						)
																								# boxes batch size of 1 by default
																								UpperCamelCase_		:							Optional[int]  =		tf.expand_dims(__UpperCamelCase			,     1						) if len(input_boxes.shape						) != 3 else input_boxes
																		encoding_image_processor.update({"""input_boxes""": input_boxes}						)
												if input_points is not None:
																		if return_tensors == "pt":
																								UpperCamelCase_		:							Optional[Any]  =		torch.from_numpy(__UpperCamelCase						)
																								# point batch size of 1 by default
																								UpperCamelCase_		:							List[Any]  =		input_points.unsqueeze(1						) if len(input_points.shape						) != 4 else input_points
																		elif return_tensors == "tf":
																								UpperCamelCase_		:							Optional[Any]  =		tf.convert_to_tensor(__UpperCamelCase						)
																								# point batch size of 1 by default
																								UpperCamelCase_		:							Dict  =		tf.expand_dims(__UpperCamelCase			,     1						) if len(input_points.shape						) != 4 else input_points
																		encoding_image_processor.update({"""input_points""": input_points}						)
												if input_labels is not None:
																		if return_tensors == "pt":
																								UpperCamelCase_		:							Optional[int]  =		torch.from_numpy(__UpperCamelCase						)
																								# point batch size of 1 by default
																								UpperCamelCase_		:							Tuple  =		input_labels.unsqueeze(1						) if len(input_labels.shape						) != 3 else input_labels
																		elif return_tensors == "tf":
																								UpperCamelCase_		:							Optional[Any]  =		tf.convert_to_tensor(__UpperCamelCase						)
																								# point batch size of 1 by default
																								UpperCamelCase_		:							Dict  =		tf.expand_dims(__UpperCamelCase			,     1						) if len(input_labels.shape						) != 3 else input_labels
																		encoding_image_processor.update({"""input_labels""": input_labels}						)

												return encoding_image_processor





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase						)				->				Tuple:
												UpperCamelCase_		:							Union[str, Any]  =		max([point.shape[0] for point in input_points]						)
												UpperCamelCase_		:							Any  =		[]
												for i, point in enumerate(__UpperCamelCase						):
																		if point.shape[0] != expected_nb_points:
																								UpperCamelCase_		:							Optional[int]  =		np.concatenate(
																								    [point, np.zeros((expected_nb_points - point.shape[0], 2)						) + self.point_pad_value]			,     axis=0						)
																								UpperCamelCase_		:							Dict  =		np.append(input_labels[i]			,     [self.point_pad_value]						)
																		processed_input_points.append(__UpperCamelCase						)
												UpperCamelCase_		:							List[Any]  =		processed_input_points
												return input_points, input_labels





						def        A_							(self			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase			,     __UpperCamelCase=False						)				->				np.ndarray:
												UpperCamelCase_,UpperCamelCase_		:							Optional[int]  =		original_size
												UpperCamelCase_,UpperCamelCase_		:							List[str]  =		self.image_processor._get_preprocess_shape(__UpperCamelCase			,     longest_edge=__UpperCamelCase						)
												UpperCamelCase_		:							str  =		deepcopy(__UpperCamelCase						).astype(__UpperCamelCase						)

												if is_bounding_box:
																		UpperCamelCase_		:							int  =		coords.reshape(-1			,     2			,     2						)

												UpperCamelCase_		:							Tuple  =		coords[..., 0] * (new_w / old_w)
												UpperCamelCase_		:							Optional[int]  =		coords[..., 1] * (new_h / old_h)

												if is_bounding_box:
																		UpperCamelCase_		:							Optional[Any]  =		coords.reshape(-1			,     4						)

												return coords





						def        A_							(self			,     __UpperCamelCase=None			,     __UpperCamelCase=None			,     __UpperCamelCase=None			,     )				->				List[str]:
												if input_points is not None:
																		if hasattr(__UpperCamelCase			,     """numpy"""						):  # Checks for TF or Torch tensor
																								UpperCamelCase_		:							int  =		input_points.numpy().tolist()

																		if not isinstance(__UpperCamelCase			,     __UpperCamelCase						) or not isinstance(input_points[0]			,     __UpperCamelCase						):
																								raise ValueError("""Input points must be a list of list of floating points."""						)
																		UpperCamelCase_		:							List[Any]  =		[np.array(__UpperCamelCase						) for input_point in input_points]
												else:
																		UpperCamelCase_		:							str  =		None

												if input_labels is not None:
																		if hasattr(__UpperCamelCase			,     """numpy"""						):
																								UpperCamelCase_		:							Any  =		input_labels.numpy().tolist()

																		if not isinstance(__UpperCamelCase			,     __UpperCamelCase						) or not isinstance(input_labels[0]			,     __UpperCamelCase						):
																								raise ValueError("""Input labels must be a list of list integers."""						)
																		UpperCamelCase_		:							List[str]  =		[np.array(__UpperCamelCase						) for label in input_labels]
												else:
																		UpperCamelCase_		:							List[str]  =		None

												if input_boxes is not None:
																		if hasattr(__UpperCamelCase			,     """numpy"""						):
																								UpperCamelCase_		:							Dict  =		input_boxes.numpy().tolist()

																		if (
																		    not isinstance(__UpperCamelCase			,     __UpperCamelCase						)
																		    or not isinstance(input_boxes[0]			,     __UpperCamelCase						)
																		    or not isinstance(input_boxes[0][0]			,     __UpperCamelCase						)
																		):
																								raise ValueError("""Input boxes must be a list of list of list of floating points."""						)
																		UpperCamelCase_		:							Tuple  =		[np.array(__UpperCamelCase						).astype(np.floataa						) for box in input_boxes]
												else:
																		UpperCamelCase_		:							List[str]  =		None

												return input_points, input_labels, input_boxes





						@property
						def        A_							(self						)				->				List[str]:
												UpperCamelCase_		:							str  =		self.image_processor.model_input_names
												return list(dict.fromkeys(__UpperCamelCase						)						)





						def        A_							(self			,     *__UpperCamelCase			,     **__UpperCamelCase						)				->				Optional[Any]:
												return self.image_processor.post_process_masks(*__UpperCamelCase			,     **__UpperCamelCase						)






