Spaces:
Running
Running
Download src/display/admin_console.py from vLAR/PhysInOne-Leaderboard: direct link, hf CLI and curl.
- Browser
- Download file 20.9 kB
-
https://huggingface.co/spaces/vLAR/PhysInOne-Leaderboard/resolve/main/src/display/admin_console.py
- Command line
-
hf download hf://spaces/vLAR/PhysInOne-Leaderboard/src/display/admin_console.py
-
curl -L -o admin_console.py https://huggingface.co/spaces/vLAR/PhysInOne-Leaderboard/resolve/main/src/display/admin_console.py
20.9 kB
| """OAuth-injected, read-only administrator views and confirmed drain controls.""" | |
| import json | |
| from datetime import datetime, timezone | |
| import math | |
| import time | |
| from typing import Optional | |
| import gradio as gr | |
| import pandas as pd | |
| from src.submission.hf_identity import account_from_userinfo | |
| from src.submission import admin | |
| from src.submission.graceful_maintenance import maintenance_status, set_maintenance | |
| admin_css = """ | |
| #admin-console { --submission-section-gap: 20px; --submission-control-gap: 14px; } | |
| #admin-console [data-testid="block-info"] { display: block; background: transparent !important; color: #777283 !important; padding: 0 !important; margin: 0 0 6px !important; font-size: 12px !important; font-weight: 500 !important; line-height: 18px !important; } | |
| #admin-console .board-refresh { min-height: 30px !important; background: #fff !important; color: #746b92 !important; border: 1px solid #e9e7f3 !important; box-shadow: none !important; } | |
| #admin-console input, #admin-console textarea { color: #253047 !important; } | |
| #admin-console .admin-pagination { align-items: center; gap: 10px; } | |
| #admin-console .admin-page-controls { flex: 0 0 auto !important; flex-wrap: nowrap !important; width: calc(88px + 64px + 88px + 20px) !important; min-width: calc(88px + 64px + 88px + 20px) !important; max-width: 100%; align-items: center; gap: 10px; } | |
| #admin-console .admin-page-controls > .form { flex: 0 0 64px !important; min-width: 64px !important; } | |
| #admin-console .admin-pagination .block { padding: 0 !important; } | |
| #admin-console .admin-pagination .admin-page-count { flex: 1 1 160px !important; min-width: 160px !important; margin: 0 !important; padding: 0 !important; } | |
| #admin-console .admin-pagination .admin-page-count p { margin: 0 !important; } | |
| #admin-console .admin-pagination button, #admin-console .admin-maintenance-actions button { min-height: 32px !important; padding: 5px 12px !important; border: 1px solid #e9e7f3 !important; border-radius: 7px !important; color: #5149b8 !important; box-shadow: none !important; } | |
| #admin-console .admin-task-filter { align-items: center; justify-content: space-between; margin: 4px 0 12px; padding: 12px 0; border-top: 1px solid #eeecf6; border-bottom: 1px solid #eeecf6; } | |
| #admin-console .admin-maintenance-row { align-items: center; gap: 16px; } | |
| #admin-console .admin-maintenance-actions { align-items: flex-end; justify-content: center; } | |
| #admin-console .admin-maintenance-row p { margin: 3px 0 !important; } | |
| #admin-console .admin-history-filters { display: grid !important; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; align-items: start; } | |
| #admin-console .admin-history-filters > .form { display: contents !important; } | |
| #admin-console .admin-history-filters .block { min-width: 0 !important; width: 100% !important; padding: 0 !important; border: 0 !important; box-shadow: none !important; } | |
| #admin-console .admin-history-filters :is(input, textarea), #admin-console #admin-task-filter input, #admin-console .admin-pagination input { height: 38px !important; min-height: 38px !important; box-sizing: border-box; padding: 8px 11px !important; font-size: 13px !important; resize: none !important; } | |
| #admin-console .admin-history-filters :is(input, textarea), #admin-console .admin-pagination input { border: 1px solid #e0ddf0 !important; border-radius: 7px !important; } | |
| #admin-console .admin-history-filters .wrap-inner, #admin-console #admin-task-filter .wrap-inner { height: 38px !important; min-height: 38px !important; border: 1px solid #e0ddf0 !important; border-radius: 7px !important; } | |
| #admin-console .admin-history-filters .wrap-inner input, #admin-console #admin-task-filter .wrap-inner input { border: 0 !important; box-shadow: none !important; } | |
| #admin-console .admin-history-filters .wrap { border: 0 !important; box-shadow: none !important; } | |
| #admin-console .admin-history-filters .wrap-inner { width: 100% !important; margin: 0 !important; padding: 0 !important; box-shadow: none !important; } | |
| #admin-console #admin-history-status :is(.container, .wrap-inner, .secondary-wrap, input) { border: 0 !important; padding: 0 !important; box-shadow: none !important; } | |
| #admin-console #admin-history-status .wrap { border: 1px solid #e0ddf0 !important; border-radius: 7px !important; padding: 0 !important; } | |
| #admin-console #admin-history-status input { padding: 8px 11px !important; } | |
| #admin-console .admin-empty-state { padding: 12px 0; color: #777283; } | |
| #admin-console .admin-details { margin-top: 12px; } | |
| #admin-console .data-table { width: 100% !important; min-width: 0 !important; } | |
| #admin-console .data-table table { width: max(100%, var(--table-content-width)) !important; min-width: 100% !important; } | |
| #admin-console .data-table :is(thead, tbody) { width: 100% !important; min-width: var(--table-content-width) !important; } | |
| #admin-console .data-table th, #admin-console .data-table td { text-align: left !important; padding-left: 14px !important; padding-right: 14px !important; } | |
| #admin-console .data-table .selected-status { width: fit-content !important; min-height: 0 !important; padding: 4px 9px !important; font-size: 11px !important; } | |
| #admin-console .admin-details { padding: 16px; border: 1px solid #e8e5f2; border-radius: 10px; background: #fff; } | |
| #admin-console .admin-readonly-summary { padding: 0 !important; background: transparent !important; border: 0 !important; } | |
| #admin-console .admin-details > .styler, #admin-console .admin-details .block, #admin-console .admin-details .form { background: #fff !important; } | |
| #admin-console .admin-task-filter > .form { background: transparent !important; padding: 0 !important; } | |
| #admin-console #admin-task-filter { width: 100% !important; } | |
| #admin-console button:focus-visible, #admin-console input:focus-visible { outline: 2px solid #8075ef !important; outline-offset: 2px; } | |
| #admin-console button:not(:disabled):hover { border-color: #b8afea !important; } | |
| #admin-console .leaderboard-toolbar { align-items: center; } | |
| #admin-console .admin-maintenance-actions { gap: 10px; } | |
| @media (max-width: 600px) { | |
| #admin-console .admin-history-filters { grid-template-columns: repeat(2, minmax(0, 1fr)); } | |
| #admin-console .admin-task-filter > .form { flex: 1 1 100% !important; min-width: 0 !important; } | |
| #admin-console .admin-maintenance-actions { align-items: flex-start; } | |
| #admin-console .admin-pagination { flex-wrap: wrap; } | |
| } | |
| .admin-readonly-summary .selected-links { display: none !important; } | |
| """ | |
| STATUS_LABELS = { | |
| "done": "Completed", "completed": "Completed", "done_partial": "Partially Completed", | |
| "failed": "Failed", "cancelled": "Cancelled", "rejected": "Rejected", "timeout": "Timed Out", | |
| "running": "Running", "queued": "Queued", "pending": "Pending", "cancelling": "Cancelling", | |
| "cancel_requested": "Cancellation Requested", "unknown": "Unknown", | |
| } | |
| def _display_frame(frame): | |
| frame = frame.copy() | |
| if "Status" in frame: | |
| frame["Status"] = frame["Status"].map(lambda value: STATUS_LABELS.get(value, value)) | |
| for column in ("Submitted At", "Completed At"): | |
| if column in frame: | |
| def format_time(value): | |
| try: | |
| stamp = datetime.fromisoformat(value.replace("Z", "+00:00")) | |
| stamp = stamp.replace(tzinfo=timezone.utc) if stamp.tzinfo is None else stamp | |
| return stamp.astimezone(timezone.utc).isoformat(sep=" ").removesuffix("+00:00") + " UTC" | |
| except (ValueError, TypeError, AttributeError): | |
| return value | |
| frame[column] = frame[column].map(format_time) | |
| return frame | |
| def authenticated_admin(profile, request): | |
| try: | |
| session = dict(getattr(request, "session", {}) | |
| or getattr(getattr(request, "request", None), "session", {}) or {}) | |
| info = dict(session.get("oauth_info") or {}) | |
| except (TypeError, ValueError): | |
| return None | |
| expiry = info.get("expires_at") | |
| if (isinstance(expiry, bool) or not isinstance(expiry, (int, float)) | |
| or not math.isfinite(expiry) or expiry <= time.time()): | |
| return None | |
| account = account_from_userinfo(info.get("userinfo")) | |
| injected = account_from_userinfo(profile) | |
| if not account or not injected or account.subject != injected.subject or not admin.is_admin(account): | |
| return None | |
| return account | |
| def require_session_admin(profile, request): | |
| account = authenticated_admin(profile, request) | |
| if account is None: | |
| raise gr.Error("A current administrator Hugging Face session is required.") | |
| return account | |
| def _maintenance_readout(include_controls=False): | |
| from src.submission import evaluator_space as lifecycle | |
| runtime = None | |
| if lifecycle.configured(): | |
| import os | |
| try: | |
| runtime = lifecycle._api().get_space_runtime(repo_id=os.environ["EVALUATOR_SPACE_ID"].strip()).stage | |
| except Exception: | |
| runtime = "Unavailable" | |
| state = maintenance_status(runtime) | |
| text = (f"**{state['state']}** 路 Worker: {runtime or 'Unavailable'}\n\n" | |
| f"Current operations: {', '.join(state['operations']) or 'None observed'} 路 Waiting: {state['pending']}\n\n" | |
| f"{state['reason']}") | |
| if include_controls: | |
| enabled = state["enabled"] | |
| return text, state["generation"], gr.update(visible=not enabled), gr.update(visible=enabled) | |
| return text, state["generation"] | |
| def _page_value(value): | |
| if value is None: | |
| return 1 | |
| if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 1 or int(value) != value: | |
| raise ValueError("Page must be a positive integer.") | |
| return int(value) | |
| def render_admin_console(groups, dataframe): | |
| group_map = {group["tab"]: group["tasks"] for group in groups} | |
| all_tasks = [name for group in groups for name in group["tasks"]] | |
| with gr.Accordion("Admin Console", open=False, visible=False, elem_classes="utility-panel submission-panel", elem_id="admin-console") as panel: | |
| with gr.Row(elem_classes="leaderboard-toolbar"): | |
| gr.Markdown("### Maintenance Control") | |
| check = gr.Button("Refresh", size="sm", scale=0, min_width=96, elem_classes="board-refresh") | |
| generation = gr.Textbox(value="", visible=False) | |
| with gr.Row(elem_classes="admin-maintenance-row"): | |
| with gr.Column(scale=3, min_width=240): | |
| state = gr.Markdown("Refresh to verify server-side maintenance state.") | |
| with gr.Column(scale=1, min_width=180, elem_classes="admin-maintenance-actions"): | |
| enable = gr.Button("Enable Maintenance", variant="secondary", size="sm", min_width=180) | |
| disable = gr.Button("Disable Maintenance", variant="secondary", size="sm", min_width=180, visible=False) | |
| with gr.Row(elem_classes="admin-task-filter"): | |
| gr.Markdown("### Task Filter\nApplies to both Queue and History.") | |
| task = gr.Dropdown(["All Tasks", *group_map], value="All Tasks", label="Task", scale=0, min_width=280, elem_id="admin-task-filter") | |
| def section(title, columns, kind): | |
| with gr.Row(elem_classes="leaderboard-toolbar"): | |
| gr.Markdown("### " + title) | |
| refresh = gr.Button("Refresh", size="sm", scale=0, min_width=96, elem_classes="board-refresh") | |
| if kind == "history": | |
| with gr.Row(elem_classes="admin-history-filters"): | |
| user = gr.Textbox(label="HF User", placeholder="All users", scale=1, min_width=150) | |
| status = gr.Dropdown([("All Statuses", ""), *[(STATUS_LABELS[value], value) for value in | |
| ("done", "done_partial", "failed", "cancelled", "rejected", "timeout", "unknown")], ("Completed (Legacy)", "completed")], | |
| value="", label="Status", scale=1, min_width=150, elem_id="admin-history-status") | |
| since = gr.Textbox(label="Submitted from (UTC)", placeholder="YYYY-MM-DD", scale=1, min_width=150) | |
| until = gr.Textbox(label="Submitted through (UTC)", placeholder="YYYY-MM-DD", scale=1, min_width=150) | |
| filters = [user, status, since, until] | |
| status.input(lambda value: gr.update(value=value or ""), inputs=status, outputs=status, queue=False) | |
| else: | |
| filters = [] | |
| empty = gr.Markdown("No submissions to display.", elem_classes="admin-empty-state") | |
| table = dataframe(pd.DataFrame(columns=columns), elem_classes=[kind + "-table", "admin-" + kind + "-table"]) | |
| table.elem_id = "admin-" + kind + "-table" | |
| table.visible = False | |
| with gr.Row(elem_classes="admin-pagination", elem_id="admin-" + kind + "-pagination"): | |
| with gr.Row(visible=False, elem_classes="admin-page-controls") as pager: | |
| previous = gr.Button("Previous", size="sm", scale=0, min_width=88) | |
| page = gr.Number(label="Page", show_label=False, value=1, precision=0, minimum=1, scale=0, min_width=64) | |
| next_page = gr.Button("Next", size="sm", scale=0, min_width=88) | |
| count = gr.Markdown("0 submissions", elem_classes="admin-page-count") | |
| with gr.Group(visible=False, elem_classes=["admin-details", "selected-submission-panel", "submission-card"], elem_id="admin-" + kind + "-details") as details: | |
| gr.Markdown("### Selected Submission") | |
| summary = gr.HTML(elem_classes="admin-readonly-summary") | |
| with gr.Accordion("Advanced 路 Read-only report", open=False): | |
| report = gr.Textbox(show_label=False, lines=6, max_lines=16, interactive=False) | |
| return dict(table=table, empty=empty, page=page, previous=previous, next=next_page, | |
| count=count, refresh=refresh, filters=filters, details=details, summary=summary, report=report, pager=pager) | |
| queue = section("Global Evaluation Queue", admin.QUEUE_COLUMNS, "queue") | |
| history = section("All Submission History", admin.HISTORY_COLUMNS[:7], "history") | |
| def selected_tasks(value): | |
| value = admin._filter_text(value) | |
| if not value or value == "All Tasks": | |
| return all_tasks | |
| if value not in group_map: | |
| raise ValueError("Select a valid task.") | |
| return group_map[value] | |
| def maintenance_updates(): | |
| return _maintenance_readout(include_controls=True) | |
| def inspect(profile: Optional[gr.OAuthProfile], request: gr.Request): | |
| require_session_admin(profile, request) | |
| return maintenance_updates() | |
| maintenance_outputs = [state, generation, enable, disable] | |
| check.click(inspect, outputs=maintenance_outputs, show_progress="hidden") | |
| panel.expand(inspect, outputs=maintenance_outputs, show_progress="hidden") | |
| def action(enabled): | |
| def apply(version, profile: Optional[gr.OAuthProfile], request: gr.Request): | |
| account = require_session_admin(profile, request) | |
| if version == "__cancelled__": | |
| return tuple(gr.update() for _ in maintenance_outputs) | |
| try: | |
| set_maintenance(account, enabled, version) | |
| except (OSError, ValueError): | |
| raise gr.Error("Maintenance state was not changed or could not be confirmed. Refresh and inspect before retrying.") | |
| return maintenance_updates() | |
| return apply | |
| for button, enabled in ((enable, True), (disable, False)): | |
| prompt = "Enable maintenance? Current operations will drain; waiting work will remain queued." if enabled else "Disable maintenance and resume normal scheduling?" | |
| button.click(action(enabled), inputs=generation, outputs=maintenance_outputs, | |
| js=f"version => [window.confirm({json.dumps(prompt)}) ? version : '__cancelled__']", | |
| concurrency_id="admin-maintenance", concurrency_limit=1) | |
| def bind(view, kind): | |
| def load(task, page, user, status, since, until, profile: Optional[gr.OAuthProfile], request: gr.Request): | |
| account = require_session_admin(profile, request) | |
| try: | |
| page = _page_value(page) | |
| names = selected_tasks(task) | |
| frame = (admin.queue_page if kind == "queue" else admin.history_page)( | |
| account, names, page=page, user=user, status=status, since=since, until=until) | |
| total = frame.attrs["total_rows"] | |
| pages = max(1, math.ceil(total / admin.PAGE_SIZE)) | |
| if page > pages: | |
| page = pages | |
| frame = (admin.queue_page if kind == "queue" else admin.history_page)( | |
| account, names, page=page, user=user, status=status, since=since, until=until) | |
| except (OSError, ValueError, TypeError): | |
| raise gr.Error("Could not load submissions. Check filters and page, then refresh.") | |
| frame = _display_frame(frame.reindex(columns=list(view["table"].headers))) | |
| return (gr.update(value=frame, visible=not frame.empty), | |
| gr.update(visible=frame.empty), gr.update(value=page), f"{total} submissions 路 Page {page} / {pages}", | |
| gr.update(interactive=page > 1), gr.update(interactive=page < pages), | |
| gr.update(visible=False), "", "", gr.update(visible=pages > 1)) | |
| outputs = [view[key] for key in ("table", "empty", "page", "count", "previous", "next", "details", "summary", "report", "pager")] | |
| if kind == "queue": | |
| blanks = [gr.State("") for _ in range(4)] | |
| inputs = [task, view["page"], *blanks] | |
| else: | |
| inputs = [task, view["page"], *view["filters"]] | |
| gr.on(triggers=[view["refresh"].click, panel.expand, view["page"].submit], fn=load, inputs=inputs, outputs=outputs, show_progress="minimal") | |
| def reset(task, page, user, status, since, until, profile: Optional[gr.OAuthProfile], request: gr.Request): | |
| return load(task, 1, user, status, since, until, profile, request) | |
| gr.on(triggers=[task.change, *[component.change for component in view["filters"]]], | |
| fn=reset, inputs=inputs, outputs=outputs, show_progress="minimal") | |
| def move(direction): | |
| def navigate(task, page, user, status, since, until, profile: Optional[gr.OAuthProfile], request: gr.Request): | |
| require_session_admin(profile, request) | |
| try: | |
| page = max(1, _page_value(page) + direction) | |
| except ValueError: | |
| raise gr.Error("Page must be a positive integer.") | |
| return load(task, page, user, status, since, until, profile, request) | |
| return navigate | |
| view["previous"].click(move(-1), inputs=inputs, outputs=outputs, show_progress="minimal") | |
| view["next"].click(move(1), inputs=inputs, outputs=outputs, show_progress="minimal") | |
| def select(task, event: gr.SelectData, profile: Optional[gr.OAuthProfile], request: gr.Request): | |
| account = require_session_admin(profile, request) | |
| if not event.row_value: | |
| return gr.update(visible=False), "", "" | |
| try: | |
| submission_id = str(event.row_value[list(view["table"].headers).index("Submission ID")]) | |
| html, text = admin.admin_details(account, submission_id, selected_tasks(task)) | |
| except (OSError, ValueError, TypeError, IndexError): | |
| raise gr.Error("Submission details are unavailable. Refresh and select again.") | |
| return gr.update(visible=True), html, text | |
| view["table"].select(select, inputs=task, outputs=[view["details"], view["summary"], view["report"]], show_progress="hidden") | |
| bind(queue, "queue") | |
| bind(history, "history") | |
| access_outputs = [panel, state, generation, enable, disable] | |
| for view in (queue, history): | |
| access_outputs.extend([view["table"], view["empty"], view["details"], view["summary"], view["report"], view["count"], view["pager"]]) | |
| def access(profile: Optional[gr.OAuthProfile], request: gr.Request): | |
| if authenticated_admin(profile, request) is not None: | |
| return gr.update(visible=True), *[gr.update() for _ in access_outputs[1:]] | |
| cleared = [gr.update(visible=False), "", "", gr.update(visible=False), gr.update(visible=False)] | |
| for view in (queue, history): | |
| cleared.extend([gr.update(value=pd.DataFrame(columns=list(view["table"].headers)), visible=False), | |
| gr.update(visible=True), gr.update(visible=False), "", "", "0 submissions", gr.update(visible=False)]) | |
| return tuple(cleared) | |
| return access, access_outputs | |