Skip to content

Commit

Permalink
fix: attempt to fix timezone (not done right) reinstated download, de…
Browse files Browse the repository at this point in the history
…lete chatlog
  • Loading branch information
ghostleek committed Feb 4, 2024
1 parent bb5829f commit 7bee12b
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 108 deletions.
Empty file removed admin/admin_panel.py
Empty file.
Empty file removed app/chatlog/chatlog.py
Empty file.
143 changes: 143 additions & 0 deletions app/chatlog/chatlog_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import csv
import io
import logging
from app.db.database_connection import connect_to_db
from datetime import datetime
from zoneinfo import ZoneInfo


def insert_chat_log(prompt, response):
conn = connect_to_db()
if conn is None:
logging.error("Failed to connect to the database.")
return

# Get current time in GMT+8 timezone
now_in_sgt = datetime.now(ZoneInfo("Asia/Singapore"))

try:
with conn, conn.cursor() as cur:
cur.execute("""
INSERT INTO chat_logs (prompt, response, timestamp)
VALUES (%s, %s, %s)
""", (prompt, response, now_in_sgt))
conn.commit()
logging.info("Chat log inserted successfully.")
except Exception as e:
logging.error(f"Error inserting chat log: {e}")
finally:
if conn is not None:
conn.close()


# fetch chatlog


def fetch_chat_logs():
conn = connect_to_db()
if conn is None:
logging.error("Failed to connect to the database for fetching logs.")
return []
try:
with conn, conn.cursor() as cur:
cur.execute("SELECT * FROM chat_logs")
chat_logs = cur.fetchall()
logging.info(f"Fetched {len(chat_logs)} chat log records.")
return chat_logs
except Exception as e:
logging.error(f"Error fetching chat logs: {e}")
return []
finally:
if conn is not None:
conn.close()

# fetch past hour chatlog


def fetch_recent_chat_logs(hours=1):
conn = connect_to_db()
if conn is None:
logging.error("Failed to connect to the database for fetching logs.")
return []

# Ensure the current time is in GMT+8
now_in_sgt = datetime.now(ZoneInfo("Asia/Singapore"))
one_hour_ago = now_in_sgt - datetime.timedelta(hours=hours)
logging.info(f"Fetching logs from: {one_hour_ago}")

try:
with conn, conn.cursor() as cur:
cur.execute("""
SELECT * FROM chat_logs
WHERE timestamp >= %s
""", (one_hour_ago,))
chat_logs = cur.fetchall()
logging.info(f"Fetched {len(chat_logs)} chat log records.")
return chat_logs
except Exception as e:
logging.error(f"Error fetching recent chat logs: {e}")
return []
finally:
if conn is not None:
conn.close()

# fetch past hour chatlog
def fetch_recent_chat_logs(hours=1):
conn = connect_to_db()
if conn is None:
logging.error("Failed to connect to the database for fetching logs.")
return []

one_hour_ago = datetime.datetime.now() - datetime.timedelta(hours=hours)
logging.info(f"Fetching logs from: {one_hour_ago}")

try:
with conn, conn.cursor() as cur:
cur.execute("""
SELECT * FROM chat_logs
WHERE timestamp >= %s
""", (one_hour_ago,))
chat_logs = cur.fetchall()
logging.info(f"Fetched {len(chat_logs)} chat log records.")
return chat_logs
except Exception as e:
logging.error(f"Error fetching recent chat logs: {e}")
return []
finally:
if conn is not None:
conn.close()



def export_chat_logs_to_csv(filename='chat_logs.csv'):
chat_logs = fetch_chat_logs()
if not chat_logs:
print("No chat logs to export.")
return

# Create a CSV in memory
output = io.StringIO()
writer = csv.writer(output)
# Writing headers
writer.writerow(['ID', 'Timestamp', 'Prompt', 'Response'])
writer.writerows(chat_logs)
return output.getvalue()


# delete chatlog
def delete_all_chatlogs():
conn = connect_to_db()
if conn is None:
logging.error("Failed to connect to the database.")
return
try:
with conn, conn.cursor() as cur:
cur.execute("DELETE FROM chat_logs")
conn.commit()
logging.info("All chat logs deleted successfully.")
except Exception as e:
logging.error(f"Error deleting chat logs: {e}")
finally:
if conn is not None:
conn.close()

Empty file removed export.py
Empty file.
98 changes: 6 additions & 92 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,113 +1,27 @@
import datetime
from openai import OpenAI
import logging
import streamlit as st
from app.chatlog.chatlog_handler import insert_chat_log
from sidebar import setup_sidebar
from app.db.database_connection import initialize_db, connect_to_db
from app.db.database_connection import initialize_db
from app.instructions.instructions_handler import get_latest_instructions
# from chatbot import process_chat_input
# from admin_panel import handle_admin_actions

# Title for now, no need subtitles. Can consider loading title/ subtitle from DB and enable users to edit
st.title("CherGPT Basic")
# Initialize session state for admin

# Set up the sidebar and initialize DB
initialize_db()

# Ensure get_latest_instructions is called once and stored
def setup_app():
# Ensure get_latest_instructions is called once and stored
if 'existing_instructions' not in st.session_state:
st.session_state['existing_instructions'] = get_latest_instructions()
setup_sidebar()

setup_app()


# Tech debt to refactor admin panel actions
# handle_admin_actions()
# Chatbot interaction
# process_chat_input()

client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])


# insert chatlog into DB
def insert_chat_log(prompt, response):
conn = connect_to_db()
if conn is None:
logging.error("Failed to connect to the database.")
return

try:
with conn, conn.cursor() as cur:
cur.execute("""
INSERT INTO chat_logs (prompt, response)
VALUES (%s, %s)
""", (prompt, response))
conn.commit()
logging.info("Chat log inserted successfully.")
except Exception as e:
logging.error(f"Error inserting chat log: {e}")
finally:
if conn is not None:
conn.close()

# fetch chatlog
def fetch_chat_logs():
conn = connect_to_db()
if conn is None:
logging.error("Failed to connect to the database for fetching logs.")
return []
try:
with conn, conn.cursor() as cur:
cur.execute("SELECT * FROM chat_logs")
chat_logs = cur.fetchall()
logging.info(f"Fetched {len(chat_logs)} chat log records.")
return chat_logs
except Exception as e:
logging.error(f"Error fetching chat logs: {e}")
return []
finally:
if conn is not None:
conn.close()

# fetch past hour chatlog


def fetch_recent_chat_logs(hours=1):
conn = connect_to_db()
if conn is None:
logging.error("Failed to connect to the database for fetching logs.")
return []

one_hour_ago = datetime.datetime.now() - datetime.timedelta(hours=hours)
logging.info(f"Fetching logs from: {one_hour_ago}")

try:
with conn, conn.cursor() as cur:
cur.execute("""
SELECT * FROM chat_logs
WHERE timestamp >= %s
""", (one_hour_ago,))
chat_logs = cur.fetchall()
logging.info(f"Fetched {len(chat_logs)} chat log records.")
return chat_logs
except Exception as e:
logging.error(f"Error fetching recent chat logs: {e}")
return []
finally:
if conn is not None:
conn.close()

# export chatlog









#chatbot
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = "gpt-3.5-turbo"

Expand Down
Empty file removed openai_integration.py
Empty file.
23 changes: 7 additions & 16 deletions sidebar.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import streamlit as st
from app.chatlog.chatlog_handler import delete_all_chatlogs, export_chat_logs_to_csv
from app.instructions.instructions_handler import get_latest_instructions, update_instructions

custominstructions_area_height = 300
Expand All @@ -11,11 +12,10 @@ def setup_sidebar():
if admin_password == st.secrets["ADMIN_PASSWORD"]:
st.session_state["is_admin"] = True
st.success("Authenticated as Admin")
elif admin_password: # Only display message if something was entered
elif admin_password:
st.error("Incorrect password")
st.session_state["is_admin"] = False

# but still under the condition checking st.session_state.get("is_admin")
if st.session_state.get("is_admin", False):
with st.sidebar:
st.title("Admin Panel")
Expand All @@ -27,18 +27,9 @@ def setup_sidebar():
st.success("Instructions updated successfully")
st.experimental_rerun()

# Assuming these functions are defined elsewhere in your code:
# csv_data = export_chat_logs_to_csv()
# if csv_data:
# st.download_button(label="Download Chat Logs", data=csv_data, file_name='chat_logs.csv', mime='text/csv',)
# if st.button("Delete All Chat Logs"):
# delete_all_chatlogs()
# if st.button("Generate Insights from Recent Chats"):
# recent_chats = fetch_recent_chat_logs(1) # Last hour
# print(recent_chats)
# if recent_chats:
# insights = generate_insights_with_openai(recent_chats)
# st.write(insights)
# else:
# st.write("No recent chats to analyze.")
csv_data = export_chat_logs_to_csv()
if csv_data:
st.download_button(label="Download Chat Logs", data=csv_data, file_name='chat_logs.csv', mime='text/csv',)
if st.button("Delete All Chat Logs"):
delete_all_chatlogs()

0 comments on commit 7bee12b

Please sign in to comment.