avtak commited on
Commit
11903cf
·
verified ·
1 Parent(s): e89cc84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -22
app.py CHANGED
@@ -3,6 +3,7 @@ from transformers import pipeline
3
  from huggingface_hub import login
4
  from openai import OpenAI
5
  import os
 
6
 
7
  # --- 1. SETUP ---
8
  hf_token = os.getenv("HF_TOKEN")
@@ -32,37 +33,53 @@ def detect_depression_risk(text: str) -> dict:
32
  """Analyzes text using Mental-Longformer (eRisk 2025)."""
33
 
34
  # --- THESIS LOGIC: AGGREGATION ---
35
- # Strictly preserving your requirement for double newlines
36
- processed_text = text.replace("\n", "\n\n")
37
 
38
  results = classifier(processed_text)[0]
39
  prob = next((r['score'] for r in results if r['label'] == 'LABEL_1'), 0)
40
 
 
41
  if prob < 0.40:
42
- level = "Low Risk (Isolated Pattern)"
 
 
 
43
  elif 0.40 <= prob < 0.60:
44
- level = "Moderate Risk (Interactive Echo Chamber Pattern)"
 
 
 
45
  else:
46
- level = "High Risk (Depressed Pattern)"
 
 
 
47
 
48
- return {"probability": prob, "risk_level": level, "word_count": len(processed_text.split())}
 
 
 
 
 
 
 
49
 
50
- # --- 4. AGENT REASONING (SambaNova/Nebius) ---
51
  def agent_reasoning(text, risk_data, provider="SambaNova"):
52
  """
53
  Uses Sponsor APIs to generate the analysis report.
54
  """
55
  client = None
56
- model = None
57
 
58
  # SYSTEM PROMPT
59
  system_prompt = f"""
60
  You are 'Dr. Longformer', an empathetic Clinical AI Research Agent.
61
 
62
- CLINICAL DATA (Mental-Longformer):
63
- - Risk Level: {risk_data['risk_level']}
64
- - Probability: {risk_data['probability']:.1%}
65
- - Input Length: {risk_data['word_count']} words
66
 
67
  USER TEXT SNIPPET: "{text[:800]}..."
68
 
@@ -73,38 +90,44 @@ def agent_reasoning(text, risk_data, provider="SambaNova"):
73
  """
74
 
75
  try:
76
- # --- SPONSOR 1: NEBIUS (Kimi K2) ---
77
  if provider == "Nebius (Kimi K2)":
78
  api_key = os.getenv("NEBIUS_API_KEY")
79
  if not api_key: return "⚠️ Nebius API Key missing."
80
 
81
- client = OpenAI(base_url="https://api.tokenfactory.nebius.com/v1/", api_key=api_key)
82
- model = "moonshotai/Kimi-K2-Thinking"
 
 
 
83
 
84
  # --- SPONSOR 2: SAMBANOVA (Llama 3.3) ---
85
  elif provider == "SambaNova":
86
  api_key = os.getenv("SAMBANOVA_API_KEY")
87
  if not api_key: return "⚠️ SambaNova API Key missing."
88
 
89
- client = OpenAI(base_url="https://api.sambanova.ai/v1", api_key=api_key)
90
- model = "Meta-Llama-3.3-70B-Instruct"
 
 
 
91
 
92
  # EXECUTE
93
  response = client.chat.completions.create(
94
- model=model,
95
  messages=[
96
  {"role": "system", "content": system_prompt},
97
  {"role": "user", "content": "Analyze this."}
98
  ],
99
  temperature=0.6,
100
- max_tokens=250
101
  )
102
  return response.choices[0].message.content
103
 
104
  except Exception as e:
105
  return f"Reasoning Error ({provider}): {str(e)}"
106
 
107
- # --- 5. PIPELINE (No Chatbot, Just Report) ---
108
  def full_analysis_pipeline(user_text, location, provider):
109
  if not user_text.strip(): return "Please enter text."
110
 
@@ -121,6 +144,7 @@ def full_analysis_pipeline(user_text, location, provider):
121
  color = "green" if risk_data['probability'] < 0.4 else "orange" if risk_data['probability'] < 0.6 else "red"
122
 
123
  # 5. Build HTML/Markdown Report
 
124
  return f"""
125
  <div style="border-left: 6px solid {color}; padding-left: 15px; background-color: {color}10; border-radius: 5px; padding: 20px;">
126
  <h2 style="color:{color}; margin:0;">{risk_data['risk_level']}</h2>
@@ -128,7 +152,9 @@ def full_analysis_pipeline(user_text, location, provider):
128
  </div>
129
 
130
  ### 🧠 Agent Analysis ({provider})
 
131
  {explanation}
 
132
 
133
  ---
134
  ### 🆘 Recommended Resources
@@ -137,15 +163,21 @@ def full_analysis_pipeline(user_text, location, provider):
137
 
138
  # --- 6. EXAMPLES ---
139
  example_low = """The new update for the Linux kernel (6.8) finally addressed the driver issues I was seeing with Realtek cards. I read the changelog on kernel.org and noticed they patched the module specific to the rtl8821ce chipset.
 
140
  On a different note, the defensive stats for the basketball team have improved significantly. Allowing 15% fewer points per possession is a game changer.
 
141
  I also spent some time woodworking. I'm building a walnut coffee table and the grain is tricky to plane. I might switch to a polyurethane finish for durability."""
142
 
143
  example_mod = """Things have been pretty busy at work. We're in the middle of a big project and deadlines are tight. Staying a bit later than usual but that's just how it goes sometimes. Team is handling it well overall.
 
144
  Sleep could be better. Been staying up too late scrolling my phone. Need to work on that. Usually feel okay once I get moving in the morning though.
145
- Went hiking with some friends last weekend which was nice. Good to get outside and move around."""
 
146
 
147
  example_high = """I don't know why I even bother getting out of bed anymore. I slept for 12 hours yesterday and I'm still exhausted. It feels like my limbs weigh a thousand pounds.
 
148
  I've been avoiding my friends for weeks. They keep texting me, but I can't bring myself to reply. The thought of socializing is terrifying.
 
149
  Everything feels like a shade of grey. I can't concentrate on my work. I feel like I'm drowning while everyone else is breathing fine. I was up until 4 AM again last night just staring at the ceiling."""
150
 
151
  # --- 7. UI ---
@@ -171,7 +203,7 @@ with gr.Blocks(title="Depression Risk Agent") as demo:
171
  gr.Markdown("### 3. Agent Settings")
172
  with gr.Row():
173
  # RENAMED to be clearer
174
- loc_dropdown = gr.Dropdown(["Global", "US", "Malaysia"], value="Global", label="Crisis Resource Region")
175
  provider_dropdown = gr.Dropdown(["SambaNova", "Nebius (Kimi K2)"], value="SambaNova", label="Reasoning Brain")
176
 
177
  submit = gr.Button("🚀 Run Analysis Agent", variant="primary", size="lg")
 
3
  from huggingface_hub import login
4
  from openai import OpenAI
5
  import os
6
+ import json
7
 
8
  # --- 1. SETUP ---
9
  hf_token = os.getenv("HF_TOKEN")
 
33
  """Analyzes text using Mental-Longformer (eRisk 2025)."""
34
 
35
  # --- THESIS LOGIC: AGGREGATION ---
36
+ # 1. We replace single newlines with double newlines for the MODEL
37
+ processed_text = text.replace("\n", "\n\n")
38
 
39
  results = classifier(processed_text)[0]
40
  prob = next((r['score'] for r in results if r['label'] == 'LABEL_1'), 0)
41
 
42
+ # Thesis Thresholds (Figure 4.15)
43
  if prob < 0.40:
44
+ level = "Low Risk"
45
+ biomarker = "Healthy External Focus"
46
+ desc = "Matches 'Isolated Control' group. High lexical diversity, focus on hobbies/events."
47
+ color = "#10b981" # Green
48
  elif 0.40 <= prob < 0.60:
49
+ level = "Moderate Risk"
50
+ biomarker = "Echo Chamber Interaction"
51
+ desc = "Matches 'Interactive Non-Depressed' group. Engaging in support forums but likely not clinically depressed."
52
+ color = "#f59e0b" # Yellow
53
  else:
54
+ level = "High Risk"
55
+ biomarker = "Nocturnal & High-Effort"
56
+ desc = "Matches 'Depressed' cohort. Indicators: Nocturnal posting spikes (00-05 UTC), high-effort/low-frequency posting."
57
+ color = "#ef4444" # Red
58
 
59
+ return {
60
+ "probability": prob,
61
+ "risk_level": level,
62
+ "biomarker": biomarker,
63
+ "description": desc,
64
+ "color": color,
65
+ "word_count": len(processed_text.split())
66
+ }
67
 
68
+ # --- 4. AGENT REASONING (SambaNova + Nebius Kimi) ---
69
  def agent_reasoning(text, risk_data, provider="SambaNova"):
70
  """
71
  Uses Sponsor APIs to generate the analysis report.
72
  """
73
  client = None
74
+ model_id = None
75
 
76
  # SYSTEM PROMPT
77
  system_prompt = f"""
78
  You are 'Dr. Longformer', an empathetic Clinical AI Research Agent.
79
 
80
+ CLINICAL DATA:
81
+ - Risk Level: {risk_data['risk_level']} ({risk_data['probability']:.1%})
82
+ - Biomarker: {risk_data['biomarker']}
 
83
 
84
  USER TEXT SNIPPET: "{text[:800]}..."
85
 
 
90
  """
91
 
92
  try:
93
+ # --- SPONSOR 1: NEBIUS (Kimi K2 Thinking) ---
94
  if provider == "Nebius (Kimi K2)":
95
  api_key = os.getenv("NEBIUS_API_KEY")
96
  if not api_key: return "⚠️ Nebius API Key missing."
97
 
98
+ client = OpenAI(
99
+ base_url="https://api.tokenfactory.nebius.com/v1/",
100
+ api_key=api_key
101
+ )
102
+ model_id = "moonshotai/Kimi-K2-Thinking"
103
 
104
  # --- SPONSOR 2: SAMBANOVA (Llama 3.3) ---
105
  elif provider == "SambaNova":
106
  api_key = os.getenv("SAMBANOVA_API_KEY")
107
  if not api_key: return "⚠️ SambaNova API Key missing."
108
 
109
+ client = OpenAI(
110
+ base_url="https://api.sambanova.ai/v1",
111
+ api_key=api_key
112
+ )
113
+ model_id = "Meta-Llama-3.3-70B-Instruct"
114
 
115
  # EXECUTE
116
  response = client.chat.completions.create(
117
+ model=model_id,
118
  messages=[
119
  {"role": "system", "content": system_prompt},
120
  {"role": "user", "content": "Analyze this."}
121
  ],
122
  temperature=0.6,
123
+ max_tokens=300
124
  )
125
  return response.choices[0].message.content
126
 
127
  except Exception as e:
128
  return f"Reasoning Error ({provider}): {str(e)}"
129
 
130
+ # --- 5. PIPELINE ---
131
  def full_analysis_pipeline(user_text, location, provider):
132
  if not user_text.strip(): return "Please enter text."
133
 
 
144
  color = "green" if risk_data['probability'] < 0.4 else "orange" if risk_data['probability'] < 0.6 else "red"
145
 
146
  # 5. Build HTML/Markdown Report
147
+ # FIX: Added 'white-space: pre-wrap' to preserve newlines in display
148
  return f"""
149
  <div style="border-left: 6px solid {color}; padding-left: 15px; background-color: {color}10; border-radius: 5px; padding: 20px;">
150
  <h2 style="color:{color}; margin:0;">{risk_data['risk_level']}</h2>
 
152
  </div>
153
 
154
  ### 🧠 Agent Analysis ({provider})
155
+ <div style="white-space: pre-wrap; font-family: sans-serif;">
156
  {explanation}
157
+ </div>
158
 
159
  ---
160
  ### 🆘 Recommended Resources
 
163
 
164
  # --- 6. EXAMPLES ---
165
  example_low = """The new update for the Linux kernel (6.8) finally addressed the driver issues I was seeing with Realtek cards. I read the changelog on kernel.org and noticed they patched the module specific to the rtl8821ce chipset.
166
+
167
  On a different note, the defensive stats for the basketball team have improved significantly. Allowing 15% fewer points per possession is a game changer.
168
+
169
  I also spent some time woodworking. I'm building a walnut coffee table and the grain is tricky to plane. I might switch to a polyurethane finish for durability."""
170
 
171
  example_mod = """Things have been pretty busy at work. We're in the middle of a big project and deadlines are tight. Staying a bit later than usual but that's just how it goes sometimes. Team is handling it well overall.
172
+
173
  Sleep could be better. Been staying up too late scrolling my phone. Need to work on that. Usually feel okay once I get moving in the morning though.
174
+
175
+ Went hiking with some friends last weekend which was nice. Good to get outside and move around. We're talking about doing another trip next month. Weather should be better by then."""
176
 
177
  example_high = """I don't know why I even bother getting out of bed anymore. I slept for 12 hours yesterday and I'm still exhausted. It feels like my limbs weigh a thousand pounds.
178
+
179
  I've been avoiding my friends for weeks. They keep texting me, but I can't bring myself to reply. The thought of socializing is terrifying.
180
+
181
  Everything feels like a shade of grey. I can't concentrate on my work. I feel like I'm drowning while everyone else is breathing fine. I was up until 4 AM again last night just staring at the ceiling."""
182
 
183
  # --- 7. UI ---
 
203
  gr.Markdown("### 3. Agent Settings")
204
  with gr.Row():
205
  # RENAMED to be clearer
206
+ loc_dropdown = gr.Dropdown(["Global", "US", "Malaysia"], value="Malaysia", label="Crisis Resource Region")
207
  provider_dropdown = gr.Dropdown(["SambaNova", "Nebius (Kimi K2)"], value="SambaNova", label="Reasoning Brain")
208
 
209
  submit = gr.Button("🚀 Run Analysis Agent", variant="primary", size="lg")