Update pages/3_Reports.py
Browse files- pages/3_Reports.py +162 -94
pages/3_Reports.py
CHANGED
@@ -5,143 +5,211 @@ from typing import List, Dict, Any
|
|
5 |
from sqlmodel import select
|
6 |
|
7 |
from config.settings import settings
|
8 |
-
from models import ChatMessage, ChatSession #
|
9 |
from models.db import get_session_context
|
10 |
-
|
|
|
11 |
from services.logger import app_logger
|
12 |
-
from services.metrics import log_report_generated
|
13 |
|
14 |
# --- Authentication Check ---
|
15 |
if not st.session_state.get("authenticated_user_id"):
|
16 |
st.warning("Please log in to access reports.")
|
17 |
-
try:
|
18 |
-
|
|
|
|
|
19 |
st.stop()
|
20 |
|
21 |
authenticated_user_id = st.session_state.get("authenticated_user_id")
|
22 |
authenticated_username = st.session_state.get("authenticated_username", "User")
|
23 |
app_logger.info(f"User '{authenticated_username}' (ID: {authenticated_user_id}) accessed Reports page.")
|
24 |
|
|
|
25 |
st.title("Consultation Reports")
|
26 |
st.markdown("View and download your past consultation sessions.")
|
27 |
-
st.info(settings.MAIN_DISCLAIMER_SHORT)
|
28 |
-
|
29 |
|
|
|
|
|
30 |
def get_user_chat_session_display_data(user_id: int) -> List[Dict[str, Any]]:
|
31 |
-
|
|
|
32 |
session_data_list: List[Dict[str, Any]] = []
|
33 |
try:
|
34 |
-
with get_session_context() as
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
39 |
session_data_list.append({
|
40 |
-
"id":
|
41 |
-
"
|
|
|
|
|
42 |
})
|
43 |
-
app_logger.debug(f"Found {len(session_data_list)} session display entries for user {user_id}")
|
44 |
except Exception as e:
|
45 |
-
app_logger.error(f"Error fetching session display data for user {user_id}: {e}", exc_info=True)
|
46 |
-
st.error("Could not load your chat sessions.")
|
47 |
return session_data_list
|
48 |
|
|
|
49 |
chat_session_display_items = get_user_chat_session_display_data(authenticated_user_id)
|
50 |
|
51 |
if not chat_session_display_items:
|
52 |
-
st.info("You have no past consultation sessions recorded.")
|
53 |
st.stop()
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
|
|
62 |
|
63 |
selected_option_tuple = st.selectbox(
|
64 |
-
"Select a Consultation Session:",
|
|
|
|
|
|
|
|
|
65 |
)
|
66 |
|
|
|
67 |
if selected_option_tuple:
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
if MESSAGES_KEY not in st.session_state:
|
72 |
-
app_logger.info(f"Fetching messages for report, session ID: {selected_session_id}")
|
73 |
-
msg_data_list: List[Dict[str, Any]] = []
|
74 |
-
try:
|
75 |
-
with get_session_context() as db:
|
76 |
-
stmt = select(ChatMessage.role, ChatMessage.content, ChatMessage.timestamp, ChatMessage.tool_name)\
|
77 |
-
.where(ChatMessage.session_id == selected_session_id).order_by(ChatMessage.timestamp)
|
78 |
-
results = db.exec(stmt).all()
|
79 |
-
for row in results:
|
80 |
-
msg_data_list.append({
|
81 |
-
"role": row.role, "content": row.content, "timestamp": row.timestamp,
|
82 |
-
"tool_name": getattr(row, 'tool_name', None)
|
83 |
-
})
|
84 |
-
st.session_state[MESSAGES_KEY] = msg_data_list
|
85 |
-
except Exception as e:
|
86 |
-
app_logger.error(f"Error fetching messages for report (session {selected_session_id}): {e}", exc_info=True)
|
87 |
-
st.error("Could not load messages for this report.")
|
88 |
-
st.session_state[MESSAGES_KEY] = []
|
89 |
-
else:
|
90 |
-
app_logger.debug(f"Using cached messages from session_state for report, session ID: {selected_session_id}")
|
91 |
-
msg_data_list = st.session_state[MESSAGES_KEY]
|
92 |
|
93 |
-
|
|
|
|
|
|
|
94 |
|
95 |
-
if
|
96 |
st.markdown("---")
|
97 |
-
st.subheader(f"Report Preview for Session ID: {
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
|
|
|
|
|
|
|
|
104 |
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
with st.expander("View Chat Transcript", expanded=False):
|
107 |
-
for
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
|
|
|
116 |
st.markdown("---")
|
117 |
try:
|
118 |
-
# Prepare
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
}
|
|
|
|
|
132 |
|
133 |
-
|
134 |
|
135 |
-
|
136 |
-
|
|
|
137 |
st.download_button(
|
138 |
-
label="Download Report as PDF",
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
141 |
)
|
142 |
-
except Exception as
|
143 |
-
app_logger.error(f"Error generating PDF for session {
|
144 |
-
st.error(f"Could not generate PDF report. Error: {type(
|
145 |
-
else:
|
146 |
-
|
147 |
-
else:
|
|
|
|
|
|
|
|
|
|
5 |
from sqlmodel import select
|
6 |
|
7 |
from config.settings import settings
|
8 |
+
from models import ChatMessage, ChatSession # SQLModel classes for DB query
|
9 |
from models.db import get_session_context
|
10 |
+
# Import generate_pdf_report AND MockChatMessage from services.pdf_report
|
11 |
+
from services.pdf_report import generate_pdf_report, MockChatMessage
|
12 |
from services.logger import app_logger
|
13 |
+
from services.metrics import log_report_generated # Assuming this function exists
|
14 |
|
15 |
# --- Authentication Check ---
|
16 |
if not st.session_state.get("authenticated_user_id"):
|
17 |
st.warning("Please log in to access reports.")
|
18 |
+
try:
|
19 |
+
st.switch_page("app.py")
|
20 |
+
except st.errors.StreamlitAPIException:
|
21 |
+
st.info("Please navigate to the main login page manually.")
|
22 |
st.stop()
|
23 |
|
24 |
authenticated_user_id = st.session_state.get("authenticated_user_id")
|
25 |
authenticated_username = st.session_state.get("authenticated_username", "User")
|
26 |
app_logger.info(f"User '{authenticated_username}' (ID: {authenticated_user_id}) accessed Reports page.")
|
27 |
|
28 |
+
# --- Page Title and Info ---
|
29 |
st.title("Consultation Reports")
|
30 |
st.markdown("View and download your past consultation sessions.")
|
31 |
+
st.info(f"{settings.MAIN_DISCLAIMER_SHORT} PDFs are summaries for review.")
|
|
|
32 |
|
33 |
+
# --- Helper Function to Load User's Chat Session Display Data ---
|
34 |
+
# @st.cache_data(ttl=300, show_spinner=False) # Consider caching if fetching is slow and data doesn't change too rapidly
|
35 |
def get_user_chat_session_display_data(user_id: int) -> List[Dict[str, Any]]:
|
36 |
+
"""Fetches essential data for chat sessions (ID, title, start_time, context) as dictionaries."""
|
37 |
+
app_logger.debug(f"ReportsPage: Fetching session display data for user_id: {user_id}")
|
38 |
session_data_list: List[Dict[str, Any]] = []
|
39 |
try:
|
40 |
+
with get_session_context() as db_session:
|
41 |
+
statement = select(
|
42 |
+
ChatSession.id,
|
43 |
+
ChatSession.title,
|
44 |
+
ChatSession.start_time,
|
45 |
+
ChatSession.patient_context_summary # Fetch this as well
|
46 |
+
).where(ChatSession.user_id == user_id).order_by(ChatSession.start_time.desc())
|
47 |
+
|
48 |
+
results = db_session.exec(statement).all() # List of Row objects
|
49 |
+
for row_item in results:
|
50 |
session_data_list.append({
|
51 |
+
"id": row_item.id,
|
52 |
+
"title": row_item.title,
|
53 |
+
"start_time": row_item.start_time, # datetime object
|
54 |
+
"patient_context_summary": row_item.patient_context_summary
|
55 |
})
|
56 |
+
app_logger.debug(f"ReportsPage: Found {len(session_data_list)} session display entries for user {user_id}")
|
57 |
except Exception as e:
|
58 |
+
app_logger.error(f"ReportsPage: Error fetching session display data for user {user_id}: {e}", exc_info=True)
|
59 |
+
st.error("Could not load your chat sessions. Please try again later.")
|
60 |
return session_data_list
|
61 |
|
62 |
+
# Fetch session display data
|
63 |
chat_session_display_items = get_user_chat_session_display_data(authenticated_user_id)
|
64 |
|
65 |
if not chat_session_display_items:
|
66 |
+
st.info("You have no past consultation sessions recorded to display.")
|
67 |
st.stop()
|
68 |
|
69 |
+
# --- UI: Select a Session ---
|
70 |
+
session_options_for_selectbox = []
|
71 |
+
for s_data_item in chat_session_display_items:
|
72 |
+
start_time = s_data_item.get("start_time")
|
73 |
+
start_time_str = start_time.strftime('%Y-%m-%d %H:%M') if start_time else "Date N/A"
|
74 |
+
title_str = s_data_item.get("title") or f"Consultation on {start_time_str}"
|
75 |
+
display_text = f"ID: {s_data_item.get('id')} | Started: {start_time_str} | Title: {title_str}"
|
76 |
+
session_options_for_selectbox.append((display_text, s_data_item.get('id'))) # (Display, Value)
|
77 |
|
78 |
selected_option_tuple = st.selectbox(
|
79 |
+
"Select a Consultation Session:",
|
80 |
+
options=session_options_for_selectbox,
|
81 |
+
format_func=lambda x_tuple: x_tuple[0], # Show only the display string
|
82 |
+
index=0, # Default to the first (most recent) session
|
83 |
+
key="report_session_selector"
|
84 |
)
|
85 |
|
86 |
+
# --- Display Details and PDF Download for Selected Session ---
|
87 |
if selected_option_tuple:
|
88 |
+
selected_session_id_val = selected_option_tuple[1] # The actual session ID
|
89 |
+
app_logger.info(f"ReportsPage: User '{authenticated_username}' selected session ID: {selected_session_id_val} for viewing.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
+
# Find the full data for the selected session from our fetched list of dicts
|
92 |
+
selected_session_dict_data = next(
|
93 |
+
(s_item for s_item in chat_session_display_items if s_item['id'] == selected_session_id_val), None
|
94 |
+
)
|
95 |
|
96 |
+
if selected_session_dict_data:
|
97 |
st.markdown("---")
|
98 |
+
st.subheader(f"Report Preview for Session ID: {selected_session_dict_data['id']}")
|
99 |
+
|
100 |
+
session_start_time = selected_session_dict_data.get("start_time")
|
101 |
+
start_time_display_detail = session_start_time.strftime('%Y-%m-%d %H:%M:%S UTC') if session_start_time else "Not recorded"
|
102 |
+
st.write(f"**Started:** {start_time_display_detail}")
|
103 |
+
st.write(f"**Title:** {selected_session_dict_data.get('title') or 'Untitled Session'}")
|
104 |
+
|
105 |
+
patient_context_from_session = selected_session_dict_data.get("patient_context_summary")
|
106 |
+
if patient_context_from_session:
|
107 |
+
with st.expander("View Patient Context Provided for this Session", expanded=False):
|
108 |
+
st.markdown(patient_context_from_session)
|
109 |
|
110 |
+
# --- Fetch and Display Messages for the Selected Session ---
|
111 |
+
# Store fetched messages in session_state to avoid re-fetching on every interaction within the page
|
112 |
+
MESSAGES_DATA_SESS_KEY = f"report_page_messages_for_session_{selected_session_id_val}"
|
113 |
+
|
114 |
+
if MESSAGES_DATA_SESS_KEY not in st.session_state:
|
115 |
+
app_logger.info(f"ReportsPage: Fetching DB messages for session ID: {selected_session_id_val}")
|
116 |
+
db_messages_as_dicts: List[Dict[str, Any]] = []
|
117 |
+
try:
|
118 |
+
with get_session_context() as db:
|
119 |
+
# Fetch specific columns needed for display and PDF
|
120 |
+
stmt = select(
|
121 |
+
ChatMessage.role, ChatMessage.content, ChatMessage.timestamp, ChatMessage.tool_name
|
122 |
+
).where(ChatMessage.session_id == selected_session_id_val).order_by(ChatMessage.timestamp)
|
123 |
+
|
124 |
+
message_results = db.exec(stmt).all() # List of Row objects
|
125 |
+
for msg_row in message_results:
|
126 |
+
db_messages_as_dicts.append({
|
127 |
+
"role": msg_row.role, "content": msg_row.content,
|
128 |
+
"timestamp": msg_row.timestamp, # datetime object
|
129 |
+
"tool_name": getattr(msg_row, 'tool_name', None)
|
130 |
+
})
|
131 |
+
st.session_state[MESSAGES_DATA_SESS_KEY] = db_messages_as_dicts
|
132 |
+
app_logger.info(f"ReportsPage: Fetched and stored {len(db_messages_as_dicts)} messages for session {selected_session_id_val} in st.session_state.")
|
133 |
+
except Exception as e_msg_fetch:
|
134 |
+
app_logger.error(f"ReportsPage: Error fetching DB messages for session {selected_session_id_val}: {e_msg_fetch}", exc_info=True)
|
135 |
+
st.error("Could not load messages for this session's transcript.")
|
136 |
+
st.session_state[MESSAGES_DATA_SESS_KEY] = [] # Store empty list on error
|
137 |
+
else:
|
138 |
+
app_logger.debug(f"ReportsPage: Using cached messages from st.session_state for session ID: {selected_session_id_val}")
|
139 |
+
|
140 |
+
messages_to_display_and_pdf = st.session_state[MESSAGES_DATA_SESS_KEY]
|
141 |
+
|
142 |
+
if messages_to_display_and_pdf:
|
143 |
with st.expander("View Chat Transcript", expanded=False):
|
144 |
+
for msg_idx, msg_dict_item in enumerate(messages_to_display_and_pdf):
|
145 |
+
msg_role = str(msg_dict_item.get("role", "N/A"))
|
146 |
+
msg_content = str(msg_dict_item.get("content", ""))
|
147 |
+
msg_timestamp_obj = msg_dict_item.get("timestamp")
|
148 |
+
|
149 |
+
# Skip verbose system messages about context in transcript view
|
150 |
+
if msg_role == "system" and "Initial Patient Context Set:" in msg_content:
|
151 |
+
continue
|
152 |
+
|
153 |
+
icon_char = "🧑⚕️" if msg_role == "assistant" else "👤"
|
154 |
+
if msg_role == "tool": icon_char = "🛠️"
|
155 |
+
if msg_role == "system": icon_char = "⚙️"
|
156 |
+
|
157 |
+
timestamp_str_display = msg_timestamp_obj.strftime('%Y-%m-%d %H:%M:%S') if msg_timestamp_obj else "N/A"
|
158 |
+
|
159 |
+
st.markdown(f"**{icon_char} {msg_role.capitalize()}** ({timestamp_str_display})")
|
160 |
+
st.markdown(f"> ```\n{msg_content}\n```") # Using markdown code block for content
|
161 |
+
if msg_idx < len(messages_to_display_and_pdf) - 1:
|
162 |
+
st.markdown("---")
|
163 |
|
164 |
+
# --- PDF Download Button ---
|
165 |
st.markdown("---")
|
166 |
try:
|
167 |
+
# Prepare list of MockChatMessage instances for the PDF generator
|
168 |
+
pdf_report_mock_messages: List[MockChatMessage] = []
|
169 |
+
for msg_d_item in messages_to_display_and_pdf:
|
170 |
+
pdf_report_mock_messages.append(
|
171 |
+
MockChatMessage( # Use the imported MockChatMessage class
|
172 |
+
role=msg_d_item.get("role"),
|
173 |
+
content=msg_d_item.get("content"),
|
174 |
+
timestamp=msg_d_item.get("timestamp"),
|
175 |
+
tool_name=msg_d_item.get("tool_name")
|
176 |
+
)
|
177 |
+
)
|
178 |
+
|
179 |
+
# Prepare the consolidated data dictionary for generate_pdf_report
|
180 |
+
report_data_for_pdf_generation = {
|
181 |
+
"patient_name": authenticated_username, # This is the clinician's username
|
182 |
+
"session_id": selected_session_dict_data['id'],
|
183 |
+
"session_title": selected_session_dict_data.get('title') or 'Untitled Session',
|
184 |
+
"session_start_time": selected_session_dict_data.get('start_time'), # datetime object
|
185 |
+
"patient_context_summary": selected_session_dict_data.get('patient_context_summary', "Not provided."),
|
186 |
+
"messages": pdf_report_mock_messages # List of MockChatMessage instances
|
187 |
}
|
188 |
+
|
189 |
+
app_logger.debug(f"ReportsPage: Data for PDF generation (session {selected_session_id_val}): Keys={list(report_data_for_pdf_generation.keys())}, NumMessages={len(pdf_report_mock_messages)}")
|
190 |
|
191 |
+
pdf_bytes_output = generate_pdf_report(report_data_for_pdf_generation)
|
192 |
|
193 |
+
current_time_filename_str = datetime.now().strftime('%Y%m%d_%H%M%S')
|
194 |
+
pdf_report_filename = f"Consultation_Report_S{selected_session_id_val}_{current_time_filename_str}.pdf"
|
195 |
+
|
196 |
st.download_button(
|
197 |
+
label="Download Report as PDF",
|
198 |
+
data=pdf_bytes_output,
|
199 |
+
file_name=pdf_report_filename,
|
200 |
+
mime="application/pdf",
|
201 |
+
key=f"download_pdf_button_session_{selected_session_id_val}", # Unique key
|
202 |
+
on_click=log_report_generated,
|
203 |
+
args=(authenticated_user_id, selected_session_id_val), # Example args for metrics
|
204 |
+
help="Click to download a PDF summary of this consultation session."
|
205 |
)
|
206 |
+
except Exception as e_pdf_gen:
|
207 |
+
app_logger.error(f"ReportsPage: Error generating PDF for session {selected_session_id_val} (User: '{authenticated_username}'): {e_pdf_gen}", exc_info=True)
|
208 |
+
st.error(f"Could not generate PDF report at this time. Error: {type(e_pdf_gen).__name__}")
|
209 |
+
else:
|
210 |
+
st.info("This session has no messages recorded to include in the report.")
|
211 |
+
else:
|
212 |
+
app_logger.error(f"ReportsPage: Selected session ID {selected_session_id_val} not found in fetched display data for user '{authenticated_username}'. This is unexpected.")
|
213 |
+
st.error("An error occurred: The selected session data could not be retrieved. Please try again or select another session.")
|
214 |
+
else:
|
215 |
+
st.info("Please select a session from the dropdown menu above to view details and generate a report.")
|