Spaces:
Sleeping
Sleeping
Update src/main.py
Browse files1234567891011127 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273742 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212310 unmodified lines1341351361371381391401411421431441451466 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941953 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302311 unmodified line23323423523623723823924024124224324424524624724824925025125225325425525625725812 unmodified lines2712722732742752762772782792802812822832 unmodified lines2862872882892902912 unmodified lines294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399# import streamlit as st# st.write("hello")import osimport jsonimport uuidimport timeimport tempfilefrom typing import Any, Dict, List, Tupleimport streamlit as st7 unmodified lines# =========================st.set_page_config(page_title="AI Benchmark Arena",page_icon="π",layout="wide",initial_sidebar_state="expanded",)#Set this to the private dataset repo that acts as the "database"DB_REPO_ID = os.getenv("DB_REPO_ID", "NidhiS09/VizWiz-submissions-db")DB_REPO_TYPE = "dataset"# print(DB_REPO_ID)# This must exist as a Space Secret in the PUBLIC UI SpaceSUBMISSIONS_TOKEN = os.getenv("SUBMISSIONS_TOKEN", "")# Phase config (copied from EvalAI config intent)PHASES = [{"label": "Dev (qeury-dev2024)", "codename": "test-dev2024"},{"label": "Standard (query-standard2024)", "codename": "test-standard2024"},{"label": "Challenge (query-challenge2024)", "codename": "test-challenge2024"},]CHALLENGE_TYPES = ["Object Detection", "Instance Segmentation"]# Leaderboard columns from your EvalAI yamlLEADERBOARD_METRICS = ["bbox_mAP", "bbox_AP50", "segm_mAP", "segm_AP50"]DEFAULT_SORT_METRIC = "segm_AP50"# =========================# HELPERS# =========================def _require_token() -> None:if not SUBMISSIONS_TOKEN:st.error("Missing SUBMISSIONS_TOKEN. Add it in Space Settings β Secrets ""(token must have read/write access ONLY to the private DB dataset repo).")st.stop()def _validate_submission_json(obj: Any) -> Tuple[bool, str]:"""Validates the submission format from your instructions:- Top-level must be a list- Each item must be a dict containing:image_id (int), score (number), category_id (int), area (number),bbox ([x,y,w,h]), segmentation (list)"""if not isinstance(obj, list):return False, "Submission must be a JSON list of annotations."2 unmodified linesfor i, ann in enumerate(obj):if not isinstance(ann, dict):return False, f"Annotation at index {i} must be an object/dict."missing = required_keys - set(ann.keys())if missing:return False, f"Annotation at index {i} missing keys: {sorted(list(missing))}"# Basic type checksif not isinstance(ann["image_id"], int):return False, f"image_id at index {i} must be an integer."if not isinstance(ann["category_id"], int):return False, f"category_id at index {i} must be an integer."if not isinstance(ann["score"], (int, float)):return False, f"score at index {i} must be a number."if not isinstance(ann["area"], (int, float)):return False, f"area at index {i} must be a number."bbox = ann["bbox"]if not (isinstance(bbox, list) and len(bbox) == 4 and all(isinstance(x, (int, float)) for x in bbox)):return False, f"bbox at index {i} must be a list of 4 numbers: [x, y, w, h]."segm = ann["segmentation"]if not isinstance(segm, list):return False, f"segmentation at index {i} must be a list."return True, "OK"def _upload_json(api: HfApi, data: Dict[str, Any] | List[Any], path_in_repo: str) -> None:with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp:json.dump(data, tmp, ensure_ascii=False)tmp_path = tmp.nametry:api.upload_file(path_or_fileobj=tmp_path,path_in_repo=path_in_repo,repo_id=DB_REPO_ID,repo_type=DB_REPO_TYPE,token=SUBMISSIONS_TOKEN,commit_message=f"Add {path_in_repo}",)finally:try:10 unmodified linesphase_codename: str,challenge_type: str,original_filename: str,) -> str:"""Writes pred/meta/status to the private DB dataset repo.Returns submission_id."""_require_token()api = HfApi()submission_id = str(uuid.uuid4())ts = int(time.time())6 unmodified lines"challenge_type": challenge_type,"timestamp": ts,"original_filename": original_filename,}status = {"state": "queued", "timestamp": ts}base = f"submissions/{submission_id}"_upload_json(api, pred, f"{base}/pred.json")_upload_json(api, meta, f"{base}/meta.json")_upload_json(api, status, f"{base}/status.json")return submission_iddef _download_leaderboard_jsonl() -> str | None:"""Downloads leaderboard.jsonl from the DB repo.Returns local path or None if missing."""_require_token()try:return hf_hub_download(repo_id=DB_REPO_ID,repo_type=DB_REPO_TYPE,filename="leaderboard.jsonl",token=SUBMISSIONS_TOKEN,)except HfHubHTTPError as e:# Most common: 404 when file doesn't exist yetif "404" in str(e):return Noneraisedef _load_leaderboard_df() -> pd.DataFrame:path = _download_leaderboard_jsonl()if path is None:return pd.DataFrame(columns=["team", "model", "phase_codename", *LEADERBOARD_METRICS, "timestamp"])rows = []with open(path, "r", encoding="utf-8") as f:for line in f:3 unmodified linestry:rows.append(json.loads(line))except json.JSONDecodeError:# Skip malformed lines rather than crashing the UIcontinueif not rows:return pd.DataFrame(columns=["team", "model", "phase_codename", *LEADERBOARD_METRICS, "timestamp"])df = pd.DataFrame(rows)# Ensure columns existfor col in ["team", "model", "phase_codename", "timestamp", *LEADERBOARD_METRICS]:if col not in df.columns:df[col] = None# Sort descending by default metricif DEFAULT_SORT_METRIC in df.columns:df = df.sort_values(by=DEFAULT_SORT_METRIC, ascending=False, kind="mergesort")return df# =========================# UI# =========================#2 FUNCTIONS WERE HERE, RENDER_OVERVIEW AND RENDER EVALdef page_submit():st.header("π Submit your Predictions")col1, col2 = st.columns([2, 1])1 unmodified linest.subheader("Submission Info")team = st.text_input("Team / Display Name", value=st.session_state.get("team", ""))model_name = st.text_input("Model Name", value=st.session_state.get("model_name", ""))phase_label = st.selectbox("Phase", [p["label"] for p in PHASES])phase_codename = next(p["codename"] for p in PHASES if p["label"] == phase_label)challenge_type = st.radio("Challenge type", CHALLENGE_TYPES, horizontal=False)st.session_state["team"] = teamst.session_state["model_name"] = model_namest.caption("Your submission will be queued for evaluation. Scores appear on the leaderboard after processing.")with col1:st.subheader("Upload Submission File")uploaded_file = st.file_uploader("Choose a JSON file", type=["json"])if uploaded_file is None:st.info("Upload a JSON file that contains a list of annotations.")return# Parse JSONtry:raw = uploaded_file.getvalue().decode("utf-8")pred_obj = json.loads(raw)12 unmodified linesif submit_clicked:if not team.strip():st.error("Please enter Team / Display Name.")returnif not model_name.strip():st.error("Please enter Model Name.")returnwith st.spinner("Uploading submission to the private database repo..."):try:submission_id = _create_submission_record(pred=pred_obj,2 unmodified linesphase_codename=phase_codename,challenge_type=challenge_type,original_filename=uploaded_file.name,)except Exception as e:st.error(f"Upload failed: {e}")2 unmodified linesst.balloons()st.success("Submission queued successfully!")st.code(f"Submission ID: {submission_id}")st.info("Next: the private evaluator will score your submission and update the leaderboard.")def page_leaderboard():st.header("π Leaderboard")st.write(f"Ranked by **{DEFAULT_SORT_METRIC}** (descending).")with st.spinner("Loading leaderboard from private database repo..."):try:df = _load_leaderboard_df()except Exception as e:st.error(f"Could not load leaderboard: {e}")returnif df.empty:st.info("No scored submissions yet. Submit a model to get started!")return# Add Rank columndf_display = df.copy()df_display.insert(0, "Rank", range(1, len(df_display) + 1))# Optional: pretty timestampif "timestamp" in df_display.columns:df_display["timestamp"] = pd.to_datetime(df_display["timestamp"], unit="s", errors="coerce")st.dataframe(df_display,column_config={"Rank": st.column_config.Column("Rank", width="small"),"team": "Team","model": "Model","phase_codename": "Phase","bbox_mAP": st.column_config.NumberColumn("bbox_mAP", format="%.4f"),"bbox_AP50": st.column_config.NumberColumn("bbox_AP50", format="%.4f"),"segm_mAP": st.column_config.NumberColumn("segm_mAP", format="%.4f"),"segm_AP50": st.column_config.NumberColumn("segm_AP50", format="%.4f"),"timestamp": st.column_config.DatetimeColumn("Scored at", format="D MMM YYYY, h:mm a"),},use_container_width=True,hide_index=True,)def main():# st.write("β App booted and rendering UI")st.sidebar.title("AI Benchmark Arena π")# Warn early if DB repo isn't configuredif DB_REPO_ID.startswith("NidhiS09/"):st.sidebar.warning("Set DB_REPO_ID env var or hardcode your private DB dataset repo id in main.py.")menu = ["Submit Model", "Leaderboard"]choice = st.sidebar.radio("Navigation", menu)st.sidebar.markdown("---")st.sidebar.caption("This Space queues submissions to a private DB repo and reads leaderboard results from it.")render_overview()render_eval_details()st.markdown("---")if choice == "Submit Model":page_submit()else:page_leaderboard()def render_overview():with st.expander("βΉοΈ Overview of the AI Benchmark Arena"):st.markdown("""**Note:** This Hugging Face Space queues submissions for evaluation and persists results in a private database repo.""")# Keep this optional so missing image doesn't crash the Spacetry:overview_image = Image.open("src/overview_image.png").resize((600, 600))st.image(overview_image, caption="Example of an object localization task")except Exception:st.info("Overview image not found at src/overview_image.png (optional).")def render_eval_details():with st.expander("π How is the Score Calculated?"):st.markdown("""Your submission is evaluated offline by a private evaluator against hidden ground-truth annotations.The leaderboard reports:- bbox_mAP- bbox_AP50- segm_mAP- segm_AP50 (default ranking)Raw submissions are kept private; only scores and metadata are shown.""")if __name__ == "__main__":123456789107 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711722 unmodified lines17517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121210 unmodified lines2232242252262272282292302312326 unmodified lines2392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712723 unmodified lines2762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694701 unmodified line47247347447547647747847948048148248348448548648748848949049149212 unmodified lines5055065075085095105115125135145155165175185195205215225232 unmodified lines5265275285295305315325332 unmodified lines536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664import osimport jsonimport uuidimport timeimport tempfileimport hashlibfrom datetime import datetime, timezonefrom typing import Any, Dict, List, Tupleimport streamlit as st7 unmodified lines# =========================st.set_page_config(page_title="VizWiz Benchmark Arena",page_icon="π",layout="wide",initial_sidebar_state="expanded",)DB_REPO_ID = os.getenv("DB_REPO_ID", "NidhiS09/VizWiz-submissions-db")DB_REPO_TYPE = "dataset"SUBMISSIONS_TOKEN = os.getenv("SUBMISSIONS_TOKEN", "")DAILY_SUBMISSION_CAP = 5PHASES = [{"label": "Dev (query-dev2024)", "codename": "test-dev2024"},{"label": "Standard (query-standard2024)", "codename": "test-standard2024"},{"label": "Challenge (query-challenge2024)", "codename": "test-challenge2024"},]CHALLENGE_TYPES = ["Object Detection", "Instance Segmentation"]LEADERBOARD_METRICS = ["bbox_mAP", "bbox_AP50", "segm_mAP", "segm_AP50"]DEFAULT_SORT_METRIC = "segm_AP50"# =========================# AUTH HELPERS# =========================def get_oauth_info() -> Dict | None:"""Returns the HF OAuth user info dict if logged in, else None.Keys: preferred_username, name, email, picture, ...This works automatically when hf_oauth: true is set in README.md"""try:user_info = st.context.headers.get("X-Space-User-Info")if user_info:return json.loads(user_info)except Exception:pass# Fallback: check session state (set after OAuth redirect)if "oauth_info" in st.session_state and st.session_state["oauth_info"]:return st.session_state["oauth_info"]# Use st.experimental_user if available (newer Streamlit on HF Spaces)try:user = st.experimental_userif user and getattr(user, "email", None):return {"preferred_username": getattr(user, "username", user.email.split("@")[0]),"name": getattr(user, "name", user.email),"email": user.email,"picture": getattr(user, "picture", None),}except Exception:passreturn Nonedef render_login_wall():"""Shows login prompt and stops rendering if not authenticated."""user = get_oauth_info()if user:return userst.markdown("---")st.markdown("## π Login Required")st.info("You need to log in with your Hugging Face account to submit predictions ""or view your submission history.")login_url = os.getenv("SPACE_HOST", "")if login_url:st.markdown(f'<a href="https://{login_url}/oauth/login" target="_self">'f'<button style="background:#FF6B35;color:white;border:none;padding:12px 28px;'f'font-size:16px;border-radius:8px;cursor:pointer;">π€ Login with Hugging Face</button></a>',unsafe_allow_html=True,)else:st.warning("OAuth login URL not available in local dev. ""Deploy to HF Spaces with `hf_oauth: true` in README.md.")st.stop()# =========================# SUBMISSION CAP HELPERS# =========================def _today_utc_str() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%d")def _count_submissions_today(hf_username: str) -> int:"""Count how many submissions this user has made today by scanning submission metadata.We do this by listing all submission files and checking meta.json for matching username + today's date.Uses a lightweight approach: filter by filename listing only."""try:files = api_client().list_repo_files(repo_id=DB_REPO_ID, repo_type=DB_REPO_TYPE, token=SUBMISSIONS_TOKEN)today = _today_utc_str()count = 0for f in files:if not (f.startswith("submissions/") and f.endswith("/meta.json")):continuetry:p = hf_hub_download(repo_id=DB_REPO_ID,repo_type=DB_REPO_TYPE,filename=f,token=SUBMISSIONS_TOKEN,)meta = json.load(open(p))if meta.get("hf_username") == hf_username:ts = meta.get("timestamp", 0)sub_date = datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%d")if sub_date == today:count += 1except Exception:continuereturn countexcept Exception:return 0# =========================# HF API HELPERS# =========================@st.cache_resourcedef api_client() -> HfApi:return HfApi()def _require_token() -> None:if not SUBMISSIONS_TOKEN:st.error("Missing SUBMISSIONS_TOKEN. Add it in Space Settings β Secrets.")st.stop()def _validate_submission_json(obj: Any) -> Tuple[bool, str]:if not isinstance(obj, list):return False, "Submission must be a JSON list of annotations."2 unmodified linesfor i, ann in enumerate(obj):if not isinstance(ann, dict):return False, f"Annotation at index {i} must be an object/dict."missing = required_keys - set(ann.keys())if missing:return False, f"Annotation at index {i} missing keys: {sorted(list(missing))}"if not isinstance(ann["image_id"], int):return False, f"image_id at index {i} must be an integer."if not isinstance(ann["category_id"], int):return False, f"category_id at index {i} must be an integer."if not isinstance(ann["score"], (int, float)):return False, f"score at index {i} must be a number."if not isinstance(ann["area"], (int, float)):return False, f"area at index {i} must be a number."bbox = ann["bbox"]if not (isinstance(bbox, list) and len(bbox) == 4 and all(isinstance(x, (int, float)) for x in bbox)):return False, f"bbox at index {i} must be a list of 4 numbers: [x, y, w, h]."if not isinstance(ann["segmentation"], list):return False, f"segmentation at index {i} must be a list."return True, "OK"def _upload_json(data: Any, path_in_repo: str, commit_message: str = "") -> None:with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp:json.dump(data, tmp, ensure_ascii=False)tmp_path = tmp.nametry:api_client().upload_file(path_or_fileobj=tmp_path,path_in_repo=path_in_repo,repo_id=DB_REPO_ID,repo_type=DB_REPO_TYPE,token=SUBMISSIONS_TOKEN,commit_message=commit_message or f"Add {path_in_repo}",)finally:try:10 unmodified linesphase_codename: str,challenge_type: str,original_filename: str,hf_username: str,hf_email: str,) -> str:_require_token()submission_id = str(uuid.uuid4())ts = int(time.time())6 unmodified lines"challenge_type": challenge_type,"timestamp": ts,"original_filename": original_filename,"hf_username": hf_username,"hf_email": hf_email,}status = {"state": "queued", "timestamp": ts}base = f"submissions/{submission_id}"_upload_json(pred, f"{base}/pred.json", f"pred {submission_id}")_upload_json(meta, f"{base}/meta.json", f"meta {submission_id}")_upload_json(status, f"{base}/status.json", f"status {submission_id}")return submission_iddef _load_leaderboard_df() -> pd.DataFrame:_require_token()try:path = hf_hub_download(repo_id=DB_REPO_ID,repo_type=DB_REPO_TYPE,filename="leaderboard.jsonl",token=SUBMISSIONS_TOKEN,)except HfHubHTTPError as e:if "404" in str(e):return pd.DataFrame(columns=["team", "model", "phase_codename", *LEADERBOARD_METRICS, "timestamp"])raiserows = []with open(path, "r", encoding="utf-8") as f:for line in f:3 unmodified linestry:rows.append(json.loads(line))except json.JSONDecodeError:continueif not rows:return pd.DataFrame(columns=["team", "model", "phase_codename", *LEADERBOARD_METRICS, "timestamp"])df = pd.DataFrame(rows)for col in ["team", "model", "phase_codename", "timestamp", *LEADERBOARD_METRICS]:if col not in df.columns:df[col] = Noneif DEFAULT_SORT_METRIC in df.columns:df = df.sort_values(by=DEFAULT_SORT_METRIC, ascending=False, kind="mergesort")return dfdef _load_user_submissions(hf_username: str) -> List[Dict]:"""Load all submissions for a specific HF user."""_require_token()try:files = api_client().list_repo_files(repo_id=DB_REPO_ID, repo_type=DB_REPO_TYPE, token=SUBMISSIONS_TOKEN)except Exception:return []results = []for f in files:if not (f.startswith("submissions/") and f.endswith("/meta.json")):continuetry:sid = f.split("/")[1]meta_path = hf_hub_download(repo_id=DB_REPO_ID, repo_type=DB_REPO_TYPE,filename=f, token=SUBMISSIONS_TOKEN)meta = json.load(open(meta_path))if meta.get("hf_username") != hf_username:continue# Get statustry:status_path = hf_hub_download(repo_id=DB_REPO_ID, repo_type=DB_REPO_TYPE,filename=f"submissions/{sid}/status.json", token=SUBMISSIONS_TOKEN)status = json.load(open(status_path))except Exception:status = {"state": "unknown"}# Get results if donemetrics = {}if status.get("state") == "done":metrics = status.get("metrics", {})results.append({"submission_id": sid,"team": meta.get("team", ""),"model": meta.get("model", ""),"phase": meta.get("phase_codename", ""),"challenge_type": meta.get("challenge_type", ""),"timestamp": meta.get("timestamp", 0),"state": status.get("state", "unknown"),**metrics,})except Exception:continueresults.sort(key=lambda x: x["timestamp"], reverse=True)return results# =========================# UI PAGES# =========================def render_overview():with st.expander("βΉοΈ Overview of the VizWiz Benchmark Arena"):st.markdown("""**VizWiz Object Localization Challenge** β Submit your model predictions and get scored automatically.- π€ **Submit**: Upload your prediction JSON for Dev, Standard, or Challenge phases- π **Leaderboard**: View public rankings for the Standard phase- π **My Submissions**: Track all your past submissions and scores""")try:overview_image = Image.open("src/overview_image.png").resize((600, 600))st.image(overview_image, caption="Example of an object localization task")except Exception:passdef render_eval_details():with st.expander("π How is the Score Calculated?"):st.markdown("""Your submission is evaluated automatically against hidden ground-truth annotations.The leaderboard reports:- **bbox_mAP** β bounding box mean average precision- **bbox_AP50** β bounding box AP at IoU=0.50- **segm_mAP** β segmentation mean average precision- **segm_AP50** β segmentation AP at IoU=0.50 *(default ranking)*""")def page_leaderboard():st.header("π Leaderboard β Standard Phase")st.caption(f"Ranked by **{DEFAULT_SORT_METRIC}** (descending). Showing Standard phase submissions only.")with st.spinner("Loading leaderboard..."):try:df = _load_leaderboard_df()except Exception as e:st.error(f"Could not load leaderboard: {e}")return# Filter to standard phase only for public leaderboardif not df.empty and "phase_codename" in df.columns:df = df[df["phase_codename"] == "test-standard2024"]if df.empty:st.info("No scored Standard phase submissions yet. Be the first!")returndf_display = df.copy()df_display.insert(0, "Rank", range(1, len(df_display) + 1))if "timestamp" in df_display.columns:df_display["timestamp"] = pd.to_datetime(df_display["timestamp"], unit="s", errors="coerce")# Drop hf_username / hf_email from public viewfor col in ["hf_username", "hf_email", "phase_codename", "submission_id"]:if col in df_display.columns:df_display.drop(columns=[col], inplace=True)st.dataframe(df_display,column_config={"Rank": st.column_config.Column("Rank", width="small"),"team": "Team","model": "Model","bbox_mAP": st.column_config.NumberColumn("bbox_mAP", format="%.4f"),"bbox_AP50": st.column_config.NumberColumn("bbox_AP50", format="%.4f"),"segm_mAP": st.column_config.NumberColumn("segm_mAP", format="%.4f"),"segm_AP50": st.column_config.NumberColumn("segm_AP50", format="%.4f"),"timestamp": st.column_config.DatetimeColumn("Scored at", format="D MMM YYYY, h:mm a"),},use_container_width=True,hide_index=True,)def page_submit():user = render_login_wall()hf_username = user.get("preferred_username", "unknown")hf_email = user.get("email", "")st.header("π Submit Your Predictions")# Show user info + daily cap statuscol_info, col_cap = st.columns([3, 1])with col_info:avatar = user.get("picture", "")name = user.get("name", hf_username)if avatar:st.markdown(f'<img src="{avatar}" width="32" style="border-radius:50%;vertical-align:middle;margin-right:8px">'f'<b>{name}</b> (@{hf_username})',unsafe_allow_html=True,)else:st.markdown(f"π€ Logged in as **{name}** (@{hf_username})")with col_cap:with st.spinner("Checking daily limit..."):subs_today = _count_submissions_today(hf_username)remaining = DAILY_SUBMISSION_CAP - subs_todaycolor = "green" if remaining > 1 else ("orange" if remaining == 1 else "red")st.markdown(f'<div style="text-align:center;padding:8px;border-radius:8px;border:1px solid {color}">'f'<b style="color:{color}">{remaining}/{DAILY_SUBMISSION_CAP}</b><br>'f'<small>submissions left today</small></div>',unsafe_allow_html=True,)st.markdown("---")if remaining <= 0:st.error(f"β You've reached your daily limit of {DAILY_SUBMISSION_CAP} submissions. Come back tomorrow!")returncol1, col2 = st.columns([2, 1])1 unmodified linest.subheader("Submission Info")team = st.text_input("Team / Display Name", value=st.session_state.get("team", ""))model_name = st.text_input("Model Name", value=st.session_state.get("model_name", ""))phase_label = st.selectbox("Phase", [p["label"] for p in PHASES])phase_codename = next(p["codename"] for p in PHASES if p["label"] == phase_label)challenge_type = st.radio("Challenge type", CHALLENGE_TYPES, horizontal=False)st.session_state["team"] = teamst.session_state["model_name"] = model_namest.caption("Submissions are scored automatically. Results appear in My Submissions once processed.")with col1:st.subheader("Upload Submission File")uploaded_file = st.file_uploader("Choose a JSON file", type=["json"])if uploaded_file is None:st.info("Upload a JSON file containing a list of annotations.")returntry:raw = uploaded_file.getvalue().decode("utf-8")pred_obj = json.loads(raw)12 unmodified linesif submit_clicked:if not team.strip():st.error("Please enter a Team / Display Name.")returnif not model_name.strip():st.error("Please enter a Model Name.")return# Re-check cap right before submittingsubs_today_fresh = _count_submissions_today(hf_username)if subs_today_fresh >= DAILY_SUBMISSION_CAP:st.error("β Daily submission limit reached. Try again tomorrow.")returnwith st.spinner("Uploading submission..."):try:submission_id = _create_submission_record(pred=pred_obj,2 unmodified linesphase_codename=phase_codename,challenge_type=challenge_type,original_filename=uploaded_file.name,hf_username=hf_username,hf_email=hf_email,)except Exception as e:st.error(f"Upload failed: {e}")2 unmodified linesst.balloons()st.success("Submission queued successfully!")st.code(f"Submission ID: {submission_id}")st.info("Track your results in **My Submissions** once the evaluator processes your file.")def page_my_submissions():user = render_login_wall()hf_username = user.get("preferred_username", "unknown")st.header("π My Submissions")st.caption(f"Showing all submissions for @{hf_username}")with st.spinner("Loading your submissions..."):submissions = _load_user_submissions(hf_username)if not submissions:st.info("You haven't made any submissions yet. Head to **Submit Model** to get started!")return# Phase filterphases_present = sorted(set(s["phase"] for s in submissions))selected_phase = st.selectbox("Filter by phase", ["All"] + phases_present)filtered = submissions if selected_phase == "All" else [s for s in submissions if s["phase"] == selected_phase]# State badgesstate_colors = {"queued": "π‘","running": "π΅","done": "π’","failed": "π΄","unknown": "βͺ",}df = pd.DataFrame(filtered)if "timestamp" in df.columns:df["submitted_at"] = pd.to_datetime(df["timestamp"], unit="s", errors="coerce")if "state" in df.columns:df["status"] = df["state"].apply(lambda s: f"{state_colors.get(s, 'βͺ')} {s.capitalize()}")display_cols = ["submitted_at", "status", "team", "model", "phase", "challenge_type"]metric_cols = [m for m in LEADERBOARD_METRICS if m in df.columns]display_cols += metric_colsdf_display = df[[c for c in display_cols if c in df.columns]].copy()col_config = {"submitted_at": st.column_config.DatetimeColumn("Submitted At", format="D MMM YYYY, h:mm a"),"status": "Status","team": "Team","model": "Model","phase": "Phase","challenge_type": "Challenge Type",}for m in metric_cols:col_config[m] = st.column_config.NumberColumn(m, format="%.4f")st.dataframe(df_display, column_config=col_config, use_container_width=True, hide_index=True)# Summary statsst.markdown("---")total = len(submissions)done = sum(1 for s in submissions if s["state"] == "done")today_count = sum(1 for s in submissionsif datetime.fromtimestamp(s["timestamp"], tz=timezone.utc).strftime("%Y-%m-%d") == _today_utc_str())c1, c2, c3 = st.columns(3)c1.metric("Total Submissions", total)c2.metric("Scored", done)c3.metric(f"Today ({DAILY_SUBMISSION_CAP} max)", f"{today_count}/{DAILY_SUBMISSION_CAP}")# =========================# MAIN# =========================def main():st.sidebar.title("VizWiz Benchmark π")# Check login state for sidebar displayuser = get_oauth_info()if user:hf_username = user.get("preferred_username", "")avatar = user.get("picture", "")if avatar:st.sidebar.markdown(f'<img src="{avatar}" width="40" style="border-radius:50%"><br>'f'<b>@{hf_username}</b>',unsafe_allow_html=True,)else:st.sidebar.markdown(f"π€ @{hf_username}")st.sidebar.markdown("---")menu = ["Leaderboard", "Submit Model", "My Submissions"]else:st.sidebar.info("Login to submit predictions and view your history.")login_url = os.getenv("SPACE_HOST", "")if login_url:st.sidebar.markdown(f'<a href="https://{login_url}/oauth/login" target="_self">'f'<button style="width:100%;background:#FF6B35;color:white;border:none;'f'padding:10px;border-radius:6px;cursor:pointer;font-size:14px;">π€ Login with HF</button></a>',unsafe_allow_html=True,)menu = ["Leaderboard", "Submit Model", "My Submissions"]choice = st.sidebar.radio("Navigation", menu)st.sidebar.markdown("---")st.sidebar.caption("Submissions are queued to a private DB repo and evaluated automatically.")render_overview()render_eval_details()st.markdown("---")if choice == "Leaderboard":page_leaderboard()elif choice == "Submit Model":page_submit()elif choice == "My Submissions":page_my_submissions()if __name__ == "__main__":
src/main.py+418-153