Spaces:
Runtime error
Runtime error
updated potentially correct huggingfacehub import
Browse files- crew.py +1 -1
- crew.txt +459 -29
- requirements.txt +2 -1
crew.py
CHANGED
|
@@ -9,7 +9,7 @@ from dataloaderImp import *
|
|
| 9 |
from typing import Union
|
| 10 |
import shap
|
| 11 |
import xgboost as xgb
|
| 12 |
-
from
|
| 13 |
|
| 14 |
# Load audio model & metadata
|
| 15 |
audio_model = xgb.Booster()
|
|
|
|
| 9 |
from typing import Union
|
| 10 |
import shap
|
| 11 |
import xgboost as xgb
|
| 12 |
+
from langchain_huggingface import HuggingFaceHub
|
| 13 |
|
| 14 |
# Load audio model & metadata
|
| 15 |
audio_model = xgb.Booster()
|
crew.txt
CHANGED
|
@@ -1,41 +1,471 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
|
|
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
| 18 |
try:
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
except Exception as e:
|
| 21 |
return {"status": "error", "message": str(e)}
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
gr.Markdown("# 🧠 NMS Dementia Risk Assessment API")
|
| 31 |
-
mode = gr.Radio(
|
| 32 |
-
choices=["lifestyle", "audio"],
|
| 33 |
-
value="lifestyle",
|
| 34 |
-
label="Select Risk Assessment Type"
|
| 35 |
-
)
|
| 36 |
-
doc_id = gr.Textbox(label="Patient Document ID <265e9lboNaBH9bQE0CHR>", placeholder="e.g., 265e9lboNaBH9bQE0CHR")
|
| 37 |
-
output = gr.JSON()
|
| 38 |
-
btn = gr.Button("Get Risk Assessment")
|
| 39 |
-
btn.click(fn=assess_risk, inputs=[doc_id, mode], outputs=output)
|
| 40 |
-
|
| 41 |
-
demo.launch()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import joblib
|
| 5 |
+
import numpy as np
|
| 6 |
+
from crewai import Agent, Task, Crew, LLM
|
| 7 |
+
from crewai.tools import tool
|
| 8 |
+
from dataloaderImp import *
|
| 9 |
+
from typing import Union
|
| 10 |
+
import shap
|
| 11 |
+
import xgboost as xgb
|
| 12 |
+
from langchain import HuggingFaceHub
|
| 13 |
|
| 14 |
+
# Load audio model & metadata
|
| 15 |
+
audio_model = xgb.Booster()
|
| 16 |
+
audio_model.load_model('modelAudiov8_ML.json')
|
| 17 |
|
| 18 |
+
metadata = joblib.load('modelAudiov8_metadata.pk1')
|
| 19 |
+
audio_feature_names = metadata['feature_names']
|
| 20 |
+
audio_mmse_index = metadata['mmse_index']
|
| 21 |
|
| 22 |
+
# Load lifestyle model & metadata
|
| 23 |
+
lifestyle_model = xgb.Booster()
|
| 24 |
+
lifestyle_model.load_model('modelLifestyleV3_ML.json')
|
| 25 |
+
|
| 26 |
+
metadata = joblib.load('modelLifestyleV3_metadata.pk1')
|
| 27 |
+
lifestyle_feature_names = metadata['feature_names']
|
| 28 |
+
|
| 29 |
+
# Load model explainers
|
| 30 |
+
audio_explainer = shap.TreeExplainer(audio_model)
|
| 31 |
+
lifestyle_explainer = shap.TreeExplainer(lifestyle_model)
|
| 32 |
+
|
| 33 |
+
placeholder_lifestyle_ID = "umWSG13rLSfHqqJlq1WluPzjLB93"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Define tools for the agents
|
| 37 |
+
@tool("calculate_dementia_risk_audio")
|
| 38 |
+
def calculate_dementia_risk_audio(docID: str, return_json: bool = False) -> Union[str, dict]:
|
| 39 |
+
"""
|
| 40 |
+
Calculates dementia risk for a specific patient using audio and transcript data from Firebase.
|
| 41 |
+
If return_json=True, returns a structured dict. Otherwise, returns a formatted report string.
|
| 42 |
+
"""
|
| 43 |
+
try:
|
| 44 |
+
# Handle JSON-wrapped input (from CrewAI)
|
| 45 |
+
if docID.strip().startswith('{'):
|
| 46 |
+
try:
|
| 47 |
+
parsed = json.loads(docID)
|
| 48 |
+
if isinstance(parsed, dict):
|
| 49 |
+
if "Audio" in parsed and isinstance(parsed["Audio"], dict):
|
| 50 |
+
docID = parsed["Audio"].get("docID", docID)
|
| 51 |
+
elif "docID" in parsed:
|
| 52 |
+
docID = parsed["docID"]
|
| 53 |
+
except json.JSONDecodeError:
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
audio_data = pull_audio(docID)
|
| 57 |
+
|
| 58 |
+
if audio_data is None:
|
| 59 |
+
error_msg = f"Error: Could not retrieve or process audio data for patient '{docID}'"
|
| 60 |
+
if return_json:
|
| 61 |
+
return {"status": "error", "message": error_msg}
|
| 62 |
+
return error_msg
|
| 63 |
+
|
| 64 |
+
# Extract values
|
| 65 |
+
age = audio_data.get("age")
|
| 66 |
+
gender_val = audio_data.get("gender")
|
| 67 |
+
mmse = audio_data.get("mmse") # Always None in current implementation
|
| 68 |
+
combined_features = audio_data.get("full_features")
|
| 69 |
+
|
| 70 |
+
if combined_features is None:
|
| 71 |
+
error_msg = f"Error: Feature extraction failed for patient '{docID}'"
|
| 72 |
+
if return_json:
|
| 73 |
+
return {"status": "error", "message": error_msg}
|
| 74 |
+
return error_msg
|
| 75 |
+
|
| 76 |
+
# Predict
|
| 77 |
+
prediction = audio_model.predict(combined_features.reshape(1, -1))[0]
|
| 78 |
+
probability = audio_model.predict_proba(combined_features.reshape(1, -1))[0]
|
| 79 |
+
confidence = float(max(probability))
|
| 80 |
+
risk_level = "High" if prediction == 1 else "Low"
|
| 81 |
+
gender_str = "Male" if gender_val == 1 else "Female"
|
| 82 |
+
|
| 83 |
+
# Structured output
|
| 84 |
+
result_dict = {
|
| 85 |
+
"risk_level": risk_level,
|
| 86 |
+
"prediction": int(prediction),
|
| 87 |
+
"confidence": confidence,
|
| 88 |
+
"age": age,
|
| 89 |
+
"gender": gender_str,
|
| 90 |
+
"docID": docID
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
if return_json:
|
| 94 |
+
return {"status": "success", **result_dict}
|
| 95 |
+
|
| 96 |
+
# Fallback: formatted string report (for CrewAI agents)
|
| 97 |
+
explanation = (
|
| 98 |
+
f"Based on speech analysis and linguistic patterns, "
|
| 99 |
+
f"the AI model detected {'concerning patterns' if prediction == 1 else 'normal patterns'} "
|
| 100 |
+
f"in speech fluency, vocabulary diversity, and cognitive response time."
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
mmse_note = "\n[Note: MMSE score not provided. Assessment based on speech and demographics only. Accuracy may be reduced.]"
|
| 104 |
+
|
| 105 |
+
report = f"""
|
| 106 |
+
DEMENTIA RISK ASSESSMENT (AUDIO)
|
| 107 |
+
================================
|
| 108 |
+
Risk Level: {risk_level}
|
| 109 |
+
Confidence: {confidence:.2%}
|
| 110 |
+
Prediction: {'Positive' if prediction == 1 else 'Negative'}
|
| 111 |
+
Age: {age}
|
| 112 |
+
Gender: {gender_str}
|
| 113 |
+
{mmse_note}
|
| 114 |
+
|
| 115 |
+
EXPLANATION:
|
| 116 |
+
{explanation}
|
| 117 |
+
"""
|
| 118 |
+
return report
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
error_msg = f"Error calculating audio-based risk: {str(e)}"
|
| 122 |
+
if return_json:
|
| 123 |
+
return {"status": "error", "message": error_msg}
|
| 124 |
+
return error_msg
|
| 125 |
+
|
| 126 |
+
@tool("explain_dementia_risk_audio")
|
| 127 |
+
def explain_dementia_risk_audio(docID: str) -> str:
|
| 128 |
+
"""Provides SHAP-based explanation for audio risk prediction."""
|
| 129 |
try:
|
| 130 |
+
# Reuse feature extraction logic (DRY: refactor if needed later)
|
| 131 |
+
audio_data = pull_audio(docID)
|
| 132 |
+
if audio_data is None:
|
| 133 |
+
return f"Error: No data for {docID}"
|
| 134 |
+
|
| 135 |
+
features = audio_data["full_features"]
|
| 136 |
+
feature_names = audio_feature_names
|
| 137 |
+
|
| 138 |
+
# SHAP values for this instance
|
| 139 |
+
shap_values = audio_explainer.shap_values(features.reshape(1, -1))
|
| 140 |
+
# shap_values is array of shape (1, n_features) for class 1 (Dementia)
|
| 141 |
+
|
| 142 |
+
# Get top 5 positive contributors (pushing toward Dementia = class 1)
|
| 143 |
+
shap_vals = shap_values[0] # for class 1
|
| 144 |
+
top_indices = np.argsort(-shap_vals)[:5] # descending by impact
|
| 145 |
+
|
| 146 |
+
explanation_lines = ["🔍 Top factors increasing dementia risk (audio analysis):"]
|
| 147 |
+
for i in top_indices:
|
| 148 |
+
feat = feature_names[i]
|
| 149 |
+
val = features[i]
|
| 150 |
+
impact = shap_vals[i]
|
| 151 |
+
if abs(impact) < 1e-4:
|
| 152 |
+
continue
|
| 153 |
+
direction = "↑" if impact > 0 else "↓"
|
| 154 |
+
explanation_lines.append(f" • {feat} = {val:.3f} → {direction} risk ({impact:+.3f})")
|
| 155 |
+
|
| 156 |
+
return "\n".join(explanation_lines)
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
+
return f"SHAP explanation failed: {str(e)}"
|
| 160 |
+
|
| 161 |
+
@tool("calculate_dementia_risk_lifestyle")
|
| 162 |
+
def calculate_dementia_risk_lifestyle(docID: str, return_json: bool = False) -> Union[str, dict]:
|
| 163 |
+
"""
|
| 164 |
+
Calculates dementia risk for a specific patient using lifestyle data.
|
| 165 |
+
If return_json=True, returns a structured dict. Otherwise, returns a formatted report string.
|
| 166 |
+
"""
|
| 167 |
+
try:
|
| 168 |
+
# Handle JSON-wrapped input (from CrewAI)
|
| 169 |
+
if docID.strip().startswith('{'):
|
| 170 |
+
try:
|
| 171 |
+
parsed = json.loads(docID)
|
| 172 |
+
if isinstance(parsed, dict):
|
| 173 |
+
if "Lifestyle" in parsed and isinstance(parsed["Lifestyle"], dict):
|
| 174 |
+
docID = parsed["Lifestyle"].get("docID", docID)
|
| 175 |
+
elif "docID" in parsed:
|
| 176 |
+
docID = parsed["docID"]
|
| 177 |
+
except json.JSONDecodeError:
|
| 178 |
+
pass
|
| 179 |
+
|
| 180 |
+
lifestyle_data = pull_lifestyle(docID)
|
| 181 |
+
if not lifestyle_data:
|
| 182 |
+
error = f"Error: No lifestyle data found for document ID '{docID}'"
|
| 183 |
+
if return_json:
|
| 184 |
+
return {"status": "error", "message": error}
|
| 185 |
+
return error
|
| 186 |
+
|
| 187 |
+
FEATURE_MAPPING = {
|
| 188 |
+
'Age': 'age',
|
| 189 |
+
'Gender': 'gender',
|
| 190 |
+
'Ethnicity': 'ethnicity',
|
| 191 |
+
'EducationLevel': 'education_level',
|
| 192 |
+
'BMI': 'bmi',
|
| 193 |
+
'Smoking': 'smoking',
|
| 194 |
+
'AlcoholConsumption': 'alcohol_consumption',
|
| 195 |
+
'PhysicalActivity': 'physical_activity',
|
| 196 |
+
'DietQuality': 'diet_quality',
|
| 197 |
+
'SleepQuality': 'sleep_quality',
|
| 198 |
+
'FamilyHistoryAlzheimers': 'family_history_dementia',
|
| 199 |
+
'CardiovascularDisease': 'cardiovascular_disease',
|
| 200 |
+
'Diabetes': 'diabetes',
|
| 201 |
+
'Depression': 'depression',
|
| 202 |
+
'HeadInjury': 'head_injury',
|
| 203 |
+
'Hypertension': 'hypertension'
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
features = []
|
| 207 |
+
for feat_name in lifestyle_feature_names:
|
| 208 |
+
firestore_key = FEATURE_MAPPING.get(feat_name)
|
| 209 |
+
if firestore_key is None:
|
| 210 |
+
error = f"Error: No mapping defined for feature '{feat_name}'"
|
| 211 |
+
if return_json:
|
| 212 |
+
return {"status": "error", "message": error}
|
| 213 |
+
return error
|
| 214 |
+
val = lifestyle_data.get(firestore_key)
|
| 215 |
+
if val is None:
|
| 216 |
+
error = f"Error: Missing required lifestyle feature '{feat_name}' (Firestore key: '{firestore_key}')"
|
| 217 |
+
if return_json:
|
| 218 |
+
return {"status": "error", "message": error}
|
| 219 |
+
return error
|
| 220 |
+
features.append(val)
|
| 221 |
+
|
| 222 |
+
life = np.array(features).reshape(1, -1)
|
| 223 |
+
age = lifestyle_data.get("age")
|
| 224 |
+
gender_val = lifestyle_data.get("gender")
|
| 225 |
+
|
| 226 |
+
prediction = lifestyle_model.predict(life)[0]
|
| 227 |
+
probability = lifestyle_model.predict_proba(life)[0]
|
| 228 |
+
confidence = float(max(probability))
|
| 229 |
+
risk_level = "High" if prediction == 1 else "Low"
|
| 230 |
+
gender_str = "Male" if gender_val == 1 else "Female"
|
| 231 |
+
|
| 232 |
+
# Structured output
|
| 233 |
+
result_dict = {
|
| 234 |
+
"risk_level": risk_level,
|
| 235 |
+
"prediction": int(prediction),
|
| 236 |
+
"confidence": confidence,
|
| 237 |
+
"age": age,
|
| 238 |
+
"gender": gender_str,
|
| 239 |
+
"docID": docID
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
if return_json:
|
| 243 |
+
return result_dict
|
| 244 |
+
|
| 245 |
+
# Original string report
|
| 246 |
+
explanation = (
|
| 247 |
+
f"Based on lifestyle factors including diet, physical activity, and medical history, "
|
| 248 |
+
f"the AI model detected {'concerning patterns' if prediction == 1 else 'normal patterns'} "
|
| 249 |
+
f"associated with increased dementia risk."
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
report = f"""
|
| 253 |
+
DEMENTIA RISK ASSESSMENT (LIFESTYLE)
|
| 254 |
+
===================================
|
| 255 |
+
Risk Level: {risk_level}
|
| 256 |
+
Confidence: {confidence:.2%}
|
| 257 |
+
Prediction: {'Positive' if prediction == 1 else 'Negative'}
|
| 258 |
+
Age: {age}
|
| 259 |
+
Gender: {gender_str}
|
| 260 |
+
|
| 261 |
+
EXPLANATION:
|
| 262 |
+
{explanation}
|
| 263 |
+
"""
|
| 264 |
+
return report
|
| 265 |
+
|
| 266 |
+
except Exception as e:
|
| 267 |
+
error_msg = f"Error calculating risk: {str(e)}"
|
| 268 |
+
if return_json:
|
| 269 |
+
return {"status": "error", "message": error_msg}
|
| 270 |
+
return error_msg
|
| 271 |
+
|
| 272 |
+
@tool("explain_dementia_risk_lifestyle")
|
| 273 |
+
def explain_dementia_risk_lifestyle(docID: str) -> str:
|
| 274 |
+
"""Provides SHAP-based explanation for lifestyle risk prediction."""
|
| 275 |
+
try:
|
| 276 |
+
lifestyle_data = pull_lifestyle(docID)
|
| 277 |
+
if not lifestyle_data:
|
| 278 |
+
return f"Error: No lifestyle data for {docID}"
|
| 279 |
+
|
| 280 |
+
FEATURE_MAPPING = {
|
| 281 |
+
'Age': 'age', 'Gender': 'gender', 'Ethnicity': 'ethnicity',
|
| 282 |
+
'EducationLevel': 'education_level', 'BMI': 'bmi', 'Smoking': 'smoking',
|
| 283 |
+
'AlcoholConsumption': 'alcohol_consumption', 'PhysicalActivity': 'physical_activity',
|
| 284 |
+
'DietQuality': 'diet_quality', 'SleepQuality': 'sleep_quality',
|
| 285 |
+
'FamilyHistoryAlzheimers': 'family_history_dementia',
|
| 286 |
+
'CardiovascularDisease': 'cardiovascular_disease', 'Diabetes': 'diabetes',
|
| 287 |
+
'Depression': 'depression', 'HeadInjury': 'head_injury', 'Hypertension': 'hypertension'
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
features = []
|
| 291 |
+
for feat_name in lifestyle_feature_names:
|
| 292 |
+
val = lifestyle_data.get(FEATURE_MAPPING[feat_name])
|
| 293 |
+
if val is None:
|
| 294 |
+
return f"Missing feature: {feat_name}"
|
| 295 |
+
features.append(val)
|
| 296 |
+
|
| 297 |
+
X_instance = np.array(features).reshape(1, -1)
|
| 298 |
+
shap_vals = lifestyle_explainer.shap_values(X_instance)[0] # class 1
|
| 299 |
+
|
| 300 |
+
top_indices = np.argsort(-shap_vals)[:5]
|
| 301 |
+
|
| 302 |
+
explanation_lines = ["🔍 Top factors increasing dementia risk (lifestyle analysis):"]
|
| 303 |
+
for i in top_indices:
|
| 304 |
+
feat = lifestyle_feature_names[i]
|
| 305 |
+
val = features[i]
|
| 306 |
+
impact = shap_vals[i]
|
| 307 |
+
if abs(impact) < 1e-4:
|
| 308 |
+
continue
|
| 309 |
+
# Map categorical to readable (optional but nice)
|
| 310 |
+
readable_val = val
|
| 311 |
+
if feat == "Gender":
|
| 312 |
+
readable_val = "Male" if val == 1 else "Female"
|
| 313 |
+
elif feat in ["Smoking", "AlcoholConsumption", "FamilyHistoryAlzheimers",
|
| 314 |
+
"CardiovascularDisease", "Diabetes", "Depression", "HeadInjury", "Hypertension"]:
|
| 315 |
+
readable_val = "Yes" if val == 1 else "No"
|
| 316 |
+
elif feat == "EducationLevel":
|
| 317 |
+
edu_map = {1: "Primary", 2: "Secondary", 3: "Bachelor", 4: "Postgrad"}
|
| 318 |
+
readable_val = edu_map.get(val, val)
|
| 319 |
+
|
| 320 |
+
direction = "↑" if impact > 0 else "↓"
|
| 321 |
+
explanation_lines.append(f" • {feat} = {readable_val} → {direction} risk ({impact:+.3f})")
|
| 322 |
+
|
| 323 |
+
return "\n".join(explanation_lines)
|
| 324 |
+
|
| 325 |
+
except Exception as e:
|
| 326 |
+
return f"SHAP explanation failed: {str(e)}"
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# Load LLM from huggingface repos
|
| 330 |
+
llm = HuggingFaceHub(
|
| 331 |
+
repo_id="mistralai/Mistral-7B-Instruct-v0.2",
|
| 332 |
+
model_kwargs={"temperature":0.7, "max_new_tokens":512},
|
| 333 |
+
huggingfacehub_api_token=os.getenv("HF_TOKEN")
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# Define agents for Alzheimer's detection system
|
| 337 |
+
risk_calculator_audio = Agent(
|
| 338 |
+
role="Risk Calculator Audio Agent",
|
| 339 |
+
goal="Calculate dementia risk for a specific patient using ML model and LLM interpretation",
|
| 340 |
+
backstory="You combine machine learning predictions with natural language explanations to provide personalized risk assessments.",
|
| 341 |
+
verbose=True,
|
| 342 |
+
llm=llm,
|
| 343 |
+
tools=[calculate_dementia_risk_audio, explain_dementia_risk_audio]
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
risk_calculator_lifestyle = Agent(
|
| 347 |
+
role="Risk Calculator Lifestyle Agent",
|
| 348 |
+
goal="Calculate dementia risk for a specific patient using ML model and LLM interpretation",
|
| 349 |
+
backstory="You combine machine learning predictions with natural language explanations to provide personalized risk assessments.",
|
| 350 |
+
verbose=True,
|
| 351 |
+
llm=llm,
|
| 352 |
+
tools=[calculate_dementia_risk_lifestyle, explain_dementia_risk_lifestyle]
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# Define tasks for agents
|
| 357 |
+
risk_assessment_task_audio = Task(
|
| 358 |
+
description=f"Calculate dementia risk for patient",
|
| 359 |
+
expected_output="Risk level, confidence score, and plain-language explanation.",
|
| 360 |
+
agent=risk_calculator_audio,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
explanation_task_audio = Task(
|
| 364 |
+
description="Explain the dementia risk prediction for patient using SHAP",
|
| 365 |
+
expected_output="Top 5 features increasing risk from audio analysis.",
|
| 366 |
+
agent=risk_calculator_audio
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
risk_assessment_task_lifestyle = Task(
|
| 370 |
+
description=f"Calculate dementia risk for patient using the given patient id: {placeholder_lifestyle_ID}",
|
| 371 |
+
expected_output="Risk level, confidence score, and plain-language explanation.",
|
| 372 |
+
agent=risk_calculator_lifestyle,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
explanation_task_lifestyle = Task(
|
| 376 |
+
description=f"Explain the dementia risk prediction for patient {placeholder_lifestyle_ID} using SHAP",
|
| 377 |
+
expected_output="Top 5 features increasing risk, with impact direction and magnitude.",
|
| 378 |
+
agent=risk_calculator_lifestyle
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Create crew of agents
|
| 382 |
+
crew = Crew(
|
| 383 |
+
agents=[risk_calculator_audio, risk_calculator_lifestyle],
|
| 384 |
+
tasks=[risk_assessment_task_lifestyle],
|
| 385 |
+
verbose=True
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
def run_crewai_lifestyle(docID: str) -> dict:
|
| 389 |
+
"""
|
| 390 |
+
Runs the full CrewAI pipeline for lifestyle risk + SHAP + LLM summary.
|
| 391 |
+
Returns a JSON-serializable dict (success/error).
|
| 392 |
+
"""
|
| 393 |
+
try:
|
| 394 |
+
# Update task with dynamic docID
|
| 395 |
+
risk_assessment_task_lifestyle.description = f"Calculate dementia risk for patient using lifestyle data for ID: {docID}"
|
| 396 |
+
explanation_task_lifestyle.description = f"Explain the dementia risk prediction for patient {docID} using SHAP"
|
| 397 |
+
|
| 398 |
+
# Rebuild crew with updated tasks
|
| 399 |
+
crew_lifestyle = Crew(
|
| 400 |
+
agents=[risk_calculator_lifestyle],
|
| 401 |
+
tasks=[risk_assessment_task_lifestyle, explanation_task_lifestyle],
|
| 402 |
+
verbose=False # Keep logs clean for API
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# Run
|
| 406 |
+
raw_output = crew_lifestyle.kickoff()
|
| 407 |
+
|
| 408 |
+
# Parse raw_output (usually a string) → try to extract JSON or format
|
| 409 |
+
# Since agents return natural language, we'll wrap it + add structured fields
|
| 410 |
+
# First, get raw model output for structured data
|
| 411 |
+
lifestyle_data = pull_lifestyle(docID)
|
| 412 |
+
if not lifestyle_data:
|
| 413 |
+
return {"status": "error", "message": f"No lifestyle data for {docID}"}
|
| 414 |
+
|
| 415 |
+
# Reuse function logic just for prediction (fast, reliable)
|
| 416 |
+
risk_result = calculate_dementia_risk_lifestyle(docID, return_json=True)
|
| 417 |
+
if risk_result["status"] != "success":
|
| 418 |
+
return risk_result
|
| 419 |
+
|
| 420 |
+
# Add explanation
|
| 421 |
+
shap_explanation = explain_dementia_risk_lifestyle(docID)
|
| 422 |
+
|
| 423 |
+
return {
|
| 424 |
+
"status": "success",
|
| 425 |
+
**risk_result,
|
| 426 |
+
"shap_explanation": shap_explanation,
|
| 427 |
+
"crew_summary": str(raw_output).strip()
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
except Exception as e:
|
| 431 |
return {"status": "error", "message": str(e)}
|
| 432 |
|
| 433 |
+
|
| 434 |
+
def run_crewai_audio(docID: str) -> dict:
|
| 435 |
+
"""Same for audio."""
|
| 436 |
try:
|
| 437 |
+
risk_assessment_task_audio.description = f"Calculate dementia risk for patient using audio data for ID: {docID}"
|
| 438 |
+
explanation_task_audio.description = f"Explain the dementia risk prediction for patient {docID} using SHAP"
|
| 439 |
+
|
| 440 |
+
crew_audio = Crew(
|
| 441 |
+
agents=[risk_calculator_audio],
|
| 442 |
+
tasks=[risk_assessment_task_audio, explanation_task_audio],
|
| 443 |
+
verbose=False
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
raw_output = crew_audio.kickoff()
|
| 447 |
+
|
| 448 |
+
# Get structured result
|
| 449 |
+
risk_result = calculate_dementia_risk_audio(docID, return_json=True)
|
| 450 |
+
if risk_result["status"] != "success":
|
| 451 |
+
return risk_result
|
| 452 |
+
|
| 453 |
+
shap_explanation = explain_dementia_risk_audio(docID)
|
| 454 |
+
|
| 455 |
+
return {
|
| 456 |
+
"status": "success",
|
| 457 |
+
**risk_result,
|
| 458 |
+
"shap_explanation": shap_explanation,
|
| 459 |
+
"crew_summary": str(raw_output).strip()
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
except Exception as e:
|
| 463 |
return {"status": "error", "message": str(e)}
|
| 464 |
|
| 465 |
+
|
| 466 |
+
# Run crew
|
| 467 |
+
if __name__ == "__main__":
|
| 468 |
+
print("Starting Alzheimer's Detection Crew with Llama3.1:8b...")
|
| 469 |
+
result = crew.kickoff()
|
| 470 |
+
print("\n=== FINAL REPORT ===\n")
|
| 471 |
+
print(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -13,4 +13,5 @@ spacy
|
|
| 13 |
openai-whisper
|
| 14 |
en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.7.1/en_core_web_sm-3.7.1-py3-none-any.whl
|
| 15 |
shap
|
| 16 |
-
xgboost==3.0.5
|
|
|
|
|
|
| 13 |
openai-whisper
|
| 14 |
en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.7.1/en_core_web_sm-3.7.1-py3-none-any.whl
|
| 15 |
shap
|
| 16 |
+
xgboost==3.0.5
|
| 17 |
+
langchain-huggingface
|