Create handler.py
Browse files- handler.py +35 -0
handler.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
import spacy
|
| 3 |
+
|
| 4 |
+
class EndpointHandler:
|
| 5 |
+
def __init__(self, path=""):
|
| 6 |
+
# This loads the model.
|
| 7 |
+
# 'path' points to the repo storage, but since we will install
|
| 8 |
+
# the model via requirements.txt, we load it by package name.
|
| 9 |
+
try:
|
| 10 |
+
self.nlp = spacy.load("en_core_web_sm")
|
| 11 |
+
except OSError:
|
| 12 |
+
# Fallback: try loading from path if you uploaded model files directly
|
| 13 |
+
self.nlp = spacy.load(path)
|
| 14 |
+
|
| 15 |
+
def __call__(self, data: Dict[str, Any]) -> List[str]:
|
| 16 |
+
"""
|
| 17 |
+
Args:
|
| 18 |
+
data (:obj:): The payload of the request.
|
| 19 |
+
Usually contains {"inputs": "Your text here"}
|
| 20 |
+
"""
|
| 21 |
+
# 1. Get the raw text from the input JSON
|
| 22 |
+
raw_text = data.pop("inputs", data)
|
| 23 |
+
|
| 24 |
+
# Handle edge case if input is sent as a list
|
| 25 |
+
if isinstance(raw_text, list):
|
| 26 |
+
raw_text = raw_text[0]
|
| 27 |
+
|
| 28 |
+
# 2. Process with spaCy (The exact logic you provided)
|
| 29 |
+
doc = self.nlp(raw_text)
|
| 30 |
+
|
| 31 |
+
# 3. Extract sentences (Your specific list comprehension)
|
| 32 |
+
raw_sentences = [s.text.strip() for s in doc.sents if s.text.strip()]
|
| 33 |
+
|
| 34 |
+
# 4. Return the list of strings
|
| 35 |
+
return raw_sentences
|