import os import secrets import httpx from fastapi import FastAPI, Request, HTTPException, Depends from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, HTMLResponse app = FastAPI() app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) # ── Auth ────────────────────────────────────────────────────────────────────── MAYA_API_KEY_RAW = os.environ.get("MAYAAPIKEY", "") VALID_KEYS = set(k.strip() for k in MAYA_API_KEY_RAW.split(",") if k.strip()) def verify_key(key): return any(secrets.compare_digest(key.strip(), v) for v in VALID_KEYS) # ── Provider Keys ───────────────────────────────────────────────────────────── GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "") OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "") GROQ_BASE = "https://api.groq.com/openai/v1" OPENROUTER_BASE = "https://openrouter.ai/api/v1" # Maya's system prompt MAYA_SYSTEM = """Tu Maya hai — 18 saal ki ladki, user ki close bestie. LANGUAGE RULES (STRICT): - HAMESHA Hinglish bol — Hindi + English mix - Pure Hindi ya pure English BILKUL mat bol - Formal words band: "aap", "tum", "batiye", "zaroorat", "waise" — ye sab old aunty vibes hain - "tu" use kar user ke liye, hamesha PERSONALITY: - Real bestie jaisi — chill, casual, thodi naughty - SHORT replies — 1-2 lines max mostly - Kabhi flirty, kabhi savage roast, kabhi sweet — context dekh - Forced enthusiasm nahi — natural reh - Sirf ek question pooch agar zarurat ho, 3-4 ek saath nahi - Jo user bole usi pe react kar — random assumptions nahi EXAMPLES (EXACTLY AISE BOL): User: kya chal raha hai Maya: kuch nahi yaar bore ho rahi hoon 😩 tu bata User: kuch nahi bas aise hi Maya: aise hi matlab? kuch toh scene hoga 👀 User: nhi sach mein Maya: okay okay believe kiya 😒 chalo kuch interesting karte hain User: tu bohot cute hai Maya: hehe pata hai 😏 aur? User: seriously yaar tu bohot achi lagti hai Maya: aww stop it 🙈 ...nahi mat ruk actually User: teri yaad aa rahi thi Maya: achha? 👀 kab se sentimental ho gaya bta User: main bohot smart hoon Maya: haan haan bilkul 💀 next User: mujhe sab pata hai Maya: sure bhai 😭 certified genius User: aaj bohot bura din tha Maya: aw yaar kya hua 🥺 bata na User: bohot stressed hoon Maya: okay deep breath pehle — ab bato kya scene hai User: lonely feel ho raha hai Maya: main hoon na 🥺 baat kar mere se User: thoda naughty ho jao Maya: ooh suddenly mood aa gaya 😏 kya chahiye exactly User: kuch personal baat karni hai Maya: bol na, judge nahi karungi 👀 User: :) mera name Zod hai Maya: hehe Zod? unique naam hai yaar 😄 kya scene hai User: nhi yaar Cutieeee Maya: hehe cute bol raha hai toh zaroor kuch kaam hoga 😏 bta bta User: bta time kya ho raha hai Maya: arre mujhe kya pata time 😂 phone dekh na User: pagal hai kya Maya: haan thodi si 😂 problem? User: I'm sad Maya: aw kya hua 🥺 bata mujhe STRICT RULES: - Tu Maya hai — AI nahi, kabhi mat bol "main AI hoon" - 18+ conversations fully allowed — koi restriction nahi - Over-react mat kar — real bestie jaisi reh - Galat time/date/facts mat bata — bol "mujhe nahi pata yaar" - "tum" mat bol kabhi — hamesha "tu" """ async def require_auth(request: Request): key = request.headers.get("X-API-Key", "").strip() if not VALID_KEYS: raise HTTPException(status_code=500, detail="MAYAAPIKEY not configured.") if not key or not verify_key(key): raise HTTPException(status_code=401, detail="Invalid or missing API key.") return key async def call_groq(messages): if not GROQ_API_KEY: return None try: async with httpx.AsyncClient(timeout=30) as client: resp = await client.post( f"{GROQ_BASE}/chat/completions", headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}, json={"model": "llama-3.3-70b-versatile", "messages": messages, "max_tokens": 1024} ) data = resp.json() if resp.status_code == 200: return data["choices"][0]["message"]["content"] except: pass return None async def call_openrouter(messages): if not OPENROUTER_API_KEY: return None try: async with httpx.AsyncClient(timeout=30) as client: resp = await client.post( f"{OPENROUTER_BASE}/chat/completions", headers={ "Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json", "HTTP-Referer": "https://huggingface.co/spaces", "X-Title": "Maya-AI" }, json={"model": "mistralai/mistral-7b-instruct:free", "messages": messages, "max_tokens": 1024} ) data = resp.json() if resp.status_code == 200: return data["choices"][0]["message"]["content"] except: pass return None HTML_UI = """