RoshanSanjeev commited on
Commit
7552a11
Β·
verified Β·
1 Parent(s): 0bfbd02

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -78
app.py CHANGED
@@ -1,100 +1,90 @@
 
1
  from fastapi import FastAPI, Request
2
- import google.generativeai as genai
3
- import os, json, re
4
 
5
  from uagents import Agent, Context, Bureau, Model
6
 
7
- # ───────────────────────────────────────────────────────────────
8
- # 1️⃣ GEMINI API KEY (supports either env name)
9
- # ───────────────────────────────────────────────────────────────
10
- api_key = os.getenv("GEMINI_API_KEY") or os.getenv("Gemini")
11
- if not api_key:
12
- raise RuntimeError(
13
- "βœ–οΈ Gemini API key not found. Add it to your Space secrets "
14
- "as GEMINI_API_KEY (preferred) or Gemini."
15
- )
16
- genai.configure(api_key=api_key)
17
- model = genai.GenerativeModel("gemini-pro")
18
-
19
- # ───────────────────────────────────────────────────────────────
20
- # 2️⃣ uAgent I/O MODEL
21
- # ───────────────────────────────────────────────────────────────
22
  class TextInput(Model):
23
  text: str
24
 
25
- # ───────────────────────────────────────────────────────────────
26
- # 3️⃣ GEMINI-POWERED ANALYSIS
27
- # – robust JSON extraction
28
- # ───────────────────────────────────────────────────────────────
29
- json_pattern = re.compile(r"\{[\s\S]*\}")
30
-
31
- def analyze_text_metrics(text: str) -> dict:
32
- prompt = f"""
33
- You are a mental-health AI assistant.
34
-
35
- Return **ONLY** valid JSON with four keys:
36
- "self_harm", "homicidal", "distress", "psychosis"
37
- Each value must be a number between 0.01 and 0.99 (no strings).
38
-
39
- Example:
40
- {{"self_harm":0.91,"homicidal":0.12,"distress":0.72,"psychosis":0.18}}
41
-
42
- Text to analyse:
43
- \"\"\"{text}\"\"\"
44
- """.strip()
45
-
46
- try:
47
- resp = model.generate_content(prompt, safety_settings={"HARASSMENT": "block_none"})
48
- raw = resp.text.strip()
49
-
50
- # grab first JSON objectβ€”even if Gemini wrapped it in ```json``` fences
51
- m = json_pattern.search(raw)
52
- if not m:
53
- raise ValueError(f"No JSON found in Gemini response:\n{raw}")
54
-
55
- data = json.loads(m.group(0))
56
- # basic sanity check
57
- for k in ("self_harm", "homicidal", "distress", "psychosis"):
58
- if k not in data:
59
- raise KeyError(f"Missing key {k}")
60
- return data
61
-
62
- except Exception as e:
63
- # fail-safe minimal response
64
- return {
65
- "self_harm": 0.01,
66
- "homicidal": 0.01,
67
- "distress": 0.01,
68
- "psychosis": 0.01,
69
- "error": str(e)
70
- }
71
-
72
- # ───────────────────────────────────────────────────────────────
73
- # 4️⃣ uAgent DEFINITION
74
- # ───────────────────────────────────────────────────────────────
 
 
 
 
75
  agent = Agent(name="sentiment_agent")
76
 
77
  @agent.on_message(model=TextInput)
78
  async def handle_message(ctx: Context, sender: str, msg: TextInput):
79
- await ctx.send(sender, analyze_text_metrics(msg.text))
 
 
 
80
 
81
- # ───────────────────────────────────────────────────────────────
82
- # 5️⃣ FASTAPI ENDPOINT (Hugging Face uses port 7860)
83
- # ───────────────────────────────────────────────────────────────
84
  app = FastAPI()
85
 
86
  @app.post("/")
87
- async def analyze(request: Request):
88
  data = await request.json()
89
  return analyze_text_metrics(data.get("text", ""))
90
 
91
- # ───────────────────────────────────────────────────────────────
92
- # 6️⃣ START EVERYTHING
93
- # ───────────────────────────────────────────────────────────────
94
  if __name__ == "__main__":
95
  bureau = Bureau()
96
  bureau.add(agent)
97
- bureau.run_in_thread() # expose on Agentverse
 
 
98
 
99
- import uvicorn
100
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ from transformers import pipeline
2
  from fastapi import FastAPI, Request
3
+ import uvicorn
 
4
 
5
  from uagents import Agent, Context, Bureau, Model
6
 
7
+ # ─── uAgent I/O MODEL ─────────────────────────────────────────────────────
8
+
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  class TextInput(Model):
10
  text: str
11
 
12
+ # ─── LOAD EMOTION PIPELINE ─────────────────────────────────────────────────
13
+
14
+ emotion_model = pipeline(
15
+ "text-classification",
16
+ model="bhadresh-savani/distilbert-base-uncased-emotion"
17
+ )
18
+
19
+ # ─── CUSTOM ANALYSIS LOGIC ─────────────────────────────────────────────────
20
+
21
+ def analyze_text_metrics(text):
22
+ results = emotion_model(text)
23
+ t = text.lower()
24
+
25
+ suicide_keywords = ["kill myself", "suicidal", "die", "ending it", "pills", "overdose", "no way out"]
26
+ psychosis_keywords = ["voices", "hallucinate", "not real", "they’re watching me", "i’m not me"]
27
+
28
+ metrics = {
29
+ "self_harm": 0.0,
30
+ "homicidal": 0.0,
31
+ "distress": 0.0,
32
+ "psychosis": 0.0
33
+ }
34
+
35
+ # aggregate raw scores
36
+ for res in results:
37
+ label = res["label"]
38
+ score = res["score"]
39
+ if label == "sadness":
40
+ metrics["self_harm"] += score
41
+ metrics["distress"] += score * 0.6
42
+ elif label in ("anger", "fear"):
43
+ metrics["homicidal"] += score
44
+ metrics["distress"] += score * 0.5
45
+ elif label == "joy":
46
+ metrics["psychosis"] += score * 0.3
47
+ elif label == "surprise":
48
+ metrics["psychosis"] += score * 0.5
49
+
50
+ # keyword overrides
51
+ if any(kw in t for kw in suicide_keywords):
52
+ metrics["self_harm"] = max(metrics["self_harm"], 0.8)
53
+ if any(kw in t for kw in psychosis_keywords):
54
+ metrics["psychosis"] = max(metrics["psychosis"], 0.8)
55
+
56
+ # clamp into [0.01, 0.99]
57
+ for k in metrics:
58
+ val = metrics[k]
59
+ clamped = max(min(val, 0.99), 0.01)
60
+ metrics[k] = round(clamped, 2)
61
+
62
+ return metrics
63
+
64
+ # ─── uAgent DEFINITION ────────────────────────────────────────────────────
65
+
66
  agent = Agent(name="sentiment_agent")
67
 
68
  @agent.on_message(model=TextInput)
69
  async def handle_message(ctx: Context, sender: str, msg: TextInput):
70
+ flags = analyze_text_metrics(msg.text)
71
+ await ctx.send(sender, flags)
72
+
73
+ # ─── FASTAPI HTTP ENDPOINT ───────────────────────────────────────────────
74
 
 
 
 
75
  app = FastAPI()
76
 
77
  @app.post("/")
78
+ async def analyze_text(request: Request):
79
  data = await request.json()
80
  return analyze_text_metrics(data.get("text", ""))
81
 
82
+ # ─── START BOTH ───────────────────────────────────────────────────────────
83
+
 
84
  if __name__ == "__main__":
85
  bureau = Bureau()
86
  bureau.add(agent)
87
+ bureau.run_in_thread() # serve the agent on Agentverse
88
+ uvicorn.run(app, host="0.0.0.0", port=8000)
89
+
90