


from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__snake_case   							=						logging.get_logger(__name__)






def 		_A		(		_lowercase )					-> List[int]:


     """simple docstring"""


     if isinstance(_lowercase					,  np.ndarray ):
          return list(tensor.shape )

     __UpperCamelCase =			tf.shape(_lowercase )

     if tensor.shape == tf.TensorShape(_lowercase ):
          return dynamic

     __UpperCamelCase =			tensor.shape.as_list()

     return [dynamic[i] if s is None else s for i, s in enumerate(_lowercase )]






def 		_A		(		_lowercase					,  _lowercase = None					,  _lowercase = None )					-> tf.Tensor:


     """simple docstring"""


     return tf.nn.softmax(logits=logits + 1e-9					,  axis=_lowercase					,  name=_lowercase )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase					,  _lowercase=1e-5					,  _lowercase=-1 )					-> str:


     """simple docstring"""


     if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(_lowercase					,  _lowercase ):
          raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' )

     # Get mean and variance on the axis to be normalized
     __UpperCamelCase,    __UpperCamelCase =			tf.nn.moments(_lowercase					,  axes=[axis]					,  keepdims=_lowercase )

     if axis != -1:
          # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
          # on every dimension except axis
          __UpperCamelCase =			[1] * inputs.shape.rank
          __UpperCamelCase =			shape_list(_lowercase )[axis]
          __UpperCamelCase =			tf.reshape(_lowercase					,  _lowercase )
          __UpperCamelCase =			tf.reshape(_lowercase					,  _lowercase )

     # Compute layer normalization using the batch_normalization
     # function.
     __UpperCamelCase =			tf.nn.batch_normalization(
         _lowercase					,  _lowercase					,  _lowercase					,  offset=_lowercase					,  scale=_lowercase					,  variance_epsilon=_lowercase					,  )
     return outputs






def 		_A		(		_lowercase					,  _lowercase=0					,  _lowercase=-1 )					-> Tuple:


     """simple docstring"""


     if end_dim < 0:
          end_dim += input.shape.rank
     if start_dim < 0:
          start_dim += input.shape.rank

     if start_dim == end_dim:
          return input

     __UpperCamelCase =			tf.shape(_lowercase )
     __UpperCamelCase =			tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] )
     __UpperCamelCase =			tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]					,  axis=0 )
     return tf.reshape(_lowercase					,  _lowercase )






def 		_A		(		_lowercase )					-> tf.Tensor:


     """simple docstring"""


     if not isinstance(_lowercase					,  tf.Tensor ):
          __UpperCamelCase =			tf.convert_to_tensor(_lowercase )  # Catches stray NumPy inputs
     if encoder_attention_mask.shape.rank == 3:
          __UpperCamelCase =			encoder_attention_mask[:, None, :, :]
     if encoder_attention_mask.shape.rank == 2:
          __UpperCamelCase =			encoder_attention_mask[:, None, None, :]
     # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
     # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
     # /transformer/transformer_layers.py#L270
     # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
     # encoder_extended_attention_mask.transpose(-1, -2))
     __UpperCamelCase =			(
         tf.cast(1					,  encoder_attention_mask.dtype ) - encoder_extended_attention_mask
     ) * encoder_extended_attention_mask.dtype.min

     return encoder_extended_attention_mask






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase = "input_ids" )					-> None:


     """simple docstring"""


     tf.debugging.assert_less(
         _lowercase					,  tf.cast(_lowercase					,  dtype=tensor.dtype )					,  message=(
             f'''The maximum value of {tensor_name} ({tf.math.reduce_max(_lowercase )}) must be smaller than the embedding '''
             f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.'''
         )					,  )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase )					-> Optional[int]:


     """simple docstring"""


     __UpperCamelCase =			6_45_12
     # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
     # because in that case even chunking the array would not make the saving
     # possible.
     __UpperCamelCase =			[x for x in data if len(_lowercase ) > HDF5_OBJECT_HEADER_LIMIT]

     # Expecting this to never be true.
     if bad_attributes:
          raise RuntimeError(
              'The following attributes cannot be saved to HDF5 file because '
              f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} '''
              f'''bytes: {bad_attributes}''' )

     __UpperCamelCase =			np.asarray(_lowercase )

     __UpperCamelCase =			1
     __UpperCamelCase =			np.array_split(_lowercase					,  _lowercase )

     # This will never loop forever thanks to the test above.
     while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ):
          num_chunks += 1
          __UpperCamelCase =			np.array_split(_lowercase					,  _lowercase )

     if num_chunks > 1:
          for chunk_id, chunk_data in enumerate(_lowercase ):
               __UpperCamelCase =			chunk_data
     else:
          __UpperCamelCase =			data






def 		_A		(		_lowercase					,  _lowercase )					-> Tuple:


     """simple docstring"""


     if name in group.attrs:
          __UpperCamelCase =			[n.decode('utf8' ) if hasattr(_lowercase					,  'decode' ) else n for n in group.attrs[name]]
     else:
          __UpperCamelCase =			[]
          __UpperCamelCase =			0
          while "%s%d" % (name, chunk_id) in group.attrs:
               data.extend(
                   [n.decode('utf8' ) if hasattr(_lowercase					,  'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] )
               chunk_id += 1
     return data






def 		_A		(		_lowercase )					-> Tuple:


     """simple docstring"""


     def _expand_single_ad_tensor(_lowercase ):
          if isinstance(_lowercase					,  tf.Tensor ) and t.shape.rank == 1:
               return tf.expand_dims(_lowercase					,  axis=-1 )
          return t

     return tf.nest.map_structure(_expand_single_ad_tensor					,  _lowercase )









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