Update pages/3_Reports.py
Browse files- pages/3_Reports.py +99 -69
pages/3_Reports.py
CHANGED
@@ -2,120 +2,150 @@
|
|
2 |
import streamlit as st
|
3 |
from datetime import datetime
|
4 |
from typing import List
|
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 |
from services.pdf_report import generate_pdf_report
|
11 |
from services.logger import app_logger
|
12 |
-
from services.metrics import log_report_generated
|
13 |
|
14 |
-
# ---
|
|
|
|
|
|
|
15 |
if not st.session_state.get("authenticated_user_id"):
|
16 |
st.warning("Please log in to access reports.")
|
17 |
try:
|
18 |
-
st.switch_page("app.py")
|
19 |
-
except st.errors.StreamlitAPIException:
|
20 |
-
|
21 |
-
|
|
|
|
|
22 |
|
|
|
23 |
authenticated_user_id = st.session_state.get("authenticated_user_id")
|
24 |
-
authenticated_username = st.session_state.get("authenticated_username", "User")
|
25 |
-
app_logger.info(f"User {authenticated_username} (ID: {authenticated_user_id}) accessed Reports page.")
|
26 |
|
|
|
27 |
st.title("Consultation Reports")
|
28 |
st.markdown("View and download your past consultation sessions.")
|
29 |
|
30 |
-
# --- Load User's Chat Sessions ---
|
31 |
-
# @st.cache_data(ttl=300) #
|
|
|
32 |
def get_user_chat_sessions(user_id: int) -> List[ChatSession]:
|
|
|
33 |
app_logger.debug(f"Fetching chat sessions for user_id: {user_id}")
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
app_logger.debug(f"Found {len(sessions)} sessions for user_id: {user_id}")
|
41 |
-
|
|
|
|
|
|
|
42 |
|
|
|
43 |
chat_sessions = get_user_chat_sessions(authenticated_user_id)
|
44 |
|
|
|
45 |
if not chat_sessions:
|
46 |
-
st.info("You have no past consultation sessions
|
47 |
-
st.stop()
|
48 |
|
49 |
-
#
|
50 |
session_options = []
|
51 |
for s in chat_sessions:
|
52 |
-
start_time_display = s.start_time.strftime('%Y-%m-%d %H:%M') if s.start_time else "N/A"
|
53 |
-
|
|
|
54 |
display_string = f"ID: {s.id} | Started: {start_time_display} | Title: {title_display}"
|
55 |
-
session_options.append((display_string, s.id))
|
56 |
|
|
|
57 |
selected_option_tuple = st.selectbox(
|
58 |
"Select a Consultation Session:",
|
59 |
options=session_options,
|
60 |
-
format_func=lambda x: x[0]
|
|
|
61 |
)
|
62 |
|
63 |
if selected_option_tuple:
|
64 |
-
selected_session_id = selected_option_tuple[1]
|
65 |
-
app_logger.info(f"User {authenticated_username} selected session ID: {selected_session_id} for report.")
|
66 |
-
|
67 |
-
|
68 |
-
if
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
with st.expander("View Chat Transcript", expanded=False):
|
83 |
-
for msg_idx, msg in enumerate(
|
84 |
icon = "🧑⚕️" if msg.role == "assistant" else "👤"
|
85 |
if msg.role == "tool": icon = "🛠️"
|
86 |
-
timestamp_display = msg.timestamp.strftime('%H:%M:%S') if msg.timestamp else "N/A"
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
|
|
|
|
|
|
91 |
|
92 |
-
|
|
|
93 |
try:
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
97 |
st.download_button(
|
98 |
label="Download Report as PDF",
|
99 |
data=pdf_bytes,
|
100 |
file_name=pdf_file_name,
|
101 |
mime="application/pdf",
|
102 |
-
key=f"
|
103 |
on_click=log_report_generated,
|
104 |
-
|
|
|
|
|
105 |
)
|
106 |
except Exception as e:
|
107 |
-
app_logger.error(f"Error generating PDF for session {
|
108 |
-
st.error(f"Could not generate PDF report: {type(e).__name__}")
|
109 |
else:
|
110 |
st.info("This session has no messages recorded.")
|
|
|
|
|
|
|
|
|
111 |
else:
|
112 |
-
|
113 |
-
|
114 |
-
# (Ensure the rest of 3_Reports.py from the previous good version is here if anything was omitted for brevity)
|
115 |
-
# Example for start_time display in selected_session details:
|
116 |
-
if selected_session:
|
117 |
-
# ... other details
|
118 |
-
start_time_detail = selected_session.start_time.strftime('%Y-%m-%d %H:%M:%S UTC') if selected_session.start_time else "Not recorded"
|
119 |
-
st.write(f"**Started:** {start_time_detail}")
|
120 |
-
st.write(f"**Title:** {selected_session.title or 'Untitled Session'}")
|
121 |
-
# ... rest of message display and PDF generation ...
|
|
|
2 |
import streamlit as st
|
3 |
from datetime import datetime
|
4 |
from typing import List
|
5 |
+
from sqlmodel import select # For SQLModel queries
|
6 |
|
7 |
from config.settings import settings
|
8 |
+
from models import ChatMessage, ChatSession # User model not directly needed here if ID is sufficient
|
9 |
+
from models.db import get_session_context # SQLModel session context
|
10 |
from services.pdf_report import generate_pdf_report
|
11 |
from services.logger import app_logger
|
12 |
+
from services.metrics import log_report_generated # Assuming this function exists and is set up
|
13 |
|
14 |
+
# --- Page Configuration (Typically set in main app.py) ---
|
15 |
+
# st.set_page_config(page_title=f"Reports - {settings.APP_TITLE}", layout="wide")
|
16 |
+
|
17 |
+
# --- Authentication Check ---
|
18 |
if not st.session_state.get("authenticated_user_id"):
|
19 |
st.warning("Please log in to access reports.")
|
20 |
try:
|
21 |
+
st.switch_page("app.py") # Redirect to the main login page
|
22 |
+
except st.errors.StreamlitAPIException as e:
|
23 |
+
# Handle cases where switch_page might not work (e.g., not in MPA mode during dev)
|
24 |
+
app_logger.warning(f"Reports: Could not switch page (maybe not in MPA mode or other issue): {e}")
|
25 |
+
st.info("Please navigate to the main login page manually.")
|
26 |
+
st.stop() # Halt script execution for unauthenticated users
|
27 |
|
28 |
+
# --- Get Authenticated User Info ---
|
29 |
authenticated_user_id = st.session_state.get("authenticated_user_id")
|
30 |
+
authenticated_username = st.session_state.get("authenticated_username", "User") # Default to "User"
|
31 |
+
app_logger.info(f"User '{authenticated_username}' (ID: {authenticated_user_id}) accessed Reports page.")
|
32 |
|
33 |
+
# --- Page Title and Description ---
|
34 |
st.title("Consultation Reports")
|
35 |
st.markdown("View and download your past consultation sessions.")
|
36 |
|
37 |
+
# --- Helper Function to Load User's Chat Sessions ---
|
38 |
+
# @st.cache_data(ttl=300) # Cache for 5 minutes. Invalidate if session titles change or new sessions added frequently.
|
39 |
+
# For caching to work correctly, arguments to the cached function must be hashable. user_id (int) is.
|
40 |
def get_user_chat_sessions(user_id: int) -> List[ChatSession]:
|
41 |
+
"""Fetches all chat sessions for a given user ID, ordered by start time descending."""
|
42 |
app_logger.debug(f"Fetching chat sessions for user_id: {user_id}")
|
43 |
+
sessions: List[ChatSession] = []
|
44 |
+
try:
|
45 |
+
with get_session_context() as db_session: # db_session is a SQLModel Session
|
46 |
+
statement = select(ChatSession).where(ChatSession.user_id == user_id).order_by(ChatSession.start_time.desc())
|
47 |
+
results = db_session.exec(statement)
|
48 |
+
sessions = results.all()
|
49 |
app_logger.debug(f"Found {len(sessions)} sessions for user_id: {user_id}")
|
50 |
+
except Exception as e:
|
51 |
+
app_logger.error(f"Error fetching chat sessions for user_id {user_id}: {e}", exc_info=True)
|
52 |
+
st.error("Could not load your chat sessions. Please try again later.")
|
53 |
+
return sessions
|
54 |
|
55 |
+
# Fetch the chat sessions for the current authenticated user
|
56 |
chat_sessions = get_user_chat_sessions(authenticated_user_id)
|
57 |
|
58 |
+
# --- Display Logic ---
|
59 |
if not chat_sessions:
|
60 |
+
st.info("You have no past consultation sessions recorded.")
|
61 |
+
st.stop() # No further processing if no sessions
|
62 |
|
63 |
+
# Prepare options for the selectbox: (Display String, Session ID)
|
64 |
session_options = []
|
65 |
for s in chat_sessions:
|
66 |
+
start_time_display = s.start_time.strftime('%Y-%m-%d %H:%M') if s.start_time else "Date N/A"
|
67 |
+
# Use a more descriptive title if the session title is None
|
68 |
+
title_display = s.title if s.title else f"Consultation on {start_time_display}"
|
69 |
display_string = f"ID: {s.id} | Started: {start_time_display} | Title: {title_display}"
|
70 |
+
session_options.append((display_string, s.id)) # Store (display_text, actual_id)
|
71 |
|
72 |
+
# Let the user select a session
|
73 |
selected_option_tuple = st.selectbox(
|
74 |
"Select a Consultation Session:",
|
75 |
options=session_options,
|
76 |
+
format_func=lambda x: x[0], # Show only the display string in the selectbox
|
77 |
+
index=0 # Default to the first (most recent) session
|
78 |
)
|
79 |
|
80 |
if selected_option_tuple:
|
81 |
+
selected_session_id = selected_option_tuple[1] # Extract the session ID
|
82 |
+
app_logger.info(f"User '{authenticated_username}' selected session ID: {selected_session_id} for report viewing.")
|
83 |
+
|
84 |
+
# Find the full ChatSession object from the already fetched list
|
85 |
+
selected_session_object = next((s for s in chat_sessions if s.id == selected_session_id), None)
|
86 |
+
|
87 |
+
if selected_session_object:
|
88 |
+
st.markdown("---") # Visual separator
|
89 |
+
st.subheader(f"Details for Session ID: {selected_session_object.id}")
|
90 |
+
|
91 |
+
start_time_detail = selected_session_object.start_time.strftime('%Y-%m-%d %H:%M:%S UTC') if selected_session_object.start_time else "Not recorded"
|
92 |
+
st.write(f"**Started:** {start_time_detail}")
|
93 |
+
st.write(f"**Title:** {selected_session_object.title or 'Untitled Session'}")
|
94 |
+
|
95 |
+
# Fetch messages for the selected session
|
96 |
+
messages_for_report: List[ChatMessage] = []
|
97 |
+
try:
|
98 |
+
with get_session_context() as db_session:
|
99 |
+
statement = select(ChatMessage).where(ChatMessage.session_id == selected_session_id).order_by(ChatMessage.timestamp)
|
100 |
+
results = db_session.exec(statement)
|
101 |
+
messages_for_report = results.all()
|
102 |
+
except Exception as e:
|
103 |
+
app_logger.error(f"Error fetching messages for session {selected_session_id}: {e}", exc_info=True)
|
104 |
+
st.error("Could not load messages for this session.")
|
105 |
+
|
106 |
+
if messages_for_report:
|
107 |
with st.expander("View Chat Transcript", expanded=False):
|
108 |
+
for msg_idx, msg in enumerate(messages_for_report):
|
109 |
icon = "🧑⚕️" if msg.role == "assistant" else "👤"
|
110 |
if msg.role == "tool": icon = "🛠️"
|
111 |
+
timestamp_display = msg.timestamp.strftime('%Y-%m-%d %H:%M:%S') if msg.timestamp else "Time N/A"
|
112 |
+
|
113 |
+
# Displaying role and timestamp
|
114 |
+
st.markdown(f"**{icon} {msg.role.capitalize()}** ({timestamp_display})")
|
115 |
+
# Displaying content in a blockquote or code block for better readability
|
116 |
+
st.markdown(f"> ```\n{msg.content}\n```") # Markdown code block
|
117 |
+
if msg_idx < len(messages_for_report) - 1:
|
118 |
+
st.markdown("---") # Separator between messages
|
119 |
|
120 |
+
# PDF Download Button
|
121 |
+
st.markdown("---") # Visual separator before download button
|
122 |
try:
|
123 |
+
# Use the authenticated username as the patient name for the report
|
124 |
+
pdf_bytes = generate_pdf_report(messages_for_report, patient_name=authenticated_username)
|
125 |
+
|
126 |
+
current_time_str = datetime.now().strftime('%Y%m%d_%H%M%S')
|
127 |
+
pdf_file_name = f"Consultation_Report_Session{selected_session_id}_{current_time_str}.pdf"
|
128 |
+
|
129 |
st.download_button(
|
130 |
label="Download Report as PDF",
|
131 |
data=pdf_bytes,
|
132 |
file_name=pdf_file_name,
|
133 |
mime="application/pdf",
|
134 |
+
key=f"download_pdf_btn_{selected_session_id}", # Unique key for the button
|
135 |
on_click=log_report_generated,
|
136 |
+
# Pass necessary arguments to the on_click callback if it needs them
|
137 |
+
args=(authenticated_user_id, selected_session_id), # Example arguments
|
138 |
+
help="Click to download the consultation transcript as a PDF file."
|
139 |
)
|
140 |
except Exception as e:
|
141 |
+
app_logger.error(f"Error generating PDF for session {selected_session_id} (User: '{authenticated_username}'): {e}", exc_info=True)
|
142 |
+
st.error(f"Could not generate PDF report for this session. Error: {type(e).__name__}")
|
143 |
else:
|
144 |
st.info("This session has no messages recorded.")
|
145 |
+
else:
|
146 |
+
# This case should ideally not happen if selected_session_id comes from chat_sessions
|
147 |
+
app_logger.error(f"Selected session ID {selected_session_id} not found in fetched sessions for user '{authenticated_username}'.")
|
148 |
+
st.error("Selected session could not be found. Please try again.")
|
149 |
else:
|
150 |
+
# This case handles if session_options is empty, though the earlier check for `if not chat_sessions` should catch it.
|
151 |
+
st.info("Please select a session from the dropdown menu to view details.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|