bhavika24 commited on
Commit
81dac89
Β·
verified Β·
1 Parent(s): cce2735

Upload 2 files

Browse files
Files changed (1) hide show
  1. UI.py +134 -102
UI.py CHANGED
@@ -1,102 +1,134 @@
1
- import streamlit as st
2
- from engine import process_question,download_transcript_txt
3
-
4
-
5
-
6
- st.set_page_config(page_title="Hospital AI Assistant", layout="wide")
7
-
8
- st.title("πŸ₯ Hospital AI Assistant")
9
- st.caption("Ask questions about patients, conditions, visits, medications, labs")
10
-
11
- # =========================
12
- # Session State
13
- # =========================
14
- if "messages" not in st.session_state:
15
- st.session_state.messages = []
16
-
17
- # =========================
18
- # Show Chat History
19
- # =========================
20
- for msg in st.session_state.messages:
21
- with st.chat_message(msg["role"]):
22
- st.markdown(msg["content"], unsafe_allow_html=True)
23
-
24
- # =========================
25
- # Chat Input
26
- # =========================
27
- user_input = st.chat_input("Ask a question about hospital data...")
28
-
29
- if user_input:
30
- # Show user message
31
- st.session_state.messages.append(
32
- {"role": "user", "content": user_input}
33
- )
34
- with st.chat_message("user"):
35
- st.markdown(user_input)
36
-
37
- # Call backend
38
- with st.spinner("Thinking..."):
39
- try:
40
- result = process_question(user_input)
41
- except Exception as e:
42
- result = {
43
- "status": "error",
44
- "message": str(e)
45
- }
46
-
47
- # =========================
48
- # Build Assistant Reply
49
- # =========================
50
- reply = ""
51
-
52
- if result.get("status") == "ok":
53
-
54
- # Message (important for time-based or empty data)
55
- if result.get("message"):
56
- reply += f"❗ {result['message']}\n\n"
57
-
58
- # Time note
59
- if result.get("note"):
60
- reply += f"πŸ•’ {result['note']}\n\n"
61
-
62
- # Table output
63
- if result.get("data"):
64
- columns = result.get("columns", [])
65
- data = result["data"]
66
-
67
- reply += "### Result\n"
68
- reply += "| " + " | ".join(columns) + " |\n"
69
- reply += "| " + " | ".join(["---"] * len(columns)) + " |\n"
70
-
71
- for row in data[:10]:
72
- reply += "| " + " | ".join(str(x) for x in row) + " |\n"
73
-
74
- # SQL (ONLY if present)
75
- if result.get("sql"):
76
- reply += "\n---\n"
77
- reply += "<details><summary><b>Generated SQL</b></summary>\n\n"
78
- reply += f"```sql\n{result['sql']}\n```"
79
- reply += "\n</details>"
80
-
81
- else:
82
- reply = f"❌ {result.get('message', 'Something went wrong')}"
83
-
84
- # =========================
85
- # Display Assistant Message
86
- # =========================
87
- st.session_state.messages.append(
88
- {"role": "assistant", "content": reply}
89
- )
90
-
91
- with st.chat_message("assistant"):
92
- st.markdown(reply, unsafe_allow_html=True)
93
-
94
- # Download button inside chat bubble
95
- st.download_button(
96
- label="⬇️ Download conversation",
97
- data=download_transcript_txt(),
98
- file_name="chat_transcript.txt",
99
- mime="text/plain",
100
- use_container_width=True
101
- )
102
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from engine import process_question
3
+ from datetime import datetime
4
+
5
+ # =========================
6
+ # PAGE SETUP
7
+ # =========================
8
+ st.set_page_config(page_title="Hospital AI Assistant", layout="wide")
9
+
10
+ st.title("πŸ₯ Hospital AI Assistant")
11
+ st.caption("Ask questions about patients, conditions, visits, medications, labs")
12
+
13
+ # =========================
14
+ # SESSION STATE
15
+ # =========================
16
+ if "messages" not in st.session_state:
17
+ st.session_state.messages = []
18
+
19
+ if "transcript" not in st.session_state:
20
+ st.session_state.transcript = []
21
+
22
+ # =========================
23
+ # SHOW CHAT HISTORY
24
+ # =========================
25
+ for msg in st.session_state.messages:
26
+ with st.chat_message(msg["role"]):
27
+ st.markdown(msg["content"], unsafe_allow_html=True)
28
+
29
+ # =========================
30
+ # CHAT INPUT
31
+ # =========================
32
+ user_input = st.chat_input("Ask a question about hospital data...")
33
+
34
+ if user_input:
35
+ # Show user message
36
+ st.session_state.messages.append(
37
+ {"role": "user", "content": user_input}
38
+ )
39
+
40
+ with st.chat_message("user"):
41
+ st.markdown(user_input)
42
+
43
+ # Call backend
44
+ with st.spinner("Thinking..."):
45
+ try:
46
+ result = process_question(user_input)
47
+
48
+ # βœ… Store transcript safely
49
+ st.session_state.transcript.append({
50
+ "timestamp": datetime.utcnow().isoformat(),
51
+ "question": user_input,
52
+ "sql": result.get("sql"),
53
+ "result_preview": result.get("data", [])[:10],
54
+ "error": result.get("message") if result.get("status") != "ok" else None
55
+ })
56
+
57
+ except Exception as e:
58
+ result = {
59
+ "status": "error",
60
+ "message": str(e)
61
+ }
62
+
63
+ # =========================
64
+ # BUILD RESPONSE
65
+ # =========================
66
+ reply = ""
67
+
68
+ if result.get("status") == "ok":
69
+
70
+ if result.get("message"):
71
+ reply += f"❗ {result['message']}\n\n"
72
+
73
+ if result.get("note"):
74
+ reply += f"πŸ•’ {result['note']}\n\n"
75
+
76
+ if result.get("data"):
77
+ columns = result.get("columns", [])
78
+ data = result["data"]
79
+
80
+ reply += "### Result\n"
81
+ reply += "| " + " | ".join(columns) + " |\n"
82
+ reply += "| " + " | ".join(["---"] * len(columns)) + " |\n"
83
+
84
+ for row in data[:10]:
85
+ reply += "| " + " | ".join(str(x) for x in row) + " |\n"
86
+
87
+ if result.get("sql"):
88
+ reply += "\n---\n"
89
+ reply += "<details><summary><b>Generated SQL</b></summary>\n\n"
90
+ reply += f"```sql\n{result['sql']}\n```"
91
+ reply += "\n</details>"
92
+
93
+ else:
94
+ reply = f"❌ {result.get('message', 'Something went wrong')}"
95
+
96
+ # Show assistant message
97
+ st.session_state.messages.append(
98
+ {"role": "assistant", "content": reply}
99
+ )
100
+
101
+ with st.chat_message("assistant"):
102
+ st.markdown(reply, unsafe_allow_html=True)
103
+
104
+ # =========================
105
+ # DOWNLOAD TRANSCRIPT (BOTTOM ONLY)
106
+ # =========================
107
+ def download_transcript_txt():
108
+ lines = []
109
+ for i, entry in enumerate(st.session_state.transcript, 1):
110
+ lines.append(f"\n--- Query {i} ---")
111
+ lines.append(f"Time: {entry['timestamp']}")
112
+ lines.append(f"Question: {entry['question']}")
113
+
114
+ if entry.get("sql"):
115
+ lines.append(f"SQL: {entry['sql']}")
116
+
117
+ if entry.get("result_preview"):
118
+ lines.append(f"Result Preview: {entry['result_preview']}")
119
+
120
+ if entry.get("error"):
121
+ lines.append(f"Error: {entry['error']}")
122
+
123
+ return "\n".join(lines)
124
+
125
+
126
+ if st.session_state.transcript:
127
+ st.divider()
128
+ st.download_button(
129
+ label="⬇️ Download conversation",
130
+ data=download_transcript_txt(),
131
+ file_name="chat_transcript.txt",
132
+ mime="text/plain",
133
+ use_container_width=True
134
+ )