...
Browse files
app.py
CHANGED
@@ -1,152 +1,92 @@
|
|
1 |
import streamlit as st
|
|
|
2 |
import uuid
|
|
|
3 |
from datetime import datetime
|
4 |
-
from
|
5 |
-
|
6 |
-
from streamlit_cookies_manager import EncryptedCookieManager
|
7 |
|
8 |
-
#
|
9 |
cookies = EncryptedCookieManager(
|
10 |
-
prefix="
|
11 |
-
password="replace_this_with_a_random_very_long_key"
|
12 |
)
|
13 |
if not cookies.ready():
|
14 |
st.stop()
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
cookies["user_id"] = user_id
|
23 |
-
st.session_state.user_id = user_id
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
st.session_state[key] = cookies.get(key) or default
|
30 |
|
31 |
-
#
|
32 |
if "history" not in st.session_state:
|
33 |
-
st.session_state.history =
|
34 |
-
|
35 |
-
#
|
36 |
-
st.
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
st.
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
st.
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
# --- MAIN FUNCTIONALITY ---
|
60 |
-
mode = st.radio("Select mode", ["Symptom Checker", "Health Q&A"])
|
61 |
-
|
62 |
-
def extract_keywords(symptoms: str) -> str:
|
63 |
-
prompt = f"Extract the main symptoms from this text as comma-separated keywords: {symptoms}"
|
64 |
-
keywords = query_groq(prompt)
|
65 |
-
return keywords.strip().strip(".,").lower()
|
66 |
-
|
67 |
-
if mode == "Symptom Checker":
|
68 |
-
symptoms = st.text_area("Enter your symptoms", placeholder="e.g., headache, fever, sore throat")
|
69 |
-
if st.button("Analyze Symptoms"):
|
70 |
-
dt = datetime.now().strftime("%Y-%m-%d %H:%M")
|
71 |
-
keywords = extract_keywords(symptoms)
|
72 |
-
prompt = (
|
73 |
-
f"A user named {st.session_state.user_name} (Age: {st.session_state.user_age}, "
|
74 |
-
f"Gender: {st.session_state.user_gender}) reports: {symptoms}. "
|
75 |
-
"List possible causes and precautions."
|
76 |
-
)
|
77 |
-
response = query_groq(prompt)
|
78 |
-
st.success(response)
|
79 |
-
|
80 |
-
entry = {
|
81 |
-
"mode": "Symptom Checker",
|
82 |
-
"datetime": dt,
|
83 |
-
"query": symptoms,
|
84 |
-
"keywords": keywords,
|
85 |
-
"response": response
|
86 |
-
}
|
87 |
-
save_interaction(st.session_state.user_id, entry)
|
88 |
-
st.session_state.history.append(entry)
|
89 |
-
|
90 |
-
elif mode == "Health Q&A":
|
91 |
-
question = st.text_input("Ask your health question")
|
92 |
-
if st.button("Get Answer"):
|
93 |
-
dt = datetime.now().strftime("%Y-%m-%d %H:%M")
|
94 |
prompt = (
|
95 |
-
f"
|
96 |
-
f"
|
|
|
97 |
)
|
98 |
-
response = query_groq(prompt)
|
99 |
-
st.success(response)
|
100 |
-
|
101 |
-
entry = {
|
102 |
-
"mode": "Health Q&A",
|
103 |
-
"datetime": dt,
|
104 |
-
"query": question,
|
105 |
-
"keywords": "",
|
106 |
-
"response": response
|
107 |
-
}
|
108 |
-
save_interaction(st.session_state.user_id, entry)
|
109 |
-
st.session_state.history.append(entry)
|
110 |
|
111 |
-
#
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
lines.append(f"Keywords: {entry['keywords']}")
|
120 |
-
else:
|
121 |
-
lines.append(f"Question: {entry['query']}")
|
122 |
-
lines.append("Response:")
|
123 |
-
lines.append(entry["response"])
|
124 |
-
lines.append("-" * 50)
|
125 |
-
return "\n".join(lines)
|
126 |
-
|
127 |
-
with st.expander("π Show Previous Interactions"):
|
128 |
-
if st.session_state.history:
|
129 |
-
for entry in st.session_state.history[::-1]:
|
130 |
-
if entry["mode"] == "Symptom Checker":
|
131 |
-
title = f"{entry['datetime']} | Symptoms: {entry['keywords']}"
|
132 |
-
else:
|
133 |
-
title = f"{entry['datetime']} | Question: {entry['query'][:50]}"
|
134 |
-
with st.expander(title):
|
135 |
-
st.markdown("**Diagnosis / Answer:**")
|
136 |
-
st.write(entry["response"])
|
137 |
-
|
138 |
-
st.download_button(
|
139 |
-
label="π Download My History",
|
140 |
-
data=format_history_txt(st.session_state.history),
|
141 |
-
file_name="my_health_history.txt",
|
142 |
-
mime="text/plain"
|
143 |
)
|
144 |
-
else:
|
145 |
-
st.info("No history found.")
|
146 |
|
147 |
-
|
148 |
-
st.markdown("
|
149 |
-
st.
|
150 |
-
|
151 |
-
|
152 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
from streamlit_cookies_manager import EncryptedCookieManager
|
3 |
import uuid
|
4 |
+
import json
|
5 |
from datetime import datetime
|
6 |
+
from groq import Groq # Ensure groq package is installed and configured
|
7 |
+
import os
|
|
|
8 |
|
9 |
+
# Initialize cookies
|
10 |
cookies = EncryptedCookieManager(
|
11 |
+
prefix="health_app", password=os.getenv("COOKIE_SECRET", "my_secret_password")
|
|
|
12 |
)
|
13 |
if not cookies.ready():
|
14 |
st.stop()
|
15 |
|
16 |
+
# Session ID from cookie
|
17 |
+
if not cookies.get("user_id"):
|
18 |
+
cookies["user_id"] = str(uuid.uuid4())
|
19 |
+
cookies["user_name"] = ""
|
20 |
+
cookies["user_age"] = "0"
|
21 |
+
cookies["user_sex"] = ""
|
|
|
|
|
22 |
|
23 |
+
user_id = cookies.get("user_id")
|
24 |
+
user_name = cookies.get("user_name")
|
25 |
+
user_age = cookies.get("user_age")
|
26 |
+
user_sex = cookies.get("user_sex")
|
|
|
27 |
|
28 |
+
# Initialize session history in session state
|
29 |
if "history" not in st.session_state:
|
30 |
+
st.session_state.history = []
|
31 |
+
|
32 |
+
# Page title
|
33 |
+
st.title("Health Assistant")
|
34 |
+
|
35 |
+
# Collect user info if not already stored
|
36 |
+
with st.expander("π€ Personal Information", expanded=(not user_name or not user_age or not user_sex)):
|
37 |
+
name = st.text_input("Name", value=user_name)
|
38 |
+
age = st.number_input("Age", min_value=1, max_value=120, value=int(user_age) if user_age else 25)
|
39 |
+
sex = st.selectbox("Sex", ["Male", "Female", "Other"], index=["Male", "Female", "Other"].index(user_sex or "Male"))
|
40 |
+
|
41 |
+
if st.button("Save Information"):
|
42 |
+
cookies["user_name"] = str(name)
|
43 |
+
cookies["user_age"] = str(age)
|
44 |
+
cookies["user_sex"] = str(sex)
|
45 |
+
st.success("Information saved. You can now enter your symptoms.")
|
46 |
+
|
47 |
+
# User input
|
48 |
+
st.subheader("π Describe Your Symptoms")
|
49 |
+
symptoms = st.text_area("Enter your symptoms (e.g., fever, sore throat, headache):")
|
50 |
+
|
51 |
+
if st.button("Diagnose"):
|
52 |
+
if not symptoms:
|
53 |
+
st.warning("Please enter your symptoms.")
|
54 |
+
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
prompt = (
|
56 |
+
f"You are a medical assistant. A user named {name}, age {age}, sex {sex} reports the following symptoms:\n"
|
57 |
+
f"{symptoms}\n"
|
58 |
+
f"Please provide:\n1. Possible causes\n2. Recommended precautions."
|
59 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
+
# Call Groq API (assumes GROQ_API_KEY and model is correctly configured)
|
62 |
+
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
63 |
+
response = client.chat.completions.create(
|
64 |
+
model="llama3-70b-8192",
|
65 |
+
messages=[
|
66 |
+
{"role": "system", "content": "You are a helpful medical assistant."},
|
67 |
+
{"role": "user", "content": prompt}
|
68 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
)
|
|
|
|
|
70 |
|
71 |
+
diagnosis = response.choices[0].message.content.strip()
|
72 |
+
st.markdown("### π§Ύ Diagnosis")
|
73 |
+
st.write(diagnosis)
|
74 |
+
|
75 |
+
# Extract keywords (basic method)
|
76 |
+
keywords = ", ".join(sym.strip() for sym in symptoms.split(",")[:4])
|
77 |
+
|
78 |
+
# Save to session history
|
79 |
+
st.session_state.history.append({
|
80 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
81 |
+
"symptoms": keywords,
|
82 |
+
"diagnosis": diagnosis
|
83 |
+
})
|
84 |
+
|
85 |
+
# Display history
|
86 |
+
if st.session_state.history:
|
87 |
+
st.markdown("### π Previous History")
|
88 |
+
for i, item in reversed(list(enumerate(st.session_state.history))):
|
89 |
+
with st.expander(f"{item['timestamp']} | Symptoms: {item['symptoms']}"):
|
90 |
+
st.write(item["diagnosis"])
|
91 |
+
else:
|
92 |
+
st.info("No previous history found.")
|