Update pages/3_Reports.py
Browse files- pages/3_Reports.py +83 -33
pages/3_Reports.py
CHANGED
@@ -1,79 +1,129 @@
|
|
|
|
1 |
import streamlit as st
|
2 |
from datetime import datetime
|
|
|
3 |
|
4 |
from config.settings import settings
|
5 |
-
from models import ChatMessage, ChatSession, User
|
6 |
-
from models.db import get_session_context
|
7 |
from services.pdf_report import generate_pdf_report
|
8 |
from services.logger import app_logger
|
9 |
-
from services.metrics import log_report_generated
|
10 |
|
11 |
-
|
|
|
12 |
|
13 |
-
|
|
|
14 |
st.warning("Please log in to access reports.")
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
-
current_user: User = st.session_state.authenticated_user
|
18 |
|
19 |
st.title("Consultation Reports")
|
20 |
st.markdown("View and download your past consultation sessions.")
|
21 |
|
22 |
# --- Load User's Chat Sessions ---
|
23 |
-
@st.cache_data(ttl=300) # Cache for 5 minutes
|
24 |
-
def
|
|
|
25 |
with get_session_context() as db:
|
|
|
|
|
26 |
sessions = db.query(ChatSession).filter(ChatSession.user_id == user_id).order_by(ChatSession.start_time.desc()).all()
|
|
|
27 |
return sessions
|
28 |
|
29 |
-
|
|
|
|
|
30 |
|
31 |
if not chat_sessions:
|
32 |
-
st.info("You have no past consultation sessions.")
|
33 |
st.stop()
|
34 |
|
35 |
# --- Display Sessions and Download Option ---
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
"Select a Consultation Session:",
|
38 |
-
options=
|
39 |
-
format_func=lambda x: x[0] # Display the descriptive string
|
40 |
)
|
41 |
|
42 |
-
if
|
43 |
-
selected_session_id =
|
44 |
-
|
45 |
-
|
|
|
46 |
selected_session = next((s for s in chat_sessions if s.id == selected_session_id), None)
|
47 |
|
48 |
if selected_session:
|
49 |
st.subheader(f"Details for Session ID: {selected_session.id}")
|
50 |
-
|
51 |
-
st.write(f"
|
|
|
52 |
|
|
|
53 |
with get_session_context() as db:
|
54 |
-
|
55 |
-
|
|
|
|
|
56 |
if messages:
|
57 |
with st.expander("View Chat Transcript", expanded=False):
|
58 |
-
for msg in messages:
|
59 |
icon = "π§ββοΈ" if msg.role == "assistant" else "π€"
|
60 |
if msg.role == "tool": icon = "π οΈ"
|
61 |
-
|
62 |
-
st.markdown(f"
|
63 |
-
|
|
|
|
|
|
|
|
|
64 |
# PDF Download Button
|
|
|
65 |
try:
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
68 |
st.download_button(
|
69 |
label="Download Report as PDF",
|
70 |
data=pdf_bytes,
|
71 |
-
file_name=
|
72 |
mime="application/pdf",
|
73 |
-
|
|
|
|
|
74 |
)
|
75 |
except Exception as e:
|
76 |
-
app_logger.error(f"Error generating PDF for session {selected_session.id}: {e}")
|
77 |
-
st.error(f"Could not generate PDF report: {e}")
|
78 |
else:
|
79 |
-
st.info("This session has no messages.")
|
|
|
|
|
|
1 |
+
# /home/user/app/pages/3_Reports.py
|
2 |
import streamlit as st
|
3 |
from datetime import datetime
|
4 |
+
from typing import List # For type hinting
|
5 |
|
6 |
from config.settings import settings
|
7 |
+
from models import ChatMessage, ChatSession, User # User might not be needed if ID is used
|
8 |
+
from models.db import get_session_context # Or from models 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 # Assuming this function exists
|
12 |
|
13 |
+
# Page config typically in app.py
|
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 as e:
|
22 |
+
if "st.switch_page can only be called when running in MPA mode" in str(e):
|
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) # Cache for 5 minutes; ensure function args are hashable
|
41 |
+
def get_user_chat_sessions(user_id: int) -> List[ChatSession]: # Return type hint
|
42 |
+
app_logger.debug(f"Fetching chat sessions for user_id: {user_id}")
|
43 |
with get_session_context() as db:
|
44 |
+
# If using SQLModel: from sqlmodel import select
|
45 |
+
# sessions = db.exec(select(ChatSession).where(ChatSession.user_id == user_id).order_by(ChatSession.start_time.desc())).all()
|
46 |
sessions = db.query(ChatSession).filter(ChatSession.user_id == user_id).order_by(ChatSession.start_time.desc()).all()
|
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"
|
63 |
+
title_display = s.title or f"Session on {start_time_display}"
|
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] # Display the descriptive string from the tuple
|
72 |
)
|
73 |
|
74 |
+
if selected_option_tuple:
|
75 |
+
selected_session_id = selected_option_tuple[1] # Get the session_id from the tuple
|
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 |
+
start_time_detail = selected_session.start_time.strftime('%Y-%m-%d %H:%M:%S UTC') if selected_session.start_time else "Not recorded"
|
84 |
+
st.write(f"**Started:** {start_time_detail}")
|
85 |
+
st.write(f"**Title:** {selected_session.title or 'Untitled Session'}")
|
86 |
|
87 |
+
# Fetch messages for the selected session
|
88 |
with get_session_context() as db:
|
89 |
+
# If using SQLModel: from sqlmodel import select
|
90 |
+
# messages = db.exec(select(ChatMessage).where(ChatMessage.session_id == selected_session.id).order_by(ChatMessage.timestamp)).all()
|
91 |
+
messages: List[ChatMessage] = db.query(ChatMessage).filter(ChatMessage.session_id == selected_session.id).order_by(ChatMessage.timestamp).all()
|
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 |
+
# Use st.code or st.markdown for content display. Using a quote block.
|
101 |
+
st.markdown(f"> ```\n{msg.content}\n```")
|
102 |
+
if msg_idx < len(messages) - 1:
|
103 |
+
st.markdown("---") # Separator between messages
|
104 |
+
|
105 |
# PDF Download Button
|
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}", # Unique key for the button
|
120 |
+
on_click=log_report_generated, # Pass any necessary args if log_report_generated needs them
|
121 |
+
args=(authenticated_user_id, selected_session_id) # Example: if metrics logger needs user_id and 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 at this time. Error: {type(e).__name__}")
|
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.")
|