
'''simple docstring'''
import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
		import torch_xla.core.xla_model as xm
		import torch_xla.debug.metrics as met







class   a_ (      lowerCamelCase__					):




			def __init__(       self					,   *UpperCAmelCase					,   UpperCAmelCase=None					,   UpperCAmelCase=None					,   **UpperCAmelCase	):
				super().__init__(*snake_case__					,   **snake_case__	)
				a_      				=						eval_examples
				a_      				=						post_process_function




			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase=None					,   UpperCAmelCase=None					,   UpperCAmelCase=None					,   UpperCAmelCase = "eval"	):
				a_      				=						self.eval_dataset if eval_dataset is None else eval_dataset
				a_      				=						self.get_eval_dataloader(snake_case__	)
				a_      				=						self.eval_examples if eval_examples is None else eval_examples

				# Temporarily disable metric computation, we will do it in the loop here.
				a_      				=						self.compute_metrics
				a_      				=						None
				a_      				=						self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
				a_      				=						time.time()
				try:
					a_      				=						eval_loop(
					    snake_case__					,   description="""Evaluation"""					,   prediction_loss_only=True if compute_metrics is None else None					,   ignore_keys=snake_case__					,   metric_key_prefix=snake_case__					,   )
				finally:
					a_      				=						compute_metrics
				a_      				=						self.args.eval_batch_size * self.args.world_size
				if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
					start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
				output.metrics.update(
				    speed_metrics(
				        snake_case__					,   snake_case__					,   num_samples=output.num_samples					,   num_steps=math.ceil(output.num_samples / total_batch_size	)					,   )	)
				if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
					# Only the main node write the results by default
					a_      				=						self.post_process_function(snake_case__					,   snake_case__					,   output.predictions	)
					a_      				=						self.compute_metrics(snake_case__	)

					# Prefix all keys with metric_key_prefix + '_'
					for key in list(metrics.keys()	):
						if not key.startswith(f'''{metric_key_prefix}_'''	):
							a_      				=						metrics.pop(snake_case__	)
					metrics.update(output.metrics	)
				else:
					a_      				=						output.metrics

				if self.args.should_log:
					# Only the main node log the results by default
					self.log(snake_case__	)

				if self.args.tpu_metrics_debug or self.args.debug:
					# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
					xm.master_print(met.metrics_report()	)

				a_      				=						self.callback_handler.on_evaluate(self.args					,   self.state					,   self.control					,   snake_case__	)
				return metrics






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase=None					,   UpperCAmelCase = "test"	):
				a_      				=						self.get_test_dataloader(snake_case__	)

				# Temporarily disable metric computation, we will do it in the loop here.
				a_      				=						self.compute_metrics
				a_      				=						None
				a_      				=						self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
				a_      				=						time.time()
				try:
					a_      				=						eval_loop(
					    snake_case__					,   description="""Prediction"""					,   prediction_loss_only=True if compute_metrics is None else None					,   ignore_keys=snake_case__					,   metric_key_prefix=snake_case__					,   )
				finally:
					a_      				=						compute_metrics
				a_      				=						self.args.eval_batch_size * self.args.world_size
				if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
					start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
				output.metrics.update(
				    speed_metrics(
				        snake_case__					,   snake_case__					,   num_samples=output.num_samples					,   num_steps=math.ceil(output.num_samples / total_batch_size	)					,   )	)

				if self.post_process_function is None or self.compute_metrics is None:
					return output

				a_      				=						self.post_process_function(snake_case__					,   snake_case__					,   output.predictions					,   """predict"""	)
				a_      				=						self.compute_metrics(snake_case__	)

				# Prefix all keys with metric_key_prefix + '_'
				for key in list(metrics.keys()	):
					if not key.startswith(f'''{metric_key_prefix}_'''	):
						a_      				=						metrics.pop(snake_case__	)
				metrics.update(output.metrics	)
				return PredictionOutput(predictions=predictions.predictions					,   label_ids=predictions.label_ids					,   metrics=snake_case__	)







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