Michael Rabinovich commited on
Commit ·
47c86cf
1
Parent(s): 0bd3c0a
app: add admin tab for promoting and demoting rows
Browse filesnew admin tab with a login button, a submission dropdown, a
validation_method radio, and mark validated / mark unvalidated buttons.
the controls are gated on membership in the CADGENBENCH_ADMINS set via a
blocks.load handler, mirroring the submit button's login gate; the
promote and demote handlers re-check admin rights server-side and
refresh the dropdown plus both leaderboard tables after a write.
33 unmodified lines343536373839115 unmodified lines155156157158159160217 unmodified lines37837938038138238310 unmodified lines39439539639739839933 unmodified linesbuild_combined_csv,load_leaderboard_split,)from submit import handle_submitlogger = logging.getLogger(__name__)115 unmodified linesreturn gr.Button(interactive=profile is not None)def _format_detail_and_report(df: pd.DataFrame | None, evt: gr.SelectData,) -> tuple[str, str]:217 unmodified lineswith gr.Tab("About"):gr.Markdown(ABOUT_MD)# gradio_leaderboard.Leaderboard handles its own update path# cleanly; bind a Timer to push fresh dataframes every 10 seconds.# Single tick runs `load_leaderboard_split` once and pushes the10 unmodified lines# Gradio's auth-event plumbing.blocks.load(fn=_enable_submit_when_logged_in, outputs=submit_btn)# Mount Gradio under a FastAPI parent so the custom proxy route# above lives at the same origin as the UI. Direct routes on `app`33 unmodified lines34353637383940115 unmodified lines156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269217 unmodified lines48748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054110 unmodified lines55255355455555655755855956056156256356456556656756856957057133 unmodified linesbuild_combined_csv,load_leaderboard_split,)from admin import VALID_METHODS, demote_row, is_admin, promote_rowfrom submit import handle_submitlogger = logging.getLogger(__name__)115 unmodified linesreturn gr.Button(interactive=profile is not None)def _choices_from_split(validated: pd.DataFrame | None,unvalidated: pd.DataFrame | None,) -> list[tuple[str, str]]:"""Build the admin dropdown's ``(label, submission_id)`` choice list.Lists unvalidated rows first (the common promote target), thenvalidated rows. Each label is tagged with its current tier so theadmin can tell which direction a button press moves the row."""choices: list[tuple[str, str]] = []for df, tier in ((unvalidated, "unvalidated"), (validated, "validated")):if df is None or "submission_id" not in df.columns:continuefor sid in df["submission_id"].tolist():if sid:choices.append((f"{sid} ({tier})", str(sid)))return choicesdef _admin_row_choices() -> list[tuple[str, str]]:"""Fresh choice list pulled from the current results split."""return _choices_from_split(*load_leaderboard_split())def _gate_admin_controls(profile: gr.OAuthProfile | None,) -> tuple[gr.Dropdown, gr.Radio, gr.Button, gr.Button, str]:"""Enable the admin controls only for a logged-in user in the admin set.Runs on every page load and re-runs on LoginButton auth events.Logged-out visitors and non-admins see the tab but every controlstays disabled, mirroring the server-side gate in the promote /demote handlers (which raise ``gr.Error`` if invoked without adminrights)."""admin = is_admin(profile)if profile is None:status = "Log in with an admin account to enable the controls below."elif admin:status = f"Signed in as `{profile.username}`. Promotion controls enabled."else:status = (f"Signed in as `{profile.username}`, which is not in the admin ""set. Controls are disabled.")return (gr.Dropdown(interactive=admin),gr.Radio(interactive=admin),gr.Button(interactive=admin),gr.Button(interactive=admin),status,)def _admin_promote(submission_id: str | None,method: str | None,profile: gr.OAuthProfile | None,) -> tuple[gr.Dropdown, pd.DataFrame, pd.DataFrame]:"""Promote the selected row, then refresh the dropdown + both tables.Re-checks :func:`admin.is_admin` server-side so a tampered clientthat re-enables the button still can't write. Surfaces the outcomevia a toast; maps the helper's ``LookupError`` / ``ValueError`` toa clean ``gr.Error``."""if not is_admin(profile):raise gr.Error("You are not in the admin set.")if not submission_id:raise gr.Error("Select a submission first.")if not method:raise gr.Error("Select a validation method first.")try:promote_row(submission_id, method)except (LookupError, ValueError) as e:raise gr.Error(str(e))gr.Info(f"Promoted {submission_id} to validated ({method}).")validated, unvalidated = load_leaderboard_split()return (gr.Dropdown(choices=_choices_from_split(validated, unvalidated)),validated,unvalidated,)def _admin_demote(submission_id: str | None,profile: gr.OAuthProfile | None,) -> tuple[gr.Dropdown, pd.DataFrame, pd.DataFrame]:"""Demote the selected row, then refresh the dropdown + both tables."""if not is_admin(profile):raise gr.Error("You are not in the admin set.")if not submission_id:raise gr.Error("Select a submission first.")try:demote_row(submission_id)except LookupError as e:raise gr.Error(str(e))gr.Info(f"Demoted {submission_id} to unvalidated.")validated, unvalidated = load_leaderboard_split()return (gr.Dropdown(choices=_choices_from_split(validated, unvalidated)),validated,unvalidated,)def _format_detail_and_report(df: pd.DataFrame | None, evt: gr.SelectData,) -> tuple[str, str]:217 unmodified lineswith gr.Tab("About"):gr.Markdown(ABOUT_MD)with gr.Tab("Admin"):# Maintainer-only promotion controls. The tab is visible to# everyone (a hint that the path exists); the controls are# gated to OAuth users in the CADGENBENCH_ADMINS set via the# `blocks.load` handler below + a server-side re-check in the# promote / demote handlers. See decisions/validation-policy.md.gr.Markdown("## Admin\n""Promote a submission into the **Validated** table (recording the ""evidence type) or demote it back to **Unvalidated**. Limited to ""maintainers in the admin set; everyone else sees the tab with the ""controls disabled.")admin_login_btn = gr.LoginButton()admin_status = gr.Markdown("Log in with an admin account to enable the controls below.")admin_submission_dd = gr.Dropdown(choices=_choices_from_split(initial_validated, initial_unvalidated),label="Submission",interactive=False,)admin_method_radio = gr.Radio(choices=list(VALID_METHODS),label="validation_method (required to promote)",interactive=False,)with gr.Row():promote_btn = gr.Button("Mark validated", variant="primary", interactive=False,)demote_btn = gr.Button("Mark unvalidated", interactive=False)admin_refresh_btn = gr.Button("Refresh list", size="sm")promote_btn.click(fn=_admin_promote,inputs=[admin_submission_dd, admin_method_radio],outputs=[admin_submission_dd, validated_view, unvalidated_view],)demote_btn.click(fn=_admin_demote,inputs=[admin_submission_dd],outputs=[admin_submission_dd, validated_view, unvalidated_view],)admin_refresh_btn.click(fn=lambda: gr.Dropdown(choices=_admin_row_choices()),outputs=admin_submission_dd,)# gradio_leaderboard.Leaderboard handles its own update path# cleanly; bind a Timer to push fresh dataframes every 10 seconds.# Single tick runs `load_leaderboard_split` once and pushes the10 unmodified lines# Gradio's auth-event plumbing.blocks.load(fn=_enable_submit_when_logged_in, outputs=submit_btn)# Same per-load OAuth read, gating the Admin tab's controls on# membership in the CADGENBENCH_ADMINS set. Logged-out / non-admin# visitors get the tab with everything disabled.blocks.load(fn=_gate_admin_controls,outputs=[admin_submission_dd,admin_method_radio,promote_btn,demote_btn,admin_status,],)# Mount Gradio under a FastAPI parent so the custom proxy route# above lives at the same origin as the UI. Direct routes on `app`
app.py+172