Shreesha-2011 commited on
Commit
38ce9bf
Β·
1 Parent(s): 0f9b3f8

Add Supabase auth + per-user sessions/flashcards

Browse files
Files changed (3) hide show
  1. .env +3 -0
  2. app.py +183 -11
  3. requirements.txt +2 -0
.env CHANGED
@@ -4,3 +4,6 @@ EDUAI_DATA_DIR=/tmp/data
4
  EDUAI_LLM_MODEL_FILE=Llama-3.2-1B-Instruct-Q4_K_M.gguf
5
  EDUAI_CONTEXT_SIZE=2048
6
  EDUAI_ASR_COMPUTE_TYPE=int8
 
 
 
 
4
  EDUAI_LLM_MODEL_FILE=Llama-3.2-1B-Instruct-Q4_K_M.gguf
5
  EDUAI_CONTEXT_SIZE=2048
6
  EDUAI_ASR_COMPUTE_TYPE=int8
7
+ SUPABASE_URL=https://mqbbccfzbtgnxbuopqtz.supabase.co
8
+ SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1xYmJjY2Z6YnRnbnhidW9wcXR6Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc4MjMwNTQ4MSwiZXhwIjoyMDk3ODgxNDgxfQ.2OHLqUmdss32OSSqhHdxJ75jYDbzAiAHYO8OKNHD-RU
9
+ SUPABASE_JWT_SECRET=o5KFsEwKHGulJbVqgh1egVjGO3sF8h2w2zygJ6EJYJPS+I47XxYz+C/wf1XwfhAuime9ft1WHOZkYAqpZYZmRg==
app.py CHANGED
@@ -20,11 +20,13 @@ from functools import partial
20
  PROJECT_ROOT = Path(__file__).resolve().parent
21
  sys.path.insert(0, str(PROJECT_ROOT))
22
 
23
- from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request
24
  from fastapi.middleware.cors import CORSMiddleware
25
  from fastapi.responses import JSONResponse, Response
26
  from pydantic import BaseModel
27
  import uvicorn
 
 
28
 
29
  from core.settings import load_settings
30
  from core.session_manager import SessionManager
@@ -199,6 +201,19 @@ async def lifespan(app):
199
  "messages": [{"role": "system", "content": SYSTEM_PROMPT}],
200
  })
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  # Start a fresh session
203
  session_mgr.start_new_session({"role": "system", "content": SYSTEM_PROMPT})
204
  state["protected_names"] = _get_protected_sources()
@@ -248,6 +263,32 @@ app.add_middleware(
248
  )
249
 
250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  # ──────────────────────────────────────────────
252
  # Helpers
253
  # ──────────────────────────────────────────────
@@ -417,7 +458,7 @@ async def health():
417
 
418
 
419
  @app.post("/api/chat")
420
- async def chat(req: ChatRequest):
421
  """Send a message and get an AI response."""
422
  loop = asyncio.get_event_loop()
423
  answer, mode = await loop.run_in_executor(
@@ -433,7 +474,50 @@ async def chat(req: ChatRequest):
433
  cards = parse_flashcards(answer)
434
  if cards:
435
  parsed = {"type": "flashcard", "cards": cards}
 
436
  state["review"].add_cards(cards, req.prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
 
438
  return {"answer": answer, "mode": mode, "parsed": parsed}
439
 
@@ -487,13 +571,24 @@ async def upload_file(file: UploadFile = File(...)):
487
  # ── Sessions ──
488
 
489
  @app.get("/api/sessions")
490
- async def list_sessions():
 
 
 
 
 
491
  sessions = state["session_mgr"].list_sessions()
492
  return {"sessions": sessions}
493
 
494
 
495
  @app.post("/api/sessions/new")
496
- async def new_session():
 
 
 
 
 
 
497
  state["session_mgr"].save_messages(state["messages"])
498
  sys_msg = {"role": "system", "content": SYSTEM_PROMPT}
499
  state["messages"] = [sys_msg]
@@ -501,8 +596,21 @@ async def new_session():
501
  return {"status": "ok"}
502
 
503
 
504
- @app.get("/api/sessions/{index}")
505
- async def load_session(index: int):
 
 
 
 
 
 
 
 
 
 
 
 
 
506
  sys_msg = {"role": "system", "content": SYSTEM_PROMPT}
507
  loaded = state["session_mgr"].load_session(index, sys_msg)
508
  if loaded is None:
@@ -511,8 +619,17 @@ async def load_session(index: int):
511
  return {"messages": [m for m in loaded if m["role"] != "system"]}
512
 
513
 
514
- @app.delete("/api/sessions/{index}")
515
- async def delete_session(index: int):
 
 
 
 
 
 
 
 
 
516
  title = state["session_mgr"].delete_session(index)
517
  return {"deleted": title or "unknown"}
518
 
@@ -583,18 +700,55 @@ async def remove_source(index: int):
583
  # ── Review / Flashcards ──
584
 
585
  @app.get("/api/review/stats")
586
- async def review_stats():
 
 
 
 
 
 
587
  return state["review"].get_stats()
588
 
589
 
590
  @app.get("/api/review/due")
591
- async def review_due():
 
 
 
 
592
  cards = state["review"].get_due_cards()
593
  return {"cards": cards}
594
 
595
 
596
  @app.post("/api/review/rate")
597
- async def review_rate(req: RateRequest):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
598
  interval = state["review"].record_answer(req.card_id, req.quality)
599
  return {"interval": interval}
600
 
@@ -618,6 +772,24 @@ async def text_to_speech(req: ChatRequest):
618
  raise HTTPException(status_code=500, detail=str(e))
619
 
620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621
  # ──────────────────────────────────────────────
622
  # Entry point
623
  # ──────────────────────────────────────────────
 
20
  PROJECT_ROOT = Path(__file__).resolve().parent
21
  sys.path.insert(0, str(PROJECT_ROOT))
22
 
23
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Depends
24
  from fastapi.middleware.cors import CORSMiddleware
25
  from fastapi.responses import JSONResponse, Response
26
  from pydantic import BaseModel
27
  import uvicorn
28
+ import jwt as pyjwt
29
+ from datetime import date, timedelta, datetime
30
 
31
  from core.settings import load_settings
32
  from core.session_manager import SessionManager
 
201
  "messages": [{"role": "system", "content": SYSTEM_PROMPT}],
202
  })
203
 
204
+ # Supabase client (optional)
205
+ sb_url = os.getenv("SUPABASE_URL", "")
206
+ sb_key = os.getenv("SUPABASE_SERVICE_KEY", "")
207
+ if sb_url and sb_key:
208
+ try:
209
+ from supabase import create_client
210
+ state["sb"] = create_client(sb_url, sb_key)
211
+ log.info("Supabase client initialized.")
212
+ except Exception as e:
213
+ log.warning(f"Supabase init failed (running without auth): {e}")
214
+ else:
215
+ log.warning("Supabase not configured β€” running without auth.")
216
+
217
  # Start a fresh session
218
  session_mgr.start_new_session({"role": "system", "content": SYSTEM_PROMPT})
219
  state["protected_names"] = _get_protected_sources()
 
263
  )
264
 
265
 
266
+ # ── Auth dependency ──
267
+
268
+ async def get_current_user(request: Request) -> str | None:
269
+ """Extract and verify user_id from Bearer token. Returns None if no auth."""
270
+ sb = state.get("sb")
271
+ if not sb:
272
+ return None # No auth configured β€” allow anonymous
273
+
274
+ auth_header = request.headers.get("authorization", "")
275
+ if not auth_header.startswith("Bearer "):
276
+ return None # Allow unauthenticated requests to fall back
277
+
278
+ token = auth_header[7:]
279
+ try:
280
+ jwt_secret = os.getenv("SUPABASE_JWT_SECRET", "")
281
+ payload = pyjwt.decode(token, jwt_secret, algorithms=["HS256"], audience="authenticated")
282
+ user_id = payload.get("sub")
283
+ if not user_id:
284
+ raise HTTPException(status_code=401, detail="Invalid token: no user ID")
285
+ return user_id
286
+ except pyjwt.ExpiredSignatureError:
287
+ raise HTTPException(status_code=401, detail="Token expired")
288
+ except pyjwt.InvalidTokenError as e:
289
+ raise HTTPException(status_code=401, detail=f"Invalid token: {e}")
290
+
291
+
292
  # ──────────────────────────────────────────────
293
  # Helpers
294
  # ──────────────────────────────────────────────
 
458
 
459
 
460
  @app.post("/api/chat")
461
+ async def chat(req: ChatRequest, user_id: str | None = Depends(get_current_user)):
462
  """Send a message and get an AI response."""
463
  loop = asyncio.get_event_loop()
464
  answer, mode = await loop.run_in_executor(
 
474
  cards = parse_flashcards(answer)
475
  if cards:
476
  parsed = {"type": "flashcard", "cards": cards}
477
+ # Save flashcards to file-based storage (always)
478
  state["review"].add_cards(cards, req.prompt)
479
+ # Also save to Supabase if user is authenticated
480
+ sb = state.get("sb")
481
+ if sb and user_id:
482
+ for card in cards:
483
+ try:
484
+ sb.table("flashcards").insert({
485
+ "user_id": user_id,
486
+ "front": card.get("front", ""),
487
+ "back": card.get("back", ""),
488
+ "source_prompt": req.prompt[:200],
489
+ }).execute()
490
+ except Exception as e:
491
+ log.error(f"Failed to save flashcard to Supabase: {e}")
492
+
493
+ # Save chat to Supabase if authenticated
494
+ sb = state.get("sb")
495
+ if sb and user_id:
496
+ try:
497
+ # Get most recent session or create one
498
+ sessions_res = sb.table("chat_sessions").select("id,title").eq("user_id", user_id).order("updated_at", desc=True).limit(1).execute()
499
+ if sessions_res.data:
500
+ session_id = sessions_res.data[0]["id"]
501
+ session_title = sessions_res.data[0]["title"]
502
+ else:
503
+ new_s = sb.table("chat_sessions").insert({"user_id": user_id, "title": req.prompt[:60]}).execute()
504
+ session_id = new_s.data[0]["id"]
505
+ session_title = req.prompt[:60]
506
+
507
+ # Save user + assistant messages
508
+ sb.table("chat_messages").insert([
509
+ {"session_id": session_id, "role": "user", "content": req.prompt},
510
+ {"session_id": session_id, "role": "assistant", "content": answer},
511
+ ]).execute()
512
+
513
+ # Update session metadata
514
+ msg_count = sb.table("chat_messages").select("id", count="exact").eq("session_id", session_id).neq("role", "system").execute()
515
+ update_data = {"message_count": msg_count.count or 0, "updated_at": datetime.utcnow().isoformat()}
516
+ if session_title == "Untitled Session":
517
+ update_data["title"] = req.prompt[:60]
518
+ sb.table("chat_sessions").update(update_data).eq("id", session_id).execute()
519
+ except Exception as e:
520
+ log.error(f"Failed to save chat to Supabase: {e}")
521
 
522
  return {"answer": answer, "mode": mode, "parsed": parsed}
523
 
 
571
  # ── Sessions ──
572
 
573
  @app.get("/api/sessions")
574
+ async def list_sessions(user_id: str | None = Depends(get_current_user)):
575
+ sb = state.get("sb")
576
+ if sb and user_id:
577
+ res = sb.table("chat_sessions").select("*").eq("user_id", user_id).order("updated_at", desc=True).execute()
578
+ return {"sessions": [{"id": s["id"], "title": s["title"], "created_at": s["created_at"], "updated_at": s["updated_at"], "message_count": s["message_count"]} for s in res.data]}
579
+ # Fallback: file-based
580
  sessions = state["session_mgr"].list_sessions()
581
  return {"sessions": sessions}
582
 
583
 
584
  @app.post("/api/sessions/new")
585
+ async def new_session(user_id: str | None = Depends(get_current_user)):
586
+ sb = state.get("sb")
587
+ if sb and user_id:
588
+ sb.table("chat_sessions").insert({"user_id": user_id}).execute()
589
+ state["messages"] = [{"role": "system", "content": SYSTEM_PROMPT}]
590
+ return {"status": "ok"}
591
+ # Fallback: file-based
592
  state["session_mgr"].save_messages(state["messages"])
593
  sys_msg = {"role": "system", "content": SYSTEM_PROMPT}
594
  state["messages"] = [sys_msg]
 
596
  return {"status": "ok"}
597
 
598
 
599
+ @app.get("/api/sessions/{session_id}")
600
+ async def load_session(session_id: str, user_id: str | None = Depends(get_current_user)):
601
+ sb = state.get("sb")
602
+ if sb and user_id:
603
+ # Verify session belongs to user
604
+ session = sb.table("chat_sessions").select("id").eq("id", session_id).eq("user_id", user_id).execute()
605
+ if not session.data:
606
+ raise HTTPException(status_code=404, detail="Session not found")
607
+ msgs = sb.table("chat_messages").select("role, content").eq("session_id", session_id).order("created_at", desc=False).execute()
608
+ return {"messages": [{"role": m["role"], "content": m["content"]} for m in msgs.data if m["role"] != "system"]}
609
+ # Fallback: file-based (index is an int)
610
+ try:
611
+ index = int(session_id)
612
+ except ValueError:
613
+ raise HTTPException(status_code=400, detail="Invalid session index")
614
  sys_msg = {"role": "system", "content": SYSTEM_PROMPT}
615
  loaded = state["session_mgr"].load_session(index, sys_msg)
616
  if loaded is None:
 
619
  return {"messages": [m for m in loaded if m["role"] != "system"]}
620
 
621
 
622
+ @app.delete("/api/sessions/{session_id}")
623
+ async def delete_session(session_id: str, user_id: str | None = Depends(get_current_user)):
624
+ sb = state.get("sb")
625
+ if sb and user_id:
626
+ sb.table("chat_sessions").delete().eq("id", session_id).eq("user_id", user_id).execute()
627
+ return {"deleted": session_id}
628
+ # Fallback: file-based
629
+ try:
630
+ index = int(session_id)
631
+ except ValueError:
632
+ raise HTTPException(status_code=400, detail="Invalid session index")
633
  title = state["session_mgr"].delete_session(index)
634
  return {"deleted": title or "unknown"}
635
 
 
700
  # ── Review / Flashcards ──
701
 
702
  @app.get("/api/review/stats")
703
+ async def review_stats(user_id: str | None = Depends(get_current_user)):
704
+ sb = state.get("sb")
705
+ if sb and user_id:
706
+ total = sb.table("flashcards").select("id", count="exact").eq("user_id", user_id).execute()
707
+ due = sb.table("flashcards").select("id", count="exact").eq("user_id", user_id).lte("next_review", date.today().isoformat()).execute()
708
+ mastered = sb.table("flashcards").select("id", count="exact").eq("user_id", user_id).gte("repetitions", 5).execute()
709
+ return {"total": total.count or 0, "due": due.count or 0, "mastered": mastered.count or 0}
710
  return state["review"].get_stats()
711
 
712
 
713
  @app.get("/api/review/due")
714
+ async def review_due(user_id: str | None = Depends(get_current_user)):
715
+ sb = state.get("sb")
716
+ if sb and user_id:
717
+ res = sb.table("flashcards").select("*").eq("user_id", user_id).lte("next_review", date.today().isoformat()).execute()
718
+ return {"cards": res.data}
719
  cards = state["review"].get_due_cards()
720
  return {"cards": cards}
721
 
722
 
723
  @app.post("/api/review/rate")
724
+ async def review_rate(req: RateRequest, user_id: str | None = Depends(get_current_user)):
725
+ sb = state.get("sb")
726
+ if sb and user_id:
727
+ card_res = sb.table("flashcards").select("*").eq("id", req.card_id).eq("user_id", user_id).execute()
728
+ if not card_res.data:
729
+ raise HTTPException(status_code=404, detail="Card not found")
730
+ card = card_res.data[0]
731
+
732
+ q = req.quality
733
+ ef = card["easiness"]
734
+ rep = card["repetitions"]
735
+ ivl = card["interval"]
736
+
737
+ ef = max(1.3, ef + 0.1 - (5 - q) * (0.08 + (5 - q) * 0.02))
738
+ if q < 3:
739
+ rep = 0
740
+ ivl = 1
741
+ else:
742
+ rep += 1
743
+ if rep == 1: ivl = 1
744
+ elif rep == 2: ivl = 6
745
+ else: ivl = round(ivl * ef)
746
+
747
+ next_date = (date.today() + timedelta(days=ivl)).isoformat()
748
+ sb.table("flashcards").update({
749
+ "easiness": ef, "interval": ivl, "repetitions": rep, "next_review": next_date
750
+ }).eq("id", req.card_id).execute()
751
+ return {"interval": ivl}
752
  interval = state["review"].record_answer(req.card_id, req.quality)
753
  return {"interval": interval}
754
 
 
772
  raise HTTPException(status_code=500, detail=str(e))
773
 
774
 
775
+ # ── Profile ──
776
+
777
+ @app.get("/api/auth/profile")
778
+ async def get_profile(user_id: str | None = Depends(get_current_user)):
779
+ sb = state.get("sb")
780
+ if not sb or not user_id:
781
+ return {"authenticated": False}
782
+ try:
783
+ res = sb.table("profiles").select("*").eq("id", user_id).execute()
784
+ if not res.data:
785
+ return {"authenticated": False}
786
+ p = res.data[0]
787
+ return {"authenticated": True, "user_id": user_id, "display_name": p["display_name"], "avatar_url": p.get("avatar_url", "")}
788
+ except Exception as e:
789
+ log.error(f"Profile fetch error: {e}")
790
+ return {"authenticated": False}
791
+
792
+
793
  # ──────────────────────────────────────────────
794
  # Entry point
795
  # ──────────────────────────────────────────────
requirements.txt CHANGED
@@ -7,3 +7,5 @@ soundfile==0.13.1
7
  numpy<2
8
  huggingface_hub
9
  python-multipart
 
 
 
7
  numpy<2
8
  huggingface_hub
9
  python-multipart
10
+ supabase
11
+ PyJWT[crypto]