






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
  import PIL


SCREAMING_SNAKE_CASE 							=						logging.get_logger(__name__)
class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			int =					["pixel_values"]


 def __init__(	self							,  _A = True							,  _A = None							,  _A = PIL.Image.BICUBIC							,  _A = True							,  _A = None							,  _A = 1 / 255							,  _A = True							,  _A = True							,  _A = None							,  _A = None							,  **_A							,  ) ->		None:

     """simple docstring"""



     super().__init__(**_A)
     _UpperCAmelCase				:      Any			  =				size if size is not None else {'''height''': 256, '''width''': 256}
     _UpperCAmelCase				:      str			  =				get_size_dict(_A)
     _UpperCAmelCase				:      str			  =				crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
     _UpperCAmelCase				:      int			  =				get_size_dict(_A							,  param_name='''crop_size''')

     _UpperCAmelCase				:      Union[str, Any]			  =				do_resize
     _UpperCAmelCase				:      Optional[Any]			  =				size
     _UpperCAmelCase				:      str			  =				resample
     _UpperCAmelCase				:      Optional[int]			  =				do_center_crop
     _UpperCAmelCase				:      Any			  =				crop_size
     _UpperCAmelCase				:      Optional[Any]			  =				do_rescale
     _UpperCAmelCase				:      int			  =				rescale_factor
     _UpperCAmelCase				:      Optional[int]			  =				do_normalize
     _UpperCAmelCase				:      Any			  =				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     _UpperCAmelCase				:      Dict			  =				image_std if image_std is not None else IMAGENET_STANDARD_STD


 def  snake_case__				(	self							,  _A							,  _A							,  _A = PIL.Image.BICUBIC							,  _A = None							,  **_A							,  ) ->		np.ndarray:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				get_size_dict(_A)
     if "height" not in size or "width" not in size:
         raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''')
     return resize(
         _A							,  size=(size['''height'''], size['''width'''])							,  resample=_A							,  data_format=_A							,  **_A)


 def  snake_case__				(	self							,  _A							,  _A							,  _A = None							,  **_A							,  ) ->		np.ndarray:

     """simple docstring"""



     _UpperCAmelCase				:      str			  =				get_size_dict(_A)
     if "height" not in size or "width" not in size:
         raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''')
     return center_crop(_A							,  size=(size['''height'''], size['''width'''])							,  data_format=_A							,  **_A)


 def  snake_case__				(	self							,  _A							,  _A							,  _A = None							,  **_A							,  ) ->		List[Any]:

     """simple docstring"""



     return rescale(_A							,  scale=_A							,  data_format=_A							,  **_A)


 def  snake_case__				(	self							,  _A							,  _A							,  _A							,  _A = None							,  **_A							,  ) ->		np.ndarray:

     """simple docstring"""



     return normalize(_A							,  mean=_A							,  std=_A							,  data_format=_A							,  **_A)


 def  snake_case__				(	self							,  _A							,  _A = None							,  _A = None							,  _A=None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = None							,  _A = ChannelDimension.FIRST							,  **_A							,  ) ->		PIL.Image.Image:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				do_resize if do_resize is not None else self.do_resize
     _UpperCAmelCase				:      Dict			  =				resample if resample is not None else self.resample
     _UpperCAmelCase				:      Optional[int]			  =				do_center_crop if do_center_crop is not None else self.do_center_crop
     _UpperCAmelCase				:      Dict			  =				do_rescale if do_rescale is not None else self.do_rescale
     _UpperCAmelCase				:      Optional[Any]			  =				rescale_factor if rescale_factor is not None else self.rescale_factor
     _UpperCAmelCase				:      List[Any]			  =				do_normalize if do_normalize is not None else self.do_normalize
     _UpperCAmelCase				:      Union[str, Any]			  =				image_mean if image_mean is not None else self.image_mean
     _UpperCAmelCase				:      Optional[Any]			  =				image_std if image_std is not None else self.image_std

     _UpperCAmelCase				:      Optional[Any]			  =				size if size is not None else self.size
     _UpperCAmelCase				:      Tuple			  =				get_size_dict(_A)
     _UpperCAmelCase				:      Optional[int]			  =				crop_size if crop_size is not None else self.crop_size
     _UpperCAmelCase				:      Union[str, Any]			  =				get_size_dict(_A							,  param_name='''crop_size''')

     _UpperCAmelCase				:      Optional[Any]			  =				make_list_of_images(_A)

     if not valid_images(_A):
         raise ValueError(
             '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
             '''torch.Tensor, tf.Tensor or jax.ndarray.''')

     if do_resize and size is None or resample is None:
         raise ValueError('''Size and resample must be specified if do_resize is True.''')

     if do_center_crop and crop_size is None:
         raise ValueError('''Crop size must be specified if do_center_crop is True.''')

     if do_rescale and rescale_factor is None:
         raise ValueError('''Rescale factor must be specified if do_rescale is True.''')

     if do_normalize and (image_mean is None or image_std is None):
         raise ValueError('''Image mean and std must be specified if do_normalize is True.''')

     # All transformations expect numpy arrays.
     _UpperCAmelCase				:      Optional[Any]			  =				[to_numpy_array(_A) for image in images]

     if do_resize:
         _UpperCAmelCase				:      Any			  =				[self.resize(image=_A							,  size=_A							,  resample=_A) for image in images]

     if do_center_crop:
         _UpperCAmelCase				:      List[Any]			  =				[self.center_crop(image=_A							,  size=_A) for image in images]

     if do_rescale:
         _UpperCAmelCase				:      Optional[int]			  =				[self.rescale(image=_A							,  scale=_A) for image in images]

     if do_normalize:
         _UpperCAmelCase				:      Optional[int]			  =				[self.normalize(image=_A							,  mean=_A							,  std=_A) for image in images]

     _UpperCAmelCase				:      Any			  =				[to_channel_dimension_format(_A							,  _A) for image in images]

     _UpperCAmelCase				:      Any			  =				{'''pixel_values''': images}
     return BatchFeature(data=_A							,  tensor_type=_A)












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)})




