Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Port to FastAPI + Granian Docker Space: /api/* JSON routes, fetch() frontend, single supervised ingest worker (file lock + wait for previous worker)
Browse filesFiles changed (6)
- .dockerignoreAdded+3
- DockerfileAdded+21
- README.md+6-4
- app.py+122-17
- index.html+19-9
- requirements.txt+5-4
123__pycache__/.ruff_cache/*.pyc123456789101112131415161718192021FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=1 \ HF_HOME=/tmp/hf \ FIREHOSE_DIR=/data
RUN useradd -m -u 1000 userWORKDIR /home/user/app
# CPU-only torch for the ingest worker (GLiNER2.5-Decide); gliner2 pins transformers<5 / huggingface_hub<1.0.COPY --chown=user requirements.txt .RUN pip install --extra-index-url https://download.pytorch.org/whl/cpu -r requirements.txt
COPY --chown=user . .USER userEXPOSE 7860
# One Granian worker process: the app supervises the single ingest worker (single-writer rule for the bucket).CMD ["granian", "--interface", "asgi", "--host", "0.0.0.0", "--port", "7860", "--workers", "1", \ "--runtime-threads", "2", "app:app"]2 unmodified lines345678910111219 unmodified lines3233343536372 unmodified linesemoji: 🧭colorFrom: indigocolorTo: greensdk: gradiosdk_version: 6.16.0python_version: "3.12"app_file: app.pypinned: falseshort_description: Follow and browse new Hub items by topic---19 unmodified linesA background worker process in this Space (cpu-upgrade, CPU only, lower priority than the page) watches the Hub fornew and updated models and datasets plus HF Daily Papers, checks whether the card changed, and scores changed itemswith GLiNER2.5-Decide. The page loads the scores into memory and picks up new files every 20 s.- Default thresholds (`cat48-v1.1.json`) are set so each topic tags about as many items as an LLM reference labellingdid on a 750-item sample, with a floor of 0.1.2 unmodified lines34567891019 unmodified lines303132333435363738392 unmodified linesemoji: 🧭colorFrom: indigocolorTo: greensdk: dockerapp_port: 7860pinned: falseshort_description: Follow and browse new Hub items by topic---19 unmodified linesA background worker process in this Space (cpu-upgrade, CPU only, lower priority than the page) watches the Hub fornew and updated models and datasets plus HF Daily Papers, checks whether the card changed, and scores changed itemswith GLiNER2.5-Decide. The page loads the scores into memory and picks up new files every 20 s.- The app is FastAPI served by Granian (Docker Space, one app process). It supervises exactly one ingest worker(a file lock enforces this). JSON API: `GET /api/catalogue`, `/api/status`, `/api/live`, `/api/events`,`/api/browse` (list params repeated, e.g. `?topics=robotics&topics=video`; `thresholds` is a JSON object;docs at `/api/docs`).- Default thresholds (`cat48-v1.1.json`) are set so each topic tags about as many items as an LLM reference labellingdid on a 750-item sample, with a floor of 0.1.
12349 unmodified lines1415161718192021173 unmodified lines1951961971981992006 unmodified lines2072082092102112122132142152 unmodified lines2182192202212222232242252262272 unmodified lines2302312322332342351 unmodified line23723823924024124224324424524624724824925025125225325425567 unmodified lines3233243253263273283292 unmodified lines33233333433533633733833934034134234334434534634734834935035135224 unmodified lines37737837938038138238336 unmodified lines42042142242342442542644 unmodified lines471472473474"""Topic Feed Lab: browse and follow new Hub items by topic, from precomputed scores (gradio.Server, CPU only).Scores come from the private bucket davanstrien/hub-firehose (GLiNER2.5-Decide, 48-topic catalogue cat48-v1),mounted in the Space at FIREHOSE_DIR (default /data). The page itself runs no model; a background worker process9 unmodified linesimport numpy as npimport pandas as pdimport pyarrow.parquet as pqfrom fastapi.responses import HTMLResponsefrom gradio import ServerHERE = os.path.dirname(os.path.abspath(__file__))DATA = os.environ.get("FIREHOSE_DIR", "/data")173 unmodified linesif changed and self.files:df = pd.concat([f[2] for f in self.files.values()], ignore_index=True)df["t_dt"] = pd.to_datetime(df["t"], utc=True, errors="coerce", format="ISO8601")df = df.dropna(subset=["t_dt"]).sort_values("t_dt").tail(20000).reset_index(drop=True)with self.lock:self.df = df6 unmodified linesSTORE = Store()STORE.refresh()EVENTS = Events()EVENTS.refresh()def refresher(obj, every):2 unmodified linesobj.refresh()threading.Thread(target=refresher, args=(STORE, REFRESH_S), daemon=True).start()threading.Thread(target=refresher, args=(EVENTS, EVENTS_REFRESH_S), daemon=True).start()# ---------------------------------------------------------------- in-Space ingest worker# The worker (firehose_worker.py) runs GLiNER2.5-Decide on CPU and appends scores to the bucket mounted at DATA.# It runs as a child process at lower CPU priority so page requests stay responsive. RUN_WORKER=0 disables it.2 unmodified lines"--sweep-hours", "6", "--canary-secs", "600"]def supervise_worker():import subprocessimport sys1 unmodified linewhile not os.path.isdir(os.path.join(DATA, "state")):print("worker: waiting for the bucket mount at", DATA, flush=True)time.sleep(10)backoff = 30while True:started = time.time()proc = subprocess.Popen([sys.executable, os.path.join(HERE, "firehose_worker.py"), *WORKER_ARGS],preexec_fn=lambda: os.nice(10))rc = proc.wait()print("worker exited with", rc, flush=True)backoff = 30 if time.time() - started > 600 else min(600, backoff * 2)time.sleep(backoff)if RUN_WORKER:threading.Thread(target=supervise_worker, daemon=True).start()# ---------------------------------------------------------------- helpers67 unmodified lines# ---------------------------------------------------------------- appapp = Server()@app.get("/", response_class=HTMLResponse)2 unmodified linesreturn f.read()@app.api(name="catalogue")def catalogue() -> dict:"""Topic catalogue: labels, notes, theme groups, broad/narrow pairs, default thresholds."""return {k: CAT[k] for k in ("catalogue_version", "labels", "notes", "groups", "pairs", "thresholds")} | {"thresholds_v1": CAT.get("thresholds_v1"), "custom_topics_enabled": CUSTOM_TOPICS_ENABLED}@app.api(name="status")def status() -> dict:"""Data status: row counts, newest item, worker status (if any)."""meta, _, _ = STORE.snapshot()return status_payload(meta)@app.api(name="live")def live(topics: list, thresholds: dict, limit: int = 50, offset: int = 0, since: str = "",all_items: bool = False) -> dict:"""Newest items first (by last_modified) where any of `topics` passes its threshold (all_items: every item).24 unmodified lines"new_since": new_since, "arrivals": arrivals, "status": status_payload(meta)}@app.api(name="events")def events(topics: list, thresholds: dict, since: str = "", limit: int = 400) -> dict:"""Recent worker events, newest last, with each scored item's lane among `topics` and its top topics.Returns whether the worker is active (an event in the last 10 min), counts for the last 10 min and the status."""36 unmodified linesSORTS = {"score", "newest", "likes", "downloads"}@app.api(name="browse")def browse(topics: list, thresholds: dict, days: int = 7, sources: list = None, q: str = "", sort: str = "score",limit: int = 30, offset: int = 0, match: str = "any") -> dict:"""Items in one or more topics. days: 1, 3, 7 or 0 (all). sources: model/dataset/paper. q: text search over44 unmodified lines"summary": summary, "status": status_payload(meta)}app.launch(show_error=True)12349 unmodified lines1415161718192021222324173 unmodified lines1981992002012022032042056 unmodified lines2122132142152162172182 unmodified lines2212222232242252262 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522531 unmodified line25525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429567 unmodified lines3633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114122 unmodified lines41541641741841942042142242342442542642742842943043143224 unmodified lines45745845946046146236 unmodified lines49950050150250350444 unmodified lines549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579"""Topic Feed Lab: browse and follow new Hub items by topic, from precomputed scores (FastAPI on Granian, Docker Space).Scores come from the private bucket davanstrien/hub-firehose (GLiNER2.5-Decide, 48-topic catalogue cat48-v1),mounted in the Space at FIREHOSE_DIR (default /data). The page itself runs no model; a background worker process9 unmodified linesimport numpy as npimport pandas as pdimport pyarrow.parquet as pqfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, Queryfrom fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.responses import HTMLResponse, JSONResponseHERE = os.path.dirname(os.path.abspath(__file__))DATA = os.environ.get("FIREHOSE_DIR", "/data")173 unmodified linesif changed and self.files:df = pd.concat([f[2] for f in self.files.values()], ignore_index=True)df["t_dt"] = pd.to_datetime(df["t"], utc=True, errors="coerce", format="ISO8601")# The worker may write the same event to both logs (parquet + jsonl): keep one.df = df.drop_duplicates(["t", "source", "id", "event"])df = df.dropna(subset=["t_dt"]).sort_values("t_dt").tail(20000).reset_index(drop=True)with self.lock:self.df = df6 unmodified linesSTORE = Store()EVENTS = Events()def refresher(obj, every):2 unmodified linesobj.refresh()# ---------------------------------------------------------------- in-Space ingest worker# The worker (firehose_worker.py) runs GLiNER2.5-Decide on CPU and appends scores to the bucket mounted at DATA.# It runs as a child process at lower CPU priority so page requests stay responsive. RUN_WORKER=0 disables it.2 unmodified lines"--sweep-hours", "6", "--canary-secs", "600"]def wait_for_previous_worker(stale_s=150, max_wait_s=900):"""On a redeploy the old container keeps running until the new one is up. Its worker writesstate/worker_status.json every ~60 s; wait until that goes stale so two workers never write at once."""path = os.path.join(DATA, "state", "worker_status.json")t0 = time.time()while time.time() - t0 < max_wait_s:try:with open(path, encoding="utf-8") as f:upd = pd.to_datetime(json.load(f).get("updated_at"), utc=True)age = (datetime.now(timezone.utc) - upd).total_seconds()except Exception:returnif age > stale_s:returnprint(f"worker: previous worker active {age:.0f} s ago; waiting before starting", flush=True)time.sleep(20)print("worker: previous worker still reporting after 15 min; starting anyway", flush=True)def supervise_worker():import subprocessimport sys1 unmodified linewhile not os.path.isdir(os.path.join(DATA, "state")):print("worker: waiting for the bucket mount at", DATA, flush=True)time.sleep(10)wait_for_previous_worker()backoff = 30while True:started = time.time()proc = subprocess.Popen([sys.executable, os.path.join(HERE, "firehose_worker.py"), *WORKER_ARGS],preexec_fn=lambda: os.nice(10))print(f"worker: started pid {proc.pid}", flush=True)rc = proc.wait()print("worker exited with", rc, flush=True)backoff = 30 if time.time() - started > 600 else min(600, backoff * 2)time.sleep(backoff)_WORKER_LOCK = None # held for the life of the process that supervises the workerdef start_worker_once():"""Single-writer rule: at most one ingest worker per container. Granian runs one process (--workers 1);the file lock also guards against a second app process (e.g. a reload) starting another worker."""global _WORKER_LOCKimport fcntlf = open(os.environ.get("WORKER_LOCK", "/tmp/topic-feed-worker.lock"), "w")try:fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)except OSError:print(f"worker: another process (pid file {f.name}) supervises the worker; not starting one", flush=True)f.close()return Falsef.write(str(os.getpid()))f.flush()_WORKER_LOCK = fprint(f"worker: supervisor started in pid {os.getpid()}", flush=True)threading.Thread(target=supervise_worker, daemon=True).start()return True# ---------------------------------------------------------------- helpers67 unmodified lines# ---------------------------------------------------------------- appclass NPJSONResponse(JSONResponse):"""JSON that also accepts numpy scalars/arrays (value_counts, argmax results)."""def render(self, content):def default(o):if isinstance(o, np.generic):return o.item()if isinstance(o, np.ndarray):return o.tolist()raise TypeError(type(o).__name__)return json.dumps(content, default=default, separators=(",", ":"), allow_nan=False).encode()@asynccontextmanagerasync def lifespan(_app):STORE.refresh()EVENTS.refresh()threading.Thread(target=refresher, args=(STORE, REFRESH_S), daemon=True).start()threading.Thread(target=refresher, args=(EVENTS, EVENTS_REFRESH_S), daemon=True).start()if RUN_WORKER:start_worker_once()yieldapp = FastAPI(title="Topic Feed Lab", default_response_class=NPJSONResponse, lifespan=lifespan,docs_url="/api/docs", openapi_url="/api/openapi.json")app.add_middleware(GZipMiddleware, minimum_size=1000)@app.middleware("http")async def timing(request, call_next):t0 = time.perf_counter()resp = await call_next(request)resp.headers["Server-Timing"] = f"app;dur={(time.perf_counter() - t0) * 1000:.1f}"return respdef _thresholds(s):"""thresholds query param: a JSON object {topic: value}."""try:d = json.loads(s) if s else {}return d if isinstance(d, dict) else {}except ValueError:return {}@app.get("/", response_class=HTMLResponse)2 unmodified linesreturn f.read()def catalogue() -> dict:"""Topic catalogue: labels, notes, theme groups, broad/narrow pairs, default thresholds."""return {k: CAT[k] for k in ("catalogue_version", "labels", "notes", "groups", "pairs", "thresholds")} | {"thresholds_v1": CAT.get("thresholds_v1"), "custom_topics_enabled": CUSTOM_TOPICS_ENABLED}def status() -> dict:"""Data status: row counts, newest item, worker status (if any)."""meta, _, _ = STORE.snapshot()return status_payload(meta)def live(topics: list, thresholds: dict, limit: int = 50, offset: int = 0, since: str = "",all_items: bool = False) -> dict:"""Newest items first (by last_modified) where any of `topics` passes its threshold (all_items: every item).24 unmodified lines"new_since": new_since, "arrivals": arrivals, "status": status_payload(meta)}def events(topics: list, thresholds: dict, since: str = "", limit: int = 400) -> dict:"""Recent worker events, newest last, with each scored item's lane among `topics` and its top topics.Returns whether the worker is active (an event in the last 10 min), counts for the last 10 min and the status."""36 unmodified linesSORTS = {"score", "newest", "likes", "downloads"}def browse(topics: list, thresholds: dict, days: int = 7, sources: list = None, q: str = "", sort: str = "score",limit: int = 30, offset: int = 0, match: str = "any") -> dict:"""Items in one or more topics. days: 1, 3, 7 or 0 (all). sources: model/dataset/paper. q: text search over44 unmodified lines"summary": summary, "status": status_payload(meta)}# ---------------------------------------------------------------- JSON API# Lists (topics, sources) are repeated query params: ?topics=robotics&topics=video. thresholds is a JSON object.@app.get("/api/catalogue")def api_catalogue():return NPJSONResponse(catalogue(), headers={"Cache-Control": "public, max-age=3600"})@app.get("/api/status")def api_status():return NPJSONResponse(status(), headers={"Cache-Control": "public, max-age=15"})@app.get("/api/live")def api_live(topics: list[str] = Query(default=[]), thresholds: str = "", limit: int = 50, offset: int = 0,since: str = "", all_items: bool = False):return live(topics, _thresholds(thresholds), limit, offset, since, all_items)@app.get("/api/events")def api_events(topics: list[str] = Query(default=[]), thresholds: str = "", since: str = "", limit: int = 400):return events(topics, _thresholds(thresholds), since, limit)@app.get("/api/browse")def api_browse(topics: list[str] = Query(default=[]), thresholds: str = "", days: int = 7,sources: list[str] = Query(default=[]), q: str = "", sort: str = "score", limit: int = 30,offset: int = 0, match: str = "any"):return browse(topics, _thresholds(thresholds), days, sources or None, q, sort, limit, offset, match)
255 unmodified lines256257258259260261262161 unmodified lines424425426427428429430431432433434435436437438439440441442443444445208 unmodified lines654655656657658659660173 unmodified lines834835836837838839840255 unmodified lines</div><script type="module">import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";const MIN_POS_FOR_MARKS = 3; // positives needed before a topic's threshold comes from the user's confirmationsconst PAGE = 30, POLL_MS = 20000, EVENTS_MS = 8000;161 unmodified lines$("q").addEventListener("input", () => { clearTimeout(qTimer); qTimer = setTimeout(reload, 300); });/* ---------- data ---------- */let client = null;async function getClient(){ if (!client) client = await Client.connect(window.location.origin); return client; }let reqId = 0;async function reload(append = false, poll = false){if (!CAT || editing) return;const my = ++reqId;if (!append){ offset = 0; }try {const c = await getClient();let d;if (mode === "live"){d = (await c.predict("/live", {topics: feedTopics(), thresholds: thrMap(feedTopics()), limit: PAGE, offset, since: prevVisit || "", all_items: liveAll})).data[0];lastLive = d;} else {d = (await c.predict("/browse", {topics: browseTopics(), thresholds: thrMap(browseTopics()), days: bDays, sources: bSources,q: $("q").value, sort: bSort, limit: PAGE, offset, match: "any"})).data[0];lastBrowse = d;}if (my !== reqId) return; // a newer request superseded this one208 unmodified linesasync function pollEvents(){if (!CAT || mode !== "live" || document.hidden) return;try {const d = (await (await getClient()).predict("/events", {topics: feedTopics(), thresholds: thrMap(feedTopics()), since: lastEvT, limit: 800})).data[0];evInfo = d;const fresh = d.events.filter(e => { const k = e.t + "|" + e.source + "|" + e.id + "|" + e.event; if (evSeen.has(k)) return false; evSeen.add(k); return true; });if (fresh.length){173 unmodified linesfunction renderAll(){ renderToggles(); renderFeed(); renderCal(); }async function init(){renderControls();try { CAT = (await (await getClient()).predict("/catalogue", {})).data[0]; }catch (e) {$("status").textContent = "Could not connect: " + (e?.message || e);$("feed").innerHTML = `<div class="empty">Could not reach the app. If the Space was asleep it may still be starting; reload the page in a minute.</div>`;255 unmodified lines256257258259260261262263264265266267268269270271272273274161 unmodified lines436437438439440441442443444445446447448449450451452453454455208 unmodified lines664665666667668669670173 unmodified lines844845846847848849850255 unmodified lines</div><script type="module">// JSON API: GET /api/<name>. Arrays become repeated params (?topics=a&topics=b); objects are sent as JSON strings.async function api(name, params = {}){const q = new URLSearchParams();for (const [k, v] of Object.entries(params)){if (v === undefined || v === null) continue;if (Array.isArray(v)) v.forEach(x => q.append(k, x));else if (typeof v === "object") q.append(k, JSON.stringify(v));else q.append(k, String(v));}const r = await fetch(`api/${name}?${q}`, {headers: {Accept: "application/json"}});if (!r.ok) throw new Error(`${r.status} ${r.statusText}`);return r.json();}const MIN_POS_FOR_MARKS = 3; // positives needed before a topic's threshold comes from the user's confirmationsconst PAGE = 30, POLL_MS = 20000, EVENTS_MS = 8000;161 unmodified lines$("q").addEventListener("input", () => { clearTimeout(qTimer); qTimer = setTimeout(reload, 300); });/* ---------- data ---------- */let reqId = 0;async function reload(append = false, poll = false){if (!CAT || editing) return;const my = ++reqId;if (!append){ offset = 0; }try {let d;if (mode === "live"){d = (await api("live", {topics: feedTopics(), thresholds: thrMap(feedTopics()), limit: PAGE, offset, since: prevVisit || "", all_items: liveAll}));lastLive = d;} else {d = (await api("browse", {topics: browseTopics(), thresholds: thrMap(browseTopics()), days: bDays, sources: bSources,q: $("q").value, sort: bSort, limit: PAGE, offset, match: "any"}));lastBrowse = d;}if (my !== reqId) return; // a newer request superseded this one208 unmodified linesasync function pollEvents(){if (!CAT || mode !== "live" || document.hidden) return;try {const d = await api("events", {topics: feedTopics(), thresholds: thrMap(feedTopics()), since: lastEvT, limit: 800});evInfo = d;const fresh = d.events.filter(e => { const k = e.t + "|" + e.source + "|" + e.id + "|" + e.event; if (evSeen.has(k)) return false; evSeen.add(k); return true; });if (fresh.length){173 unmodified linesfunction renderAll(){ renderToggles(); renderFeed(); renderCal(); }async function init(){renderControls();try { CAT = await api("catalogue"); }catch (e) {$("status").textContent = "Could not connect: " + (e?.message || e);$("feed").innerHTML = `<div class="empty">Could not reach the app. If the Space was asleep it may still be starting; reload the page in a minute.</div>`;
123456789--extra-index-url https://download.pytorch.org/whl/cpupandaspyarrownumpytorchgliner2[local]==2.0.0protobufsentencepiecerequests12345678910torchgliner2[local]==2.0.0protobufsentencepiecefastapigranianpandaspyarrownumpyrequests
.dockerignoreAdded+3
DockerfileAdded+21
README.md+6-4
app.py+122-17
index.html+19-9
requirements.txt+5-4