"""m.ai API Space: the server behind https://mai-alus.web.app, on a free Hugging Face Space (Gradio SDK, ZeroGPU). Three parts in one Space: * this file, the front door Hugging Face runs on port 7860. It forwards /api/* to the Node API unchanged; * the Node API (api/main.mjs, 127.0.0.1:7861): sign-in checks, Razorpay payments, plans and usage limits; * Spark (spark_server.py, 127.0.0.1:8800): m.ai's own small chat model, research preview, on the CPU. Every decision (who is signed in, what they paid for, how many messages are left) is made in the Node API, never here and never in the browser. Nothing here uses a GPU, so no ZeroGPU quota is ever spent. """ import spaces # first: on ZeroGPU it must load before torch import os import signal import subprocess import sys import threading import time from http.server import ThreadingHTTPServer from pathlib import Path import httpx from fastapi import Request from fastapi.responses import JSONResponse, PlainTextResponse, Response, StreamingResponse from gradio import Server from nodejs_wheel.executable import ROOT_DIR as NODE_ROOT from starlette.background import BackgroundTask from starlette.datastructures import Headers, MutableHeaders import spark_server SITE = os.environ.get('SITE_ORIGIN', 'https://mai-alus.web.app') API_DIR = Path(__file__).parent / 'api' API_PORT = 7861 BODY_LIMIT = 32768 # the Node API's own limit; bigger requests stop here NODE_BIN = os.path.join(NODE_ROOT, 'bin') NODE = os.path.join(NODE_BIN, 'node') NPM_CLI = os.path.join(NODE_ROOT, 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js') # Request headers the API reads, and response headers it sets. Everything else stays behind. PASS_IN = ('authorization', 'content-type', 'origin', 'x-razorpay-signature', 'x-razorpay-event-id') PASS_OUT = ('content-type', 'cache-control', 'x-content-type-options', 'x-frame-options', 'referrer-policy', 'retry-after', 'allow') NO_STORE = {'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'} # The only public paths: this page, the API, and three read-only Gradio status routes Hugging Face may check. # Everything else Gradio serves (file uploads, the queue, file downloads, MCP, monitoring) answers 404. OPEN_PATHS = {'/', '/config', '/gradio_api/info', '/gradio_api/startup-events'} @spaces.GPU(duration=1) def _noop(): # ZeroGPU needs one decorated function to start; it is never called pass def log(event, **data): print({'event': event, **data}, flush=True) # ---------------------------------------------------------------- Spark (research preview, CPU) threading.Thread(target=spark_server.load, daemon=True).start() _spark = ThreadingHTTPServer((spark_server.HOST, spark_server.PORT), spark_server.Handler) threading.Thread(target=_spark.serve_forever, daemon=True).start() # ---------------------------------------------------------------- Node API (kept running) def run_api(): env = {**os.environ, 'PATH': NODE_BIN + os.pathsep + os.environ.get('PATH', ''), 'PORT': str(API_PORT), 'HOST': '127.0.0.1', 'TRUST_PROXY': 'yes', 'MAI_MODEL_URL': f'http://{spark_server.HOST}:{spark_server.PORT}/api/chat'} wait = 2 while not (API_DIR / 'node_modules').is_dir(): # first start: install firebase-admin from the lock file done = subprocess.run([NODE, NPM_CLI, 'ci', '--omit=dev', '--no-audit', '--no-fund'], cwd=API_DIR, env=env) if done.returncode == 0: break log('api_install_failed', code=done.returncode) time.sleep(wait) wait = min(wait * 2, 60) while True: # restart the API if it ever stops started = time.time() child = subprocess.Popen([NODE, 'main.mjs'], cwd=API_DIR, env=env) children.add(child) code = child.wait() children.discard(child) log('api_stopped', code=code) time.sleep(2 if time.time() - started > 60 else 10) def stop(*_): # on SIGTERM (Space restart or update), stop the API with this app for child in list(children): child.terminate() sys.exit(0) children = set() if threading.current_thread() is threading.main_thread(): signal.signal(signal.SIGTERM, stop) threading.Thread(target=run_api, daemon=True).start() # ---------------------------------------------------------------- front door class SiteOnly: """CORS for the website only, wrapped around everything else (Gradio's own CORS layer lets any site in on a public host, so its access-control headers are dropped here). Hugging Face's edge proxy in front of every Space adds its own permissive CORS headers anyway, so CORS is not the lock: no cookies are used, every paid action needs the user's Firebase token, and the API refuses requests from other sites with 403.""" def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): if scope['type'] == 'websocket': # nothing here speaks websockets; Gradio's would be reachable otherwise await receive() return await send({'type': 'websocket.close', 'code': 1008}) if scope['type'] != 'http': return await self.app(scope, receive, send) path = scope.get('path', '') if not (path in OPEN_PATHS or path.startswith('/api/')): # Gradio's own routes (uploads, queue, files) stay shut return await JSONResponse({'error': 'Not found'}, 404, headers=NO_STORE)(scope, receive, send) origin = Headers(scope=scope).get('origin') if scope['method'] == 'OPTIONS' and origin is not None: # preflight: answered here, never by Gradio headers = {'Vary': 'Origin', **NO_STORE} if origin == SITE: headers.update({'Access-Control-Allow-Origin': SITE, 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Authorization, Content-Type', 'Access-Control-Max-Age': '600'}) reply = Response(status_code=204, headers=headers) if origin == SITE else \ JSONResponse({'error': 'Origin not allowed'}, 403, headers=headers) return await reply(scope, receive, send) async def send_site_only(message): if message['type'] == 'http.response.start': headers = MutableHeaders(scope=message) for name in {k for k in headers.keys() if k.lower().startswith('access-control-')}: del headers[name] if origin == SITE: headers['Access-Control-Allow-Origin'] = SITE headers.add_vary_header('Origin') await send(message) await self.app(scope, receive, send_site_only) class Front(Server): def build_middleware_stack(self): return SiteOnly(super().build_middleware_stack()) server = Front(title='m.ai API', docs_url=None, redoc_url=None, openapi_url=None) upstream = httpx.AsyncClient(base_url=f'http://127.0.0.1:{API_PORT}', timeout=httpx.Timeout(70, connect=3)) def visitor_ip(request): """Hugging Face's load balancer appends the visitor's address to X-Forwarded-For; anything before it was sent by the client and could be made up, so only the last entry counts (it keys the API's per-address rate limits).""" hops = [h.strip() for h in request.headers.get('x-forwarded-for', '').split(',') if h.strip()] return hops[-1] if hops else (request.client.host if request.client else 'unknown') @server.api_route('/', methods=['GET', 'HEAD'], include_in_schema=False) def home(): return PlainTextResponse(f'm.ai API is running. The website is {SITE}\n', headers=NO_STORE) @server.api_route('/api/{path:path}', methods=['GET', 'HEAD', 'POST'], include_in_schema=False) async def api(path: str, request: Request): if int(request.headers.get('content-length') or 0) > BODY_LIMIT: return JSONResponse({'error': 'Request too large.'}, 413, headers=NO_STORE) body, size = [], 0 async for chunk in request.stream(): size += len(chunk) if size > BODY_LIMIT: return JSONResponse({'error': 'Request too large.'}, 413, headers=NO_STORE) body.append(chunk) headers = {k: v for k, v in request.headers.items() if k in PASS_IN} headers['x-forwarded-for'] = visitor_ip(request) try: reply = await upstream.send(upstream.build_request(request.method, '/api/' + path, params=request.query_params, headers=headers, content=b''.join(body)), stream=True) except httpx.TransportError: return JSONResponse({'error': 'm.ai is starting up. Please try again in a minute.'}, 503, headers={**NO_STORE, 'Retry-After': '30'}) out = {k: v for k, v in reply.headers.items() if k in PASS_OUT} if out.get('content-type', '').startswith('text/event-stream'): out['X-Accel-Buffering'] = 'no' # chat replies stream word by word return StreamingResponse(reply.aiter_raw(), status_code=reply.status_code, headers=out, background=BackgroundTask(reply.aclose)) demo = server # Hugging Face runs `demo` if __name__ == '__main__': demo.launch(ssr_mode=False)