abidkh commited on
Commit
93054e0
Β·
1 Parent(s): 0ca6919
Files changed (1) hide show
  1. app.py +51 -66
app.py CHANGED
@@ -1,92 +1,77 @@
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.")
 
 
 
1
  import streamlit as st
 
 
 
2
  from datetime import datetime
3
+ from streamlit_cookies_manager import EncryptedCookieManager
4
+ from uuid import uuid4
5
+ import hashlib
6
 
7
+ # Ensure secret is set
8
+ cookies = EncryptedCookieManager(prefix="health_app_", password="your_cookie_secret_here")
 
 
9
  if not cookies.ready():
10
  st.stop()
11
 
12
+ # Generate or retrieve session ID
 
 
 
 
 
 
13
  user_id = cookies.get("user_id")
14
+ if not user_id:
15
+ user_id = hashlib.sha256(str(uuid4()).encode()).hexdigest()
16
+ cookies["user_id"] = user_id
17
+
18
+ # Retrieve saved details
19
  user_name = cookies.get("user_name")
20
+ user_gender = cookies.get("user_gender")
21
  user_age = cookies.get("user_age")
 
22
 
23
+ st.title("🩺 AI Health Assistant")
 
 
24
 
25
+ # User Info Form
26
+ with st.expander("πŸ‘€ User Information", expanded=not all([user_name, user_gender, user_age])):
27
+ name = st.text_input("Name", value=user_name or "")
28
+ gender = st.selectbox("Gender", ["Male", "Female", "Other"], index=["Male", "Female", "Other"].index(user_gender) if user_gender else 0)
29
 
30
+ # Safe age default
31
+ default_age = int(user_age) if user_age and user_age.isdigit() and 1 <= int(user_age) <= 120 else 25
32
+ age = st.number_input("Age", min_value=1, max_value=120, value=default_age)
 
 
33
 
34
+ if st.button("Save Info"):
35
+ cookies["user_name"] = name
36
+ cookies["user_gender"] = gender
37
  cookies["user_age"] = str(age)
38
+ st.success("User info saved!")
39
+
40
+ # Session storage for history
41
+ if "history" not in st.session_state:
42
+ st.session_state.history = []
43
 
44
+ st.markdown("---")
45
+ st.subheader("πŸ“ Describe your symptoms:")
46
+
47
+ user_input = st.text_area("Enter symptoms", height=100)
48
 
49
  if st.button("Diagnose"):
50
+ if not user_input.strip():
51
+ st.warning("Please enter some symptoms.")
52
  else:
53
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
54
+ # Simulated diagnosis result
55
+ diagnosis = f"Based on symptoms, possible cause: 'Common cold' or 'Flu'. Please consult a doctor for confirmation."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Extract keywords (simple placeholder logic)
58
+ keywords = ", ".join(user_input.lower().replace('.', '').replace(',', '').split()[:5])
59
 
 
60
  st.session_state.history.append({
61
+ "timestamp": now,
62
  "symptoms": keywords,
63
  "diagnosis": diagnosis
64
  })
65
 
66
+ st.success("βœ… Diagnosis complete!")
67
+ st.write(diagnosis)
68
+
69
+ st.markdown("---")
70
+ st.subheader("πŸ“š Previous History")
71
+
72
+ if not st.session_state.history:
73
+ st.info("No previous history available.")
74
  else:
75
+ for idx, entry in reversed(list(enumerate(st.session_state.history))):
76
+ with st.expander(f"{entry['timestamp']} | Symptoms: {entry['symptoms']}"):
77
+ st.write(entry["diagnosis"])