RoshanSanjeev commited on
Commit
7e9c3a6
·
verified ·
1 Parent(s): f064a8d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py CHANGED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ from fastapi import FastAPI, Request
3
+ import uvicorn
4
+
5
+ from uagents import Agent, Context, Bureau
6
+
7
+ # Load emotion detection model
8
+ emotion_model = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion")
9
+
10
+ def analyze_text_metrics(text):
11
+ results = emotion_model(text)
12
+ text_lower = text.lower()
13
+
14
+ suicide_keywords = ["kill myself", "suicidal", "die", "ending it", "pills", "overdose", "no way out"]
15
+ psychosis_keywords = ["voices", "hallucinate", "not real", "they’re watching me", "i’m not me"]
16
+
17
+ metrics = {
18
+ "self_harm": 0,
19
+ "homicidal": 0,
20
+ "distress": 0,
21
+ "psychosis": 0
22
+ }
23
+
24
+ for result in results:
25
+ label = result['label']
26
+ score = result['score']
27
+ if label == 'sadness':
28
+ metrics["self_harm"] += score
29
+ metrics["distress"] += score * 0.6
30
+ elif label in ['anger', 'fear']:
31
+ metrics["homicidal"] += score
32
+ metrics["distress"] += score * 0.5
33
+ elif label == 'joy':
34
+ metrics["psychosis"] += score * 0.3
35
+ elif label == 'surprise':
36
+ metrics["psychosis"] += score * 0.5
37
+
38
+ if any(word in text_lower for word in suicide_keywords):
39
+ metrics["self_harm"] = max(metrics["self_harm"], 0.8)
40
+ if any(word in text_lower for word in psychosis_keywords):
41
+ metrics["psychosis"] = max(metrics["psychosis"], 0.8)
42
+
43
+ for k in metrics:
44
+ metrics[k] = round(min(metrics[k] * 100, 100), 2)
45
+
46
+ return metrics
47
+
48
+ # Define uAgent
49
+ agent = Agent(name="sentiment_agent")
50
+
51
+ @agent.on_message()
52
+ async def handle_message(ctx: Context, sender: str, msg: str):
53
+ metrics = analyze_text_metrics(msg)
54
+ await ctx.send(sender, str(metrics))
55
+
56
+ # FastAPI wrapper
57
+ app = FastAPI()
58
+
59
+ @app.post("/")
60
+ async def analyze_text(request: Request):
61
+ data = await request.json()
62
+ text = data.get("text", "")
63
+ result = analyze_text_metrics(text)
64
+ return result
65
+
66
+ # Run both FastAPI and agent
67
+ if __name__ == "__main__":
68
+ bureau = Bureau()
69
+ bureau.add(agent)
70
+ bureau.run_in_thread()
71
+ uvicorn.run(app, host="0.0.0.0", port=8000)