File size: 5,463 Bytes
0baa188
057bb86
0baa188
 
 
 
 
59011a4
 
 
 
 
 
d707079
59011a4
0baa188
59011a4
0baa188
d707079
59011a4
af64b12
59011a4
d707079
59011a4
 
0baa188
 
 
 
 
 
59011a4
 
 
b508057
0baa188
 
d707079
 
59011a4
0baa188
59011a4
 
 
 
 
 
 
 
 
0baa188
59011a4
 
 
 
 
 
d707079
 
0baa188
 
59011a4
0baa188
59011a4
0baa188
 
 
d707079
59011a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0baa188
59011a4
 
 
 
 
 
 
 
 
0baa188
59011a4
 
 
 
 
 
 
 
0baa188
 
 
 
 
 
 
59011a4
 
 
 
 
0baa188
 
59011a4
 
 
 
 
 
0baa188
 
 
 
 
59011a4
 
0baa188
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""jev-fin-0.8b: custom HTML front-end served from a Gradio-SDK Space (ZeroGPU-safe).

Fixes vs. the previous version:
  1. launch(ssr_mode=False): with SSR on, a Node proxy sits on :7860 and serves Gradio's own page,
     so our custom "/" route never showed. SSR off = Python serves everything directly.
  2. The model is loaded on the MAIN thread at startup (ZeroGPU only emulates CUDA there). If that still
     fails, it is loaded lazily inside the @spaces.GPU function on the first request, where real CUDA exists.
"""
import importlib.util
import json
import os
import sys
import threading

import gradio as gr
from fastapi.responses import HTMLResponse, JSONResponse
from huggingface_hub import hf_hub_download, snapshot_download
from starlette.routing import Route

HERE = os.path.dirname(os.path.abspath(__file__))
MODEL_REPO = os.environ.get("MODEL_REPO", "NeoSapian/Rodinia")
TOKEN = os.environ.get("HF_TOKEN")  # only needed if the model repo is private

try:  # ZeroGPU when available, plain no-op otherwise
    import spaces
    # Ask ZeroGPU for as little time as needed: it refuses the call up front if the visitor's remaining quota
    # is smaller than the requested duration. Once the model is loaded a call takes only a few seconds.
    def _duration(state, questions, debias):
        return 20 if _clf is not None else 90

    gpu = spaces.GPU(duration=_duration)
except Exception:  # noqa: BLE001
    def gpu(fn):
        return fn

# ----------------------------------------------------------------------------- model
_clf, _err, _lazy, _lock = None, None, False, threading.Lock()


def get_clf():
    global _clf, _err, _lazy
    with _lock:
        if _clf is None:
            try:
                p = hf_hub_download(MODEL_REPO, "jev_common.py", token=TOKEN)
                spec = importlib.util.spec_from_file_location("jev_common", p)
                mod = importlib.util.module_from_spec(spec)
                sys.modules["jev_common"] = mod
                spec.loader.exec_module(mod)
                _clf = mod.JevClassifier(snapshot_download(MODEL_REPO, token=TOKEN))
                _err, _lazy = None, False
                print("model loaded on", _clf.device, flush=True)
            except Exception as e:  # noqa: BLE001
                _err = repr(e)
                print("model load failed:", _err, flush=True)
                raise
    return _clf


# Load on the main thread (ZeroGPU's CUDA emulation does not cover background threads).
if not os.environ.get("SKIP_LOAD"):
    try:
        get_clf()
    except Exception:  # noqa: BLE001
        # Fall back to loading inside the GPU-decorated function on the first request.
        _lazy, _err = True, None
        print("startup load failed; will load lazily on first request", flush=True)


@gpu
def _decide(state, questions, debias):
    return get_clf().decide(state, questions, debias=debias)


# ----------------------------------------------------------------------------- hidden Gradio API
def api_decide(state, questions_json, debias):
    try:
        if len(state) > 8000:
            raise ValueError("state too long (max 8000 characters)")
        qs = json.loads(questions_json)
        if not isinstance(qs, dict) or not 1 <= len(qs) <= 8:
            raise ValueError("send 1 to 8 questions")
        res = _decide(state, qs, bool(debias))
        return json.dumps({"ok": True, "result": res, "device": str(getattr(_clf, "device", "?"))})
    except Exception as e:  # noqa: BLE001
        return json.dumps({"ok": False, "error": f"{type(e).__name__}: {e}"})


with gr.Blocks() as demo:
    _s, _q, _d, _o = gr.Textbox(), gr.Textbox(), gr.Checkbox(value=True), gr.Textbox()
    gr.Button().click(api_decide, [_s, _q, _d], _o, api_name="decide")
demo.queue(max_size=16)

# ----------------------------------------------------------------------------- custom web routes
INDEX = open(os.path.join(HERE, "index.html"), encoding="utf-8").read()


async def index(request):
    return HTMLResponse(INDEX)


async def info(request):
    if _clf is not None:
        return JSONResponse({"ready": True, "device": str(getattr(_clf, "device", None)),
                             "error": None, "repo": MODEL_REPO})
    if _lazy:  # loads on the first Analyze click, inside the ZeroGPU function
        return JSONResponse({"ready": True, "device": "ZeroGPU (loads on first run)",
                             "error": None, "repo": MODEL_REPO})
    return JSONResponse({"ready": False, "device": None, "error": _err, "repo": MODEL_REPO})


async def metrics(request):
    try:
        p = hf_hub_download(MODEL_REPO, "metrics.json", token=TOKEN)
        with open(p) as f:
            rows = json.load(f)
        keep = ("slice", "n", "acc", "ece_raw", "ece_cal", "brier_cal")
        return JSONResponse({"rows": [{k: r.get(k) for k in keep} for r in rows]})
    except Exception as e:  # noqa: BLE001
        return JSONResponse({"rows": [], "error": type(e).__name__})


CUSTOM_ROUTES = [
    Route("/", index, methods=["GET"]),
    Route("/api/info", info, methods=["GET"]),
    Route("/api/metrics", metrics, methods=["GET"]),
]

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=int(os.environ.get("PORT", "7860")),
        ssr_mode=False,                      # no Node proxy, so our "/" route is what gets served
        app_kwargs={"routes": CUSTOM_ROUTES},  # registered before Gradio's own "/"
    )