StevesInfinityDrive's picture
Update app.py
dc7c980 verified
import sys
import os
import json
import logging
import uuid
import streamlit as st
# Make sure "src" folder can be imported
sys.path.append(os.path.abspath("src"))
# Import the multi-turn function rather than the single-turn one
from src.chatbot import generate_response_with_history, COUNTRY_HELPLINES, get_helpline_for_country
# Set up logging for safeguard triggers
logging.basicConfig(filename="safeguard_logs.txt", level=logging.INFO)
# Persistent storage for metrics
METRICS_FILE = "user_metrics.json"
def load_metrics():
"""Load existing user metrics or initialize them."""
if os.path.exists(METRICS_FILE):
with open(METRICS_FILE, "r") as f:
return json.load(f)
return {"sessions": [], "feedback": {"thumbs_up": 0, "thumbs_down": 0}, "harmful_content": []}
def save_metrics(metrics):
"""Save updated user metrics to file."""
with open(METRICS_FILE, "w") as f:
json.dump(metrics, f, indent=4)
# Initialize session state
if "metrics" not in st.session_state:
st.session_state.metrics = load_metrics()
if "session_id" not in st.session_state:
st.session_state.session_id = str(uuid.uuid4())[:8] # Short unique session ID
# Ensure we have a list of turn dicts for conversation history
if "chat_history" not in st.session_state:
st.session_state.chat_history = [] # Each element: { "role": "user"/"bot", "content": str }
# Streamlit UI
st.title("Fine-Tuned GPT Chatbot πŸ€–")
# --- Disclaimer ---
st.markdown(
"**Disclaimer:** This chatbot is a prototype and is **not a substitute** for professional mental health advice. "
"If you are in crisis, please reach out to a professional or a mental health helpline."
)
# --- Country Selection ---
st.subheader("Select Your Country for Helpline Information:")
if "selected_country" not in st.session_state:
st.session_state.selected_country = "Other" # Default
st.session_state.selected_country = st.selectbox(
"Choose your country:", options=list(COUNTRY_HELPLINES.keys()), index=0
)
# --- User Input ---
user_input = st.text_input("Ask me anything:")
if st.button("Send"):
# Only proceed if user typed something
if user_input.strip():
# 1) Append user turn to the chat history
st.session_state.chat_history.append({"role": "user", "content": user_input})
# 2) Generate response using *entire* conversation history
response = generate_response_with_history(
st.session_state.chat_history,
st.session_state.selected_country
)
# 3) Append bot turn
st.session_state.chat_history.append({"role": "bot", "content": response})
# 4) Display the entire conversation so far
for turn in st.session_state.chat_history:
if turn["role"] == "user":
st.write(f"**You:** {turn['content']}")
else:
st.write(f"**Bot:** {turn['content']}")
# 5) Display country-specific helpline info
st.markdown(
f"πŸ“ž **Helpline for {st.session_state.selected_country}:** "
f"{get_helpline_for_country(st.session_state.selected_country)}"
)
else:
st.warning("Please enter a message.")
# --- Feedback System ---
st.markdown("---")
st.subheader("Feedback")
col1, col2 = st.columns(2)
with col1:
if st.button("πŸ‘ Thumbs Up"):
st.session_state.metrics["feedback"]["thumbs_up"] += 1
save_metrics(st.session_state.metrics)
st.success("Thank you for your feedback! 😊")
with col2:
if st.button("πŸ‘Ž Thumbs Down"):
st.session_state.metrics["feedback"]["thumbs_down"] += 1
save_metrics(st.session_state.metrics)
st.error("We're sorry to hear that. We'll try to improve! πŸ˜”")
# --- User Experience Progress Bar ---
total_feedback = (
st.session_state.metrics["feedback"]["thumbs_up"]
+ st.session_state.metrics["feedback"]["thumbs_down"]
)
if total_feedback > 0:
thumbs_up_percentage = (
st.session_state.metrics["feedback"]["thumbs_up"] / total_feedback
) * 100
st.markdown("---")
st.subheader("User Experience")
st.write(f"Positive Feedback: {thumbs_up_percentage:.2f}%")
st.progress(thumbs_up_percentage / 100)
else:
st.markdown("---")
st.subheader("User Experience")
st.write("No feedback yet. Be the first to share your experience!")
# --- Session ID Display ---
st.markdown("---")
st.write(f"Session ID: {st.session_state.session_id}")