SCANSKY commited on
Commit
2bc2351
·
verified ·
1 Parent(s): c1a44d8

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +79 -0
handler.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from bertopic import BERTopic
3
+
4
+ class EndpointHandler:
5
+ def __init__(self, model_path="SCANSKY/BERTopic-Tourism-English"):
6
+ """
7
+ Initialize the handler. Load the BERTopic model from Hugging Face.
8
+ """
9
+ self.topic_model = BERTopic.load(model_path)
10
+
11
+ def preprocess(self, data):
12
+ """
13
+ Preprocess the incoming request data.
14
+ - Extract text input from the request.
15
+ """
16
+ try:
17
+ # Parse the incoming data
18
+ body = json.loads(data)
19
+ text_input = body.get("text", "")
20
+ return text_input
21
+ except Exception as e:
22
+ raise ValueError(f"Error during preprocessing: {str(e)}")
23
+
24
+ def inference(self, text_input):
25
+ """
26
+ Perform inference using the BERTopic model.
27
+ - Process the text input and generate topic predictions.
28
+ """
29
+ try:
30
+ # Split text into documents (assuming one document per line)
31
+ docs = text_input.strip().split('\n')
32
+
33
+ # Perform topic inference
34
+ topics, probabilities = self.topic_model.transform(docs)
35
+
36
+ # Get topic information
37
+ topics_info = self.topic_model.get_topics()
38
+
39
+ # Prepare the results
40
+ results = []
41
+ for topic, prob in zip(topics, probabilities):
42
+ topic_words = topics_info.get(topic, [])
43
+ results.append({
44
+ "topic": int(topic),
45
+ "probability": float(prob),
46
+ "top_words": [word for word, _ in topic_words[:5]] # Top 5 words
47
+ })
48
+
49
+ return results
50
+ except Exception as e:
51
+ raise ValueError(f"Error during inference: {str(e)}")
52
+
53
+ def postprocess(self, results):
54
+ """
55
+ Postprocess the inference results into a JSON response.
56
+ """
57
+ return {
58
+ "results": results
59
+ }
60
+
61
+ def __call__(self, data):
62
+ """
63
+ Handle the incoming request.
64
+ """
65
+ try:
66
+ # Preprocess the data
67
+ text_input = self.preprocess(data)
68
+
69
+ # Perform inference
70
+ results = self.inference(text_input)
71
+
72
+ # Postprocess the results
73
+ response = self.postprocess(results)
74
+
75
+ return response
76
+ except Exception as e:
77
+ return {
78
+ "error": str(e)
79
+ }