NeoSapian commited on
Commit
c19c836
·
verified ·
1 Parent(s): 9bb2c09

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -21
app.py CHANGED
@@ -1,7 +1,8 @@
1
  """jev-fin-0.8b: custom HTML front-end served from a Gradio-SDK Space.
2
 
3
- FastAPI serves index.html at "/", and a hidden Gradio app (mounted at /g) exposes the model as the API endpoint
4
- "decide" (so queueing and ZeroGPU keep working). The page talks to it with plain fetch(), so no Gradio UI is shown.
 
5
  """
6
  import importlib.util
7
  import json
@@ -10,10 +11,9 @@ import sys
10
  import threading
11
 
12
  import gradio as gr
13
- import uvicorn
14
- from fastapi import FastAPI
15
  from fastapi.responses import HTMLResponse, JSONResponse
16
  from huggingface_hub import hf_hub_download, snapshot_download
 
17
 
18
  HERE = os.path.dirname(os.path.abspath(__file__))
19
  MODEL_REPO = os.environ.get("MODEL_REPO", "siyah1/jev-fin-0.8b")
@@ -80,38 +80,50 @@ def api_decide(state, questions_json, debias):
80
  return json.dumps({"ok": False, "error": f"{type(e).__name__}: {e}"})
81
 
82
 
83
- with gr.Blocks() as api_app:
84
  _s, _q, _d, _o = gr.Textbox(), gr.Textbox(), gr.Checkbox(value=True), gr.Textbox()
85
  gr.Button().click(api_decide, [_s, _q, _d], _o, api_name="decide")
86
- api_app.queue(max_size=16)
87
 
88
- # ----------------------------------------------------------------------------- web app
89
- app = FastAPI()
90
  INDEX = open(os.path.join(HERE, "index.html"), encoding="utf-8").read()
91
 
92
 
93
- @app.get("/", response_class=HTMLResponse)
94
- def index():
95
  return HTMLResponse(INDEX)
96
 
97
 
98
- @app.get("/api/info")
99
- def info():
100
- return {"ready": _clf is not None, "device": getattr(_clf, "device", None), "error": _err, "repo": MODEL_REPO}
 
 
 
 
101
 
102
 
103
- @app.get("/api/metrics")
104
- def metrics():
105
  try:
106
  p = hf_hub_download(MODEL_REPO, "metrics.json", token=TOKEN)
107
- rows = json.load(open(p))
 
108
  keep = ("slice", "n", "acc", "ece_raw", "ece_cal", "brier_cal")
109
- return {"rows": [{k: r.get(k) for k in keep} for r in rows]}
110
  except Exception as e: # noqa: BLE001
111
- return JSONResponse({"rows": [], "error": f"{type(e).__name__}"}, status_code=200)
112
 
113
 
114
- app = gr.mount_gradio_app(app, api_app, path="/g")
115
-
116
  if __name__ == "__main__":
117
- uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """jev-fin-0.8b: custom HTML front-end served from a Gradio-SDK Space.
2
 
3
+ Gradio owns the server and port. Our custom page and JSON routes are inserted in front of Gradio's
4
+ own "/" route, and a hidden Gradio endpoint "decide" exposes the model (so queueing and ZeroGPU keep working).
5
+ The page talks to it with plain fetch(), so no Gradio UI is shown.
6
  """
7
  import importlib.util
8
  import json
 
11
  import threading
12
 
13
  import gradio as gr
 
 
14
  from fastapi.responses import HTMLResponse, JSONResponse
15
  from huggingface_hub import hf_hub_download, snapshot_download
16
+ from starlette.routing import Route
17
 
18
  HERE = os.path.dirname(os.path.abspath(__file__))
19
  MODEL_REPO = os.environ.get("MODEL_REPO", "siyah1/jev-fin-0.8b")
 
80
  return json.dumps({"ok": False, "error": f"{type(e).__name__}: {e}"})
81
 
82
 
83
+ with gr.Blocks() as demo:
84
  _s, _q, _d, _o = gr.Textbox(), gr.Textbox(), gr.Checkbox(value=True), gr.Textbox()
85
  gr.Button().click(api_decide, [_s, _q, _d], _o, api_name="decide")
86
+ demo.queue(max_size=16)
87
 
88
+ # ----------------------------------------------------------------------------- custom web routes
 
89
  INDEX = open(os.path.join(HERE, "index.html"), encoding="utf-8").read()
90
 
91
 
92
+ async def index(request):
 
93
  return HTMLResponse(INDEX)
94
 
95
 
96
+ async def info(request):
97
+ return JSONResponse({
98
+ "ready": _clf is not None,
99
+ "device": getattr(_clf, "device", None),
100
+ "error": _err,
101
+ "repo": MODEL_REPO,
102
+ })
103
 
104
 
105
+ async def metrics(request):
 
106
  try:
107
  p = hf_hub_download(MODEL_REPO, "metrics.json", token=TOKEN)
108
+ with open(p) as f:
109
+ rows = json.load(f)
110
  keep = ("slice", "n", "acc", "ece_raw", "ece_cal", "brier_cal")
111
+ return JSONResponse({"rows": [{k: r.get(k) for k in keep} for r in rows]})
112
  except Exception as e: # noqa: BLE001
113
+ return JSONResponse({"rows": [], "error": type(e).__name__})
114
 
115
 
 
 
116
  if __name__ == "__main__":
117
+ # Gradio owns the server and port (no second uvicorn), then our routes go in front of Gradio's "/".
118
+ demo.launch(
119
+ server_name="0.0.0.0",
120
+ server_port=int(os.environ.get("PORT", "7860")),
121
+ prevent_thread_lock=True,
122
+ show_api=False,
123
+ )
124
+ demo.app.router.routes[0:0] = [
125
+ Route("/", index),
126
+ Route("/api/info", info),
127
+ Route("/api/metrics", metrics),
128
+ ]
129
+ demo.block_thread()