






import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
 import tensorflow as tf


class     _a							(	enum.Enum     ):






  """simple docstring"""





  A_						       = 0
  A_						       = 1
  A_						       = 2




@add_end_docstrings(UpperCAmelCase__     )
class     _a							(	UpperCAmelCase__     ):






  """simple docstring"""





  A_						       = """
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    """




  def __init__(  self		,		*_UpperCAmelCase		,		**_UpperCAmelCase			)      ->			List[str]:
     super().__init__(*_UpperCAmelCase		,		**_UpperCAmelCase			)
     self.check_model_type(
         TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING			)
     if "prefix" not in self._preprocess_params:
        # This is very specific. The logic is quite complex and needs to be done
        # as a "default".
        # It also defines both some preprocess_kwargs and generate_kwargs
        # which is why we cannot put them in their respective methods.
        UpperCamelCase_						=  None
        if self.model.config.prefix is not None:
           UpperCamelCase_						=  self.model.config.prefix
        if prefix is None and self.model.__class__.__name__ in [
            "XLNetLMHeadModel",
            "TransfoXLLMHeadModel",
            "TFXLNetLMHeadModel",
            "TFTransfoXLLMHeadModel",
        ]:
           # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
           UpperCamelCase_						=  self.XL_PREFIX
        if prefix is not None:
           # Recalculate some generate_kwargs linked to prefix.
           UpperCamelCase_		,   UpperCamelCase_		,   UpperCamelCase_						=  self._sanitize_parameters(prefix=_UpperCAmelCase		,		**self._forward_params			)
           UpperCamelCase_						=  {**self._preprocess_params, **preprocess_params}
           UpperCamelCase_						=  {**self._forward_params, **forward_params}




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		_UpperCAmelCase=None		,		**_UpperCAmelCase		,		)      ->			Any:
     UpperCamelCase_						=  {}
     if prefix is not None:
        UpperCamelCase_						=  prefix
     if prefix:
        UpperCamelCase_						=  self.tokenizer(
            _UpperCAmelCase		,		padding=_UpperCAmelCase		,		add_special_tokens=_UpperCAmelCase		,		return_tensors=self.framework			)
        UpperCamelCase_						=  prefix_inputs['input_ids'].shape[-1]

     if handle_long_generation is not None:
        if handle_long_generation not in {"hole"}:
           raise ValueError(
               f"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"""
               ' [None, \'hole\']'			)
        UpperCamelCase_						=  handle_long_generation

     preprocess_params.update(_UpperCAmelCase			)
     UpperCamelCase_						=  generate_kwargs

     UpperCamelCase_						=  {}
     if return_full_text is not None and return_type is None:
        if return_text is not None:
           raise ValueError('`return_text` is mutually exclusive with `return_full_text`'			)
        if return_tensors is not None:
           raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`'			)
        UpperCamelCase_						=  ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
     if return_tensors is not None and return_type is None:
        if return_text is not None:
           raise ValueError('`return_text` is mutually exclusive with `return_tensors`'			)
        UpperCamelCase_						=  ReturnType.TENSORS
     if return_type is not None:
        UpperCamelCase_						=  return_type
     if clean_up_tokenization_spaces is not None:
        UpperCamelCase_						=  clean_up_tokenization_spaces

     if stop_sequence is not None:
        UpperCamelCase_						=  self.tokenizer.encode(_UpperCAmelCase		,		add_special_tokens=_UpperCAmelCase			)
        if len(_UpperCAmelCase			) > 1:
           warnings.warn(
               'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
               ' the stop sequence will be used as the stop sequence string in the interim.'			)
        UpperCamelCase_						=  stop_sequence_ids[0]

     return preprocess_params, forward_params, postprocess_params




  def  _UpperCAmelCase  (  self		,		*_UpperCAmelCase		,		**_UpperCAmelCase			)      ->			Any:
     # Parse arguments
     if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
        kwargs.update({'add_space_before_punct_symbol': True}			)

     return super()._parse_and_tokenize(*_UpperCAmelCase		,		**_UpperCAmelCase			)




  def __call__(  self		,		_UpperCAmelCase		,		**_UpperCAmelCase			)      ->			Any:
     return super().__call__(_UpperCAmelCase		,		**_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase=""		,		_UpperCAmelCase=None		,		**_UpperCAmelCase			)      ->			Tuple:
     UpperCamelCase_						=  self.tokenizer(
         prefix + prompt_text		,		padding=_UpperCAmelCase		,		add_special_tokens=_UpperCAmelCase		,		return_tensors=self.framework			)
     UpperCamelCase_						=  prompt_text

     if handle_long_generation == "hole":
        UpperCamelCase_						=  inputs['input_ids'].shape[-1]
        if "max_new_tokens" in generate_kwargs:
           UpperCamelCase_						=  generate_kwargs['max_new_tokens']
        else:
           UpperCamelCase_						=  generate_kwargs.get('max_length'		,		self.model.config.max_length			) - cur_len
           if new_tokens < 0:
              raise ValueError('We cannot infer how many new tokens are expected'			)
        if cur_len + new_tokens > self.tokenizer.model_max_length:
           UpperCamelCase_						=  self.tokenizer.model_max_length - new_tokens
           if keep_length <= 0:
              raise ValueError(
                  'We cannot use `hole` to handle this generation the number of desired tokens exceeds the'
                  ' models max length'			)

           UpperCamelCase_						=  inputs['input_ids'][:, -keep_length:]
           if "attention_mask" in inputs:
              UpperCamelCase_						=  inputs['attention_mask'][:, -keep_length:]

     return inputs




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		**_UpperCAmelCase			)      ->			Dict:
     UpperCamelCase_						=  model_inputs['input_ids']
     UpperCamelCase_						=  model_inputs.get('attention_mask'		,		_UpperCAmelCase			)
     # Allow empty prompts
     if input_ids.shape[1] == 0:
        UpperCamelCase_						=  None
        UpperCamelCase_						=  None
        UpperCamelCase_						=  1
     else:
        UpperCamelCase_						=  input_ids.shape[0]
     UpperCamelCase_						=  model_inputs.pop('prompt_text'			)

     # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
     # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
     UpperCamelCase_						=  generate_kwargs.pop('prefix_length'		,		0			)
     if prefix_length > 0:
        UpperCamelCase_						=  'max_new_tokens' in generate_kwargs or (
            'generation_config' in generate_kwargs
            and generate_kwargs['generation_config'].max_new_tokens is not None
        )
        if not has_max_new_tokens:
           UpperCamelCase_						=  generate_kwargs.get('max_length'			) or self.model.config.max_length
           generate_kwargs["max_length"] += prefix_length
        UpperCamelCase_						=  'min_new_tokens' in generate_kwargs or (
            'generation_config' in generate_kwargs
            and generate_kwargs['generation_config'].min_new_tokens is not None
        )
        if not has_min_new_tokens and "min_length" in generate_kwargs:
           generate_kwargs["min_length"] += prefix_length

        # BS x SL
     UpperCamelCase_						=  self.model.generate(input_ids=_UpperCAmelCase		,		attention_mask=_UpperCAmelCase		,		**_UpperCAmelCase			)
     UpperCamelCase_						=  generated_sequence.shape[0]
     if self.framework == "pt":
        UpperCamelCase_						=  generated_sequence.reshape(_UpperCAmelCase		,		out_b // in_b		,		*generated_sequence.shape[1:]			)
     elif self.framework == "tf":
        UpperCamelCase_						=  tf.reshape(_UpperCAmelCase		,		(in_b, out_b // in_b, *generated_sequence.shape[1:])			)
     return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase=ReturnType.FULL_TEXT		,		_UpperCAmelCase=True			)      ->			Optional[int]:
     UpperCamelCase_						=  model_outputs['generated_sequence'][0]
     UpperCamelCase_						=  model_outputs['input_ids']
     UpperCamelCase_						=  model_outputs['prompt_text']
     UpperCamelCase_						=  generated_sequence.numpy().tolist()
     UpperCamelCase_						=  []
     for sequence in generated_sequence:
        if return_type == ReturnType.TENSORS:
           UpperCamelCase_						=  {'generated_token_ids': sequence}
        elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
           # Decode text
           UpperCamelCase_						=  self.tokenizer.decode(
               _UpperCAmelCase		,		skip_special_tokens=_UpperCAmelCase		,		clean_up_tokenization_spaces=_UpperCAmelCase		,		)

           # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
           if input_ids is None:
              UpperCamelCase_						=  0
           else:
              UpperCamelCase_						=  len(
                  self.tokenizer.decode(
                      input_ids[0]		,		skip_special_tokens=_UpperCAmelCase		,		clean_up_tokenization_spaces=_UpperCAmelCase		,		)			)

           if return_type == ReturnType.FULL_TEXT:
              UpperCamelCase_						=  prompt_text + text[prompt_length:]
           else:
              UpperCamelCase_						=  text[prompt_length:]

           UpperCamelCase_						=  {'generated_text': all_text}
        records.append(_UpperCAmelCase			)

     return records












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__  (				*lowercase				,       **lowercase				)				-> Optional[Any]:

														"""simple docstring"""



														pass




							UpperCAmelCase_							=				False


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





def  __magic_name__  (				lowercase				)				-> int:

							"""simple docstring"""



							lowercase_	:   Any  				=     pipeline(
							    task=args.task				,       model=args.model if args.model else None				,       config=args.config				,       tokenizer=args.tokenizer				,       device=args.device				,       )
							return ServeCommand(lowercase				,       args.host				,       args.port				,       args.workers				)
class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       dict




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       List[str]
		__a       :       Optional[List[int]]




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       str




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		__a       :       Any




class     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		@staticmethod
		def 						snake_case__				(							snake_case__  )       -> Optional[int]:






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






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






									"""simple docstring"""
									lowercase_	:   str  				=     pipeline

									lowercase_	:   List[str]  				=     host
									lowercase_	:   int  				=     port
									lowercase_	:   Optional[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}"""  )
																lowercase_	:   Union[str, Any]  				=     FastAPI(
																    routes=[
																        APIRoute(
																            """/""",   self.model_info,   response_model=snake_case__,   response_class=snake_case__,   methods=["""GET"""],   ),
																        APIRoute(
																            """/tokenize""",   self.tokenize,   response_model=snake_case__,   response_class=snake_case__,   methods=["""POST"""],   ),
																        APIRoute(
																            """/detokenize""",   self.detokenize,   response_model=snake_case__,   response_class=snake_case__,   methods=["""POST"""],   ),
																        APIRoute(
																            """/forward""",   self.forward,   response_model=snake_case__,   response_class=snake_case__,   methods=["""POST"""],   ),
																    ],   timeout=6_00,   )






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






									"""simple docstring"""
									run(self._app,   host=self.host,   port=self.port,   workers=self.workers  )






		def 						snake_case__				(							self  )       -> Dict:






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






		def 						snake_case__				(							self,   snake_case__ = Body(snake_case__,   embed=snake_case__  ),   snake_case__ = Body(snake_case__,   embed=snake_case__  )  )       -> Optional[int]:






									"""simple docstring"""
									try:
																lowercase_	:   Tuple  				=     self._pipeline.tokenizer.tokenize(snake_case__  )

																if return_ids:
																							lowercase_	:   Union[str, Any]  				=     self._pipeline.tokenizer.convert_tokens_to_ids(snake_case__  )
																							return ServeTokenizeResult(tokens=snake_case__,   tokens_ids=snake_case__  )
																else:
																							return ServeTokenizeResult(tokens=snake_case__  )

									except Exception as e:
																raise HTTPException(status_code=5_00,   detail={"""model""": """""", """error""": str(snake_case__  )}  )






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






									"""simple docstring"""
									try:
																lowercase_	:   List[Any]  				=     self._pipeline.tokenizer.decode(snake_case__,   snake_case__,   snake_case__  )
																return ServeDeTokenizeResult(model="""""",   text=snake_case__  )
									except Exception as e:
																raise HTTPException(status_code=5_00,   detail={"""model""": """""", """error""": str(snake_case__  )}  )






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






									"""simple docstring"""

									# Check we don't have empty string
									if len(snake_case__  ) == 0:
																return ServeForwardResult(output=[],   attention=[]  )

									try:
																# Forward through the model
																lowercase_	:   Optional[int]  				=     self._pipeline(snake_case__  )
																return ServeForwardResult(output=snake_case__  )
									except Exception as e:
																raise HTTPException(5_00,   {"""error""": str(snake_case__  )}  )