






"""simple docstring"""


from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


__SCREAMING_SNAKE_CASE   =   [
    'openmmlab/upernet-convnext-tiny',
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
__SCREAMING_SNAKE_CASE   =   'UperNetConfig'




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	List[Any]     , UpperCAmelCase							:	int     , UpperCAmelCase							:	int     , UpperCAmelCase							:	Union[int, Tuple[int, int]]     , UpperCAmelCase							:	Union[int, Tuple[int, int], str] = 0     , UpperCAmelCase							:	bool = False     , UpperCAmelCase							:	Union[int, Tuple[int, int]] = 1     , )	->       None:
											super().__init__()
											lowerCAmelCase   :str						=			nn.Convad(
											    in_channels=UpperCAmelCase     , out_channels=UpperCAmelCase     , kernel_size=UpperCAmelCase     , padding=UpperCAmelCase     , bias=UpperCAmelCase     , dilation=UpperCAmelCase     , )
											lowerCAmelCase   :List[Any]						=			nn.BatchNormad(UpperCAmelCase   )
											lowerCAmelCase   :int						=			nn.ReLU()
					def        UpperCAmelCase__ (							self							:	Tuple     , UpperCAmelCase							:	torch.Tensor   )	->       torch.Tensor:
											lowerCAmelCase   :List[str]						=			self.conv(UpperCAmelCase   )
											lowerCAmelCase   :List[str]						=			self.batch_norm(UpperCAmelCase   )
											lowerCAmelCase   :Union[str, Any]						=			self.activation(UpperCAmelCase   )

											return output




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	Tuple     , UpperCAmelCase							:	int     , UpperCAmelCase							:	int     , UpperCAmelCase							:	int   )	->       None:
											super().__init__()
											lowerCAmelCase   :List[Any]						=			[
											    nn.AdaptiveAvgPoolad(UpperCAmelCase   ),
											    UperNetConvModule(UpperCAmelCase     , UpperCAmelCase     , kernel_size=1   ),
											]
											for i, layer in enumerate(self.layers   ):
																	self.add_module(str(UpperCAmelCase   )     , UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	List[str]     , UpperCAmelCase							:	torch.Tensor   )	->       torch.Tensor:
											lowerCAmelCase   :Optional[int]						=			input
											for layer in self.layers:
																	lowerCAmelCase   :int						=			layer(UpperCAmelCase   )
											return hidden_state




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	Tuple     , UpperCAmelCase							:	Tuple[int, ...]     , UpperCAmelCase							:	int     , UpperCAmelCase							:	int     , UpperCAmelCase							:	bool   )	->       None:
											super().__init__()
											lowerCAmelCase   :List[str]						=			pool_scales
											lowerCAmelCase   :List[Any]						=			align_corners
											lowerCAmelCase   :List[Any]						=			in_channels
											lowerCAmelCase   :List[Any]						=			channels
											lowerCAmelCase   :Dict						=			[]
											for i, pool_scale in enumerate(UpperCAmelCase   ):
																	lowerCAmelCase   :str						=			UperNetPyramidPoolingBlock(pool_scale=UpperCAmelCase     , in_channels=UpperCAmelCase     , channels=UpperCAmelCase   )
																	self.blocks.append(UpperCAmelCase   )
																	self.add_module(str(UpperCAmelCase   )     , UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	List[Any]     , UpperCAmelCase							:	torch.Tensor   )	->       List[torch.Tensor]:
											lowerCAmelCase   :Optional[Any]						=			[]
											for ppm in self.blocks:
																	lowerCAmelCase   :int						=			ppm(UpperCAmelCase   )
																	lowerCAmelCase   :int						=			nn.functional.interpolate(
																	    UpperCAmelCase     , size=x.size()[2:]     , mode='bilinear'     , align_corners=self.align_corners   )
																	ppm_outs.append(UpperCAmelCase   )
											return ppm_outs




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	Optional[Any]     , UpperCAmelCase							:	List[str]     , UpperCAmelCase							:	List[Any]   )	->       Any:
											super().__init__()

											lowerCAmelCase   :str						=			config
											lowerCAmelCase   :List[Any]						=			config.pool_scales  # e.g. (1, 2, 3, 6)
											lowerCAmelCase   :Optional[int]						=			in_channels
											lowerCAmelCase   :Optional[Any]						=			config.hidden_size
											lowerCAmelCase   :Any						=			False
											lowerCAmelCase   :Optional[int]						=			nn.Convad(self.channels     , config.num_labels     , kernel_size=1   )

											# PSP Module
											lowerCAmelCase   :Dict						=			UperNetPyramidPoolingModule(
											    self.pool_scales     , self.in_channels[-1]     , self.channels     , align_corners=self.align_corners     , )
											lowerCAmelCase   :List[Any]						=			UperNetConvModule(
											    self.in_channels[-1] + len(self.pool_scales   ) * self.channels     , self.channels     , kernel_size=3     , padding=1     , )
											# FPN Module
											lowerCAmelCase   :Tuple						=			nn.ModuleList()
											lowerCAmelCase   :List[Any]						=			nn.ModuleList()
											for in_channels in self.in_channels[:-1]:  # skip the top layer
																	lowerCAmelCase   :Dict						=			UperNetConvModule(UpperCAmelCase     , self.channels     , kernel_size=1   )
																	lowerCAmelCase   :Optional[Any]						=			UperNetConvModule(self.channels     , self.channels     , kernel_size=3     , padding=1   )
																	self.lateral_convs.append(UpperCAmelCase   )
																	self.fpn_convs.append(UpperCAmelCase   )

											lowerCAmelCase   :List[Any]						=			UperNetConvModule(
											    len(self.in_channels   ) * self.channels     , self.channels     , kernel_size=3     , padding=1     , )
					def        UpperCAmelCase__ (							self							:	Dict   )	->       Dict:
											self.apply(self._init_weights   )
					def        UpperCAmelCase__ (							self							:	Optional[Any]     , UpperCAmelCase							:	Optional[Any]   )	->       List[str]:
											if isinstance(UpperCAmelCase     , nn.Convad   ):
																	module.weight.data.normal_(mean=0.0     , std=self.config.initializer_range   )
																	if module.bias is not None:
																							module.bias.data.zero_()
					def        UpperCAmelCase__ (							self							:	List[Any]     , UpperCAmelCase							:	str   )	->       Union[str, Any]:
											lowerCAmelCase   :int						=			inputs[-1]
											lowerCAmelCase   :Any						=			[x]
											psp_outs.extend(self.psp_modules(UpperCAmelCase   )   )
											lowerCAmelCase   :Any						=			torch.cat(UpperCAmelCase     , dim=1   )
											lowerCAmelCase   :Any						=			self.bottleneck(UpperCAmelCase   )

											return output
					def        UpperCAmelCase__ (							self							:	int     , UpperCAmelCase							:	torch.Tensor   )	->       torch.Tensor:
											# build laterals
											lowerCAmelCase   :List[str]						=			[lateral_conv(encoder_hidden_states[i]   ) for i, lateral_conv in enumerate(self.lateral_convs   )]

											laterals.append(self.psp_forward(UpperCAmelCase   )   )

											# build top-down path
											lowerCAmelCase   :Any						=			len(UpperCAmelCase   )
											for i in range(used_backbone_levels - 1     , 0     , -1   ):
																	lowerCAmelCase   :Optional[Any]						=			laterals[i - 1].shape[2:]
																	lowerCAmelCase   :Any						=			laterals[i - 1] + nn.functional.interpolate(
																	    laterals[i]     , size=UpperCAmelCase     , mode='bilinear'     , align_corners=self.align_corners   )

											# build outputs
											lowerCAmelCase   :List[Any]						=			[self.fpn_convs[i](laterals[i]   ) for i in range(used_backbone_levels - 1   )]
											# append psp feature
											fpn_outs.append(laterals[-1]   )

											for i in range(used_backbone_levels - 1     , 0     , -1   ):
																	lowerCAmelCase   :Union[str, Any]						=			nn.functional.interpolate(
																	    fpn_outs[i]     , size=fpn_outs[0].shape[2:]     , mode='bilinear'     , align_corners=self.align_corners   )
											lowerCAmelCase   :Optional[Any]						=			torch.cat(UpperCAmelCase     , dim=1   )
											lowerCAmelCase   :Union[str, Any]						=			self.fpn_bottleneck(UpperCAmelCase   )
											lowerCAmelCase   :List[str]						=			self.classifier(UpperCAmelCase   )

											return output




class 						__UpperCamelCase     (     nn.Module						):
					def __init__(							self							:	Optional[int]     , UpperCAmelCase							:	Dict     , UpperCAmelCase							:	int = 2     , UpperCAmelCase							:	int = 3     , UpperCAmelCase							:	Union[int, Tuple[int, int]] = 1   )	->       None:
											super().__init__()

											lowerCAmelCase   :List[str]						=			config
											lowerCAmelCase   :List[str]						=			config.auxiliary_in_channels
											lowerCAmelCase   :str						=			config.auxiliary_channels
											lowerCAmelCase   :int						=			config.auxiliary_num_convs
											lowerCAmelCase   :Union[str, Any]						=			config.auxiliary_concat_input
											lowerCAmelCase   :Any						=			in_index

											lowerCAmelCase   :Tuple						=			(kernel_size // 2) * dilation
											lowerCAmelCase   :Optional[Any]						=			[]
											convs.append(
											    UperNetConvModule(
											        self.in_channels     , self.channels     , kernel_size=UpperCAmelCase     , padding=UpperCAmelCase     , dilation=UpperCAmelCase   )   )
											for i in range(self.num_convs - 1   ):
																	convs.append(
																	    UperNetConvModule(
																	        self.channels     , self.channels     , kernel_size=UpperCAmelCase     , padding=UpperCAmelCase     , dilation=UpperCAmelCase   )   )
											if self.num_convs == 0:
																	lowerCAmelCase   :List[str]						=			nn.Identity()
											else:
																	lowerCAmelCase   :int						=			nn.Sequential(*UpperCAmelCase   )
											if self.concat_input:
																	lowerCAmelCase   :Any						=			UperNetConvModule(
																	    self.in_channels + self.channels     , self.channels     , kernel_size=UpperCAmelCase     , padding=kernel_size // 2   )

											lowerCAmelCase   :Any						=			nn.Convad(self.channels     , config.num_labels     , kernel_size=1   )
					def        UpperCAmelCase__ (							self							:	List[str]   )	->       int:
											self.apply(self._init_weights   )
					def        UpperCAmelCase__ (							self							:	Tuple     , UpperCAmelCase							:	Union[str, Any]   )	->       List[Any]:
											if isinstance(UpperCAmelCase     , nn.Convad   ):
																	module.weight.data.normal_(mean=0.0     , std=self.config.initializer_range   )
																	if module.bias is not None:
																							module.bias.data.zero_()
					def        UpperCAmelCase__ (							self							:	Any     , UpperCAmelCase							:	torch.Tensor   )	->       torch.Tensor:
											# just take the relevant feature maps
											lowerCAmelCase   :Any						=			encoder_hidden_states[self.in_index]
											lowerCAmelCase   :Optional[int]						=			self.convs(UpperCAmelCase   )
											if self.concat_input:
																	lowerCAmelCase   :Optional[int]						=			self.conv_cat(torch.cat([hidden_states, output]     , dim=1   )   )
											lowerCAmelCase   :Dict						=			self.classifier(UpperCAmelCase   )
											return output




class 						__UpperCamelCase     (     UpperCamelCase						):
					lowercase_    :				List[str]      =  UperNetConfig
					lowercase_    :				Optional[Any]      =  """pixel_values"""
					lowercase_    :				List[Any]      =  True
					def        UpperCAmelCase__ (							self							:	Tuple     , UpperCAmelCase							:	str   )	->       int:
											if isinstance(UpperCAmelCase     , UpperCAmelCase   ):
																	module.backbone.init_weights()
																	module.decode_head.init_weights()
																	module.auxiliary_head.init_weights()
					def        UpperCAmelCase__ (							self							:	Optional[Any]   )	->       str:
											self.backbone.init_weights()
											self.decode_head.init_weights()
											self.auxiliary_head.init_weights()
					def        UpperCAmelCase__ (							self							:	Dict     , UpperCAmelCase							:	Optional[Any]     , UpperCAmelCase							:	Dict=False   )	->       Optional[Any]:
											if isinstance(UpperCAmelCase     , UpperCAmelCase   ):
																	lowerCAmelCase   :int						=			value


__SCREAMING_SNAKE_CASE   =   R'\n    Parameters:\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

__SCREAMING_SNAKE_CASE   =   R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n            `attentions` under returned tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n            returned tensors for more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'




@add_start_docstrings(
    """UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes."""   ,     UpperCamelCase   ,     )
class 						__UpperCamelCase     (     UpperCamelCase						):
					def __init__(							self							:	Optional[Any]     , UpperCAmelCase							:	Any   )	->       str:
											super().__init__(UpperCAmelCase   )

											lowerCAmelCase   :Tuple						=			AutoBackbone.from_config(config.backbone_config   )

											# Semantic segmentation head(s)
											lowerCAmelCase   :Tuple						=			UperNetHead(UpperCAmelCase     , in_channels=self.backbone.channels   )
											lowerCAmelCase   :Any						=			UperNetFCNHead(UpperCAmelCase   ) if config.use_auxiliary_head else None

											# Initialize weights and apply final processing
											self.post_init()
					@add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('batch_size, sequence_length'   )   )
					@replace_return_docstrings(output_type=UpperCAmelCase     , config_class=_CONFIG_FOR_DOC   )
					def        UpperCAmelCase__ (							self							:	Dict     , UpperCAmelCase							:	Optional[torch.Tensor] = None     , UpperCAmelCase							:	Optional[bool] = None     , UpperCAmelCase							:	Optional[bool] = None     , UpperCAmelCase							:	Optional[torch.Tensor] = None     , UpperCAmelCase							:	Optional[bool] = None     , )	->       Union[tuple, SemanticSegmenterOutput]:
											lowerCAmelCase   :List[Any]						=			return_dict if return_dict is not None else self.config.use_return_dict
											lowerCAmelCase   :Dict						=			(
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											lowerCAmelCase   :Optional[Any]						=			output_attentions if output_attentions is not None else self.config.output_attentions

											lowerCAmelCase   :Optional[Any]						=			self.backbone.forward_with_filtered_kwargs(
											    UpperCAmelCase     , output_hidden_states=UpperCAmelCase     , output_attentions=UpperCAmelCase   )
											lowerCAmelCase   :Any						=			outputs.feature_maps

											lowerCAmelCase   :List[str]						=			self.decode_head(UpperCAmelCase   )
											lowerCAmelCase   :List[Any]						=			nn.functional.interpolate(UpperCAmelCase     , size=pixel_values.shape[2:]     , mode='bilinear'     , align_corners=UpperCAmelCase   )

											lowerCAmelCase   :List[Any]						=			None
											if self.auxiliary_head is not None:
																	lowerCAmelCase   :Any						=			self.auxiliary_head(UpperCAmelCase   )
																	lowerCAmelCase   :Optional[Any]						=			nn.functional.interpolate(
																	    UpperCAmelCase     , size=pixel_values.shape[2:]     , mode='bilinear'     , align_corners=UpperCAmelCase   )

											lowerCAmelCase   :List[Any]						=			None
											if labels is not None:
																	if self.config.num_labels == 1:
																							raise ValueError('The number of labels should be greater than one'   )
																	else:
																							# compute weighted loss
																							lowerCAmelCase   :Optional[int]						=			CrossEntropyLoss(ignore_index=self.config.loss_ignore_index   )
																							lowerCAmelCase   :Union[str, Any]						=			loss_fct(UpperCAmelCase     , UpperCAmelCase   )
																							lowerCAmelCase   :Optional[Any]						=			loss_fct(UpperCAmelCase     , UpperCAmelCase   )
																							lowerCAmelCase   :Dict						=			main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

											if not return_dict:
																	if output_hidden_states:
																							lowerCAmelCase   :int						=			(logits,) + outputs[1:]
																	else:
																							lowerCAmelCase   :List[Any]						=			(logits,) + outputs[2:]
																	return ((loss,) + output) if loss is not None else output

											return SemanticSegmenterOutput(
											    loss=UpperCAmelCase     , logits=UpperCAmelCase     , hidden_states=outputs.hidden_states     , attentions=outputs.attentions     , )







"""simple docstring"""


# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
		from PIL import Image




class 						__UpperCamelCase     (     UpperCamelCase						):
					lowercase_    :				Optional[Any]      =  """Salesforce/blip-image-captioning-base"""
					lowercase_    :				Optional[int]      =  (
					    """This is a tool that generates a description of an image. It takes an input named `image` which should be the """
					    """image to caption, and returns a text that contains the description in English."""
					)
					lowercase_    :				int      =  """image_captioner"""
					lowercase_    :				int      =  AutoModelForVisionaSeq

					lowercase_    :				List[str]      =  ["""image"""]
					lowercase_    :				int      =  ["""text"""]
					def __init__(							self							:	Any     , *UpperCAmelCase							:	str     , **UpperCAmelCase							:	List[str]   )	->       Union[str, Any]:
											requires_backends(self     , ['vision']   )
											super().__init__(*UpperCAmelCase     , **UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	int     , UpperCAmelCase							:	"Image"   )	->       Union[str, Any]:
											return self.pre_processor(images=UpperCAmelCase     , return_tensors='pt'   )
					def        UpperCAmelCase__ (							self							:	int     , UpperCAmelCase							:	Optional[int]   )	->       Optional[int]:
											return self.model.generate(**UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	Dict     , UpperCAmelCase							:	int   )	->       Dict:
											return self.pre_processor.batch_decode(UpperCAmelCase     , skip_special_tokens=UpperCAmelCase   )[0].strip()