ajit3259 commited on
Commit
edc3880
·
1 Parent(s): 2087311

feat(server): serve React UI and interpret API from gr.Server

Browse files

Single FastAPI process: assets under /assets, index.html at /, plus the
interpret and health endpoints. Avoids mounting at "/" so Gradio's own
startup routes keep working.

Files changed (1) hide show
  1. app.py +108 -0
app.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chalchitra — a film for this moment.
2
+
3
+ Entry point for the Hugging Face Space. Uses Gradio's `gr.Server` (a FastAPI
4
+ app) so the React frontend and the /api/interpret endpoint run from a single
5
+ process — one server, our own interface in front of it.
6
+
7
+ The frontend POSTs images + a fragment; the oracle returns the frozen contract:
8
+ {"interpretation": str, "films": [{"title", "year", "rationale"}]}
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from functools import lru_cache
15
+ from pathlib import Path
16
+
17
+ from dotenv import load_dotenv
18
+ from fastapi.middleware.cors import CORSMiddleware
19
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
20
+ from fastapi.staticfiles import StaticFiles
21
+ from pydantic import BaseModel, Field
22
+
23
+ import gradio as gr
24
+
25
+ from backend import OracleError, interpret
26
+ from backend.providers import get_provider
27
+
28
+ load_dotenv()
29
+
30
+ HERE = Path(__file__).parent
31
+ DIST = HERE / "frontend" / "dist"
32
+
33
+ app = gr.Server(title="Chalchitra", docs_url="/api/docs")
34
+
35
+ # Same-origin in production; permissive here so the Vite dev server (5173) and
36
+ # quick local tools can call the API without friction.
37
+ app.add_middleware(
38
+ CORSMiddleware,
39
+ allow_origins=["*"],
40
+ allow_methods=["*"],
41
+ allow_headers=["*"],
42
+ )
43
+
44
+
45
+ @lru_cache(maxsize=1)
46
+ def _provider():
47
+ """Build the configured provider once and reuse it (matters for hf_local)."""
48
+ return get_provider()
49
+
50
+
51
+ class Moment(BaseModel):
52
+ images: list[str] = Field(default_factory=list) # data URLs or raw base64 JPEG
53
+ fragment: str = ""
54
+
55
+
56
+ @app.post("/api/interpret")
57
+ async def api_interpret(moment: Moment):
58
+ if not moment.images:
59
+ return JSONResponse({"error": "Bring at least one image."}, status_code=400)
60
+ try:
61
+ result = interpret(moment.images, moment.fragment, provider=_provider())
62
+ return result
63
+ except OracleError as exc:
64
+ # The reel slipped — a model/parse problem the user can retry past.
65
+ return JSONResponse({"error": str(exc)}, status_code=422)
66
+ except Exception as exc: # noqa: BLE001 — surface a clean message, log the rest
67
+ return JSONResponse(
68
+ {"error": f"Something slipped through the reel. ({exc})"},
69
+ status_code=500,
70
+ )
71
+
72
+
73
+ @app.get("/api/health")
74
+ async def health():
75
+ p = _provider()
76
+ return {"ok": True, "provider": p.name, "model": getattr(p, "model", None)}
77
+
78
+
79
+ _PLACEHOLDER = """<!doctype html><html><head><meta charset="utf-8">
80
+ <title>Chalchitra</title><style>body{background:#0C0907;color:#EDE6D9;
81
+ font-family:Georgia,serif;display:grid;place-items:center;height:100vh;margin:0}
82
+ em{color:#C9923E}</style></head><body><div style="text-align:center">
83
+ <h1 style="font-weight:300;font-style:italic">Chalchitra</h1>
84
+ <p><em>a film for this moment</em></p>
85
+ <p style="opacity:.6">Frontend not built yet — run <code>npm run build</code> in
86
+ <code>frontend/</code>. The API is live at <code>/api/interpret</code>.</p>
87
+ </div></body></html>"""
88
+
89
+ # Serve the built SPA: assets under /assets, index.html at /. We deliberately do
90
+ # NOT mount StaticFiles at "/" — that would shadow Gradio's own /gradio_api/*
91
+ # routes and break launch()'s startup self-check.
92
+ if DIST.exists():
93
+ app.mount("/assets", StaticFiles(directory=str(DIST / "assets")), name="assets")
94
+
95
+ @app.get("/", response_class=HTMLResponse)
96
+ async def index():
97
+ return FileResponse(str(DIST / "index.html"))
98
+ else:
99
+ @app.get("/", response_class=HTMLResponse)
100
+ async def placeholder():
101
+ return _PLACEHOLDER
102
+
103
+
104
+ if __name__ == "__main__":
105
+ app.launch(
106
+ server_name="0.0.0.0",
107
+ server_port=int(os.environ.get("PORT", 7860)),
108
+ )