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


__a         =   logging.get_logger(__name__)

__a         =   {
    'tanreinama/GPTSAN-2.8B-spout_is_uniform': (
        'https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json'
    ),
}
class 					lowercase__(							UpperCAmelCase				):



	"""simple docstring"""




	a     :Union[str, Any]       	=      'gptsan-japanese'
	a     :Dict       	=      [
	    'past_key_values',
	]
	a     :List[Any]       	=      {
	    'hidden_size': 'd_model',
	    'num_attention_heads': 'num_heads',
	    'num_hidden_layers': 'num_layers',
	}
	def __init__(			self    :     Any			,				SCREAMING_SNAKE_CASE_    :     Tuple=3_6_0_0_0			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]=1_2_8_0			,				SCREAMING_SNAKE_CASE_    :     Dict=1_0_2_4			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]=8_1_9_2			,				SCREAMING_SNAKE_CASE_    :     str=4_0_9_6			,				SCREAMING_SNAKE_CASE_    :     Optional[int]=1_2_8			,				SCREAMING_SNAKE_CASE_    :     Any=1_0			,				SCREAMING_SNAKE_CASE_    :     Dict=0			,				SCREAMING_SNAKE_CASE_    :     str=1_6			,				SCREAMING_SNAKE_CASE_    :     int=1_6			,				SCREAMING_SNAKE_CASE_    :     Optional[int]=1_2_8			,				SCREAMING_SNAKE_CASE_    :     Tuple=0.0			,				SCREAMING_SNAKE_CASE_    :     Optional[int]=1e-5			,				SCREAMING_SNAKE_CASE_    :     int=False			,				SCREAMING_SNAKE_CASE_    :     List[Any]=0.0			,				SCREAMING_SNAKE_CASE_    :     Optional[Any]="float32"			,				SCREAMING_SNAKE_CASE_    :     Any=False			,				SCREAMING_SNAKE_CASE_    :     Dict=False			,				SCREAMING_SNAKE_CASE_    :     List[str]=False			,				SCREAMING_SNAKE_CASE_    :     Any=0.0_02			,				SCREAMING_SNAKE_CASE_    :     int=False			,				SCREAMING_SNAKE_CASE_    :     Optional[Any]=True			,				SCREAMING_SNAKE_CASE_    :     List[Any]=3_5_9_9_8			,				SCREAMING_SNAKE_CASE_    :     str=3_5_9_9_5			,				SCREAMING_SNAKE_CASE_    :     Any=3_5_9_9_9			,				**SCREAMING_SNAKE_CASE_    :     Tuple			,				)			->	int:
					lowercase_	    =   vocab_size
					lowercase_	    =   max_position_embeddings
					lowercase_	    =   d_model
					lowercase_	    =   d_ff
					lowercase_	    =   d_ext
					lowercase_	    =   d_spout
					lowercase_	    =   num_switch_layers
					lowercase_	    =   num_ext_layers
					lowercase_	    =   num_switch_layers + num_ext_layers
					lowercase_	    =   num_heads
					lowercase_	    =   num_experts
					lowercase_	    =   expert_capacity
					lowercase_	    =   dropout_rate
					lowercase_	    =   layer_norm_epsilon
					lowercase_	    =   router_bias
					lowercase_	    =   router_jitter_noise
					lowercase_	    =   router_dtype
					lowercase_	    =   router_ignore_padding_tokens
					lowercase_	    =   output_hidden_states
					lowercase_	    =   output_attentions
					lowercase_	    =   initializer_factor
					lowercase_	    =   output_router_logits
					lowercase_	    =   use_cache

					super().__init__(
					    separator_token_id=SCREAMING_SNAKE_CASE_			,				pad_token_id=SCREAMING_SNAKE_CASE_			,				eos_token_id=SCREAMING_SNAKE_CASE_			,				**SCREAMING_SNAKE_CASE_			,				)






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

lowerCamelCase__     :		Optional[Any]        = logging.get_logger(__name__)



@add_end_docstrings(UpperCAmelCase_				)
class    _snake_case (						UpperCAmelCase_				):


 def __init__(       self       ,	**SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   super().__init__(**SCREAMING_SNAKE_CASE_)

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

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


 def __call__(       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




   if "text_queries" in kwargs:
     lowercase__	: Any     		=   kwargs.pop("""text_queries""")

   if isinstance(SCREAMING_SNAKE_CASE_       ,	(str, Image.Image)):
     lowercase__	: Optional[Any]     		=   {"""image""": image, """candidate_labels""": candidate_labels}
   else:
     lowercase__	: int     		=   image
   lowercase__	: List[str]     		=   super().__call__(SCREAMING_SNAKE_CASE_       ,	**SCREAMING_SNAKE_CASE_)
   return results


 def   lowercase__  (       self       ,	**SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: Tuple     		=   {}
   if "threshold" in kwargs:
     lowercase__	: List[Any]     		=   kwargs["""threshold"""]
   if "top_k" in kwargs:
     lowercase__	: int     		=   kwargs["""top_k"""]
   return {}, {}, postprocess_params


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: str     		=   load_image(inputs["""image"""])
   lowercase__	: Any     		=   inputs["""candidate_labels"""]
   if isinstance(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):
     lowercase__	: List[str]     		=   candidate_labels.split(""",""")

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


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: str     		=   model_inputs.pop("""target_size""")
   lowercase__	: Optional[int]     		=   model_inputs.pop("""candidate_label""")
   lowercase__	: Dict     		=   model_inputs.pop("""is_last""")

   lowercase__	: Union[str, Any]     		=   self.model(**SCREAMING_SNAKE_CASE_)

   lowercase__	: Union[str, Any]     		=   {"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs}
   return model_outputs


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=0.1       ,	SCREAMING_SNAKE_CASE_=None):


   '''simple docstring'''




   lowercase__	: Union[str, Any]     		=   []
   for model_output in model_outputs:
     lowercase__	: Optional[int]     		=   model_output["""candidate_label"""]
     lowercase__	: Tuple     		=   BaseModelOutput(SCREAMING_SNAKE_CASE_)
     lowercase__	: List[str]     		=   self.image_processor.post_process_object_detection(
         outputs=SCREAMING_SNAKE_CASE_       ,	threshold=SCREAMING_SNAKE_CASE_       ,	target_sizes=model_output["""target_size"""])[0]

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

       lowercase__	: Tuple     		=   {"""score""": score, """label""": label, """box""": box}
       results.append(SCREAMING_SNAKE_CASE_)

   lowercase__	: int     		=   sorted(SCREAMING_SNAKE_CASE_       ,	key=lambda SCREAMING_SNAKE_CASE_: x["score"]       ,	reverse=SCREAMING_SNAKE_CASE_)
   if top_k:
     lowercase__	: Any     		=   results[:top_k]

   return results



 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   if self.framework != "pt":
     raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch.""")
   lowercase__		,     lowercase__		,     lowercase__		,     lowercase__	: List[Any]     		=   box.int().tolist()
   lowercase__	: Optional[int]     		=   {
       """xmin""": xmin,
       """ymin""": ymin,
       """xmax""": xmax,
       """ymax""": ymax,
   }
   return bbox






