
"""simple docstring"""






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

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




					def __magic_name__	(				*_lowerCamelCase:		Union[str, Any],					**_lowerCamelCase:		List[str]			)					->						List[str]:

						'''simple docstring'''




						pass



					UpperCAmelCase        =				False


UpperCAmelCase        =				logging.get_logger("""transformers-cli/serving""")




def __magic_name__	(				_lowerCamelCase:		Namespace			)					->						Dict:

	'''simple docstring'''




	lowerCAmelCase												=  pipeline(
	    task=args.task,					model=args.model if args.model else None,					config=args.config,					tokenizer=args.tokenizer,					device=args.device,					)
	return ServeCommand(_UpperCAmelCase,					args.host,					args.port,					args.workers			)



class 			lowercase					( SCREAMING_SNAKE_CASE_		):
			lowercase        =     42





class 			lowercase					( SCREAMING_SNAKE_CASE_		):
			lowercase        =     42
			lowercase        =     42





class 			lowercase					( SCREAMING_SNAKE_CASE_		):
			lowercase        =     42





class 			lowercase					( SCREAMING_SNAKE_CASE_		):
			lowercase        =     42





class 			lowercase					( SCREAMING_SNAKE_CASE_		):






			@staticmethod
			def 					UpperCAmelCase							(SCREAMING_SNAKE_CASE_  :	ArgumentParser			)       ->	Any:





				"""simple docstring"""


				lowerCAmelCase												=  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=8_888      ,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  :	str      ,SCREAMING_SNAKE_CASE_  :	Pipeline      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	int      ,SCREAMING_SNAKE_CASE_  :	int			)       ->	int:





				"""simple docstring"""


				lowerCAmelCase												=  pipeline

				lowerCAmelCase												=  host
				lowerCAmelCase												=  port
				lowerCAmelCase												=  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}"""			)
					lowerCAmelCase												=  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 					UpperCAmelCase							(self  :	List[Any]			)       ->	Union[str, Any]:





				"""simple docstring"""


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






			def 					UpperCAmelCase							(self  :	List[Any]			)       ->	int:





				"""simple docstring"""


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






			def 					UpperCAmelCase							(self  :	List[str]      ,SCREAMING_SNAKE_CASE_  :	str = Body(__a      ,embed=__a			)      ,SCREAMING_SNAKE_CASE_  :	bool = Body(__a      ,embed=__a			)			)       ->	Optional[Any]:





				"""simple docstring"""


				try:
					lowerCAmelCase												=  self._pipeline.tokenizer.tokenize(__a			)

					if return_ids:
						lowerCAmelCase												=  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 					UpperCAmelCase							(self  :	Any      ,SCREAMING_SNAKE_CASE_  :	List[int] = Body(__a      ,embed=__a			)      ,SCREAMING_SNAKE_CASE_  :	bool = Body(__a      ,embed=__a			)      ,SCREAMING_SNAKE_CASE_  :	bool = Body(__a      ,embed=__a			)      ,)       ->	Tuple:





				"""simple docstring"""


				try:
					lowerCAmelCase												=  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 					UpperCAmelCase							(self  :	List[Any]      ,SCREAMING_SNAKE_CASE_  :	Optional[Any]=Body(__a      ,embed=__a			)			)       ->	Dict:





				"""simple docstring"""


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

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







'''simple docstring'''





import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


A__    :   Tuple           =					logging.get_logger(__name__)

A__    :   int           =					{'''vocab_file''': '''sentencepiece.bpe.model'''}

A__    :   int           =					{
    '''vocab_file''': {
        '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''',
    }
}

A__    :   List[str]           =					{
    '''camembert-base''': 5_1_2,
}

A__    :   str           =					'''▁'''



class  snake_case__						(    SCREAMING_SNAKE_CASE_				):
 A__				= VOCAB_FILES_NAMES
 A__				= PRETRAINED_VOCAB_FILES_MAP
 A__				= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 A__				= ['''input_ids''', '''attention_mask''']
 def __init__(   self						:							List[Any]      ,     __a						:							int      ,     __a						:							str="<s>"      ,     __a						:							Dict="</s>"      ,     __a						:							Union[str, Any]="</s>"      ,     __a						:							List[str]="<s>"      ,     __a						:							Optional[int]="<unk>"      ,     __a						:							Optional[Any]="<pad>"      ,     __a						:							str="<mask>"      ,     __a						:							Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"]      ,     __a						:							Optional[Dict[str, Any]] = None      ,     **__a						:							Any      ,     )      ->   None:







       '''simple docstring'''
       # Mask token behave like a normal word, i.e. include the space before it
       __snake_case :   Optional[int]													=    AddedToken(__a      ,     lstrip=__a      ,     rstrip=__a  ) if isinstance(__a      ,     __a  ) else mask_token

       __snake_case :   Optional[Any]													=    {} if sp_model_kwargs is None else sp_model_kwargs

       super().__init__(
           bos_token=__a      ,     eos_token=__a      ,     unk_token=__a      ,     sep_token=__a      ,     cls_token=__a      ,     pad_token=__a      ,     mask_token=__a      ,     additional_special_tokens=__a      ,     sp_model_kwargs=self.sp_model_kwargs      ,     **__a      ,     )
       __snake_case :   Optional[Any]													=    spm.SentencePieceProcessor(**self.sp_model_kwargs  )
       self.sp_model.Load(str(__a  )  )
       __snake_case :   str													=    vocab_file
       # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual
       # sentencepiece vocabulary (this is the case for <s> and </s>
       __snake_case :   Any													=    {'<s>NOTUSED': 0, '<pad>': 1, '</s>NOTUSED': 2, '<unk>': 3}
       __snake_case :   Optional[int]													=    len(self.fairseq_tokens_to_ids  )
       __snake_case :   str													=    len(self.sp_model  ) + len(self.fairseq_tokens_to_ids  )
       __snake_case :   Dict													=    {v: k for k, v in self.fairseq_tokens_to_ids.items()}
 def A_   (   self						:							List[str]      ,     __a						:							List[int]      ,     __a						:							Optional[List[int]] = None  )      ->   List[int]:







       '''simple docstring'''

       if token_ids_a is None:
             return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
       __snake_case :   Dict													=    [self.cls_token_id]
       __snake_case :   Optional[int]													=    [self.sep_token_id]
       return cls + token_ids_a + sep + sep + token_ids_a + sep
 def A_   (   self						:							Optional[Any]      ,     __a						:							List[int]      ,     __a						:							Optional[List[int]] = None      ,     __a						:							bool = False  )      ->   List[int]:







       '''simple docstring'''
       if already_has_special_tokens:
             return super().get_special_tokens_mask(
                 token_ids_a=__a      ,     token_ids_a=__a      ,     already_has_special_tokens=__a  )

       if token_ids_a is None:
             return [1] + ([0] * len(__a  )) + [1]
       return [1] + ([0] * len(__a  )) + [1, 1] + ([0] * len(__a  )) + [1]
 def A_   (   self						:							int      ,     __a						:							List[int]      ,     __a						:							Optional[List[int]] = None  )      ->   List[int]:







       '''simple docstring'''
       __snake_case :   Dict													=    [self.sep_token_id]
       __snake_case :   Optional[int]													=    [self.cls_token_id]

       if token_ids_a is None:
             return len(cls + token_ids_a + sep  ) * [0]
       return len(cls + token_ids_a + sep + sep + token_ids_a + sep  ) * [0]
 @property
 def A_   (   self						:							Dict  )      ->   List[str]:







       '''simple docstring'''
       return len(self.fairseq_tokens_to_ids  ) + len(self.sp_model  )
 def A_   (   self						:							List[str]  )      ->   str:







       '''simple docstring'''
       __snake_case :   Any													=    {self.convert_ids_to_tokens(__a  ): i for i in range(self.vocab_size  )}
       vocab.update(self.added_tokens_encoder  )
       return vocab
 def A_   (   self						:							Dict      ,     __a						:							str  )      ->   List[str]:







       '''simple docstring'''
       return self.sp_model.encode(__a      ,     out_type=__a  )
 def A_   (   self						:							Optional[Any]      ,     __a						:							List[str]  )      ->   List[Any]:







       '''simple docstring'''
       if token in self.fairseq_tokens_to_ids:
             return self.fairseq_tokens_to_ids[token]
       elif self.sp_model.PieceToId(__a  ) == 0:
             # Convert sentence piece unk token to fairseq unk token index
             return self.unk_token_id
       return self.fairseq_offset + self.sp_model.PieceToId(__a  )
 def A_   (   self						:							Optional[int]      ,     __a						:							List[Any]  )      ->   Optional[Any]:







       '''simple docstring'''
       if index in self.fairseq_ids_to_tokens:
             return self.fairseq_ids_to_tokens[index]
       return self.sp_model.IdToPiece(index - self.fairseq_offset  )
 def A_   (   self						:							Dict      ,     __a						:							Union[str, Any]  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Tuple													=    []
       __snake_case :   List[Any]													=    ''
       __snake_case :   Optional[int]													=    False
       for token in tokens:
             # make sure that special tokens are not decoded using sentencepiece model
             if token in self.all_special_tokens:
                   if not prev_is_special:
                         out_string += " "
                   out_string += self.sp_model.decode(__a  ) + token
                   __snake_case :   Optional[int]													=    True
                   __snake_case :   Any													=    []
             else:
                   current_sub_tokens.append(__a  )
                   __snake_case :   Dict													=    False
       out_string += self.sp_model.decode(__a  )
       return out_string.strip()
 def __getstate__(   self						:							str  )      ->   Optional[int]:







       '''simple docstring'''
       __snake_case :   Dict													=    self.__dict__.copy()
       __snake_case :   int													=    None
       return state
 def __setstate__(   self						:							List[str]      ,     __a						:							List[str]  )      ->   Dict:







       '''simple docstring'''
       __snake_case :   List[str]													=    d

       # for backward compatibility
       if not hasattr(self      ,     'sp_model_kwargs'  ):
             __snake_case :   Dict													=    {}

       __snake_case :   Optional[Any]													=    spm.SentencePieceProcessor(**self.sp_model_kwargs  )
       self.sp_model.Load(self.vocab_file  )





 def A_   (   self						:							Tuple      ,     __a						:							str      ,     __a						:							Optional[str] = None  )      ->   Tuple[str]:







       '''simple docstring'''
       if not os.path.isdir(__a  ):
             logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''  )
             return
       __snake_case :   Dict													=    os.path.join(
           __a      ,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']  )

       if os.path.abspath(self.vocab_file  ) != os.path.abspath(__a  ) and os.path.isfile(self.vocab_file  ):
             copyfile(self.vocab_file      ,     __a  )
       elif not os.path.isfile(self.vocab_file  ):
             with open(__a      ,     'wb'  ) as fi:
                   __snake_case :   Union[str, Any]													=    self.sp_model.serialized_model_proto()
                   fi.write(__a  )

       return (out_vocab_file,)



