






import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      TFEfficientFormerForImageClassification,
      TFEfficientFormerForImageClassificationWithTeacher,
      TFEfficientFormerModel,
  )
  from transformers.models.efficientformer.modeling_tf_efficientformer import (
      TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
  )


if is_vision_available():
  from PIL import Image

  from transformers import EfficientFormerImageProcessor
class 							A_    :






 '''simple docstring'''




 def __init__(	self							,  _A							,  _A = 13							,  _A = 64							,  _A = 2							,  _A = 3							,  _A = 3							,  _A = True							,  _A = True							,  _A = 128							,  _A=[16, 32, 64, 128]							,  _A = 7							,  _A = 4							,  _A = 37							,  _A = "gelu"							,  _A = 0.1							,  _A = 0.1							,  _A = 10							,  _A = 0.02							,  _A = 2							,  _A = 1							,  _A = 128							,  _A = [2, 2, 2, 2]							,  _A = 2							,  _A = 2							,  ) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				parent
     _UpperCAmelCase				:      Dict			  =				batch_size
     _UpperCAmelCase				:      Optional[int]			  =				image_size
     _UpperCAmelCase				:      Optional[Any]			  =				patch_size
     _UpperCAmelCase				:      List[str]			  =				num_channels
     _UpperCAmelCase				:      Tuple			  =				is_training
     _UpperCAmelCase				:      Optional[Any]			  =				use_labels
     _UpperCAmelCase				:      Optional[int]			  =				hidden_size
     _UpperCAmelCase				:      List[Any]			  =				num_hidden_layers
     _UpperCAmelCase				:      Tuple			  =				num_attention_heads
     _UpperCAmelCase				:      List[Any]			  =				intermediate_size
     _UpperCAmelCase				:      Any			  =				hidden_act
     _UpperCAmelCase				:      Dict			  =				hidden_dropout_prob
     _UpperCAmelCase				:      Optional[int]			  =				attention_probs_dropout_prob
     _UpperCAmelCase				:      List[Any]			  =				type_sequence_label_size
     _UpperCAmelCase				:      Optional[Any]			  =				initializer_range
     _UpperCAmelCase				:      Any			  =				encoder_stride
     _UpperCAmelCase				:      str			  =				num_attention_outputs
     _UpperCAmelCase				:      str			  =				embed_dim
     _UpperCAmelCase				:      Dict			  =				embed_dim + 1
     _UpperCAmelCase				:      str			  =				resolution
     _UpperCAmelCase				:      int			  =				depths
     _UpperCAmelCase				:      Optional[Any]			  =				hidden_sizes
     _UpperCAmelCase				:      str			  =				dim
     _UpperCAmelCase				:      Any			  =				mlp_expansion_ratio


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

     _UpperCAmelCase				:      Optional[int]			  =				None
     if self.use_labels:
         _UpperCAmelCase				:      Tuple			  =				ids_tensor([self.batch_size]							,  self.type_sequence_label_size)

     _UpperCAmelCase				:      Tuple			  =				self.get_config()

     return config, pixel_values, labels


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     return EfficientFormerConfig(
         image_size=self.image_size							,  patch_size=self.patch_size							,  num_channels=self.num_channels							,  hidden_size=self.hidden_size							,  num_hidden_layers=self.num_hidden_layers							,  num_attention_heads=self.num_attention_heads							,  intermediate_size=self.intermediate_size							,  hidden_act=self.hidden_act							,  hidden_dropout_prob=self.hidden_dropout_prob							,  attention_probs_dropout_prob=self.attention_probs_dropout_prob							,  is_decoder=a_							,  initializer_range=self.initializer_range							,  encoder_stride=self.encoder_stride							,  resolution=self.resolution							,  depths=self.depths							,  hidden_sizes=self.hidden_sizes							,  dim=self.dim							,  mlp_expansion_ratio=self.mlp_expansion_ratio							,  )


 def  snake_case__				(	self							,  _A							,  _A							,  _A) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				TFEfficientFormerModel(config=a_)
     _UpperCAmelCase				:      Optional[int]			  =				model(a_							,  training=a_)
     self.parent.assertEqual(result.last_hidden_state.shape							,  (self.batch_size, self.seq_length, self.hidden_size))


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

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				self.type_sequence_label_size
     _UpperCAmelCase				:      List[str]			  =				TFEfficientFormerForImageClassification(a_)
     _UpperCAmelCase				:      Union[str, Any]			  =				model(a_							,  labels=a_							,  training=a_)
     self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.type_sequence_label_size))

     # test greyscale images
     _UpperCAmelCase				:      int			  =				1
     _UpperCAmelCase				:      Union[str, Any]			  =				TFEfficientFormerForImageClassification(a_)

     _UpperCAmelCase				:      Optional[Any]			  =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
     _UpperCAmelCase				:      List[Any]			  =				model(a_							,  labels=a_)
     self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.type_sequence_label_size))


 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				self.prepare_config_and_inputs()
     _UpperCAmelCase				:      List[Any]			  =				config_and_inputs
     _UpperCAmelCase				:      Optional[int]			  =				{"pixel_values": pixel_values}
     return config, inputs_dict



@require_tf
class 							A_    (						__lowerCamelCase ,   __lowerCamelCase ,   unittest.TestCase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Any =					(
     (
         TFEfficientFormerModel,
         TFEfficientFormerForImageClassificationWithTeacher,
         TFEfficientFormerForImageClassification,
     )
     if is_tf_available()
     else ()
 )
 _SCREAMING_SNAKE_CASE							:			Tuple =					(
     {
         '''feature-extraction''': TFEfficientFormerModel,
         '''image-classification''': (
             TFEfficientFormerForImageClassification,
             TFEfficientFormerForImageClassificationWithTeacher,
         ),
     }
     if is_tf_available()
     else {}
 )

 _SCREAMING_SNAKE_CASE							:			str =					False

 _SCREAMING_SNAKE_CASE							:			Union[str, Any] =					False
 _SCREAMING_SNAKE_CASE							:			List[Any] =					False
 _SCREAMING_SNAKE_CASE							:			Union[str, Any] =					False
 _SCREAMING_SNAKE_CASE							:			Dict =					False


 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      int			  =				TFEfficientFormerModelTester(self)
     _UpperCAmelCase				:      str			  =				ConfigTester(
         self							,  config_class=a_							,  has_text_modality=a_							,  hidden_size=37)


 def  snake_case__				(	self) ->		Optional[int]:

     """simple docstring"""



     self.config_tester.run_common_tests()


 @unittest.skip(reason='''EfficientFormer does not use inputs_embeds''')
 def  snake_case__				(	self) ->		List[Any]:

     """simple docstring"""



     pass


 @unittest.skip(reason='''EfficientFormer does not support input and output embeddings''')
 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     pass


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

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         _UpperCAmelCase				:      str			  =				model_class(a_)
         _UpperCAmelCase				:      str			  =				inspect.signature(model.call)
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         _UpperCAmelCase				:      Optional[int]			  =				[*signature.parameters.keys()]

         _UpperCAmelCase				:      Optional[Any]			  =				["pixel_values"]
         self.assertListEqual(arg_names[:1]							,  a_)


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

     """simple docstring"""



     def check_hidden_states_output(_A							,  _A							,  _A):
         _UpperCAmelCase				:      int			  =				model_class(a_)

         _UpperCAmelCase				:      int			  =				model(**self._prepare_for_class(a_							,  a_)							,  training=a_)
         _UpperCAmelCase				:      Any			  =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         _UpperCAmelCase				:      List[Any]			  =				getattr(
             self.model_tester							,  '''expected_num_hidden_layers'''							,  self.model_tester.num_hidden_layers + 1)
         self.assertEqual(len(a_)							,  a_)

         if hasattr(self.model_tester							,  '''encoder_seq_length'''):
             _UpperCAmelCase				:      List[Any]			  =				self.model_tester.encoder_seq_length
             if hasattr(self.model_tester							,  '''chunk_length''') and self.model_tester.chunk_length > 1:
                 _UpperCAmelCase				:      int			  =				seq_length * self.model_tester.chunk_length
         else:
             _UpperCAmelCase				:      Union[str, Any]			  =				self.model_tester.seq_length

         self.assertListEqual(
             list(hidden_states[-1].shape[-2:])							,  [seq_length, self.model_tester.hidden_size]							,  )

         if config.is_encoder_decoder:
             _UpperCAmelCase				:      str			  =				outputs.decoder_hidden_states

             self.asseretIsInstance(a_							,  (list, tuple))
             self.assertEqual(len(a_)							,  a_)
             _UpperCAmelCase				:      Any			  =				getattr(self.model_tester							,  '''seq_length'''							,  a_)
             _UpperCAmelCase				:      Union[str, Any]			  =				getattr(self.model_tester							,  '''decoder_seq_length'''							,  a_)

             self.assertListEqual(
                 list(hidden_states[-1].shape[-2:])							,  [decoder_seq_length, self.model_tester.hidden_size]							,  )

     _UpperCAmelCase				:      Any			  =				self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         _UpperCAmelCase				:      Optional[int]			  =				True
         check_hidden_states_output(a_							,  a_							,  a_)

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         _UpperCAmelCase				:      Tuple			  =				True

         check_hidden_states_output(a_							,  a_							,  a_)


 def  snake_case__				(	self							,  _A							,  _A							,  _A=False) ->		Optional[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				super()._prepare_for_class(a_							,  a_							,  return_labels=a_)

     if return_labels:
         if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
             del inputs_dict["labels"]

     return inputs_dict


 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      int			  =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*a_)


 @unittest.skip(reason='''EfficientFormer does not implement masked image modeling yet''')
 def  snake_case__				(	self) ->		Optional[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*a_)


 def  snake_case__				(	self) ->		Optional[int]:

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*a_)


 @slow
 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _UpperCAmelCase				:      Tuple			  =				TFEfficientFormerModel.from_pretrained(a_)
         self.assertIsNotNone(a_)


 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				self.model_tester.prepare_config_and_inputs_for_common()
     _UpperCAmelCase				:      Tuple			  =				True

     _UpperCAmelCase				:      Tuple			  =				getattr(self.model_tester							,  '''seq_length'''							,  a_)
     _UpperCAmelCase				:      List[Any]			  =				getattr(self.model_tester							,  '''encoder_seq_length'''							,  a_)
     _UpperCAmelCase				:      Dict			  =				getattr(self.model_tester							,  '''key_length'''							,  a_)
     _UpperCAmelCase				:      Optional[Any]			  =				getattr(self.model_tester							,  '''chunk_length'''							,  a_)

     if chunk_length is not None and hasattr(self.model_tester							,  '''num_hashes'''):
         _UpperCAmelCase				:      Optional[int]			  =				encoder_seq_length * self.model_tester.num_hashes

     for model_class in self.all_model_classes:
         _UpperCAmelCase				:      Union[str, Any]			  =				True
         _UpperCAmelCase				:      Optional[int]			  =				False
         _UpperCAmelCase				:      Dict			  =				True
         _UpperCAmelCase				:      str			  =				model_class(a_)

         _UpperCAmelCase				:      Dict			  =				model(**self._prepare_for_class(a_							,  a_)							,  training=a_)
         _UpperCAmelCase				:      Any			  =				outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
         self.assertEqual(len(a_)							,  self.model_tester.num_attention_outputs)

         # check that output_attentions also work using config
         del inputs_dict["output_attentions"]
         _UpperCAmelCase				:      Optional[int]			  =				True
         _UpperCAmelCase				:      Any			  =				model_class(a_)
         _UpperCAmelCase				:      str			  =				model(**self._prepare_for_class(a_							,  a_)							,  training=a_)

         _UpperCAmelCase				:      List[str]			  =				outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
         self.assertEqual(len(a_)							,  self.model_tester.num_attention_outputs)

         if chunk_length is not None:
             self.assertListEqual(
                 list(attentions[0].shape[-4:])							,  [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]							,  )
         else:
             self.assertListEqual(
                 list(attentions[0].shape[-3:])							,  [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]							,  )


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

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         # Prepare our model
         _UpperCAmelCase				:      Optional[int]			  =				model_class(a_)
         # These are maximally general inputs for the model, with multiple None dimensions
         # Hopefully this will catch any conditionals that fail for flexible shapes
         _UpperCAmelCase				:      Optional[Any]			  =				{
             key: tf.keras.Input(shape=val.shape[1:]							,  dtype=val.dtype							,  name=a_)
             for key, val in model.input_signature.items()
             if key in model.dummy_inputs
         }
         _UpperCAmelCase				:      List[str]			  =				model(a_)
         self.assertTrue(outputs_dict is not None)



def      _lowerCamelCase	(						)      ->					Optional[int]:
    _UpperCAmelCase				:      Dict			  =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
    return image


@require_tf
@require_vision
class 							A_    (						unittest.TestCase			):






 '''simple docstring'''




 @cached_property
 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



     return (
         EfficientFormerImageProcessor.from_pretrained('''snap-research/efficientformer-l1-300''')
         if is_vision_available()
         else None
     )


 @slow
 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				TFEfficientFormerForImageClassification.from_pretrained('''snap-research/efficientformer-l1-300''')
     _UpperCAmelCase				:      List[str]			  =				self.default_image_processor
     _UpperCAmelCase				:      Tuple			  =				prepare_img()
     _UpperCAmelCase				:      str			  =				image_processor(images=a_							,  return_tensors='''tf''')
     # forward pass
     _UpperCAmelCase				:      Any			  =				model(**a_							,  training=a_)
     # verify the logits
     _UpperCAmelCase				:      Optional[Any]			  =				tf.TensorShape((1, 1000))
     self.assertEqual(outputs.logits.shape							,  a_)
     _UpperCAmelCase				:      Any			  =				tf.constant([-0.0555, 0.4825, -0.0852])
     self.assertTrue(np.allclose(outputs.logits[0, :3]							,  a_							,  atol=1e-4))


 @slow
 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
         '''snap-research/efficientformer-l1-300''')
     _UpperCAmelCase				:      List[str]			  =				self.default_image_processor
     _UpperCAmelCase				:      int			  =				prepare_img()
     _UpperCAmelCase				:      Optional[int]			  =				image_processor(images=a_							,  return_tensors='''tf''')
     # forward pass
     _UpperCAmelCase				:      int			  =				model(**a_							,  training=a_)
     # verify the logits
     _UpperCAmelCase				:      Dict			  =				tf.TensorShape((1, 1000))
     self.assertEqual(outputs.logits.shape							,  a_)
     _UpperCAmelCase				:      List[str]			  =				tf.constant([-0.1312, 0.4353, -1.0499])
     self.assertTrue(np.allclose(outputs.logits[0, :3]							,  a_							,  atol=1e-4))








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      _lowerCamelCase	(						*__A    :							List[Any]		,		**__A    :							Any )      ->					Any:
      pass


  SCREAMING_SNAKE_CASE 							=						False


SCREAMING_SNAKE_CASE 							=						logging.get_logger('transformers-cli/serving')

def      _lowerCamelCase	(						__A    :							Namespace )      ->					Tuple:
    _UpperCAmelCase				:      Any			  =				pipeline(
        task=args.task		,		model=args.model if args.model else None		,		config=args.config		,		tokenizer=args.tokenizer		,		device=args.device		,		)
    return ServeCommand(__A		,		args.host		,		args.port		,		args.workers )
class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			dict



class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			List[str]
 _SCREAMING_SNAKE_CASE							:			Optional[List[int]]



class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			str



class 							A_    (						__lowercase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Any



class 							A_    (						__lowercase			):






 '''simple docstring'''




 @staticmethod
 def  snake_case__				(	_A) ->		List[Any]:

     """simple docstring"""



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


 def __init__(	self							,  _A							,  _A							,  _A							,  _A) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      List[Any]			  =				pipeline

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


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

     """simple docstring"""



     run(self._app							,  host=self.host							,  port=self.port							,  workers=self.workers)


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

     """simple docstring"""



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


 def  snake_case__				(	self							,  _A = Body(_A							,  embed=_A)							,  _A = Body(_A							,  embed=_A)) ->		List[Any]:

     """simple docstring"""



     try:
         _UpperCAmelCase				:      int			  =				self._pipeline.tokenizer.tokenize(_A)

         if return_ids:
             _UpperCAmelCase				:      List[Any]			  =				self._pipeline.tokenizer.convert_tokens_to_ids(_A)
             return ServeTokenizeResult(tokens=_A							,  tokens_ids=_A)
         else:
             return ServeTokenizeResult(tokens=_A)

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


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

     """simple docstring"""



     try:
         _UpperCAmelCase				:      Optional[Any]			  =				self._pipeline.tokenizer.decode(_A							,  _A							,  _A)
         return ServeDeTokenizeResult(model=''''''							,  text=_A)
     except Exception as e:
         raise HTTPException(status_code=500							,  detail={'''model''': '''''', '''error''': str(_A)})


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

     """simple docstring"""



     if len(_A) == 0:
         return ServeForwardResult(output=[]							,  attention=[])

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




