






# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os

from accelerate.test_utils import execute_subprocess_async

def      _lowerCamelCase	(						__A    :							Optional[Any]=None )      ->					List[str]:
    if subparsers is not None:
        _UpperCAmelCase				:      str			  =				subparsers.add_parser('''test''' )
    else:
        _UpperCAmelCase				:      Optional[Any]			  =				argparse.ArgumentParser('''Accelerate test command''' )

    parser.add_argument(
        '''--config_file'''		,		default=__A		,		help=(
            '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
            '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
            '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
            '''with \'huggingface\'.'''
        )		,		)

    if subparsers is not None:
        parser.set_defaults(func=__A )
    return parser

def      _lowerCamelCase	(						__A    :							int )      ->					Union[str, Any]:
    _UpperCAmelCase				:      Union[str, Any]			  =				os.path.sep.join(__file__.split(os.path.sep )[:-2] + ['''test_utils''', '''scripts''', '''test_script.py'''] )

    if args.config_file is None:
        _UpperCAmelCase				:      List[Any]			  =				script_name
    else:
        _UpperCAmelCase				:      str			  =				f'''--config_file={args.config_file} {script_name}'''

    _UpperCAmelCase				:      Union[str, Any]			  =				['''accelerate-launch'''] + test_args.split()
    _UpperCAmelCase				:      str			  =				execute_subprocess_async(__A		,		env=os.environ.copy() )
    if result.returncode == 0:
        print('''Test is a success! You are ready for your distributed training!''' )

def      _lowerCamelCase	(						)      ->					Tuple:
    _UpperCAmelCase				:      int			  =				test_command_parser()
    _UpperCAmelCase				:      int			  =				parser.parse_args()
    test_command(__A )


if __name__ == "__main__":
  main()












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




