Create handler.py
Browse files- handler.py +62 -0
handler.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
|
| 4 |
+
class EndpontHandler():
|
| 5 |
+
def __init__(self):
|
| 6 |
+
"""
|
| 7 |
+
Initialize the handler by setting up the summarization pipeline.
|
| 8 |
+
"""
|
| 9 |
+
self.summarizer = None
|
| 10 |
+
|
| 11 |
+
def load_model(self, model_dir):
|
| 12 |
+
"""
|
| 13 |
+
Load the summarization pipeline with the fine-tuned model.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
model_dir (str): The directory where the fine-tuned model is stored.
|
| 17 |
+
"""
|
| 18 |
+
print("Loading summarization pipeline...")
|
| 19 |
+
self.summarizer = pipeline("summarization", model=model_dir)
|
| 20 |
+
|
| 21 |
+
def __call__(self, inputs):
|
| 22 |
+
"""
|
| 23 |
+
Handle incoming requests by processing input text and returning the summary.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
inputs (str): JSON string with "text" key containing the input text.
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
str: JSON string containing the "summary" key with the generated summary.
|
| 30 |
+
"""
|
| 31 |
+
try:
|
| 32 |
+
# Parse input JSON
|
| 33 |
+
input_data = json.loads(inputs)
|
| 34 |
+
input_text = input_data.get("text", "")
|
| 35 |
+
|
| 36 |
+
if not input_text:
|
| 37 |
+
return json.dumps({"error": "No input text provided."})
|
| 38 |
+
|
| 39 |
+
# Prepend custom instruction to input text
|
| 40 |
+
modified_text = f"summarize in one paragraph: {input_text}"
|
| 41 |
+
|
| 42 |
+
# Generate the summary
|
| 43 |
+
summary = self.summarizer(
|
| 44 |
+
modified_text,
|
| 45 |
+
truncation=True,
|
| 46 |
+
max_length=150,
|
| 47 |
+
min_length=30
|
| 48 |
+
)[0]["summary_text"]
|
| 49 |
+
|
| 50 |
+
# Return the summary in JSON format
|
| 51 |
+
return json.dumps({"summary": summary})
|
| 52 |
+
|
| 53 |
+
except Exception as e:
|
| 54 |
+
# Handle unexpected errors
|
| 55 |
+
return json.dumps({"error": str(e)})
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Example usage:
|
| 59 |
+
# handler = CustomHandler()
|
| 60 |
+
# handler.load_model("path_to_your_model_directory")
|
| 61 |
+
# result = handler(json.dumps({"text": "Your input text here"}))
|
| 62 |
+
# print(result)
|