






import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


SCREAMING_SNAKE_CASE 							=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE 							=						{
    'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json',
    # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}
class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Optional[int] =					"deformable_detr"
 _SCREAMING_SNAKE_CASE							:			Optional[int] =					{
     "hidden_size": "d_model",
     "num_attention_heads": "encoder_attention_heads",
 }


 def __init__(	self							,  _A=True							,  _A=None							,  _A=3							,  _A=300							,  _A=1024							,  _A=6							,  _A=1024							,  _A=8							,  _A=6							,  _A=1024							,  _A=8							,  _A=0.0							,  _A=True							,  _A="relu"							,  _A=256							,  _A=0.1							,  _A=0.0							,  _A=0.0							,  _A=0.02							,  _A=1.0							,  _A=True							,  _A=False							,  _A="sine"							,  _A="resnet50"							,  _A=True							,  _A=False							,  _A=4							,  _A=4							,  _A=4							,  _A=False							,  _A=300							,  _A=False							,  _A=1							,  _A=5							,  _A=2							,  _A=1							,  _A=1							,  _A=5							,  _A=2							,  _A=0.1							,  _A=0.25							,  _A=False							,  **_A							,  ) ->		Union[str, Any]:

     """simple docstring"""



     if backbone_config is not None and use_timm_backbone:
         raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''')

     if not use_timm_backbone:
         if backbone_config is None:
             logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''')
             _UpperCAmelCase				:      int			  =				CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''])
         elif isinstance(_A							,  _A):
             _UpperCAmelCase				:      List[str]			  =				backbone_config.get('''model_type''')
             _UpperCAmelCase				:      List[str]			  =				CONFIG_MAPPING[backbone_model_type]
             _UpperCAmelCase				:      Union[str, Any]			  =				config_class.from_dict(_A)
     _UpperCAmelCase				:      List[Any]			  =				use_timm_backbone
     _UpperCAmelCase				:      Optional[int]			  =				backbone_config
     _UpperCAmelCase				:      List[Any]			  =				num_channels
     _UpperCAmelCase				:      Any			  =				num_queries
     _UpperCAmelCase				:      int			  =				max_position_embeddings
     _UpperCAmelCase				:      int			  =				d_model
     _UpperCAmelCase				:      List[str]			  =				encoder_ffn_dim
     _UpperCAmelCase				:      List[Any]			  =				encoder_layers
     _UpperCAmelCase				:      Optional[Any]			  =				encoder_attention_heads
     _UpperCAmelCase				:      Any			  =				decoder_ffn_dim
     _UpperCAmelCase				:      int			  =				decoder_layers
     _UpperCAmelCase				:      Union[str, Any]			  =				decoder_attention_heads
     _UpperCAmelCase				:      int			  =				dropout
     _UpperCAmelCase				:      List[Any]			  =				attention_dropout
     _UpperCAmelCase				:      Tuple			  =				activation_dropout
     _UpperCAmelCase				:      List[str]			  =				activation_function
     _UpperCAmelCase				:      str			  =				init_std
     _UpperCAmelCase				:      Any			  =				init_xavier_std
     _UpperCAmelCase				:      List[Any]			  =				encoder_layerdrop
     _UpperCAmelCase				:      Dict			  =				auxiliary_loss
     _UpperCAmelCase				:      Optional[Any]			  =				position_embedding_type
     _UpperCAmelCase				:      Any			  =				backbone
     _UpperCAmelCase				:      List[str]			  =				use_pretrained_backbone
     _UpperCAmelCase				:      Any			  =				dilation
     # deformable attributes
     _UpperCAmelCase				:      int			  =				num_feature_levels
     _UpperCAmelCase				:      Dict			  =				encoder_n_points
     _UpperCAmelCase				:      Any			  =				decoder_n_points
     _UpperCAmelCase				:      List[str]			  =				two_stage
     _UpperCAmelCase				:      Optional[int]			  =				two_stage_num_proposals
     _UpperCAmelCase				:      List[str]			  =				with_box_refine
     if two_stage is True and with_box_refine is False:
         raise ValueError('''If two_stage is True, with_box_refine must be True.''')
     # Hungarian matcher
     _UpperCAmelCase				:      List[Any]			  =				class_cost
     _UpperCAmelCase				:      List[Any]			  =				bbox_cost
     _UpperCAmelCase				:      str			  =				giou_cost
     # Loss coefficients
     _UpperCAmelCase				:      Any			  =				mask_loss_coefficient
     _UpperCAmelCase				:      Dict			  =				dice_loss_coefficient
     _UpperCAmelCase				:      int			  =				bbox_loss_coefficient
     _UpperCAmelCase				:      Union[str, Any]			  =				giou_loss_coefficient
     _UpperCAmelCase				:      List[str]			  =				eos_coefficient
     _UpperCAmelCase				:      List[Any]			  =				focal_alpha
     _UpperCAmelCase				:      int			  =				disable_custom_kernels
     super().__init__(is_encoder_decoder=_A							,  **_A)


 @property
 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     return self.encoder_attention_heads


 @property
 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     return self.d_model


 def  snake_case__				(	self) ->		Any:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				copy.deepcopy(self.__dict__)
     if self.backbone_config is not None:
         _UpperCAmelCase				:      Any			  =				self.backbone_config.to_dict()
     _UpperCAmelCase				:      str			  =				self.__class__.model_type
     return output












from argparse import ArgumentParser, Namespace
from typing import Any, List, Optional

from ..pipelines import Pipeline, get_supported_tasks, pipeline
from ..utils import logging
from . import BaseTransformersCLICommand


try:
  from fastapi import Body, FastAPI, HTTPException
  from fastapi.routing import APIRoute
  from pydantic import BaseModel
  from starlette.responses import JSONResponse
  from uvicorn import run

  SCREAMING_SNAKE_CASE 							=						True
except (ImportError, AttributeError):
  SCREAMING_SNAKE_CASE 							=						object

  def      _lowerCamelCase	(						*__A    :							List[Any]		,		**__A    :							Any )      ->					Any:
      pass


  SCREAMING_SNAKE_CASE 							=						False


SCREAMING_SNAKE_CASE 							=						logging.get_logger('transformers-cli/serving')

def      _lowerCamelCase	(						__A    :							Namespace )      ->					Tuple:
    _UpperCAmelCase				:      Any			  =				pipeline(
        task=args.task		,		model=args.model if args.model else None		,		config=args.config		,		tokenizer=args.tokenizer		,		device=args.device		,		)
    return ServeCommand(__A		,		args.host		,		args.port		,		args.workers )
class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			dict



class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			List[str]
 _SCREAMING_SNAKE_CASE							:			Optional[List[int]]



class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			str



class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Any



class 							A_    (						__lowercase			):






 '''simple docstring'''




 @staticmethod
 def  snake_case__				(	_A) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				parser.add_parser(
         '''serve'''							,  help='''CLI tool to run inference requests through REST and GraphQL endpoints.''')
     serve_parser.add_argument(
         '''--task'''							,  type=_A							,  choices=get_supported_tasks()							,  help='''The task to run the pipeline on'''							,  )
     serve_parser.add_argument('''--host'''							,  type=_A							,  default='''localhost'''							,  help='''Interface the server will listen on.''')
     serve_parser.add_argument('''--port'''							,  type=_A							,  default=8888							,  help='''Port the serving will listen to.''')
     serve_parser.add_argument('''--workers'''							,  type=_A							,  default=1							,  help='''Number of http workers''')
     serve_parser.add_argument('''--model'''							,  type=_A							,  help='''Model\'s name or path to stored model.''')
     serve_parser.add_argument('''--config'''							,  type=_A							,  help='''Model\'s config name or path to stored model.''')
     serve_parser.add_argument('''--tokenizer'''							,  type=_A							,  help='''Tokenizer name to use.''')
     serve_parser.add_argument(
         '''--device'''							,  type=_A							,  default=-1							,  help='''Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)'''							,  )
     serve_parser.set_defaults(func=_A)


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

     """simple docstring"""



     _UpperCAmelCase				:      List[Any]			  =				pipeline

     _UpperCAmelCase				:      List[Any]			  =				host
     _UpperCAmelCase				:      Tuple			  =				port
     _UpperCAmelCase				:      Union[str, Any]			  =				workers

     if not _serve_dependencies_installed:
         raise RuntimeError(
             '''Using serve command requires FastAPI and uvicorn. '''
             '''Please install transformers with [serving]: pip install "transformers[serving]".'''
             '''Or install FastAPI and uvicorn separately.''')
     else:
         logger.info(f'''Serving model over {host}:{port}''')
         _UpperCAmelCase				:      str			  =				FastAPI(
             routes=[
                 APIRoute(
                     '''/'''							,  self.model_info							,  response_model=_A							,  response_class=_A							,  methods=['''GET''']							,  ),
                 APIRoute(
                     '''/tokenize'''							,  self.tokenize							,  response_model=_A							,  response_class=_A							,  methods=['''POST''']							,  ),
                 APIRoute(
                     '''/detokenize'''							,  self.detokenize							,  response_model=_A							,  response_class=_A							,  methods=['''POST''']							,  ),
                 APIRoute(
                     '''/forward'''							,  self.forward							,  response_model=_A							,  response_class=_A							,  methods=['''POST''']							,  ),
             ]							,  timeout=600							,  )


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

     """simple docstring"""



     run(self._app							,  host=self.host							,  port=self.port							,  workers=self.workers)


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

     """simple docstring"""



     return ServeModelInfoResult(infos=vars(self._pipeline.model.config))


 def  snake_case__				(	self							,  _A = Body(_A							,  embed=_A)							,  _A = Body(_A							,  embed=_A)) ->		List[Any]:

     """simple docstring"""



     try:
         _UpperCAmelCase				:      int			  =				self._pipeline.tokenizer.tokenize(_A)

         if return_ids:
             _UpperCAmelCase				:      List[Any]			  =				self._pipeline.tokenizer.convert_tokens_to_ids(_A)
             return ServeTokenizeResult(tokens=_A							,  tokens_ids=_A)
         else:
             return ServeTokenizeResult(tokens=_A)

     except Exception as e:
         raise HTTPException(status_code=500							,  detail={'''model''': '''''', '''error''': str(_A)})


 def  snake_case__				(	self							,  _A = Body(_A							,  embed=_A)							,  _A = Body(_A							,  embed=_A)							,  _A = Body(_A							,  embed=_A)							,  ) ->		str:

     """simple docstring"""



     try:
         _UpperCAmelCase				:      Optional[Any]			  =				self._pipeline.tokenizer.decode(_A							,  _A							,  _A)
         return ServeDeTokenizeResult(model=''''''							,  text=_A)
     except Exception as e:
         raise HTTPException(status_code=500							,  detail={'''model''': '''''', '''error''': str(_A)})


 async def  snake_case__				(	self							,  _A=Body(_A							,  embed=_A)) ->		str:

     """simple docstring"""



     if len(_A) == 0:
         return ServeForwardResult(output=[]							,  attention=[])

     try:
         # Forward through the model
         _UpperCAmelCase				:      Any			  =				self._pipeline(_A)
         return ServeForwardResult(output=_A)
     except Exception as e:
         raise HTTPException(500							,  {'''error''': str(_A)})




