-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
588 lines (461 loc) · 17.3 KB
/
app.py
File metadata and controls
588 lines (461 loc) · 17.3 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import os
import random
import datetime
from functools import wraps
import requests
from dotenv import load_dotenv
from flask import Flask, request, jsonify, session, send_from_directory, redirect
from flask_cors import CORS
import firebase_admin
from firebase_admin import credentials, auth, firestore
# OpenAI is optional (only needed for /api/petchat)
try:
from openai import OpenAI
except Exception:
OpenAI = None
# ==============================
# Config / init
# ==============================
load_dotenv()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIR = os.path.join(BASE_DIR, "template")
# Serve HTML from /template and also serve static assets from /template
# so links like /styles/style.css and /scripts/script.js work.
app = Flask(
__name__,
template_folder="template",
static_folder="template",
static_url_path="",
)
# Cookies (helps with session)
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
)
CORS(app, supports_credentials=True)
# REQUIRED ENV VARS:
# - FLASK_SECRET_KEY
# - FIREBASE_API_KEY
# - GOOGLE_APPLICATION_CREDENTIALS (path to serviceAccountKey.json)
app.secret_key = os.getenv("FLASK_SECRET_KEY", "dev_change_me")
FIREBASE_API_KEY = os.getenv("FIREBASE_API_KEY")
SERVICE_ACCOUNT_JSON = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
# Friendly fallback: if GOOGLE_APPLICATION_CREDENTIALS is not set,
# try serviceAccountKey.json in the project folder.
if not SERVICE_ACCOUNT_JSON:
local_key = os.path.join(BASE_DIR, "serviceAccountKey.json")
if os.path.exists(local_key):
SERVICE_ACCOUNT_JSON = local_key
if not FIREBASE_API_KEY:
raise RuntimeError("Missing FIREBASE_API_KEY in .env")
if not SERVICE_ACCOUNT_JSON:
raise RuntimeError(
"Missing GOOGLE_APPLICATION_CREDENTIALS in .env (or serviceAccountKey.json not found next to app.py)"
)
if not firebase_admin._apps:
firebase_admin.initialize_app(credentials.Certificate(SERVICE_ACCOUNT_JSON))
db = firestore.client()
# OpenAI client (optional)
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
openai_client = OpenAI(api_key=OPENAI_API_KEY) if (OPENAI_API_KEY and OpenAI) else None
# ==============================
# Helpers
# ==============================
def login_required(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not session.get("uid"):
return jsonify({"error": "Not logged in"}), 401
return fn(*args, **kwargs)
return wrapper
def user_ref(uid: str):
return db.collection("users").document(uid)
def ensure_user_doc(uid: str, email: str, username: str = ""):
ref = user_ref(uid)
snap = ref.get()
if snap.exists:
return ref
ref.set(
{
"email": email,
"username": username,
"coins": 0,
"pet": {"hunger": 50, "thirst": 50, "health": 50, "happiness": 50},
"flashcard_counter": 0,
"todo_counter": 0,
"chat": {
# No logs stored. Just a persona/settings blob.
"persona": "You are a friendly virtual pet. Keep replies short, playful, and encouraging.",
},
}
)
return ref
def parse_int(v, default=None):
try:
return int(v)
except Exception:
return default
def next_counter(ref, field_name: str) -> int:
tx = db.transaction()
@firestore.transactional
def _inc(transaction):
snap = ref.get(transaction=transaction)
current = int(snap.get(field_name) or 0)
new_val = current + 1
transaction.update(ref, {field_name: new_val})
return new_val
return _inc(tx)
def firebase_password_login(email: str, password: str):
"""Firebase Admin SDK cannot verify email/password.
Use Firebase Auth REST API signInWithPassword.
"""
url = (
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword"
f"?key={FIREBASE_API_KEY}"
)
payload = {"email": email, "password": password, "returnSecureToken": True}
r = requests.post(url, json=payload, timeout=15)
if r.status_code != 200:
try:
code = r.json().get("error", {}).get("message", "LOGIN_FAILED")
except Exception:
code = "LOGIN_FAILED"
return None, code
return r.json(), None
# ==============================
# Pages
# ==============================
@app.get("/")
def root():
return redirect("/login.html")
@app.get("/login.html")
def login_page():
return send_from_directory("template", "login.html")
@app.get("/signup.html")
def signup_page():
return send_from_directory("template", "signup.html")
@app.get("/dashboard.html")
def dashboard_page():
return send_from_directory("template", "dashboard.html")
# ==============================
# Auth APIs
# ==============================
@app.post("/api/signup")
def api_signup():
body = request.get_json(silent=True) or {}
username = str(body.get("username", "")).strip()
email = str(body.get("email", "")).strip()
password = str(body.get("password", "")).strip()
if not username or not email or not password:
return jsonify({"error": "username, email, password required"}), 400
try:
u = auth.create_user(email=email, password=password, display_name=username)
ensure_user_doc(u.uid, email=email, username=username)
# auto login
data, err = firebase_password_login(email, password)
if err:
return jsonify({"error": "Signup succeeded, but login failed", "code": err}), 401
session["uid"] = data["localId"]
session["email"] = email
return jsonify({"ok": True})
except auth.EmailAlreadyExistsError:
return jsonify({"error": "Email already in use"}), 400
except Exception as e:
return jsonify({"error": "Signup failed", "detail": str(e)}), 400
@app.post("/api/login")
def api_login():
body = request.get_json(silent=True) or {}
email = str(body.get("email", "")).strip()
password = str(body.get("password", "")).strip()
if not email or not password:
return jsonify({"error": "email and password required"}), 400
data, err = firebase_password_login(email, password)
if err:
return jsonify({"error": err, "code": err}), 401
uid = data["localId"]
ensure_user_doc(uid, email=email)
session["uid"] = uid
session["email"] = email
return jsonify({"ok": True})
@app.post("/api/logout")
def api_logout():
session.clear()
return jsonify({"ok": True})
# ==============================
# Profile update
# ==============================
@app.put("/api/profile")
@login_required
def api_profile_update():
uid = session["uid"]
body = request.get_json(silent=True) or {}
username = str(body.get("username", "")).strip()
email = str(body.get("email", "")).strip()
new_password = body.get("password", None)
if not username or not email:
return jsonify({"error": "Username and email are required."}), 400
# Update Firebase Auth (Admin SDK)
try:
args = {"display_name": username, "email": email}
if new_password is not None and str(new_password).strip() != "":
args["password"] = str(new_password)
auth.update_user(uid, **args)
except Exception as e:
msg = str(e)
upper = msg.upper()
code = ""
if "WEAK_PASSWORD" in upper or "AT LEAST" in upper or "6" in upper:
code = "WEAK_PASSWORD"
elif "INVALID_EMAIL" in upper:
code = "INVALID_EMAIL"
elif "EMAIL_ALREADY_EXISTS" in upper or "EMAIL_EXISTS" in upper:
code = "EMAIL_EXISTS"
return jsonify({"error": "Profile update failed", "code": code, "detail": msg}), 400
# Update Firestore user doc
updates = {"username": username, "email": email}
if new_password is not None and str(new_password).strip() != "":
# We never store actual password, only length so you can render *****
updates["password_length"] = len(str(new_password))
user_ref(uid).set(updates, merge=True)
session["email"] = email
return jsonify({"ok": True})
# ==============================
# User Data
# ==============================
@app.get("/api/me")
@login_required
def api_me():
uid = session["uid"]
d = user_ref(uid).get().to_dict() or {}
d["uid"] = uid
return jsonify(d)
@app.put("/api/me")
@login_required
def api_update_me():
uid = session["uid"]
ref = user_ref(uid)
body = request.get_json(silent=True) or {}
updates = {}
if "username" in body:
updates["username"] = str(body["username"]).strip()
if "coins" in body:
coins = parse_int(body["coins"], None)
if coins is None or coins < 0:
return jsonify({"error": "coins must be non-negative int"}), 400
updates["coins"] = coins
if not updates:
return jsonify({"error": "No valid fields"}), 400
ref.update(updates)
return jsonify({"ok": True})
# ==============================
# Pet Data
# ==============================
@app.get("/api/pet")
@login_required
def api_get_pet():
uid = session["uid"]
d = user_ref(uid).get().to_dict() or {}
return jsonify(d.get("pet", {}))
@app.put("/api/pet")
@login_required
def api_update_pet():
uid = session["uid"]
ref = user_ref(uid)
body = request.get_json(silent=True) or {}
allowed = ["hunger", "thirst", "health", "happiness"]
pet_updates = {}
for k in allowed:
if k in body:
v = parse_int(body[k], None)
if v is None or v < 0:
return jsonify({"error": f"{k} must be non-negative int"}), 400
pet_updates[f"pet.{k}"] = v
if not pet_updates:
return jsonify({"error": "No valid pet fields"}), 400
ref.update(pet_updates)
return jsonify({"ok": True})
# ==============================
# Flashcards
# ==============================
@app.get("/api/flashcards")
@login_required
def api_list_flashcards():
uid = session["uid"]
out = []
for doc in user_ref(uid).collection("flashcards").stream():
d = doc.to_dict()
d["id"] = doc.id
out.append(d)
out.sort(key=lambda x: int(x.get("number", 0)))
return jsonify(out)
@app.post("/api/flashcards")
@login_required
def api_create_flashcard():
uid = session["uid"]
uref = user_ref(uid)
body = request.get_json(silent=True) or {}
front = str(body.get("front", "")).strip()
back = str(body.get("back", "")).strip()
if not front or not back:
return jsonify({"error": "front and back required"}), 400
number = next_counter(uref, "flashcard_counter")
doc_ref = uref.collection("flashcards").document()
doc_ref.set({"number": number, "front": front, "back": back})
return jsonify({"ok": True, "id": doc_ref.id, "number": number}), 201
# ==============================
# Todos
# ==============================
@app.get("/api/todos")
@login_required
def api_list_todos():
uid = session["uid"]
out = []
for doc in user_ref(uid).collection("todos").stream():
d = doc.to_dict()
d["id"] = doc.id
out.append(d)
out.sort(key=lambda x: int(x.get("number", 0)))
return jsonify(out)
@app.post("/api/todos")
@login_required
def api_create_todo():
uid = session["uid"]
uref = user_ref(uid)
body = request.get_json(silent=True) or {}
todo_name = str(body.get("todo_name", "")).strip()
coin_worth = parse_int(body.get("coin_worth", 0), None)
if not todo_name:
return jsonify({"error": "todo_name required"}), 400
if coin_worth is None or coin_worth < 0:
return jsonify({"error": "coin_worth must be non-negative int"}), 400
number = next_counter(uref, "todo_counter")
doc_ref = uref.collection("todos").document()
doc_ref.set({"number": number, "todo_name": todo_name, "coin_worth": coin_worth, "done": False})
return jsonify({"ok": True, "id": doc_ref.id, "number": number}), 201
# ==============================
# AI Daily Quest (3 per day)
# ==============================
QUEST_BANK = [
"Do a 10-minute review of today’s notes and write 3 key takeaways.",
"Solve 3 practice problems from your current topic and check one mistake.",
"Make 5 flashcards for a chapter/lecture and test yourself once.",
"Write a 4-sentence summary of what you learned today in your own words.",
"Spend 15 minutes cleaning up your to-do list: prioritize top 3 tasks.",
"Write a small function (10–20 lines) to practice a concept you’re learning (loops, lists, recursion).",
"Refactor one small piece of code: rename variables + add 2 helpful comments.",
"Do 1 LeetCode easy (or similar) and write down the core idea in 2 sentences.",
"Explain a CS concept to your pet in 3 sentences (e.g., stacks vs queues).",
"Work 2 math/physics drills and note 1 pattern you noticed.",
"Draw a diagram for a physics problem and label forces/known values.",
"Pick 1 formula you keep forgetting and create a memory cue for it.",
]
def _utc_date_key():
return datetime.datetime.utcnow().strftime("%Y-%m-%d")
def _pick_three_quests(seed_key: str):
rng = random.Random(seed_key)
bank = QUEST_BANK[:]
rng.shuffle(bank)
return bank[:3]
def _ensure_daily_quests(uid: str):
date_key = _utc_date_key()
ref = db.collection("users").document(uid).collection("daily_quests").document(date_key)
doc = ref.get()
if doc.exists:
return doc.to_dict(), date_key
quests = _pick_three_quests(seed_key=f"{uid}:{date_key}")
payload = {
"date": date_key,
"created_at": firestore.SERVER_TIMESTAMP,
"quests": [
{"qid": "q1", "text": quests[0], "done": False, "reward": 10},
{"qid": "q2", "text": quests[1], "done": False, "reward": 10},
{"qid": "q3", "text": quests[2], "done": False, "reward": 10},
],
}
ref.set(payload)
return payload, date_key
@app.get("/api/daily_quests")
@login_required
def api_daily_quests():
uid = session["uid"]
data, date_key = _ensure_daily_quests(uid)
return jsonify({"date": date_key, "quests": data.get("quests", [])})
@app.post("/api/daily_quests/complete")
@login_required
def api_daily_quests_complete():
uid = session["uid"]
body = request.get_json(silent=True) or {}
qid = body.get("qid")
if not qid:
return jsonify({"error": "Missing qid"}), 400
data, date_key = _ensure_daily_quests(uid)
ref = db.collection("users").document(uid).collection("daily_quests").document(date_key)
quests = data.get("quests", [])
idx = next((i for i, q in enumerate(quests) if q.get("qid") == qid), None)
if idx is None:
return jsonify({"error": "Quest not found"}), 404
if quests[idx].get("done") is True:
user_doc = user_ref(uid).get().to_dict() or {}
return jsonify({"ok": True, "already": True, "coins": user_doc.get("coins", 0)})
reward = int(quests[idx].get("reward", 10))
@firestore.transactional
def _tx_complete(tx):
qsnap = ref.get(transaction=tx)
qdata = qsnap.to_dict() or {}
qlist = qdata.get("quests", [])
for q in qlist:
if q.get("qid") == qid:
if q.get("done") is True:
return False
q["done"] = True
tx.set(ref, {"quests": qlist}, merge=True)
uref = user_ref(uid)
usnap = uref.get(transaction=tx)
udata = usnap.to_dict() or {}
current = int(udata.get("coins", 0))
tx.set(uref, {"coins": current + reward}, merge=True)
return True
tx = db.transaction()
changed = _tx_complete(tx)
user_doc = user_ref(uid).get().to_dict() or {}
return jsonify({"ok": True, "updated": bool(changed), "coins": user_doc.get("coins", 0), "reward": reward})
# ==============================
# AI Pet Chat (no persistence)
# ==============================
@app.post("/api/petchat")
@login_required
def api_petchat():
body = request.get_json(silent=True) or {}
user_msg = (body.get("message") or "").strip()
if not user_msg:
return jsonify({"error": "Message is empty"}), 400
if openai_client is None:
return jsonify({"error": "OPENAI_API_KEY missing (or openai not installed)"}), 500
system_prompt = (
"You are 'Kat', a cute virtual pet tutor.\n"
"Personality: friendly, upbeat, supportive; short + clear by default.\n"
"Educational rules: If user asks school questions, teach step-by-step, explain reasoning, and check understanding. "
"Ask 1 clarifying question if needed. Never give only a final answer without explanation. Encourage good study habits."
)
try:
resp = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_msg},
],
temperature=0.7,
max_tokens=350,
)
reply = (resp.choices[0].message.content or "").strip()
return jsonify({"reply": reply})
except Exception as e:
return jsonify({"error": "Pet chat failed", "detail": str(e)}), 500
# ==============================
# Run
# ==============================
if __name__ == "__main__":
# IMPORTANT: run on ONE port only.
# Use PORT if set, otherwise default to 5001 (matches your JS logs).
port = int(os.getenv("PORT", "5001"))
app.run(host="127.0.0.1", port=port, debug=True)