Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
API performance: Polars metadata, NumPy masks, orjson, 20 s response cache, slim payloads (raw scores as a list)
Browse files- app.py +333 -236
- index.html +1 -0
- requirements.txt +2 -0
app.py
CHANGED
|
@@ -3,34 +3,41 @@
|
|
| 3 |
Scores come from the private bucket davanstrien/hub-firehose (GLiNER2.5-Decide, 48-topic catalogue cat48-v1),
|
| 4 |
mounted in the Space at FIREHOSE_DIR (default /data). The page itself runs no model; a background worker process
|
| 5 |
(firehose_worker.py, see supervise_worker) scores new Hub items on CPU and writes them to the same bucket.
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
import glob
|
| 8 |
import json
|
| 9 |
import os
|
| 10 |
import threading
|
| 11 |
import time
|
|
|
|
| 12 |
from datetime import datetime, timedelta, timezone
|
| 13 |
|
| 14 |
import numpy as np
|
|
|
|
| 15 |
import pandas as pd
|
| 16 |
-
import
|
| 17 |
-
from contextlib import asynccontextmanager
|
| 18 |
-
|
| 19 |
from fastapi import FastAPI, Query
|
| 20 |
from fastapi.middleware.gzip import GZipMiddleware
|
| 21 |
-
from fastapi.responses import HTMLResponse,
|
| 22 |
|
| 23 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 24 |
DATA = os.environ.get("FIREHOSE_DIR", "/data")
|
| 25 |
REFRESH_S = 20 # items: the worker writes a new parquet file every few minutes
|
| 26 |
EVENTS_REFRESH_S = 8
|
| 27 |
ACTIVE_WITHIN = timedelta(minutes=10) # worker counts as active if it logged an event this recently
|
|
|
|
| 28 |
# Custom (user-defined) topics need a model. They are planned for the worker, not the Space.
|
| 29 |
CUSTOM_TOPICS_ENABLED = False
|
| 30 |
|
| 31 |
-
META_COLS = ["id", "source", "url", "title", "created_at", "last_modified", "snippet", "tags", "
|
| 32 |
-
"
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
def _version(v):
|
|
@@ -39,8 +46,7 @@ def _version(v):
|
|
| 39 |
|
| 40 |
|
| 41 |
def load_catalogue():
|
| 42 |
-
"""Newest catalogue with the same labels: the bucket's copies, or the one shipped with the Space
|
| 43 |
-
(cat48-v1.1 ships here first; thresholds change, scores do not)."""
|
| 44 |
paths = glob.glob(os.path.join(DATA, "catalogue", "cat48-v*.json")) + glob.glob(os.path.join(HERE, "cat48-v*.json"))
|
| 45 |
cats = []
|
| 46 |
for p in paths:
|
|
@@ -60,27 +66,62 @@ for b, n in CAT["pairs"]:
|
|
| 60 |
NARROW.setdefault(L[b], []).append(L[n])
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
class Store:
|
| 64 |
-
"""
|
| 65 |
|
| 66 |
def __init__(self):
|
| 67 |
-
self.files = {} # path -> (mtime, size, DataFrame, raw scores)
|
| 68 |
-
|
| 69 |
-
self.
|
| 70 |
-
self.eff = self.raw
|
| 71 |
-
self.index = {}
|
| 72 |
self.status = {}
|
|
|
|
| 73 |
self.loaded_at = None
|
| 74 |
self.load_seconds = None
|
| 75 |
self.error = None
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
def _read(self, path):
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def refresh(self):
|
| 86 |
t0 = time.time()
|
|
@@ -106,34 +147,28 @@ class Store:
|
|
| 106 |
self.error = f"{type(e).__name__}: {e}"
|
| 107 |
self.loaded_at = datetime.now(timezone.utc)
|
| 108 |
self.load_seconds = round(time.time() - t0, 2)
|
|
|
|
| 109 |
|
| 110 |
def _rebuild(self):
|
| 111 |
-
parts =
|
| 112 |
if not parts:
|
| 113 |
return
|
| 114 |
-
meta =
|
| 115 |
raw = np.concatenate([p[3] for p in parts])
|
| 116 |
-
for c in META_COLS:
|
| 117 |
-
if c not in meta:
|
| 118 |
-
meta[c] = None
|
| 119 |
# One row per item: the newest score wins (the worker re-scores items when their card changes).
|
| 120 |
-
meta["
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
| 128 |
eff = raw.copy()
|
| 129 |
for b, ns in NARROW.items():
|
| 130 |
eff[:, b] = np.max(raw[:, [b, *ns]], axis=1)
|
| 131 |
-
|
| 132 |
-
+ meta["tags"].map(lambda x: " ".join(x) if x is not None else ""))
|
| 133 |
-
meta["_search"] = text.str.lower()
|
| 134 |
-
index = {(s, i): r for r, (s, i) in enumerate(zip(meta["source"], meta["id"]))}
|
| 135 |
-
with self.lock:
|
| 136 |
-
self.meta, self.raw, self.eff, self.index = meta, raw, eff, index
|
| 137 |
|
| 138 |
def _read_status(self):
|
| 139 |
out = {}
|
|
@@ -147,10 +182,6 @@ class Store:
|
|
| 147 |
out[name] = {"error": str(e)}
|
| 148 |
return out
|
| 149 |
|
| 150 |
-
def snapshot(self):
|
| 151 |
-
with self.lock:
|
| 152 |
-
return self.meta, self.raw, self.eff
|
| 153 |
-
|
| 154 |
|
| 155 |
STAGES = {"skip_same_etag": "unchanged", "skip_unchanged_etag": "unchanged", "skip_yaml_only": "unchanged",
|
| 156 |
"skip_no_readme": "filtered", "skip_thin_card": "filtered", "skip_private_or_disabled": "filtered",
|
|
@@ -166,6 +197,7 @@ class Events:
|
|
| 166 |
self.files = {}
|
| 167 |
self.df = pd.DataFrame(columns=["t", "id", "source", "event", "decide_s", "queue_len"])
|
| 168 |
self.lock = threading.Lock()
|
|
|
|
| 169 |
|
| 170 |
def _read(self, p):
|
| 171 |
df = pd.read_parquet(p) if p.endswith(".parquet") else pd.read_json(p, lines=True)
|
|
@@ -203,6 +235,7 @@ class Events:
|
|
| 203 |
df = df.dropna(subset=["t_dt"]).sort_values("t_dt").tail(20000).reset_index(drop=True)
|
| 204 |
with self.lock:
|
| 205 |
self.df = df
|
|
|
|
| 206 |
except Exception as e:
|
| 207 |
print("events refresh failed:", e)
|
| 208 |
|
|
@@ -297,7 +330,10 @@ def thr_vector(thresholds):
|
|
| 297 |
th = DEFAULT_THR.copy()
|
| 298 |
for t, v in (thresholds or {}).items():
|
| 299 |
if t in L and v is not None:
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
| 301 |
return th
|
| 302 |
|
| 303 |
|
|
@@ -305,75 +341,260 @@ def topic_idx(topics):
|
|
| 305 |
return [L[t] for t in (topics or []) if t in L]
|
| 306 |
|
| 307 |
|
| 308 |
-
def
|
| 309 |
-
return None if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
| 314 |
|
| 315 |
|
| 316 |
-
def
|
| 317 |
-
|
|
|
|
| 318 |
|
| 319 |
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
|
| 323 |
-
def
|
| 324 |
-
|
| 325 |
-
c, lm = m["created_at_dt"], m["last_modified_dt"]
|
| 326 |
-
if m["source"] == "paper" or pd.isna(c) or pd.isna(lm):
|
| 327 |
-
return "new"
|
| 328 |
-
return "new" if (lm - c) <= NEW_WITHIN or c >= window_start else "updated"
|
| 329 |
|
| 330 |
|
| 331 |
-
|
| 332 |
-
return not pd.isna(ts) and ts.hour == 0 and ts.minute == 0 and ts.second == 0 and ts.microsecond == 0
|
| 333 |
|
| 334 |
|
| 335 |
-
def
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
|
| 350 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
now = datetime.now(timezone.utc)
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
|
| 365 |
# ---------------------------------------------------------------- app
|
| 366 |
-
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
|
|
|
|
|
|
| 377 |
|
| 378 |
|
| 379 |
@asynccontextmanager
|
|
@@ -387,8 +608,7 @@ async def lifespan(_app):
|
|
| 387 |
yield
|
| 388 |
|
| 389 |
|
| 390 |
-
app = FastAPI(title="Topic Feed Lab",
|
| 391 |
-
docs_url="/api/docs", openapi_url="/api/openapi.json")
|
| 392 |
app.add_middleware(GZipMiddleware, minimum_size=1000)
|
| 393 |
|
| 394 |
|
|
@@ -409,171 +629,48 @@ def _thresholds(s):
|
|
| 409 |
return {}
|
| 410 |
|
| 411 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
@app.get("/", response_class=HTMLResponse)
|
| 413 |
async def homepage():
|
| 414 |
with open(os.path.join(HERE, "index.html"), encoding="utf-8") as f:
|
| 415 |
return f.read()
|
| 416 |
|
| 417 |
|
| 418 |
-
def catalogue() -> dict:
|
| 419 |
-
"""Topic catalogue: labels, notes, theme groups, broad/narrow pairs, default thresholds."""
|
| 420 |
-
return {k: CAT[k] for k in ("catalogue_version", "labels", "notes", "groups", "pairs", "thresholds")} | {
|
| 421 |
-
"thresholds_v1": CAT.get("thresholds_v1"), "custom_topics_enabled": CUSTOM_TOPICS_ENABLED}
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
def status() -> dict:
|
| 425 |
-
"""Data status: row counts, newest item, worker status (if any)."""
|
| 426 |
-
meta, _, _ = STORE.snapshot()
|
| 427 |
-
return status_payload(meta)
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
def live(topics: list, thresholds: dict, limit: int = 50, offset: int = 0, since: str = "",
|
| 431 |
-
all_items: bool = False) -> dict:
|
| 432 |
-
"""Newest items first (by last_modified) where any of `topics` passes its threshold (all_items: every item).
|
| 433 |
-
thresholds: {topic: value} per-user overrides; catalogue defaults otherwise. since: ISO time for 'new' counts.
|
| 434 |
-
Also returns the last 200 arrivals across all topics with their lane (for the replay)."""
|
| 435 |
-
meta, raw, eff = STORE.snapshot()
|
| 436 |
-
th, idx = thr_vector(thresholds), topic_idx(topics)
|
| 437 |
-
order = np.argsort(-meta["t_ns"].to_numpy(), kind="stable")
|
| 438 |
-
if all_items:
|
| 439 |
-
passing = np.ones(len(meta), bool)
|
| 440 |
-
else:
|
| 441 |
-
passing = (eff[:, idx] >= th[idx]).any(axis=1) if idx else np.zeros(len(meta), bool)
|
| 442 |
-
rows = order[passing[order]]
|
| 443 |
-
new_since = None
|
| 444 |
-
if since:
|
| 445 |
-
cut = pd.to_datetime(since, utc=True, errors="coerce")
|
| 446 |
-
if not pd.isna(cut):
|
| 447 |
-
new_since = int((meta["t_ns"].to_numpy()[rows] > cut.value).sum())
|
| 448 |
-
arrivals = []
|
| 449 |
-
for r in order[:200]:
|
| 450 |
-
lane = None
|
| 451 |
-
if idx:
|
| 452 |
-
margins = eff[r, idx] - th[idx]
|
| 453 |
-
j = int(np.argmax(margins))
|
| 454 |
-
lane = topics[j] if margins[j] >= 0 else None
|
| 455 |
-
arrivals.append({"t": iso(meta["t"].iloc[r]), "source": meta["source"].iloc[r], "lane": lane})
|
| 456 |
-
return {"items": item_payload(meta, raw, rows[offset:offset + limit]), "total": int(len(rows)),
|
| 457 |
-
"new_since": new_since, "arrivals": arrivals, "status": status_payload(meta)}
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
def events(topics: list, thresholds: dict, since: str = "", limit: int = 400) -> dict:
|
| 461 |
-
"""Recent worker events, newest last, with each scored item's lane among `topics` and its top topics.
|
| 462 |
-
Returns whether the worker is active (an event in the last 10 min), counts for the last 10 min and the status."""
|
| 463 |
-
ev = EVENTS.snapshot()
|
| 464 |
-
meta, raw, eff = STORE.snapshot()
|
| 465 |
-
index = STORE.index
|
| 466 |
-
th, idx = thr_vector(thresholds), topic_idx(topics)
|
| 467 |
-
now = datetime.now(timezone.utc)
|
| 468 |
-
last = ev["t_dt"].max() if len(ev) else None
|
| 469 |
-
recent = ev[ev["t_dt"] >= now - timedelta(minutes=10)] if len(ev) else ev
|
| 470 |
-
counts = {}
|
| 471 |
-
for e in recent["event"].tolist():
|
| 472 |
-
k = STAGES.get(e, e)
|
| 473 |
-
counts[k] = counts.get(k, 0) + 1
|
| 474 |
-
sel = ev
|
| 475 |
-
if since:
|
| 476 |
-
cut = pd.to_datetime(since, utc=True, errors="coerce")
|
| 477 |
-
if not pd.isna(cut):
|
| 478 |
-
sel = ev[ev["t_dt"] >= cut] # same-second events: the client de-duplicates
|
| 479 |
-
out = []
|
| 480 |
-
for e in sel.tail(int(limit)).itertuples():
|
| 481 |
-
stage = STAGES.get(e.event, e.event)
|
| 482 |
-
d = {"t": e.t, "id": e.id, "source": e.source, "stage": stage, "event": e.event,
|
| 483 |
-
"decide_s": None if pd.isna(e.decide_s) else round(float(e.decide_s), 2)}
|
| 484 |
-
r = index.get((e.source, e.id))
|
| 485 |
-
if stage == "scored" and r is not None:
|
| 486 |
-
top = np.argsort(-eff[r])[:3]
|
| 487 |
-
d["top"] = [LABELS[j] for j in top if eff[r, j] >= DEFAULT_THR[j]]
|
| 488 |
-
if idx:
|
| 489 |
-
margins = eff[r, idx] - th[idx]
|
| 490 |
-
j = int(np.argmax(margins))
|
| 491 |
-
d["lane"] = topics[j] if margins[j] >= 0 else None
|
| 492 |
-
out.append(d)
|
| 493 |
-
return {"events": out, "last_event_at": iso(last) if last is not None else None,
|
| 494 |
-
"active": bool(last is not None and last >= now - ACTIVE_WITHIN), "last_10min": counts,
|
| 495 |
-
"worker_status": STORE.status.get("worker_status"), "rows": int(len(meta)),
|
| 496 |
-
"newest": iso(meta["t"].max()) if len(meta) else None}
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
SORTS = {"score", "newest", "likes", "downloads"}
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
def browse(topics: list, thresholds: dict, days: int = 7, sources: list = None, q: str = "", sort: str = "score",
|
| 503 |
-
limit: int = 30, offset: int = 0, match: str = "any") -> dict:
|
| 504 |
-
"""Items in one or more topics. days: 1, 3, 7 or 0 (all). sources: model/dataset/paper. q: text search over
|
| 505 |
-
title, id, snippet and tags. sort: score (best selected-topic score), newest, likes, downloads (papers: upvotes).
|
| 506 |
-
match: 'any' or 'all' of the topics. Returns items, total and a summary (per-source counts, co-occurring topics)."""
|
| 507 |
-
meta, raw, eff = STORE.snapshot()
|
| 508 |
-
th, idx = thr_vector(thresholds), topic_idx(topics)
|
| 509 |
-
mask = np.ones(len(meta), bool)
|
| 510 |
-
if idx:
|
| 511 |
-
hits = eff[:, idx] >= th[idx]
|
| 512 |
-
mask &= hits.all(axis=1) if match == "all" else hits.any(axis=1)
|
| 513 |
-
if days and days > 0:
|
| 514 |
-
# Hub items: the last `days` x 24 h. Papers have date-only times and arrive in daily batches, so their window
|
| 515 |
-
# ends at the latest paper date available ("today" = the latest paper day).
|
| 516 |
-
hub_ok = (meta["t"] >= datetime.now(timezone.utc) - timedelta(days=int(days))).to_numpy()
|
| 517 |
-
is_paper = (meta["source"] == "paper").to_numpy()
|
| 518 |
-
latest_paper = meta.loc[is_paper, "t"].max()
|
| 519 |
-
paper_ok = np.zeros(len(meta), bool)
|
| 520 |
-
if not pd.isna(latest_paper):
|
| 521 |
-
day0 = latest_paper.normalize() - timedelta(days=int(days) - 1)
|
| 522 |
-
paper_ok = (meta["t"] >= day0).to_numpy()
|
| 523 |
-
mask &= np.where(is_paper, paper_ok, hub_ok)
|
| 524 |
-
if sources:
|
| 525 |
-
mask &= meta["source"].isin(sources).to_numpy()
|
| 526 |
-
if q and q.strip():
|
| 527 |
-
for word in q.lower().split():
|
| 528 |
-
mask &= meta["_search"].str.contains(word, regex=False).to_numpy()
|
| 529 |
-
rows = np.flatnonzero(mask)
|
| 530 |
-
sort = sort if sort in SORTS else "score"
|
| 531 |
-
if sort == "score" and idx:
|
| 532 |
-
key = -eff[rows][:, idx].max(axis=1)
|
| 533 |
-
elif sort in ("likes", "downloads"):
|
| 534 |
-
col = meta[sort].fillna(0).to_numpy(float)
|
| 535 |
-
if sort == "downloads": # papers have no downloads: rank them by upvotes
|
| 536 |
-
col = np.where(meta["source"].to_numpy() == "paper", meta["upvotes"].fillna(0).to_numpy(float), col)
|
| 537 |
-
key = -col[rows]
|
| 538 |
-
else:
|
| 539 |
-
key = -meta["t_ns"].to_numpy()[rows]
|
| 540 |
-
rows = rows[np.argsort(key, kind="stable")]
|
| 541 |
-
# Summary: counts per source, and which other topics the matched items are about (catalogue defaults).
|
| 542 |
-
sub = eff[rows] >= DEFAULT_THR
|
| 543 |
-
co = sub.sum(axis=0)
|
| 544 |
-
co_topics = [{"topic": LABELS[j], "n": int(co[j])} for j in np.argsort(-co) if co[j] and j not in idx][:10]
|
| 545 |
-
per_topic = {LABELS[j]: int((eff[rows, j] >= th[j]).sum()) for j in idx}
|
| 546 |
-
summary = {"total": int(len(rows)), "by_source": meta["source"].iloc[rows].value_counts().to_dict(),
|
| 547 |
-
"co_topics": co_topics, "per_topic": per_topic}
|
| 548 |
-
return {"items": item_payload(meta, raw, rows[offset:offset + limit]), "total": int(len(rows)),
|
| 549 |
-
"summary": summary, "status": status_payload(meta)}
|
| 550 |
-
|
| 551 |
-
|
| 552 |
# ---------------------------------------------------------------- JSON API
|
| 553 |
# Lists (topics, sources) are repeated query params: ?topics=robotics&topics=video. thresholds is a JSON object.
|
|
|
|
| 554 |
@app.get("/api/catalogue")
|
| 555 |
def api_catalogue():
|
| 556 |
-
return
|
| 557 |
|
| 558 |
|
| 559 |
@app.get("/api/status")
|
| 560 |
def api_status():
|
| 561 |
-
return
|
| 562 |
|
| 563 |
|
| 564 |
@app.get("/api/live")
|
| 565 |
def api_live(topics: list[str] = Query(default=[]), thresholds: str = "", limit: int = 50, offset: int = 0,
|
| 566 |
since: str = "", all_items: bool = False):
|
| 567 |
-
|
|
|
|
|
|
|
| 568 |
|
| 569 |
|
| 570 |
@app.get("/api/events")
|
| 571 |
def api_events(topics: list[str] = Query(default=[]), thresholds: str = "", since: str = "", limit: int = 400):
|
| 572 |
-
return events(topics, _thresholds(thresholds), since, limit)
|
| 573 |
|
| 574 |
|
| 575 |
@app.get("/api/browse")
|
| 576 |
def api_browse(topics: list[str] = Query(default=[]), thresholds: str = "", days: int = 7,
|
| 577 |
sources: list[str] = Query(default=[]), q: str = "", sort: str = "score", limit: int = 30,
|
| 578 |
offset: int = 0, match: str = "any"):
|
| 579 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
Scores come from the private bucket davanstrien/hub-firehose (GLiNER2.5-Decide, 48-topic catalogue cat48-v1),
|
| 4 |
mounted in the Space at FIREHOSE_DIR (default /data). The page itself runs no model; a background worker process
|
| 5 |
(firehose_worker.py, see supervise_worker) scores new Hub items on CPU and writes them to the same bucket.
|
| 6 |
+
|
| 7 |
+
Data in memory: a Polars table of item metadata, a NumPy float32 matrix of effective scores (broad topic =
|
| 8 |
+
max(broad, narrow), computed once per refresh) and NumPy arrays for the columns requests filter and sort on.
|
| 9 |
"""
|
| 10 |
import glob
|
| 11 |
import json
|
| 12 |
import os
|
| 13 |
import threading
|
| 14 |
import time
|
| 15 |
+
from contextlib import asynccontextmanager
|
| 16 |
from datetime import datetime, timedelta, timezone
|
| 17 |
|
| 18 |
import numpy as np
|
| 19 |
+
import orjson
|
| 20 |
import pandas as pd
|
| 21 |
+
import polars as pl
|
|
|
|
|
|
|
| 22 |
from fastapi import FastAPI, Query
|
| 23 |
from fastapi.middleware.gzip import GZipMiddleware
|
| 24 |
+
from fastapi.responses import HTMLResponse, Response
|
| 25 |
|
| 26 |
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 27 |
DATA = os.environ.get("FIREHOSE_DIR", "/data")
|
| 28 |
REFRESH_S = 20 # items: the worker writes a new parquet file every few minutes
|
| 29 |
EVENTS_REFRESH_S = 8
|
| 30 |
ACTIVE_WITHIN = timedelta(minutes=10) # worker counts as active if it logged an event this recently
|
| 31 |
+
CACHE_TTL_S = 20
|
| 32 |
# Custom (user-defined) topics need a model. They are planned for the worker, not the Space.
|
| 33 |
CUSTOM_TOPICS_ENABLED = False
|
| 34 |
|
| 35 |
+
META_COLS = ["id", "source", "url", "title", "created_at", "last_modified", "snippet", "tags", "likes", "downloads",
|
| 36 |
+
"upvotes", "scored_at", "scorer"]
|
| 37 |
+
PAGE_COLS = ["id", "source", "url", "title", "snippet", "tags", "likes", "downloads", "upvotes"]
|
| 38 |
+
SOURCES = ["model", "dataset", "paper"]
|
| 39 |
+
NEW_WITHIN = timedelta(days=7)
|
| 40 |
+
NS = 1_000_000_000
|
| 41 |
|
| 42 |
|
| 43 |
def _version(v):
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
def load_catalogue():
|
| 49 |
+
"""Newest catalogue with the same labels: the bucket's copies, or the one shipped with the Space."""
|
|
|
|
| 50 |
paths = glob.glob(os.path.join(DATA, "catalogue", "cat48-v*.json")) + glob.glob(os.path.join(HERE, "cat48-v*.json"))
|
| 51 |
cats = []
|
| 52 |
for p in paths:
|
|
|
|
| 66 |
NARROW.setdefault(L[b], []).append(L[n])
|
| 67 |
|
| 68 |
|
| 69 |
+
def _ns(col):
|
| 70 |
+
"""ISO-8601 string column -> Int64 ns since epoch (UTC), null when unparsable."""
|
| 71 |
+
return (pl.col(col).str.to_datetime(time_zone="UTC", strict=False, time_unit="ns").dt.epoch("ns"))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class Data:
|
| 75 |
+
"""One immutable snapshot of all items; requests read it without locks."""
|
| 76 |
+
|
| 77 |
+
def __init__(self, meta, raw, eff, version):
|
| 78 |
+
n = len(meta)
|
| 79 |
+
self.meta, self.raw, self.eff, self.version, self.n = meta, raw, eff, version, n
|
| 80 |
+
self.src = meta["source"].to_numpy()
|
| 81 |
+
self.is_paper = self.src == "paper"
|
| 82 |
+
self.t_ns = meta["t_ns"].fill_null(np.iinfo(np.int64).min).to_numpy()
|
| 83 |
+
self.created_ns = meta["created_ns"].fill_null(0).to_numpy()
|
| 84 |
+
self.modified_ns = meta["modified_ns"].fill_null(0).to_numpy()
|
| 85 |
+
self.likes = meta["likes"].fill_null(0).cast(pl.Float64).to_numpy()
|
| 86 |
+
self.downloads = meta["downloads"].fill_null(0).cast(pl.Float64).to_numpy()
|
| 87 |
+
self.upvotes = meta["upvotes"].fill_null(0).cast(pl.Float64).to_numpy()
|
| 88 |
+
self.order_t = np.argsort(-self.t_ns, kind="stable") # newest first, computed once per refresh
|
| 89 |
+
self.search = meta["_search"]
|
| 90 |
+
self.index = {(s, i): r for r, (s, i) in enumerate(zip(self.src, meta["id"].to_list()))}
|
| 91 |
+
paper_t = self.t_ns[self.is_paper]
|
| 92 |
+
self.latest_paper_ns = int(paper_t.max()) if paper_t.size else None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
class Store:
|
| 96 |
+
"""Loads items/date=*/*.parquet from the bucket mount; re-reads only new or changed files."""
|
| 97 |
|
| 98 |
def __init__(self):
|
| 99 |
+
self.files = {} # path -> (mtime, size, polars DataFrame, raw scores)
|
| 100 |
+
z = np.zeros((0, len(LABELS)), np.float32)
|
| 101 |
+
self.data = Data(self._empty(), z, z, 0)
|
|
|
|
|
|
|
| 102 |
self.status = {}
|
| 103 |
+
self.status_cache = None
|
| 104 |
self.loaded_at = None
|
| 105 |
self.load_seconds = None
|
| 106 |
self.error = None
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def _empty():
|
| 110 |
+
return pl.DataFrame({c: [] for c in META_COLS}).with_columns(
|
| 111 |
+
pl.lit(None, pl.Int64).alias("t_ns"), pl.lit(None, pl.Int64).alias("created_ns"),
|
| 112 |
+
pl.lit(None, pl.Int64).alias("modified_ns"), pl.lit("").alias("_search"))
|
| 113 |
|
| 114 |
def _read(self, path):
|
| 115 |
+
df = pl.read_parquet(path)
|
| 116 |
+
raw = np.asarray(df["scores"].list.to_array(len(LABELS)).to_numpy(), np.float32) if len(df) else \
|
| 117 |
+
np.zeros((0, len(LABELS)), np.float32)
|
| 118 |
+
for c in META_COLS:
|
| 119 |
+
if c not in df.columns:
|
| 120 |
+
df = df.with_columns(pl.lit(None).alias(c))
|
| 121 |
+
df = df.select(META_COLS).with_columns(
|
| 122 |
+
pl.col("likes").cast(pl.Int64, strict=False), pl.col("downloads").cast(pl.Int64, strict=False),
|
| 123 |
+
pl.col("upvotes").cast(pl.Int64, strict=False), pl.col("tags").cast(pl.List(pl.String), strict=False))
|
| 124 |
+
return df, raw
|
| 125 |
|
| 126 |
def refresh(self):
|
| 127 |
t0 = time.time()
|
|
|
|
| 147 |
self.error = f"{type(e).__name__}: {e}"
|
| 148 |
self.loaded_at = datetime.now(timezone.utc)
|
| 149 |
self.load_seconds = round(time.time() - t0, 2)
|
| 150 |
+
self.status_cache = None
|
| 151 |
|
| 152 |
def _rebuild(self):
|
| 153 |
+
parts = [p for p in self.files.values() if len(p[2])]
|
| 154 |
if not parts:
|
| 155 |
return
|
| 156 |
+
meta = pl.concat([p[2] for p in parts], how="vertical_relaxed").with_row_index("_row")
|
| 157 |
raw = np.concatenate([p[3] for p in parts])
|
|
|
|
|
|
|
|
|
|
| 158 |
# One row per item: the newest score wins (the worker re-scores items when their card changes).
|
| 159 |
+
meta = meta.sort("scored_at", nulls_last=False).unique(["source", "id"], keep="last", maintain_order=True)
|
| 160 |
+
raw = raw[meta["_row"].to_numpy()]
|
| 161 |
+
meta = meta.drop("_row").with_columns(_ns("created_at").alias("created_ns"),
|
| 162 |
+
_ns("last_modified").alias("modified_ns"))
|
| 163 |
+
meta = meta.with_columns(
|
| 164 |
+
pl.coalesce("modified_ns", "created_ns").alias("t_ns"),
|
| 165 |
+
pl.concat_str([pl.col("title").fill_null(""), pl.col("id").fill_null(""), pl.col("snippet").fill_null(""),
|
| 166 |
+
pl.col("tags").list.join(" ").fill_null("")], separator=" ").str.to_lowercase()
|
| 167 |
+
.alias("_search"))
|
| 168 |
eff = raw.copy()
|
| 169 |
for b, ns in NARROW.items():
|
| 170 |
eff[:, b] = np.max(raw[:, [b, *ns]], axis=1)
|
| 171 |
+
self.data = Data(meta, raw, eff, self.data.version + 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
def _read_status(self):
|
| 174 |
out = {}
|
|
|
|
| 182 |
out[name] = {"error": str(e)}
|
| 183 |
return out
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
STAGES = {"skip_same_etag": "unchanged", "skip_unchanged_etag": "unchanged", "skip_yaml_only": "unchanged",
|
| 187 |
"skip_no_readme": "filtered", "skip_thin_card": "filtered", "skip_private_or_disabled": "filtered",
|
|
|
|
| 197 |
self.files = {}
|
| 198 |
self.df = pd.DataFrame(columns=["t", "id", "source", "event", "decide_s", "queue_len"])
|
| 199 |
self.lock = threading.Lock()
|
| 200 |
+
self.version = 0
|
| 201 |
|
| 202 |
def _read(self, p):
|
| 203 |
df = pd.read_parquet(p) if p.endswith(".parquet") else pd.read_json(p, lines=True)
|
|
|
|
| 235 |
df = df.dropna(subset=["t_dt"]).sort_values("t_dt").tail(20000).reset_index(drop=True)
|
| 236 |
with self.lock:
|
| 237 |
self.df = df
|
| 238 |
+
self.version += 1
|
| 239 |
except Exception as e:
|
| 240 |
print("events refresh failed:", e)
|
| 241 |
|
|
|
|
| 330 |
th = DEFAULT_THR.copy()
|
| 331 |
for t, v in (thresholds or {}).items():
|
| 332 |
if t in L and v is not None:
|
| 333 |
+
try:
|
| 334 |
+
th[L[t]] = float(v)
|
| 335 |
+
except (TypeError, ValueError):
|
| 336 |
+
pass
|
| 337 |
return th
|
| 338 |
|
| 339 |
|
|
|
|
| 341 |
return [L[t] for t in (topics or []) if t in L]
|
| 342 |
|
| 343 |
|
| 344 |
+
def iso_ns(v):
|
| 345 |
+
return None if v is None or v <= 0 else datetime.fromtimestamp(v / NS, timezone.utc).isoformat()
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def items_payload(d, rows):
|
| 349 |
+
"""The fields the page uses, for one page of rows (vectorised; scores as a list in catalogue label order)."""
|
| 350 |
+
if len(rows) == 0:
|
| 351 |
+
return []
|
| 352 |
+
page = d.meta[rows].select(PAGE_COLS).to_dicts()
|
| 353 |
+
window_start = (datetime.now(timezone.utc) - NEW_WITHIN).timestamp() * NS
|
| 354 |
+
created, modified, t = d.created_ns[rows], d.modified_ns[rows], d.t_ns[rows]
|
| 355 |
+
has_both = (created > 0) & (modified > 0)
|
| 356 |
+
new = ~has_both | ((modified - created) <= NEW_WITHIN.total_seconds() * NS) | (created >= window_start)
|
| 357 |
+
new |= d.is_paper[rows]
|
| 358 |
+
date_only = d.is_paper[rows] & (t % (86400 * NS) == 0)
|
| 359 |
+
scores = np.round(d.raw[rows], 3) # raw: the page applies max(broad, narrow) and marks where it came from
|
| 360 |
+
for i, it in enumerate(page):
|
| 361 |
+
it["snip"] = it.pop("snippet")
|
| 362 |
+
it["tags"] = (it["tags"] or [])[:8]
|
| 363 |
+
it["t"] = iso_ns(int(t[i]))
|
| 364 |
+
it["created"] = iso_ns(int(created[i]))
|
| 365 |
+
it["modified"] = iso_ns(int(modified[i]))
|
| 366 |
+
it["date_only"] = bool(date_only[i])
|
| 367 |
+
it["badge"] = "new" if new[i] else "updated"
|
| 368 |
+
it["s"] = scores[i]
|
| 369 |
+
return page
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def slim_worker_status(ws):
|
| 373 |
+
"""Only the worker fields the page shows."""
|
| 374 |
+
if not ws or "error" in ws:
|
| 375 |
+
return ws
|
| 376 |
+
return {"updated_at": ws.get("updated_at"), "state": ws.get("state"), "queue": {"total": (ws.get("queue") or {}).get("total")},
|
| 377 |
+
"sources": {s: {"last_hour": {"scored": (v.get("last_hour") or {}).get("scored")},
|
| 378 |
+
"latency_modified_to_scored_s": v.get("latency_modified_to_scored_s")}
|
| 379 |
+
for s, v in (ws.get("sources") or {}).items()}}
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def status_payload():
|
| 383 |
+
"""Cached per data refresh (the refresher clears it)."""
|
| 384 |
+
if STORE.status_cache is not None:
|
| 385 |
+
return STORE.status_cache
|
| 386 |
+
d = STORE.data
|
| 387 |
+
now_ns = int(datetime.now(timezone.utc).timestamp() * NS)
|
| 388 |
+
valid = d.t_ns > 0
|
| 389 |
+
bf = (STORE.status.get("backfill_stats") or {}).get("fetch") or {}
|
| 390 |
+
out = {"rows": d.n, "by_source": {s: int((d.src == s).sum()) for s in SOURCES},
|
| 391 |
+
"newest": iso_ns(int(d.t_ns[valid].max())) if valid.any() else None,
|
| 392 |
+
"last_24h": int((d.t_ns >= now_ns - 86400 * NS).sum()), "last_1h": int((d.t_ns >= now_ns - 3600 * NS).sum()),
|
| 393 |
+
"worker_status": slim_worker_status(STORE.status.get("worker_status")),
|
| 394 |
+
"backfill_stats": {"fetch": {s: {"listed": v.get("listed"), "kept": v.get("kept")} for s, v in bf.items()
|
| 395 |
+
if isinstance(v, dict)}},
|
| 396 |
+
"loaded_at": STORE.loaded_at.isoformat() if STORE.loaded_at else None, "load_seconds": STORE.load_seconds,
|
| 397 |
+
"files": len(STORE.files), "error": STORE.error, "catalogue_version": CAT["catalogue_version"],
|
| 398 |
+
"latest_paper_date": iso_ns(d.latest_paper_ns)}
|
| 399 |
+
STORE.status_cache = out
|
| 400 |
+
return out
|
| 401 |
|
| 402 |
|
| 403 |
+
# ---------------------------------------------------------------- endpoints (pure functions)
|
| 404 |
+
def catalogue() -> dict:
|
| 405 |
+
"""Topic catalogue: labels, notes, theme groups, broad/narrow pairs, default thresholds."""
|
| 406 |
+
return {k: CAT[k] for k in ("catalogue_version", "labels", "notes", "groups", "pairs", "thresholds")} | {
|
| 407 |
+
"thresholds_v1": CAT.get("thresholds_v1"), "custom_topics_enabled": CUSTOM_TOPICS_ENABLED}
|
| 408 |
|
| 409 |
|
| 410 |
+
def status() -> dict:
|
| 411 |
+
"""Data status: row counts, newest item, worker status (if any)."""
|
| 412 |
+
return status_payload()
|
| 413 |
|
| 414 |
|
| 415 |
+
def live(topics, thresholds, limit=50, offset=0, since="", all_items=False, prof=None) -> dict:
|
| 416 |
+
"""Newest items first (by last_modified) where any of `topics` passes its threshold (all_items: every item).
|
| 417 |
+
Also returns the last 200 arrivals across all topics with their lane (for the replay)."""
|
| 418 |
+
tick = _Tick(prof)
|
| 419 |
+
d = STORE.data
|
| 420 |
+
th, idx = thr_vector(thresholds), topic_idx(topics)
|
| 421 |
+
if all_items:
|
| 422 |
+
passing = np.ones(d.n, bool)
|
| 423 |
+
elif idx:
|
| 424 |
+
passing = (d.eff[:, idx] >= th[idx]).any(axis=1)
|
| 425 |
+
else:
|
| 426 |
+
passing = np.zeros(d.n, bool)
|
| 427 |
+
tick("thresholds+filter")
|
| 428 |
+
rows = d.order_t[passing[d.order_t]]
|
| 429 |
+
tick("sort")
|
| 430 |
+
new_since = None
|
| 431 |
+
if since:
|
| 432 |
+
cut = pd.to_datetime(since, utc=True, errors="coerce")
|
| 433 |
+
if not pd.isna(cut):
|
| 434 |
+
new_since = int((d.t_ns[rows] > cut.value).sum())
|
| 435 |
+
top = d.order_t[:200]
|
| 436 |
+
if idx:
|
| 437 |
+
margins = d.eff[np.ix_(top, idx)] - th[idx]
|
| 438 |
+
best = margins.argmax(axis=1)
|
| 439 |
+
ok = margins[np.arange(len(top)), best] >= 0
|
| 440 |
+
lanes = [topics_in(idx, j) if k else None for j, k in zip(best, ok)]
|
| 441 |
+
else:
|
| 442 |
+
lanes = [None] * len(top)
|
| 443 |
+
arrivals = [{"t": iso_ns(int(t)), "source": s, "lane": ln} for t, s, ln in zip(d.t_ns[top], d.src[top], lanes)]
|
| 444 |
+
tick("arrivals")
|
| 445 |
+
page = items_payload(d, rows[offset:offset + limit])
|
| 446 |
+
tick("pagination+payload")
|
| 447 |
+
out = {"items": page, "total": int(len(rows)), "new_since": new_since, "arrivals": arrivals,
|
| 448 |
+
"status": status_payload()}
|
| 449 |
+
tick("status")
|
| 450 |
+
return out
|
| 451 |
|
| 452 |
|
| 453 |
+
def topics_in(idx, j):
|
| 454 |
+
return LABELS[idx[j]]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
|
| 456 |
|
| 457 |
+
SORTS = {"score", "newest", "likes", "downloads"}
|
|
|
|
| 458 |
|
| 459 |
|
| 460 |
+
def browse(topics, thresholds, days=7, sources=None, q="", sort="score", limit=30, offset=0, match="any",
|
| 461 |
+
prof=None) -> dict:
|
| 462 |
+
"""Items in one or more topics. days: 1, 3, 7 or 0 (all). sources: model/dataset/paper. q: text search over
|
| 463 |
+
title, id, snippet and tags. sort: score, newest, likes, downloads (papers: upvotes). match: 'any' or 'all'."""
|
| 464 |
+
tick = _Tick(prof)
|
| 465 |
+
d = STORE.data
|
| 466 |
+
th, idx = thr_vector(thresholds), topic_idx(topics)
|
| 467 |
+
mask = np.ones(d.n, bool)
|
| 468 |
+
if idx:
|
| 469 |
+
hits = d.eff[:, idx] >= th[idx]
|
| 470 |
+
mask &= hits.all(axis=1) if match == "all" else hits.any(axis=1)
|
| 471 |
+
tick("thresholds")
|
| 472 |
+
if days and days > 0:
|
| 473 |
+
# Hub items: the last `days` x 24 h. Papers have date-only times: their window ends at the latest paper day.
|
| 474 |
+
now_ns = int(datetime.now(timezone.utc).timestamp() * NS)
|
| 475 |
+
ok = d.t_ns >= now_ns - int(days) * 86400 * NS
|
| 476 |
+
if d.latest_paper_ns is not None:
|
| 477 |
+
day0 = d.latest_paper_ns - d.latest_paper_ns % (86400 * NS) - (int(days) - 1) * 86400 * NS
|
| 478 |
+
ok = np.where(d.is_paper, d.t_ns >= day0, ok)
|
| 479 |
+
mask &= ok
|
| 480 |
+
if sources:
|
| 481 |
+
mask &= np.isin(d.src, list(sources))
|
| 482 |
+
if q and q.strip():
|
| 483 |
+
expr = pl.lit(True)
|
| 484 |
+
for word in q.lower().split():
|
| 485 |
+
expr = expr & pl.col("_search").str.contains(word, literal=True)
|
| 486 |
+
mask &= d.meta.select(expr.alias("m"))["m"].to_numpy()
|
| 487 |
+
tick("filter")
|
| 488 |
+
rows = np.flatnonzero(mask)
|
| 489 |
+
sort = sort if sort in SORTS else "score"
|
| 490 |
+
if sort == "score" and idx:
|
| 491 |
+
key = -d.eff[np.ix_(rows, idx)].max(axis=1)
|
| 492 |
+
elif sort == "likes":
|
| 493 |
+
key = -d.likes[rows]
|
| 494 |
+
elif sort == "downloads": # papers have no downloads: rank them by upvotes
|
| 495 |
+
key = -np.where(d.is_paper[rows], d.upvotes[rows], d.downloads[rows])
|
| 496 |
+
else:
|
| 497 |
+
key = -d.t_ns[rows]
|
| 498 |
+
rows = rows[np.argsort(key, kind="stable")]
|
| 499 |
+
tick("sort")
|
| 500 |
+
# Summary: counts per source, and which other topics the matched items are about (catalogue defaults).
|
| 501 |
+
co = (d.eff[rows] >= DEFAULT_THR).sum(axis=0)
|
| 502 |
+
co_topics = [{"topic": LABELS[j], "n": int(co[j])} for j in np.argsort(-co) if co[j] and j not in idx][:10]
|
| 503 |
+
per_topic = {LABELS[j]: int((d.eff[rows, j] >= th[j]).sum()) for j in idx}
|
| 504 |
+
srcs = d.src[rows]
|
| 505 |
+
summary = {"total": int(len(rows)), "by_source": {s: int((srcs == s).sum()) for s in SOURCES if (srcs == s).any()},
|
| 506 |
+
"co_topics": co_topics, "per_topic": per_topic}
|
| 507 |
+
tick("summary")
|
| 508 |
+
page = items_payload(d, rows[offset:offset + limit])
|
| 509 |
+
tick("pagination+payload")
|
| 510 |
+
return {"items": page, "total": int(len(rows)), "summary": summary, "status": status_payload()}
|
| 511 |
|
| 512 |
|
| 513 |
+
def events(topics, thresholds, since="", limit=400) -> dict:
|
| 514 |
+
"""Recent worker events, newest last, with each scored item's lane among `topics` and its top topics."""
|
| 515 |
+
ev = EVENTS.snapshot()
|
| 516 |
+
d = STORE.data
|
| 517 |
+
th, idx = thr_vector(thresholds), topic_idx(topics)
|
| 518 |
now = datetime.now(timezone.utc)
|
| 519 |
+
last = ev["t_dt"].max() if len(ev) else None
|
| 520 |
+
recent = ev[ev["t_dt"] >= now - timedelta(minutes=10)] if len(ev) else ev
|
| 521 |
+
counts = {}
|
| 522 |
+
for e in recent["event"].tolist():
|
| 523 |
+
k = STAGES.get(e, e)
|
| 524 |
+
counts[k] = counts.get(k, 0) + 1
|
| 525 |
+
sel = ev
|
| 526 |
+
if since:
|
| 527 |
+
cut = pd.to_datetime(since, utc=True, errors="coerce")
|
| 528 |
+
if not pd.isna(cut):
|
| 529 |
+
sel = ev[ev["t_dt"] >= cut] # same-second events: the client de-duplicates
|
| 530 |
+
out = []
|
| 531 |
+
for e in sel.tail(int(limit)).itertuples():
|
| 532 |
+
stage = STAGES.get(e.event, e.event)
|
| 533 |
+
o = {"t": e.t, "id": e.id, "source": e.source, "stage": stage, "event": e.event}
|
| 534 |
+
r = d.index.get((e.source, e.id))
|
| 535 |
+
if stage == "scored" and r is not None:
|
| 536 |
+
top = np.argsort(-d.eff[r])[:3]
|
| 537 |
+
o["top"] = [LABELS[j] for j in top if d.eff[r, j] >= DEFAULT_THR[j]]
|
| 538 |
+
if idx:
|
| 539 |
+
margins = d.eff[r, idx] - th[idx]
|
| 540 |
+
j = int(np.argmax(margins))
|
| 541 |
+
o["lane"] = LABELS[idx[j]] if margins[j] >= 0 else None
|
| 542 |
+
out.append(o)
|
| 543 |
+
return {"events": out, "last_event_at": last.isoformat() if last is not None else None,
|
| 544 |
+
"active": bool(last is not None and last >= now - ACTIVE_WITHIN), "last_10min": counts,
|
| 545 |
+
"worker_status": slim_worker_status(STORE.status.get("worker_status")), "rows": d.n}
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
class _Tick:
|
| 549 |
+
"""Optional per-stage timer: fills `prof` (dict) with ms per stage."""
|
| 550 |
+
|
| 551 |
+
def __init__(self, prof):
|
| 552 |
+
self.prof, self.t = prof, time.perf_counter()
|
| 553 |
+
|
| 554 |
+
def __call__(self, stage):
|
| 555 |
+
if self.prof is not None:
|
| 556 |
+
now = time.perf_counter()
|
| 557 |
+
self.prof[stage] = round((now - self.t) * 1000, 2)
|
| 558 |
+
self.t = now
|
| 559 |
|
| 560 |
|
| 561 |
# ---------------------------------------------------------------- app
|
| 562 |
+
def dumps(obj):
|
| 563 |
+
return orjson.dumps(obj, option=orjson.OPT_SERIALIZE_NUMPY)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
class Cache:
|
| 567 |
+
"""Serialised responses for CACHE_TTL_S, keyed by route + normalised params + data versions."""
|
| 568 |
+
|
| 569 |
+
def __init__(self, maxsize=512):
|
| 570 |
+
self.d, self.maxsize, self.lock = {}, maxsize, threading.Lock()
|
| 571 |
+
|
| 572 |
+
def get_or_make(self, key, make):
|
| 573 |
+
key = (key, STORE.data.version, EVENTS.version)
|
| 574 |
+
now = time.time()
|
| 575 |
+
with self.lock:
|
| 576 |
+
hit = self.d.get(key)
|
| 577 |
+
if hit and now - hit[0] < CACHE_TTL_S:
|
| 578 |
+
return hit[1], True
|
| 579 |
+
body = dumps(make())
|
| 580 |
+
with self.lock:
|
| 581 |
+
if len(self.d) >= self.maxsize:
|
| 582 |
+
for k in sorted(self.d, key=lambda k: self.d[k][0])[: self.maxsize // 4]:
|
| 583 |
+
del self.d[k]
|
| 584 |
+
self.d[key] = (now, body)
|
| 585 |
+
return body, False
|
| 586 |
+
|
| 587 |
|
| 588 |
+
CACHE = Cache()
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def cached_json(route, params, make, max_age=0):
|
| 592 |
+
key = route + "?" + json.dumps(params, sort_keys=True, default=str)
|
| 593 |
+
body, hit = CACHE.get_or_make(key, make)
|
| 594 |
+
headers = {"X-Cache": "hit" if hit else "miss"}
|
| 595 |
+
if max_age:
|
| 596 |
+
headers["Cache-Control"] = f"public, max-age={max_age}"
|
| 597 |
+
return Response(body, media_type="application/json", headers=headers)
|
| 598 |
|
| 599 |
|
| 600 |
@asynccontextmanager
|
|
|
|
| 608 |
yield
|
| 609 |
|
| 610 |
|
| 611 |
+
app = FastAPI(title="Topic Feed Lab", lifespan=lifespan, docs_url="/api/docs", openapi_url="/api/openapi.json")
|
|
|
|
| 612 |
app.add_middleware(GZipMiddleware, minimum_size=1000)
|
| 613 |
|
| 614 |
|
|
|
|
| 629 |
return {}
|
| 630 |
|
| 631 |
|
| 632 |
+
@app.get("/favicon.ico")
|
| 633 |
+
def favicon():
|
| 634 |
+
return Response(status_code=204)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
@app.get("/", response_class=HTMLResponse)
|
| 638 |
async def homepage():
|
| 639 |
with open(os.path.join(HERE, "index.html"), encoding="utf-8") as f:
|
| 640 |
return f.read()
|
| 641 |
|
| 642 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 643 |
# ---------------------------------------------------------------- JSON API
|
| 644 |
# Lists (topics, sources) are repeated query params: ?topics=robotics&topics=video. thresholds is a JSON object.
|
| 645 |
+
# Item scores come as `s`: a list of 48 raw scores in catalogue label order (the page applies max(broad, narrow)).
|
| 646 |
@app.get("/api/catalogue")
|
| 647 |
def api_catalogue():
|
| 648 |
+
return cached_json("catalogue", {}, catalogue, max_age=3600)
|
| 649 |
|
| 650 |
|
| 651 |
@app.get("/api/status")
|
| 652 |
def api_status():
|
| 653 |
+
return cached_json("status", {}, status, max_age=15)
|
| 654 |
|
| 655 |
|
| 656 |
@app.get("/api/live")
|
| 657 |
def api_live(topics: list[str] = Query(default=[]), thresholds: str = "", limit: int = 50, offset: int = 0,
|
| 658 |
since: str = "", all_items: bool = False):
|
| 659 |
+
th = _thresholds(thresholds)
|
| 660 |
+
p = {"topics": topics, "th": th, "limit": limit, "offset": offset, "since": since, "all": all_items}
|
| 661 |
+
return cached_json("live", p, lambda: live(topics, th, limit, offset, since, all_items))
|
| 662 |
|
| 663 |
|
| 664 |
@app.get("/api/events")
|
| 665 |
def api_events(topics: list[str] = Query(default=[]), thresholds: str = "", since: str = "", limit: int = 400):
|
| 666 |
+
return Response(dumps(events(topics, _thresholds(thresholds), since, limit)), media_type="application/json")
|
| 667 |
|
| 668 |
|
| 669 |
@app.get("/api/browse")
|
| 670 |
def api_browse(topics: list[str] = Query(default=[]), thresholds: str = "", days: int = 7,
|
| 671 |
sources: list[str] = Query(default=[]), q: str = "", sort: str = "score", limit: int = 30,
|
| 672 |
offset: int = 0, match: str = "any"):
|
| 673 |
+
th = _thresholds(thresholds)
|
| 674 |
+
p = {"topics": topics, "th": th, "days": days, "sources": sorted(sources), "q": q.strip().lower(), "sort": sort,
|
| 675 |
+
"limit": limit, "offset": offset, "match": match}
|
| 676 |
+
return cached_json("browse", p, lambda: browse(topics, th, days, sources or None, q, sort, limit, offset, match))
|
index.html
CHANGED
|
@@ -453,6 +453,7 @@ async function reload(append = false, poll = false){
|
|
| 453 |
lastBrowse = d;
|
| 454 |
}
|
| 455 |
if (my !== reqId) return; // a newer request superseded this one
|
|
|
|
| 456 |
if (mode === "live" && !append && poll && seenKeys.size) freshKeys = new Set(d.items.map(key).filter(k => !seenKeys.has(k)));
|
| 457 |
else if (!append) freshKeys = new Set();
|
| 458 |
if (mode === "live" && !append) seenKeys = new Set(d.items.map(key));
|
|
|
|
| 453 |
lastBrowse = d;
|
| 454 |
}
|
| 455 |
if (my !== reqId) return; // a newer request superseded this one
|
| 456 |
+
for (const it of d.items) if (it.s){ it.scores = Object.fromEntries(CAT.labels.map((l, i) => [l, it.s[i]])); delete it.s; }
|
| 457 |
if (mode === "live" && !append && poll && seenKeys.size) freshKeys = new Set(d.items.map(key).filter(k => !seenKeys.has(k)));
|
| 458 |
else if (!append) freshKeys = new Set();
|
| 459 |
if (mode === "live" && !append) seenKeys = new Set(d.items.map(key));
|
requirements.txt
CHANGED
|
@@ -5,6 +5,8 @@ sentencepiece
|
|
| 5 |
fastapi
|
| 6 |
granian
|
| 7 |
pandas
|
|
|
|
|
|
|
| 8 |
pyarrow
|
| 9 |
numpy
|
| 10 |
requests
|
|
|
|
| 5 |
fastapi
|
| 6 |
granian
|
| 7 |
pandas
|
| 8 |
+
polars
|
| 9 |
+
orjson
|
| 10 |
pyarrow
|
| 11 |
numpy
|
| 12 |
requests
|