import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowercase__      :    Optional[Any]          =     logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=2.0.0''', '''To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt''')

def        SCREAMING_SNAKE_CASE_					(						snake_case__       ,  snake_case__       ,  snake_case__=0							)					->     Any:
							lowerCAmelCase     		=		(size, size) if isinstance(snake_case__       ,  snake_case__							) else size
							lowerCAmelCase		,				lowerCAmelCase     		=		img.size
							lowerCAmelCase     		=		size[1] - original_height if original_height < size[1] else 0
							lowerCAmelCase     		=		size[0] - original_width if original_width < size[0] else 0
							lowerCAmelCase     		=		functional.pad(snake_case__       ,  (0, 0, pad_width, pad_height)       ,  fill=snake_case__							)
							return img




class        lowercase_  :



	"""simple docstring"""





	def __init__(							self		,      __SCREAMING_SNAKE_CASE    )						->str:
								lowerCAmelCase     		=		transforms




	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->List[str]:
								for t in self.transforms:
															lowerCAmelCase		,				lowerCAmelCase     		=		t(__SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __init__(							self    )						->Optional[int]:
								pass




	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->List[Any]:
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __init__(							self		,      __SCREAMING_SNAKE_CASE    )						->Dict:
								lowerCAmelCase     		=		size




	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->Optional[Any]:
								lowerCAmelCase     		=		functional.resize(__SCREAMING_SNAKE_CASE		,      self.size    )
								lowerCAmelCase     		=		functional.resize(__SCREAMING_SNAKE_CASE		,      self.size		,      interpolation=transforms.InterpolationMode.NEAREST    )
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __init__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE=None    )						->Optional[int]:
								lowerCAmelCase     		=		min_size
								if max_size is None:
															lowerCAmelCase     		=		min_size
								lowerCAmelCase     		=		max_size




	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->Any:
								lowerCAmelCase     		=		random.randint(self.min_size		,      self.max_size    )
								lowerCAmelCase     		=		functional.resize(__SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )
								lowerCAmelCase     		=		functional.resize(__SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE		,      interpolation=transforms.InterpolationMode.NEAREST    )
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __init__(							self		,      __SCREAMING_SNAKE_CASE    )						->int:
								lowerCAmelCase     		=		size if isinstance(__SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    ) else (size, size)




	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->Tuple:
								lowerCAmelCase     		=		pad_if_smaller(__SCREAMING_SNAKE_CASE		,      self.size    )
								lowerCAmelCase     		=		pad_if_smaller(__SCREAMING_SNAKE_CASE		,      self.size		,      fill=255    )
								lowerCAmelCase     		=		transforms.RandomCrop.get_params(__SCREAMING_SNAKE_CASE		,      self.size    )
								lowerCAmelCase     		=		functional.crop(__SCREAMING_SNAKE_CASE		,      *__SCREAMING_SNAKE_CASE    )
								lowerCAmelCase     		=		functional.crop(__SCREAMING_SNAKE_CASE		,      *__SCREAMING_SNAKE_CASE    )
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __init__(							self		,      __SCREAMING_SNAKE_CASE    )						->str:
								lowerCAmelCase     		=		flip_prob




	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->List[str]:
								if random.random() < self.flip_prob:
															lowerCAmelCase     		=		functional.hflip(__SCREAMING_SNAKE_CASE    )
															lowerCAmelCase     		=		functional.hflip(__SCREAMING_SNAKE_CASE    )
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->str:
								lowerCAmelCase     		=		functional.pil_to_tensor(__SCREAMING_SNAKE_CASE    )
								lowerCAmelCase     		=		torch.as_tensor(np.array(__SCREAMING_SNAKE_CASE    )		,      dtype=torch.intaa    )
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __init__(							self		,      __SCREAMING_SNAKE_CASE    )						->Dict:
								lowerCAmelCase     		=		dtype




	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->Optional[int]:
								lowerCAmelCase     		=		functional.convert_image_dtype(__SCREAMING_SNAKE_CASE		,      self.dtype    )
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __init__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->Any:
								lowerCAmelCase     		=		mean
								lowerCAmelCase     		=		std




	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->Any:
								lowerCAmelCase     		=		functional.normalize(__SCREAMING_SNAKE_CASE		,      mean=self.mean		,      std=self.std    )
								return image, target




class        lowercase_  :



	"""simple docstring"""





	def __call__(							self		,      __SCREAMING_SNAKE_CASE		,      __SCREAMING_SNAKE_CASE    )						->List[Any]:
								if not isinstance(__SCREAMING_SNAKE_CASE		,      np.ndarray    ):
															lowerCAmelCase     		=		np.array(__SCREAMING_SNAKE_CASE    ).astype(np.uinta    )
								# avoid using underflow conversion
								lowerCAmelCase     		=		255
								lowerCAmelCase     		=		target - 1
								lowerCAmelCase     		=		255

								lowerCAmelCase     		=		Image.fromarray(__SCREAMING_SNAKE_CASE    )
								return image, target




@dataclass
class        lowercase_  :



	"""simple docstring"""





	UpperCAmelCase_  : Optional[str]       =    field(
	    default="""segments/sidewalk-semantic"""				,					metadata={
	        """help""": """Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."""
	    }				,					)
	UpperCAmelCase_  : Optional[str]       =    field(
	    default=UpperCamelCase_				,					metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}						)
	UpperCAmelCase_  : Optional[float]       =    field(
	    default=0.15				,					metadata={"""help""": """Percent to split off of train for validation."""}						)
	UpperCAmelCase_  : Optional[int]       =    field(
	    default=UpperCamelCase_				,					metadata={
	        """help""": (
	            """For debugging purposes or quicker training, truncate the number of training examples to this """
	            """value if set."""
	        )
	    }				,					)
	UpperCAmelCase_  : Optional[int]       =    field(
	    default=UpperCamelCase_				,					metadata={
	        """help""": (
	            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
	            """value if set."""
	        )
	    }				,					)
	UpperCAmelCase_  : Optional[bool]       =    field(
	    default=UpperCamelCase_				,					metadata={"""help""": """Whether or not to reduce all labels by 1 and replace background by 255."""}				,					)


	def       SCREAMING_SNAKE_CASE_    (							self    )						->Optional[int]:
								if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
															raise ValueError(
															    '''You must specify either a dataset name from the hub or a train and/or validation directory.'''    )




@dataclass
class        lowercase_  :



	"""simple docstring"""





	UpperCAmelCase_  : str       =    field(
	    default="""nvidia/mit-b0"""				,					metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}				,					)
	UpperCAmelCase_  : Optional[str]       =    field(
	    default=UpperCamelCase_				,					metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}						)
	UpperCAmelCase_  : Optional[str]       =    field(
	    default=UpperCamelCase_				,					metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""}						)
	UpperCAmelCase_  : str       =    field(
	    default="""main"""				,					metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}				,					)
	UpperCAmelCase_  : str       =    field(default=UpperCamelCase_				,					metadata={"""help""": """Name or path of preprocessor config."""}						)
	UpperCAmelCase_  : bool       =    field(
	    default=UpperCamelCase_				,					metadata={
	        """help""": (
	            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
	            """with private models)."""
	        )
	    }				,					)

def        SCREAMING_SNAKE_CASE_					(						)					->     str:
							# See all possible arguments in src/transformers/training_args.py
							# or by passing the --help flag to this script.
							# We now keep distinct sets of args, for a cleaner separation of concerns.

							lowerCAmelCase     		=		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)
							if len(sys.argv							) == 2 and sys.argv[1].endswith('''.json'''							):
														# If we pass only one argument to the script and it's the path to a json file,
														# let's parse it to get our arguments.
														lowerCAmelCase		,				lowerCAmelCase		,				lowerCAmelCase     		=		parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]							)							)
							else:
														lowerCAmelCase		,				lowerCAmelCase		,				lowerCAmelCase     		=		parser.parse_args_into_dataclasses()

							# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
							# information sent is the one passed as arguments along with your Python/PyTorch versions.
							send_example_telemetry('''run_semantic_segmentation'''       ,  snake_case__       ,  snake_case__							)

							# Setup logging
							logging.basicConfig(
							    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''       ,  datefmt='''%m/%d/%Y %H:%M:%S'''       ,  handlers=[logging.StreamHandler(sys.stdout							)]       ,  )

							if training_args.should_log:
														# The default of training_args.log_level is passive, so we set log level at info here to have that default.
														transformers.utils.logging.set_verbosity_info()

							lowerCAmelCase     		=		training_args.get_process_log_level()
							logger.setLevel(snake_case__							)
							transformers.utils.logging.set_verbosity(snake_case__							)
							transformers.utils.logging.enable_default_handler()
							transformers.utils.logging.enable_explicit_format()

							# Log on each process the small summary:
							logger.warning(
							    f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
							    + f"distributed training: {bool(training_args.local_rank != -1							)}, 16-bits training: {training_args.fpaa}"							)
							logger.info(f"Training/evaluation parameters {training_args}"							)

							# Detecting last checkpoint.
							lowerCAmelCase     		=		None
							if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
														lowerCAmelCase     		=		get_last_checkpoint(training_args.output_dir							)
														if last_checkpoint is None and len(os.listdir(training_args.output_dir							)							) > 0:
																					raise ValueError(
																					    f"Output directory ({training_args.output_dir}) already exists and is not empty. "
																					    '''Use --overwrite_output_dir to overcome.'''							)
														elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
																					logger.info(
																					    f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
																					    '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''							)

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
							lowerCAmelCase     		=		load_dataset(data_args.dataset_name       ,  cache_dir=model_args.cache_dir							)

							# Rename column names to standardized names (only "image" and "label" need to be present)
							if "pixel_values" in dataset["train"].column_names:
														lowerCAmelCase     		=		dataset.rename_columns({'''pixel_values''': '''image'''}							)
							if "annotation" in dataset["train"].column_names:
														lowerCAmelCase     		=		dataset.rename_columns({'''annotation''': '''label'''}							)

							# If we don't have a validation split, split off a percentage of train as validation.
							lowerCAmelCase     		=		None if '''validation''' in dataset.keys() else data_args.train_val_split
							if isinstance(data_args.train_val_split       ,  snake_case__							) and data_args.train_val_split > 0.0:
														lowerCAmelCase     		=		dataset['''train'''].train_test_split(data_args.train_val_split							)
														lowerCAmelCase     		=		split['''train''']
														lowerCAmelCase     		=		split['''test''']

							# Prepare label mappings.
							# We'll include these in the model's config to get human readable labels in the Inference API.
							if data_args.dataset_name == "scene_parse_150":
														lowerCAmelCase     		=		'''huggingface/label-files'''
														lowerCAmelCase     		=		'''ade20k-id2label.json'''
							else:
														lowerCAmelCase     		=		data_args.dataset_name
														lowerCAmelCase     		=		'''id2label.json'''
							lowerCAmelCase     		=		json.load(open(hf_hub_download(snake_case__       ,  snake_case__       ,  repo_type='''dataset'''							)       ,  '''r'''							)							)
							lowerCAmelCase     		=		{int(snake_case__							): v for k, v in idalabel.items()}
							lowerCAmelCase     		=		{v: str(snake_case__							) for k, v in idalabel.items()}

							# Load the mean IoU metric from the datasets package
							lowerCAmelCase     		=		evaluate.load('''mean_iou'''							)

							# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
							# predictions and label_ids field) and has to return a dictionary string to float.
							@torch.no_grad()
							def compute_metrics(snake_case__							):
														lowerCAmelCase		,				lowerCAmelCase     		=		eval_pred
														lowerCAmelCase     		=		torch.from_numpy(snake_case__							)
														# scale the logits to the size of the label
														lowerCAmelCase     		=		nn.functional.interpolate(
														    snake_case__       ,  size=labels.shape[-2:]       ,  mode='''bilinear'''       ,  align_corners=snake_case__       ,  ).argmax(dim=1							)

														lowerCAmelCase     		=		logits_tensor.detach().cpu().numpy()
														lowerCAmelCase     		=		metric.compute(
														    predictions=snake_case__       ,  references=snake_case__       ,  num_labels=len(snake_case__							)       ,  ignore_index=0       ,  reduce_labels=image_processor.do_reduce_labels       ,  )
														# add per category metrics as individual key-value pairs
														lowerCAmelCase     		=		metrics.pop('''per_category_accuracy'''							).tolist()
														lowerCAmelCase     		=		metrics.pop('''per_category_iou'''							).tolist()

														metrics.update({f"accuracy_{idalabel[i]}": v for i, v in enumerate(snake_case__							)}							)
														metrics.update({f"iou_{idalabel[i]}": v for i, v in enumerate(snake_case__							)}							)

														return metrics

							lowerCAmelCase     		=		AutoConfig.from_pretrained(
							    model_args.config_name or model_args.model_name_or_path       ,  labelaid=snake_case__       ,  idalabel=snake_case__       ,  cache_dir=model_args.cache_dir       ,  revision=model_args.model_revision       ,  use_auth_token=True if model_args.use_auth_token else None       ,  )
							lowerCAmelCase     		=		AutoModelForSemanticSegmentation.from_pretrained(
							    model_args.model_name_or_path       ,  from_tf=bool('''.ckpt''' in model_args.model_name_or_path							)       ,  config=snake_case__       ,  cache_dir=model_args.cache_dir       ,  revision=model_args.model_revision       ,  use_auth_token=True if model_args.use_auth_token else None       ,  )
							lowerCAmelCase     		=		AutoImageProcessor.from_pretrained(
							    model_args.image_processor_name or model_args.model_name_or_path       ,  cache_dir=model_args.cache_dir       ,  revision=model_args.model_revision       ,  use_auth_token=True if model_args.use_auth_token else None       ,  )

							# Define torchvision transforms to be applied to each image + target.
							# Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
							# Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
							if "shortest_edge" in image_processor.size:
														# We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
														lowerCAmelCase     		=		(image_processor.size['''shortest_edge'''], image_processor.size['''shortest_edge'''])
							else:
														lowerCAmelCase     		=		(image_processor.size['''height'''], image_processor.size['''width'''])
							lowerCAmelCase     		=		Compose(
							    [
							        ReduceLabels() if data_args.reduce_labels else Identity(),
							        RandomCrop(size=snake_case__							),
							        RandomHorizontalFlip(flip_prob=0.5							),
							        PILToTensor(),
							        ConvertImageDtype(torch.float							),
							        Normalize(mean=image_processor.image_mean       ,  std=image_processor.image_std							),
							    ]							)
							# Define torchvision transform to be applied to each image.
							# jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
							lowerCAmelCase     		=		Compose(
							    [
							        ReduceLabels() if data_args.reduce_labels else Identity(),
							        Resize(size=snake_case__							),
							        PILToTensor(),
							        ConvertImageDtype(torch.float							),
							        Normalize(mean=image_processor.image_mean       ,  std=image_processor.image_std							),
							    ]							)

							def preprocess_train(snake_case__							):
														lowerCAmelCase     		=		[]
														lowerCAmelCase     		=		[]
														for image, target in zip(example_batch['''image''']       ,  example_batch['''label''']							):
																					lowerCAmelCase		,				lowerCAmelCase     		=		train_transforms(image.convert('''RGB'''							)       ,  snake_case__							)
																					pixel_values.append(snake_case__							)
																					labels.append(snake_case__							)

														lowerCAmelCase     		=		{}
														lowerCAmelCase     		=		torch.stack(snake_case__							)
														lowerCAmelCase     		=		torch.stack(snake_case__							)

														return encoding

							def preprocess_val(snake_case__							):
														lowerCAmelCase     		=		[]
														lowerCAmelCase     		=		[]
														for image, target in zip(example_batch['''image''']       ,  example_batch['''label''']							):
																					lowerCAmelCase		,				lowerCAmelCase     		=		val_transforms(image.convert('''RGB'''							)       ,  snake_case__							)
																					pixel_values.append(snake_case__							)
																					labels.append(snake_case__							)

														lowerCAmelCase     		=		{}
														lowerCAmelCase     		=		torch.stack(snake_case__							)
														lowerCAmelCase     		=		torch.stack(snake_case__							)

														return encoding

							if training_args.do_train:
														if "train" not in dataset:
																					raise ValueError('''--do_train requires a train dataset'''							)
														if data_args.max_train_samples is not None:
																					lowerCAmelCase     		=		(
																					    dataset['''train'''].shuffle(seed=training_args.seed							).select(range(data_args.max_train_samples							)							)
																					)
														# Set the training transforms
														dataset["train"].set_transform(snake_case__							)

							if training_args.do_eval:
														if "validation" not in dataset:
																					raise ValueError('''--do_eval requires a validation dataset'''							)
														if data_args.max_eval_samples is not None:
																					lowerCAmelCase     		=		(
																					    dataset['''validation'''].shuffle(seed=training_args.seed							).select(range(data_args.max_eval_samples							)							)
																					)
														# Set the validation transforms
														dataset["validation"].set_transform(snake_case__							)

							# Initalize our trainer
							lowerCAmelCase     		=		Trainer(
							    model=snake_case__       ,  args=snake_case__       ,  train_dataset=dataset['''train'''] if training_args.do_train else None       ,  eval_dataset=dataset['''validation'''] if training_args.do_eval else None       ,  compute_metrics=snake_case__       ,  tokenizer=snake_case__       ,  data_collator=snake_case__       ,  )

							# Training
							if training_args.do_train:
														lowerCAmelCase     		=		None
														if training_args.resume_from_checkpoint is not None:
																					lowerCAmelCase     		=		training_args.resume_from_checkpoint
														elif last_checkpoint is not None:
																					lowerCAmelCase     		=		last_checkpoint
														lowerCAmelCase     		=		trainer.train(resume_from_checkpoint=snake_case__							)
														trainer.save_model()
														trainer.log_metrics('''train'''       ,  train_result.metrics							)
														trainer.save_metrics('''train'''       ,  train_result.metrics							)
														trainer.save_state()

							# Evaluation
							if training_args.do_eval:
														lowerCAmelCase     		=		trainer.evaluate()
														trainer.log_metrics('''eval'''       ,  snake_case__							)
														trainer.save_metrics('''eval'''       ,  snake_case__							)

							# Write model card and (optionally) push to hub
							lowerCAmelCase     		=		{
							    '''finetuned_from''': model_args.model_name_or_path,
							    '''dataset''': data_args.dataset_name,
							    '''tags''': ['''image-segmentation''', '''vision'''],
							}
							if training_args.push_to_hub:
														trainer.push_to_hub(**snake_case__							)
							else:
														trainer.create_model_card(**snake_case__							)


if __name__ == "__main__":
	main()




from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


lowercase__      :    Dict          =     {
    '''configuration_sam''': [
        '''SAM_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''SamConfig''',
        '''SamMaskDecoderConfig''',
        '''SamPromptEncoderConfig''',
        '''SamVisionConfig''',
    ],
    '''processing_sam''': ['''SamProcessor'''],
}


try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	lowercase__      :    Dict          =     [
	    '''SAM_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''SamModel''',
	    '''SamPreTrainedModel''',
	]
try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	lowercase__      :    str          =     [
	    '''TF_SAM_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''TFSamModel''',
	    '''TFSamPreTrainedModel''',
	]
try:
	if not is_vision_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	lowercase__      :    Dict          =     ['''SamImageProcessor''']


if TYPE_CHECKING:
	from .configuration_sam import (
	    SAM_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    SamConfig,
	    SamMaskDecoderConfig,
	    SamPromptEncoderConfig,
	    SamVisionConfig,
	)
	from .processing_sam import SamProcessor

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_sam import SAM_PRETRAINED_MODEL_ARCHIVE_LIST, SamModel, SamPreTrainedModel

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_sam import TF_SAM_PRETRAINED_MODEL_ARCHIVE_LIST, TFSamModel, TFSamPreTrainedModel

	try:
		if not is_vision_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .image_processing_sam import SamImageProcessor

else:
	import sys

	lowercase__      :    Dict          =     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



