
"""simple docstring"""





import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
				import tensorflow as tf

				from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

if is_torch_available():
				from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

_a								=						logging.get_logger(__name__)






class        _UpperCAmelCase(       enum.Enum      ):
		lowercase__         = 0
		lowercase__         = 1






@add_end_docstrings(lowerCamelCase      )
class        _UpperCAmelCase(       lowerCamelCase      ):
		lowercase__         = 'generated'



		def __init__(   self							,						*__a							,						**__a)			->			List[Any]:






							'''simple docstring'''
							super().__init__(*__a							,						**__a)

							self.check_model_type(
							    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
							    if self.framework == '''tf'''
							    else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING)



		def 		UpperCAmelCase				(   self							,						__a=None							,						__a=None							,						__a=None							,						__a=None							,						__a=None							,						__a=None							,						**__a							,						)			->			Tuple:






							'''simple docstring'''
							_UpperCamelCase									=    {}
							if truncation is not None:
												_UpperCamelCase									=    truncation

							_UpperCamelCase									=    generate_kwargs

							_UpperCamelCase									=    {}
							if return_tensors is not None and return_type is None:
												_UpperCamelCase									=    ReturnType.TENSORS if return_tensors else ReturnType.TEXT
							if return_type is not None:
												_UpperCamelCase									=    return_type

							if clean_up_tokenization_spaces is not None:
												_UpperCamelCase									=    clean_up_tokenization_spaces

							if stop_sequence is not None:
												_UpperCamelCase									=    self.tokenizer.encode(__a							,						add_special_tokens=__a)
												if len(__a) > 1:
																	warnings.warn(
																	    '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of'''
																	    ''' the stop sequence will be used as the stop sequence string in the interim.''')
												_UpperCamelCase									=    stop_sequence_ids[0]

							return preprocess_params, forward_params, postprocess_params



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a)			->			Any:






							'''simple docstring'''
							return True



		def 		UpperCAmelCase				(   self							,						*__a							,						__a)			->			Any:






							'''simple docstring'''
							_UpperCamelCase									=    self.model.config.prefix if self.model.config.prefix is not None else ''''''
							if isinstance(args[0]							,						__a):
												if self.tokenizer.pad_token_id is None:
																	raise ValueError('''Please make sure that the tokenizer has a pad_token_id when using a batch input''')
												_UpperCamelCase									=    ([prefix + arg for arg in args[0]],)
												_UpperCamelCase									=    True

							elif isinstance(args[0]							,						__a):
												_UpperCamelCase									=    (prefix + args[0],)
												_UpperCamelCase									=    False
							else:
												raise ValueError(
												    F''' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`''')
							_UpperCamelCase									=    self.tokenizer(*__a							,						padding=__a							,						truncation=__a							,						return_tensors=self.framework)
							# This is produced by tokenizers but is an invalid generate kwargs
							if "token_type_ids" in inputs:
												del inputs["token_type_ids"]
							return inputs



		def __call__(   self							,						*__a							,						**__a)			->			Optional[int]:






							'''simple docstring'''
							_UpperCamelCase									=    super().__call__(*__a							,						**__a)
							if (
							    isinstance(args[0]							,						__a)
							    and all(isinstance(__a							,						__a) for el in args[0])
							    and all(len(__a) == 1 for res in result)
							):
												return [res[0] for res in result]
							return result



		def 		UpperCAmelCase				(   self							,						__a							,						__a=TruncationStrategy.DO_NOT_TRUNCATE							,						**__a)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    self._parse_and_tokenize(__a							,						truncation=__a							,						**__a)
							return inputs



		def 		UpperCAmelCase				(   self							,						__a							,						**__a)			->			Optional[int]:






							'''simple docstring'''
							if self.framework == "pt":
												_UpperCamelCase					,    _UpperCamelCase									=    model_inputs['''input_ids'''].shape
							elif self.framework == "tf":
												_UpperCamelCase					,    _UpperCamelCase									=    tf.shape(model_inputs['''input_ids''']).numpy()

							_UpperCamelCase									=    generate_kwargs.get('''min_length'''							,						self.model.config.min_length)
							_UpperCamelCase									=    generate_kwargs.get('''max_length'''							,						self.model.config.max_length)
							self.check_inputs(__a							,						generate_kwargs['''min_length''']							,						generate_kwargs['''max_length'''])
							_UpperCamelCase									=    self.model.generate(**__a							,						**__a)
							_UpperCamelCase									=    output_ids.shape[0]
							if self.framework == "pt":
												_UpperCamelCase									=    output_ids.reshape(__a							,						out_b // in_b							,						*output_ids.shape[1:])
							elif self.framework == "tf":
												_UpperCamelCase									=    tf.reshape(__a							,						(in_b, out_b // in_b, *output_ids.shape[1:]))
							return {"output_ids": output_ids}




		def 		UpperCAmelCase				(   self							,						__a							,						__a=ReturnType.TEXT							,						__a=False)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    []
							for output_ids in model_outputs["output_ids"][0]:
												if return_type == ReturnType.TENSORS:
																	_UpperCamelCase									=    {F'''{self.return_name}_token_ids''': output_ids}
												elif return_type == ReturnType.TEXT:
																	_UpperCamelCase									=    {
																	    F'''{self.return_name}_text''': self.tokenizer.decode(
																	        __a							,						skip_special_tokens=__a							,						clean_up_tokenization_spaces=__a							,						)
																	}
												records.append(__a)
							return records






@add_end_docstrings(lowerCamelCase      )
class        _UpperCAmelCase(       lowerCamelCase      ):
		lowercase__         = 'summary'



		def __call__(   self							,						*__a							,						**__a)			->			Dict:






							'''simple docstring'''
							return super().__call__(*__a							,						**__a)




		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a)			->			bool:






							'''simple docstring'''
							if max_length < min_length:
												logger.warning(F'''Your min_length={min_length} must be inferior than your max_length={max_length}.''')

							if input_length < max_length:
												logger.warning(
												    F'''Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '''
												    '''a summarization task, where outputs shorter than the input are typically wanted, you might '''
												    F'''consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})''')






@add_end_docstrings(lowerCamelCase      )
class        _UpperCAmelCase(       lowerCamelCase      ):
		lowercase__         = 'translation'



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a)			->			List[str]:






							'''simple docstring'''
							if input_length > 0.9 * max_length:
												logger.warning(
												    F'''Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '''
												    '''increasing your max_length manually, e.g. translator(\'...\', max_length=400)''')
							return True



		def 		UpperCAmelCase				(   self							,						*__a							,						__a=TruncationStrategy.DO_NOT_TRUNCATE							,						__a=None							,						__a=None)			->			Dict:






							'''simple docstring'''
							if getattr(self.tokenizer							,						'''_build_translation_inputs'''							,						__a):
												return self.tokenizer._build_translation_inputs(
												    *__a							,						return_tensors=self.framework							,						truncation=__a							,						src_lang=__a							,						tgt_lang=__a)
							else:
												return super()._parse_and_tokenize(*__a							,						truncation=__a)



		def 		UpperCAmelCase				(   self							,						__a=None							,						__a=None							,						**__a)			->			Union[str, Any]:






							'''simple docstring'''
							_UpperCamelCase					,    _UpperCamelCase					,    _UpperCamelCase									=    super()._sanitize_parameters(**__a)
							if src_lang is not None:
												_UpperCamelCase									=    src_lang
							if tgt_lang is not None:
												_UpperCamelCase									=    tgt_lang
							if src_lang is None and tgt_lang is None:
												# Backward compatibility, direct arguments use is preferred.
												_UpperCamelCase									=    kwargs.get('''task'''							,						self.task)
												_UpperCamelCase									=    task.split('''_''')
												if task and len(__a) == 4:
																	# translation, XX, to YY
																	_UpperCamelCase									=    items[1]
																	_UpperCamelCase									=    items[3]
							return preprocess_params, forward_params, postprocess_params




		def __call__(   self							,						*__a							,						**__a)			->			Dict:






							'''simple docstring'''
							return super().__call__(*__a							,						**__a)








"""simple docstring"""





import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import UperNetForSemanticSegmentation
				from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor






class        _UpperCAmelCase:



		def __init__(   self							,						__a							,						__a=13							,						__a=32							,						__a=3							,						__a=4							,						__a=[10, 20, 30, 40]							,						__a=[2, 2, 3, 2]							,						__a=True							,						__a=True							,						__a=37							,						__a="gelu"							,						__a=10							,						__a=0.02							,						__a=["stage2", "stage3", "stage4"]							,						__a=3							,						__a=None							,						)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    parent
							_UpperCamelCase									=    batch_size
							_UpperCamelCase									=    image_size
							_UpperCamelCase									=    num_channels
							_UpperCamelCase									=    num_stages
							_UpperCamelCase									=    hidden_sizes
							_UpperCamelCase									=    depths
							_UpperCamelCase									=    is_training
							_UpperCamelCase									=    use_labels
							_UpperCamelCase									=    intermediate_size
							_UpperCamelCase									=    hidden_act
							_UpperCamelCase									=    type_sequence_label_size
							_UpperCamelCase									=    initializer_range
							_UpperCamelCase									=    out_features
							_UpperCamelCase									=    num_labels
							_UpperCamelCase									=    scope
							_UpperCamelCase									=    num_stages



		def 		UpperCAmelCase				(   self)			->			List[str]:






							'''simple docstring'''
							_UpperCamelCase									=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

							_UpperCamelCase									=    None
							if self.use_labels:
												_UpperCamelCase									=    ids_tensor([self.batch_size]							,						self.type_sequence_label_size)

							_UpperCamelCase									=    self.get_config()

							return config, pixel_values, labels



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							return ConvNextConfig(
							    num_channels=self.num_channels							,						num_stages=self.num_stages							,						hidden_sizes=self.hidden_sizes							,						depths=self.depths							,						is_training=self.is_training							,						intermediate_size=self.intermediate_size							,						hidden_act=self.hidden_act							,						out_features=self.out_features							,						)



		def 		UpperCAmelCase				(   self)			->			Optional[int]:






							'''simple docstring'''
							return UperNetConfig(
							    backbone_config=self.get_backbone_config()							,						hidden_size=5_12							,						pool_scales=[1, 2, 3, 6]							,						use_auxiliary_head=__a							,						auxiliary_loss_weight=0.4							,						auxiliary_in_channels=40							,						auxiliary_channels=2_56							,						auxiliary_num_convs=1							,						auxiliary_concat_input=__a							,						loss_ignore_index=2_55							,						num_labels=self.num_labels							,						)



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    UperNetForSemanticSegmentation(config=__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase									=    model(__a)
							self.parent.assertEqual(
							    result.logits.shape							,						(self.batch_size, self.num_labels, self.image_size, self.image_size))




		def 		UpperCAmelCase				(   self)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    self.prepare_config_and_inputs()
							(
							    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    
							)									=    config_and_inputs
							_UpperCamelCase									=    {'''pixel_values''': pixel_values}
							return config, inputs_dict






@require_torch
class        _UpperCAmelCase(       lowerCamelCase ,	lowerCamelCase ,	unittest.TestCase      ):
		lowercase__         = (UperNetForSemanticSegmentation,) if is_torch_available() else ()
		lowercase__         = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
		lowercase__         = False
		lowercase__         = False
		lowercase__         = False
		lowercase__         = False
		lowercase__         = False
		lowercase__         = False



		def 		UpperCAmelCase				(   self)			->			Union[str, Any]:






							'''simple docstring'''
							_UpperCamelCase									=    UperNetModelTester(self)
							_UpperCamelCase									=    ConfigTester(self							,						config_class=__a							,						has_text_modality=__a							,						hidden_size=37)



		def 		UpperCAmelCase				(   self)			->			Dict:






							'''simple docstring'''
							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							return



		def 		UpperCAmelCase				(   self)			->			str:






							'''simple docstring'''
							_UpperCamelCase					,    _UpperCamelCase									=    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												_UpperCamelCase									=    model_class(__a)
												_UpperCamelCase									=    inspect.signature(model.forward)
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												_UpperCamelCase									=    [*signature.parameters.keys()]

												_UpperCamelCase									=    ['''pixel_values''']
												self.assertListEqual(arg_names[:1]							,						__a)



		def 		UpperCAmelCase				(   self)			->			Optional[int]:






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*__a)



		@unittest.skip(reason='''UperNet does not use inputs_embeds''')
		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							pass



		@unittest.skip(reason='''UperNet does not support input and output embeddings''')
		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							pass



		@unittest.skip(reason='''UperNet does not have a base model''')
		def 		UpperCAmelCase				(   self)			->			Tuple:






							'''simple docstring'''
							pass



		@unittest.skip(reason='''UperNet does not have a base model''')
		def 		UpperCAmelCase				(   self)			->			int:






							'''simple docstring'''
							pass



		@require_torch_multi_gpu
		@unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''')
		def 		UpperCAmelCase				(   self)			->			Union[str, Any]:






							'''simple docstring'''
							pass



		@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							pass



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							def check_hidden_states_output(__a							,						__a							,						__a):
												_UpperCamelCase									=    model_class(__a)
												model.to(__a)
												model.eval()

												with torch.no_grad():
																	_UpperCamelCase									=    model(**self._prepare_for_class(__a							,						__a))

												_UpperCamelCase									=    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												_UpperCamelCase									=    self.model_tester.num_stages
												self.assertEqual(len(__a)							,						expected_num_stages + 1)

												# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
												self.assertListEqual(
												    list(hidden_states[0].shape[-2:])							,						[self.model_tester.image_size // 4, self.model_tester.image_size // 4]							,						)

							_UpperCamelCase					,    _UpperCamelCase									=    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												_UpperCamelCase									=    True
												check_hidden_states_output(__a							,						__a							,						__a)

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												_UpperCamelCase									=    True

												check_hidden_states_output(__a							,						__a							,						__a)



		def 		UpperCAmelCase				(   self)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase					,    _UpperCamelCase									=    self.model_tester.prepare_config_and_inputs_for_common()

							_UpperCamelCase									=    _config_zero_init(__a)
							_UpperCamelCase									=    _config_zero_init(configs_no_init.backbone_config)
							for model_class in self.all_model_classes:
												_UpperCamelCase									=    model_class(config=__a)
												for name, param in model.named_parameters():
																	if param.requires_grad:
																						self.assertIn(
																						    ((param.data.mean() * 1e9).round() / 1e9).item()							,						[0.0, 1.0]							,						msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''							,						)



		@unittest.skip(reason='''UperNet does not have tied weights''')
		def 		UpperCAmelCase				(   self)			->			Optional[int]:






							'''simple docstring'''
							pass




		@slow
		def 		UpperCAmelCase				(   self)			->			Optional[Any]:






							'''simple docstring'''
							for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_UpperCamelCase									=    UperNetForSemanticSegmentation.from_pretrained(__a)
												self.assertIsNotNone(__a)





def  lowerCamelCase__						(     )				->						int:


					"""simple docstring"""





					_UpperCamelCase									=    hf_hub_download(
					    repo_id='''hf-internal-testing/fixtures_ade20k''',	repo_type='''dataset''',	filename='''ADE_val_00000001.jpg'''      )
					_UpperCamelCase									=    Image.open(__snake_case      ).convert('''RGB'''      )
					return image






@require_torch
@require_vision
@slow
class        _UpperCAmelCase(       unittest.TestCase      ):



		def 		UpperCAmelCase				(   self)			->			Optional[int]:






							'''simple docstring'''
							_UpperCamelCase									=    AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny''')
							_UpperCamelCase									=    UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny''').to(__a)

							_UpperCamelCase									=    prepare_img()
							_UpperCamelCase									=    processor(images=__a							,						return_tensors='''pt''').to(__a)

							with torch.no_grad():
												_UpperCamelCase									=    model(**__a)

							_UpperCamelCase									=    torch.Size((1, model.config.num_labels, 5_12, 5_12))
							self.assertEqual(outputs.logits.shape							,						__a)

							_UpperCamelCase									=    torch.tensor(
							    [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]).to(__a)
							self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]							,						__a							,						atol=1e-4))




		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny''')
							_UpperCamelCase									=    UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny''').to(__a)

							_UpperCamelCase									=    prepare_img()
							_UpperCamelCase									=    processor(images=__a							,						return_tensors='''pt''').to(__a)

							with torch.no_grad():
												_UpperCamelCase									=    model(**__a)

							_UpperCamelCase									=    torch.Size((1, model.config.num_labels, 5_12, 5_12))
							self.assertEqual(outputs.logits.shape							,						__a)

							_UpperCamelCase									=    torch.tensor(
							    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]).to(__a)
							self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]							,						__a							,						atol=1e-4))






