Spaces:
Runtime error
Runtime error
updated comments
Browse files
app.py
CHANGED
|
@@ -5,21 +5,21 @@ sys.path.append(os.path.dirname(__file__))
|
|
| 5 |
from crew import run_crewai_lifestyle, run_crewai_audio, run_crewai_news_patient, run_crewai_news_doctor
|
| 6 |
import gradio as gr
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
| 9 |
def assess_lifestyle(docID: str):
|
| 10 |
try:
|
| 11 |
return run_crewai_lifestyle(docID)
|
| 12 |
except Exception as e:
|
| 13 |
return {"status": "error", "message": str(e)}
|
| 14 |
|
| 15 |
-
|
| 16 |
def assess_audio(docID: str):
|
| 17 |
try:
|
| 18 |
return run_crewai_audio(docID)
|
| 19 |
except Exception as e:
|
| 20 |
return {"status": "error", "message": str(e)}
|
| 21 |
|
| 22 |
-
|
| 23 |
def news_patient(count: int = 5):
|
| 24 |
try:
|
| 25 |
return run_crewai_news_patient(count=count)
|
|
@@ -32,11 +32,14 @@ def news_doctor(count: int = 5):
|
|
| 32 |
except Exception as e:
|
| 33 |
return {"status": "error", "message": str(e)}
|
| 34 |
|
|
|
|
| 35 |
with gr.Blocks() as demo:
|
|
|
|
| 36 |
gr.Markdown("# 🧠 NMS Dementia Risk Assessment API - Development Zone")
|
| 37 |
-
|
| 38 |
with gr.Tabs():
|
|
|
|
| 39 |
# Predictions Tab
|
|
|
|
| 40 |
with gr.Tab("Predictions"):
|
| 41 |
gr.Markdown("### 🔮 Risk Assessment (Lifestyle or Audio)")
|
| 42 |
mode_pred = gr.Radio(
|
|
@@ -54,10 +57,11 @@ with gr.Blocks() as demo:
|
|
| 54 |
fn=lambda doc_id, mode: assess_lifestyle(doc_id) if mode == "lifestyle" else assess_audio(doc_id),
|
| 55 |
inputs=[doc_id_pred, mode_pred],
|
| 56 |
outputs=output_pred,
|
| 57 |
-
api_name="assess_risk"
|
| 58 |
)
|
| 59 |
-
|
| 60 |
# News Tab
|
|
|
|
| 61 |
with gr.Tab("News"):
|
| 62 |
gr.Markdown("### 📰 Dementia News for Different Audiences")
|
| 63 |
mode_news = gr.Radio(
|
|
@@ -73,7 +77,7 @@ with gr.Blocks() as demo:
|
|
| 73 |
),
|
| 74 |
inputs=[mode_news, gr.Number(value=5, label="Number of articles", minimum=1, maximum=10)],
|
| 75 |
outputs=output_news,
|
| 76 |
-
api_name="get_news"
|
| 77 |
)
|
| 78 |
|
| 79 |
demo.launch()
|
|
|
|
| 5 |
from crew import run_crewai_lifestyle, run_crewai_audio, run_crewai_news_patient, run_crewai_news_doctor
|
| 6 |
import gradio as gr
|
| 7 |
|
| 8 |
+
# ================================================================
|
| 9 |
+
# Runs the respective crew for each of the 4 functions
|
| 10 |
+
# ================================================================
|
| 11 |
def assess_lifestyle(docID: str):
|
| 12 |
try:
|
| 13 |
return run_crewai_lifestyle(docID)
|
| 14 |
except Exception as e:
|
| 15 |
return {"status": "error", "message": str(e)}
|
| 16 |
|
|
|
|
| 17 |
def assess_audio(docID: str):
|
| 18 |
try:
|
| 19 |
return run_crewai_audio(docID)
|
| 20 |
except Exception as e:
|
| 21 |
return {"status": "error", "message": str(e)}
|
| 22 |
|
|
|
|
| 23 |
def news_patient(count: int = 5):
|
| 24 |
try:
|
| 25 |
return run_crewai_news_patient(count=count)
|
|
|
|
| 32 |
except Exception as e:
|
| 33 |
return {"status": "error", "message": str(e)}
|
| 34 |
|
| 35 |
+
# Creates a GUI using gradio to test the functions above
|
| 36 |
with gr.Blocks() as demo:
|
| 37 |
+
# Page title
|
| 38 |
gr.Markdown("# 🧠 NMS Dementia Risk Assessment API - Development Zone")
|
|
|
|
| 39 |
with gr.Tabs():
|
| 40 |
+
# ================
|
| 41 |
# Predictions Tab
|
| 42 |
+
# ================
|
| 43 |
with gr.Tab("Predictions"):
|
| 44 |
gr.Markdown("### 🔮 Risk Assessment (Lifestyle or Audio)")
|
| 45 |
mode_pred = gr.Radio(
|
|
|
|
| 57 |
fn=lambda doc_id, mode: assess_lifestyle(doc_id) if mode == "lifestyle" else assess_audio(doc_id),
|
| 58 |
inputs=[doc_id_pred, mode_pred],
|
| 59 |
outputs=output_pred,
|
| 60 |
+
api_name="assess_risk" # this is where the api endpoint name is defined
|
| 61 |
)
|
| 62 |
+
# ================
|
| 63 |
# News Tab
|
| 64 |
+
# ================
|
| 65 |
with gr.Tab("News"):
|
| 66 |
gr.Markdown("### 📰 Dementia News for Different Audiences")
|
| 67 |
mode_news = gr.Radio(
|
|
|
|
| 77 |
),
|
| 78 |
inputs=[mode_news, gr.Number(value=5, label="Number of articles", minimum=1, maximum=10)],
|
| 79 |
outputs=output_news,
|
| 80 |
+
api_name="get_news" # this is where the api endpoint name is defined
|
| 81 |
)
|
| 82 |
|
| 83 |
demo.launch()
|
crew.py
CHANGED
|
@@ -13,6 +13,10 @@ import xgboost as xgb
|
|
| 13 |
from xgboost import DMatrix
|
| 14 |
from math import exp
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# Load audio model & metadata
|
| 17 |
audio_model = xgb.Booster()
|
| 18 |
audio_model.load_model('modelAudiov8_ML.json')
|
|
@@ -28,6 +32,11 @@ lifestyle_model.load_model('modelLifestyleV3_ML.json')
|
|
| 28 |
metadata = joblib.load('modelLifestyleV3_metadata.pk1')
|
| 29 |
lifestyle_feature_names = metadata['feature_names']
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
# Load model explainers
|
| 32 |
audio_explainer = shap.TreeExplainer(audio_model)
|
| 33 |
lifestyle_explainer = shap.TreeExplainer(lifestyle_model)
|
|
@@ -38,7 +47,13 @@ placeholder_lifestyle_ID = "umWSG13rLSfHqqJlq1WluPzjLB93"
|
|
| 38 |
llm_predict = LLM(model="huggingface/openai/gpt-oss-120b")
|
| 39 |
llm_news = LLM(model="huggingface/Qwen/Qwen3-4B-Thinking-2507")
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
@tool("calculate_dementia_risk_audio")
|
| 43 |
def calculate_dementia_risk_audio(docID: str) -> Union[str, dict]:
|
| 44 |
"""
|
|
@@ -58,48 +73,49 @@ def calculate_dementia_risk_audio(docID: str) -> Union[str, dict]:
|
|
| 58 |
except json.JSONDecodeError:
|
| 59 |
pass
|
| 60 |
|
|
|
|
| 61 |
audio_data = pull_audio(docID)
|
| 62 |
|
|
|
|
| 63 |
if audio_data is None:
|
| 64 |
error_msg = f"Error: Could not retrieve or process audio data for patient '{docID}'"
|
| 65 |
return {"status": "error", "message": error_msg}
|
| 66 |
|
| 67 |
-
# Extract values
|
| 68 |
age = audio_data.get("age")
|
| 69 |
gender_val = audio_data.get("gender")
|
| 70 |
-
mmse = audio_data.get("mmse") #
|
| 71 |
combined_features = audio_data.get("full_features")
|
| 72 |
|
| 73 |
if combined_features is None:
|
| 74 |
error_msg = f"Error: Feature extraction failed for patient '{docID}'"
|
| 75 |
return {"status": "error", "message": error_msg}
|
| 76 |
|
| 77 |
-
|
|
|
|
| 78 |
audio_array = np.array(combined_features).reshape(1, -1)
|
| 79 |
dmat = DMatrix(audio_array)
|
| 80 |
|
| 81 |
-
# Predict
|
| 82 |
prediction = audio_model.predict(dmat)[0]
|
| 83 |
-
|
|
|
|
| 84 |
try:
|
| 85 |
# If model supports predict_proba (e.g., scikit-learn wrapper), use it
|
| 86 |
proba = audio_model.predict_proba(dmat)[0]
|
| 87 |
confidence = float(max(proba))
|
| 88 |
except AttributeError:
|
| 89 |
-
# Fallback
|
| 90 |
raw_score = audio_model.predict(dmat, output_margin=True)[0]
|
| 91 |
# Convert to probability via sigmoid (for binary classification)
|
| 92 |
proba_pos = 1 / (1 + exp(-raw_score))
|
| 93 |
confidence = proba_pos if prediction == 1 else (1 - proba_pos)
|
| 94 |
|
| 95 |
-
|
| 96 |
-
# prediction = audio_model.predict(combined_features.reshape(1, -1))[0]
|
| 97 |
-
# probability = audio_model.predict_proba(combined_features.reshape(1, -1))[0]
|
| 98 |
-
# confidence = float(max(probability))
|
| 99 |
risk_level = "High" if prediction == 1 else "Low"
|
| 100 |
gender_str = "Male" if gender_val == 1 else "Female"
|
| 101 |
|
| 102 |
-
# Structured output
|
| 103 |
result_dict = {
|
| 104 |
"risk_level": risk_level,
|
| 105 |
"prediction": int(prediction),
|
|
@@ -111,19 +127,24 @@ def calculate_dementia_risk_audio(docID: str) -> Union[str, dict]:
|
|
| 111 |
|
| 112 |
return {"status": "success", **result_dict}
|
| 113 |
|
|
|
|
| 114 |
except Exception as e:
|
| 115 |
error_msg = f"Error calculating audio-based risk: {str(e)}"
|
| 116 |
return {"status": "error", "message": error_msg}
|
| 117 |
|
|
|
|
| 118 |
@tool("explain_dementia_risk_audio")
|
| 119 |
def explain_dementia_risk_audio(docID: str) -> str:
|
| 120 |
"""Provides SHAP-based explanation for audio risk prediction."""
|
| 121 |
try:
|
| 122 |
-
#
|
| 123 |
audio_data = pull_audio(docID)
|
|
|
|
|
|
|
| 124 |
if audio_data is None:
|
| 125 |
return f"Error: No data for {docID}"
|
| 126 |
|
|
|
|
| 127 |
features = audio_data["full_features"]
|
| 128 |
feature_names = audio_feature_names
|
| 129 |
|
|
|
|
| 13 |
from xgboost import DMatrix
|
| 14 |
from math import exp
|
| 15 |
|
| 16 |
+
# ================================================================
|
| 17 |
+
# Loading in the prediction models
|
| 18 |
+
# ================================================================
|
| 19 |
+
|
| 20 |
# Load audio model & metadata
|
| 21 |
audio_model = xgb.Booster()
|
| 22 |
audio_model.load_model('modelAudiov8_ML.json')
|
|
|
|
| 32 |
metadata = joblib.load('modelLifestyleV3_metadata.pk1')
|
| 33 |
lifestyle_feature_names = metadata['feature_names']
|
| 34 |
|
| 35 |
+
|
| 36 |
+
# ================================================================
|
| 37 |
+
# Loading in the SHAP explainers
|
| 38 |
+
# ================================================================
|
| 39 |
+
|
| 40 |
# Load model explainers
|
| 41 |
audio_explainer = shap.TreeExplainer(audio_model)
|
| 42 |
lifestyle_explainer = shap.TreeExplainer(lifestyle_model)
|
|
|
|
| 47 |
llm_predict = LLM(model="huggingface/openai/gpt-oss-120b")
|
| 48 |
llm_news = LLM(model="huggingface/Qwen/Qwen3-4B-Thinking-2507")
|
| 49 |
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ================================================================
|
| 53 |
+
# Defining the tools for the agents to make use of
|
| 54 |
+
# ================================================================
|
| 55 |
+
|
| 56 |
+
# Prediction tool using the audio model
|
| 57 |
@tool("calculate_dementia_risk_audio")
|
| 58 |
def calculate_dementia_risk_audio(docID: str) -> Union[str, dict]:
|
| 59 |
"""
|
|
|
|
| 73 |
except json.JSONDecodeError:
|
| 74 |
pass
|
| 75 |
|
| 76 |
+
# Pulls data from firebase using the patientID (docID)
|
| 77 |
audio_data = pull_audio(docID)
|
| 78 |
|
| 79 |
+
# Error handling for missing patient entry
|
| 80 |
if audio_data is None:
|
| 81 |
error_msg = f"Error: Could not retrieve or process audio data for patient '{docID}'"
|
| 82 |
return {"status": "error", "message": error_msg}
|
| 83 |
|
| 84 |
+
# Extract values
|
| 85 |
age = audio_data.get("age")
|
| 86 |
gender_val = audio_data.get("gender")
|
| 87 |
+
mmse = audio_data.get("mmse") # This feature was defined as optional during the audio model training
|
| 88 |
combined_features = audio_data.get("full_features")
|
| 89 |
|
| 90 |
if combined_features is None:
|
| 91 |
error_msg = f"Error: Feature extraction failed for patient '{docID}'"
|
| 92 |
return {"status": "error", "message": error_msg}
|
| 93 |
|
| 94 |
+
|
| 95 |
+
# Convert the numpy array to DMatrix for compatability
|
| 96 |
audio_array = np.array(combined_features).reshape(1, -1)
|
| 97 |
dmat = DMatrix(audio_array)
|
| 98 |
|
| 99 |
+
# Predict using the patient data, returns a 1 or 0
|
| 100 |
prediction = audio_model.predict(dmat)[0]
|
| 101 |
+
|
| 102 |
+
# Getting the confidence (probability) of the prediction
|
| 103 |
try:
|
| 104 |
# If model supports predict_proba (e.g., scikit-learn wrapper), use it
|
| 105 |
proba = audio_model.predict_proba(dmat)[0]
|
| 106 |
confidence = float(max(proba))
|
| 107 |
except AttributeError:
|
| 108 |
+
# Fallback, use raw prediction scores (if binary classification)
|
| 109 |
raw_score = audio_model.predict(dmat, output_margin=True)[0]
|
| 110 |
# Convert to probability via sigmoid (for binary classification)
|
| 111 |
proba_pos = 1 / (1 + exp(-raw_score))
|
| 112 |
confidence = proba_pos if prediction == 1 else (1 - proba_pos)
|
| 113 |
|
| 114 |
+
# Setting the risk level
|
|
|
|
|
|
|
|
|
|
| 115 |
risk_level = "High" if prediction == 1 else "Low"
|
| 116 |
gender_str = "Male" if gender_val == 1 else "Female"
|
| 117 |
|
| 118 |
+
# Structured output for easy parsing
|
| 119 |
result_dict = {
|
| 120 |
"risk_level": risk_level,
|
| 121 |
"prediction": int(prediction),
|
|
|
|
| 127 |
|
| 128 |
return {"status": "success", **result_dict}
|
| 129 |
|
| 130 |
+
# Handles failure to predict
|
| 131 |
except Exception as e:
|
| 132 |
error_msg = f"Error calculating audio-based risk: {str(e)}"
|
| 133 |
return {"status": "error", "message": error_msg}
|
| 134 |
|
| 135 |
+
# Prediction tool using the lifestyle model
|
| 136 |
@tool("explain_dementia_risk_audio")
|
| 137 |
def explain_dementia_risk_audio(docID: str) -> str:
|
| 138 |
"""Provides SHAP-based explanation for audio risk prediction."""
|
| 139 |
try:
|
| 140 |
+
# Pulls data from firebase using the patientID (docID)
|
| 141 |
audio_data = pull_audio(docID)
|
| 142 |
+
|
| 143 |
+
# Handles missing patient entry
|
| 144 |
if audio_data is None:
|
| 145 |
return f"Error: No data for {docID}"
|
| 146 |
|
| 147 |
+
# Get the patients data
|
| 148 |
features = audio_data["full_features"]
|
| 149 |
feature_names = audio_feature_names
|
| 150 |
|