File size: 4,957 Bytes
d6adae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f37d148
 
 
 
 
 
 
 
 
 
d6adae3
 
 
 
 
 
 
 
86bc4c2
 
 
 
 
 
 
 
 
 
d6adae3
86bc4c2
d6adae3
86bc4c2
 
d6adae3
 
 
 
 
86bc4c2
d6adae3
 
 
 
 
 
86bc4c2
d6adae3
 
 
 
 
 
 
 
f37d148
d6adae3
 
 
f37d148
d6adae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f37d148
d6adae3
 
 
 
 
 
 
 
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
from datetime import datetime, timezone

import streamlit as st

from chatbot import chat
from memory import delete_all_memories, get_all_memories

st.set_page_config(page_title="MemoryMind", page_icon="🧠", layout="wide")

# --- session state ---
if "chat_history" not in st.session_state:
    st.session_state.chat_history = []
if "last_used_ids" not in st.session_state:
    st.session_state.last_used_ids = []
if "confirm_reset" not in st.session_state:
    st.session_state.confirm_reset = False


def _relative_time(iso_str: str) -> str:
    try:
        dt = datetime.fromisoformat(iso_str)
        seconds = int((datetime.now(timezone.utc) - dt).total_seconds())
        if seconds < 60:
            return "just now"
        if seconds < 3600:
            return f"{seconds // 60}m ago"
        if seconds < 86400:
            return f"{seconds // 3600}h ago"
        return f"{seconds // 86400}d ago"
    except Exception:
        return ""


# --- sidebar ---
with st.sidebar:
    st.title("🧠 MemoryMind")
    st.divider()

    username = st.text_input("Who are you?", placeholder="Enter your name...", key="username_input")
    user_id = username.strip().lower().replace(" ", "_") or "guest"

    st.divider()

    memories = get_all_memories(user_id=user_id)
    st.caption(f"{len(memories)} fact{'s' if len(memories) != 1 else ''} stored for **{username or 'guest'}**")
    st.divider()

    if not memories:
        st.caption("No memories yet. Start chatting!")
    else:
        for m in memories:
            is_used = m["id"] in st.session_state.last_used_ids
            meta = m["metadata"]

            # staleness — gray out if not used in 7+ days
            try:
                last_used_dt = datetime.fromisoformat(meta.get("last_used", meta.get("timestamp", "")))
                days_stale = (datetime.now(timezone.utc) - last_used_dt).days
                is_stale = days_stale >= 7
            except Exception:
                is_stale = False

            border_color = "#4caf50" if is_used else ("#555" if is_stale else "#444")
            bg_color = "#1a2e1a" if is_used else "#1a1a1a"
            text_color = "#888" if is_stale else "#e0e0e0"
            checkmark = " ✓" if is_used else ""
            confidence = meta.get("confidence", 1)
            confidence_stars = "★" * min(confidence, 5)

            st.markdown(
                f"""
                <div style="background:{bg_color};border-left:3px solid {border_color};
                padding:8px 12px;border-radius:4px;margin-bottom:8px;line-height:1.4;">
                <div style="font-size:0.85rem;color:{text_color};">{m['fact']}{checkmark}</div>
                <div style="font-size:0.7rem;color:#888;margin-top:5px;">
                    <span style="background:#2a2a2a;padding:1px 7px;border-radius:10px;color:#aaa;">
                        {meta.get('type', '—')}
                    </span>
                    &nbsp;·&nbsp;{_relative_time(meta.get('timestamp', ''))}
                    &nbsp;·&nbsp;used {meta.get('usage_count', 0)}×
                    &nbsp;·&nbsp;<span style="color:#f4c542;">{confidence_stars}</span>
                </div>
                </div>""",
                unsafe_allow_html=True,
            )

    st.divider()

    if st.session_state.confirm_reset:
        st.warning(f"Wipe all memories for **{username or 'guest'}**?")
        col1, col2 = st.columns(2)
        with col1:
            if st.button("Yes, reset", type="primary", use_container_width=True):
                delete_all_memories(user_id=user_id)
                st.session_state.chat_history = []
                st.session_state.last_used_ids = []
                st.session_state.confirm_reset = False
                st.rerun()
        with col2:
            if st.button("Cancel", use_container_width=True):
                st.session_state.confirm_reset = False
                st.rerun()
    else:
        if st.button("🗑️ Reset Memory", use_container_width=True):
            st.session_state.confirm_reset = True
            st.rerun()


# --- main chat area ---
st.title("MemoryMind")
st.caption("The chatbot that actually remembers you.")

for message in st.session_state.chat_history:
    with st.chat_message(message["role"]):
        st.write(message["content"])

if prompt := st.chat_input("Say something..."):
    with st.chat_message("user"):
        st.write(prompt)

    with st.chat_message("assistant"):
        with st.spinner("Thinking..."):
            reply, used_ids = chat(prompt, st.session_state.chat_history, user_id=user_id)
        st.write(reply)
        if used_ids:
            st.caption(f"💡 {len(used_ids)} memor{'ies' if len(used_ids) != 1 else 'y'} used")

    st.session_state.chat_history.append({"role": "user", "content": prompt})
    st.session_state.chat_history.append({"role": "assistant", "content": reply})
    st.session_state.last_used_ids = used_ids
    st.rerun()