angelLino commited on
Commit
7d6745c
·
verified ·
1 Parent(s): 544215a

Create a handler.py

Browse files

Added a handler for the endpoint.

Files changed (1) hide show
  1. handler.py +32 -0
handler.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from pipeline import PreTrainedPipeline
3
+
4
+ class PreTrainedPipelineHandler:
5
+ def __init__(self, path=""):
6
+ # Initialize the pre-trained translation pipeline
7
+ self.pipeline = PreTrainedPipeline(path=path)
8
+
9
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
10
+ """
11
+ Args:
12
+ data (Dict[str, Any]): A dictionary containing input text and language codes.
13
+ - text (str): The text to translate.
14
+ - src_lang (str): Source language code.
15
+ - tgt_lang (str): Target language code.
16
+
17
+ Returns:
18
+ List[Dict[str, Any]]: A list of dictionaries containing translated sentences.
19
+ """
20
+ text = data.get("text", "")
21
+ src_lang = data.get("src_lang", "spa_Latn")
22
+ tgt_lang = data.get("tgt_lang", "agr_Latn")
23
+
24
+ # Perform translation using the pre-trained pipeline
25
+ translation = self.pipeline({
26
+ "text": text,
27
+ "src_lang": src_lang,
28
+ "tgt_lang": tgt_lang
29
+ })
30
+
31
+ # Format the output
32
+ return [{"original": text, "translation": translation["translation"]}]