


'''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

__SCREAMING_SNAKE_CASE					:				str									=		logging.get_logger(__name__)






@add_end_docstrings(lowercase						)
class 					__lowerCAmelCase   (   lowercase						):

						"""simple docstring"""






						def __init__(  self							:      List[str] ,  **lowerCAmelCase							:      Dict	):
													super().__init__(**lowerCAmelCase	)

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

													requires_backends(self ,  "vision"	)
													self.check_model_type(lowerCAmelCase	)






						def __call__(  self							:      Tuple ,  lowerCAmelCase							:      Union[str, "Image.Image", List[Dict[str, Any]]] ,  lowerCAmelCase							:      Union[str, List[str]] = None ,  **lowerCAmelCase							:      int ,  ):
													if "text_queries" in kwargs:
																				A_			    =		kwargs.pop("text_queries"	)

													if isinstance(lowerCAmelCase ,  (str, Image.Image)	):
																				A_			    =		{"image": image, "candidate_labels": candidate_labels}
													else:
																				A_			    =		image
													A_			    =		super().__call__(lowerCAmelCase ,  **lowerCAmelCase	)
													return results






						def 				_UpperCAmelCase       (  self							:      Any ,  **lowerCAmelCase							:      Optional[int]	):
													A_			    =		{}
													if "threshold" in kwargs:
																				A_			    =		kwargs["threshold"]
													if "top_k" in kwargs:
																				A_			    =		kwargs["top_k"]
													return {}, {}, postprocess_params






						def 				_UpperCAmelCase       (  self							:      int ,  lowerCAmelCase							:      Optional[Any]	):
													A_			    =		load_image(inputs["image"]	)
													A_			    =		inputs["candidate_labels"]
													if isinstance(lowerCAmelCase ,  lowerCAmelCase	):
																				A_			    =		candidate_labels.split(","	)

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






						def 				_UpperCAmelCase       (  self							:      Union[str, Any] ,  lowerCAmelCase							:      str	):
													A_			    =		model_inputs.pop("target_size"	)
													A_			    =		model_inputs.pop("candidate_label"	)
													A_			    =		model_inputs.pop("is_last"	)

													A_			    =		self.model(**lowerCAmelCase	)

													A_			    =		{"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
													return model_outputs






						def 				_UpperCAmelCase       (  self							:      Any ,  lowerCAmelCase							:      Tuple ,  lowerCAmelCase							:      Union[str, Any]=0.1 ,  lowerCAmelCase							:      Any=None	):
													A_			    =		[]
													for model_output in model_outputs:
																				A_			    =		model_output["candidate_label"]
																				A_			    =		BaseModelOutput(lowerCAmelCase	)
																				A_			    =		self.image_processor.post_process_object_detection(
																				    outputs=lowerCAmelCase ,  threshold=lowerCAmelCase ,  target_sizes=model_output["target_size"]	)[0]

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

																											A_			    =		{"score": score, "label": label, "box": box}
																											results.append(lowerCAmelCase	)

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

													return results






						def 				_UpperCAmelCase       (  self							:      int ,  lowerCAmelCase							:      "torch.Tensor"	):
													if self.framework != "pt":
																				raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch."	)
													A_    ,					A_    ,					A_    ,					A_			    =		box.int().tolist()
													A_			    =		{
													    "xmin": xmin,
													    "ymin": ymin,
													    "xmax": xmax,
													    "ymax": ymax,
													}
													return bbox









'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging


__SCREAMING_SNAKE_CASE					:				Tuple									=		logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE					:				Union[str, Any]									=		{
    '''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config.json''',
}






class 					__lowerCAmelCase   (   lowercase						):

						"""simple docstring"""






						_UpperCAmelCase		:       Optional[Any]   						="transfo-xl"
						_UpperCAmelCase		:       str   						=["mems"]
						_UpperCAmelCase		:       Optional[int]   						={
						    "n_token": "vocab_size",
						    "hidden_size": "d_model",
						    "num_attention_heads": "n_head",
						    "num_hidden_layers": "n_layer",
						}






						def __init__(  self							:      str ,  lowerCAmelCase							:      Tuple=26_77_35 ,  lowerCAmelCase							:      List[Any]=[2_00_00, 4_00_00, 20_00_00] ,  lowerCAmelCase							:      Dict=10_24 ,  lowerCAmelCase							:      List[str]=10_24 ,  lowerCAmelCase							:      int=16 ,  lowerCAmelCase							:      Optional[Any]=64 ,  lowerCAmelCase							:      str=40_96 ,  lowerCAmelCase							:      Optional[int]=4 ,  lowerCAmelCase							:      Any=False ,  lowerCAmelCase							:      List[str]=18 ,  lowerCAmelCase							:      Any=16_00 ,  lowerCAmelCase							:      List[str]=10_00 ,  lowerCAmelCase							:      int=True ,  lowerCAmelCase							:      List[str]=True ,  lowerCAmelCase							:      List[str]=0 ,  lowerCAmelCase							:      Tuple=-1 ,  lowerCAmelCase							:      Optional[int]=True ,  lowerCAmelCase							:      List[str]=0.1 ,  lowerCAmelCase							:      int=0.0 ,  lowerCAmelCase							:      Tuple=True ,  lowerCAmelCase							:      List[str]="normal" ,  lowerCAmelCase							:      Tuple=0.0_1 ,  lowerCAmelCase							:      Optional[int]=0.0_1 ,  lowerCAmelCase							:      List[Any]=0.0_2 ,  lowerCAmelCase							:      Dict=1e-5 ,  lowerCAmelCase							:      Optional[int]=0 ,  **lowerCAmelCase							:      List[str] ,  ):
													A_			    =		vocab_size
													A_			    =		[]
													self.cutoffs.extend(lowerCAmelCase	)
													if proj_share_all_but_first:
																				A_			    =		[False] + [True] * len(self.cutoffs	)
													else:
																				A_			    =		[False] + [False] * len(self.cutoffs	)
													A_			    =		d_model
													A_			    =		d_embed
													A_			    =		d_head
													A_			    =		d_inner
													A_			    =		div_val
													A_			    =		pre_lnorm
													A_			    =		n_layer
													A_			    =		n_head
													A_			    =		mem_len
													A_			    =		same_length
													A_			    =		attn_type
													A_			    =		clamp_len
													A_			    =		sample_softmax
													A_			    =		adaptive
													A_			    =		dropout
													A_			    =		dropatt
													A_			    =		untie_r
													A_			    =		init
													A_			    =		init_range
													A_			    =		proj_init_std
													A_			    =		init_std
													A_			    =		layer_norm_epsilon
													super().__init__(eos_token_id=lowerCAmelCase ,  **lowerCAmelCase	)






						@property
						def 				_UpperCAmelCase       (  self							:      str	):
													# Message copied from Transformer-XL documentation
													logger.info(F"The model {self.model_type} is one of the few models that has no sequence length limit."	)
													return -1






						@max_position_embeddings.setter
						def 				_UpperCAmelCase       (  self							:      Tuple ,  lowerCAmelCase							:      Dict	):
													# Message copied from Transformer-XL documentation
													raise NotImplementedError(
													    F"The model {self.model_type} is one of the few models that has no sequence length limit."	)





