Update handler.py
Browse files- handler.py +39 -36
handler.py
CHANGED
@@ -20,43 +20,46 @@ class EndpointHandler:
|
|
20 |
except Exception as e:
|
21 |
raise ValueError(f"Error during preprocessing: {str(e)}")
|
22 |
|
23 |
-
def inference(self, text_input):
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
|
|
56 |
|
57 |
-
|
58 |
-
|
59 |
-
raise ValueError(f"Error during inference: {str(e)}") def postprocess(self, results):
|
60 |
"""
|
61 |
Postprocess the inference results into a JSON-serializable list.
|
62 |
"""
|
|
|
20 |
except Exception as e:
|
21 |
raise ValueError(f"Error during preprocessing: {str(e)}")
|
22 |
|
23 |
+
def inference(self, text_input):
|
24 |
+
"""
|
25 |
+
Perform inference using the BERTopic model.
|
26 |
+
- Combine all sentences into a single document and find shared topics.
|
27 |
+
"""
|
28 |
+
try:
|
29 |
+
# Split text into sentences (assuming one sentence per line)
|
30 |
+
sentences = text_input.strip().split('\n')
|
31 |
+
|
32 |
+
# Combine all sentences into a single document
|
33 |
+
combined_document = " ".join(sentences)
|
34 |
+
|
35 |
+
# Perform topic inference on the combined document
|
36 |
+
topics, probabilities = self.topic_model.transform([combined_document])
|
37 |
+
|
38 |
+
# Prepare the results
|
39 |
+
results = []
|
40 |
+
for topic, prob in zip(topics, probabilities):
|
41 |
+
topic_info = self.topic_model.get_topic(topic)
|
42 |
+
topic_words = [word for word, _ in topic_info] if topic_info else []
|
43 |
+
|
44 |
+
# Get custom label for the topic
|
45 |
+
if hasattr(self.topic_model, "custom_labels_") and self.topic_model.custom_labels_ is not None:
|
46 |
+
custom_label = self.topic_model.custom_labels_[topic + 1]
|
47 |
+
else:
|
48 |
+
custom_label = f"Topic {topic}" # Fallback label
|
49 |
+
|
50 |
+
results.append({
|
51 |
+
"topic": int(topic),
|
52 |
+
"probability": float(prob),
|
53 |
+
"top_words": topic_words[:5], # Top 5 words
|
54 |
+
"customLabel": custom_label # Add custom label
|
55 |
+
})
|
56 |
+
|
57 |
+
return results
|
58 |
+
except Exception as e:
|
59 |
+
raise ValueError(f"Error during inference: {str(e)}")
|
60 |
|
61 |
+
|
62 |
+
def postprocess(self, results):
|
|
|
63 |
"""
|
64 |
Postprocess the inference results into a JSON-serializable list.
|
65 |
"""
|