Spaces:
Sleeping
Sleeping
Ujjwal Patil commited on
Commit ·
d143e1a
0
Parent(s):
Initial Commit: Production-Ready AI Codebase
Browse files- Dockerfile +29 -0
- app/__init__.py +0 -0
- app/ai/__init__.py +0 -0
- app/ai/service.py +140 -0
- app/api/__init__.py +0 -0
- app/api/analysis.py +27 -0
- app/api/games.py +63 -0
- app/api/journal.py +112 -0
- app/api/profile.py +63 -0
- app/core/__init__.py +0 -0
- app/core/config.py +17 -0
- app/core/ratelimit.py +10 -0
- app/core/security.py +63 -0
- app/main.py +52 -0
- app/schemas/__init__.py +0 -0
- app/schemas/analysis.py +15 -0
- app/services/__init__.py +0 -0
- app/utils/__init__.py +0 -0
- app/utils/supabase.py +102 -0
- database/schema.sql +61 -0
- requirements.txt +12 -0
- scripts/analyze_dataset.py +17 -0
- scripts/health_check.py +87 -0
Dockerfile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use the official Python 3.11 image
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Set the working directory in the container
|
| 5 |
+
WORKDIR /code
|
| 6 |
+
|
| 7 |
+
# Install system dependencies (needed for some ML libraries)
|
| 8 |
+
RUN apt-get update && apt-get install -y \
|
| 9 |
+
build-essential \
|
| 10 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
+
|
| 12 |
+
# Copy the requirements file into the container
|
| 13 |
+
COPY ./requirements.txt /code/requirements.txt
|
| 14 |
+
|
| 15 |
+
# Install the Python dependencies
|
| 16 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
| 17 |
+
|
| 18 |
+
# Copy the entire backend directory into the container
|
| 19 |
+
COPY . /code
|
| 20 |
+
|
| 21 |
+
# Set environment variables (Supabase, etc. will be set in HF Space settings)
|
| 22 |
+
ENV PYTHONUNBUFFERED=1
|
| 23 |
+
|
| 24 |
+
# Expose the port Hugging Face Spaces expects
|
| 25 |
+
EXPOSE 7860
|
| 26 |
+
|
| 27 |
+
# Start the FastAPI server using uvicorn
|
| 28 |
+
# We use port 7860 because that is the default for HF Spaces
|
| 29 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
app/__init__.py
ADDED
|
File without changes
|
app/ai/__init__.py
ADDED
|
File without changes
|
app/ai/service.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import pipeline # type: ignore
|
| 2 |
+
from typing import Dict, Any
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 6 |
+
MODEL_NAME = os.path.join(BASE_DIR, "models")
|
| 7 |
+
|
| 8 |
+
# Load model at module level (singleton)
|
| 9 |
+
sentiment_ai = pipeline( # type: ignore
|
| 10 |
+
"sentiment-analysis",
|
| 11 |
+
model=MODEL_NAME,
|
| 12 |
+
tokenizer=MODEL_NAME,
|
| 13 |
+
top_k=None
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# ---------------- HELPERS ----------------
|
| 18 |
+
|
| 19 |
+
def clamp(v: int, min_v: int = 1, max_v: int = 10) -> int:
|
| 20 |
+
return max(min_v, min(max_v, v))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ---------------- ENGLISH MAPS ----------------
|
| 24 |
+
|
| 25 |
+
ENG_EMOTION_MAP = {
|
| 26 |
+
"positive": "Happy",
|
| 27 |
+
"negative": "Sad",
|
| 28 |
+
"neutral": "Neutral",
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
ENG_SUMMARY_MAP = {
|
| 32 |
+
"positive": "You're feeling emotionally positive today.",
|
| 33 |
+
"negative": "You seem emotionally overwhelmed today.",
|
| 34 |
+
"neutral": "Your mood feels calm and balanced.",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
ENG_TIPS_MAP = {
|
| 38 |
+
"positive": ["Celebrate small wins", "Share your happiness"],
|
| 39 |
+
"negative": ["Pause and breathe", "Talk to someone you trust"],
|
| 40 |
+
"neutral": ["Reflect calmly", "Plan something meaningful"],
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# ---------------- MARATHI MAPS ----------------
|
| 44 |
+
|
| 45 |
+
MAR_EMOTION_MAP = {
|
| 46 |
+
"positive": "आनंदी",
|
| 47 |
+
"negative": "दुःखी",
|
| 48 |
+
"neutral": "शांत/तटस्थ",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
MAR_SUMMARY_MAP = {
|
| 52 |
+
"positive": "तुम्हाला आज खूप सकारात्मक आणि उत्साही वाटत आहे.",
|
| 53 |
+
"negative": "तुम्ही थोडे अस्वस्थ किंवा दुःखी असल्याचे जाणवत आहे. स्वतःची काळजी घ्या.",
|
| 54 |
+
"neutral": "तुमची मनःस्थिती आज संतुलित आणि शांत आहे.",
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
MAR_TIPS_MAP = {
|
| 58 |
+
"positive": ["ही आनंदाची क्षणे साजरी करा", "तुमचा आनंद इतरांसोबत शेअर करा"],
|
| 59 |
+
"negative": ["दीर्घ श्वास घ्या आणि थोडा वेळ विश्रांती घ्या", "तुमच्या जवळच्या व्यक्तीशी बोला"],
|
| 60 |
+
"neutral": ["आजचा दिवस नियोजित करा", "शांतपणे विचार करा"],
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
# ---------------- GLOBAL MAPS ----------------
|
| 64 |
+
|
| 65 |
+
EMOJI_MAP = {
|
| 66 |
+
"positive": "😊",
|
| 67 |
+
"negative": "😔",
|
| 68 |
+
"neutral": "😐",
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
COLOR_MAP = {
|
| 72 |
+
"positive": "#22c55e",
|
| 73 |
+
"negative": "#ef4444",
|
| 74 |
+
"neutral": "#facc15",
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ---------------- MAIN ----------------
|
| 79 |
+
|
| 80 |
+
def analyze_mood(text: str, language: str = "English") -> Dict[str, Any]:
|
| 81 |
+
text = text.strip()
|
| 82 |
+
if not text:
|
| 83 |
+
raise ValueError("Text cannot be empty.")
|
| 84 |
+
|
| 85 |
+
is_marathi = language.lower() in ["marathi", "mr"]
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
results = sentiment_ai(text)[0] # type: ignore
|
| 89 |
+
scores = {r["label"].lower(): float(r["score"]) for r in results}
|
| 90 |
+
|
| 91 |
+
# Primary prediction (top)
|
| 92 |
+
label = results[0]["label"].lower()
|
| 93 |
+
score = float(results[0]["score"])
|
| 94 |
+
|
| 95 |
+
# Normalize to sentiment key
|
| 96 |
+
if label == "positive":
|
| 97 |
+
sentiment = "positive"
|
| 98 |
+
elif label == "negative":
|
| 99 |
+
sentiment = "negative"
|
| 100 |
+
else:
|
| 101 |
+
sentiment = "neutral"
|
| 102 |
+
|
| 103 |
+
# Intensity calculation
|
| 104 |
+
neutral_score = scores.get("neutral", 0.0)
|
| 105 |
+
|
| 106 |
+
if sentiment == "neutral":
|
| 107 |
+
intensity = 4 - round(score * 2)
|
| 108 |
+
else:
|
| 109 |
+
diff = score - neutral_score
|
| 110 |
+
intensity = 5 + round(diff * 5)
|
| 111 |
+
|
| 112 |
+
intensity = clamp(intensity, 2, 10)
|
| 113 |
+
|
| 114 |
+
# Select Maps
|
| 115 |
+
emotion_map = MAR_EMOTION_MAP if is_marathi else ENG_EMOTION_MAP
|
| 116 |
+
summary_map = MAR_SUMMARY_MAP if is_marathi else ENG_SUMMARY_MAP
|
| 117 |
+
tips_map = MAR_TIPS_MAP if is_marathi else ENG_TIPS_MAP
|
| 118 |
+
|
| 119 |
+
return {
|
| 120 |
+
"sentiment": sentiment.capitalize(),
|
| 121 |
+
"emotion": emotion_map[sentiment],
|
| 122 |
+
"confidence": round(score, 3),
|
| 123 |
+
"intensity": intensity,
|
| 124 |
+
"emoji": EMOJI_MAP[sentiment],
|
| 125 |
+
"summary": summary_map[sentiment],
|
| 126 |
+
"coping_suggestions": tips_map[sentiment],
|
| 127 |
+
"color_code": COLOR_MAP[sentiment],
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
except Exception:
|
| 131 |
+
return {
|
| 132 |
+
"sentiment": "Neutral",
|
| 133 |
+
"emotion": "शांत" if is_marathi else "Neutral",
|
| 134 |
+
"confidence": 0,
|
| 135 |
+
"intensity": 3,
|
| 136 |
+
"emoji": "❓",
|
| 137 |
+
"summary": "विश्लेषण अयशस्वी. पुन्हा प्रयत्न करा." if is_marathi else "Mood analysis failed. Please try again.",
|
| 138 |
+
"coping_suggestions": ["पुन्हा प्रयत्न करा"] if is_marathi else ["Try again with different phrasing"],
|
| 139 |
+
"color_code": "#facc15",
|
| 140 |
+
}
|
app/api/__init__.py
ADDED
|
File without changes
|
app/api/analysis.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import anyio
|
| 2 |
+
from fastapi import APIRouter, HTTPException, Depends
|
| 3 |
+
from ..schemas.analysis import AnalyzeRequest
|
| 4 |
+
from ..ai.service import analyze_mood
|
| 5 |
+
from ..core.security import get_current_user
|
| 6 |
+
|
| 7 |
+
router = APIRouter(tags=["Analysis"])
|
| 8 |
+
|
| 9 |
+
@router.post("/analyze")
|
| 10 |
+
async def analyze_text(request: AnalyzeRequest, user: dict = Depends(get_current_user)):
|
| 11 |
+
"""
|
| 12 |
+
Authenticated sentiment analysis endpoint.
|
| 13 |
+
Accepts text, returns mood/intensity/confidence/suggestions.
|
| 14 |
+
Now protected and optimized with threadpool.
|
| 15 |
+
"""
|
| 16 |
+
try:
|
| 17 |
+
# Run CPU-bound sync inference in a separate thread
|
| 18 |
+
return await anyio.to_thread.run_sync(analyze_mood, request.content, request.language)
|
| 19 |
+
except ValueError as e:
|
| 20 |
+
raise HTTPException(status_code=422, detail=str(e))
|
| 21 |
+
except Exception as e:
|
| 22 |
+
# Log error here in a real app
|
| 23 |
+
raise HTTPException(status_code=500, detail="Internal analysis error.")
|
| 24 |
+
|
| 25 |
+
@router.get("/health")
|
| 26 |
+
async def health():
|
| 27 |
+
return {"status": "ok", "service": "MoodMate AI Engine"}
|
app/api/games.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Depends, Security
|
| 2 |
+
from fastapi.security import HTTPAuthorizationCredentials
|
| 3 |
+
from ..utils.supabase import get_supabase
|
| 4 |
+
from ..core.security import get_current_user, security
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from typing import List, Optional
|
| 7 |
+
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
class GameScore(BaseModel):
|
| 11 |
+
game_id: str
|
| 12 |
+
game_name: str
|
| 13 |
+
score: int
|
| 14 |
+
duration: Optional[int] = 0
|
| 15 |
+
|
| 16 |
+
GAMES_CATALOG = [
|
| 17 |
+
{"id": "bubble-burst", "title": "Bubble Burst", "category": "Relax", "description": "Release cortisol through sensory bubble interaction in a zero-gravity void."},
|
| 18 |
+
{"id": "prana-breathe", "title": "Prana Breathe", "category": "Meditation", "description": "Guided rhythmic breathing (प्राणायाम) to stabilize your heart rate and calm the mind."},
|
| 19 |
+
{"id": "zen-rain", "title": "Zen Rain", "category": "Focus", "description": "Interact with a falling particle stream. Calibrate your attention on fluid dynamics."},
|
| 20 |
+
{"id": "mood-canvas", "title": "Mood Canvas", "category": "Expression", "description": "A minimalist digital canvas to express emotions through color and light without judgment."},
|
| 21 |
+
{"id": "echo-harmony", "title": "Echo Harmony", "category": "Sound", "description": "Create harmonious patterns with gentle sound echoes that synchronize with your pulse."},
|
| 22 |
+
{"id": "focus-pulse", "title": "Focus Pulse", "category": "Focus", "description": "Maintain your center as concentric neural rings expand and contract in rhythm."},
|
| 23 |
+
{"id": "emotion-sort", "title": "Emotion Sort", "category": "Cognitive", "description": "Connect Marathi emotional nuances to their corresponding color frequencies."},
|
| 24 |
+
{"id": "celestial-drift", "title": "Celestial Drift", "category": "Relax", "description": "Guide a lone star through a deep space nebula. High-fidelity cosmic relaxation."},
|
| 25 |
+
{"id": "starlight-connect", "title": "Starlight Connect", "category": "Cognitive", "description": "Unite distant stars to form ancient constellations. Focus and pattern recognition."},
|
| 26 |
+
{"id": "nature-loop", "title": "Nature Loop", "category": "Sound", "description": "Immersive Marathi nature soundscapes paired with procedural high-end visuals."}
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
@router.get("/catalog")
|
| 30 |
+
async def get_catalog():
|
| 31 |
+
return {"status": "success", "data": GAMES_CATALOG}
|
| 32 |
+
|
| 33 |
+
@router.post("/scores")
|
| 34 |
+
async def save_score(
|
| 35 |
+
score: GameScore,
|
| 36 |
+
user: dict = Depends(get_current_user),
|
| 37 |
+
auth: HTTPAuthorizationCredentials = Security(security)
|
| 38 |
+
):
|
| 39 |
+
try:
|
| 40 |
+
user_id = user["id"]
|
| 41 |
+
client = get_supabase(auth.credentials)
|
| 42 |
+
|
| 43 |
+
score_data = score.dict()
|
| 44 |
+
score_data["user_id"] = user_id
|
| 45 |
+
|
| 46 |
+
# We'll save this in a game_scores table
|
| 47 |
+
data = await client.save_game_score(score_data)
|
| 48 |
+
return {"status": "success", "data": data}
|
| 49 |
+
except Exception as e:
|
| 50 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 51 |
+
|
| 52 |
+
@router.get("/stats")
|
| 53 |
+
async def get_game_stats(
|
| 54 |
+
user: dict = Depends(get_current_user),
|
| 55 |
+
auth: HTTPAuthorizationCredentials = Security(security)
|
| 56 |
+
):
|
| 57 |
+
try:
|
| 58 |
+
user_id = user["id"]
|
| 59 |
+
client = get_supabase(auth.credentials)
|
| 60 |
+
data = await client.get_game_stats(user_id)
|
| 61 |
+
return {"status": "success", "data": data}
|
| 62 |
+
except Exception as e:
|
| 63 |
+
raise HTTPException(status_code=500, detail=str(e))
|
app/api/journal.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Depends, Security
|
| 2 |
+
from fastapi.security import HTTPAuthorizationCredentials
|
| 3 |
+
from ..utils.supabase import get_supabase
|
| 4 |
+
from ..core.security import get_current_user, security
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from typing import List, Optional
|
| 7 |
+
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
class JournalEntry(BaseModel):
|
| 11 |
+
text: str
|
| 12 |
+
emotion: str
|
| 13 |
+
mood: str
|
| 14 |
+
color_code: str
|
| 15 |
+
intensity: int
|
| 16 |
+
language: str = "English"
|
| 17 |
+
|
| 18 |
+
@router.get("/entries")
|
| 19 |
+
async def get_entries(
|
| 20 |
+
user: dict = Depends(get_current_user),
|
| 21 |
+
auth: HTTPAuthorizationCredentials = Security(security)
|
| 22 |
+
):
|
| 23 |
+
try:
|
| 24 |
+
user_id = user["id"]
|
| 25 |
+
client = get_supabase(auth.credentials)
|
| 26 |
+
data = await client.get_entries(user_id)
|
| 27 |
+
return {"status": "success", "data": data}
|
| 28 |
+
except Exception as e:
|
| 29 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 30 |
+
|
| 31 |
+
@router.get("/stats")
|
| 32 |
+
async def get_stats(
|
| 33 |
+
user: dict = Depends(get_current_user),
|
| 34 |
+
auth: HTTPAuthorizationCredentials = Security(security)
|
| 35 |
+
):
|
| 36 |
+
try:
|
| 37 |
+
user_id = user["id"]
|
| 38 |
+
client = get_supabase(auth.credentials)
|
| 39 |
+
entries = await client.get_entries(user_id)
|
| 40 |
+
|
| 41 |
+
# Aggregate on server
|
| 42 |
+
total = len(entries)
|
| 43 |
+
positive = len([e for e in entries if 'positive' in (e.get('mood') or '').lower() or 'happy' in (e.get('mood') or '').lower()])
|
| 44 |
+
negative = len([e for e in entries if 'negative' in (e.get('mood') or '').lower() or 'sad' in (e.get('mood') or '').lower()])
|
| 45 |
+
neutral = total - positive - negative
|
| 46 |
+
|
| 47 |
+
# Calculate Streak
|
| 48 |
+
streak = 0
|
| 49 |
+
if entries:
|
| 50 |
+
from datetime import datetime, timedelta
|
| 51 |
+
# Sort by date
|
| 52 |
+
dates = sorted(list(set([datetime.fromisoformat(e['created_at'].replace('Z', '+00:00')).date() for e in entries])), reverse=True)
|
| 53 |
+
|
| 54 |
+
today = datetime.now().date()
|
| 55 |
+
current = today
|
| 56 |
+
|
| 57 |
+
# If latest entry is not today or yesterday, streak is 0
|
| 58 |
+
if dates and (dates[0] == today or dates[0] == today - timedelta(days=1)):
|
| 59 |
+
for d in dates:
|
| 60 |
+
if d == current:
|
| 61 |
+
streak += 1
|
| 62 |
+
current -= timedelta(days=1)
|
| 63 |
+
elif d > current:
|
| 64 |
+
continue
|
| 65 |
+
else:
|
| 66 |
+
break
|
| 67 |
+
|
| 68 |
+
return {
|
| 69 |
+
"status": "success",
|
| 70 |
+
"data": {
|
| 71 |
+
"total": total,
|
| 72 |
+
"positive": positive,
|
| 73 |
+
"negative": negative,
|
| 74 |
+
"neutral": neutral,
|
| 75 |
+
"streak": streak,
|
| 76 |
+
"entries": entries[:10]
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
except Exception as e:
|
| 80 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 81 |
+
|
| 82 |
+
@router.post("/entries")
|
| 83 |
+
async def create_entry(
|
| 84 |
+
entry: JournalEntry,
|
| 85 |
+
user: dict = Depends(get_current_user),
|
| 86 |
+
auth: HTTPAuthorizationCredentials = Security(security)
|
| 87 |
+
):
|
| 88 |
+
try:
|
| 89 |
+
user_id = user["id"]
|
| 90 |
+
client = get_supabase(auth.credentials)
|
| 91 |
+
|
| 92 |
+
entry_dict = entry.dict()
|
| 93 |
+
entry_dict["user_id"] = user_id
|
| 94 |
+
|
| 95 |
+
data = await client.create_entry(entry_dict)
|
| 96 |
+
return {"status": "success", "data": data}
|
| 97 |
+
except Exception as e:
|
| 98 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 99 |
+
|
| 100 |
+
@router.delete("/entries/{entry_id}")
|
| 101 |
+
async def delete_entry(
|
| 102 |
+
entry_id: str,
|
| 103 |
+
user: dict = Depends(get_current_user),
|
| 104 |
+
auth: HTTPAuthorizationCredentials = Security(security)
|
| 105 |
+
):
|
| 106 |
+
try:
|
| 107 |
+
user_id = user["id"]
|
| 108 |
+
client = get_supabase(auth.credentials)
|
| 109 |
+
await client.delete_entry(entry_id, user_id)
|
| 110 |
+
return {"status": "success", "message": "Entry deleted successfully"}
|
| 111 |
+
except Exception as e:
|
| 112 |
+
raise HTTPException(status_code=500, detail=str(e))
|
app/api/profile.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Depends, Security
|
| 2 |
+
from fastapi.security import HTTPAuthorizationCredentials
|
| 3 |
+
from ..utils.supabase import get_supabase
|
| 4 |
+
from ..core.security import get_current_user, security
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
class ProfileUpdate(BaseModel):
|
| 11 |
+
full_name: Optional[str] = None
|
| 12 |
+
age: Optional[str] = None
|
| 13 |
+
gender: Optional[str] = None
|
| 14 |
+
mood_goal: Optional[str] = None
|
| 15 |
+
bio: Optional[str] = None
|
| 16 |
+
triggers: Optional[str] = None
|
| 17 |
+
preferences: Optional[dict] = None
|
| 18 |
+
avatar_url: Optional[str] = None
|
| 19 |
+
|
| 20 |
+
@router.get("/me")
|
| 21 |
+
async def get_my_profile(
|
| 22 |
+
user: dict = Depends(get_current_user),
|
| 23 |
+
auth: HTTPAuthorizationCredentials = Security(security)
|
| 24 |
+
):
|
| 25 |
+
try:
|
| 26 |
+
user_id = user["id"]
|
| 27 |
+
client = get_supabase(auth.credentials)
|
| 28 |
+
|
| 29 |
+
# Try to get from profiles table
|
| 30 |
+
profile_data = await client.get_profile(user_id)
|
| 31 |
+
|
| 32 |
+
# Merge with auth metadata for fallback
|
| 33 |
+
return {
|
| 34 |
+
"status": "success",
|
| 35 |
+
"data": {
|
| 36 |
+
"id": user_id,
|
| 37 |
+
"full_name": profile_data.get("full_name") or user.get("user_metadata", {}).get("display_name", ""),
|
| 38 |
+
"email": user.get("email", ""),
|
| 39 |
+
**profile_data
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
except Exception as e:
|
| 43 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 44 |
+
|
| 45 |
+
@router.post("/me")
|
| 46 |
+
async def update_my_profile(
|
| 47 |
+
profile_update: ProfileUpdate,
|
| 48 |
+
user: dict = Depends(get_current_user),
|
| 49 |
+
auth: HTTPAuthorizationCredentials = Security(security)
|
| 50 |
+
):
|
| 51 |
+
try:
|
| 52 |
+
user_id = user["id"]
|
| 53 |
+
client = get_supabase(auth.credentials)
|
| 54 |
+
|
| 55 |
+
update_data = profile_update.dict(exclude_unset=True)
|
| 56 |
+
data = await client.update_profile(user_id, update_data)
|
| 57 |
+
|
| 58 |
+
return {
|
| 59 |
+
"status": "success",
|
| 60 |
+
"data": data
|
| 61 |
+
}
|
| 62 |
+
except Exception as e:
|
| 63 |
+
raise HTTPException(status_code=500, detail=str(e))
|
app/core/__init__.py
ADDED
|
File without changes
|
app/core/config.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic_settings import BaseSettings
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
class Settings(BaseSettings):
|
| 5 |
+
API_V1_STR: str = "/api/v1"
|
| 6 |
+
PROJECT_NAME: str = "MoodMate AI Engine"
|
| 7 |
+
DATABASE_URL: str
|
| 8 |
+
SUPABASE_URL: str
|
| 9 |
+
SUPABASE_ANON_KEY: str
|
| 10 |
+
|
| 11 |
+
ALLOWED_ORIGINS: List[str] = ["*"]
|
| 12 |
+
|
| 13 |
+
class Config:
|
| 14 |
+
env_file = ".env"
|
| 15 |
+
case_sensitive = True
|
| 16 |
+
|
| 17 |
+
settings = Settings()
|
app/core/ratelimit.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 2 |
+
from slowapi.util import get_remote_address
|
| 3 |
+
from slowapi.errors import RateLimitExceeded
|
| 4 |
+
from fastapi import Request
|
| 5 |
+
|
| 6 |
+
limiter = Limiter(key_func=get_remote_address)
|
| 7 |
+
|
| 8 |
+
def setup_ratelimit(app):
|
| 9 |
+
app.state.limiter = limiter
|
| 10 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
app/core/security.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import httpx
|
| 2 |
+
from fastapi import HTTPException, Security, Depends
|
| 3 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 4 |
+
from .config import settings
|
| 5 |
+
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
security = HTTPBearer(auto_error=False)
|
| 9 |
+
|
| 10 |
+
async def get_current_user(auth: Optional[HTTPAuthorizationCredentials] = Security(security)):
|
| 11 |
+
"""
|
| 12 |
+
Verifies the JWT token with Supabase Auth API.
|
| 13 |
+
Returns the user data or None if guest/invalid.
|
| 14 |
+
"""
|
| 15 |
+
if not auth:
|
| 16 |
+
return None
|
| 17 |
+
|
| 18 |
+
token = auth.credentials
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
async with httpx.AsyncClient() as client:
|
| 22 |
+
response = await client.get(
|
| 23 |
+
f"{settings.SUPABASE_URL}/auth/v1/user",
|
| 24 |
+
headers={
|
| 25 |
+
"apikey": settings.SUPABASE_ANON_KEY,
|
| 26 |
+
"Authorization": f"Bearer {token}"
|
| 27 |
+
}
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
if response.status_code == 200:
|
| 31 |
+
return response.json()
|
| 32 |
+
else:
|
| 33 |
+
print(f"SUPABASE AUTH ERROR: {response.status_code} - {response.text}")
|
| 34 |
+
# Log specific error if unauthorized
|
| 35 |
+
if response.status_code == 401:
|
| 36 |
+
raise HTTPException(
|
| 37 |
+
status_code=401,
|
| 38 |
+
detail=f"Supabase Auth Error: {response.json().get('msg', 'Unauthorized')}",
|
| 39 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 40 |
+
)
|
| 41 |
+
except HTTPException:
|
| 42 |
+
raise
|
| 43 |
+
except Exception as e:
|
| 44 |
+
print(f"JWT VERIFICATION EXCEPTION: {str(e)}")
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
raise HTTPException(
|
| 48 |
+
status_code=401,
|
| 49 |
+
detail="Invalid or expired authentication token",
|
| 50 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
async def get_authenticated_user(user: Optional[dict] = Depends(get_current_user)):
|
| 54 |
+
"""
|
| 55 |
+
Ensures that a user is actually logged in.
|
| 56 |
+
"""
|
| 57 |
+
if not user:
|
| 58 |
+
raise HTTPException(
|
| 59 |
+
status_code=401,
|
| 60 |
+
detail="Authentication required for this action",
|
| 61 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 62 |
+
)
|
| 63 |
+
return user
|
app/main.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MoodMate AI Engine — FastAPI
|
| 3 |
+
God Mode Architecture v2.0
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from fastapi import FastAPI
|
| 7 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
+
from .api.analysis import router as analysis_router
|
| 9 |
+
from .api.journal import router as journal_router
|
| 10 |
+
from .api.profile import router as profile_router
|
| 11 |
+
from .api.games import router as games_router
|
| 12 |
+
from .core.ratelimit import setup_ratelimit
|
| 13 |
+
|
| 14 |
+
# ---------------- APP INITIALIZATION ----------------
|
| 15 |
+
|
| 16 |
+
app = FastAPI(
|
| 17 |
+
title="MoodMate AI Engine",
|
| 18 |
+
description="Deep Space Cybernetic Emotional Analytics Platform",
|
| 19 |
+
version="2.1.0"
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# ---------------- CORS CONFIGURATION ----------------
|
| 23 |
+
|
| 24 |
+
app.add_middleware(
|
| 25 |
+
CORSMiddleware,
|
| 26 |
+
allow_origins=["*"], # In production, replace with specific origins
|
| 27 |
+
allow_credentials=True,
|
| 28 |
+
allow_methods=["*"],
|
| 29 |
+
allow_headers=["*"],
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# ---------------- ROUTER INCLUSION ----------------
|
| 33 |
+
|
| 34 |
+
app.include_router(analysis_router, prefix="/api/v1")
|
| 35 |
+
app.include_router(journal_router, prefix="/api/v1/journal")
|
| 36 |
+
app.include_router(profile_router, prefix="/api/v1/profile")
|
| 37 |
+
app.include_router(games_router, prefix="/api/v1/games")
|
| 38 |
+
app.include_router(analysis_router) # Support legacy path
|
| 39 |
+
|
| 40 |
+
# ---------------- ROOT ENDPOINT ----------------
|
| 41 |
+
|
| 42 |
+
@app.get("/")
|
| 43 |
+
async def root():
|
| 44 |
+
return {
|
| 45 |
+
"message": "Welcome to MoodMate AI Engine",
|
| 46 |
+
"docs": "/docs",
|
| 47 |
+
"health": "/health"
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
import uvicorn
|
| 52 |
+
uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
|
app/schemas/__init__.py
ADDED
|
File without changes
|
app/schemas/analysis.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, field_validator
|
| 2 |
+
|
| 3 |
+
class AnalyzeRequest(BaseModel):
|
| 4 |
+
content: str
|
| 5 |
+
language: str = "English"
|
| 6 |
+
|
| 7 |
+
@field_validator("content")
|
| 8 |
+
@classmethod
|
| 9 |
+
def content_must_not_be_empty(cls, v: str) -> str:
|
| 10 |
+
stripped = v.strip()
|
| 11 |
+
if not stripped:
|
| 12 |
+
raise ValueError("Content cannot be empty.")
|
| 13 |
+
if len(stripped) < 3:
|
| 14 |
+
raise ValueError("Content is too short for analysis.")
|
| 15 |
+
return stripped
|
app/services/__init__.py
ADDED
|
File without changes
|
app/utils/__init__.py
ADDED
|
File without changes
|
app/utils/supabase.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import httpx
|
| 2 |
+
import logging
|
| 3 |
+
from ..core.config import settings
|
| 4 |
+
|
| 5 |
+
logger = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
class SupabaseClient:
|
| 8 |
+
def __init__(self, token: str = None):
|
| 9 |
+
self.url = settings.SUPABASE_URL
|
| 10 |
+
self.key = settings.SUPABASE_ANON_KEY
|
| 11 |
+
|
| 12 |
+
# If token is provided, we use it for Authorization to trigger RLS
|
| 13 |
+
# Otherwise we use the anon key
|
| 14 |
+
self.auth_header = f"Bearer {token}" if token else f"Bearer {self.key}"
|
| 15 |
+
self.headers = {
|
| 16 |
+
"apikey": self.key,
|
| 17 |
+
"Authorization": self.auth_header,
|
| 18 |
+
"Content-Type": "application/json",
|
| 19 |
+
"Prefer": "return=representation"
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
async def _handle_response(self, response):
|
| 23 |
+
try:
|
| 24 |
+
response.raise_for_status()
|
| 25 |
+
return response.json()
|
| 26 |
+
except httpx.HTTPStatusError as e:
|
| 27 |
+
error_data = {}
|
| 28 |
+
try:
|
| 29 |
+
error_data = e.response.json()
|
| 30 |
+
except:
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
message = error_data.get("message") or error_data.get("msg") or e.response.text
|
| 34 |
+
logger.error(f"Supabase error ({e.response.status_code}): {message}")
|
| 35 |
+
raise Exception(f"Supabase API error: {message}")
|
| 36 |
+
|
| 37 |
+
async def get_entries(self, user_id: str):
|
| 38 |
+
async with httpx.AsyncClient() as client:
|
| 39 |
+
response = await client.get(
|
| 40 |
+
f"{self.url}/rest/v1/journal_entries?user_id=eq.{user_id}&order=created_at.desc",
|
| 41 |
+
headers=self.headers
|
| 42 |
+
)
|
| 43 |
+
return await self._handle_response(response)
|
| 44 |
+
|
| 45 |
+
async def get_profile(self, user_id: str):
|
| 46 |
+
async with httpx.AsyncClient() as client:
|
| 47 |
+
response = await client.get(
|
| 48 |
+
f"{self.url}/rest/v1/profiles?id=eq.{user_id}",
|
| 49 |
+
headers=self.headers
|
| 50 |
+
)
|
| 51 |
+
data = await self._handle_response(response)
|
| 52 |
+
return data[0] if data else {}
|
| 53 |
+
|
| 54 |
+
async def create_entry(self, entry_data: dict):
|
| 55 |
+
async with httpx.AsyncClient() as client:
|
| 56 |
+
response = await client.post(
|
| 57 |
+
f"{self.url}/rest/v1/journal_entries",
|
| 58 |
+
headers=self.headers,
|
| 59 |
+
json=entry_data
|
| 60 |
+
)
|
| 61 |
+
return await self._handle_response(response)
|
| 62 |
+
|
| 63 |
+
async def delete_entry(self, entry_id: str, user_id: str):
|
| 64 |
+
async with httpx.AsyncClient() as client:
|
| 65 |
+
response = await client.delete(
|
| 66 |
+
f"{self.url}/rest/v1/journal_entries?id=eq.{entry_id}&user_id=eq.{user_id}",
|
| 67 |
+
headers=self.headers
|
| 68 |
+
)
|
| 69 |
+
return await self._handle_response(response)
|
| 70 |
+
|
| 71 |
+
async def update_profile(self, user_id: str, profile_data: dict):
|
| 72 |
+
async with httpx.AsyncClient() as client:
|
| 73 |
+
# Upsert into profiles
|
| 74 |
+
headers = {**self.headers, "Prefer": "return=representation,resolution=merge-duplicates"}
|
| 75 |
+
profile_data["id"] = user_id
|
| 76 |
+
|
| 77 |
+
response = await client.post(
|
| 78 |
+
f"{self.url}/rest/v1/profiles",
|
| 79 |
+
headers=headers,
|
| 80 |
+
json=profile_data
|
| 81 |
+
)
|
| 82 |
+
return await self._handle_response(response)
|
| 83 |
+
|
| 84 |
+
async def save_game_score(self, score_data: dict):
|
| 85 |
+
async with httpx.AsyncClient() as client:
|
| 86 |
+
response = await client.post(
|
| 87 |
+
f"{self.url}/rest/v1/game_scores",
|
| 88 |
+
headers=self.headers,
|
| 89 |
+
json=score_data
|
| 90 |
+
)
|
| 91 |
+
return await self._handle_response(response)
|
| 92 |
+
|
| 93 |
+
async def get_game_stats(self, user_id: str):
|
| 94 |
+
async with httpx.AsyncClient() as client:
|
| 95 |
+
response = await client.get(
|
| 96 |
+
f"{self.url}/rest/v1/game_scores?user_id=eq.{user_id}&order=created_at.desc",
|
| 97 |
+
headers=self.headers
|
| 98 |
+
)
|
| 99 |
+
return await self._handle_response(response)
|
| 100 |
+
|
| 101 |
+
def get_supabase(token: str = None):
|
| 102 |
+
return SupabaseClient(token)
|
database/schema.sql
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- MoodMate Supabase Database Schema
|
| 2 |
+
|
| 3 |
+
-- 1. Profiles Table
|
| 4 |
+
CREATE TABLE IF NOT EXISTS public.profiles (
|
| 5 |
+
id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
|
| 6 |
+
full_name TEXT,
|
| 7 |
+
age INTEGER,
|
| 8 |
+
gender TEXT,
|
| 9 |
+
mood_goal TEXT,
|
| 10 |
+
triggers TEXT,
|
| 11 |
+
preferences JSONB DEFAULT '{}'::jsonb,
|
| 12 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL,
|
| 13 |
+
updated_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL
|
| 14 |
+
);
|
| 15 |
+
|
| 16 |
+
-- 2. Journal Entries Table
|
| 17 |
+
CREATE TABLE IF NOT EXISTS public.journal_entries (
|
| 18 |
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
| 19 |
+
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
| 20 |
+
text TEXT NOT NULL,
|
| 21 |
+
emotion TEXT NOT NULL,
|
| 22 |
+
mood TEXT NOT NULL,
|
| 23 |
+
color_code TEXT,
|
| 24 |
+
intensity INTEGER DEFAULT 50,
|
| 25 |
+
language TEXT DEFAULT 'English',
|
| 26 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL
|
| 27 |
+
);
|
| 28 |
+
|
| 29 |
+
-- 3. Game Scores Table
|
| 30 |
+
CREATE TABLE IF NOT EXISTS public.game_scores (
|
| 31 |
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
| 32 |
+
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
| 33 |
+
game_id INTEGER NOT NULL,
|
| 34 |
+
game_name TEXT NOT NULL,
|
| 35 |
+
score INTEGER NOT NULL,
|
| 36 |
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL
|
| 37 |
+
);
|
| 38 |
+
|
| 39 |
+
-- RLS SETTINGS (Row Level Security)
|
| 40 |
+
-- Run these for each table to ensure users only see their own data
|
| 41 |
+
|
| 42 |
+
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
|
| 43 |
+
CREATE POLICY "Users can view own profile" ON public.profiles FOR SELECT USING (auth.uid() = id);
|
| 44 |
+
CREATE POLICY "Users can update own profile" ON public.profiles FOR UPDATE USING (auth.uid() = id);
|
| 45 |
+
CREATE POLICY "Users can insert own profile" ON public.profiles FOR INSERT WITH CHECK (auth.uid() = id);
|
| 46 |
+
|
| 47 |
+
ALTER TABLE public.journal_entries ENABLE ROW LEVEL SECURITY;
|
| 48 |
+
CREATE POLICY "Users can view own entries" ON public.journal_entries FOR SELECT USING (auth.uid() = user_id);
|
| 49 |
+
CREATE POLICY "Users can insert own entries" ON public.journal_entries FOR INSERT WITH CHECK (auth.uid() = user_id);
|
| 50 |
+
CREATE POLICY "Users can delete own entries" ON public.journal_entries FOR DELETE USING (auth.uid() = user_id);
|
| 51 |
+
|
| 52 |
+
ALTER TABLE public.game_scores ENABLE ROW LEVEL SECURITY;
|
| 53 |
+
CREATE POLICY "Users can view own scores" ON public.game_scores FOR SELECT USING (auth.uid() = user_id);
|
| 54 |
+
CREATE POLICY "Users can insert own scores" ON public.game_scores FOR INSERT WITH CHECK (auth.uid() = user_id);
|
| 55 |
+
|
| 56 |
+
-- 4. Performance Indexes
|
| 57 |
+
CREATE INDEX IF NOT EXISTS idx_journal_user_id ON public.journal_entries(user_id);
|
| 58 |
+
CREATE INDEX IF NOT EXISTS idx_journal_created_at ON public.journal_entries(created_at);
|
| 59 |
+
CREATE INDEX IF NOT EXISTS idx_game_scores_user_id ON public.game_scores(user_id);
|
| 60 |
+
CREATE INDEX IF NOT EXISTS idx_game_scores_created_at ON public.game_scores(created_at);
|
| 61 |
+
CREATE INDEX IF NOT EXISTS idx_profiles_id ON public.profiles(id);
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
pydantic
|
| 4 |
+
pydantic-settings
|
| 5 |
+
transformers
|
| 6 |
+
torch
|
| 7 |
+
sentencepiece
|
| 8 |
+
python-multipart
|
| 9 |
+
python-dotenv
|
| 10 |
+
httpx
|
| 11 |
+
anyio
|
| 12 |
+
slowapi
|
scripts/analyze_dataset.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
train_path = r"d:\Ujjwal\College\Major Project\MoodMate\DataSet Model Training\trainr.csv"
|
| 5 |
+
val_path = r"d:\Ujjwal\College\Major Project\MoodMate\DataSet Model Training\validationr.csv"
|
| 6 |
+
test_path = r"d:\Ujjwal\College\Major Project\MoodMate\DataSet Model Training\testr.csv"
|
| 7 |
+
|
| 8 |
+
def get_info(path, name):
|
| 9 |
+
df = pd.read_csv(path)
|
| 10 |
+
print(f"--- {name} ---")
|
| 11 |
+
print(f"Total Rows: {len(df)}")
|
| 12 |
+
print(f"Label Distribution:\n{df['label'].value_counts()}")
|
| 13 |
+
print("-" * 20)
|
| 14 |
+
|
| 15 |
+
get_info(train_path, "Train")
|
| 16 |
+
get_info(val_path, "Validation")
|
| 17 |
+
get_info(test_path, "Test")
|
scripts/health_check.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
MoodMate Backend Health Check
|
| 4 |
+
Run this script to verify the backend setup is correct.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
def check_python_version():
|
| 11 |
+
"""Check if Python version is 3.11+"""
|
| 12 |
+
if sys.version_info < (3, 11):
|
| 13 |
+
print("❌ Python 3.11+ required")
|
| 14 |
+
return False
|
| 15 |
+
print(f"✅ Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")
|
| 16 |
+
return True
|
| 17 |
+
|
| 18 |
+
def check_imports():
|
| 19 |
+
"""Check if all required packages are importable"""
|
| 20 |
+
required_packages = [
|
| 21 |
+
'fastapi',
|
| 22 |
+
'uvicorn',
|
| 23 |
+
'pydantic',
|
| 24 |
+
'transformers',
|
| 25 |
+
'torch',
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
all_ok = True
|
| 29 |
+
for package in required_packages:
|
| 30 |
+
try:
|
| 31 |
+
__import__(package)
|
| 32 |
+
print(f"✅ {package}")
|
| 33 |
+
except ImportError:
|
| 34 |
+
print(f"❌ {package} - missing, run: pip install -r requirements.txt")
|
| 35 |
+
all_ok = False
|
| 36 |
+
return all_ok
|
| 37 |
+
|
| 38 |
+
def check_models():
|
| 39 |
+
"""Check if model files exist"""
|
| 40 |
+
model_dir = os.path.join(os.path.dirname(__file__), 'app', 'ai', 'models')
|
| 41 |
+
required_files = [
|
| 42 |
+
'config.json',
|
| 43 |
+
'model.safetensors',
|
| 44 |
+
'tokenizer.json',
|
| 45 |
+
'special_tokens_map.json',
|
| 46 |
+
'tokenizer_config.json',
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
all_ok = True
|
| 50 |
+
for file in required_files:
|
| 51 |
+
file_path = os.path.join(model_dir, file)
|
| 52 |
+
if os.path.exists(file_path):
|
| 53 |
+
size = os.path.getsize(file_path)
|
| 54 |
+
print(f"✅ {file} ({size:,} bytes)")
|
| 55 |
+
else:
|
| 56 |
+
print(f"❌ {file} - missing")
|
| 57 |
+
all_ok = False
|
| 58 |
+
|
| 59 |
+
return all_ok
|
| 60 |
+
|
| 61 |
+
def main():
|
| 62 |
+
print("\n🔍 MoodMate Backend Health Check\n")
|
| 63 |
+
|
| 64 |
+
checks = [
|
| 65 |
+
("Python Version", check_python_version),
|
| 66 |
+
("Required Packages", check_imports),
|
| 67 |
+
("Model Files", check_models),
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
results = []
|
| 71 |
+
for check_name, check_func in checks:
|
| 72 |
+
print(f"\n📋 Checking {check_name}...")
|
| 73 |
+
result = check_func()
|
| 74 |
+
results.append(result)
|
| 75 |
+
|
| 76 |
+
print("\n" + "="*50)
|
| 77 |
+
if all(results):
|
| 78 |
+
print("✅ All checks passed! Ready to start backend.")
|
| 79 |
+
print("\nStart the server with:")
|
| 80 |
+
print(" python -m uvicorn app.main:app --reload")
|
| 81 |
+
return 0
|
| 82 |
+
else:
|
| 83 |
+
print("❌ Some checks failed. Fix the issues above.")
|
| 84 |
+
return 1
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
sys.exit(main())
|