alesamodio commited on
Commit
5dd8014
Β·
1 Parent(s): 974aeab

remove streamlit from config

Browse files
Files changed (2) hide show
  1. app.py +33 -37
  2. config.py +0 -35
app.py CHANGED
@@ -1,5 +1,7 @@
1
  # app.py (for Hugging Face Docker space)
2
 
 
 
3
  from fastapi import FastAPI, Header, HTTPException
4
  from pydantic import BaseModel
5
  from typing import Optional
@@ -29,47 +31,41 @@ async def chat_send(
29
  body: ChatRequest,
30
  authorization: Optional[str] = Header(default=None),
31
  ):
32
- """
33
- Main endpoint used by the mobile app.
34
- For now:
35
- - Use username to find user_id + profile in Supabase.
36
- - Ignore JWT verification (authorization header) or just log it.
37
- Later:
38
- - Verify JWT, extract user_id directly from token.
39
- """
40
-
41
- message = body.message.strip()
42
- username = body.username.strip()
43
-
44
- if not message:
45
  raise HTTPException(status_code=400, detail="Empty message")
46
 
47
- # TODO (later): parse/verify JWT if you want:
48
- # if authorization and authorization.startswith("Bearer "):
49
- # token = authorization.split(" ", 1)[1]
50
- # user_id = verify_and_get_user_id_from_token(token)
51
- # else:
52
- # ...
 
 
 
 
 
53
 
54
- # For now, derive user_id from username via Supabase (simple helper)
55
  try:
56
- # You can write this helper to look up user_profiles where username == body.username
57
- profile, user_id = get_user_profile_by_username(username)
58
- except Exception as e:
59
- # fallback: use username as id if lookup fails (dev only)
60
- user_id = username
61
- profile = {}
62
-
63
- # Call the core Socrates pipeline
64
- reply_text = socrates_reply(
65
- user_id=user_id,
66
- username=username,
67
- user_msg=message,
68
- profile=profile,
69
- ui_lang="en", # or from profile / user_ui_language table later
70
- )
71
-
72
- return {"reply": reply_text}
73
 
74
 
75
 
 
1
  # app.py (for Hugging Face Docker space)
2
 
3
+
4
+ import jwt
5
  from fastapi import FastAPI, Header, HTTPException
6
  from pydantic import BaseModel
7
  from typing import Optional
 
31
  body: ChatRequest,
32
  authorization: Optional[str] = Header(default=None),
33
  ):
34
+ # 1) get user_id from the JWT
35
+ user_id = get_user_id_from_jwt(authorization)
36
+
37
+ # 2) simple test reply for now
38
+ msg = body.message.strip()
39
+ if not msg:
 
 
 
 
 
 
 
40
  raise HTTPException(status_code=400, detail="Empty message")
41
 
42
+ short_id = user_id[:8]
43
+
44
+ return {
45
+ "reply": f"Socrates (user_id={short_id}…) says: {msg[::-1]}",
46
+ }
47
+
48
+ def get_user_id_from_jwt(authorization: Optional[str]) -> str:
49
+ if not authorization or not authorization.startswith("Bearer "):
50
+ raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
51
+
52
+ token = authorization.split(" ", 1)[1]
53
 
 
54
  try:
55
+ payload = jwt.decode(
56
+ token,
57
+ SUPABASE_JWT_SECRET,
58
+ algorithms=["HS256"],
59
+ options={"verify_aud": False}, # keep simple for now
60
+ )
61
+ except jwt.InvalidTokenError:
62
+ raise HTTPException(status_code=401, detail="Invalid token")
63
+
64
+ user_id = payload.get("sub")
65
+ if not user_id:
66
+ raise HTTPException(status_code=401, detail="Token missing subject (user id)")
67
+
68
+ return user_id
 
 
 
69
 
70
 
71
 
config.py CHANGED
@@ -1,17 +1,8 @@
1
  import os
2
  import re
3
- import streamlit as st
4
 
5
  def _get(name: str, required: bool = True, default=None):
6
- # 1) Environment variables (HF / Render)
7
  val = os.getenv(name)
8
- if val is None:
9
- # 2) Optional Streamlit Cloud fallback
10
- try:
11
- import streamlit as st
12
- val = st.secrets.get(name)
13
- except Exception:
14
- val = None
15
  if val is None:
16
  if required:
17
  raise RuntimeError(f"Missing required secret: {name}")
@@ -56,32 +47,6 @@ def username_from_email(email: str | None) -> str:
56
  safe = _USERNAME_SAFE_RE.sub("-", local).strip("-")
57
  return safe or "user"
58
 
59
- # ── Session β†’ globals refresh (no external deps) ───────────────────────────────
60
- def refresh_user_context() -> None:
61
- """
62
- Re-sync legacy globals from Streamlit session after login.
63
- """
64
- user_id = st.session_state.get("uuid")
65
- email = st.session_state.get("email")
66
- username = st.session_state.get("username") or username_from_email(email)
67
-
68
- # ── Public getters used across the app ────────────────────────────────────────
69
- def get_uuid() -> str | None:
70
- """
71
- Preferred source: st.session_state['uuid'].
72
- """
73
- return st.session_state.get("uuid")
74
 
75
- def get_username() -> str | None:
76
- """
77
- Preferred: st.session_state['username'] (email-derived).
78
- Fallbacks (in order):
79
- - derive from st.session_state['email']
80
- """
81
- return (
82
- st.session_state.get("username")
83
- or username_from_email(st.session_state.get("email"))
84
- )
85
 
86
- # Reusable headers for PostgREST / RPC calls
87
 
 
1
  import os
2
  import re
 
3
 
4
  def _get(name: str, required: bool = True, default=None):
 
5
  val = os.getenv(name)
 
 
 
 
 
 
 
6
  if val is None:
7
  if required:
8
  raise RuntimeError(f"Missing required secret: {name}")
 
47
  safe = _USERNAME_SAFE_RE.sub("-", local).strip("-")
48
  return safe or "user"
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
 
 
 
 
 
 
 
 
 
 
51
 
 
52