abidkh commited on
Commit
4b02284
·
1 Parent(s): c084f11

Enabled for local deployment.

Browse files
Files changed (6) hide show
  1. .gitignore +10 -0
  2. README.md +1 -1
  3. app.py +7 -3
  4. database.py +71 -43
  5. requirements.txt +4 -3
  6. user_management.py +13 -13
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ .env.local
3
+ __pycache__/
4
+ *.pyc
5
+ *.pyo
6
+ *.pyd
7
+ .Python
8
+ env/
9
+ venv/
10
+ *.log
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 🏥
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: streamlit
7
- sdk_version: "1.38.0"
8
  app_file: app.py
9
  pinned: false
10
  ---
 
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: streamlit
7
+ sdk_version: "1.44.1"
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py CHANGED
@@ -1,9 +1,13 @@
 
 
1
  import streamlit as st
2
  from groq import Groq
3
- import os
4
  from database import get_symptoms, get_disease_info
5
  from user_management import show_user_management, save_history_if_logged_in
6
 
 
 
 
7
  # Initialize Groq client
8
  groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
9
 
@@ -63,7 +67,7 @@ if st.button("Ask"):
63
  max_tokens=500
64
  )
65
  st.write("**Response**:")
66
- st.write(response.choices[0].message.content)
67
 
68
  # Save to history if user is logged in
69
  if st.session_state.get("user_id"):
@@ -75,4 +79,4 @@ if st.button("Ask"):
75
 
76
  # Footer
77
  st.markdown("---")
78
- st.write("Developed by xAI. Powered by Groq and Neon.")
 
1
+ from dotenv import load_dotenv
2
+ import os
3
  import streamlit as st
4
  from groq import Groq
 
5
  from database import get_symptoms, get_disease_info
6
  from user_management import show_user_management, save_history_if_logged_in
7
 
8
+ # Load environment variables from .env.local
9
+ load_dotenv(dotenv_path=".env.local")
10
+
11
  # Initialize Groq client
12
  groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
13
 
 
67
  max_tokens=500
68
  )
69
  st.write("**Response**:")
70
+ st.markdown(response.choices[0].message.content)
71
 
72
  # Save to history if user is logged in
73
  if st.session_state.get("user_id"):
 
79
 
80
  # Footer
81
  st.markdown("---")
82
+ st.write("Developed by Pacman. Powered by AI.")
database.py CHANGED
@@ -1,67 +1,90 @@
 
1
  import os
2
  import psycopg2
3
  from contextlib import contextmanager
4
  from typing import List, Tuple, Optional
5
 
 
 
 
6
  # Database connection string from environment variable
7
  DB_CONNECT = os.getenv("DB_CONNECT")
8
 
 
 
 
9
  @contextmanager
10
  def get_db_connection():
11
  """Context manager for database connections."""
12
- conn = psycopg2.connect(DB_CONNECT)
13
  try:
 
14
  yield conn
 
 
15
  finally:
16
- conn.close()
 
17
 
18
  def get_symptoms() -> List[str]:
19
  """Fetch all symptom names from the database."""
20
- with get_db_connection() as conn:
21
- with conn.cursor() as cur:
22
- cur.execute("SELECT symptom_name FROM mb_symptoms ORDER BY symptom_name")
23
- return [row[0] for row in cur.fetchall()]
 
 
 
24
 
25
  def get_disease_info(symptoms: List[str]) -> List[Tuple[str, str, List[str]]]:
26
  """Get possible diseases and precautions based on symptoms."""
27
- with get_db_connection() as conn:
28
- with conn.cursor() as cur:
29
- # Calculate severity score and match diseases
30
- placeholders = ','.join(['%s'] * len(symptoms))
31
- query = """
32
- SELECT d.disease_name, d.description,
33
- ARRAY[COALESCE(d.precaution_1, ''), COALESCE(d.precaution_2, ''),
34
- COALESCE(d.precaution_3, ''), COALESCE(d.precaution_4, '')] as precautions
35
- FROM mb_diseases d
36
- JOIN mb_disease_symptoms ds ON d.disease_id = ds.disease_id
37
- JOIN mb_symptoms s ON ds.symptom_id = s.symptom_id
38
- WHERE s.symptom_name IN (%s)
39
- GROUP BY d.disease_id, d.disease_name, d.description, d.precaution_1, d.precaution_2, d.precaution_3, d.precaution_4
40
- ORDER BY COUNT(*) DESC
41
- LIMIT 5
42
- """ % placeholders
43
- cur.execute(query, symptoms)
44
- return cur.fetchall()
 
 
 
45
 
46
  def save_user_history(user_id: str, symptoms: str, predicted_diseases: str) -> None:
47
  """Save user symptom history to database."""
48
- with get_db_connection() as conn:
49
- with conn.cursor() as cur:
50
- cur.execute(
51
- "INSERT INTO mb_history (user_id, symptoms, predicted_diseases) VALUES (%s, %s, %s)",
52
- (user_id, symptoms, predicted_diseases)
53
- )
54
- conn.commit()
 
 
 
55
 
56
  def get_user_history(user_id: str) -> List[Tuple[int, str, str, str]]:
57
  """Retrieve user history from database."""
58
- with get_db_connection() as conn:
59
- with conn.cursor() as cur:
60
- cur.execute(
61
- "SELECT history_id, symptoms, predicted_diseases, query_timestamp FROM mb_history WHERE user_id = %s ORDER BY query_timestamp DESC",
62
- (user_id,)
63
- )
64
- return cur.fetchall()
 
 
 
65
 
66
  def register_user(user_id: str, dob: str, email: Optional[str]) -> bool:
67
  """Register a new user."""
@@ -70,16 +93,21 @@ def register_user(user_id: str, dob: str, email: Optional[str]) -> bool:
70
  with conn.cursor() as cur:
71
  cur.execute(
72
  "INSERT INTO mb_users (user_id, date_of_birth, email) VALUES (%s, %s, %s)",
73
- (user_id, dob, email)
74
  )
75
  conn.commit()
76
  return True
77
  except psycopg2.IntegrityError:
78
  return False
 
 
79
 
80
  def user_exists(user_id: str) -> bool:
81
  """Check if user_id already exists."""
82
- with get_db_connection() as conn:
83
- with conn.cursor() as cur:
84
- cur.execute("SELECT 1 FROM mb_users WHERE user_id = %s", (user_id,))
85
- return cur.fetchone() is not None
 
 
 
 
1
+ from dotenv import load_dotenv
2
  import os
3
  import psycopg2
4
  from contextlib import contextmanager
5
  from typing import List, Tuple, Optional
6
 
7
+ # Load environment variables from .env.local
8
+ load_dotenv(dotenv_path=".env.local")
9
+
10
  # Database connection string from environment variable
11
  DB_CONNECT = os.getenv("DB_CONNECT")
12
 
13
+ if not DB_CONNECT:
14
+ raise ValueError("DB_CONNECT environment variable not set. Please check .env.local.")
15
+
16
  @contextmanager
17
  def get_db_connection():
18
  """Context manager for database connections."""
19
+ conn = None
20
  try:
21
+ conn = psycopg2.connect(DB_CONNECT)
22
  yield conn
23
+ except psycopg2.Error as e:
24
+ raise Exception(f"Database connection failed: {str(e)}")
25
  finally:
26
+ if conn:
27
+ conn.close()
28
 
29
  def get_symptoms() -> List[str]:
30
  """Fetch all symptom names from the database."""
31
+ try:
32
+ with get_db_connection() as conn:
33
+ with conn.cursor() as cur:
34
+ cur.execute("SELECT symptom_name FROM mb_symptoms ORDER BY symptom_name")
35
+ return [row[0] for row in cur.fetchall()]
36
+ except Exception as e:
37
+ raise Exception(f"Error fetching symptoms: {str(e)}")
38
 
39
  def get_disease_info(symptoms: List[str]) -> List[Tuple[str, str, List[str]]]:
40
  """Get possible diseases and precautions based on symptoms."""
41
+ try:
42
+ with get_db_connection() as conn:
43
+ with conn.cursor() as cur:
44
+ # Calculate severity score and match diseases
45
+ placeholders = ','.join(['%s'] * len(symptoms))
46
+ query = """
47
+ SELECT d.disease_name, d.description,
48
+ ARRAY[COALESCE(d.precaution_1, ''), COALESCE(d.precaution_2, ''),
49
+ COALESCE(d.precaution_3, ''), COALESCE(d.precaution_4, '')] as precautions
50
+ FROM mb_diseases d
51
+ JOIN mb_disease_symptoms ds ON d.disease_id = ds.disease_id
52
+ JOIN mb_symptoms s ON ds.symptom_id = s.symptom_id
53
+ WHERE s.symptom_name IN (%s)
54
+ GROUP BY d.disease_id, d.disease_name, d.description, d.precaution_1, d.precaution_2, d.precaution_3, d.precaution_4
55
+ ORDER BY COUNT(*) DESC
56
+ LIMIT 5
57
+ """ % placeholders
58
+ cur.execute(query, symptoms)
59
+ return cur.fetchall()
60
+ except Exception as e:
61
+ raise Exception(f"Error fetching disease info: {str(e)}")
62
 
63
  def save_user_history(user_id: str, symptoms: str, predicted_diseases: str) -> None:
64
  """Save user symptom history to database."""
65
+ try:
66
+ with get_db_connection() as conn:
67
+ with conn.cursor() as cur:
68
+ cur.execute(
69
+ "INSERT INTO mb_history (user_id, symptoms, predicted_diseases) VALUES (%s, %s, %s)",
70
+ (user_id, symptoms, predicted_diseases)
71
+ )
72
+ conn.commit()
73
+ except Exception as e:
74
+ raise Exception(f"Error saving user history: {str(e)}")
75
 
76
  def get_user_history(user_id: str) -> List[Tuple[int, str, str, str]]:
77
  """Retrieve user history from database."""
78
+ try:
79
+ with get_db_connection() as conn:
80
+ with conn.cursor() as cur:
81
+ cur.execute(
82
+ "SELECT history_id, symptoms, predicted_diseases, query_timestamp FROM mb_history WHERE user_id = %s ORDER BY query_timestamp DESC",
83
+ (user_id,)
84
+ )
85
+ return cur.fetchall()
86
+ except Exception as e:
87
+ raise Exception(f"Error fetching user history: {str(e)}")
88
 
89
  def register_user(user_id: str, dob: str, email: Optional[str]) -> bool:
90
  """Register a new user."""
 
93
  with conn.cursor() as cur:
94
  cur.execute(
95
  "INSERT INTO mb_users (user_id, date_of_birth, email) VALUES (%s, %s, %s)",
96
+ (user_id, dob, email or None)
97
  )
98
  conn.commit()
99
  return True
100
  except psycopg2.IntegrityError:
101
  return False
102
+ except Exception as e:
103
+ raise Exception(f"Error registering user: {str(e)}")
104
 
105
  def user_exists(user_id: str) -> bool:
106
  """Check if user_id already exists."""
107
+ try:
108
+ with get_db_connection() as conn:
109
+ with conn.cursor() as cur:
110
+ cur.execute("SELECT 1 FROM mb_users WHERE user_id = %s", (user_id,))
111
+ return cur.fetchone() is not None
112
+ except Exception as e:
113
+ raise Exception(f"Error checking user existence: {str(e)}")
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
- streamlit==1.38.0
2
- groq==0.11.0
3
- psycopg2-binary==2.9.9
 
 
1
+ streamlit==1.44.1
2
+ groq
3
+ psycopg2-binary
4
+ python-dotenv
user_management.py CHANGED
@@ -36,22 +36,22 @@ def show_user_management():
36
  if not user_id:
37
  st.sidebar.error("User ID is required.")
38
  elif user_exists(user_id):
39
- st.sidebar.error("User ID already taken. Please choose another.")
40
  else:
41
- if register_user(user_id, dob, email or None):
42
- st.session_state.user_id = user_id
43
- st.sidebar.success("Registered successfully!")
44
- else:
45
- st.sidebar.error("Registration failed. Please try again.")
46
-
47
  if st.sidebar.button("Login"):
48
- if user_exists(user_id):
49
  st.session_state.user_id = user_id
50
  st.sidebar.success("Logged in successfully!")
51
  else:
52
- st.sidebar.error("User ID not found. Please register or try another ID.")
53
 
54
- def save_history_if_logged_in(symptoms: str, predicted_diseases: str):
55
- """Save history if user is logged in."""
56
- if st.session_state.get("user_id"):
57
- save_user_history(st.session_state.user_id, symptoms, predicted_diseases)
 
 
 
 
36
  if not user_id:
37
  st.sidebar.error("User ID is required.")
38
  elif user_exists(user_id):
39
+ st.sidebar.error("User ID already exists. Please choose another.")
40
  else:
41
+ if register_user(user_id, dob, email st.session_state.user_id = user_id
42
+ st.sidebar.success("Registered successfully!")
43
+
 
 
 
44
  if st.sidebar.button("Login"):
45
+ if user_exists(user_id,):
46
  st.session_state.user_id = user_id
47
  st.sidebar.success("Logged in successfully!")
48
  else:
49
+ st.sidebar.error("User ID not found. Please register or try again.")
50
 
51
+ def save_history_if_logged_in(user_id: str, symptoms: str, predicted_diseases: str):
52
+ """Save user history if user is logged in."""
53
+ try:
54
+ if user_id.get("user_id"):
55
+ save_user_history(st.session_state.user_id, symptoms, predicted_diseases)
56
+ except Exception as e:
57
+ raise Exception(f"Error saving user history: {str(e)}")