

'''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

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




 def       UpperCamelCase(     *UpperCAmelCase_  ,       **UpperCAmelCase_	):
  pass




 lowercase__			    =			False


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




def       UpperCamelCase(     UpperCAmelCase_	):
 UpperCAmelCase       :	List[Any]											= 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        A_ (				_UpperCAmelCase							):






     '''simple docstring'''



     UpperCAmelCase_						:	int  		=  42




class        A_ (				_UpperCAmelCase							):






     '''simple docstring'''



     UpperCAmelCase_						:	Any  		=  42
     UpperCAmelCase_						:	Union[str, Any]  		=  42




class        A_ (				_UpperCAmelCase							):






     '''simple docstring'''



     UpperCAmelCase_						:	Union[str, Any]  		=  42




class        A_ (				_UpperCAmelCase							):






     '''simple docstring'''



     UpperCAmelCase_						:	List[Any]  		=  42




class        A_ (				_UpperCAmelCase							):






     '''simple docstring'''



     @staticmethod
     def    UpperCAmelCase_       (		lowercase_ :     str       )						->	Any:
      UpperCAmelCase       :	str											= parser.add_parser(
          'serve'     ,			help='CLI tool to run inference requests through REST and GraphQL endpoints.'       )
      serve_parser.add_argument(
          '--task'     ,			type=lowercase_     ,			choices=get_supported_tasks()     ,			help='The task to run the pipeline on'     ,			)
      serve_parser.add_argument('--host'     ,			type=lowercase_     ,			default='localhost'     ,			help='Interface the server will listen on.'       )
      serve_parser.add_argument('--port'     ,			type=lowercase_     ,			default=8_888     ,			help='Port the serving will listen to.'       )
      serve_parser.add_argument('--workers'     ,			type=lowercase_     ,			default=1     ,			help='Number of http workers'       )
      serve_parser.add_argument('--model'     ,			type=lowercase_     ,			help='Model\'s name or path to stored model.'       )
      serve_parser.add_argument('--config'     ,			type=lowercase_     ,			help='Model\'s config name or path to stored model.'       )
      serve_parser.add_argument('--tokenizer'     ,			type=lowercase_     ,			help='Tokenizer name to use.'       )
      serve_parser.add_argument(
          '--device'     ,			type=lowercase_     ,			default=-1     ,			help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)'     ,			)
      serve_parser.set_defaults(func=lowercase_       )


     def __init__(		self :     List[str]     ,			lowercase_ :     Optional[Any]     ,			lowercase_ :     List[str]     ,			lowercase_ :     str     ,			lowercase_ :     Union[str, Any]       )						->	Tuple:
      UpperCAmelCase       :	List[Any]											= pipeline

      UpperCAmelCase       :	Union[str, Any]											= host
      UpperCAmelCase       :	Any											= port
      UpperCAmelCase       :	str											= 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       :	List[str]											= FastAPI(
           routes=[
               APIRoute(
                   '/'     ,			self.model_info     ,			response_model=lowercase_     ,			response_class=lowercase_     ,			methods=['GET']     ,			),
               APIRoute(
                   '/tokenize'     ,			self.tokenize     ,			response_model=lowercase_     ,			response_class=lowercase_     ,			methods=['POST']     ,			),
               APIRoute(
                   '/detokenize'     ,			self.detokenize     ,			response_model=lowercase_     ,			response_class=lowercase_     ,			methods=['POST']     ,			),
               APIRoute(
                   '/forward'     ,			self.forward     ,			response_model=lowercase_     ,			response_class=lowercase_     ,			methods=['POST']     ,			),
           ]     ,			timeout=600     ,			)


     def    UpperCAmelCase_       (		self :     Any       )						->	str:
      run(self._app     ,			host=self.host     ,			port=self.port     ,			workers=self.workers       )


     def    UpperCAmelCase_       (		self :     int       )						->	List[Any]:
      return ServeModelInfoResult(infos=vars(self._pipeline.model.config       )       )


     def    UpperCAmelCase_       (		self :     Optional[Any]     ,			lowercase_ :     Optional[int] = Body(lowercase_     ,			embed=lowercase_       )     ,			lowercase_ :     Tuple = Body(lowercase_     ,			embed=lowercase_       )       )						->	Dict:
      try:
       UpperCAmelCase       :	Tuple											= self._pipeline.tokenizer.tokenize(lowercase_       )

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

      except Exception as e:
       raise HTTPException(status_code=500     ,			detail={'model': '', 'error': str(lowercase_       )}       )


     def    UpperCAmelCase_       (		self :     int     ,			lowercase_ :     List[str] = Body(lowercase_     ,			embed=lowercase_       )     ,			lowercase_ :     Optional[int] = Body(lowercase_     ,			embed=lowercase_       )     ,			lowercase_ :     Optional[Any] = Body(lowercase_     ,			embed=lowercase_       )     ,			)						->	Any:
      try:
       UpperCAmelCase       :	Optional[Any]											= self._pipeline.tokenizer.decode(lowercase_     ,			lowercase_     ,			lowercase_       )
       return ServeDeTokenizeResult(model=''     ,			text=lowercase_       )
      except Exception as e:
       raise HTTPException(status_code=500     ,			detail={'model': '', 'error': str(lowercase_       )}       )




     async def    UpperCAmelCase_       (		self :     Any     ,			lowercase_ :     Any=Body(lowercase_     ,			embed=lowercase_       )       )						->	str:

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

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











"""simple docstring"""





from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import fa_score, matthews_corrcoef

import datasets


SCREAMING_SNAKE_CASE__					=   "\\n@inproceedings{wang2019glue,\n  title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n  author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n  note={In the Proceedings of ICLR.},\n  year={2019}\n}\n"

SCREAMING_SNAKE_CASE__					=   "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n"

SCREAMING_SNAKE_CASE__					=   "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n    predictions: list of predictions to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n    \"accuracy\": Accuracy\n    \"f1\": F1 score\n    \"pearson\": Pearson Correlation\n    \"spearmanr\": Spearman Correlation\n    \"matthews_correlation\": Matthew Correlation\nExamples:\n\n    >>> glue_metric = datasets.load_metric('glue', 'sst2')  # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'mrpc')  # 'mrpc' or 'qqp'\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0, 'f1': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'stsb')\n    >>> references = [0., 1., 2., 3., 4., 5.]\n    >>> predictions = [0., 1., 2., 3., 4., 5.]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n    {'pearson': 1.0, 'spearmanr': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'cola')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'matthews_correlation': 1.0}\n"


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Tuple							,						SCREAMING_SNAKE_CASE     :						List[Any]			):







      '''simple docstring'''




      return float((preds == labels).mean()			)


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Optional[Any]							,						SCREAMING_SNAKE_CASE     :						Any			):







      '''simple docstring'''




      lowerCAmelCase  						=       simple_accuracy(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)
      lowerCAmelCase  						=       float(fa_score(y_true=SCREAMING_SNAKE_CASE							,						y_pred=SCREAMING_SNAKE_CASE			)			)
      return {
          "accuracy": acc,
          "f1": fa,
      }


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						List[str]							,						SCREAMING_SNAKE_CASE     :						Tuple			):







      '''simple docstring'''




      lowerCAmelCase  						=       float(pearsonr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)[0]			)
      lowerCAmelCase  						=       float(spearmanr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)[0]			)
      return {
          "pearson": pearson_corr,
          "spearmanr": spearman_corr,
      }






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,  _KWARGS_DESCRIPTION					)
class 		lowercase					(					datasets.Metric					):





      def     _snake_case			(       self )		->     List[str]:
            if self.config_name not in [
                "sst2",
                "mnli",
                "mnli_mismatched",
                "mnli_matched",
                "cola",
                "stsb",
                "mrpc",
                "qqp",
                "qnli",
                "rte",
                "wnli",
                "hans",
            ]:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )
            return datasets.MetricInfo(
                description=_DESCRIPTION      ,						citation=_CITATION      ,						inputs_description=_KWARGS_DESCRIPTION      ,						features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ),
                        """references""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ),
                    } )      ,						codebase_urls=[]      ,						reference_urls=[]      ,						format="""numpy"""      ,						)





      def     _snake_case			(       self      ,						lowercase      ,						lowercase )		->     Any:
            if self.config_name == "cola":
                  return {"matthews_correlation": matthews_corrcoef(lowercase      ,						lowercase )}
            elif self.config_name == "stsb":
                  return pearson_and_spearman(lowercase      ,						lowercase )
            elif self.config_name in ["mrpc", "qqp"]:
                  return acc_and_fa(lowercase      ,						lowercase )
            elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
                  return {"accuracy": simple_accuracy(lowercase      ,						lowercase )}
            else:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )






