Spaces:
Sleeping
Sleeping
Widen leaderboard and limit version selection to the owner
Browse filesFiles changed (4)
- app.py+59-18
- index.html+115-108
- test_version_access.pyAdded+72
- test_version_ui.mjsAdded+69
50 unmodified lines515253545556115 unmodified lines17217317417517617717817918018118218324 unmodified lines2082092102112122132142152162179 unmodified lines2272282292302312322332342352362 unmodified lines23924024124224324424524624724824921 unmodified lines271272273274275276246 unmodified lines52352452552652752852911 unmodified lines54154254354454554654754854955055155254 unmodified lines6076086096106116126136146156166179 unmodified lines62762862963063163263350 unmodified lines# hiding a row in the UI would still leave it readable on the Hub.RESULTS_PRIVATE_REPO = os.environ.get("RESULTS_PRIVATE_REPO", "Mushari440/results-private")VISIBILITIES = {"public", "private"}# Injected by HF when `hf_oauth: true` is set in the README frontmatter.OAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")115 unmodified linesdef healthz():return {"ok": True, "oauth": bool(_oauth)}@app.get("/api/me")def me(request: Request):user = request.session.get("user")# `is_owner` only decides whether the UI OFFERS the closed-source option.# /api/submit re-checks server-side, so faking this client-side gains nothing.return {"user": user, "is_owner": bool(user) and user == LEADERBOARD_OWNER}@app.get("/login", include_in_schema=False)async def login(request: Request):24 unmodified linesinfo = await _oauth.hf.userinfo(token=token)except Exception:info = {}username = info.get("preferred_username") or info.get("name") or info.get("sub")if not username:return HTMLResponse("<p>Could not read your Hugging Face username.</p>", status_code=400)request.session["user"] = str(username)safe_user = html.escape(str(username)) # display-name fallback can contain markup# Small page so the flow also works when opened in a new tab from an iframe.return HTMLResponse(9 unmodified lines@app.get("/logout", include_in_schema=False)def logout(request: Request):request.session.pop("user", None)return RedirectResponse("/", status_code=302)def _require_owner(request: Request, check_origin: bool = True) -> str:"""Every management route funnels through here. The identity comes from thesigned session, so a crafted request cannot impersonate the owner.2 unmodified linesBrowsers omit the Origin header on same-origin GETs, so enforcing it on a readendpoint rejects our own page. Reads are still session-gated, and a cross-originread cannot see the response anyway (no CORS headers are served)."""user = request.session.get("user")if not user:raise HTTPException(401, "Please sign in with Hugging Face.")if user != LEADERBOARD_OWNER:raise HTTPException(403, "Only the leaderboard maintainer can manage models.")if check_origin and not _origin_ok(request):raise HTTPException(403, "Request blocked (bad origin).")if not HF_TOKEN:21 unmodified linesreturn vdef _results_path(model: str, version: str | None = None) -> str:org, _, name = model.partition("/")return f"{_clean_version(version)}/{org}/results_{name or org}.json"246 unmodified linesout.append(d)except Exception as e:print(f"[private-results] {f}: {type(e).__name__}: {e}")return {"results": out}@app.get("/api/private-metrics")11 unmodified linestry:r = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=20)if r.status_code == 404:return {"models": {}}r.raise_for_status()return r.json()except Exception as e:print(f"[private-metrics] {v}: {type(e).__name__}: {e}")return {"models": {}}class SubmitBody(BaseModel):54 unmodified linesvisibility = (body.visibility or "public").strip().lower()if visibility not in VISIBILITIES:raise HTTPException(400, "Visibility must be 'public' or 'private'.")if visibility == "private" and user != LEADERBOARD_OWNER:raise HTTPException(403, "Private evaluations are restricted to the leaderboard maintainer.")if (max_examples is not None or subtasks) and user != LEADERBOARD_OWNER:raise HTTPException(403,"Limiting the item count or the subtask list is restricted to the "9 unmodified linesraise HTTPException(400, f"Invalid subtask id(s): {bad[:5]}")subtasks = sorted(set(subtasks))if source == "closed" and user != LEADERBOARD_OWNER:raise HTTPException(403,"Closed-source (API) models can only be submitted by the leaderboard "50 unmodified lines51525354555657115 unmodified lines17317417517617717817918018118218318418518618718818919019124 unmodified lines2162172182192202212222232242252262272282299 unmodified lines2392402412422432442452462472482492502512522532542552562 unmodified lines25926026126226326426521 unmodified lines287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317246 unmodified lines56456556656756856957011 unmodified lines58258358458558658758858959059159259354 unmodified lines6486496506516526536546556566576589 unmodified lines66866967067167267367450 unmodified lines# hiding a row in the UI would still leave it readable on the Hub.RESULTS_PRIVATE_REPO = os.environ.get("RESULTS_PRIVATE_REPO", "Mushari440/results-private")VISIBILITIES = {"public", "private"}PRIVATE_RESPONSE = {"Cache-Control": "private, no-store"}# Injected by HF when `hf_oauth: true` is set in the README frontmatter.OAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")115 unmodified linesdef healthz():return {"ok": True, "oauth": bool(_oauth)}def _is_owner(request: Request) -> bool:# Display names and legacy sessions are insufficient for privileged access.# Only the verified OAuth account handle is accepted.return request.session.get("hf_handle") == LEADERBOARD_OWNER@app.get("/api/me")def me(request: Request):owner = _is_owner(request)data = {"user": request.session.get("user"), "is_owner": owner}if owner:data["benchmark_versions"] = VERSIONSreturn JSONResponse(data, headers=PRIVATE_RESPONSE)@app.get("/login", include_in_schema=False)async def login(request: Request):24 unmodified linesinfo = await _oauth.hf.userinfo(token=token)except Exception:info = {}handle = info.get("preferred_username")username = handle or info.get("name") or info.get("sub")if not username:return HTMLResponse("<p>Could not read your Hugging Face username.</p>", status_code=400)request.session["user"] = str(username)request.session.pop("hf_handle", None)if isinstance(handle, str) and handle:request.session["hf_handle"] = handlesafe_user = html.escape(str(username)) # display-name fallback can contain markup# Small page so the flow also works when opened in a new tab from an iframe.return HTMLResponse(9 unmodified lines@app.get("/logout", include_in_schema=False)def logout(request: Request):request.session.clear()return RedirectResponse("/", status_code=302)def _require_owner_identity(request: Request) -> str:if not request.session.get("user"):raise HTTPException(401, "Please sign in with Hugging Face.")if not _is_owner(request):raise HTTPException(403, "Only the leaderboard owner can access this.")return LEADERBOARD_OWNERdef _require_owner(request: Request, check_origin: bool = True) -> str:"""Every management route funnels through here. The identity comes from thesigned session, so a crafted request cannot impersonate the owner.2 unmodified linesBrowsers omit the Origin header on same-origin GETs, so enforcing it on a readendpoint rejects our own page. Reads are still session-gated, and a cross-originread cannot see the response anyway (no CORS headers are served)."""user = _require_owner_identity(request)if check_origin and not _origin_ok(request):raise HTTPException(403, "Request blocked (bad origin).")if not HF_TOKEN:21 unmodified linesreturn v@app.get("/api/benchmark-result-files")def benchmark_result_files(request: Request, version: str):"""List result files for an owner-selected benchmark version."""_require_owner_identity(request)v = _clean_version(version)try:paths = api_public.list_repo_files(RESULTS_REPO, repo_type="dataset", token=False)except HfHubHTTPError as exc:raise HTTPException(502, "The benchmark result listing is unavailable.") from excprefix = f"{v}/"files = [{"type": "file", "path": path}for path in pathsif path.endswith(".json") and (path.startswith(prefix)or (v == LEGACY_VERSIONand path.count("/") == 1and path.split("/")[0] not in VERSIONS))]return JSONResponse(files, headers=PRIVATE_RESPONSE)def _results_path(model: str, version: str | None = None) -> str:org, _, name = model.partition("/")return f"{_clean_version(version)}/{org}/results_{name or org}.json"246 unmodified linesout.append(d)except Exception as e:print(f"[private-results] {f}: {type(e).__name__}: {e}")return JSONResponse({"results": out}, headers=PRIVATE_RESPONSE)@app.get("/api/private-metrics")11 unmodified linestry:r = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=20)if r.status_code == 404:return JSONResponse({"models": {}}, headers=PRIVATE_RESPONSE)r.raise_for_status()return JSONResponse(r.json(), headers=PRIVATE_RESPONSE)except Exception as e:print(f"[private-metrics] {v}: {type(e).__name__}: {e}")return JSONResponse({"models": {}}, headers=PRIVATE_RESPONSE)class SubmitBody(BaseModel):54 unmodified linesvisibility = (body.visibility or "public").strip().lower()if visibility not in VISIBILITIES:raise HTTPException(400, "Visibility must be 'public' or 'private'.")if visibility == "private" and not _is_owner(request):raise HTTPException(403, "Private evaluations are restricted to the leaderboard maintainer.")if (max_examples is not None or subtasks) and not _is_owner(request):raise HTTPException(403,"Limiting the item count or the subtask list is restricted to the "9 unmodified linesraise HTTPException(400, f"Invalid subtask id(s): {bad[:5]}")subtasks = sorted(set(subtasks))if source == "closed" and not _is_owner(request):raise HTTPException(403,"Closed-source (API) models can only be submitted by the leaderboard "
40 unmodified lines414243444546474849505152533 unmodified lines57585960616263646566676869706 unmodified lines777879808182838485868788899018 unmodified lines10911011111211311411519 unmodified lines135136137138139140141142143144145146147148149150162 unmodified lines3133143153163173183193203213223233243253263273283293303313323338 unmodified lines342343344345346347348324 unmodified lines67367467567667767867968068168268368468568668768868969028 unmodified lines71972072172272372472528 unmodified lines7547557567577587597607617627634 unmodified lines76876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779838 unmodified lines837838839840841842843844845138 unmodified lines98498598698798898999082 unmodified lines107310741075107610771078107992 unmodified lines117211731174117511761177117811799 unmodified lines11891190119111921193119411951196119712 unmodified lines12101211121212131214121512161217123 unmodified lines134113421343134413451346117 unmodified lines146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152140 unmodified linesfont-family:"IBM Plex Sans",ui-sans-serif,system-ui,sans-serif;font-size:15px; line-height:1.5; -webkit-font-smoothing:antialiased;}.wrap{max-width:1360px; margin:0 auto; padding:22px 22px 80px}a{color:var(--accent); text-decoration:none}a:hover{text-decoration:underline; text-decoration-style:dotted}/* ---------------- Masthead ---------------- */.masthead{position:relative; overflow:hidden; border-radius:22px; padding:36px 42px 32px;color:#f3efe4; margin-bottom:20px;background:radial-gradient(130% 150% at 12% 8%, #0c6355 0%, #074237 46%, #04231e 100%);border:1px solid rgba(201,154,63,.32);3 unmodified linesbackground-image:radial-gradient(circle at 88% 16%, rgba(231,200,119,.55) 0, transparent 42%),repeating-linear-gradient(135deg, rgba(255,255,255,.05) 0 2px, transparent 2px 16px);-webkit-mask-image:linear-gradient(90deg,transparent 42%,#000 100%); mask-image:linear-gradient(90deg,transparent 42%,#000 100%);}.masthead::after{content:"";position:absolute;left:42px;right:42px;bottom:0;height:2px;background:linear-gradient(90deg,transparent,#c99a3f 22%,#efd08a 50%,#c99a3f 78%,transparent);opacity:.75}.mh-top{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}.eyebrow{font:600 11.5px/1 "IBM Plex Sans";letter-spacing:.3em;text-transform:uppercase;color:#ecd08a}.titles{display:flex;align-items:baseline;gap:20px;flex-wrap:wrap;margin:13px 0 8px}.title-en{margin:0;font:600 clamp(30px,4.6vw,48px)/1 "Fraunces",Georgia,serif;color:#fdfbf4;letter-spacing:-.012em}.title-ar{font:700 clamp(23px,3.4vw,37px)/1.2 "Amiri",serif;color:#ecd08a;direction:rtl}.tagline{max-width:66ch;margin:2px 0 0;font:400 15px/1.6 "IBM Plex Sans";color:#cfe6dd}.stats{margin-top:17px;display:flex;gap:11px;flex-wrap:wrap;align-items:center;font:500 12.5px/1 "IBM Plex Sans";color:#b6d4ca}.stats b{color:#fff;font-weight:700}.stats .dot{color:#c99a3f;font-size:8px;opacity:.85}.theme-btn{flex:none;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);color:#f3efe4;6 unmodified lines/* ---------------- Controls ---------------- */.controls{display:flex;flex-wrap:wrap;gap:14px;align-items:center;margin-bottom:16px}/* Version picker sits OUTSIDE #controls on purpose: #controls is hidden whenever aversion has no rows, and a picker inside it would strand you on an empty board. */.verbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}.verbar label{font:600 12px "IBM Plex Sans";letter-spacing:.02em;color:var(--ink-soft)}.verbar select{padding:8px 12px;border-radius:10px;border:1px solid var(--border);background:var(--bg2);color:var(--ink);font:500 13.5px "IBM Plex Sans"}.verbar select:focus{outline:2px solid var(--accent);outline-offset:0;border-color:transparent}.verbar .vnote{font-size:12px;color:var(--ink-mute)}.search{flex:1 1 260px;position:relative}.search input{width:100%;padding:11px 14px 11px 38px;border-radius:12px;border:1px solid var(--border);background:var(--surface);color:var(--ink);font:500 14px "IBM Plex Sans"}18 unmodified lines.board-scroll::-webkit-scrollbar-thumb{background:var(--ink-mute);border-radius:8px;border:3px solid var(--scroll-track)}.board-scroll::-webkit-scrollbar-thumb:hover{background:var(--accent)}table.board{border-collapse:separate;border-spacing:0;width:100%;font-variant-numeric:tabular-nums}table.board th,table.board td{padding:12px 12px;white-space:nowrap;text-align:right}table.board th:nth-child(-n+2),table.board td:nth-child(-n+2){text-align:left}table.board thead th{position:sticky;top:0;z-index:4;background:var(--head-solid);border-bottom:2px solid var(--head-bd);19 unmodified lines.rank.r1{background:linear-gradient(135deg,#f4d980,#c99a3f)}.rank.r2{background:linear-gradient(135deg,#e6e6ea,#b8bcc6)}.rank.r3{background:linear-gradient(135deg,#e3b489,#c0824e)}.model-cell{display:flex;flex-direction:column;gap:2px;max-width:260px}.model-cell .name{font-weight:600;color:var(--ink);overflow:hidden;text-overflow:ellipsis}.model-cell .effort{font-weight:600;opacity:.95}.org{font-size:11.5px;color:var(--ink-mute)}.type-ico{font-size:13px;margin-right:2px}.avg-cell{min-width:118px}.avg-num{font:700 15px "IBM Plex Mono";color:var(--accent-strong)}.avg-bar{height:5px;border-radius:3px;background:var(--surface2);margin-top:5px;overflow:hidden}.avg-bar>i{display:block;height:100%;border-radius:3px;background:linear-gradient(90deg,var(--emerald-600),var(--emerald-400))}.score{font-family:"IBM Plex Mono";font-weight:500;border-radius:7px;padding:5px 8px;display:inline-block;min-width:48px;text-align:right}/* best score in each task column (across all shown models) */.score.na{color:var(--muted);opacity:.55;font-weight:400}.score.best{font-weight:800;color:var(--ink);box-shadow:inset 0 0 0 2px var(--gold),0 4px 12px -6px rgba(201,154,63,.5)}162 unmodified lines<h1 class="title-en">Arabic LLM Leaderboard</h1><span class="title-ar">لوحة صدارة نماذج اللغة العربية</span></div><p class="tagline">A hard, discriminating benchmark for Modern Standard Arabic — models graded by strong LLM judges across generation, reasoning, knowledge, safety, and multi-turn dialogue.</p><div class="stats"><span><b id="itemCount">34,137</b> items</span><i class="dot">◆</i><span><b id="subtaskCount">70</b> subtasks</span><i class="dot">◆</i><span><b id="catCount">13</b> categories</span><i class="dot">◆</i><span><b>5</b> formats</span><i class="dot">◆</i><span><b id="modelCount">—</b> models</span><i class="dot">◆</i><span>LLM-as-Judge</span></div></header><div class="verbar"><label for="verSel">Benchmark version</label><select id="verSel"></select><span class="vnote" id="verNote"></span></div><div class="controls" id="controls" hidden>8 unmodified lines</div><div class="board-card"><div class="board-scroll"><div class="state" id="state"><div class="spinner"></div>Loading the leaderboard…</div><table class="board" id="board" hidden><thead id="thead"></thead><tbody id="tbody"></tbody></table></div>324 unmodified lines{id:"v8", label:"v8 — corpus 32,890", dims:DIMS_V8, ks:KS_V8, subtasks:70},{id:"v9", label:"v9 — corpus 32,890", dims:DIMS_V9, ks:KS_V9, subtasks:70},{id:"v10", label:"v10 — corpus 35,390", dims:DIMS_V10, ks:KS_V10, subtasks:75},{id:"v11", label:"v11 — test split 31,846", dims:DIMS_V11, ks:KS_V11, subtasks:75,note:"train/dev were filled first with items google/gemma-4-31B-it answers and at least 5 of the 8 Mushari440 models miss"},{id:"v12", label:"v12 — gemma judge, test split 31,846", dims:DIMS_V12_DISPLAY, ks:KS_V12, subtasks:75,note:"judged by gemma-4-31b-it, not GLM-5.1 like v11, so scores run about 7 points higher and are not comparable with v11; same split as v11: train/dev filled first with items google/gemma-4-31B-it answers and at least 5 of the 8 Mushari440 models miss"}];const DEFAULT_VERSION="v11";// An id no longer listed (a retired board saved in the browser or linked) opens the default board.function versionCfg(id){return VERSIONS.find(v=>v.id===id)||VERSIONS.find(v=>v.id===DEFAULT_VERSION)||VERSIONS[0];}function verNoteText(){return CURRENT.note||(CURRENT.legacy?"the published board":"a separate board — results appear as models finish");}let CURRENT=versionCfg(DEFAULT_VERSION);let DIMS=CURRENT.dims;let KS=CURRENT.ks;let WSUM=DIMS.reduce((s,d)=>s+d[2],0);28 unmodified linesasync function getJSON(u){const r=await fetch(u);if(!r.ok)throw new Error(r.status);return r.json();}async function loadDir(repo,version){const tree=await getJSON(TREE(repo));let files=tree.filter(f=>f.type==="file"&&f.path.endsWith(".json"));if(version){const pre=version.id+"/";28 unmodified linesreturn w?s/w:0;}async function init(){const requestedVersion=CURRENT.id;document.getElementById("openComparison").disabled=true;const compareDialog=document.getElementById("comparisonDialog");if(compareDialog.open)compareDialog.close();DIMS=CURRENT.dims; KS_PARTS=CURRENT.ks; WSUM=DIMS.reduce((s,d)=>s+d[2],0);// The corpus size belongs to the version: v7 is 34,137 items and v8 is 32,890.const ic=document.getElementById("itemCount");4 unmodified linesif(sc&&CURRENT.subtasks)sc.textContent=String(CURRENT.subtasks);for(const id of ["catCount","dimCount"]){const e=document.getElementById(id);if(e)e.textContent=String(DIMS.length);}const st=document.getElementById("state");st.hidden=false; st.innerHTML='<div class="spinner"></div>Loading '+CURRENT.id+'…';document.getElementById("board").hidden=true;document.getElementById("controls").hidden=true;document.getElementById("note").hidden=true;let results,requests=[];try{results=await loadDir(RESULTS,CURRENT);}catch(e){st.textContent="⚠️ Could not load leaderboard data ("+e+").";return;}// The queue/metadata is non-essential — if it fails, still render the board from results.try{requests=await loadDir(REQUESTS);}catch(e){requests=[];}// Private scores are NOT in the public dataset; the server hands them over only// to the owner. Merged here so the maintainer sees their own hidden rows.try{const pr=await fetch('/api/private-results?version='+encodeURIComponent(CURRENT.id),{credentials:'same-origin'});if(pr.ok){const pd=await pr.json();if(Array.isArray(pd.results)&&pd.results.length)results=results.concat(pd.results);}}catch(e){/* not the owner, or not signed in — public board only */}// Owner-only extra columns (policy A / policy B / judged timestamp). Served from// the PRIVATE dataset, so a non-owner gets 401 here and the columns never appear.state.extra={};try{const em=await fetch('/api/private-metrics?version='+encodeURIComponent(CURRENT.id),{credentials:'same-origin'});if(em.ok){const ed=await em.json(); state.extra=(ed&&ed.models)||{};}}catch(e){/* not the owner — no extra columns */}if(CURRENT.id!==requestedVersion)return; // discard results from an obsolete version request// the progress card cross-checks against these to see if a run is really livestate.requests=requests;if(typeof loadProgress==='function')loadProgress();38 unmodified linesif(!models.length){st.hidden=false;st.innerHTML='<div style="text-align:center;padding:26px 12px">'+'<div style="font-size:15px;font-weight:600;margin-bottom:6px">No models evaluated on '+CURRENT.id+' yet.</div>'+'<div class="muted" style="font-size:13px">Results land here as each model finishes. '+'Use the version picker above to see an earlier board.</div></div>';document.getElementById("board").hidden=true;document.getElementById("tbody").innerHTML=""; // drop the previous version's rowsdocument.getElementById("modelCount").textContent="0";138 unmodified linesconst result=compareModels(a,b,comparisonMode,CURRENT.id,DIMS);const overallDelta=a&&b?comparisonDelta(a.avg,b.avg):0;document.getElementById('comparisonSummary').textContent=a&&b&&result.rows.length?'Overall: A '+a.avg.toFixed(2)+'% · B '+b.avg.toFixed(2)+'% · B − A '+(overallDelta>0?'+':'')+(Object.is(overallDelta,-0)?0:overallDelta).toFixed(2)+' pp':'Overall comparison unavailable for this selection.';document.getElementById('comparisonVersion').textContent=CURRENT.label;const warning=document.getElementById('comparisonWarning');warning.textContent=result.notice;warning.hidden=!result.notice;document.getElementById('comparisonBody').innerHTML=comparisonTableHTML(result,document.getElementById('comparisonOrder').value);const comparable=result.rows.filter(r=>r.delta!==null);82 unmodified linesconst active=(state.sort===key)||(key==="rank"&&state.sort==="avg");const arrow=active?`<span class="arrow">${state.dir<0?"▼":"▲"}</span>`:"";const cls=(key!=="rank"&&key!=="model"&&key!=="avg")?' class="sub"':"";return `<th data-k="${key}"${cls}>${label}${arrow}</th>`;}).join("")+"</tr>";thead.querySelectorAll("th").forEach(th=>th.onclick=()=>{const key=th.dataset.k;if(state.sort===key||(key==="rank"&&state.sort==="avg")){state.dir*=-1;}92 unmodified linesfor(const id of ['visField','maxField','subtaskField']){const el=document.getElementById(id); if(el)el.hidden=!isOwner;}// Signing in after page load must reveal the panel without a hard reload.if(isOwner&&typeof loadManage==='function')loadManage();if(!isOwner){const vs=document.getElementById('f-vis'); if(vs)vs.value='public';const mx=document.getElementById('f-max'); if(mx)mx.value='';9 unmodified linessigninView.hidden=false; submitForm.hidden=true;}}async function refreshMe(){try{const r=await fetch('/api/me',{credentials:'same-origin'});const d=await r.json();setUser(d.user||null,!!d.is_owner);}catch(e){setUser(null,false);}}function smsg(t,kind){submitMsg.className='msg'+(t?(' show '+kind):'');submitMsg.textContent=t||'';}function openModal(){modal.classList.add('open');modal.setAttribute('aria-hidden','false');smsg('');refreshMe();}12 unmodified lineselse{window.location.href='/login';}};// pick up a sign-in that completed in another tab / after returningwindow.addEventListener('focus',()=>{if(modal.classList.contains('open'))refreshMe();});document.addEventListener('visibilitychange',()=>{if(!document.hidden&&modal.classList.contains('open'))refreshMe();});submitForm.addEventListener('submit',async e=>{e.preventDefault();123 unmodified lines// delete buttons named another. Only the newest call may paint.let _manageSeq=0;async function loadManage(){const seq=++_manageSeq;const panel=document.getElementById('managePanel');const list=document.getElementById('manageList');117 unmodified linesif(boardScroll)boardScroll.addEventListener('scroll',()=>boardScroll.classList.toggle('scrolled',boardScroll.scrollLeft>2),{passive:true});// Windows mouse-wheel support: a plain vertical scroll wheel (no horizontal wheel on most PC// mice) is translated into horizontal table scrolling. Trackpads send a horizontal component// (deltaX) or small pixel deltas and are left to native handling, so Mac / precision-touchpad// behaviour is unchanged. At the table's left/right edge we release to normal page scrolling.if(boardScroll)boardScroll.addEventListener('wheel',e=>{const el=boardScroll, max=el.scrollWidth-el.clientWidth;if(max<=0) return; // nothing to scroll sidewaysif(e.deltaX!==0) return; // already horizontal (trackpad / shift+wheel)const isMouseWheel = e.deltaMode===1 || Math.abs(e.deltaY)>=50;if(!isMouseWheel) return; // small pixel deltas = trackpad vertical → pageconst dy = e.deltaMode===1 ? e.deltaY*40 : e.deltaY; // scale line-mode (Firefox) to pixelsif((dy<0 && el.scrollLeft<=0) || (dy>0 && el.scrollLeft>=max)) return; // at edge → let page scrollel.scrollLeft = Math.max(0, Math.min(max, el.scrollLeft+dy));e.preventDefault();},{passive:false});refreshMe();if(new URLSearchParams(location.search).get('signedin')) openModal();function initVersionPicker(){const sel=document.getElementById("verSel");for(const v of VERSIONS){const o=document.createElement("option");o.value=v.id;o.textContent=v.label;sel.appendChild(o);}// URL wins over the remembered choice, so a shared #v=v8 link opens on v8.const fromHash=(location.hash.match(/(?:^|[#&])v=([^&]+)/)||[])[1];let want=fromHash;if(!want){try{want=localStorage.getItem("benchVersion");}catch(e){}}CURRENT=versionCfg(want||DEFAULT_VERSION);sel.value=CURRENT.id;document.getElementById("verNote").textContent=verNoteText();sel.addEventListener("change",()=>{CURRENT=versionCfg(sel.value);try{localStorage.setItem("benchVersion",CURRENT.id);}catch(e){}history.replaceState(null,"","#v="+CURRENT.id);document.getElementById("verNote").textContent=verNoteText();init();// The manage panel is scoped to the selected version -- its counts, its queue// button and its delete button all name it. Without this it kept the version it// was built with, so switching to v8 left every control still acting on v7.if(typeof loadManage==='function')loadManage();});}document.getElementById('openComparison').onclick=openComparison;document.getElementById('closeComparison').onclick=()=>document.getElementById('comparisonDialog').close();for(const id of ['compareA','compareB','comparisonOrder'])document.getElementById(id).onchange=renderComparison;for(const button of document.querySelectorAll('[data-comparison-mode]'))button.onclick=()=>{comparisonMode=button.dataset.comparisonMode;renderComparison();};document.getElementById('swapComparison').onclick=()=>{const a=document.getElementById('compareA'),b=document.getElementById('compareB');const value=a.value;a.value=b.value;b.value=value;renderComparison();};document.getElementById('closeSubtasks').onclick=()=>document.getElementById('subtaskDialog').close();initVersionPicker(); // resolves CURRENT from #v= / localStorage before anything reads itinit();loadManage(); // must follow initVersionPicker: it is scoped to CURRENT</script></body></html>40 unmodified lines414243444546474849505152533 unmodified lines57585960616263646566676869706 unmodified lines77787980818283848586878818 unmodified lines10710810911011111211311411511611719 unmodified lines137138139140141142143144145146147148149150151152162 unmodified lines3153163173183193203213223233243253263273283293303313323333348 unmodified lines343344345346347348349324 unmodified lines67467567667767867968068168268368468568628 unmodified lines71571671771871972072172272372428 unmodified lines7537547557567577587597607617627637647657667677687697707714 unmodified lines77677777877978078178278378478578678778878979079179279379479579679779879980080180280338 unmodified lines842843844845846847848849138 unmodified lines98898999099199299399482 unmodified lines1077107810791080108110821083108492 unmodified lines1177117811791180118111829 unmodified lines1192119311941195119611971198119912001201120212031204120512061207120812 unmodified lines12211222122312241225122612271228122912301231123 unmodified lines1355135613571358135913601361117 unmodified lines1479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152840 unmodified linesfont-family:"IBM Plex Sans",ui-sans-serif,system-ui,sans-serif;font-size:15px; line-height:1.5; -webkit-font-smoothing:antialiased;}.wrap{max-width:1840px;margin:0 auto;padding:20px clamp(12px,1.25vw,24px) 72px}a{color:var(--accent); text-decoration:none}a:hover{text-decoration:underline; text-decoration-style:dotted}/* ---------------- Masthead ---------------- */.masthead{position:relative; overflow:hidden; border-radius:18px; padding:25px 34px 24px;color:#f3efe4; margin-bottom:20px;background:radial-gradient(130% 150% at 12% 8%, #0c6355 0%, #074237 46%, #04231e 100%);border:1px solid rgba(201,154,63,.32);3 unmodified linesbackground-image:radial-gradient(circle at 88% 16%, rgba(231,200,119,.55) 0, transparent 42%),repeating-linear-gradient(135deg, rgba(255,255,255,.05) 0 2px, transparent 2px 16px);-webkit-mask-image:linear-gradient(90deg,transparent 42%,#000 100%); mask-image:linear-gradient(90deg,transparent 42%,#000 100%);}.masthead::after{content:"";position:absolute;left:34px;right:34px;bottom:0;height:2px;background:linear-gradient(90deg,transparent,#c99a3f 22%,#efd08a 50%,#c99a3f 78%,transparent);opacity:.75}.mh-top{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}.eyebrow{font:600 11.5px/1 "IBM Plex Sans";letter-spacing:.3em;text-transform:uppercase;color:#ecd08a}.titles{display:flex;align-items:baseline;gap:20px;flex-wrap:wrap;margin:13px 0 8px}.title-en{margin:0;font:600 clamp(30px,4.6vw,48px)/1 "Fraunces",Georgia,serif;color:#fdfbf4;letter-spacing:-.012em}.title-ar{font:700 clamp(23px,3.4vw,37px)/1.2 "Amiri",serif;color:#ecd08a;direction:rtl}.tagline{max-width:88ch;margin:2px 0 0;font:400 15px/1.6 "IBM Plex Sans";color:#cfe6dd}.stats{margin-top:17px;display:flex;gap:11px;flex-wrap:wrap;align-items:center;font:500 12.5px/1 "IBM Plex Sans";color:#b6d4ca}.stats b{color:#fff;font-weight:700}.stats .dot{color:#c99a3f;font-size:8px;opacity:.85}.theme-btn{flex:none;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.16);color:#f3efe4;6 unmodified lines/* ---------------- Controls ---------------- */.controls{display:flex;flex-wrap:wrap;gap:14px;align-items:center;margin-bottom:16px}/* Keep this above the results so the owner can leave an empty archive. */.verbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}.verbar label{font:600 12px "IBM Plex Sans";letter-spacing:.02em;color:var(--ink-soft)}.verbar select{padding:8px 12px;border-radius:10px;border:1px solid var(--border);background:var(--bg2);color:var(--ink);font:500 13.5px "IBM Plex Sans"}.verbar select:focus{outline:2px solid var(--accent);outline-offset:0;border-color:transparent}.search{flex:1 1 260px;position:relative}.search input{width:100%;padding:11px 14px 11px 38px;border-radius:12px;border:1px solid var(--border);background:var(--surface);color:var(--ink);font:500 14px "IBM Plex Sans"}18 unmodified lines.board-scroll::-webkit-scrollbar-thumb{background:var(--ink-mute);border-radius:8px;border:3px solid var(--scroll-track)}.board-scroll::-webkit-scrollbar-thumb:hover{background:var(--accent)}table.board{border-collapse:separate;border-spacing:0;width:100%;font-variant-numeric:tabular-nums}table.board th,table.board td{padding:10px clamp(6px,.48vw,12px);white-space:nowrap;text-align:right}table.board th:nth-child(2),table.board td:nth-child(2){padding-inline:12px}.board-scroll:focus-visible{outline:2px solid var(--accent-strong);outline-offset:-2px}.sort-heading{background:none;border:0;padding:0;color:inherit;font:inherit;letter-spacing:inherit;cursor:pointer}.sort-heading:focus-visible{outline:2px solid var(--accent-strong);outline-offset:4px;border-radius:2px}table.board th:nth-child(-n+2),table.board td:nth-child(-n+2){text-align:left}table.board thead th{position:sticky;top:0;z-index:4;background:var(--head-solid);border-bottom:2px solid var(--head-bd);19 unmodified lines.rank.r1{background:linear-gradient(135deg,#f4d980,#c99a3f)}.rank.r2{background:linear-gradient(135deg,#e6e6ea,#b8bcc6)}.rank.r3{background:linear-gradient(135deg,#e3b489,#c0824e)}.model-cell{display:flex;flex-direction:column;gap:2px;max-width:clamp(235px,20vw,344px)}.model-cell .name{font-weight:600;color:var(--ink);overflow:hidden;text-overflow:ellipsis}.model-cell .effort{font-weight:600;opacity:.95}.org{font-size:11.5px;color:var(--ink-mute)}.type-ico{font-size:13px;margin-right:2px}.avg-cell{min-width:105px}.avg-num{font:700 15px "IBM Plex Mono";color:var(--accent-strong)}.avg-bar{height:5px;border-radius:3px;background:var(--surface2);margin-top:5px;overflow:hidden}.avg-bar>i{display:block;height:100%;border-radius:3px;background:linear-gradient(90deg,var(--emerald-600),var(--emerald-400))}.score{font-family:"IBM Plex Mono";font-weight:500;border-radius:7px;padding:5px 8px;display:inline-block;min-width:46px;text-align:right}/* best score in each task column (across all shown models) */.score.na{color:var(--muted);opacity:.55;font-weight:400}.score.best{font-weight:800;color:var(--ink);box-shadow:inset 0 0 0 2px var(--gold),0 4px 12px -6px rgba(201,154,63,.5)}162 unmodified lines<h1 class="title-en">Arabic LLM Leaderboard</h1><span class="title-ar">لوحة صدارة نماذج اللغة العربية</span></div><p class="tagline">Compare language models across Arabic language, reasoning, knowledge and dialogue tasks.</p><div class="stats"><span><b id="itemCount">31,846</b> items</span><i class="dot">◆</i><span><b id="subtaskCount">75</b> subtasks</span><i class="dot">◆</i><span><b id="catCount">11</b> categories</span><i class="dot">◆</i><span><b>5</b> formats</span><i class="dot">◆</i><span><b id="modelCount">—</b> models</span><i class="dot">◆</i><span>LLM-as-Judge</span></div></header><div class="verbar" id="versionBar" hidden><label for="verSel">Benchmark version</label><select id="verSel"></select></div><div class="controls" id="controls" hidden>8 unmodified lines</div><div class="board-card"><div class="board-scroll" tabindex="0" aria-label="Leaderboard scores"><div class="state" id="state"><div class="spinner"></div>Loading the leaderboard…</div><table class="board" id="board" hidden><thead id="thead"></thead><tbody id="tbody"></tbody></table></div>324 unmodified lines{id:"v8", label:"v8 — corpus 32,890", dims:DIMS_V8, ks:KS_V8, subtasks:70},{id:"v9", label:"v9 — corpus 32,890", dims:DIMS_V9, ks:KS_V9, subtasks:70},{id:"v10", label:"v10 — corpus 35,390", dims:DIMS_V10, ks:KS_V10, subtasks:75},{id:"v11", label:"v11 — test split 31,846", dims:DIMS_V11, ks:KS_V11, subtasks:75},{id:"v12", label:"v12 — test split 31,846", dims:DIMS_V12_DISPLAY, ks:KS_V12, subtasks:75}];const DEFAULT_VERSION="v12";const PUBLIC_VERSION=VERSIONS.find(v=>v.id===DEFAULT_VERSION);let ownerVersions=null;let CURRENT=PUBLIC_VERSION;let DIMS=CURRENT.dims;let KS=CURRENT.ks;let WSUM=DIMS.reduce((s,d)=>s+d[2],0);28 unmodified linesasync function getJSON(u){const r=await fetch(u);if(!r.ok)throw new Error(r.status);return r.json();}async function loadDir(repo,version){const archived=version&&version.id!==DEFAULT_VERSION;const tree=await getJSON(archived? "/api/benchmark-result-files?version="+encodeURIComponent(version.id): TREE(repo));let files=tree.filter(f=>f.type==="file"&&f.path.endsWith(".json"));if(version){const pre=version.id+"/";28 unmodified linesreturn w?s/w:0;}let boardLoadSeq=0;async function init(){const seq=++boardLoadSeq;const version=CURRENT;const requestedVersion=version.id;const showPrivate=!!ownerVersions?.size;document.getElementById("openComparison").disabled=true;for(const id of ["comparisonDialog","subtaskDialog"]){const dialog=document.getElementById(id);if(dialog.open)dialog.close();}state.models=[];state.extra={};document.getElementById("tbody").innerHTML="";DIMS=CURRENT.dims; KS_PARTS=CURRENT.ks; WSUM=DIMS.reduce((s,d)=>s+d[2],0);// The corpus size belongs to the version: v7 is 34,137 items and v8 is 32,890.const ic=document.getElementById("itemCount");4 unmodified linesif(sc&&CURRENT.subtasks)sc.textContent=String(CURRENT.subtasks);for(const id of ["catCount","dimCount"]){const e=document.getElementById(id);if(e)e.textContent=String(DIMS.length);}const st=document.getElementById("state");st.hidden=false; st.innerHTML='<div class="spinner"></div>Loading the leaderboard…';document.getElementById("board").hidden=true;document.getElementById("controls").hidden=true;document.getElementById("note").hidden=true;let results,requests,privateRows,metrics;const optional=(promise,fallback)=>promise.catch(()=>fallback);const versionQuery="?version="+encodeURIComponent(requestedVersion);try{[results,requests,privateRows,metrics]=await Promise.all([loadDir(RESULTS,version),optional(loadDir(REQUESTS),[]),showPrivate?optional(getJSON("/api/private-results"+versionQuery),null):null,showPrivate?optional(getJSON("/api/private-metrics"+versionQuery),null):null]);}catch(e){if(seq===boardLoadSeq)st.textContent="Could not load leaderboard results. Refresh to try again.";if(showPrivate&&(e.message==="401"||e.message==="403"))refreshMe();return;}if(seq!==boardLoadSeq)return;if(Array.isArray(privateRows?.results))results=results.concat(privateRows.results);state.extra=metrics?.models||{};// the progress card cross-checks against these to see if a run is really livestate.requests=requests;if(typeof loadProgress==='function')loadProgress();38 unmodified linesif(!models.length){st.hidden=false;st.innerHTML='<div style="text-align:center;padding:26px 12px">'+'<div style="font-size:15px;font-weight:600;margin-bottom:6px">No model results yet.</div>'+'<div class="muted" style="font-size:13px">Scores appear as evaluations finish.</div></div>';document.getElementById("board").hidden=true;document.getElementById("tbody").innerHTML=""; // drop the previous version's rowsdocument.getElementById("modelCount").textContent="0";138 unmodified linesconst result=compareModels(a,b,comparisonMode,CURRENT.id,DIMS);const overallDelta=a&&b?comparisonDelta(a.avg,b.avg):0;document.getElementById('comparisonSummary').textContent=a&&b&&result.rows.length?'Overall: A '+a.avg.toFixed(2)+'% · B '+b.avg.toFixed(2)+'% · B − A '+(overallDelta>0?'+':'')+(Object.is(overallDelta,-0)?0:overallDelta).toFixed(2)+' pp':'Overall comparison unavailable for this selection.';document.getElementById('comparisonVersion').textContent=ownerVersions?.size?CURRENT.label:"Current public benchmark";const warning=document.getElementById('comparisonWarning');warning.textContent=result.notice;warning.hidden=!result.notice;document.getElementById('comparisonBody').innerHTML=comparisonTableHTML(result,document.getElementById('comparisonOrder').value);const comparable=result.rows.filter(r=>r.delta!==null);82 unmodified linesconst active=(state.sort===key)||(key==="rank"&&state.sort==="avg");const arrow=active?`<span class="arrow">${state.dir<0?"▼":"▲"}</span>`:"";const cls=(key!=="rank"&&key!=="model"&&key!=="avg")?' class="sub"':"";const sort=active&&key!=="rank"?` aria-sort="${state.dir<0?"descending":"ascending"}"`:"";return `<th scope="col" data-k="${key}"${cls}${sort}><button type="button" class="sort-heading">${label}${arrow}</button></th>`;}).join("")+"</tr>";thead.querySelectorAll("th").forEach(th=>th.onclick=()=>{const key=th.dataset.k;if(state.sort===key||(key==="rank"&&state.sort==="avg")){state.dir*=-1;}92 unmodified linesfor(const id of ['visField','maxField','subtaskField']){const el=document.getElementById(id); if(el)el.hidden=!isOwner;}if(!isOwner){const vs=document.getElementById('f-vis'); if(vs)vs.value='public';const mx=document.getElementById('f-max'); if(mx)mx.value='';9 unmodified linessigninView.hidden=false; submitForm.hidden=true;}}let sessionSeq=0;async function refreshMe(){const seq=++sessionSeq;let data={};try{const response=await fetch("/api/me",{credentials:"same-origin",cache:"no-store"});if(response.ok)data=await response.json();}catch(e){/* Default to public access if the session cannot be checked. */}if(seq!==sessionSeq)return;setUser(data.user||null,!!data.is_owner);syncVersionPicker(data.is_owner&&Array.isArray(data.benchmark_versions)?data.benchmark_versions:[]);}function smsg(t,kind){submitMsg.className='msg'+(t?(' show '+kind):'');submitMsg.textContent=t||'';}function openModal(){modal.classList.add('open');modal.setAttribute('aria-hidden','false');smsg('');refreshMe();}12 unmodified lineselse{window.location.href='/login';}};// pick up a sign-in that completed in another tab / after returningfunction refreshActiveSession(){if(ownerVersions?.size||modal.classList.contains("open"))refreshMe();}window.addEventListener("focus",refreshActiveSession);document.addEventListener("visibilitychange",()=>{if(!document.hidden)refreshActiveSession();});submitForm.addEventListener('submit',async e=>{e.preventDefault();123 unmodified lines// delete buttons named another. Only the newest call may paint.let _manageSeq=0;async function loadManage(){if(!ownerVersions?.size)return;const seq=++_manageSeq;const panel=document.getElementById('managePanel');const list=document.getElementById('manageList');117 unmodified linesif(boardScroll)boardScroll.addEventListener('scroll',()=>boardScroll.classList.toggle('scrolled',boardScroll.scrollLeft>2),{passive:true});function syncVersionPicker(ids){const allowed=VERSIONS.filter(v=>ids.includes(v.id));const next=new Set(allowed.map(v=>v.id));if(ownerVersions&&[...ownerVersions].join(",")===[...next].join(","))return;ownerVersions=next;const picker=document.getElementById("verSel");const fromHash=(location.hash.match(/(?:^|[#&])v=([^&]+)/)||[])[1];let wanted=fromHash;if(next.size&&!wanted){try{wanted=localStorage.getItem("benchVersion");}catch(e){}}CURRENT=allowed.find(v=>v.id===wanted)||PUBLIC_VERSION;picker.innerHTML="";for(const version of allowed){const option=document.createElement("option");option.value=version.id;option.textContent=version.label;picker.appendChild(option);}picker.value=CURRENT.id;document.getElementById("versionBar").hidden=!next.size;if(fromHash&&fromHash!==CURRENT.id)history.replaceState(null,"","#v="+CURRENT.id);if(next.size)loadManage();else{++_manageSeq;document.getElementById("managePanel").hidden=true;}init();}document.getElementById("verSel").onchange=event=>{const version=VERSIONS.find(v=>v.id===event.target.value&&ownerVersions?.has(v.id));if(!version||CURRENT.id===version.id)return;CURRENT=version;try{localStorage.setItem("benchVersion",version.id);}catch(e){}history.replaceState(null,"","#v="+version.id);init();loadManage();};document.getElementById('openComparison').onclick=openComparison;document.getElementById('closeComparison').onclick=()=>document.getElementById('comparisonDialog').close();for(const id of ['compareA','compareB','comparisonOrder'])document.getElementById(id).onchange=renderComparison;for(const button of document.querySelectorAll('[data-comparison-mode]'))button.onclick=()=>{comparisonMode=button.dataset.comparisonMode;renderComparison();};document.getElementById('swapComparison').onclick=()=>{const a=document.getElementById('compareA'),b=document.getElementById('compareB');const value=a.value;a.value=b.value;b.value=value;renderComparison();};document.getElementById('closeSubtasks').onclick=()=>document.getElementById('subtaskDialog').close();if(new URLSearchParams(location.search).get("signedin"))openModal();else refreshMe();</script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Regression checks for public vs owner benchmark access."""import base64import jsonfrom types import SimpleNamespacefrom unittest.mock import patch
from fastapi.testclient import TestClientfrom itsdangerous import TimestampSigner
import app
def signed_client(session): client = TestClient(app.app, base_url="https://leaderboard.test") if session is not None: key = app.app.user_middleware[0].kwargs["secret_key"] payload = base64.b64encode(json.dumps(session).encode()) client.cookies.set("session", TimestampSigner(key).sign(payload).decode()) return client
def test_public_and_other_users_cannot_select_versions(): for session, code in [ (None, 401), ({"user": "somebody", "hf_handle": "somebody"}, 403), ({"user": app.LEADERBOARD_OWNER}, 403), ]: with signed_client(session) as client: profile = client.get("/api/me") assert profile.status_code == 200 assert profile.headers["cache-control"] == "private, no-store" assert profile.json()["is_owner"] is False assert "benchmark_versions" not in profile.json() with patch.object(app.api_public, "list_repo_files", side_effect=AssertionError("auth checked too late")): assert client.get("/api/benchmark-result-files?version=v8").status_code == code assert client.get("/api/private-results?version=v8").status_code == code assert client.get("/api/private-metrics?version=v8").status_code == code
def test_owner_gets_versions_and_only_matching_files(): owner = {"user": app.LEADERBOARD_OWNER, "hf_handle": app.LEADERBOARD_OWNER} paths = ["v12/org/results_one.json", "v8/org/results_two.json", "org/results_legacy.json", "v8/README.md"] with signed_client(owner) as client, patch.object(app.api_public, "list_repo_files", return_value=paths): me = client.get("/api/me").json() assert me["is_owner"] is True and me["benchmark_versions"] == app.VERSIONS result = client.get("/api/benchmark-result-files?version=v8") assert result.status_code == 200 and result.headers["cache-control"] == "private, no-store" assert result.json() == [{"type": "file", "path": "v8/org/results_two.json"}] assert client.get("/api/benchmark-result-files?version=v7").json() == [ {"type": "file", "path": "org/results_legacy.json"} ] assert client.get("/api/benchmark-result-files?version=bad-version").status_code == 400 logout = client.get("/logout", follow_redirects=False) assert "session=null" in logout.headers["set-cookie"]
def test_oauth_uses_the_account_handle_for_owner_access(): import asyncio
async def check(userinfo, expected): async def token(*args): return {"userinfo": userinfo}
request = SimpleNamespace(session={"hf_handle": app.LEADERBOARD_OWNER}) with patch.object(app, "_oauth", SimpleNamespace(hf=SimpleNamespace(authorize_access_token=token))): result = await app.login_callback(request) assert result.status_code == 200 assert app._is_owner(request) is expected
asyncio.run(check({"name": app.LEADERBOARD_OWNER, "sub": "other-id"}, False)) asyncio.run(check({"name": app.LEADERBOARD_OWNER, "preferred_username": "someone-else"}, False)) asyncio.run(check({"name": "Display name", "preferred_username": app.LEADERBOARD_OWNER}, True))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import assert from "node:assert/strict";import fs from "node:fs";import vm from "node:vm";
const html=fs.readFileSync(new URL("./index.html",import.meta.url),"utf8");const script=html.match(/<script>([\s\S]*)<\/script>/)[1];assert.match(html, /id="versionBar" hidden/);assert.doesNotMatch(html, /so scores run about 7 points higher/);
const response=(body,ok=true)=>({ok,status:ok?200:403,json:async()=>body});const element=()=>({ innerHTML:"",textContent:"",hidden:false,value:"",options:[],children:[], classList:{toggle(){},add(){},remove(){},contains(){return false;}}, style:{},dataset:{},appendChild(c){this.children.push(c);},setAttribute(){}, addEventListener(){},querySelectorAll(){return [];},});async function start({me,hash,remember}) { const requests=[],elements=new Map(), location={hash,search:""}; const document={ getElementById(id){if(!elements.has(id))elements.set(id,element());return elements.get(id);}, querySelector:element,querySelectorAll:()=>[],createElement:element, documentElement:element(),addEventListener(){}, }; const fake={ document,location, history:{replaceState(_state,_title,hash){location.hash=hash;}}, localStorage:{getItem(k){return k==="benchVersion"?remember:null;},setItem(){}}, matchMedia:()=>({matches:false,addEventListener(){},addListener(){}}), addEventListener(){},setTimeout(){},setInterval(){},URLSearchParams, fetch:async (url)=>{ requests.push(url); if(url==="/api/me")return response(me); if(url.startsWith("/api/manage"))return response({models:[],versions:["v7","v8","v9","v10","v11","v12"]}); if(url.startsWith("/api/private-results"))return response({results:[]}); if(url.startsWith("/api/private-metrics"))return response({models:{}}); if(url.startsWith("/api/benchmark-result-files")||url.startsWith("https://huggingface.co/"))return response([]); return response({},false); }, }; fake.window=fake; const ctx=vm.createContext(fake); vm.runInContext(script,ctx,{filename:"index.html"}); await new Promise(setImmediate); return {requests, ctx, location, elements, get:()=>vm.runInContext("CURRENT.id",ctx)};}
for(const me of [{user:null,is_owner:false},{user:"other",is_owner:false,benchmark_versions:["v8"]}]){ const board=await start({me,hash:"#v=v8",remember:"v9"}); assert.equal(board.get(),"v12"); assert.equal(board.location.hash,"#v=v12"); assert.equal(board.elements.get("versionBar").hidden,true); assert.equal(board.elements.get("verSel").children.length,0); board.elements.get("verSel").onchange({target:{value:"v8"}}); assert.equal(board.get(),"v12"); assert.ok(!board.requests.some(url=>url.startsWith("/api/benchmark-result-files")||url.startsWith("/api/private-")||url.startsWith("/api/manage")));}
const owner=await start({me:{user:"Mushari440",is_owner:true,benchmark_versions:["v7","v8","v9","v10","v11","v12"]},hash:"#v=v8",remember:"v9"});assert.equal(owner.get(),"v8");assert.equal(owner.elements.get("versionBar").hidden,false);assert.deepEqual(owner.elements.get("verSel").children.map(x=>x.value),["v7","v8","v9","v10","v11","v12"]);assert.ok(owner.requests.includes("/api/benchmark-result-files?version=v8"));owner.elements.get("verSel").onchange({target:{value:"v11"}});assert.equal(owner.get(),"v11");assert.ok(owner.requests.includes("/api/benchmark-result-files?version=v11"));owner.elements.get("verSel").onchange({target:{value:"v13"}});assert.equal(owner.get(),"v11");await new Promise(setImmediate);console.log("PASS guest and non-owner default, owner deep link and switching, unauthorized version rejection");app.py+59-18
index.html+115-108
test_version_access.pyAdded+72
test_version_ui.mjsAdded+69