Spaces:
Sleeping
Sleeping
StudIQ Deploy Bot commited on
Commit ·
addbd2a
1
Parent(s): 91af4d8
Deploy StudIQ v0.5.1 — 2026-05-27 05:38 UTC
Browse filesFiles changed (34)
- .gitignoreAdded+9
- app/api/v1/assignments.py+2-2
- app/api/v1/chat.py+7-2
- app/api/v1/dashboard.py+5-1
- app/api/v1/doubts.py+1-1
- app/api/v1/labfile.py+41-29
- app/api/v1/payments.pyDeleted-115
- app/api/v1/plan.py+6-2
- app/api/v1/router.py-5
- app/api/v1/store.py+10
- app/api/v1/users.py+15-6
- app/api/v1/viva.py+54-1
- app/config.py+10-4
- app/core/dependencies.py+1-1
- app/main.py+5-5
- app/models/attendance.py+4-2
- app/models/conversation.py+2-2
- app/models/flashcard.py+3-3
- app/models/user.py+2-2
- app/schemas/user.py+1-1
- app/services/assignment_service.py+47-27
- app/services/auth_service.py+3-1
- app/services/chat_service.py+72-41
- app/services/firebase_service.py+25-44
- app/services/llm_service.py+20-31
- app/services/payment_service.pyDeleted-90
- app/services/plan_service.py+11-6
- app/services/prompt_builder.py+37-2
- app/services/rag_agent_service.py+3-3
- app/utils/json_parser.py+22-9
- bypass_onboarding.py+14-2
- firebase-creds.jsonDeleted-13
- test_llm.py+3-3
- verify_e2e.py+1-1
123456789*.logtest.dbtest_*.pyverify_*.pybypass_*.pyscrach/scratch/firebase-creds.json.env55 unmodified lines5657585960616255 unmodified linesused = 0 if prefs.get("assignment_month") != current_month else prefs.get("assignments_this_month", 0)return {"used": used,"limit": 5 if user.tier == "free" else -1,"total_ever": prefs.get("total_assignments", 0),"is_unlimited": user.tier != "free",}55 unmodified lines5657585960616255 unmodified linesused = 0 if prefs.get("assignment_month") != current_month else prefs.get("assignments_this_month", 0)return {"used": used,"limit": 5,"total_ever": prefs.get("total_assignments", 0),"is_unlimited": False,}
29 unmodified lines3031323334355 unmodified lines4142434445464765 unmodified lines1131141151161171188 unmodified lines12712812913013113295 unmodified lines22822923023123223323429 unmodified linesmessage: str = Field(..., min_length=1, max_length=2000)conversation_id: Optional[str] = None@router.post("/message")5 unmodified lines"""Stream a chat response via Server-Sent Events (SSE)."""async def event_stream():async for chunk_json in handle_chat_message(user.id, body.message, body.conversation_id, db):yield f"data: {chunk_json}\n\n"return StreamingResponse(65 unmodified linestopic_name: str = Field(..., min_length=1)subject_name: Optional[str] = Noneconversation_id: Optional[str] = None@router.post("/learn-topic")8 unmodified linesuser.id, body.topic_name, db,subject_name=body.subject_name,conversation_id_str=body.conversation_id,):yield f"data: {chunk_json}\n\n"95 unmodified lines):"""Return remaining messages for today."""await check_and_reset_quota(user, db)limit = 50 if user.tier == "free" else 999return {"used": user.daily_message_count,"limit": limit,29 unmodified lines303132333435365 unmodified lines42434445464748495065 unmodified lines1161171181191201211228 unmodified lines13113213313413513613795 unmodified lines23323423523623723823929 unmodified linesmessage: str = Field(..., min_length=1, max_length=2000)conversation_id: Optional[str] = Nonetutor_mode: Optional[str] = None@router.post("/message")5 unmodified lines"""Stream a chat response via Server-Sent Events (SSE)."""async def event_stream():async for chunk_json in handle_chat_message(user.id, body.message, body.conversation_id, db, tutor_mode=body.tutor_mode):yield f"data: {chunk_json}\n\n"return StreamingResponse(65 unmodified linestopic_name: str = Field(..., min_length=1)subject_name: Optional[str] = Noneconversation_id: Optional[str] = Nonetutor_mode: Optional[str] = None@router.post("/learn-topic")8 unmodified linesuser.id, body.topic_name, db,subject_name=body.subject_name,conversation_id_str=body.conversation_id,tutor_mode=body.tutor_mode,):yield f"data: {chunk_json}\n\n"95 unmodified lines):"""Return remaining messages for today."""await check_and_reset_quota(user, db)limit = 50return {"used": user.daily_message_count,"limit": limit,
126 unmodified lines127128129130131132133134 unmodified lines26826927027127227327427510 unmodified lines286287288289290291292126 unmodified lineslast_message.created_at.isoformat() if last_message else None),"quota_used": user.daily_message_count,"quota_limit": 50 if user.tier == "free" else 999,"streak_days": user.streak_days or 0,"total_messages_sent": user.total_messages_sent or 0,"suggestion": suggestion,134 unmodified linesprefs["exam_dates"] = exam_datesuser.preferences = prefsfrom sqlalchemy.orm.attributes import flag_modifiedflag_modified(user, "preferences")await db.commit()return {"subject": payload.subject, "exam_date": payload.exam_date}10 unmodified linesprefs["exam_dates"] = exam_datesuser.preferences = prefsfrom sqlalchemy.orm.attributes import flag_modifiedflag_modified(user, "preferences")await db.commit()return {"deleted": True}126 unmodified lines127128129130131132133134 unmodified lines26826927027127227327427527627710 unmodified lines288289290291292293294295296126 unmodified lineslast_message.created_at.isoformat() if last_message else None),"quota_used": user.daily_message_count,"quota_limit": 50,"streak_days": user.streak_days or 0,"total_messages_sent": user.total_messages_sent or 0,"suggestion": suggestion,134 unmodified linesprefs["exam_dates"] = exam_datesuser.preferences = prefsfrom datetime import datetime, timezonefrom sqlalchemy.orm.attributes import flag_modifiedflag_modified(user, "preferences")user.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)await db.commit()return {"subject": payload.subject, "exam_date": payload.exam_date}10 unmodified linesprefs["exam_dates"] = exam_datesuser.preferences = prefsfrom datetime import datetime, timezonefrom sqlalchemy.orm.attributes import flag_modifiedflag_modified(user, "preferences")user.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)await db.commit()return {"deleted": True}
26 unmodified lines2728293031323326 unmodified linesfrom app.services.chat_service import check_and_reset_quota, _increment_user_activityawait check_and_reset_quota(user, db)if user.tier == "free" and user.daily_message_count >= 50:raise HTTPException(429, "Daily quota exceeded.")# Validate file26 unmodified lines2728293031323326 unmodified linesfrom app.services.chat_service import check_and_reset_quota, _increment_user_activityawait check_and_reset_quota(user, db)if user.daily_message_count >= 50:raise HTTPException(429, "Daily quota exceeded.")# Validate file
35 unmodified lines3637383940414243444546474849505152535455565758596061626364656667686970717273747576773 unmodified lines81828384858635 unmodified linesuser: User = Depends(get_current_user),db: AsyncSession = Depends(get_db),):prefs = user.preferences or {}current_month = datetime.now(IST).strftime("%Y-%m")if user.tier == "free":if prefs.get("labfile_month") != current_month:prefs["labfiles_this_month"] = 0prefs["labfile_month"] = current_monthif prefs.get("labfiles_this_month", 0) >= FREE_LABFILE_LIMIT:return {"error": "limit_reached","message": f"{FREE_LABFILE_LIMIT} free lab files per month used. Upgrade for unlimited!",}result = await generate_lab_entry(user=user,practical_title=body.practical_title,subject=body.subject,language=body.language,practical_no=body.practical_no,)if "error" not in result:prefs = user.preferences or {}if prefs.get("labfile_month") != current_month:prefs["labfiles_this_month"] = 1prefs["labfile_month"] = current_monthelse:prefs["labfiles_this_month"] = prefs.get("labfiles_this_month", 0) + 1user.preferences = prefsflag_modified(user, "preferences")xp_result = await award_xp(user, "labfile_generated")result["xp"] = xp_resultawait db.commit()return result@router.get("/usage")3 unmodified linesused = 0 if prefs.get("labfile_month") != current_month else prefs.get("labfiles_this_month", 0)return {"used": used,"limit": FREE_LABFILE_LIMIT if user.tier == "free" else -1,"is_unlimited": user.tier != "free",}35 unmodified lines36373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687883 unmodified lines9293949596979835 unmodified linesuser: User = Depends(get_current_user),db: AsyncSession = Depends(get_db),):# Atomic limit check with row lockfrom sqlalchemy import select as _selectresult = await db.execute(_select(User).where(User.id == user.id).with_for_update())locked_user = result.scalar_one()current_month = datetime.now(IST).strftime("%Y-%m")prefs = locked_user.preferences or {}if prefs.get("labfile_month") != current_month:prefs["labfiles_this_month"] = 0prefs["labfile_month"] = current_monthlabfile_count = prefs.get("labfiles_this_month", 0)if labfile_count >= FREE_LABFILE_LIMIT:return {"error": "limit_reached","message": f"You've used all {FREE_LABFILE_LIMIT} free lab files this month. Come back next month!","limit": FREE_LABFILE_LIMIT,"used": labfile_count,}# Increment atomically before LLM callprefs["labfiles_this_month"] = labfile_count + 1prefs["total_labfiles"] = prefs.get("total_labfiles", 0) + 1locked_user.preferences = prefsflag_modified(locked_user, "preferences")await db.commit()# Now call LLMresult_data = await generate_lab_entry(user=locked_user,practical_title=body.practical_title,subject=body.subject,language=body.language,practical_no=body.practical_no,)if "error" not in result_data:from datetime import datetime, timezonelocked_user.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)xp_result = await award_xp(locked_user, "labfile_generated")result_data["xp"] = xp_resultawait db.commit()return result_data@router.get("/usage")3 unmodified linesused = 0 if prefs.get("labfile_month") != current_month else prefs.get("labfiles_this_month", 0)return {"used": used,"limit": FREE_LABFILE_LIMIT,"total_ever": prefs.get("total_labfiles", 0),"resets": "1st of every month",}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115"""Payment endpoints — Razorpay integration."""
import loggingfrom datetime import datetime, timedelta
import pytzfrom fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm.attributes import flag_modified
from app.core.dependencies import get_current_userfrom app.database import get_dbfrom app.models.user import Userfrom app.services.payment_service import ( PLANS, create_razorpay_order, verify_razorpay_signature,)
logger = logging.getLogger(__name__)router = APIRouter(prefix="/payments", tags=["Payments"])
IST = pytz.timezone("Asia/Kolkata")
class CreateOrderRequest(BaseModel): plan_id: str
class VerifyPaymentRequest(BaseModel): razorpay_order_id: str razorpay_payment_id: str razorpay_signature: str plan_id: str
@router.get("/plans")async def list_plans(user: User = Depends(get_current_user)): return { "plans": [ { "id": k, "name": v["name"], "amount": v["amount"], "amount_display": f"₹{v['amount'] // 100}", "currency": v["currency"], "duration_days": v["duration_days"], "tier": v["tier"], } for k, v in PLANS.items() ], "current_tier": user.tier, }
@router.post("/create-order")async def create_order( body: CreateOrderRequest, user: User = Depends(get_current_user),): result = await create_razorpay_order( plan_id=body.plan_id, user_id=str(user.id), user_email=user.email or "", user_name=user.name or "Student", ) if "error" in result: raise HTTPException(400, result["error"]) return result
@router.post("/verify")async def verify_payment( body: VerifyPaymentRequest, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db),): is_valid = verify_razorpay_signature( body.razorpay_order_id, body.razorpay_payment_id, body.razorpay_signature, ) if not is_valid: raise HTTPException(400, "Payment verification failed. Contact support if money was deducted.")
plan = PLANS.get(body.plan_id) if not plan: raise HTTPException(400, "Invalid plan")
user.tier = plan["tier"] prefs = user.preferences or {} payment_history = prefs.get("payment_history", []) now_ist = datetime.now(IST) payment_history.append({ "plan_id": body.plan_id, "payment_id": body.razorpay_payment_id, "order_id": body.razorpay_order_id, "amount": plan["amount"], "paid_at": now_ist.isoformat(), "expires_at": (now_ist + timedelta(days=plan["duration_days"])).isoformat(), }) prefs["payment_history"] = payment_history prefs["tier_expires_at"] = (now_ist + timedelta(days=plan["duration_days"])).isoformat() user.preferences = prefs flag_modified(user, "preferences") await db.commit()
return { "status": "success", "tier": plan["tier"], "plan_name": plan["name"], "expires_at": prefs["tier_expires_at"], "message": f"Welcome to {plan['name']}!", }127 unmodified lines12812913013113213313429 unmodified lines164165166167168169170103 unmodified lines274275276277278279280127 unmodified linesfrom app.services.chat_service import check_and_reset_quotaawait check_and_reset_quota(user, db)if user.tier == "free" and user.daily_message_count >= 50:raise HTTPException(status_code=429, detail="Daily quota exceeded. Come back tomorrow!")depth = _normalize_depth(body.depth)29 unmodified lines"plan": plan_data}user.preferences["generated_topics"].insert(0, topic_entry)flag_modified(user, "preferences")await db.commit()103 unmodified linesfrom app.services.chat_service import check_and_reset_quota, _increment_user_activityawait check_and_reset_quota(user, db)if user.tier == "free" and user.daily_message_count >= 50:raise HTTPException(status_code=429, detail="Daily quota exceeded. Come back tomorrow!")exam_dt = None127 unmodified lines12812913013113213313413529 unmodified lines165166167168169170171172173103 unmodified lines277278279280281282283284127 unmodified linesfrom app.services.chat_service import check_and_reset_quotaawait check_and_reset_quota(user, db)await db.refresh(user)if user.daily_message_count >= 50:raise HTTPException(status_code=429, detail="Daily quota exceeded. Come back tomorrow!")depth = _normalize_depth(body.depth)29 unmodified lines"plan": plan_data}user.preferences["generated_topics"].insert(0, topic_entry)from datetime import timezoneflag_modified(user, "preferences")user.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)await db.commit()103 unmodified linesfrom app.services.chat_service import check_and_reset_quota, _increment_user_activityawait check_and_reset_quota(user, db)await db.refresh(user)if user.daily_message_count >= 50:raise HTTPException(status_code=429, detail="Daily quota exceeded. Come back tomorrow!")exam_dt = None
8 unmodified lines91011121314158 unmodified lines242526272829303132333435368 unmodified lines45464748498 unmodified linesfrom app.api.v1.auth import router as auth_routerfrom app.api.v1.users import router as users_routerfrom app.api.v1.doubts import router as doubts_routerfrom app.api.v1.chat import router as chat_routerfrom app.api.v1.progress import router as progress_routerfrom app.api.v1.plan import router as plan_router8 unmodified linesfrom app.api.v1.attendance import router as attendance_routerfrom app.api.v1.cgpa import router as cgpa_routerfrom app.api.v1.viva import router as viva_routerfrom app.api.v1.payments import router as payments_routerrouter = APIRouter(prefix="/api/v1")router.include_router(auth_router)router.include_router(users_router)router.include_router(doubts_router)router.include_router(chat_router)router.include_router(progress_router)router.include_router(plan_router)8 unmodified linesrouter.include_router(attendance_router)router.include_router(cgpa_router)router.include_router(viva_router)router.include_router(payments_router)8 unmodified lines910111213148 unmodified lines23242526272829303132338 unmodified lines4243448 unmodified linesfrom app.api.v1.auth import router as auth_routerfrom app.api.v1.users import router as users_routerfrom app.api.v1.doubts import router as doubts_routerfrom app.api.v1.chat import router as chat_routerfrom app.api.v1.progress import router as progress_routerfrom app.api.v1.plan import router as plan_router8 unmodified linesfrom app.api.v1.attendance import router as attendance_routerfrom app.api.v1.cgpa import router as cgpa_routerfrom app.api.v1.viva import router as viva_routerrouter = APIRouter(prefix="/api/v1")router.include_router(auth_router)router.include_router(users_router)router.include_router(doubts_router)router.include_router(chat_router)router.include_router(progress_router)router.include_router(plan_router)8 unmodified linesrouter.include_router(attendance_router)router.include_router(cgpa_router)router.include_router(viva_router)
179 unmodified lines180181182179 unmodified linesawait db.commit()return {"status": "success", "message": "Document deleted successfully."}179 unmodified lines180181182183184185186187188189190191192179 unmodified linesawait db.commit()return {"status": "success", "message": "Document deleted successfully."}@router.get("/plans")async def list_plans(user: User = Depends(get_current_user)):return {"message": "Studiq is currently free for all students.","plans": [],"current_tier": "free",}
29 unmodified lines303132333435398 unmodified lines43443543643743843944044144244344444544644744844929 unmodified lines@router.get("/me", response_model=UserResponse)async def get_me(current_user: User = Depends(get_current_user)):return current_user398 unmodified lines@router.get("/me/xp")async def get_xp_status(user: User = Depends(get_current_user)):"""Get the current user's XP, level, and streak info."""from app.services.xp_service import calculate_level, get_title, xp_for_levellevel = calculate_level(user.xp_total or 0)return {"xp_total": user.xp_total or 0,"level": level,"title": get_title(level),"xp_to_next_level": xp_for_level(level + 1) - (user.xp_total or 0),"streak_days": user.streak_days or 0,"longest_streak": user.longest_streak or 0,"streak_freeze_available": user.streak_freeze_available or 0,}29 unmodified lines303132333435363738394041398 unmodified lines44044144244344444544644744844945045145245345445545645745829 unmodified lines@router.get("/me", response_model=UserResponse)async def get_me(current_user: User = Depends(get_current_user)):# Clean up any stale payment preferences from old versionsif current_user.preferences:prefs = dict(current_user.preferences)prefs.pop("tier_expires_at", None)prefs.pop("payment_history", None)current_user.preferences = prefsreturn current_user398 unmodified lines@router.get("/me/xp")async def get_xp(user: User = Depends(get_current_user)):from app.services.xp_service import calculate_level, get_title, xp_for_levellevel = user.level or 1xp_total = user.xp_total or 0return {"xp_total": xp_total,"level": level,"title": get_title(level),"xp_to_next_level": max(0, xp_for_level(level + 1) - xp_total),"xp_for_current_level": xp_for_level(level),"xp_for_next_level": xp_for_level(level + 1),"streak_days": user.streak_days or 0,"longest_streak": user.longest_streak or 0,"streak_freeze_available": user.streak_freeze_available or 1,"total_messages_sent": user.total_messages_sent or 0,}
12345678910114 unmodified lines16171819202118 unmodified lines404142434445464727 unmodified lines757677"""Mock viva endpoints."""import loggingfrom typing import Optionalfrom fastapi import APIRouter, Dependsfrom pydantic import BaseModel, Fieldfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.dependencies import get_current_userfrom app.database import get_db4 unmodified lineslogger = logging.getLogger(__name__)router = APIRouter(prefix="/viva", tags=["Mock Viva"])class VivaStartRequest(BaseModel):topic: str = Field(..., min_length=2, max_length=300)18 unmodified linesasync def start_mock_viva(body: VivaStartRequest,user: User = Depends(get_current_user),):return await generate_viva_questions(user, body.topic, body.subject)@router.post("/evaluate")27 unmodified linesxp_result["leveled_up"] = xp_result["leveled_up"] or bonus_xp["leveled_up"]await db.commit()return {"passed": passed, "xp": xp_result}1234567891011121314154 unmodified lines20212223242526272818 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868727 unmodified lines115116117118119120121122123124125126127128129130"""Mock viva endpoints."""import loggingfrom datetime import datetimefrom typing import Optionalimport pytzfrom fastapi import APIRouter, Dependsfrom pydantic import BaseModel, Fieldfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm.attributes import flag_modifiedfrom app.core.dependencies import get_current_userfrom app.database import get_db4 unmodified lineslogger = logging.getLogger(__name__)router = APIRouter(prefix="/viva", tags=["Mock Viva"])IST = pytz.timezone("Asia/Kolkata")FREE_VIVA_LIMIT = 3class VivaStartRequest(BaseModel):topic: str = Field(..., min_length=2, max_length=300)18 unmodified linesasync def start_mock_viva(body: VivaStartRequest,user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db),):"""Generate viva questions. Enforces 3/month limit with SELECT FOR UPDATE."""# Atomic limit checkresult = await db.execute(select(User).where(User.id == user.id).with_for_update())locked_user = result.scalar_one()current_month = datetime.now(IST).strftime("%Y-%m")prefs = locked_user.preferences or {}if prefs.get("viva_month") != current_month:prefs["vivas_this_month"] = 0prefs["viva_month"] = current_monthviva_count = prefs.get("vivas_this_month", 0)if viva_count >= FREE_VIVA_LIMIT:return {"error": "limit_reached","message": f"You've used all {FREE_VIVA_LIMIT} free vivas this month. Come back next month!","limit": FREE_VIVA_LIMIT,"used": viva_count,}# Increment counter before LLM call to prevent race conditionprefs["vivas_this_month"] = viva_count + 1prefs["total_vivas"] = prefs.get("total_vivas", 0) + 1locked_user.preferences = prefsflag_modified(locked_user, "preferences")await db.commit()# Generate questionsviva_result = await generate_viva_questions(user, body.topic, body.subject)return viva_result@router.post("/evaluate")27 unmodified linesxp_result["leveled_up"] = xp_result["leveled_up"] or bonus_xp["leveled_up"]await db.commit()return {"passed": passed, "xp": xp_result}@router.get("/usage")async def get_viva_usage(user: User = Depends(get_current_user)):current_month = datetime.now(IST).strftime("%Y-%m")prefs = user.preferences or {}used = 0 if prefs.get("viva_month") != current_month else prefs.get("vivas_this_month", 0)return {"used": used,"limit": FREE_VIVA_LIMIT,"total_ever": prefs.get("total_vivas", 0),"resets": "1st of every month",}
31 unmodified lines323334353637383 unmodified lines4243444546474818 unmodified lines6768697071727374757677787931 unmodified linesdescription="Secret key for JWT signing",)jwt_algorithm: str = "HS256"jwt_expiry_minutes: int = 15refresh_token_expiry_days: int = 30# ── OTP ─────────────────────────────────────────────────────────────3 unmodified lines# Option A (recommended): Brevo API — uses HTTPS, works everywhere# Sign up free at brevo.com → Settings → API Keys → Generatebrevo_api_key: str = ""brevo_sender_email: str = "chohanjatt07@gmail.com"gmail_user: str = "" # sender address shown in "From:"# Option B (fallback): Gmail SMTP — blocked on some cloud hosts18 unmodified linesdefault="",description="Gemini API key — REQUIRED, set in .env or dynamically",)gemini_model: str = "gemini-2.5-flash"max_output_tokens: int = 3000# ── RAG Search APIs ──────────────────────────────────────────────tavily_api_key: str = ""serpapi_api_key: str = ""admin_email: str = "penduzsardar@gmail.com"# ── Google Drive Shared Drive Support ────────────────────────────gdrive_shared_drive_id: str = ""31 unmodified lines323334353637383 unmodified lines4243444546474849505118 unmodified lines7071727374757677787980818283848531 unmodified linesdescription="Secret key for JWT signing",)jwt_algorithm: str = "HS256"jwt_expiry_minutes: int = 60refresh_token_expiry_days: int = 30# ── OTP ─────────────────────────────────────────────────────────────3 unmodified lines# Option A (recommended): Brevo API — uses HTTPS, works everywhere# Sign up free at brevo.com → Settings → API Keys → Generatebrevo_api_key: str = ""brevo_sender_email: str = Field(default="",description="Brevo sender email — set in environment variable BREVO_SENDER_EMAIL",)gmail_user: str = "" # sender address shown in "From:"# Option B (fallback): Gmail SMTP — blocked on some cloud hosts18 unmodified linesdefault="",description="Gemini API key — REQUIRED, set in .env or dynamically",)gemini_model: str = "gemini-2.5-flash-latest"max_output_tokens: int = 3000# ── RAG Search APIs ──────────────────────────────────────────────tavily_api_key: str = ""serpapi_api_key: str = ""admin_email: str = Field(default="",description="Admin email address — set in environment variable ADMIN_EMAIL",)# ── Google Drive Shared Drive Support ────────────────────────────gdrive_shared_drive_id: str = ""
54 unmodified lines5556575859606154 unmodified lines) -> User:"""Verify that the user is an application administrator."""from app.config import settingsif not user.is_admin and user.email not in (settings.admin_email, "chohanjatt07@gmail.com"):raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail="Requires administrative privileges",54 unmodified lines5556575859606154 unmodified lines) -> User:"""Verify that the user is an application administrator."""from app.config import settingsif not user.is_admin and user.email != settings.admin_email:raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail="Requires administrative privileges",
79 unmodified lines8081828384858687 unmodified lines1741751761771781791801811822 unmodified lines18518618718818919079 unmodified linesapp = FastAPI(title=settings.app_name,version="0.1.0",lifespan=lifespan,)87 unmodified linesreturn {"status": status, **checks}APP_LATEST_VERSION = "0.4.6"APP_MINIMUM_VERSION = "0.4.6"APP_APK_URL = "https://github.com/baljotchohan/studiq/releases/download/v0.4.6/app-release.apk"@app.get("/app/version")2 unmodified lines"latest_version": APP_LATEST_VERSION,"minimum_version": APP_MINIMUM_VERSION,"apk_url": APP_APK_URL,"release_notes": "StudIQ v0.4.6 — Major update with robust Google Drive RAG sharing, Shared Drive support, collaborative global academic search brain, and enhanced automatic installer fallbacks.","force_update": False,}79 unmodified lines8081828384858687 unmodified lines1741751761771781791801811822 unmodified lines18518618718818919079 unmodified linesapp = FastAPI(title=settings.app_name,version="0.5.0",lifespan=lifespan,)87 unmodified linesreturn {"status": status, **checks}APP_LATEST_VERSION = "0.5.1"APP_MINIMUM_VERSION = "0.5.0"APP_APK_URL = "https://github.com/baljotchohan/studiq/releases/download/v0.5.1/app-release.apk"@app.get("/app/version")2 unmodified lines"latest_version": APP_LATEST_VERSION,"minimum_version": APP_MINIMUM_VERSION,"apk_url": APP_APK_URL,"release_notes": "StudIQ v0.5.1 — Mock Viva limits, connection timeouts, and labfile limit race condition fixes.","force_update": False,}
2 unmodified lines345678916 unmodified lines262728292 unmodified linesimport uuidfrom datetime import datetimefrom sqlalchemy import ForeignKey, Integer, String, UniqueConstraintfrom sqlalchemy.orm import Mapped, mapped_columnfrom sqlalchemy.sql import func16 unmodified linesattended_classes: Mapped[int] = mapped_column(Integer, default=0)required_percentage: Mapped[int] = mapped_column(Integer, default=75)created_at: Mapped[datetime] = mapped_column(server_default=func.now())updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), onupdate=func.now())2 unmodified lines345678916 unmodified lines2627282930312 unmodified linesimport uuidfrom datetime import datetimefrom sqlalchemy import ForeignKey, Integer, String, UniqueConstraint, textfrom sqlalchemy.orm import Mapped, mapped_columnfrom sqlalchemy.sql import func16 unmodified linesattended_classes: Mapped[int] = mapped_column(Integer, default=0)required_percentage: Mapped[int] = mapped_column(Integer, default=75)created_at: Mapped[datetime] = mapped_column(server_default=func.now())updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), server_onupdate=text("now()"))
3 unmodified lines4567891015 unmodified lines262728293031323 unmodified linesfrom datetime import datetimefrom typing import Optionalfrom sqlalchemy import ForeignKey, Stringfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom sqlalchemy.sql import func15 unmodified linestopic_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)created_at: Mapped[datetime] = mapped_column(server_default=func.now())updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), onupdate=func.now())# Relationships3 unmodified lines4567891015 unmodified lines262728293031323 unmodified linesfrom datetime import datetimefrom typing import Optionalfrom sqlalchemy import ForeignKey, String, textfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom sqlalchemy.sql import func15 unmodified linestopic_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)created_at: Mapped[datetime] = mapped_column(server_default=func.now())updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), server_onupdate=text("now()"))# Relationships
3 unmodified lines4567891018 unmodified lines2930313233343529 unmodified lines65666768693 unmodified linesfrom datetime import datetimefrom typing import Optionalfrom sqlalchemy import ForeignKey, String, Text, Float, Integer, DateTimefrom sqlalchemy.orm import Mapped, mapped_columnfrom sqlalchemy.sql import func18 unmodified linescreated_at: Mapped[datetime] = mapped_column(server_default=func.now(), index=True)updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), onupdate=func.now())29 unmodified linescreated_at: Mapped[datetime] = mapped_column(server_default=func.now(), index=True)updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), onupdate=func.now())3 unmodified lines4567891018 unmodified lines2930313233343529 unmodified lines65666768693 unmodified linesfrom datetime import datetimefrom typing import Optionalfrom sqlalchemy import ForeignKey, String, Text, Float, Integer, DateTime, textfrom sqlalchemy.orm import Mapped, mapped_columnfrom sqlalchemy.sql import func18 unmodified linescreated_at: Mapped[datetime] = mapped_column(server_default=func.now(), index=True)updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), server_onupdate=text("now()"))29 unmodified linescreated_at: Mapped[datetime] = mapped_column(server_default=func.now(), index=True)updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), server_onupdate=text("now()"))
8 unmodified lines910111213141572 unmodified lines88899091928 unmodified linesfrom datetime import date, datetimefrom typing import Any, Optionalfrom sqlalchemy import Date, Integer, String, Text, JSONfrom sqlalchemy.dialects.postgresql import JSONBfrom sqlalchemy.orm import Mapped, mapped_columnfrom sqlalchemy.sql import func72 unmodified lines# ── Timestamps ───────────────────────────────────────────────────created_at: Mapped[datetime] = mapped_column(server_default=func.now())updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), onupdate=func.now())8 unmodified lines910111213141572 unmodified lines88899091928 unmodified linesfrom datetime import date, datetimefrom typing import Any, Optionalfrom sqlalchemy import Date, Integer, String, Text, JSON, textfrom sqlalchemy.dialects.postgresql import JSONBfrom sqlalchemy.orm import Mapped, mapped_columnfrom sqlalchemy.sql import func72 unmodified lines# ── Timestamps ───────────────────────────────────────────────────created_at: Mapped[datetime] = mapped_column(server_default=func.now())updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), server_onupdate=text("now()"))
31 unmodified lines3233343536373831 unmodified lines@model_validator(mode="after")def check_admin_email(self) -> "UserResponse":from app.config import settingsif self.email in (settings.admin_email, "chohanjatt07@gmail.com"):self.is_admin = Truereturn self31 unmodified lines3233343536373831 unmodified lines@model_validator(mode="after")def check_admin_email(self) -> "UserResponse":from app.config import settingsif settings.admin_email and self.email == settings.admin_email:self.is_admin = Truereturn self
4 unmodified lines567891049 unmodified lines6061626364651 unmodified line676869707172737475767778798081828384858687888913 unmodified lines1031041051061071081091101111121131141151161171181191201211221234 unmodified linesfrom typing import Optionalimport pytzfrom sqlalchemy.orm.attributes import flag_modifiedfrom app.models.user import User49 unmodified lines"""async def generate_assignment(user: User,question: str,1 unmodified lineformat_type: str = "descriptive",word_limit: int = 300,depth: str = "detailed",db=None,) -> dict:current_month = datetime.now(IST).strftime("%Y-%m")prefs = user.preferences or {}if user.tier == "free":if prefs.get("assignment_month") != current_month:current_month_count = 0else:current_month_count = prefs.get("assignments_this_month", 0)if current_month_count >= FREE_ASSIGNMENT_LIMIT:return {"error": "limit_reached","message": f"You've used all {FREE_ASSIGNMENT_LIMIT} free assignments this month. Upgrade to Studiq Plus for unlimited!","used": current_month_count,"limit": FREE_ASSIGNMENT_LIMIT,}prompt = ASSIGNMENT_PROMPT.format(13 unmodified linesif not isinstance(result, dict) or "answer" not in result:return {"error": "generation_failed", "message": "Failed to generate assignment. Please try again."}if db and user:prefs = user.preferences or {}if prefs.get("assignment_month") != current_month:prefs["assignments_this_month"] = 1prefs["assignment_month"] = current_monthelse:prefs["assignments_this_month"] = prefs.get("assignments_this_month", 0) + 1prefs["total_assignments"] = prefs.get("total_assignments", 0) + 1user.preferences = prefsflag_modified(user, "preferences")await db.flush()result["remaining"] = (FREE_ASSIGNMENT_LIMIT - (user.preferences or {}).get("assignments_this_month", 0)if user.tier == "free"else -1)return result4 unmodified lines5678910111249 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051 unmodified line10710810911011111211311411511611711811912012112213 unmodified lines1361371381391401411421434 unmodified linesfrom typing import Optionalimport pytzfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm.attributes import flag_modifiedfrom app.models.user import User49 unmodified lines"""async def _check_and_increment_assignment_count(user: User, db: AsyncSession) -> bool:"""Atomically check and increment the monthly assignment count.Returns True if allowed, False if limit reached.Uses SELECT FOR UPDATE to prevent race conditions."""# Lock the user row for this transactionresult = await db.execute(select(User).where(User.id == user.id).with_for_update())locked_user = result.scalar_one()ist = pytz.timezone("Asia/Kolkata")current_month = datetime.now(ist).strftime("%Y-%m")prefs = locked_user.preferences or {}# Reset counter if new monthif prefs.get("assignment_month") != current_month:prefs["assignments_this_month"] = 0prefs["assignment_month"] = current_monthcurrent_count = prefs.get("assignments_this_month", 0)if current_count >= FREE_ASSIGNMENT_LIMIT:return Falseprefs["assignments_this_month"] = current_count + 1prefs["total_assignments"] = prefs.get("total_assignments", 0) + 1locked_user.preferences = prefsfrom datetime import timezoneflag_modified(locked_user, "preferences")locked_user.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)await db.flush()# Sync back to the user object in memoryuser.preferences = prefsreturn Trueasync def generate_assignment(user: User,question: str,1 unmodified lineformat_type: str = "descriptive",word_limit: int = 300,depth: str = "detailed",db: Optional[AsyncSession] = None,) -> dict:if db:allowed = await _check_and_increment_assignment_count(user, db)if not allowed:return {"error": "limit_reached","message": f"You've used all {FREE_ASSIGNMENT_LIMIT} free assignments this month. More slots open next month!","limit": FREE_ASSIGNMENT_LIMIT,"resets_on": "1st of next month",}prompt = ASSIGNMENT_PROMPT.format(13 unmodified linesif not isinstance(result, dict) or "answer" not in result:return {"error": "generation_failed", "message": "Failed to generate assignment. Please try again."}result["remaining"] = (FREE_ASSIGNMENT_LIMIT - (user.preferences or {}).get("assignments_this_month", 0))return result
130 unmodified lines13113213313413513613722 unmodified lines160161162163164165166167130 unmodified linesasync def refresh_access_token(refresh_token: str, db: AsyncSession) -> dict:"""Issue a new access token from a valid refresh token."""from app.core.security import decode_tokenfrom jose import JWTError22 unmodified linesraise AuthError("Invalid or expired refresh token.", status_code=401)new_access = create_access_token(str(user.id))return {"access_token": new_access,"token_type": "bearer",}130 unmodified lines13113213313413513613722 unmodified lines160161162163164165166167168169130 unmodified linesasync def refresh_access_token(refresh_token: str, db: AsyncSession) -> dict:"""Issue a new access token AND rotate the refresh token."""from app.core.security import decode_tokenfrom jose import JWTError22 unmodified linesraise AuthError("Invalid or expired refresh token.", status_code=401)new_access = create_access_token(str(user.id))new_refresh = create_refresh_token(str(user.id)) # Rotate on every usereturn {"access_token": new_access,"refresh_token": new_refresh, # Always return new refresh token"token_type": "bearer",}
9 unmodified lines1011121314151613 unmodified lines303132333435363738394041424344454647484950515253545556575877 unmodified lines136137138139140141142143144145146147148149150151152153154118 unmodified lines2732742752762772785 unmodified lines28428528628728828929049 unmodified lines34034134234334434545 unmodified lines39139239339439539639739839940040140240340440540640722 unmodified lines430431432433434435436126 unmodified lines56356456556656756856957057157257357457557657757819 unmodified lines59859960060160260360460560660760856 unmodified lines66566666766866967097 unmodified lines7687697707717727737747757767777789 unmodified linesimport pytzfrom fastapi import HTTPExceptionfrom sqlalchemy import and_, func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.memory import DailyMemory13 unmodified lines# ── Shared activity helper ───────────────────────────────────────────async def _increment_user_activity(user: User, db: AsyncSession, response_text: str = None) -> None:"""Increment message count, update streak/last-active date (IST), and accumulate tokens."""ist = pytz.timezone("Asia/Kolkata")today_date = datetime.now(ist).date()yesterday = today_date - timedelta(days=1)user.daily_message_count += 1user.total_messages_sent = (user.total_messages_sent or 0) + 1if user.last_active_date == yesterday:# Consecutive day — increment streakuser.streak_days = (user.streak_days or 0) + 1elif user.last_active_date != today_date:# Missed a day or first day — reset streak to 1user.streak_days = 1user.last_active_date = today_date# Accumulate tokens if response_text is providedif response_text:words = len(response_text.split())tokens = int(words * 1.33) if words > 0 else max(1, int(len(response_text) / 4.0))user.tokens_consumed = (user.tokens_consumed or 0) + tokens# ── Nova Action Helpers ──────────────────────────────────────────────77 unmodified linescontent: str,db: AsyncSession,) -> None:"""Auto-save a study note for any substantial assistant response (>200 chars)."""if len(content) < 200:returnfrom app.models.study_note import StudyNotenote = StudyNote(user_id=user_id,conversation_id=conv_id,topic_id=topic_info.get("topic_id") if topic_info else None,topic_name=topic_info.get("topic_name") if topic_info else None,subject_name=topic_info.get("subject_name") if topic_info else None,content=content[:5000],)db.add(note)async def _update_progress_with_strength(118 unmodified linesmessage: str,conversation_id_str: Optional[str],db: AsyncSession,) -> AsyncGenerator[str, None]:"""Main chat flow — validates quota, builds context, streams response.5 unmodified lines# 2. Check and reset quotaawait check_and_reset_quota(user, db)if user.tier == "free" and user.daily_message_count >= 50:yield json.dumps({"type": "error","content": "You've used today's 50 free messages. Come back tomorrow!",49 unmodified linesplan_summary=plan_summary,rag_context=rag_context,user_facts=user.user_facts,)# 8. Format message history for LLM45 unmodified linesawait _increment_user_activity(user, db, clean_response)from app.services.xp_service import award_xp as _award_xpxp_result = await _award_xp(user, "chat_message")await db.commit()# Maybe complete a matching plan sessionsession_completed = Nonetry:session_completed = await _maybe_complete_plan_session(user_id, conv_id, db)if session_completed:await db.commit()except Exception as e:logger.error(f"Plan session completion check failed: {e}")# 12. Send done signal — includes clean text and optional action proposaltry:from app.services.memory_service import maybe_update_daily_memory22 unmodified lines"""Start a chat focused on a specific topic."""user = await get_user_with_academic(user_id, db)await check_and_reset_quota(user, db)if user.tier == "free" and user.daily_message_count >= 50:yield json.dumps({"type": "error","content": "You've used today's 50 free messages. Come back tomorrow!",126 unmodified linesawait _increment_user_activity(user, db, clean_response)from app.services.xp_service import award_xp as _award_xpxp_result = await _award_xp(user, "chat_message")await db.commit()session_completed = Nonetry:session_completed = await _maybe_complete_plan_session(user_id, conv_id, db)if session_completed:await db.commit()except Exception as e:logger.error(f"Plan session completion check failed: {e}")try:from app.services.memory_service import maybe_update_daily_memoryawait maybe_update_daily_memory(user_id, db)19 unmodified linesdb: AsyncSession,subject_name: Optional[str] = None,conversation_id_str: Optional[str] = None,) -> AsyncGenerator[str, None]:"""Start a chat to learn any topic without requiring a syllabus."""user = await get_user_with_academic(user_id, db)await check_and_reset_quota(user, db)if user.tier == "free" and user.daily_message_count >= 50:yield json.dumps({"type": "error","content": "You've used today's 50 free messages. Come back tomorrow!",56 unmodified linesrecent_topics=daily_mem.topics_covered if daily_mem else [],student_bio=user.bio,user_facts=user.user_facts,)system_prompt += f"\n\nThe user wants to learn about '{topic_name}'{f' from {subject_name}' if subject_name else ''}. Teach them in an engaging, interactive way. Start with a brief overview and ask if they are ready to dive deeper."97 unmodified linesif conversation_id:conditions.append(Message.conversation_id == conversation_id)else:# Fallback for old behaviour or no conversationfrom datetime import timezonenow_utc = datetime.now(timezone.utc).replace(tzinfo=None)today_start = datetime.combine(now_utc.date(), datetime.min.time())conditions.append(Message.created_at >= today_start)result = await db.execute(select(Message).where(and_(*conditions))9 unmodified lines1011121314151613 unmodified lines3031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747577 unmodified lines153154155156157158159160161162163164165166167168169170171172173174175176118 unmodified lines2952962972982993003015 unmodified lines30730830931031131231331449 unmodified lines36436536636736836937045 unmodified lines41641741841942042142242342442542642742842943043122 unmodified lines454455456457458459460461126 unmodified lines58858959059159259359459559659759859960060160219 unmodified lines62262362462562662762862963063163263363456 unmodified lines69169269369469569669797 unmodified lines7957967977987998008018028038048058068078088099 unmodified linesimport pytzfrom fastapi import HTTPExceptionfrom sqlalchemy import and_, func, select, updatefrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.memory import DailyMemory13 unmodified lines# ── Shared activity helper ───────────────────────────────────────────async def _increment_user_activity(user: User, db: AsyncSession, response_text: str = None) -> None:"""Atomically increment message count and update streak/last-active (IST)."""ist = pytz.timezone("Asia/Kolkata")today_date = datetime.now(ist).date()yesterday = today_date - timedelta(days=1)# Streak logic (still in-memory, low stakes)if user.last_active_date == yesterday:new_streak = (user.streak_days or 0) + 1elif user.last_active_date != today_date:new_streak = 1else:new_streak = user.streak_days or 1# Token estimatenew_tokens = 0if response_text:words = len(response_text.split())new_tokens = int(words * 1.33) if words > 0 else max(1, int(len(response_text) / 4.0))# Atomic increment via SQL — prevents race conditionawait db.execute(update(User).where(User.id == user.id).values(daily_message_count=User.daily_message_count + 1,total_messages_sent=User.total_messages_sent + 1,streak_days=new_streak,last_active_date=today_date,tokens_consumed=User.tokens_consumed + new_tokens,))# Keep in-memory values in sync so the rest of the request sees themuser.daily_message_count += 1user.total_messages_sent = (user.total_messages_sent or 0) + 1user.streak_days = new_streakuser.last_active_date = today_dateuser.tokens_consumed = (user.tokens_consumed or 0) + new_tokens# ── Nova Action Helpers ──────────────────────────────────────────────77 unmodified linescontent: str,db: AsyncSession,) -> None:"""Auto-save a study note. Failures are logged but never surface to the user."""if len(content) < 200:returntry:async with db.begin_nested():from app.models.study_note import StudyNotenote = StudyNote(user_id=user_id,conversation_id=conv_id,topic_id=topic_info.get("topic_id") if topic_info else None,topic_name=topic_info.get("topic_name") if topic_info else None,subject_name=topic_info.get("subject_name") if topic_info else None,content=content[:5000],)db.add(note)await db.flush()except Exception as e:logger.warning(f"Auto-save study note failed (non-critical): {e}")async def _update_progress_with_strength(118 unmodified linesmessage: str,conversation_id_str: Optional[str],db: AsyncSession,tutor_mode: Optional[str] = None,) -> AsyncGenerator[str, None]:"""Main chat flow — validates quota, builds context, streams response.5 unmodified lines# 2. Check and reset quotaawait check_and_reset_quota(user, db)await db.refresh(user)if user.daily_message_count >= 50:yield json.dumps({"type": "error","content": "You've used today's 50 free messages. Come back tomorrow!",49 unmodified linesplan_summary=plan_summary,rag_context=rag_context,user_facts=user.user_facts,tutor_mode=tutor_mode,)# 8. Format message history for LLM45 unmodified linesawait _increment_user_activity(user, db, clean_response)from app.services.xp_service import award_xp as _award_xpxp_result = await _award_xp(user, "chat_message")# Single atomic commit covers messages + XP + study notes + memory (via updates)session_completed = Nonetry:session_completed = await _maybe_complete_plan_session(user_id, conv_id, db)except Exception as e:logger.error(f"Plan session completion check failed: {e}")await db.commit()# 12. Send done signal — includes clean text and optional action proposaltry:from app.services.memory_service import maybe_update_daily_memory22 unmodified lines"""Start a chat focused on a specific topic."""user = await get_user_with_academic(user_id, db)await check_and_reset_quota(user, db)await db.refresh(user)if user.daily_message_count >= 50:yield json.dumps({"type": "error","content": "You've used today's 50 free messages. Come back tomorrow!",126 unmodified linesawait _increment_user_activity(user, db, clean_response)from app.services.xp_service import award_xp as _award_xpxp_result = await _award_xp(user, "chat_message")session_completed = Nonetry:session_completed = await _maybe_complete_plan_session(user_id, conv_id, db)except Exception as e:logger.error(f"Plan session completion check failed: {e}")await db.commit()try:from app.services.memory_service import maybe_update_daily_memoryawait maybe_update_daily_memory(user_id, db)19 unmodified linesdb: AsyncSession,subject_name: Optional[str] = None,conversation_id_str: Optional[str] = None,tutor_mode: Optional[str] = None,) -> AsyncGenerator[str, None]:"""Start a chat to learn any topic without requiring a syllabus."""user = await get_user_with_academic(user_id, db)await check_and_reset_quota(user, db)await db.refresh(user)if user.daily_message_count >= 50:yield json.dumps({"type": "error","content": "You've used today's 50 free messages. Come back tomorrow!",56 unmodified linesrecent_topics=daily_mem.topics_covered if daily_mem else [],student_bio=user.bio,user_facts=user.user_facts,tutor_mode=tutor_mode,)system_prompt += f"\n\nThe user wants to learn about '{topic_name}'{f' from {subject_name}' if subject_name else ''}. Teach them in an engaging, interactive way. Start with a brief overview and ask if they are ready to dive deeper."97 unmodified linesif conversation_id:conditions.append(Message.conversation_id == conversation_id)else:# Fallback: today's messages using IST boundary (not UTC!)ist = pytz.timezone("Asia/Kolkata")today_ist = datetime.now(ist).date()# Convert IST midnight to UTC for DB comparisonist_midnight = ist.localize(datetime(today_ist.year, today_ist.month, today_ist.day, 0, 0, 0))utc_midnight = ist_midnight.astimezone(pytz.utc).replace(tzinfo=None)conditions.append(Message.created_at >= utc_midnight)result = await db.execute(select(Message).where(and_(*conditions))
36 unmodified lines37383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899036 unmodified lines"""Raised when an ID token cannot be verified."""def _load_credentials_from_env() -> Optional[credentials.Base]:raw = settings.firebase_credentials_jsonif raw:# Allow base64 to dodge Railway's strict env-var multiline rules.if not raw.lstrip().startswith("{"):try:raw = base64.b64decode(raw).decode("utf-8")except (ValueError, binascii.Error) as exc:raise FirebaseAuthError(f"FIREBASE_CREDENTIALS_JSON is not valid JSON or base64: {exc}")try:data = json.loads(raw)except json.JSONDecodeError as exc:raise FirebaseAuthError(f"FIREBASE_CREDENTIALS_JSON is not valid JSON: {exc}")return credentials.Certificate(data)path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")if path and os.path.exists(path):return credentials.Certificate(path)return Nonedef ensure_initialized() -> None:"""Initialize the Firebase Admin SDK exactly once. Safe to call repeatedly."""global _initializedif _initialized:returnwith _init_lock:if _initialized:returntry:firebase_admin.get_app()_initialized = Truereturnexcept ValueError:passcred = _load_credentials_from_env()if cred is not None:firebase_admin.initialize_app(cred)else:if not os.environ.get("GOOGLE_CLOUD_PROJECT"):os.environ["GOOGLE_CLOUD_PROJECT"] = "studiq-etlabs"# Will fall back to ADC; raises if nothing is configured.firebase_admin.initialize_app()logger.info("firebase_admin initialized")_initialized = Truedef verify_id_token(id_token: str) -> dict:36 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707136 unmodified lines"""Raised when an ID token cannot be verified."""def ensure_initialized():global _initializedif _initialized:returncred_json = os.environ.get("FIREBASE_CREDENTIALS_JSON", "")if not cred_json:raise RuntimeError("FIREBASE_CREDENTIALS_JSON environment variable is not set. ""Set it to the raw JSON string or base64-encoded JSON of your ""Firebase service account.")# Support both raw JSON string and base64-encoded JSONtry:cred_dict = json.loads(cred_json)except json.JSONDecodeError:try:cred_dict = json.loads(base64.b64decode(cred_json).decode("utf-8"))except Exception:raise RuntimeError("FIREBASE_CREDENTIALS_JSON is set but could not be parsed. ""Ensure it is a valid JSON string or base64-encoded JSON.")cred = credentials.Certificate(cred_dict)if not firebase_admin._apps:firebase_admin.initialize_app(cred)_initialized = Truedef verify_id_token(id_token: str) -> dict:
344 unmodified lines34534634734834935035135235335435510 unmodified lines36636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440538 unmodified lines444445446447448449450344 unmodified lines) -> AsyncGenerator[str, None]:"""Stream response chunks from Gemini API."""api_key = settings.gemini_api_keygemini_model = settings.gemini_model or "gemini-2.5-flash"if not api_key:raise ValueError("GEMINI_API_KEY is not set.")url = f"{GEMINI_BASE_URL}/{gemini_model}:streamGenerateContent?key={api_key}"contents = []for msg in messages:10 unmodified lines},"generationConfig": {"temperature": 0.7,"maxOutputTokens": 2000,}}async with httpx.AsyncClient() as client:async with client.stream("POST", url, json=payload, timeout=60.0) as response:response.raise_for_status()decoder = json.JSONDecoder()buffer = ""async for line in response.aiter_lines():if not line:continuebuffer += line + "\n"while True:buffer = buffer.lstrip()if buffer.startswith("["):buffer = buffer[1:].lstrip()elif buffer.startswith(","):buffer = buffer[1:].lstrip()elif buffer.startswith("]"):buffer = buffer[1:].lstrip()if not buffer:breaktry:obj, idx = decoder.raw_decode(buffer)buffer = buffer[idx:]if "candidates" in obj and len(obj["candidates"]) > 0:parts = obj["candidates"][0].get("content", {}).get("parts", [])if parts and "text" in parts[0] and parts[0]["text"]:yield parts[0]["text"]except json.JSONDecodeError:breakasync def call_llm(38 unmodified lines},"generationConfig": {"temperature": 0.7,"maxOutputTokens": 1000,}}344 unmodified lines34534634734834935035135235335435510 unmodified lines36636736836937037137237337437537637737837938038138238338438538638738838939039139239339438 unmodified lines433434435436437438439344 unmodified lines) -> AsyncGenerator[str, None]:"""Stream response chunks from Gemini API."""api_key = settings.gemini_api_keygemini_model = settings.gemini_model or "gemini-2.5-flash-latest"if not api_key:raise ValueError("GEMINI_API_KEY is not set.")url = f"{GEMINI_BASE_URL}/{gemini_model}:streamGenerateContent?key={api_key}&alt=sse"contents = []for msg in messages:10 unmodified lines},"generationConfig": {"temperature": 0.7,"maxOutputTokens": settings.max_output_tokens,}}async with httpx.AsyncClient(timeout=httpx.Timeout(60.0)) as client:async with client.stream("POST", url, json=payload) as response:response.raise_for_status()async for line in response.aiter_lines():# SSE format: lines starting with "data: "if not line.startswith("data: "):continuedata_str = line[6:].strip()if data_str == "[DONE]" or not data_str:continuetry:obj = json.loads(data_str)candidates = obj.get("candidates", [])if candidates:parts = candidates[0].get("content", {}).get("parts", [])if parts and parts[0].get("text"):yield parts[0]["text"]except json.JSONDecodeError:continueasync def call_llm(38 unmodified lines},"generationConfig": {"temperature": 0.7,"maxOutputTokens": settings.max_output_tokens,}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Razorpay payment integration."""
import base64import hashlibimport hmacimport logging
import httpx
from app.config import settings
logger = logging.getLogger(__name__)
PLANS = { "plus_monthly": { "amount": 9900, "currency": "INR", "name": "Studiq Plus Monthly", "tier": "plus", "duration_days": 30, }, "plus_semester": { "amount": 49900, "currency": "INR", "name": "Studiq Plus Semester", "tier": "plus", "duration_days": 180, }, "pro_yearly": { "amount": 99900, "currency": "INR", "name": "Studiq Pro Yearly", "tier": "pro", "duration_days": 365, }, "group_monthly": { "amount": 29900, "currency": "INR", "name": "Group Pack (4 friends)", "tier": "plus", "duration_days": 30, },}
async def create_razorpay_order( plan_id: str, user_id: str, user_email: str, user_name: str,) -> dict: plan = PLANS.get(plan_id) if not plan: return {"error": "Invalid plan"}
key_id = settings.razorpay_key_id key_secret = settings.razorpay_key_secret
if not key_id or not key_secret: return {"error": "Payment not configured"}
auth = base64.b64encode(f"{key_id}:{key_secret}".encode()).decode()
async with httpx.AsyncClient() as client: resp = await client.post( "https://api.razorpay.com/v1/orders", json={ "amount": plan["amount"], "currency": plan["currency"], "receipt": f"studiq_{user_id[:8]}_{plan_id}", "notes": { "user_id": str(user_id), "plan_id": plan_id, "user_email": user_email, }, }, headers={"Authorization": f"Basic {auth}"}, timeout=30.0, ) resp.raise_for_status() order = resp.json()
return { "order_id": order["id"], "amount": plan["amount"], "currency": plan["currency"], "plan_name": plan["name"], "key_id": key_id, "user_name": user_name, "user_email": user_email, }
def verify_razorpay_signature(order_id: str, payment_id: str, signature: str) -> bool: key_secret = settings.razorpay_key_secret message = f"{order_id}|{payment_id}" expected = hmac.new( key_secret.encode(), message.encode(), hashlib.sha256, ).hexdigest() return hmac.compare_digest(expected, signature)206 unmodified lines2072082092102112122132142152162172182191 unmodified line22122222322422522670 unmodified lines29729829930030130247 unmodified lines350351352353354355356206 unmodified linesfor attempt in range(3):try:raw = await call_llm_structured(prompt)parsed = Nonetry:parsed = safe_load_json(raw)except json.JSONDecodeError:parsed = _extract_json_block(raw)if parsed and _validate_study_plan_data(parsed):plan_data = parsedbreakelse:1 unmodified lineexcept Exception as e:logger.error(f"Plan generation attempt {attempt + 1} failed: {e}")if attempt == 2:raise HTTPException(500, "Failed to generate a valid study plan. Please try again.")# 9. Deactivate previous active plans70 unmodified linesif modified:plan.plan_data = plan.plan_dataflag_modified(plan, "plan_data")await db.commit()return rolled_over_sessions47 unmodified lines# Force JSONB update detectionplan.plan_data = plan_dataflag_modified(plan, "plan_data")# Auto-update topic progresstopic_updated = None206 unmodified lines2072082092102112122132142152162172181 unmodified line22022122222322422522622770 unmodified lines29829930030130230330430547 unmodified lines353354355356357358359360361206 unmodified linesfor attempt in range(3):try:raw = await call_llm_structured(prompt)parsed = safe_load_json(raw)if not parsed or not isinstance(parsed, dict):logger.error("Plan generation returned invalid JSON from LLM")raise HTTPException(500, "Failed to generate a valid study plan. Please try again.")if _validate_study_plan_data(parsed):plan_data = parsedbreakelse:1 unmodified lineexcept Exception as e:logger.error(f"Plan generation attempt {attempt + 1} failed: {e}")if attempt == 2:if isinstance(e, HTTPException):raise eraise HTTPException(500, "Failed to generate a valid study plan. Please try again.")# 9. Deactivate previous active plans70 unmodified linesif modified:plan.plan_data = plan.plan_dataflag_modified(plan, "plan_data")from datetime import datetime, timezoneplan.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)await db.commit()return rolled_over_sessions47 unmodified lines# Force JSONB update detectionplan.plan_data = plan_datafrom datetime import datetime, timezoneflag_modified(plan, "plan_data")plan.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)# Auto-update topic progresstopic_updated = None
20 unmodified lines212223242526272829303132105 unmodified lines13813914014114214314460 unmodified lines20520620720820921021120 unmodified linesplan_summary: Optional[str] = None,rag_context: Optional[str] = None,user_facts: Optional[str] = None,) -> str:"""Build Nova's system prompt with intent-aware response modes."""syllabus_section = _format_syllabus(syllabus_subjects)has_syllabus = bool(syllabus_subjects)# ── Memory context ────────────────────────────────────────────memory_section = ""if daily_memory:105 unmodified lines- "what is today tasks" → "Your tasks for today come from your study plan! Tap 'Plan' tab to see them, or I can generate one for you. Want me to?"- "what's my plan" → Summarize the plan_summary section above. If no plan: offer to create one.- "how do I upload syllabus" → Walk them through: home tab → tap 'Upload Syllabus' → take photo or pick PDF.❌ DO NOT generate "Diving into: What Is Today Tasks ✨" format. NEVER.▸ TOPIC_LEARNING → THIS is where you teach properly:- Start with 1-line crisp definition60 unmodified lines📚 THEIR SYLLABUS═══════════════════════════════════════════════════{syllabus_section}{plan_section}{focus_section}{memory_section}{topics_section}{bio_section}{user_facts_section}{rag_context_section}{actions_guide}═══════════════════════════════════════════════════⚡ FINAL CHECKS BEFORE YOU SEND20 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667105 unmodified lines17317417517617717817960 unmodified lines24024124224324424524620 unmodified linesplan_summary: Optional[str] = None,rag_context: Optional[str] = None,user_facts: Optional[str] = None,tutor_mode: Optional[str] = None,) -> str:"""Build Nova's system prompt with intent-aware response modes."""syllabus_section = _format_syllabus(syllabus_subjects)has_syllabus = bool(syllabus_subjects)# ── Tutor mode instructions ───────────────────────────────────tutor_mode_section = ""if tutor_mode:if tutor_mode == "socratic":tutor_mode_section = """── TUTORING STYLE: SOCRATIC METHOD (ACTIVE RECALL) ──Do not give direct answers immediately! Ask guiding questions to lead the student to the concept.Help them break the problem down. When they make an attempt, praise their progress, correct their misconceptions, and ask the next step."""elif tutor_mode == "analogy":tutor_mode_section = """── TUTORING STYLE: ANALOGY MASTER ──Explain all concepts using simple, creative, everyday analogies (e.g. comparing packets in networking to post office letters, or RAM to a student desk).Keep the tone fun and visual."""elif tutor_mode == "eli5":tutor_mode_section = """── TUTORING STYLE: EXPLAIN LIKE I'M 5 ──Break down the topic to its absolute simplest elements. Avoid complex jargon.Use basic words, short sentences, and super simple examples."""elif tutor_mode == "exam":tutor_mode_section = """── TUTORING STYLE: EXAM COACH ──Focus heavily on university exam patterns (2-mark, 5-mark, and 10-mark questions).Break down answers into clear bullet points, highlight the exact key phrases that fetch marks, and mention common exam pitfalls."""elif tutor_mode == "code":tutor_mode_section = """── TUTORING STYLE: CODE BUDDY ──Provide practical coding examples. Interleave code snippets in your response.Frequently encourage the student to write or debug code. Present them with coding challenges and invite them to copy-paste their attempts."""# ── Memory context ────────────────────────────────────────────memory_section = ""if daily_memory:105 unmodified lines- "what is today tasks" → "Your tasks for today come from your study plan! Tap 'Plan' tab to see them, or I can generate one for you. Want me to?"- "what's my plan" → Summarize the plan_summary section above. If no plan: offer to create one.- "how do I upload syllabus" → Walk them through: home tab → tap 'Upload Syllabus' → take photo or pick PDF.- ❌ DO NOT generate "Diving into: What Is Today Tasks ✨" format. NEVER.▸ TOPIC_LEARNING → THIS is where you teach properly:- Start with 1-line crisp definition60 unmodified lines📚 THEIR SYLLABUS═══════════════════════════════════════════════════{syllabus_section}{plan_section}{focus_section}{memory_section}{topics_section}{bio_section}{user_facts_section}{rag_context_section}{tutor_mode_section}{actions_guide}═══════════════════════════════════════════════════⚡ FINAL CHECKS BEFORE YOU SEND
90 unmodified lines919293949596973 unmodified lines10110210310410510610710890 unmodified lines# 3. Create Base Google Drive folder for RAG_AGENT_STATUS["current_task"] = "Initializing Google Drive storage..."# Setup base folder shared with the Service Account on developer's Drive (e.g. penduzsardar@gmail.com shared folder)base_folder_name = f"Studiq_RAG_{user.name or 'Student'}_{user_id}"base_folder_id = gdrive_storage.get_or_create_folder(base_folder_name)3 unmodified linesemails_to_share.append(settings.admin_email)if user.email:emails_to_share.append(user.email)if "chohanjatt07@gmail.com" not in emails_to_share:emails_to_share.append("chohanjatt07@gmail.com")log_agent_event(f"Sharing Google Drive folder '{base_folder_name}' with: {emails_to_share}")gdrive_storage.share_folder_or_file(base_folder_id, emails_to_share, role="writer")90 unmodified lines919293949596973 unmodified lines10110210310410510610710890 unmodified lines# 3. Create Base Google Drive folder for RAG_AGENT_STATUS["current_task"] = "Initializing Google Drive storage..."# Setup base folder shared with the Service Account on developer's Drive (e.g. admin shared folder)base_folder_name = f"Studiq_RAG_{user.name or 'Student'}_{user_id}"base_folder_id = gdrive_storage.get_or_create_folder(base_folder_name)3 unmodified linesemails_to_share.append(settings.admin_email)if user.email:emails_to_share.append(user.email)if settings.admin_email and settings.admin_email not in emails_to_share:emails_to_share.append(settings.admin_email)log_agent_event(f"Sharing Google Drive folder '{base_folder_name}' with: {emails_to_share}")gdrive_storage.share_folder_or_file(base_folder_id, emails_to_share, role="writer")
58 unmodified lines5960616263646566676869707158 unmodified linesreturn "".join(parts)def safe_load_json(text: str) -> Any:"""Parse JSON string safely by cleaning it first and passing strict=Falseto allow control characters like unescaped newlines/tabs."""cleaned = clean_json_text(text)try:return json.loads(cleaned, strict=False)except json.JSONDecodeError as e:logger.error(f"Failed to parse JSON. Error: {e}. Cleaned input was: {cleaned}")raise e58 unmodified lines596061626364656667686970717273747576777879808182838458 unmodified linesreturn "".join(parts)def safe_load_json(text: str) -> dict | list | None:"""Parse JSON from LLM output. Strips markdown fences. Returns None on failure."""if not text:return None# Strip markdown code fencescleaned = text.strip()if cleaned.startswith("```"):lines = cleaned.split("\n")cleaned = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:])try:return json.loads(cleaned)except json.JSONDecodeError:# Try to find JSON object/array inside the textfor start_char, end_char in [('{', '}'), ('[', ']')]:start = cleaned.find(start_char)end = cleaned.rfind(end_char)if start != -1 and end > start:try:return json.loads(cleaned[start:end+1])except json.JSONDecodeError:passlogger.warning("safe_load_json: could not parse LLM output. First 200 chars: %s", cleaned[:200])return None
123456789101112import asynciofrom sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSessionfrom sqlalchemy import selectfrom app.models.user import Userfrom app.services.syllabus_service import get_mock_syllabusasync def bypass():# Connect to the local dev SQLite databaseengine = create_async_engine("sqlite+aiosqlite:///./studiq.db")session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)async with session_factory() as db:123456789101112131415161718192021222324import asyncioimport sysimport os# Load env vars from .env file firstfrom dotenv import load_dotenvload_dotenv(os.path.join(os.path.dirname(__file__), ".env"))from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSessionfrom sqlalchemy import selectfrom app.config import settingsfrom app.models.user import Userfrom app.services.syllabus_service import get_mock_syllabusdef _build_url(url: str) -> str:if url.startswith("postgresql://"):return url.replace("postgresql://", "postgresql+asyncpg://", 1)return urlasync def bypass():engine = create_async_engine(_build_url(settings.database_url))session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)async with session_factory() as db:
12345678910111213{ "type": "service_account", "project_id": "studiq-etlabs", "private_key_id": "42556d64f30b98250b2849f4a2fd38b17afa668a", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDP9fwY2z3Xwq8j\nEzlEA7XXOMXmW3xIWlJh0BSQvVr1qvUo/F2GFJt/yMeKNeQ6vJN3Su215Yheuwax\nNjdSd2OrYfiUg8F77oTEoXH28Ku1QtHdwyLEkW4sQeXxlKjNt/g0++4nPrLKIdFq\nPUNDbQJ5GprOl7UTTRCs6BIWukCrb51e5/ZpXMLLXCBzNI9pJn9V65R3AWKsSwbD\nMIJ989x7kdktuxJyxKH9hYeCH1chQBSII5bN0KuxqusOfGXO5V3PH0HcOVb+LbcM\npVN3VatM7M1xGYIhA10mJvhKDZNiE9ez/X3i8xJ/INw3T84/dDAJt8iR+Eqo2hbM\nn2wQe5p1AgMBAAECggEAKIDYIg43aAm8uyfgGClh1gJyduh8Fwpyb6cLjlo2+FCc\n8affXkEuvQ9hn79ZzX/Td+FB1ZLYQd0K02KEGV1z7doFxIU53rWoqbRpAifDRak3\nP0olgCP0EY4fJzNlQjXx03361y1svJYkF51Jd70oRWaDXrfo9lKk7AxCE6egd1MK\nbDMNHqouvnJmvzzvHxvCc7S5RA0TienRWuASsism47Pt4Yr7IqB80dCfGPu74Xxs\n0GGLKv0+i+vA4zUgWqo7wr+dkZrXS0aG0CXX4+nehqfURAykE1DiMS200K7GKCZJ\niZSlKdqlKHZpf/Kx4KGXvxD4X7wdTQwdoBrUSl4+WQKBgQD5eAS1Z/KfwWlZl6dg\n85qUb5YAyepVqU61hb6PcElbGYLb2wdBA1in9KBlfDwtwNuA+DcFaSHu5FFHZzJq\n8ZPyQX9zaGsj6YqWa8kRiBFfZtBToJ6HzSwOdy8GNMy01hTERVLd8Bk/w6GilSUo\nWYtkepM3hxQvmheDRQetLBOVTQKBgQDVZ8Xwz+4q3j5NyWRj7sMyHUTqd9HFQadM\nrazNaI2MYbTJMrIeqzYY56iM6hkdcuYAfDypIQFbiDxyUkvb5GatDTAg0WigvAsZ\n4EJjFQMTVdx6ifCy+qXS8Q4eINV+HTKzjBChO3PVRHAjhP3ASk90TqnVwV71Rh3I\nVnYg/gRlyQKBgEBt7NllNVZpP2oyLrptb/jyMM2XWHwzM+7R0ft9xpROrGtX0DHM\nSXNnTJ2pTmmKq6ZNdPhixK7MLOnCD1VrewhQPjhyOWmXAYID6HQsrj/zb86JZygv\npzc9NNnnfQ8fU1G1jcdgIUVEo1Q4LNaU+dlDhw4KRv5cT8JJa8gf4BbpAoGBAKyo\nE/acVCYsvx2yJd3QS+7czWgh3v8H+jJIhXl+8J62Yk0yDfhQLymBK9YuhHlV/44+\n9dkkUfPbSoR33tYeeY/jDqBOrKb23Mhnr254jo9zNTmTJsG3lrgOvYxUpkYtm1q2\npLG95x6SC2RBcgfEV3pTNocxtwEcZHY0tchFnAs5AoGBALiK9UNRxFENPtpOBUT+\nLdQMhlPUfFczMmVLtI5C5kVxLxm5LOTXyoV99LYeV+SS8/vzP4RgOohJap9mT3MM\n0ntrHqE2AwHsFTpDdqX/fNLTXeLfre1ygs83F5lQmqn+Vy7fTm3uOgJb1L1nmTsP\nMwxb8klWD2DmUBuip+fqYZiY\n-----END PRIVATE KEY-----\n", "client_email": "firebase-adminsdk-fbsvc@studiq-etlabs.iam.gserviceaccount.com", "client_id": "111634846771545652261", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40studiq-etlabs.iam.gserviceaccount.com", "universe_domain": "googleapis.com"}123454 unmodified lines101112131415161718import asynciofrom app.services.llm_service import call_gemini, stream_gemini, call_ollama_structuredasync def main():print("Testing call_gemini...")4 unmodified linesprint("Exception:", e)print("-" * 50)print("Testing call_ollama_structured...")try:res_json = await call_ollama_structured("Provide a json object with a key 'message' and value 'hello'")print("Response JSON:", res_json)except Exception as e:print("Exception:", e)123454 unmodified lines101112131415161718import asynciofrom app.services.llm_service import call_gemini, stream_gemini, call_llm_structuredasync def main():print("Testing call_gemini...")4 unmodified linesprint("Exception:", e)print("-" * 50)print("Testing call_llm_structured...")try:res_json = await call_llm_structured("Provide a json object with a key 'message' and value 'hello'")print("Response JSON:", res_json)except Exception as e:print("Exception:", e)
62 unmodified lines6364656667686962 unmodified linespage.insert_text((50, 50), "Syllabus for Computer Science\\nUnit 1: Introduction to AI\\nUnit 2: Machine Learning")pdf_bytes = doc.write()files = {"file": ("test_syllabus.pdf", pdf_bytes, "application/pdf")}res_upload = await client.post("/api/v1/users/me/syllabus/upload", headers=headers, files=files, timeout=30.0)assert res_upload.status_code == 200, f"Failed to upload syllabus: {res_upload.text}"62 unmodified lines6364656667686962 unmodified linespage.insert_text((50, 50), "Syllabus for Computer Science\\nUnit 1: Introduction to AI\\nUnit 2: Machine Learning")pdf_bytes = doc.write()files = {"files": ("test_syllabus.pdf", pdf_bytes, "application/pdf")}res_upload = await client.post("/api/v1/users/me/syllabus/upload", headers=headers, files=files, timeout=30.0)assert res_upload.status_code == 200, f"Failed to upload syllabus: {res_upload.text}"
.gitignoreAdded+9
app/api/v1/assignments.py+2-2
app/api/v1/chat.py+7-2
app/api/v1/dashboard.py+5-1
app/api/v1/doubts.py+1-1
app/api/v1/labfile.py+41-29
app/api/v1/payments.pyDeleted-115
app/api/v1/plan.py+6-2
app/api/v1/router.py-5
app/api/v1/store.py+10
app/api/v1/users.py+15-6
app/api/v1/viva.py+54-1
app/config.py+10-4
app/core/dependencies.py+1-1
app/main.py+5-5
app/models/attendance.py+4-2
app/models/conversation.py+2-2
app/models/flashcard.py+3-3
app/models/user.py+2-2
app/schemas/user.py+1-1
app/services/assignment_service.py+47-27
app/services/auth_service.py+3-1
app/services/chat_service.py+72-41
app/services/firebase_service.py+25-44
app/services/llm_service.py+20-31
app/services/payment_service.pyDeleted-90
app/services/plan_service.py+11-6
app/services/prompt_builder.py+37-2
app/services/rag_agent_service.py+3-3
app/utils/json_parser.py+22-9
bypass_onboarding.py+14-2
firebase-creds.jsonDeleted-13
test_llm.py+3-3
verify_e2e.py+1-1