davanstrien HF Staff commited on
Commit
a7b43cf
·
verified ·
1 Parent(s): 32990ae

Browse: trending sort (Hub trendingScore top 1000, refreshed every 15 min; papers by upvotes); animation: rests at stations + fading trails

Browse files
Files changed (2) hide show
  1. app.py +48 -3
  2. index.html +15 -8
app.py CHANGED
@@ -29,6 +29,8 @@ 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
 
@@ -244,8 +246,43 @@ class Events:
244
  return self.df
245
 
246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  STORE = Store()
248
  EVENTS = Events()
 
249
 
250
 
251
  def refresher(obj, every):
@@ -358,6 +395,7 @@ def items_payload(d, rows):
358
  new |= d.is_paper[rows]
359
  date_only = d.is_paper[rows] & (t % (86400 * NS) == 0)
360
  scores = np.round(d.raw[rows], 3) # raw: the page applies max(broad, narrow) and marks where it came from
 
361
  for i, it in enumerate(page):
362
  it["snip"] = it.pop("snippet")
363
  it["tags"] = (it["tags"] or [])[:8]
@@ -367,6 +405,8 @@ def items_payload(d, rows):
367
  it["date_only"] = bool(date_only[i])
368
  it["badge"] = "new" if new[i] else "updated"
369
  it["s"] = scores[i]
 
 
370
  return page
371
 
372
 
@@ -408,7 +448,9 @@ def status_payload():
408
  if isinstance(v, dict)}},
409
  "loaded_at": STORE.loaded_at.isoformat() if STORE.loaded_at else None, "load_seconds": STORE.load_seconds,
410
  "files": len(STORE.files), "error": STORE.error, "catalogue_version": CAT["catalogue_version"],
411
- "latest_paper_date": iso_ns(d.latest_paper_ns), "app_rss_mb": _rss_mb()}
 
 
412
  STORE.status_cache = out
413
  return out
414
 
@@ -467,7 +509,7 @@ def topics_in(idx, j):
467
  return LABELS[idx[j]]
468
 
469
 
470
- SORTS = {"score", "newest", "likes", "downloads"}
471
 
472
 
473
  def browse(topics, thresholds, days=7, sources=None, q="", sort="score", limit=30, offset=0, match="any",
@@ -504,6 +546,8 @@ def browse(topics, thresholds, days=7, sources=None, q="", sort="score", limit=3
504
  key = -d.eff[np.ix_(rows, idx)].max(axis=1)
505
  elif sort == "likes":
506
  key = -d.likes[rows]
 
 
507
  elif sort == "downloads": # papers have no downloads: rank them by upvotes
508
  key = -np.where(d.is_paper[rows], d.upvotes[rows], d.downloads[rows])
509
  else:
@@ -583,7 +627,7 @@ class Cache:
583
  self.d, self.maxsize, self.lock = {}, maxsize, threading.Lock()
584
 
585
  def get_or_make(self, key, make):
586
- key = (key, STORE.data.version, EVENTS.version)
587
  now = time.time()
588
  with self.lock:
589
  hit = self.d.get(key)
@@ -615,6 +659,7 @@ async def lifespan(_app):
615
  EVENTS.refresh()
616
  threading.Thread(target=refresher, args=(STORE, REFRESH_S), daemon=True).start()
617
  threading.Thread(target=refresher, args=(EVENTS, EVENTS_REFRESH_S), daemon=True).start()
 
618
  if RUN_WORKER:
619
  start_worker_once()
620
  yield
 
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
+ TRENDING_REFRESH_S = 15 * 60
33
+ TRENDING_TOP_N = 1000
34
  # Custom (user-defined) topics need a model. They are planned for the worker, not the Space.
35
  CUSTOM_TOPICS_ENABLED = False
36
 
 
246
  return self.df
247
 
248
 
249
+ class Trending:
250
+ """Hub trending scores, refreshed every 15 min (two listing calls). Not stored per row: it changes.
251
+ Items outside the top-N get 0; papers use their Daily Papers upvotes instead."""
252
+
253
+ def __init__(self):
254
+ self.scores = {} # (source, id) -> trendingScore
255
+ self.version = 0
256
+ self.updated_at = None
257
+ self.error = None
258
+ self._arr = (None, None) # (data version, trending version) -> array aligned with STORE.data
259
+
260
+ def refresh(self):
261
+ try:
262
+ from huggingface_hub import HfApi
263
+
264
+ api, scores = HfApi(), {}
265
+ for source, lister in (("model", api.list_models), ("dataset", api.list_datasets)):
266
+ for x in lister(sort="trending_score", limit=TRENDING_TOP_N, expand=["trendingScore"]):
267
+ scores[(source, x.id)] = float(getattr(x, "trending_score", 0) or 0)
268
+ self.scores, self.updated_at, self.error = scores, datetime.now(timezone.utc), None
269
+ self.version += 1
270
+ except Exception as e: # keep the last good map
271
+ self.error = f"{type(e).__name__}: {e}"
272
+ print("trending refresh failed:", self.error, flush=True)
273
+
274
+ def array(self, d):
275
+ """Trending key per row of `d`: Hub trendingScore, or upvotes for papers."""
276
+ key = (d.version, self.version)
277
+ if self._arr[0] != key:
278
+ hub = np.fromiter((self.scores.get(k, 0.0) for k in zip(d.src, d.meta["id"].to_list())), np.float64, d.n)
279
+ self._arr = (key, np.where(d.is_paper, d.upvotes, hub))
280
+ return self._arr[1]
281
+
282
+
283
  STORE = Store()
284
  EVENTS = Events()
285
+ TRENDING = Trending()
286
 
287
 
288
  def refresher(obj, every):
 
395
  new |= d.is_paper[rows]
396
  date_only = d.is_paper[rows] & (t % (86400 * NS) == 0)
397
  scores = np.round(d.raw[rows], 3) # raw: the page applies max(broad, narrow) and marks where it came from
398
+ trend = TRENDING.array(d)[rows]
399
  for i, it in enumerate(page):
400
  it["snip"] = it.pop("snippet")
401
  it["tags"] = (it["tags"] or [])[:8]
 
405
  it["date_only"] = bool(date_only[i])
406
  it["badge"] = "new" if new[i] else "updated"
407
  it["s"] = scores[i]
408
+ if trend[i] > 0 and not d.is_paper[rows[i]]:
409
+ it["trend"] = int(trend[i])
410
  return page
411
 
412
 
 
448
  if isinstance(v, dict)}},
449
  "loaded_at": STORE.loaded_at.isoformat() if STORE.loaded_at else None, "load_seconds": STORE.load_seconds,
450
  "files": len(STORE.files), "error": STORE.error, "catalogue_version": CAT["catalogue_version"],
451
+ "latest_paper_date": iso_ns(d.latest_paper_ns), "app_rss_mb": _rss_mb(),
452
+ "trending": {"items": len(TRENDING.scores), "updated_at": TRENDING.updated_at.isoformat() if TRENDING.updated_at
453
+ else None, "error": TRENDING.error}}
454
  STORE.status_cache = out
455
  return out
456
 
 
509
  return LABELS[idx[j]]
510
 
511
 
512
+ SORTS = {"score", "newest", "likes", "downloads", "trending"}
513
 
514
 
515
  def browse(topics, thresholds, days=7, sources=None, q="", sort="score", limit=30, offset=0, match="any",
 
546
  key = -d.eff[np.ix_(rows, idx)].max(axis=1)
547
  elif sort == "likes":
548
  key = -d.likes[rows]
549
+ elif sort == "trending": # Hub trendingScore (top 1000, refreshed every 15 min); papers: upvotes
550
+ key = -TRENDING.array(d)[rows]
551
  elif sort == "downloads": # papers have no downloads: rank them by upvotes
552
  key = -np.where(d.is_paper[rows], d.upvotes[rows], d.downloads[rows])
553
  else:
 
627
  self.d, self.maxsize, self.lock = {}, maxsize, threading.Lock()
628
 
629
  def get_or_make(self, key, make):
630
+ key = (key, STORE.data.version, EVENTS.version, TRENDING.version)
631
  now = time.time()
632
  with self.lock:
633
  hit = self.d.get(key)
 
659
  EVENTS.refresh()
660
  threading.Thread(target=refresher, args=(STORE, REFRESH_S), daemon=True).start()
661
  threading.Thread(target=refresher, args=(EVENTS, EVENTS_REFRESH_S), daemon=True).start()
662
+ threading.Thread(target=lambda: (TRENDING.refresh(), refresher(TRENDING, TRENDING_REFRESH_S)), daemon=True).start()
663
  if RUN_WORKER:
664
  start_worker_once()
665
  yield
index.html CHANGED
@@ -207,7 +207,7 @@ input[type=search]{min-width:14rem}
207
  <span class="seg" id="daysSeg" role="group" aria-label="Time range"></span>
208
  <span class="row" id="srcBoxes" style="gap:10px" role="group" aria-label="Sources"></span>
209
  <input type="search" id="q" placeholder="search title, id, snippet, tags" aria-label="Search">
210
- <label class="status">sort <select id="bsort"><option value="score">topic score</option><option value="newest">newest</option><option value="likes">likes</option><option value="downloads">downloads / upvotes</option></select></label>
211
  </div>
212
  </div>
213
  <div class="editor" id="editor" hidden>
@@ -533,7 +533,7 @@ function itemHTML(it){
533
  <button class="tn" data-cal="${esc(t)}" title="Calibrate ${esc(t)}">${esc(t)}</button>
534
  <span class="bar" aria-hidden="true"><i class="${on ? "on" : ""}" style="width:${(s*100).toFixed(1)}%"></i><b style="left:${(thr(t)*100).toFixed(1)}%"></b></span>
535
  <span class="num"${via}>${s.toFixed(2)}${via ? "*" : ""}</span></div>`; }).join("");
536
- const pop = it.source === "paper" ? (it.upvotes ? `▲ ${fmt(it.upvotes)}` : "") : [it.likes ? `♥ ${fmt(it.likes)}` : "", it.downloads ? `↓ ${fmt(it.downloads)}` : ""].filter(Boolean).join(" ");
537
  const when = it.date_only ? new Date(it.t).toLocaleDateString([], {month: "short", day: "numeric", timeZone: "UTC"})
538
  : it.badge === "new" && it.created ? `created ${ago(it.created)}` : ago(it.modified || it.t);
539
  const badge = it.source === "paper" ? "" : `<span class="badge ${esc(it.badge)}">${esc(it.badge)}</span>`;
@@ -745,10 +745,11 @@ function laneTarget(fate){
745
  }
746
  function pathFor(fate, fromX, dropX){
747
  const f = flow, jit = (Math.random() - 0.5) * 6, y0 = f.mainY + jit;
748
- if (fate === "filtered" || fate === "unchanged"){ const t = laneTarget(fate); return {pts: [[fromX, y0], [dropX, y0], [t.x, t.y]], lane: t.lane}; }
 
749
  if (fate === "queued"){ const x = f.qx + (Math.random() - 0.5) * 16; return {pts: [[fromX, y0], [x, f.mainY + 8 + Math.random() * 10]], lane: "queue"}; }
750
  const t = laneTarget(fate);
751
- return {pts: [[fromX, y0], [f.xLast, y0], [t.x, t.y]], lane: t.lane};
752
  }
753
  function at(p, now){
754
  const u = Math.min(1, Math.max(0, (now - p.start) / p.dur)), pts = p.pts;
@@ -773,6 +774,11 @@ function flowDraw(now){
773
  for (const p of f.parts){
774
  if (now < p.start) { moving = true; continue; }
775
  const q = at(p, now); if (!q.done) moving = true; else done[p.lane] = (done[p.lane] || 0) + 1;
 
 
 
 
 
776
  const fading = p.lane === "not" && q.done;
777
  ctx.globalAlpha = fading ? 0.45 : 1;
778
  ctx.fillStyle = typeof p.lane === "number" ? C.accent : p.lane === "queue" ? C.muted : q.done ? C.faint : C.ink;
@@ -789,7 +795,7 @@ function flowLoop(){
789
  if (reduceMotion()){ flowDraw(1e12); return; } // static final state
790
  flowRAF = requestAnimationFrame(tick);
791
  }
792
- const DUR = 2600;
793
  function fateOf(e){
794
  if (e.stage === "filtered") return "filtered";
795
  if (e.stage === "unchanged" || e.stage === "superseded") return "unchanged";
@@ -803,7 +809,8 @@ function flowEvent(e, startAt){
803
  if (p){
804
  if (fate === "queued" || p.final) return;
805
  const rest = p.pts[p.pts.length - 1], t = laneTarget(fate);
806
- const pts = typeof fate === "number" || fate === "unmatched" ? [rest, [f.xLast, f.mainY], [t.x, t.y]] : [rest, [t.x, t.y]];
 
807
  Object.assign(p, {pts, lane: t.lane, start: Math.max(startAt, p.start + p.dur), dur: DUR * 0.6, final: true});
808
  return;
809
  }
@@ -820,7 +827,7 @@ function flowStart(){
820
  function flowFromEvents(){
821
  const ws = () => evInfo?.worker_status?.queue?.total;
822
  flowSetup([[0.14, "card checks"], [0.33, () => `queue${ws() != null ? " · " + ws().toLocaleString() : ""}`], [0.49, `Decide · ${CAT?.labels.length || 48} topics`], [0.62, "your topics"]]);
823
- flow.kind = "events"; flow.qx = flow.stations[1][0];
824
  const recent = evts.filter(e => e.stage !== "detected").slice(-500);
825
  const t0 = Date.parse(recent[0]?.t), t1 = Date.parse(recent[recent.length - 1]?.t), REPLAY = 10000;
826
  recent.forEach((e, i) => flowEvent(e, t1 > t0 ? (Date.parse(e.t) - t0) / (t1 - t0) * REPLAY : i * 20));
@@ -843,7 +850,7 @@ function flowStats(recent){
843
  // No worker events yet: replay the latest scored items; filtered marks are estimated from the backfill rate.
844
  function flowReplay(){
845
  flowSetup([[0.16, "cheap filters"], [0.38, `Decide · ${CAT?.labels.length || 48} topics`], [0.58, "your topics"]]);
846
- flow.kind = "replay"; flow.qx = flow.stations[0][0];
847
  const arr = (lastLive?.arrivals || []).filter(a => a.t);
848
  const bs = lastLive?.status?.backfill_stats?.fetch || {};
849
  const listed = ["model", "dataset"].reduce((a, s) => a + (bs[s]?.listed || 0), 0), keptN = ["model", "dataset"].reduce((a, s) => a + (bs[s]?.kept || 0), 0);
 
207
  <span class="seg" id="daysSeg" role="group" aria-label="Time range"></span>
208
  <span class="row" id="srcBoxes" style="gap:10px" role="group" aria-label="Sources"></span>
209
  <input type="search" id="q" placeholder="search title, id, snippet, tags" aria-label="Search">
210
+ <label class="status">sort <select id="bsort"><option value="score">topic score</option><option value="newest">newest</option><option value="likes">likes</option><option value="downloads">downloads / upvotes</option><option value="trending">trending</option></select></label>
211
  </div>
212
  </div>
213
  <div class="editor" id="editor" hidden>
 
533
  <button class="tn" data-cal="${esc(t)}" title="Calibrate ${esc(t)}">${esc(t)}</button>
534
  <span class="bar" aria-hidden="true"><i class="${on ? "on" : ""}" style="width:${(s*100).toFixed(1)}%"></i><b style="left:${(thr(t)*100).toFixed(1)}%"></b></span>
535
  <span class="num"${via}>${s.toFixed(2)}${via ? "*" : ""}</span></div>`; }).join("");
536
+ const pop = it.source === "paper" ? (it.upvotes ? `▲ ${fmt(it.upvotes)}` : "") : [it.trend ? `↑ ${fmt(it.trend)} trending` : "", it.likes ? `♥ ${fmt(it.likes)}` : "", it.downloads ? `↓ ${fmt(it.downloads)}` : ""].filter(Boolean).join(" ");
537
  const when = it.date_only ? new Date(it.t).toLocaleDateString([], {month: "short", day: "numeric", timeZone: "UTC"})
538
  : it.badge === "new" && it.created ? `created ${ago(it.created)}` : ago(it.modified || it.t);
539
  const badge = it.source === "paper" ? "" : `<span class="badge ${esc(it.badge)}">${esc(it.badge)}</span>`;
 
745
  }
746
  function pathFor(fate, fromX, dropX){
747
  const f = flow, jit = (Math.random() - 0.5) * 6, y0 = f.mainY + jit;
748
+ // Repeated points = a short rest at a station, so a still frame is rarely empty.
749
+ if (fate === "filtered" || fate === "unchanged"){ const t = laneTarget(fate); return {pts: [[fromX, y0], [dropX, y0], [dropX, y0], [t.x, t.y]], lane: t.lane}; }
750
  if (fate === "queued"){ const x = f.qx + (Math.random() - 0.5) * 16; return {pts: [[fromX, y0], [x, f.mainY + 8 + Math.random() * 10]], lane: "queue"}; }
751
  const t = laneTarget(fate);
752
+ return {pts: [[fromX, y0], [f.xDecide, y0], [f.xDecide, y0], [f.xLast, y0], [t.x, t.y]], lane: t.lane};
753
  }
754
  function at(p, now){
755
  const u = Math.min(1, Math.max(0, (now - p.start) / p.dur)), pts = p.pts;
 
774
  for (const p of f.parts){
775
  if (now < p.start) { moving = true; continue; }
776
  const q = at(p, now); if (!q.done) moving = true; else done[p.lane] = (done[p.lane] || 0) + 1;
777
+ if (!q.done && !reduceMotion()){ // short fading trail behind moving items
778
+ ctx.fillStyle = C.faint;
779
+ [[90, .35], [180, .2], [270, .1]].forEach(([dt, a]) => { if (now - dt < p.start) return;
780
+ const g = at(p, now - dt); ctx.globalAlpha = a; ctx.fillRect(g.x - 1, g.y - 1.5, 2, 3); });
781
+ }
782
  const fading = p.lane === "not" && q.done;
783
  ctx.globalAlpha = fading ? 0.45 : 1;
784
  ctx.fillStyle = typeof p.lane === "number" ? C.accent : p.lane === "queue" ? C.muted : q.done ? C.faint : C.ink;
 
795
  if (reduceMotion()){ flowDraw(1e12); return; } // static final state
796
  flowRAF = requestAnimationFrame(tick);
797
  }
798
+ const DUR = 3400;
799
  function fateOf(e){
800
  if (e.stage === "filtered") return "filtered";
801
  if (e.stage === "unchanged" || e.stage === "superseded") return "unchanged";
 
809
  if (p){
810
  if (fate === "queued" || p.final) return;
811
  const rest = p.pts[p.pts.length - 1], t = laneTarget(fate);
812
+ const pts = typeof fate === "number" || fate === "unmatched"
813
+ ? [rest, [f.xDecide, f.mainY], [f.xDecide, f.mainY], [f.xLast, f.mainY], [t.x, t.y]] : [rest, [t.x, t.y]];
814
  Object.assign(p, {pts, lane: t.lane, start: Math.max(startAt, p.start + p.dur), dur: DUR * 0.6, final: true});
815
  return;
816
  }
 
827
  function flowFromEvents(){
828
  const ws = () => evInfo?.worker_status?.queue?.total;
829
  flowSetup([[0.14, "card checks"], [0.33, () => `queue${ws() != null ? " · " + ws().toLocaleString() : ""}`], [0.49, `Decide · ${CAT?.labels.length || 48} topics`], [0.62, "your topics"]]);
830
+ flow.kind = "events"; flow.qx = flow.stations[1][0]; flow.xDecide = flow.stations[2][0];
831
  const recent = evts.filter(e => e.stage !== "detected").slice(-500);
832
  const t0 = Date.parse(recent[0]?.t), t1 = Date.parse(recent[recent.length - 1]?.t), REPLAY = 10000;
833
  recent.forEach((e, i) => flowEvent(e, t1 > t0 ? (Date.parse(e.t) - t0) / (t1 - t0) * REPLAY : i * 20));
 
850
  // No worker events yet: replay the latest scored items; filtered marks are estimated from the backfill rate.
851
  function flowReplay(){
852
  flowSetup([[0.16, "cheap filters"], [0.38, `Decide · ${CAT?.labels.length || 48} topics`], [0.58, "your topics"]]);
853
+ flow.kind = "replay"; flow.qx = flow.stations[0][0]; flow.xDecide = flow.stations[1][0];
854
  const arr = (lastLive?.arrivals || []).filter(a => a.t);
855
  const bs = lastLive?.status?.backfill_stats?.fetch || {};
856
  const listed = ["model", "dataset"].reduce((a, s) => a + (bs[s]?.listed || 0), 0), keptN = ["model", "dataset"].reduce((a, s) => a + (bs[s]?.kept || 0), 0);