


import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
						import torch



class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			'''char'''
					A__      =			'''bpe'''
					A__      =			'''wp'''






A	:		List[Any]    =       (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)



class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			['''image_processor''', '''char_tokenizer''']
					A__      =			'''ViTImageProcessor'''
					A__      =			'''MgpstrTokenizer'''

					def __init__(self   :						List[str]				, _UpperCAmelCase   :						Tuple=None				, _UpperCAmelCase   :						Any=None				, **_UpperCAmelCase   :						Any		)						->       Union[str, Any]:




							"""simple docstring"""


							lowercase__					      =		None
							if "feature_extractor" in kwargs:
									warnings.warn(
									    """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
									    """ instead."""				, _UpperCAmelCase				, )
									lowercase__					      =		kwargs.pop("""feature_extractor"""		)

							lowercase__					      =		image_processor if image_processor is not None else feature_extractor
							if image_processor is None:
									raise ValueError("""You need to specify an `image_processor`."""		)
							if tokenizer is None:
									raise ValueError("""You need to specify a `tokenizer`."""		)

							lowercase__					      =		tokenizer
							lowercase__					      =		AutoTokenizer.from_pretrained("""gpt2"""		)
							lowercase__					      =		AutoTokenizer.from_pretrained("""bert-base-uncased"""		)

							super().__init__(_UpperCAmelCase				, _UpperCAmelCase		)

					def __call__(self   :						Tuple				, _UpperCAmelCase   :						List[str]=None				, _UpperCAmelCase   :						Optional[int]=None				, _UpperCAmelCase   :						Any=None				, **_UpperCAmelCase   :						Optional[int]		)						->       Any:




							"""simple docstring"""


							if images is None and text is None:
									raise ValueError("""You need to specify either an `images` or `text` input to process."""		)

							if images is not None:
									lowercase__					      =		self.image_processor(_UpperCAmelCase				, return_tensors=_UpperCAmelCase				, **_UpperCAmelCase		)
							if text is not None:
									lowercase__					      =		self.char_tokenizer(_UpperCAmelCase				, return_tensors=_UpperCAmelCase				, **_UpperCAmelCase		)

							if text is None:
									return inputs
							elif images is None:
									return encodings
							else:
									lowercase__					      =		encodings["""input_ids"""]
									return inputs

					def   lowerCamelCase__					(self   :						int				, _UpperCAmelCase   :						List[str]		)						->       List[str]:




							"""simple docstring"""


							lowercase__      ,     lowercase__      ,     lowercase__					      =		sequences
							lowercase__					      =		char_preds.size(0		)

							lowercase__      ,     lowercase__					      =		self._decode_helper(_UpperCAmelCase				, """char"""		)
							lowercase__      ,     lowercase__					      =		self._decode_helper(_UpperCAmelCase				, """bpe"""		)
							lowercase__      ,     lowercase__					      =		self._decode_helper(_UpperCAmelCase				, """wp"""		)

							lowercase__					      =		[]
							lowercase__					      =		[]
							for i in range(_UpperCAmelCase		):
									lowercase__					      =		[char_scores[i], bpe_scores[i], wp_scores[i]]
									lowercase__					      =		[char_strs[i], bpe_strs[i], wp_strs[i]]
									lowercase__					      =		scores.index(max(_UpperCAmelCase		)		)
									final_strs.append(strs[max_score_index]		)
									final_scores.append(scores[max_score_index]		)

							lowercase__					      =		{}
							lowercase__					      =		final_strs
							lowercase__					      =		final_scores
							lowercase__					      =		char_strs
							lowercase__					      =		bpe_strs
							lowercase__					      =		wp_strs
							return out

					def   lowerCamelCase__					(self   :						List[Any]				, _UpperCAmelCase   :						Optional[int]				, _UpperCAmelCase   :						List[Any]		)						->       Any:




							"""simple docstring"""


							if format == DecodeType.CHARACTER:
									lowercase__					      =		self.char_decode
									lowercase__					      =		1
									lowercase__					      =		"""[s]"""
							elif format == DecodeType.BPE:
									lowercase__					      =		self.bpe_decode
									lowercase__					      =		2
									lowercase__					      =		"""#"""
							elif format == DecodeType.WORDPIECE:
									lowercase__					      =		self.wp_decode
									lowercase__					      =		102
									lowercase__					      =		"""[SEP]"""
							else:
									raise ValueError(f'''Format {format} is not supported.'''		)

							lowercase__      ,     lowercase__					      =		[], []
							lowercase__					      =		pred_logits.size(0		)
							lowercase__					      =		pred_logits.size(1		)
							lowercase__      ,     lowercase__					      =		pred_logits.topk(1				, dim=-1				, largest=_UpperCAmelCase				, sorted=_UpperCAmelCase		)
							lowercase__					      =		preds_index.view(-1				, _UpperCAmelCase		)[:, 1:]
							lowercase__					      =		decoder(_UpperCAmelCase		)
							lowercase__      ,     lowercase__					      =		torch.nn.functional.softmax(_UpperCAmelCase				, dim=2		).max(dim=2		)
							lowercase__					      =		preds_max_prob[:, 1:]

							for index in range(_UpperCAmelCase		):
									lowercase__					      =		preds_str[index].find(_UpperCAmelCase		)
									lowercase__					      =		preds_str[index][:pred_eos]
									lowercase__					      =		preds_index[index].cpu().tolist()
									lowercase__					      =		pred_index.index(_UpperCAmelCase		) if eos_token in pred_index else -1
									lowercase__					      =		preds_max_prob[index][: pred_eos_index + 1]
									lowercase__					      =		pred_max_prob.cumprod(dim=0		)[-1] if pred_max_prob.nelement() != 0 else 0.0
									dec_strs.append(_UpperCAmelCase		)
									conf_scores.append(_UpperCAmelCase		)

							return dec_strs, conf_scores

					def   lowerCamelCase__					(self   :						Any				, _UpperCAmelCase   :						List[str]		)						->       Dict:




							"""simple docstring"""


							lowercase__					      =		[seq.replace(""" """				, """"""		) for seq in self.char_tokenizer.batch_decode(_UpperCAmelCase		)]
							return decode_strs

					def   lowerCamelCase__					(self   :						Dict				, _UpperCAmelCase   :						Union[str, Any]		)						->       int:




							"""simple docstring"""


							return self.bpe_tokenizer.batch_decode(_UpperCAmelCase		)


					def   lowerCamelCase__					(self   :						Optional[Any]				, _UpperCAmelCase   :						List[Any]		)						->       Tuple:




							"""simple docstring"""


							lowercase__					      =		[seq.replace(""" """				, """"""		) for seq in self.wp_tokenizer.batch_decode(_UpperCAmelCase		)]
							return decode_strs





import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A	:		List[str]    =       logging.get_logger(__name__)

A	:		List[Any]    =       {
    'nvidia/segformer-b0-finetuned-ade-512-512': (
        'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}



class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			'''segformer'''

					def __init__(self   :						Dict				, _UpperCAmelCase   :						Optional[int]=3				, _UpperCAmelCase   :						Dict=4				, _UpperCAmelCase   :						Union[str, Any]=[2, 2, 2, 2]				, _UpperCAmelCase   :						List[str]=[8, 4, 2, 1]				, _UpperCAmelCase   :						str=[32, 64, 160, 256]				, _UpperCAmelCase   :						Optional[int]=[7, 3, 3, 3]				, _UpperCAmelCase   :						int=[4, 2, 2, 2]				, _UpperCAmelCase   :						str=[1, 2, 5, 8]				, _UpperCAmelCase   :						Optional[int]=[4, 4, 4, 4]				, _UpperCAmelCase   :						List[Any]="gelu"				, _UpperCAmelCase   :						Optional[Any]=0.0				, _UpperCAmelCase   :						Dict=0.0				, _UpperCAmelCase   :						Dict=0.1				, _UpperCAmelCase   :						List[str]=0.02				, _UpperCAmelCase   :						str=0.1				, _UpperCAmelCase   :						Optional[Any]=1E-6				, _UpperCAmelCase   :						Optional[Any]=256				, _UpperCAmelCase   :						Any=255				, **_UpperCAmelCase   :						str				, )						->       Tuple:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase		)

							if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
									warnings.warn(
									    """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"""
									    """ removed, as the behaviour will default to that of reshape_last_stage = True."""				, _UpperCAmelCase				, )

							lowercase__					      =		num_channels
							lowercase__					      =		num_encoder_blocks
							lowercase__					      =		depths
							lowercase__					      =		sr_ratios
							lowercase__					      =		hidden_sizes
							lowercase__					      =		patch_sizes
							lowercase__					      =		strides
							lowercase__					      =		mlp_ratios
							lowercase__					      =		num_attention_heads
							lowercase__					      =		hidden_act
							lowercase__					      =		hidden_dropout_prob
							lowercase__					      =		attention_probs_dropout_prob
							lowercase__					      =		classifier_dropout_prob
							lowercase__					      =		initializer_range
							lowercase__					      =		drop_path_rate
							lowercase__					      =		layer_norm_eps
							lowercase__					      =		decoder_hidden_size
							lowercase__					      =		kwargs.get("""reshape_last_stage"""				, _UpperCAmelCase		)
							lowercase__					      =		semantic_loss_ignore_index






class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			version.parse('''1.11'''							)

					@property
					def   lowerCamelCase__					(self   :						Optional[int]		)						->       Mapping[str, Mapping[int, str]]:




							"""simple docstring"""


							return OrderedDict(
							    [
							        ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
							    ]		)

					@property
					def   lowerCamelCase__					(self   :						Optional[int]		)						->       float:




							"""simple docstring"""


							return 1E-4


					@property
					def   lowerCamelCase__					(self   :						Optional[Any]		)						->       int:




							"""simple docstring"""


							return 12

