



"""simple docstring"""


from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
					from PIL import Image

					from ..image_utils import load_image

if is_torch_available():
					import torch

					from transformers.modeling_outputs import BaseModelOutput

					from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

__A   :							Dict										=   logging.get_logger(__name__)
@add_end_docstrings(lowerCAmelCase)
class 			_a (					lowerCAmelCase):
			"""simple docstring"""



			def __init__(		self     :    Dict				,   **__UpperCamelCase     :    List[str]   )->int:
							super().__init__(**__UpperCamelCase   )

							if self.framework == "tf":
											raise ValueError(F'The {self.__class__} is only available in PyTorch.'   )

							requires_backends(self				,   '''vision'''   )
							self.check_model_type(__UpperCamelCase   )



			def __call__(		self     :    List[str]				,   __UpperCamelCase     :    Union[str, "Image.Image", List[Dict[str, Any]]]				,   __UpperCamelCase     :    Union[str, List[str]] = None				,   **__UpperCamelCase     :    List[Any]				,   )->Any:
							if "text_queries" in kwargs:
											_UpperCAmelCase					=    kwargs.pop('''text_queries'''   )

							if isinstance(__UpperCamelCase				,   (str, Image.Image)   ):
											_UpperCAmelCase					=    {'''image''': image, '''candidate_labels''': candidate_labels}
							else:
											_UpperCAmelCase					=    image
							_UpperCAmelCase					=    super().__call__(__UpperCamelCase				,   **__UpperCamelCase   )
							return results



			def  lowercase__						(		self     :    Tuple				,   **__UpperCamelCase     :    Union[str, Any]   )->Optional[Any]:
							_UpperCAmelCase					=    {}
							if "threshold" in kwargs:
											_UpperCAmelCase					=    kwargs['''threshold''']
							if "top_k" in kwargs:
											_UpperCAmelCase					=    kwargs['''top_k''']
							return {}, {}, postprocess_params



			def  lowercase__						(		self     :    List[Any]				,   __UpperCamelCase     :    str   )->int:
							_UpperCAmelCase					=    load_image(inputs['''image''']   )
							_UpperCAmelCase					=    inputs['''candidate_labels''']
							if isinstance(__UpperCamelCase				,   __UpperCamelCase   ):
											_UpperCAmelCase					=    candidate_labels.split(''','''   )

							_UpperCAmelCase					=    torch.tensor([[image.height, image.width]]				,   dtype=torch.intaa   )
							for i, candidate_label in enumerate(__UpperCamelCase   ):
											_UpperCAmelCase					=    self.tokenizer(__UpperCamelCase				,   return_tensors=self.framework   )
											_UpperCAmelCase					=    self.image_processor(__UpperCamelCase				,   return_tensors=self.framework   )
											yield {
											    "is_last": i == len(__UpperCamelCase   ) - 1,
											    "target_size": target_size,
											    "candidate_label": candidate_label,
											    **text_inputs,
											    **image_features,
											}



			def  lowercase__						(		self     :    Dict				,   __UpperCamelCase     :    str   )->Tuple:
							_UpperCAmelCase					=    model_inputs.pop('''target_size'''   )
							_UpperCAmelCase					=    model_inputs.pop('''candidate_label'''   )
							_UpperCAmelCase					=    model_inputs.pop('''is_last'''   )

							_UpperCAmelCase					=    self.model(**__UpperCamelCase   )

							_UpperCAmelCase					=    {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs}
							return model_outputs



			def  lowercase__						(		self     :    Any				,   __UpperCamelCase     :    Dict				,   __UpperCamelCase     :    Union[str, Any]=0.1				,   __UpperCamelCase     :    int=None   )->List[str]:
							_UpperCAmelCase					=    []
							for model_output in model_outputs:
											_UpperCAmelCase					=    model_output['''candidate_label''']
											_UpperCAmelCase					=    BaseModelOutput(__UpperCamelCase   )
											_UpperCAmelCase					=    self.image_processor.post_process_object_detection(
											    outputs=__UpperCamelCase				,   threshold=__UpperCamelCase				,   target_sizes=model_output['''target_size''']   )[0]

											for index in outputs["scores"].nonzero():
															_UpperCAmelCase					=    outputs['''scores'''][index].item()
															_UpperCAmelCase					=    self._get_bounding_box(outputs['''boxes'''][index][0]   )

															_UpperCAmelCase					=    {'''score''': score, '''label''': label, '''box''': box}
															results.append(__UpperCamelCase   )

							_UpperCAmelCase					=    sorted(__UpperCamelCase				,   key=lambda __UpperCamelCase   : x["score"]				,   reverse=__UpperCamelCase   )
							if top_k:
											_UpperCAmelCase					=    results[:top_k]

							return results



			def  lowercase__						(		self     :    Optional[Any]				,   __UpperCamelCase     :    "torch.Tensor"   )->Dict[str, int]:
							if self.framework != "pt":
											raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.'''   )
							_UpperCAmelCase		,						_UpperCAmelCase		,						_UpperCAmelCase		,						_UpperCAmelCase					=    box.int().tolist()
							_UpperCAmelCase					=    {
							    '''xmin''': xmin,
							    '''ymin''': ymin,
							    '''xmax''': xmax,
							    '''ymax''': ymax,
							}
							return bbox








"""simple docstring"""


from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A   :							Any										=   logging.get_logger(__name__)

__A   :							Dict										=   {
    "huggingface/informer-tourism-monthly": (
        "https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json"
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}
class 			_a (					lowerCAmelCase):
			"""simple docstring"""
			UpperCamelCase__			      =	"""informer"""
			UpperCamelCase__			      =	{
			    """hidden_size""": """d_model""",
			    """num_attention_heads""": """encoder_attention_heads""",
			    """num_hidden_layers""": """encoder_layers""",
			}



			def __init__(		self     :    List[str]				,   __UpperCamelCase     :    Optional[int] = None				,   __UpperCamelCase     :    Optional[int] = None				,   __UpperCamelCase     :    str = "student_t"				,   __UpperCamelCase     :    str = "nll"				,   __UpperCamelCase     :    int = 1				,   __UpperCamelCase     :    List[int] = None				,   __UpperCamelCase     :    Optional[Union[str, bool]] = "mean"				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    Optional[List[int]] = None				,   __UpperCamelCase     :    Optional[List[int]] = None				,   __UpperCamelCase     :    int = 6_4				,   __UpperCamelCase     :    int = 3_2				,   __UpperCamelCase     :    int = 3_2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    bool = True				,   __UpperCamelCase     :    str = "gelu"				,   __UpperCamelCase     :    float = 0.0_5				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    int = 1_0_0				,   __UpperCamelCase     :    float = 0.0_2				,   __UpperCamelCase     :    Optional[Any]=True				,   __UpperCamelCase     :    str = "prob"				,   __UpperCamelCase     :    int = 5				,   __UpperCamelCase     :    bool = True				,   **__UpperCamelCase     :    Union[str, Any]				,   )->Dict:
							# time series specific configuration
							_UpperCAmelCase					=    prediction_length
							_UpperCAmelCase					=    context_length or prediction_length
							_UpperCAmelCase					=    distribution_output
							_UpperCAmelCase					=    loss
							_UpperCAmelCase					=    input_size
							_UpperCAmelCase					=    num_time_features
							_UpperCAmelCase					=    lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
							_UpperCAmelCase					=    scaling
							_UpperCAmelCase					=    num_dynamic_real_features
							_UpperCAmelCase					=    num_static_real_features
							_UpperCAmelCase					=    num_static_categorical_features

							# set cardinality
							if cardinality and num_static_categorical_features > 0:
											if len(__UpperCamelCase   ) != num_static_categorical_features:
															raise ValueError(
															    '''The cardinality should be a list of the same length as `num_static_categorical_features`'''   )
											_UpperCAmelCase					=    cardinality
							else:
											_UpperCAmelCase					=    [0]

							# set embedding_dimension
							if embedding_dimension and num_static_categorical_features > 0:
											if len(__UpperCamelCase   ) != num_static_categorical_features:
															raise ValueError(
															    '''The embedding dimension should be a list of the same length as `num_static_categorical_features`'''   )
											_UpperCAmelCase					=    embedding_dimension
							else:
											_UpperCAmelCase					=    [min(5_0				,   (cat + 1) // 2   ) for cat in self.cardinality]

							_UpperCAmelCase					=    num_parallel_samples

							# Transformer architecture configuration
							_UpperCAmelCase					=    input_size * len(self.lags_sequence   ) + self._number_of_features
							_UpperCAmelCase					=    d_model
							_UpperCAmelCase					=    encoder_attention_heads
							_UpperCAmelCase					=    decoder_attention_heads
							_UpperCAmelCase					=    encoder_ffn_dim
							_UpperCAmelCase					=    decoder_ffn_dim
							_UpperCAmelCase					=    encoder_layers
							_UpperCAmelCase					=    decoder_layers

							_UpperCAmelCase					=    dropout
							_UpperCAmelCase					=    attention_dropout
							_UpperCAmelCase					=    activation_dropout
							_UpperCAmelCase					=    encoder_layerdrop
							_UpperCAmelCase					=    decoder_layerdrop

							_UpperCAmelCase					=    activation_function
							_UpperCAmelCase					=    init_std

							_UpperCAmelCase					=    use_cache

							# Informer
							_UpperCAmelCase					=    attention_type
							_UpperCAmelCase					=    sampling_factor
							_UpperCAmelCase					=    distil

							super().__init__(is_encoder_decoder=__UpperCamelCase				,   **__UpperCamelCase   )



			@property
			def  lowercase__						(		self     :    Optional[int]   )->int:
							return (
							    sum(self.embedding_dimension   )
							    + self.num_dynamic_real_features
							    + self.num_time_features
							    + self.num_static_real_features
							    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
							)



