File size: 4,485 Bytes
60eab3b
 
fd5ba92
f9f4189
fd5ba92
f201597
620a22d
dc7c980
f9f4189
dc7c980
 
257f58c
fd57cc3
f9f4189
 
f201597
fd5ba92
 
 
 
620a22d
fd5ba92
 
 
 
 
 
620a22d
fd5ba92
 
 
dc7c980
fd5ba92
 
 
 
620a22d
f9f4189
dc7c980
 
 
 
620a22d
f201597
 
620a22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f201597
 
 
dc7c980
620a22d
dc7c980
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620a22d
 
 
 
 
f9f4189
 
 
 
 
 
fd5ba92
 
f9f4189
 
 
 
fd5ba92
 
f9f4189
 
620a22d
fd5ba92
dc7c980
 
fd5ba92
 
f9f4189
fd5ba92
f9f4189
 
 
 
 
 
 
 
 
fd5ba92
620a22d
fd5ba92
620a22d
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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}")