





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

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


       def 			UpperCAmelCase__							(  *SCREAMING_SNAKE_CASE     :						List[str]							,						**SCREAMING_SNAKE_CASE     :						int			):







             '''simple docstring'''




             pass






       SCREAMING_SNAKE_CASE__					=   False


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


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Namespace			):







      '''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(SCREAMING_SNAKE_CASE							,						args.host							,						args.port							,						args.workers			)

class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      42







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      42
      _SCREAMING_SNAKE_CASE					=      42







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      42







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      42







class 		lowercase					(					_UpperCAmelCase					):





      @staticmethod
      def     _snake_case			(       lowercase )		->     Any:
            lowerCAmelCase  						=       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      ,						lowercase      ,						lowercase      ,						lowercase      ,						lowercase )		->     Tuple:
            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=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     _snake_case			(       self )		->     str:
            run(self._app      ,						host=self.host      ,						port=self.port      ,						workers=self.workers )





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





      def     _snake_case			(       self      ,						lowercase = Body(lowercase      ,						embed=lowercase )      ,						lowercase = Body(lowercase      ,						embed=lowercase ) )		->     Dict:
            try:
                  lowerCAmelCase  						=       self._pipeline.tokenizer.tokenize(lowercase )

                  if return_ids:
                        lowerCAmelCase  						=       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     _snake_case			(       self      ,						lowercase = Body(lowercase      ,						embed=lowercase )      ,						lowercase = Body(lowercase      ,						embed=lowercase )      ,						lowercase = Body(lowercase      ,						embed=lowercase )      ,						)		->     Any:
            try:
                  lowerCAmelCase  						=       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     _snake_case			(       self      ,						lowercase=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
                  lowerCAmelCase  						=       self._pipeline(lowercase )
                  return ServeForwardResult(output=lowercase )
            except Exception as e:
                  raise HTTPException(500      ,						{"""error""": str(lowercase )} )













"""simple docstring"""





import re
import string

import numpy as np

import datasets


SCREAMING_SNAKE_CASE__					=   "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n"

SCREAMING_SNAKE_CASE__					=   "\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results[\"exact_match\"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric(\"exact_match\")\n    >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n    >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results[\"exact_match\"], 1))\n    33.3\n\n"

SCREAMING_SNAKE_CASE__					=   "\n"

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





      def     _snake_case			(       self )		->     Optional[int]:
            return datasets.MetricInfo(
                description=_DESCRIPTION      ,						citation=_CITATION      ,						inputs_description=_KWARGS_DESCRIPTION      ,						features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""string"""      ,						id="""sequence""" ),
                        """references""": datasets.Value("""string"""      ,						id="""sequence""" ),
                    } )      ,						reference_urls=[]      ,						)





      def     _snake_case			(       self      ,						lowercase      ,						lowercase      ,						lowercase=None      ,						lowercase=False      ,						lowercase=False      ,						lowercase=False      ,						)		->     Optional[Any]:
            if regexes_to_ignore is not None:
                  for s in regexes_to_ignore:
                        lowerCAmelCase  						=       np.array([re.sub(lowercase      ,						""""""      ,						lowercase ) for x in predictions] )
                        lowerCAmelCase  						=       np.array([re.sub(lowercase      ,						""""""      ,						lowercase ) for x in references] )
            else:
                  lowerCAmelCase  						=       np.asarray(lowercase )
                  lowerCAmelCase  						=       np.asarray(lowercase )

            if ignore_case:
                  lowerCAmelCase  						=       np.char.lower(lowercase )
                  lowerCAmelCase  						=       np.char.lower(lowercase )

            if ignore_punctuation:
                  lowerCAmelCase  						=       string.punctuation.maketrans(""""""      ,						""""""      ,						string.punctuation )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )

            if ignore_numbers:
                  lowerCAmelCase  						=       string.digits.maketrans(""""""      ,						""""""      ,						string.digits )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )
                  lowerCAmelCase  						=       np.char.translate(lowercase      ,						table=lowercase )

            lowerCAmelCase  						=       predictions == references

            return {"exact_match": np.mean(lowercase ) * 100}






