bhavika24 commited on
Commit
0c140fa
Β·
verified Β·
1 Parent(s): 68078e3

Upload 2 files

Browse files
Files changed (2) hide show
  1. UI.py +102 -121
  2. engine.py +30 -13
UI.py CHANGED
@@ -1,121 +1,102 @@
1
- import streamlit as st
2
- from engine import process_question,download_transcript_txt,download_transcript_json
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 Conversation
95
- # =========================
96
- st.divider()
97
- st.subheader("πŸ“₯ Download Conversation")
98
-
99
- # Create 3 columns: spacer | TXT | JSON
100
- col_spacer, col_txt, col_json = st.columns([6, 2, 2])
101
-
102
- with col_txt:
103
- txt = download_transcript_txt()
104
- st.download_button(
105
- label="πŸ“„ TXT",
106
- data=txt,
107
- file_name="chat_transcript.txt",
108
- mime="text/plain",
109
- use_container_width=True
110
- )
111
-
112
- with col_json:
113
- js = download_transcript_json()
114
- st.download_button(
115
- label="🧾 JSON",
116
- data=js,
117
- file_name="chat_transcript.json",
118
- mime="application/json",
119
- use_container_width=True
120
- )
121
-
 
1
+ import streamlit as st
2
+ from engine import process_question,download_transcript_txt,download_transcript_json
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
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
engine.py CHANGED
@@ -7,6 +7,16 @@ from datetime import datetime
7
 
8
  TRANSCRIPT = []
9
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  # =========================
12
  # SETUP
@@ -628,15 +638,6 @@ def build_table_summary(table_name):
628
 
629
  def process_question(question):
630
 
631
- def log_interaction(user_q, sql=None, result=None, error=None):
632
- TRANSCRIPT.append({
633
- "timestamp": datetime.utcnow().isoformat(),
634
- "question": user_q,
635
- "sql": sql,
636
- "result_preview": result[:10] if isinstance(result, list) else result,
637
- "error": error
638
- })
639
-
640
  global LAST_PROMPT_TYPE, LAST_SUGGESTED_DATE
641
 
642
  q = question.strip().lower()
@@ -758,11 +759,27 @@ def process_question(question):
758
  sql = validate_sql(sql)
759
  cols, rows = run_query(sql)
760
 
 
761
  log_interaction(
762
- user_q=question,
763
- sql=sql,
764
- result=rows
765
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
766
 
767
 
768
  # ----------------------------------
 
7
 
8
  TRANSCRIPT = []
9
 
10
+ def log_interaction(user_q, sql=None, result=None, error=None):
11
+ TRANSCRIPT.append({
12
+ "timestamp": datetime.utcnow().isoformat(),
13
+ "question": user_q,
14
+ "sql": sql,
15
+ "result_preview": result[:10] if isinstance(result, list) else result,
16
+ "error": error
17
+ })
18
+
19
+
20
 
21
  # =========================
22
  # SETUP
 
638
 
639
  def process_question(question):
640
 
 
 
 
 
 
 
 
 
 
641
  global LAST_PROMPT_TYPE, LAST_SUGGESTED_DATE
642
 
643
  q = question.strip().lower()
 
759
  sql = validate_sql(sql)
760
  cols, rows = run_query(sql)
761
 
762
+ # βœ… LOG ONCE (THIS FIXES YOUR DOWNLOAD ISSUE)
763
  log_interaction(
764
+ user_q=question,
765
+ sql=sql,
766
+ result=rows
767
+ )
768
+
769
+ if not rows:
770
+ return {
771
+ "status": "ok",
772
+ "message": friendly("No records found."),
773
+ "data": []
774
+ }
775
+
776
+ return {
777
+ "status": "ok",
778
+ "sql": sql,
779
+ "columns": cols,
780
+ "data": rows
781
+ }
782
+
783
 
784
 
785
  # ----------------------------------