Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 80 additions & 19 deletions TalkHeal.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,42 @@

st.set_page_config(page_title="TalkHeal", page_icon="💬", layout="wide")


# --- AUTHENTICATION AND SESSION INIT ---
if "conversations" not in st.session_state:
st.session_state.conversations = []
if "active_conversation" not in st.session_state:
st.session_state.active_conversation = None
if "db_initialized" not in st.session_state:
init_db()
st.session_state["db_initialized"] = True

# --- DB Initialization ---
if "db_initialized" not in st.session_state:
init_db()
st.session_state["db_initialized"] = True

# --- Auth State Initialization ---

if "authenticated" not in st.session_state:
st.session_state.authenticated = False
if "show_signup" not in st.session_state:
st.session_state.show_signup = False
if "anonymous_mode" not in st.session_state:
st.session_state.anonymous_mode = False


# --- LOGIN/SIGNUP UI FUNCTIONS ---
def show_login_ui():
st.subheader("🔐 Login")
email = st.text_input("Email", key="login_email")
password = st.text_input("Password", type="password", key="login_password")
if st.button("Login"):
success, user = authenticate_user(email, password)
if success:
st.session_state.authenticated = True
st.session_state.user_email = user["email"]
st.session_state.user_name = user["name"]

# --- LOGIN PAGE ---
if not st.session_state.authenticated:
Expand All @@ -30,6 +56,7 @@
if st.button("🌙" if is_dark else "☀️", key="top_theme_toggle", help="Toggle Light/Dark Mode", use_container_width=True):
st.session_state.dark_mode = not is_dark
st.session_state.theme_changed = True

st.rerun()
with col_logout:
if st.button("Logout", key="logout_btn", use_container_width=True):
Expand All @@ -44,6 +71,14 @@
st.title(f"Welcome to TalkHeal, {st.session_state.user_name}! 💬")
st.markdown("Navigate to other pages from the sidebar.")

if st.button("Logout"):
for key in ["authenticated", "user_email", "user_name", "show_signup"]:
if key in st.session_state:
del st.session_state[key]
st.rerun()

# --- IMPORTS ---

import google.generativeai as genai
from core.utils import save_conversations, load_conversations
from core.config import configure_gemini, PAGE_CONFIG
Expand All @@ -55,11 +90,15 @@
from components.emergency_page import render_emergency_page
from components.profile import apply_global_font_size


# --- SESSION INITIALIZATION ---

# --- 1. INITIALIZE SESSION STATE ---

if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "conversations" not in st.session_state:
st.session_state.conversations = load_conversations()
st.session_state.conversations = [] if st.session_state.anonymous_mode else load_conversations()
if "active_conversation" not in st.session_state:
st.session_state.active_conversation = -1
if "show_emergency_page" not in st.session_state:
Expand All @@ -76,14 +115,16 @@
if "selected_tone" not in st.session_state:
st.session_state.selected_tone = "Compassionate Listener"

# --- 2. SET PAGE CONFIG ---
# --- CONFIG ---
apply_global_font_size()


# --- 3. APPLY STYLES & CONFIGURATIONS ---

apply_custom_css()
model = configure_gemini()

# --- 4. TONE SELECTION DROPDOWN IN SIDEBAR ---
# --- SIDEBAR TONE & PRIVACY TOGGLE ---
TONE_OPTIONS = {
"Compassionate Listener": "You are a compassionate listener — soft, empathetic, patient — like a therapist who listens without judgment.",
"Motivating Coach": "You are a motivating coach — energetic, encouraging, and action-focused — helping the user push through rough days.",
Expand All @@ -101,28 +142,44 @@
)
st.session_state.selected_tone = selected_tone

# --- 5. DEFINE FUNCTION TO GET TONE PROMPT ---
st.markdown("---")
st.markdown("### 🔒 Privacy Mode")
anonymous_mode_toggle = st.toggle("Enable Anonymous Mode", value=st.session_state.anonymous_mode)
if st.session_state.anonymous_mode != anonymous_mode_toggle:
st.session_state.anonymous_mode = anonymous_mode_toggle
st.rerun()

# --- TONE PROMPT FUNCTION ---
def get_tone_prompt():
return TONE_OPTIONS.get(st.session_state.get("selected_tone", "Compassionate Listener"), TONE_OPTIONS["Compassionate Listener"])
return TONE_OPTIONS.get(st.session_state.get("selected_tone", "Compassionate Listener"))

# --- RENDER SIDEBAR ---
def render_sidebar():
st.sidebar.title("🧠 TalkHeal")
st.sidebar.markdown(f"**🕒 Current Time:** {get_current_time()}")
st.sidebar.markdown("---")

if st.sidebar.button("➕ Start New Conversation"):
create_new_conversation()

st.sidebar.markdown("### 💬 Past Conversations")
if not st.session_state.conversations:
st.sidebar.info("No conversations yet.")
else:
for idx, convo in enumerate(st.session_state.conversations):
title = convo.get("title", f"Conversation {idx+1}")
if st.sidebar.button(f"🗂️ {title}", key=f"convo_{idx}"):
st.session_state.active_conversation = idx

# --- 6. RENDER SIDEBAR ---
render_sidebar()

# --- 7. PAGE ROUTING ---
# --- ROUTING ---
main_area = st.container()

if not st.session_state.conversations:
saved_conversations = load_conversations()
if saved_conversations:
st.session_state.conversations = saved_conversations
if st.session_state.active_conversation == -1:
st.session_state.active_conversation = 0
else:
create_new_conversation()
st.session_state.active_conversation = 0
create_new_conversation()
st.rerun()

# --- 8. RENDER PAGE ---
# --- MAIN CONTENT ---
if st.session_state.get("show_emergency_page"):
with main_area:
render_emergency_page()
Expand Down Expand Up @@ -210,7 +267,11 @@ def mood_slider():
render_chat_interface()
handle_chat_input(model, system_prompt=get_tone_prompt())

# --- 9. SCROLL SCRIPT ---
# ✅ Save only if not in anonymous mode
if not st.session_state.anonymous_mode:
save_conversations(st.session_state.conversations)

# --- AUTO-SCROLL SCRIPT ---
st.markdown("""
<script>
function scrollToBottom() {
Expand All @@ -221,4 +282,4 @@ def mood_slider():
}
setTimeout(scrollToBottom, 100);
</script>
""", unsafe_allow_html=True)
""", unsafe_allow_html=True)
15 changes: 9 additions & 6 deletions components/chat_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ def handle_chat_input(model, system_prompt):
title = user_input[:30] + "..." if len(user_input) > 30 else user_input
active_convo["title"] = title

save_conversations(st.session_state.conversations)
if not st.session_state.anonymous_mode:
save_conversations(st.session_state.conversations)

# Format memory
def format_memory(convo_history, max_turns=10):
Expand All @@ -118,27 +119,29 @@ def format_memory(convo_history, max_turns=10):
"time": get_current_time()
})

except ValueError as e:
except ValueError:
st.error("I'm having trouble understanding your message. Could you please rephrase it?")
active_convo["messages"].append({
"sender": "bot",
"message": "I'm having trouble understanding your message. Could you please rephrase it?",
"time": get_current_time()
})
except requests.RequestException as e:
except requests.RequestException:
st.error("Network connection issue. Please check your internet connection.")
active_convo["messages"].append({
"sender": "bot",
"message": "I'm having trouble connecting to my services. Please check your internet connection and try again.",
"time": get_current_time()
})
except Exception as e:
st.error(f"An unexpected error occurred. Please try again.")
except Exception:
st.error("An unexpected error occurred. Please try again.")
active_convo["messages"].append({
"sender": "bot",
"message": "I'm having trouble responding right now. Please try again in a moment.",
"time": get_current_time()
})

save_conversations(st.session_state.conversations)
if not st.session_state.anonymous_mode:
save_conversations(st.session_state.conversations)

st.rerun()
4 changes: 3 additions & 1 deletion components/sidebar.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,9 @@ def render_sidebar():
del st.session_state.conversations[st.session_state.delete_candidate]

from core.utils import save_conversations
save_conversations(st.session_state.conversations)
if not st.session_state.get("anonymous_mode", False):
save_conversations(st.session_state.conversations)


del st.session_state.delete_candidate
st.session_state.active_conversation = -1
Expand Down
Loading