avtak commited on
Commit
e89cc84
·
verified ·
1 Parent(s): 213f41f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -18
app.py CHANGED
@@ -9,7 +9,7 @@ hf_token = os.getenv("HF_TOKEN")
9
  if hf_token:
10
  login(token=hf_token)
11
 
12
- # --- 2. TOOL LOADING ---
13
  print("Loading Mental-Longformer...")
14
  model_name = "avtak/erisk-longformer-depression-v1"
15
  classifier = pipeline("text-classification", model=model_name, truncation=True, max_length=4096, top_k=None)
@@ -23,7 +23,6 @@ def get_crisis_resources(location: str = "Global") -> str:
23
  "Malaysia": "🇲🇾 **Malaysia:** Befrienders KL: 03-76272929 | Talian Kasih: 15999",
24
  "Global": "🌍 **International:** [befrienders.org](https://www.befrienders.org)"
25
  }
26
- # Fallback logic
27
  for key in resources:
28
  if location and key.lower() in location.lower():
29
  return resources[key]
@@ -31,28 +30,32 @@ def get_crisis_resources(location: str = "Global") -> str:
31
 
32
  def detect_depression_risk(text: str) -> dict:
33
  """Analyzes text using Mental-Longformer (eRisk 2025)."""
34
- # Thesis Aggregation Logic:
35
- # We replace single newlines with double newlines so the model sees distinct posts
 
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: level = "Low Risk (Isolated Pattern)"
42
- elif 0.40 <= prob < 0.60: level = "Moderate Risk (Interactive Echo Chamber Pattern)"
43
- else: level = "High Risk (Depressed Pattern)"
 
 
 
44
 
45
  return {"probability": prob, "risk_level": level, "word_count": len(processed_text.split())}
46
 
47
- # --- 4. AGENT REASONING (UPDATED MODELS) ---
48
  def agent_reasoning(text, risk_data, provider="SambaNova"):
49
  """
50
- Uses Sponsor APIs to interpret the clinical data.
51
  """
52
  client = None
53
  model = None
54
 
55
- # SYSTEM PROMPT (Thesis-Informed)
56
  system_prompt = f"""
57
  You are 'Dr. Longformer', an empathetic Clinical AI Research Agent.
58
 
@@ -76,7 +79,6 @@ def agent_reasoning(text, risk_data, provider="SambaNova"):
76
  if not api_key: return "⚠️ Nebius API Key missing."
77
 
78
  client = OpenAI(base_url="https://api.tokenfactory.nebius.com/v1/", api_key=api_key)
79
- # UPDATED MODEL ID
80
  model = "moonshotai/Kimi-K2-Thinking"
81
 
82
  # --- SPONSOR 2: SAMBANOVA (Llama 3.3) ---
@@ -85,7 +87,6 @@ def agent_reasoning(text, risk_data, provider="SambaNova"):
85
  if not api_key: return "⚠️ SambaNova API Key missing."
86
 
87
  client = OpenAI(base_url="https://api.sambanova.ai/v1", api_key=api_key)
88
- # UPDATED MODEL ID
89
  model = "Meta-Llama-3.3-70B-Instruct"
90
 
91
  # EXECUTE
@@ -96,33 +97,40 @@ def agent_reasoning(text, risk_data, provider="SambaNova"):
96
  {"role": "user", "content": "Analyze this."}
97
  ],
98
  temperature=0.6,
99
- max_tokens=300
100
  )
101
  return response.choices[0].message.content
102
 
103
  except Exception as e:
104
  return f"Reasoning Error ({provider}): {str(e)}"
105
 
106
- # --- 5. PIPELINE ---
107
  def full_analysis_pipeline(user_text, location, provider):
108
- if not user_text.strip(): return "Please enter text.", "No data", "No data"
109
 
 
110
  risk_data = detect_depression_risk(user_text)
 
 
111
  resources = get_crisis_resources(location)
 
 
112
  explanation = agent_reasoning(user_text, risk_data, provider)
113
 
114
- # Color logic
115
  color = "green" if risk_data['probability'] < 0.4 else "orange" if risk_data['probability'] < 0.6 else "red"
116
 
 
117
  return f"""
118
- <div style="border-left: 5px solid {color}; padding-left: 10px;">
119
  <h2 style="color:{color}; margin:0;">{risk_data['risk_level']}</h2>
120
- <h3 style="margin-top:0;">Probability: {risk_data['probability']*100:.1f}%</h3>
121
  </div>
122
 
123
  ### 🧠 Agent Analysis ({provider})
124
  {explanation}
125
 
 
126
  ### 🆘 Recommended Resources
127
  {resources}
128
  """
 
9
  if hf_token:
10
  login(token=hf_token)
11
 
12
+ # --- 2. LOAD TOOL ---
13
  print("Loading Mental-Longformer...")
14
  model_name = "avtak/erisk-longformer-depression-v1"
15
  classifier = pipeline("text-classification", model=model_name, truncation=True, max_length=4096, top_k=None)
 
23
  "Malaysia": "🇲🇾 **Malaysia:** Befrienders KL: 03-76272929 | Talian Kasih: 15999",
24
  "Global": "🌍 **International:** [befrienders.org](https://www.befrienders.org)"
25
  }
 
26
  for key in resources:
27
  if location and key.lower() in location.lower():
28
  return resources[key]
 
30
 
31
  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
 
 
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) ---
 
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
 
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
 
111
+ # 1. Run Tool
112
  risk_data = detect_depression_risk(user_text)
113
+
114
+ # 2. Get Resources
115
  resources = get_crisis_resources(location)
116
+
117
+ # 3. Agent Reasoning
118
  explanation = agent_reasoning(user_text, risk_data, provider)
119
 
120
+ # 4. Color Logic
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>
127
+ <h3 style="margin-top:5px;">Probability: {risk_data['probability']*100:.1f}%</h3>
128
  </div>
129
 
130
  ### 🧠 Agent Analysis ({provider})
131
  {explanation}
132
 
133
+ ---
134
  ### 🆘 Recommended Resources
135
  {resources}
136
  """