Update pages/3_Reports.py
Browse files- pages/3_Reports.py +45 -53
pages/3_Reports.py
CHANGED
@@ -1,62 +1,52 @@
|
|
1 |
# /home/user/app/pages/3_Reports.py
|
2 |
import streamlit as st
|
3 |
from datetime import datetime
|
4 |
-
from typing import List
|
|
|
5 |
|
6 |
from config.settings import settings
|
7 |
-
from models import ChatMessage, ChatSession, User # User
|
8 |
-
from models.db import get_session_context
|
9 |
from services.pdf_report import generate_pdf_report
|
10 |
from services.logger import app_logger
|
11 |
-
from services.metrics import log_report_generated
|
12 |
|
13 |
-
#
|
14 |
-
# st.set_page_config(page_title=f"Reports - {settings.APP_TITLE}", layout="wide")
|
15 |
-
|
16 |
-
# --- Authentication Check ---
|
17 |
if not st.session_state.get("authenticated_user_id"):
|
18 |
st.warning("Please log in to access reports.")
|
19 |
try:
|
20 |
st.switch_page("app.py")
|
21 |
-
except st.errors.StreamlitAPIException
|
22 |
-
|
23 |
-
app_logger.warning("Reports: Running in single-page mode or st.switch_page issue. Stopping script.")
|
24 |
-
st.info("Please navigate to the main login page.")
|
25 |
-
else:
|
26 |
-
app_logger.error(f"Reports: Error during st.switch_page: {e}")
|
27 |
-
st.error("Redirection error. Please go to the login page manually.")
|
28 |
st.stop()
|
29 |
|
30 |
-
# Get authenticated user's ID and username
|
31 |
authenticated_user_id = st.session_state.get("authenticated_user_id")
|
32 |
authenticated_username = st.session_state.get("authenticated_username", "User")
|
33 |
app_logger.info(f"User {authenticated_username} (ID: {authenticated_user_id}) accessed Reports page.")
|
34 |
|
35 |
-
|
36 |
st.title("Consultation Reports")
|
37 |
st.markdown("View and download your past consultation sessions.")
|
38 |
|
39 |
# --- Load User's Chat Sessions ---
|
40 |
-
# @st.cache_data(ttl=300) #
|
41 |
-
def get_user_chat_sessions(user_id: int) -> List[ChatSession]:
|
42 |
app_logger.debug(f"Fetching chat sessions for user_id: {user_id}")
|
43 |
-
with get_session_context() as db:
|
44 |
-
#
|
45 |
-
|
46 |
-
|
|
|
|
|
47 |
app_logger.debug(f"Found {len(sessions)} sessions for user_id: {user_id}")
|
48 |
return sessions
|
49 |
|
50 |
-
# Fetch sessions (caching is good, but ensure it invalidates appropriately if sessions are added/updated frequently)
|
51 |
-
# For simplicity without complex cache invalidation, direct fetch on each load:
|
52 |
chat_sessions = get_user_chat_sessions(authenticated_user_id)
|
53 |
|
54 |
if not chat_sessions:
|
55 |
st.info("You have no past consultation sessions to display.")
|
56 |
st.stop()
|
57 |
|
58 |
-
# --- Display Sessions and Download Option ---
|
59 |
-
# Create a list of tuples for selectbox: (display_string, session_id)
|
60 |
session_options = []
|
61 |
for s in chat_sessions:
|
62 |
start_time_display = s.start_time.strftime('%Y-%m-%d %H:%M') if s.start_time else "N/A"
|
@@ -64,66 +54,68 @@ for s in chat_sessions:
|
|
64 |
display_string = f"ID: {s.id} | Started: {start_time_display} | Title: {title_display}"
|
65 |
session_options.append((display_string, s.id))
|
66 |
|
67 |
-
|
68 |
selected_option_tuple = st.selectbox(
|
69 |
"Select a Consultation Session:",
|
70 |
options=session_options,
|
71 |
-
format_func=lambda x: x[0]
|
72 |
)
|
73 |
|
74 |
if selected_option_tuple:
|
75 |
-
selected_session_id = selected_option_tuple[1]
|
76 |
app_logger.info(f"User {authenticated_username} selected session ID: {selected_session_id} for report.")
|
77 |
-
|
78 |
-
# Find the selected session object (already fetched in chat_sessions)
|
79 |
selected_session = next((s for s in chat_sessions if s.id == selected_session_id), None)
|
80 |
|
81 |
if selected_session:
|
82 |
st.subheader(f"Details for Session ID: {selected_session.id}")
|
83 |
-
|
84 |
-
st.write(f"**Started:** {start_time_detail}")
|
85 |
-
st.write(f"**Title:** {selected_session.title or 'Untitled Session'}")
|
86 |
|
87 |
-
#
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
messages: List[ChatMessage] =
|
|
|
92 |
|
93 |
if messages:
|
|
|
|
|
94 |
with st.expander("View Chat Transcript", expanded=False):
|
95 |
for msg_idx, msg in enumerate(messages):
|
96 |
icon = "🧑⚕️" if msg.role == "assistant" else "👤"
|
97 |
if msg.role == "tool": icon = "🛠️"
|
98 |
timestamp_display = msg.timestamp.strftime('%H:%M:%S') if msg.timestamp else "N/A"
|
99 |
st.markdown(f"**{icon} {msg.role.capitalize()} ({timestamp_display}):**")
|
100 |
-
|
101 |
-
st.markdown(f"> ```\n{msg.content}\n```")
|
102 |
if msg_idx < len(messages) - 1:
|
103 |
-
st.markdown("---")
|
104 |
|
105 |
-
|
106 |
-
st.markdown("---") # Separator before download button
|
107 |
try:
|
108 |
-
# Use authenticated_username for patient_name, or a more specific field if available
|
109 |
pdf_bytes = generate_pdf_report(messages, patient_name=authenticated_username)
|
110 |
-
|
111 |
file_name_timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
112 |
pdf_file_name = f"Consultation_Report_Session{selected_session.id}_{file_name_timestamp}.pdf"
|
113 |
-
|
114 |
st.download_button(
|
115 |
label="Download Report as PDF",
|
116 |
data=pdf_bytes,
|
117 |
file_name=pdf_file_name,
|
118 |
mime="application/pdf",
|
119 |
-
key=f"download_pdf_{selected_session.id}",
|
120 |
-
on_click=log_report_generated,
|
121 |
-
args=(authenticated_user_id, selected_session_id)
|
122 |
)
|
123 |
except Exception as e:
|
124 |
app_logger.error(f"Error generating PDF for session {selected_session.id} for user {authenticated_username}: {e}", exc_info=True)
|
125 |
-
st.error(f"Could not generate PDF report
|
126 |
else:
|
127 |
st.info("This session has no messages recorded.")
|
128 |
else:
|
129 |
-
st.info("Select a session from the dropdown to view details and download the report.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# /home/user/app/pages/3_Reports.py
|
2 |
import streamlit as st
|
3 |
from datetime import datetime
|
4 |
+
from typing import List
|
5 |
+
from sqlmodel import select # <--- IMPORT SELECT FOR SQLMODEL QUERIES
|
6 |
|
7 |
from config.settings import settings
|
8 |
+
from models import ChatMessage, ChatSession, User # User not directly used if ID is sufficient
|
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 |
+
# --- Auth Check (same as before) ---
|
|
|
|
|
|
|
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 |
+
st.info("Please navigate to the main login page.")
|
|
|
|
|
|
|
|
|
|
|
21 |
st.stop()
|
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) # Consider re-enabling with SQLModel if args are hashable
|
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 |
+
with get_session_context() as db: # db is a SQLModel Session
|
35 |
+
# --- SQLMODEL QUERY ---
|
36 |
+
statement = select(ChatSession).where(ChatSession.user_id == user_id).order_by(ChatSession.start_time.desc())
|
37 |
+
results = db.exec(statement)
|
38 |
+
sessions = results.all()
|
39 |
+
# --------------------
|
40 |
app_logger.debug(f"Found {len(sessions)} sessions for user_id: {user_id}")
|
41 |
return sessions
|
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 to display.")
|
47 |
st.stop()
|
48 |
|
49 |
+
# --- Display Sessions and Download Option (largely same, but ensure messages query is updated) ---
|
|
|
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"
|
|
|
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 |
selected_session = next((s for s in chat_sessions if s.id == selected_session_id), None)
|
67 |
|
68 |
if selected_session:
|
69 |
st.subheader(f"Details for Session ID: {selected_session.id}")
|
70 |
+
# ... (display session details - same as before)
|
|
|
|
|
71 |
|
72 |
+
with get_session_context() as db: # db is a SQLModel Session
|
73 |
+
# --- SQLMODEL QUERY ---
|
74 |
+
statement = select(ChatMessage).where(ChatMessage.session_id == selected_session.id).order_by(ChatMessage.timestamp)
|
75 |
+
results = db.exec(statement)
|
76 |
+
messages: List[ChatMessage] = results.all()
|
77 |
+
# --------------------
|
78 |
|
79 |
if messages:
|
80 |
+
# ... (display transcript and PDF download - same as before)
|
81 |
+
# The generate_pdf_report(messages, ...) part doesn't change.
|
82 |
with st.expander("View Chat Transcript", expanded=False):
|
83 |
for msg_idx, msg in enumerate(messages):
|
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 |
st.markdown(f"**{icon} {msg.role.capitalize()} ({timestamp_display}):**")
|
88 |
+
st.markdown(f"> ```\n{msg.content}\n```") # Using markdown code block for content
|
|
|
89 |
if msg_idx < len(messages) - 1:
|
90 |
+
st.markdown("---")
|
91 |
|
92 |
+
st.markdown("---")
|
|
|
93 |
try:
|
|
|
94 |
pdf_bytes = generate_pdf_report(messages, patient_name=authenticated_username)
|
|
|
95 |
file_name_timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
96 |
pdf_file_name = f"Consultation_Report_Session{selected_session.id}_{file_name_timestamp}.pdf"
|
|
|
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"download_pdf_{selected_session.id}",
|
103 |
+
on_click=log_report_generated,
|
104 |
+
args=(authenticated_user_id, selected_session_id)
|
105 |
)
|
106 |
except Exception as e:
|
107 |
app_logger.error(f"Error generating PDF for session {selected_session.id} for user {authenticated_username}: {e}", exc_info=True)
|
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 |
+
st.info("Select a session from the dropdown to view details and download the report.")
|
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 ...
|