File size: 6,889 Bytes
4a9af1a
a9b1573
 
 
 
 
4a9af1a
a9b1573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
987b294
a9b1573
987b294
a9b1573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import streamlit as st
import sqlite3
from datetime import datetime, timedelta
import os
import json
import requests

# -----------------------------
# CONFIG
# -----------------------------
st.set_page_config(
    page_title="SmartDay.AI",
    page_icon="🌸",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Theme Colors
PRIMARY_COLOR = "#FF6F61"  # Coral
BG_COLOR = "#FFFFFF"       # White

# Database setup
DB_FILE = "smartday_ai.db"

def init_db():
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS users
                 (username TEXT PRIMARY KEY, password TEXT)''')
    c.execute('''CREATE TABLE IF NOT EXISTS journal
                 (username TEXT, date TEXT, entry TEXT)''')
    c.execute('''CREATE TABLE IF NOT EXISTS planner
                 (username TEXT, date TEXT, task TEXT, status TEXT)''')
    conn.commit()
    conn.close()

init_db()

# -----------------------------
# AUTHENTICATION
# -----------------------------
def register_user(username, password):
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    try:
        c.execute("INSERT INTO users VALUES (?,?)", (username, password))
        conn.commit()
        return True
    except:
        return False
    finally:
        conn.close()

def login_user(username, password):
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
    result = c.fetchone()
    conn.close()
    return result is not None

# -----------------------------
# GROQ AI INTEGRATION
# -----------------------------
def groq_chat(prompt):
    """Call Groq API - key saved in Hugging Face Secrets"""
    api_key = os.environ.get("GROQ_API_KEY")
    if not api_key:
        return "⚠️ No API key found. Please set GROQ_API_KEY in Secrets."
    
    url = "https://api.groq.com/openai/v1/chat/completions"
    headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
    data = {
        "model": "llama-3.1-8b-instant",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.5
    }

    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        return response.json()["choices"][0]["message"]["content"]
    else:
        return f"Error: {response.text}"

# -----------------------------
# DASHBOARD COMPONENTS
# -----------------------------
def learning_journal(username):
    st.header("📖 Learning Journal")
    today = datetime.today().strftime("%Y-%m-%d")
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()

    entry = st.text_area("Write today’s reflection or learning:", height=150)
    if st.button("Save Entry"):
        c.execute("INSERT INTO journal VALUES (?,?,?)", (username, today, entry))
        conn.commit()
        st.success("Journal saved!")

    st.subheader("Past Entries")
    c.execute("SELECT date, entry FROM journal WHERE username=? ORDER BY date DESC", (username,))
    rows = c.fetchall()
    for r in rows:
        st.markdown(f"**{r[0]}** — {r[1]}")
    conn.close()

def smart_day_planner(username):
    st.header("🧠 Smart Day Planner")
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()

    task = st.text_input("Add a new task:")
    if st.button("Add Task"):
        c.execute("INSERT INTO planner VALUES (?,?,?,?)", (username, datetime.today().strftime("%Y-%m-%d"), task, "Pending"))
        conn.commit()
        st.success("Task added!")

    st.subheader("Today’s Tasks")
    c.execute("SELECT task, status FROM planner WHERE username=? AND date=?", (username, datetime.today().strftime("%Y-%m-%d"),))
    tasks = c.fetchall()
    for t in tasks:
        if st.checkbox(f"{t[0]} — {t[1]}", value=(t[1]=="Done")):
            c.execute("UPDATE planner SET status='Done' WHERE username=? AND task=?", (username, t[0]))
            conn.commit()
    conn.close()

def weekly_summary(username):
    st.header("📅 Weekly Summary & Insights")
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    week_start = (datetime.today() - timedelta(days=7)).strftime("%Y-%m-%d")
    c.execute("SELECT date, entry FROM journal WHERE username=? AND date>=?", (username, week_start))
    data = c.fetchall()

    if not data:
        st.info("No entries found for this week.")
        return

    combined_text = "\n".join([f"{d[0]}: {d[1]}" for d in data])
    st.write("Here’s your AI-powered reflection summary 👇")
    summary = groq_chat(f"Summarize and analyze this weekly journal:\n{combined_text}")
    st.markdown(summary)
    conn.close()

def ai_assistant():
    st.header("🤖 Ask SmartDay.AI")
    query = st.text_area("What would you like help with?", height=100)
    if st.button("Ask AI"):
        response = groq_chat(query)
        st.markdown(f"**Answer:** {response}")

# -----------------------------
# MAIN APP
# -----------------------------
def main():
    st.markdown(
        f"""
        <style>
        body {{
            background-color: {BG_COLOR};
            color: #333;
        }}
        .stButton>button {{
            background-color: {PRIMARY_COLOR};
            color: white;
            border-radius: 8px;
            padding: 0.6em 1.2em;
        }}
        </style>
        """,
        unsafe_allow_html=True
    )

    st.sidebar.title("🌸 SmartDay.AI")
    menu = ["Login", "Register"]
    choice = st.sidebar.selectbox("Menu", menu)

    if choice == "Register":
        st.subheader("Create Account")
        new_user = st.text_input("Username")
        new_pass = st.text_input("Password", type="password")
        if st.button("Register"):
            if register_user(new_user, new_pass):
                st.success("Account created! Please go to Login.")
            else:
                st.error("User already exists.")

    elif choice == "Login":
        st.subheader("User Login")
        username = st.text_input("Username")
        password = st.text_input("Password", type="password")
        if st.button("Login"):
            if login_user(username, password):
                st.session_state["user"] = username
                st.success(f"Welcome, {username}!")
            else:
                st.error("Invalid credentials.")

    if "user" in st.session_state:
        username = st.session_state["user"]
        st.sidebar.success(f"Logged in as {username}")

        page = st.sidebar.radio("Navigate", ["Learning Journal", "Smart Day Planner", "Weekly Summary", "AI Assistant"])
        if page == "Learning Journal":
            learning_journal(username)
        elif page == "Smart Day Planner":
            smart_day_planner(username)
        elif page == "Weekly Summary":
            weekly_summary(username)
        elif page == "AI Assistant":
            ai_assistant()

if __name__ == "__main__":
    main()