Spaces:
Sleeping
Sleeping
File size: 1,308 Bytes
f80362a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # get_csv.py
import streamlit as st
import sqlite3
import pandas as pd
from session import get_session_id
from logging_config import logger
from database import DB_NAME
def get_db_contents_as_csv(session_id):
"""
Fetches the database contents for the current session as a CSV-formatted byte string.
"""
session_id = get_session_id()
logger.info(f"Fetching chat history for session_id={session_id} as CSV.")
try:
conn = sqlite3.connect(DB_NAME)
query = "SELECT role, content, timestamp FROM conversations WHERE session_id = ? ORDER BY id ASC"
df = pd.read_sql_query(query, conn, params=(session_id,))
conn.close()
if not df.empty:
logger.info(f"Successfully fetched {len(df)} rows for session_id={session_id}.")
return df.to_csv(index=False).encode('utf-8')
else:
logger.warning(f"No data found for session_id={session_id}. Returning empty result.")
return None
except sqlite3.Error as e:
logger.error(f"Error reading database: {e}")
st.error(f"Error reading database: {e}")
return None
except Exception as e:
logger.error(f"Unexpected error while fetching database contents: {e}")
st.error(f"Unexpected error: {e}")
return None |