Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,11 @@ import json
|
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
import re
|
| 7 |
import plotly.graph_objs as go
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Load environment variables
|
| 10 |
load_dotenv()
|
|
@@ -12,7 +17,7 @@ load_dotenv()
|
|
| 12 |
# Initialize Groq client
|
| 13 |
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
| 14 |
|
| 15 |
-
def parse_non_json_response(text):
|
| 16 |
# Attempt to extract structured information from non-JSON text
|
| 17 |
cancer_types = re.findall(r"(?:cancer type|Cancer Type):\s*(.+?)(?:\n|$)", text, re.IGNORECASE)
|
| 18 |
risk_levels = re.findall(r"(?:risk level|Risk Level):\s*(.+?)(?:\n|$)", text, re.IGNORECASE)
|
|
@@ -39,7 +44,7 @@ def parse_non_json_response(text):
|
|
| 39 |
"disclaimer": disclaimer
|
| 40 |
}
|
| 41 |
|
| 42 |
-
def get_diagnosis(age, gender, symptoms, medical_history):
|
| 43 |
prompt = f"""
|
| 44 |
Given the following patient information, provide a preliminary analysis of potential cancer risks and recommended tests.
|
| 45 |
Give professional medical advice to the best of your ability.
|
|
@@ -72,7 +77,7 @@ def get_diagnosis(age, gender, symptoms, medical_history):
|
|
| 72 |
"content": prompt,
|
| 73 |
}
|
| 74 |
],
|
| 75 |
-
model="llama-3.1-8b-instant",
|
| 76 |
temperature=0.5,
|
| 77 |
max_tokens=1500,
|
| 78 |
)
|
|
@@ -86,9 +91,10 @@ def get_diagnosis(age, gender, symptoms, medical_history):
|
|
| 86 |
|
| 87 |
return response
|
| 88 |
except Exception as e:
|
|
|
|
| 89 |
return {"error": f"An error occurred while communicating with the API: {str(e)}"}
|
| 90 |
|
| 91 |
-
def plot_risk(potential_cancer_types):
|
| 92 |
if not potential_cancer_types:
|
| 93 |
return None
|
| 94 |
|
|
@@ -99,17 +105,24 @@ def plot_risk(potential_cancer_types):
|
|
| 99 |
fig = go.Figure(data=[go.Bar(
|
| 100 |
x=names,
|
| 101 |
y=risk_levels,
|
| 102 |
-
marker_color=colors
|
|
|
|
|
|
|
| 103 |
)])
|
| 104 |
fig.update_layout(
|
| 105 |
title="Cancer Risk Levels",
|
| 106 |
-
yaxis_title="Risk Level
|
| 107 |
-
xaxis_tickangle=-45
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
)
|
| 109 |
|
| 110 |
return fig
|
| 111 |
|
| 112 |
-
def format_output(response):
|
| 113 |
if "error" in response:
|
| 114 |
return f"Error: {response['error']}"
|
| 115 |
|
|
@@ -129,7 +142,7 @@ def format_output(response):
|
|
| 129 |
|
| 130 |
return output
|
| 131 |
|
| 132 |
-
def validate_input(age, gender, symptoms, medical_history):
|
| 133 |
errors = []
|
| 134 |
if not (0 < age < 120):
|
| 135 |
errors.append("Please enter a valid age between 1 and 120.")
|
|
@@ -137,7 +150,7 @@ def validate_input(age, gender, symptoms, medical_history):
|
|
| 137 |
errors.append("Please enter at least one symptom.")
|
| 138 |
return errors
|
| 139 |
|
| 140 |
-
def process_input(age, gender, symptoms, medical_history):
|
| 141 |
errors = validate_input(age, gender, symptoms, medical_history)
|
| 142 |
if errors:
|
| 143 |
return "\n".join(errors), None
|
|
@@ -149,6 +162,9 @@ def process_input(age, gender, symptoms, medical_history):
|
|
| 149 |
|
| 150 |
return output, risk_plot
|
| 151 |
|
|
|
|
|
|
|
|
|
|
| 152 |
# Create Gradio interface
|
| 153 |
iface = gr.Interface(
|
| 154 |
fn=process_input,
|
|
@@ -164,10 +180,19 @@ iface = gr.Interface(
|
|
| 164 |
],
|
| 165 |
title="Vers3Dynamics HealthScan: Personalized Cancer Risk Insights",
|
| 166 |
description="This Groq-powered tool provides a preliminary analysis of potential cancer risks based on the information you provide. It is designed to support early awareness and is not a substitute for professional medical advice, diagnosis, or treatment.",
|
| 167 |
-
article="IMPORTANT: HealthScan AI is for educational and informational purposes only. Always consult with a qualified healthcare provider for medical concerns. The insights provided by this tool should not be used for self-diagnosis or treatment. Early detection and regular check-ups with healthcare professionals are crucial for managing your health effectively."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
)
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
# Launch the app
|
| 171 |
if __name__ == "__main__":
|
| 172 |
-
iface.launch()
|
| 173 |
-
|
|
|
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
import re
|
| 7 |
import plotly.graph_objs as go
|
| 8 |
+
from typing import List, Dict, Any
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
# Set up logging
|
| 12 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 13 |
|
| 14 |
# Load environment variables
|
| 15 |
load_dotenv()
|
|
|
|
| 17 |
# Initialize Groq client
|
| 18 |
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
| 19 |
|
| 20 |
+
def parse_non_json_response(text: str) -> Dict[str, Any]:
|
| 21 |
# Attempt to extract structured information from non-JSON text
|
| 22 |
cancer_types = re.findall(r"(?:cancer type|Cancer Type):\s*(.+?)(?:\n|$)", text, re.IGNORECASE)
|
| 23 |
risk_levels = re.findall(r"(?:risk level|Risk Level):\s*(.+?)(?:\n|$)", text, re.IGNORECASE)
|
|
|
|
| 44 |
"disclaimer": disclaimer
|
| 45 |
}
|
| 46 |
|
| 47 |
+
def get_diagnosis(age: int, gender: str, symptoms: str, medical_history: str) -> Dict[str, Any]:
|
| 48 |
prompt = f"""
|
| 49 |
Given the following patient information, provide a preliminary analysis of potential cancer risks and recommended tests.
|
| 50 |
Give professional medical advice to the best of your ability.
|
|
|
|
| 77 |
"content": prompt,
|
| 78 |
}
|
| 79 |
],
|
| 80 |
+
model="llama-3.1-8b-instant",
|
| 81 |
temperature=0.5,
|
| 82 |
max_tokens=1500,
|
| 83 |
)
|
|
|
|
| 91 |
|
| 92 |
return response
|
| 93 |
except Exception as e:
|
| 94 |
+
logging.error(f"Error in get_diagnosis: {str(e)}")
|
| 95 |
return {"error": f"An error occurred while communicating with the API: {str(e)}"}
|
| 96 |
|
| 97 |
+
def plot_risk(potential_cancer_types: List[Dict[str, str]]) -> go.Figure:
|
| 98 |
if not potential_cancer_types:
|
| 99 |
return None
|
| 100 |
|
|
|
|
| 105 |
fig = go.Figure(data=[go.Bar(
|
| 106 |
x=names,
|
| 107 |
y=risk_levels,
|
| 108 |
+
marker_color=colors,
|
| 109 |
+
text=risk_levels,
|
| 110 |
+
textposition='auto',
|
| 111 |
)])
|
| 112 |
fig.update_layout(
|
| 113 |
title="Cancer Risk Levels",
|
| 114 |
+
yaxis_title="Risk Level",
|
| 115 |
+
xaxis_tickangle=-45,
|
| 116 |
+
yaxis=dict(
|
| 117 |
+
tickmode='array',
|
| 118 |
+
tickvals=[1, 2, 3],
|
| 119 |
+
ticktext=['Low', 'Medium', 'High']
|
| 120 |
+
)
|
| 121 |
)
|
| 122 |
|
| 123 |
return fig
|
| 124 |
|
| 125 |
+
def format_output(response: Dict[str, Any]) -> str:
|
| 126 |
if "error" in response:
|
| 127 |
return f"Error: {response['error']}"
|
| 128 |
|
|
|
|
| 142 |
|
| 143 |
return output
|
| 144 |
|
| 145 |
+
def validate_input(age: int, gender: str, symptoms: str, medical_history: str) -> List[str]:
|
| 146 |
errors = []
|
| 147 |
if not (0 < age < 120):
|
| 148 |
errors.append("Please enter a valid age between 1 and 120.")
|
|
|
|
| 150 |
errors.append("Please enter at least one symptom.")
|
| 151 |
return errors
|
| 152 |
|
| 153 |
+
def process_input(age: int, gender: str, symptoms: str, medical_history: str) -> tuple:
|
| 154 |
errors = validate_input(age, gender, symptoms, medical_history)
|
| 155 |
if errors:
|
| 156 |
return "\n".join(errors), None
|
|
|
|
| 162 |
|
| 163 |
return output, risk_plot
|
| 164 |
|
| 165 |
+
def clear_inputs():
|
| 166 |
+
return gr.Number(value=None), gr.Radio(value=None), gr.Textbox(value=""), gr.Textbox(value="")
|
| 167 |
+
|
| 168 |
# Create Gradio interface
|
| 169 |
iface = gr.Interface(
|
| 170 |
fn=process_input,
|
|
|
|
| 180 |
],
|
| 181 |
title="Vers3Dynamics HealthScan: Personalized Cancer Risk Insights",
|
| 182 |
description="This Groq-powered tool provides a preliminary analysis of potential cancer risks based on the information you provide. It is designed to support early awareness and is not a substitute for professional medical advice, diagnosis, or treatment.",
|
| 183 |
+
article="IMPORTANT: HealthScan AI is for educational and informational purposes only. Always consult with a qualified healthcare provider for medical concerns. The insights provided by this tool should not be used for self-diagnosis or treatment. Early detection and regular check-ups with healthcare professionals are crucial for managing your health effectively.",
|
| 184 |
+
examples=[
|
| 185 |
+
[45, "Male", "Persistent cough, weight loss", "Family history of lung cancer"],
|
| 186 |
+
[35, "Female", "Unexplained fatigue, bruising easily", "No significant medical history"],
|
| 187 |
+
[60, "Other", "Blood in stool, abdominal pain", "History of inflammatory bowel disease"]
|
| 188 |
+
],
|
| 189 |
+
theme=gr.themes.Soft()
|
| 190 |
)
|
| 191 |
|
| 192 |
+
# Add a clear button
|
| 193 |
+
clear_button = gr.Button("Clear Inputs")
|
| 194 |
+
clear_button.click(fn=clear_inputs, inputs=[], outputs=[iface.inputs[0], iface.inputs[1], iface.inputs[2], iface.inputs[3]])
|
| 195 |
+
|
| 196 |
# Launch the app
|
| 197 |
if __name__ == "__main__":
|
| 198 |
+
iface.launch()
|
|
|