Spaces:
Sleeping
Sleeping
| from __future__ import annotations | |
| import html | |
| import inspect | |
| import json | |
| import math | |
| import re | |
| from datetime import datetime | |
| from functools import lru_cache | |
| from pathlib import Path | |
| from typing import Any | |
| import gradio as gr | |
| from packing_benchmark.dates import ( | |
| date_from_friedman_record, | |
| date_from_submission, | |
| display_date_info, | |
| is_recent_date_info, | |
| parse_friedman_date_text, | |
| ) | |
| from packing_benchmark.hub_sync import maybe_hydrate_from_dataset | |
| from packing_benchmark.store import SolutionStore, is_trivial_record | |
| from packing_benchmark.verifier import ( | |
| DEFAULT_TOLERANCE, | |
| load_solution_json, | |
| make_container_shape, | |
| make_item_shape, | |
| normalize_solution, | |
| solution_case, | |
| solution_hash, | |
| verify_solution, | |
| ) | |
| SPACE_ROOT = Path(__file__).resolve().parent | |
| DATA_DIR = SPACE_ROOT / "data" | |
| DATA_DIR.mkdir(parents=True, exist_ok=True) | |
| FAVICON_PATH = SPACE_ROOT / "assets" / "favicon.svg" | |
| HYDRATE_STATUS = maybe_hydrate_from_dataset(DATA_DIR) | |
| STORE = SolutionStore(DATA_DIR) | |
| SUBMISSION_MIN_IMPROVEMENT = 1.0e-4 | |
| SUBMISSION_MAX_NEW_CASE_N = 100 | |
| VERIFIER_REPO_URL = "https://github.com/Nathan-Roll1/packing-verifier" | |
| def cached_reference_records() -> list[dict[str, Any]]: | |
| return STORE.load_reference_records() | |
| def cached_verified_records() -> list[dict[str, Any]]: | |
| return STORE.load_records() | |
| def cached_family_updates() -> dict[str, Any]: | |
| path = DATA_DIR / "friedman_family_updates.json" | |
| if not path.exists(): | |
| return {} | |
| try: | |
| payload = json.loads(path.read_text()) | |
| except Exception: | |
| return {} | |
| families = payload.get("families", {}) | |
| return families if isinstance(families, dict) else {} | |
| def cached_public_records(setup: str = "", show_all: bool = False) -> list[dict[str, Any]]: | |
| return STORE.public_records(setup or None, show_all=show_all) | |
| def clear_page_caches() -> None: | |
| cached_reference_records.cache_clear() | |
| cached_verified_records.cache_clear() | |
| cached_family_updates.cache_clear() | |
| cached_public_records.cache_clear() | |
| setup_choices.cache_clear() | |
| coordinate_records_by_case.cache_clear() | |
| family_page_html.cache_clear() | |
| directory_html.cache_clear() | |
| CSS = """ | |
| :root { | |
| color-scheme: light; | |
| --page: #f3eddf; | |
| --paper: #fffdf7; | |
| --paper-soft: #faf6ec; | |
| --ink: #151515; | |
| --muted: #58544d; | |
| --quiet: #7b766d; | |
| --line: #1b1b1b; | |
| --line-soft: #d4cab8; | |
| --green: #b9e7bd; | |
| --green-strong: #2e7d32; | |
| --link: #174f8a; | |
| --tri: #e69f00; | |
| --cir: #56b4e9; | |
| --squ: #009e73; | |
| --pen: #f0e442; | |
| --hex: #0072b2; | |
| --oct: #d55e00; | |
| --dom: #cc79a7; | |
| --unknown-shape: #999999; | |
| --radius: 6px; | |
| } | |
| html, | |
| body, | |
| gradio-app, | |
| .gradio-container, | |
| .main, | |
| .app { | |
| background: var(--page) !important; | |
| color: var(--ink) !important; | |
| font-family: Helvetica, Arial, sans-serif !important; | |
| } | |
| .gradio-container { | |
| max-width: none !important; | |
| margin: 0 !important; | |
| padding: 0 !important; | |
| font-family: Helvetica, Arial, sans-serif !important; | |
| line-height: 1.45; | |
| } | |
| .gradio-container *, | |
| .gradio-container button, | |
| .gradio-container input, | |
| .gradio-container textarea, | |
| .gradio-container select { | |
| box-sizing: border-box; | |
| font-family: Helvetica, Arial, sans-serif !important; | |
| letter-spacing: 0 !important; | |
| } | |
| .gradio-container a { | |
| color: var(--link) !important; | |
| text-decoration: underline; | |
| text-underline-offset: 2px; | |
| } | |
| .contain { | |
| width: min(1180px, calc(100% - 32px)); | |
| margin: 0 auto; | |
| } | |
| .packing-shell { | |
| min-height: 0; | |
| background: var(--page); | |
| color: var(--ink); | |
| font-family: Helvetica, Arial, sans-serif !important; | |
| padding-bottom: 44px; | |
| } | |
| .packing-shell * { | |
| font-family: Helvetica, Arial, sans-serif !important; | |
| } | |
| #leaderboard-panel, | |
| #submit-entry-panel { | |
| display: none; | |
| } | |
| #leaderboard-panel:target, | |
| #submit-entry-panel:target, | |
| #leaderboard-panel:target #leaderboard-panel, | |
| #submit-entry-panel:target #submit-entry-panel, | |
| html:has(#leaderboard-table:target) #leaderboard-panel, | |
| html:has(.leaderboard-modal:target) #leaderboard-panel { | |
| display: block !important; | |
| } | |
| html:has(#leaderboard-panel:target) #home-panel, | |
| html:has(#submit-entry-panel:target) #home-panel, | |
| html:has(#leaderboard-table:target) #home-panel, | |
| html:has(.leaderboard-modal:target) #home-panel { | |
| display: none !important; | |
| } | |
| html:has(#leaderboard-panel:target) #submit-entry-panel, | |
| html:has(#leaderboard-table:target) #submit-entry-panel, | |
| html:has(.leaderboard-modal:target) #submit-entry-panel, | |
| html:has(#submit-entry-panel:target) #leaderboard-panel { | |
| display: none !important; | |
| } | |
| .hero-stage { | |
| border-bottom: 2px solid var(--line); | |
| padding: 30px 0 20px; | |
| } | |
| .hero-stage h1 { | |
| margin: 0 0 10px; | |
| color: var(--ink); | |
| font-size: 36px; | |
| line-height: 1.05; | |
| font-weight: 700; | |
| } | |
| .hero-copy { | |
| max-width: 820px; | |
| margin: 0; | |
| color: var(--muted); | |
| font-size: 16px; | |
| line-height: 1.55; | |
| } | |
| .gradio-container .tab-nav, | |
| .gradio-container [role="tablist"] { | |
| display: none !important; | |
| } | |
| .site-nav { | |
| position: sticky !important; | |
| top: 0; | |
| z-index: 50; | |
| min-height: 48px; | |
| display: flex; | |
| flex-wrap: wrap; | |
| align-items: center; | |
| gap: 8px; | |
| padding: 7px max(16px, calc((100% - 1180px) / 2)) !important; | |
| background: rgba(243, 237, 223, 0.98) !important; | |
| border-bottom: 1px solid var(--line) !important; | |
| } | |
| .site-nav-link { | |
| display: inline-flex; | |
| align-items: center; | |
| justify-content: center; | |
| min-height: 32px !important; | |
| padding: 5px 11px !important; | |
| background: transparent !important; | |
| border: 1px solid transparent !important; | |
| border-radius: 4px !important; | |
| box-shadow: none !important; | |
| color: var(--ink) !important; | |
| font-size: 14px !important; | |
| font-weight: 700 !important; | |
| line-height: 1.2; | |
| text-decoration: none !important; | |
| } | |
| .site-nav-link:hover, | |
| .site-nav-link.active { | |
| background: var(--paper) !important; | |
| border-color: var(--line) !important; | |
| } | |
| .site-nav-link.submit-link { | |
| margin-left: auto !important; | |
| background: var(--green-strong) !important; | |
| border-color: #1f5d25 !important; | |
| color: #fff !important; | |
| } | |
| .site-nav-link.submit-link:hover, | |
| .site-nav-link.submit-link.active { | |
| background: #236c29 !important; | |
| color: #fff !important; | |
| } | |
| footer, | |
| .gradio-container footer, | |
| .gradio-container .footer, | |
| .gradio-container .built-with, | |
| .gradio-container .api-docs, | |
| .gradio-container .app > header, | |
| .gradio-container .app > .header, | |
| .gradio-container .contain > button:not(.site-nav-link), | |
| .gradio-container a[href*="view=api"], | |
| .gradio-container a[href*="/api"], | |
| .gradio-container button[aria-label="Settings"], | |
| .gradio-container button[title="Settings"], | |
| .gradio-container button[aria-label="More"], | |
| .gradio-container button[aria-label="More options"], | |
| .gradio-container button[title="More"], | |
| .gradio-container button[title="More options"], | |
| .gradio-container [data-testid="settings-button"], | |
| .gradio-container [data-testid="more-button"], | |
| .gradio-container [data-testid="app-menu"], | |
| .gradio-container [data-testid="menu-button"], | |
| .gradio-container [class*="settings"], | |
| .gradio-container [class*="kebab"], | |
| .gradio-container [class*="ellipsis"] { | |
| display: none !important; | |
| } | |
| .section { | |
| padding: 30px 0 8px; | |
| } | |
| .section-head { | |
| display: flex; | |
| justify-content: space-between; | |
| gap: 20px; | |
| align-items: end; | |
| margin-bottom: 16px; | |
| } | |
| .section-head h2, | |
| .family-title-card h2 { | |
| margin: 0 0 4px; | |
| color: var(--ink); | |
| font-size: 24px; | |
| line-height: 1.2; | |
| font-weight: 700; | |
| } | |
| .section-note, | |
| .family-subtitle { | |
| margin: 0; | |
| color: var(--muted); | |
| font-size: 14px; | |
| line-height: 1.45; | |
| } | |
| .family-matrix { | |
| display: grid; | |
| gap: 22px; | |
| } | |
| .family-row { | |
| padding-top: 14px; | |
| border-top: 1px solid var(--line); | |
| } | |
| .family-row:first-child { | |
| padding-top: 0; | |
| border-top: 0; | |
| } | |
| .family-grid { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fill, minmax(178px, 1fr)); | |
| gap: 10px; | |
| } | |
| .family-card { | |
| display: block; | |
| min-height: 218px; | |
| padding: 12px; | |
| color: var(--ink) !important; | |
| text-decoration: none !important; | |
| background: var(--paper); | |
| border: 1px solid var(--line); | |
| border-radius: var(--radius); | |
| } | |
| .family-card:hover, | |
| .family-card:focus-visible { | |
| background: #fffaf0; | |
| outline: 2px solid var(--line); | |
| outline-offset: 2px; | |
| } | |
| .family-card-top { | |
| display: block; | |
| } | |
| .family-render { | |
| height: 150px; | |
| margin: 8px 0 10px; | |
| } | |
| .family-render .packing-svg { | |
| max-width: 160px; | |
| max-height: 160px; | |
| } | |
| .family-code { | |
| margin: 0 0 7px; | |
| color: var(--quiet); | |
| font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important; | |
| font-size: 12px; | |
| text-transform: uppercase; | |
| } | |
| .family-card h3 { | |
| margin: 0; | |
| color: var(--ink); | |
| font-size: 18px; | |
| line-height: 1.22; | |
| font-weight: 700; | |
| } | |
| .front-family-card { | |
| min-height: 232px; | |
| margin-bottom: 8px; | |
| } | |
| .front-family-card .family-render { | |
| height: 154px; | |
| } | |
| .record-book { | |
| padding: 10px 0 0; | |
| } | |
| .family-section { | |
| margin-top: 34px; | |
| padding-top: 22px; | |
| border-top: 2px solid var(--line); | |
| } | |
| .family-title-card { | |
| display: flex; | |
| align-items: end; | |
| justify-content: space-between; | |
| gap: 18px; | |
| margin-bottom: 14px; | |
| } | |
| .record-grid { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fill, minmax(178px, 1fr)); | |
| gap: 12px; | |
| } | |
| .record-card { | |
| overflow: hidden; | |
| background: var(--paper); | |
| border: 1px solid var(--line); | |
| border-radius: var(--radius); | |
| color: var(--ink); | |
| } | |
| .record-card:hover, | |
| .record-card:focus-within { | |
| background: #fffaf0; | |
| outline: 2px solid var(--line); | |
| outline-offset: 2px; | |
| } | |
| .record-open { | |
| display: block; | |
| color: inherit !important; | |
| text-decoration: none !important; | |
| } | |
| .record-top { | |
| padding: 9px 10px 0; | |
| } | |
| .record-case { | |
| color: var(--ink); | |
| font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important; | |
| font-size: 12px; | |
| font-weight: 700; | |
| } | |
| .recent-dot { | |
| display: inline-block; | |
| width: 9px; | |
| height: 9px; | |
| margin-left: 7px; | |
| background: var(--green-strong); | |
| border: 1px solid #174c1b; | |
| border-radius: 999px; | |
| vertical-align: 1px; | |
| } | |
| .family-card h3 .recent-dot { | |
| width: 10px; | |
| height: 10px; | |
| vertical-align: 2px; | |
| } | |
| .render-stage { | |
| height: 178px; | |
| margin: 8px 10px 0; | |
| display: grid; | |
| place-items: center; | |
| background: transparent; | |
| border: 0; | |
| border-radius: 0; | |
| } | |
| .placeholder, | |
| .empty-state { | |
| padding: 0 14px; | |
| color: var(--quiet); | |
| font-size: 12px; | |
| line-height: 1.35; | |
| text-align: center; | |
| } | |
| .packing-svg { | |
| display: block; | |
| width: 100%; | |
| height: 100%; | |
| max-width: 162px; | |
| max-height: 162px; | |
| overflow: visible; | |
| } | |
| .shape-item { | |
| fill: var(--unknown-shape); | |
| stroke: #000; | |
| stroke-width: 1.5px !important; | |
| stroke-linejoin: round; | |
| vector-effect: non-scaling-stroke; | |
| } | |
| .shape-item.inner-tri { fill: var(--tri); } | |
| .shape-item.inner-cir { fill: var(--cir); } | |
| .shape-item.inner-squ { fill: var(--squ); } | |
| .shape-item.inner-pen { fill: var(--pen); } | |
| .shape-item.inner-hex { fill: var(--hex); } | |
| .shape-item.inner-oct { fill: var(--oct); } | |
| .shape-item.inner-dom { fill: var(--dom); } | |
| .shape-container { | |
| fill: none; | |
| stroke: #000; | |
| stroke-width: 2.6px !important; | |
| stroke-linejoin: round; | |
| vector-effect: non-scaling-stroke; | |
| } | |
| .record-body { | |
| padding: 9px 10px 12px; | |
| } | |
| .metric { | |
| display: flex; | |
| align-items: baseline; | |
| justify-content: space-between; | |
| gap: 8px; | |
| color: var(--ink); | |
| } | |
| .metric strong { | |
| color: var(--ink); | |
| font-size: 17px; | |
| line-height: 1.2; | |
| } | |
| .metric span { | |
| color: var(--muted); | |
| font-size: 12px; | |
| white-space: nowrap; | |
| } | |
| .expression { | |
| min-height: 18px; | |
| margin-top: 4px; | |
| color: var(--muted); | |
| font-size: 12px; | |
| line-height: 1.35; | |
| overflow-wrap: anywhere; | |
| } | |
| .meta { | |
| margin-top: 8px; | |
| padding-top: 8px; | |
| border-top: 1px solid var(--line-soft); | |
| color: var(--muted); | |
| font-size: 12px; | |
| line-height: 1.4; | |
| } | |
| .meta strong { | |
| color: var(--ink); | |
| } | |
| .record-author { | |
| margin-top: 8px; | |
| color: var(--muted); | |
| font-size: 12px; | |
| line-height: 1.35; | |
| } | |
| .record-author strong { | |
| color: var(--ink); | |
| } | |
| .trivial-badge { | |
| display: inline-flex; | |
| align-items: center; | |
| min-height: 22px; | |
| padding: 2px 7px; | |
| background: var(--paper-soft); | |
| border: 1px solid var(--line); | |
| border-radius: 4px; | |
| color: var(--ink); | |
| font-size: 11px; | |
| font-weight: 700; | |
| line-height: 1.1; | |
| text-transform: uppercase; | |
| } | |
| .page-card { | |
| background: var(--paper); | |
| border: 1px solid var(--line); | |
| border-radius: var(--radius); | |
| padding: 16px; | |
| } | |
| .record-modal { | |
| display: none; | |
| position: fixed; | |
| inset: 0; | |
| z-index: 1000; | |
| align-items: center; | |
| justify-content: center; | |
| padding: 24px; | |
| } | |
| .record-modal:target { | |
| display: flex; | |
| } | |
| .modal-backdrop { | |
| position: absolute; | |
| inset: 0; | |
| background: rgba(21, 21, 21, 0.42); | |
| } | |
| .modal-panel { | |
| position: relative; | |
| z-index: 1; | |
| width: min(920px, calc(100vw - 32px)); | |
| max-height: calc(100vh - 32px); | |
| overflow: auto; | |
| background: var(--paper) !important; | |
| border: 2px solid var(--line); | |
| border-radius: var(--radius); | |
| color: var(--ink) !important; | |
| box-shadow: 0 16px 40px rgba(0, 0, 0, 0.24); | |
| } | |
| .record-modal, | |
| .record-modal .modal-panel, | |
| .record-modal .modal-panel * { | |
| color: var(--ink) !important; | |
| } | |
| .modal-close { | |
| position: absolute; | |
| top: 12px; | |
| right: 12px; | |
| display: grid; | |
| place-items: center; | |
| width: 32px; | |
| height: 32px; | |
| background: var(--paper) !important; | |
| border: 1px solid var(--line); | |
| border-radius: 4px; | |
| color: var(--ink) !important; | |
| font-size: 18px; | |
| font-weight: 700; | |
| line-height: 1; | |
| text-decoration: none !important; | |
| } | |
| .modal-close:hover, | |
| .modal-close:focus-visible { | |
| background: #fffaf0 !important; | |
| outline: 2px solid var(--line); | |
| outline-offset: 2px; | |
| } | |
| .modal-head { | |
| padding: 18px 58px 12px 18px; | |
| border-bottom: 1px solid var(--line); | |
| } | |
| .modal-case { | |
| margin: 0 0 4px; | |
| color: var(--quiet) !important; | |
| font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important; | |
| font-size: 12px; | |
| font-weight: 700; | |
| text-transform: uppercase; | |
| } | |
| .modal-head h3 { | |
| margin: 0; | |
| color: var(--ink) !important; | |
| font-size: 22px; | |
| line-height: 1.2; | |
| } | |
| .modal-subtitle { | |
| margin-top: 7px; | |
| color: var(--muted) !important; | |
| font-size: 13px; | |
| line-height: 1.45; | |
| } | |
| .modal-layout { | |
| display: grid; | |
| grid-template-columns: minmax(240px, 340px) 1fr; | |
| gap: 18px; | |
| padding: 18px; | |
| } | |
| .modal-visual .render-stage { | |
| height: 320px; | |
| margin: 0; | |
| } | |
| .modal-visual .packing-svg { | |
| max-width: 300px; | |
| max-height: 300px; | |
| } | |
| .download-actions { | |
| display: flex; | |
| justify-content: center; | |
| gap: 8px; | |
| margin-top: 10px; | |
| } | |
| .download-btn { | |
| appearance: none; | |
| min-height: 32px; | |
| padding: 6px 10px; | |
| background: var(--paper-soft) !important; | |
| border: 1px solid var(--line); | |
| border-radius: 4px; | |
| color: var(--ink) !important; | |
| cursor: pointer; | |
| font-size: 12px; | |
| font-weight: 700; | |
| line-height: 1; | |
| } | |
| .download-btn:hover, | |
| .download-btn:focus-visible { | |
| background: #fffaf0 !important; | |
| outline: 2px solid var(--line); | |
| outline-offset: 2px; | |
| } | |
| .modal-metric { | |
| margin-bottom: 14px; | |
| padding: 10px 12px; | |
| background: var(--paper-soft) !important; | |
| border: 1px solid var(--line-soft); | |
| border-radius: var(--radius); | |
| } | |
| .modal-metric strong { | |
| display: block; | |
| color: var(--ink) !important; | |
| font-size: 20px; | |
| line-height: 1.2; | |
| } | |
| .modal-metric span { | |
| display: block; | |
| margin-top: 3px; | |
| color: var(--muted) !important; | |
| font-size: 13px; | |
| } | |
| .modal-details { | |
| margin: 0; | |
| display: grid; | |
| grid-template-columns: 142px minmax(0, 1fr); | |
| gap: 8px 14px; | |
| color: var(--muted) !important; | |
| font-size: 13px; | |
| line-height: 1.42; | |
| } | |
| .modal-details dt { | |
| color: var(--ink) !important; | |
| font-weight: 700; | |
| } | |
| .modal-details dd { | |
| margin: 0; | |
| color: var(--muted) !important; | |
| overflow-wrap: anywhere; | |
| } | |
| .modal-details a { | |
| color: var(--link) !important; | |
| } | |
| .previous-bests-table { | |
| width: 100%; | |
| border-collapse: collapse; | |
| background: var(--paper) !important; | |
| color: var(--ink) !important; | |
| font-size: 12px; | |
| } | |
| .previous-bests-table th, | |
| .previous-bests-table td { | |
| padding: 6px 7px; | |
| border: 1px solid var(--line-soft); | |
| color: var(--ink) !important; | |
| text-align: left; | |
| vertical-align: top; | |
| } | |
| .previous-bests-table th { | |
| background: var(--paper-soft) !important; | |
| font-weight: 700; | |
| } | |
| .date-source { | |
| color: var(--muted) !important; | |
| } | |
| .record-modal .modal-panel .modal-case { | |
| color: var(--quiet) !important; | |
| } | |
| .record-modal .modal-panel .modal-subtitle, | |
| .record-modal .modal-panel .modal-metric span, | |
| .record-modal .modal-panel .modal-details, | |
| .record-modal .modal-panel .modal-details dd { | |
| color: var(--muted) !important; | |
| } | |
| .record-modal .modal-panel .modal-head h3, | |
| .record-modal .modal-panel .modal-metric strong, | |
| .record-modal .modal-panel .modal-details dt, | |
| .record-modal .modal-panel .modal-subtitle strong, | |
| .record-modal .modal-panel .modal-close { | |
| color: var(--ink) !important; | |
| } | |
| .record-modal .modal-panel .modal-details a { | |
| color: var(--link) !important; | |
| } | |
| .leaderboard-table { | |
| width: 100%; | |
| border-collapse: collapse; | |
| background: var(--paper); | |
| border: 1px solid var(--line); | |
| } | |
| .leaderboard-table th, | |
| .leaderboard-table td { | |
| padding: 10px 12px; | |
| border-bottom: 1px solid var(--line-soft); | |
| color: var(--ink); | |
| text-align: left; | |
| vertical-align: top; | |
| } | |
| .leaderboard-table th { | |
| background: var(--paper-soft); | |
| font-size: 12px; | |
| text-transform: uppercase; | |
| } | |
| .leaderboard-table th:not(:nth-child(2)), | |
| .leaderboard-table td:not(:nth-child(2)) { | |
| text-align: center; | |
| } | |
| .leaderboard-table th:nth-child(2), | |
| .leaderboard-table td:nth-child(2) { | |
| text-align: left; | |
| } | |
| .leaderboard-table strong, | |
| .leaderboard-table a { | |
| color: var(--ink) !important; | |
| } | |
| .leaderboard-best { | |
| font-weight: 800; | |
| } | |
| .leaderboard-best strong { | |
| font-weight: 800; | |
| } | |
| .case-links { | |
| max-width: 560px; | |
| color: var(--ink); | |
| font-size: 13px; | |
| line-height: 1.55; | |
| } | |
| .case-links a { | |
| display: inline-block; | |
| margin-right: 6px; | |
| color: var(--link) !important; | |
| } | |
| .leaderboard-author-link, | |
| .leaderboard-author-link strong { | |
| color: var(--ink) !important; | |
| font-weight: 700; | |
| } | |
| .leaderboard-author-link { | |
| text-decoration: underline; | |
| text-underline-offset: 2px; | |
| } | |
| .leaderboard-table .leaderboard-open { | |
| white-space: nowrap; | |
| } | |
| .leaderboard-stat-grid { | |
| display: grid; | |
| grid-template-columns: repeat(4, minmax(0, 1fr)); | |
| gap: 10px; | |
| margin: 0 0 16px; | |
| } | |
| .leaderboard-stat { | |
| padding: 10px 12px; | |
| background: var(--paper-soft); | |
| border: 1px solid var(--line-soft); | |
| border-radius: var(--radius); | |
| } | |
| .leaderboard-stat strong { | |
| display: block; | |
| color: var(--ink) !important; | |
| font-size: 22px; | |
| line-height: 1.15; | |
| } | |
| .leaderboard-stat span { | |
| display: block; | |
| margin-top: 3px; | |
| color: var(--muted) !important; | |
| font-size: 12px; | |
| } | |
| .leaderboard-class-strip { | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 7px; | |
| margin: 0 0 14px; | |
| } | |
| .leaderboard-class-strip span { | |
| display: inline-flex; | |
| align-items: center; | |
| gap: 5px; | |
| padding: 4px 7px; | |
| background: #fff !important; | |
| border: 1px solid var(--line-soft); | |
| border-radius: 4px; | |
| color: var(--muted) !important; | |
| font-size: 12px; | |
| } | |
| .leaderboard-class-strip strong { | |
| color: var(--ink) !important; | |
| } | |
| .leaderboard-full-list { | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 6px; | |
| max-height: 260px; | |
| overflow: auto; | |
| padding: 1px; | |
| } | |
| .leaderboard-full-list a { | |
| display: inline-block; | |
| padding: 4px 7px; | |
| color: var(--ink) !important; | |
| background: #fff !important; | |
| border: 1px solid var(--line-soft); | |
| border-radius: 4px; | |
| font-size: 12px; | |
| line-height: 1.2; | |
| text-decoration: none; | |
| } | |
| .leaderboard-modal .modal-layout { | |
| grid-template-columns: 1fr; | |
| } | |
| .leaderboard-modal .case-links { | |
| max-width: none; | |
| margin-bottom: 14px; | |
| } | |
| .submit-shell, | |
| .schema-shell, | |
| .family-button-shell { | |
| width: min(1180px, calc(100% - 32px)); | |
| margin: 18px auto 44px; | |
| color: var(--ink) !important; | |
| } | |
| .submit-hero { | |
| padding-bottom: 0; | |
| } | |
| .submit-hero .section-head { | |
| align-items: start; | |
| } | |
| .submit-flow { | |
| display: grid; | |
| grid-template-columns: repeat(3, minmax(0, 1fr)); | |
| gap: 10px; | |
| margin-top: 16px; | |
| } | |
| .submission-guide { | |
| margin-top: 18px; | |
| } | |
| .guide-grid { | |
| display: grid; | |
| grid-template-columns: repeat(2, minmax(0, 1fr)); | |
| gap: 12px; | |
| } | |
| .guide-card { | |
| min-width: 0; | |
| padding: 14px; | |
| background: var(--paper); | |
| border: 1px solid var(--line); | |
| border-radius: var(--radius); | |
| } | |
| .guide-card.wide { | |
| grid-column: 1 / -1; | |
| } | |
| .guide-card h3 { | |
| margin: 0 0 8px; | |
| color: var(--ink); | |
| font-size: 16px; | |
| line-height: 1.25; | |
| } | |
| .guide-card p, | |
| .guide-card li { | |
| color: var(--muted) !important; | |
| font-size: 13px; | |
| line-height: 1.45; | |
| } | |
| .guide-card ul { | |
| margin: 8px 0 0; | |
| padding-left: 18px; | |
| } | |
| .code-block { | |
| max-height: 360px; | |
| overflow: auto; | |
| margin: 10px 0 0; | |
| padding: 12px; | |
| background: #fff !important; | |
| color: var(--ink) !important; | |
| border: 1px solid var(--line-soft); | |
| border-radius: var(--radius); | |
| font-size: 12px; | |
| line-height: 1.45; | |
| white-space: pre; | |
| } | |
| .code-block code { | |
| color: var(--ink) !important; | |
| font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important; | |
| } | |
| .submit-step { | |
| min-height: 96px; | |
| padding: 12px; | |
| background: var(--paper-soft); | |
| border: 1px solid var(--line); | |
| border-radius: var(--radius); | |
| } | |
| .submit-step strong { | |
| display: block; | |
| margin-bottom: 4px; | |
| color: var(--ink); | |
| font-size: 14px; | |
| } | |
| .submit-step span { | |
| color: var(--muted) !important; | |
| font-size: 13px; | |
| line-height: 1.4; | |
| } | |
| .submit-shell > .gradio-group, | |
| .schema-shell > .gradio-group, | |
| .family-button-shell > .gradio-group, | |
| .gradio-container .accordion, | |
| .gradio-container .block, | |
| .gradio-container .form, | |
| .gradio-container .panel, | |
| .gradio-container .input-container, | |
| .gradio-container .wrap { | |
| background: var(--paper) !important; | |
| color: var(--ink) !important; | |
| border-color: var(--line-soft) !important; | |
| box-shadow: none !important; | |
| } | |
| .submit-shell > .gradio-group { | |
| padding: 0 !important; | |
| background: transparent !important; | |
| border: 0 !important; | |
| } | |
| .submit-layout { | |
| align-items: stretch !important; | |
| gap: 14px !important; | |
| } | |
| .submit-editor, | |
| .submit-meta, | |
| .submit-results { | |
| min-width: 0; | |
| } | |
| .submit-panel, | |
| .submit-doc-panel, | |
| .submit-results-card { | |
| height: 100%; | |
| padding: 14px !important; | |
| background: var(--paper) !important; | |
| border: 1px solid var(--line) !important; | |
| border-radius: var(--radius) !important; | |
| box-shadow: none !important; | |
| } | |
| .submit-panel-title { | |
| margin: 0 0 10px; | |
| color: var(--ink); | |
| font-size: 16px; | |
| line-height: 1.25; | |
| font-weight: 700; | |
| } | |
| .submit-panel-note { | |
| margin: -4px 0 12px; | |
| color: var(--muted) !important; | |
| font-size: 13px; | |
| line-height: 1.45; | |
| } | |
| .submit-actions { | |
| gap: 8px !important; | |
| } | |
| .submit-actions button { | |
| min-height: 38px !important; | |
| font-weight: 700 !important; | |
| } | |
| .verification-report { | |
| min-height: 152px; | |
| margin-top: 8px; | |
| padding: 12px; | |
| background: var(--paper-soft) !important; | |
| color: var(--ink) !important; | |
| border: 1px solid var(--line-soft) !important; | |
| border-radius: var(--radius); | |
| } | |
| .verification-report, | |
| .verification-report *, | |
| .submit-results-card .verification-report, | |
| .submit-results-card .verification-report * { | |
| color: var(--ink) !important; | |
| } | |
| .verification-report .markdown, | |
| .verification-report .prose, | |
| .verification-report [data-testid="markdown"], | |
| .verification-report [class*="markdown"], | |
| .verification-report [class*="prose"] { | |
| background: transparent !important; | |
| color: var(--ink) !important; | |
| } | |
| .verification-report h1, | |
| .verification-report h2, | |
| .verification-report h3, | |
| .verification-report h4 { | |
| margin-top: 0 !important; | |
| color: var(--ink) !important; | |
| } | |
| .verification-report p, | |
| .verification-report li, | |
| .verification-report ul, | |
| .verification-report ol { | |
| color: var(--ink) !important; | |
| } | |
| .verification-report code { | |
| display: inline-block; | |
| padding: 1px 5px; | |
| background: #fff !important; | |
| color: var(--ink) !important; | |
| border: 1px solid var(--line-soft); | |
| border-radius: 4px; | |
| font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important; | |
| } | |
| .verification-report pre, | |
| .verification-report pre code { | |
| display: block; | |
| background: #fff !important; | |
| color: var(--ink) !important; | |
| border-color: var(--line-soft) !important; | |
| } | |
| .submit-docs { | |
| margin-top: 14px; | |
| } | |
| .submit-docs .accordion, | |
| .submit-docs details { | |
| border: 1px solid var(--line) !important; | |
| border-radius: var(--radius) !important; | |
| background: var(--paper) !important; | |
| } | |
| .submit-docs code, | |
| .submit-docs pre { | |
| background: #fff !important; | |
| border-color: var(--line-soft) !important; | |
| } | |
| .gradio-container label, | |
| .gradio-container .label-wrap, | |
| .gradio-container .markdown, | |
| .gradio-container .prose, | |
| .gradio-container p, | |
| .gradio-container span, | |
| .gradio-container h1, | |
| .gradio-container h2, | |
| .gradio-container h3, | |
| .gradio-container h4, | |
| .gradio-container code, | |
| .gradio-container pre { | |
| color: var(--ink) !important; | |
| } | |
| .gradio-container textarea, | |
| .gradio-container input, | |
| .gradio-container select, | |
| .gradio-container [role="combobox"], | |
| .gradio-container .input-container textarea, | |
| .gradio-container .input-container input { | |
| background: #fff !important; | |
| color: var(--ink) !important; | |
| border-color: var(--line-soft) !important; | |
| } | |
| .gradio-container [role="listbox"], | |
| .gradio-container [role="option"], | |
| .gradio-container .dropdown, | |
| .gradio-container .options, | |
| .gradio-container .item { | |
| background: #fff !important; | |
| color: var(--ink) !important; | |
| } | |
| .gradio-container .code_wrap, | |
| .gradio-container .cm-editor, | |
| .gradio-container .cm-scroller, | |
| .gradio-container .cm-content, | |
| .gradio-container .cm-gutters, | |
| .gradio-container .cm-line, | |
| .gradio-container .cm-activeLine, | |
| .gradio-container .cm-activeLineGutter { | |
| background: #fff !important; | |
| color: var(--ink) !important; | |
| border-color: var(--line-soft) !important; | |
| } | |
| .gradio-container .cm-cursor { | |
| border-left-color: var(--ink) !important; | |
| } | |
| .gradio-container button { | |
| border-radius: 4px !important; | |
| border: 1px solid var(--line) !important; | |
| box-shadow: none !important; | |
| color: var(--ink) !important; | |
| background: #fff !important; | |
| } | |
| .gradio-container button.primary, | |
| .gradio-container button[variant="primary"] { | |
| color: #fff !important; | |
| background: var(--green-strong) !important; | |
| } | |
| .preview-card { | |
| max-width: 420px; | |
| background: var(--paper); | |
| border: 1px solid var(--line); | |
| border-radius: var(--radius); | |
| padding: 10px; | |
| } | |
| .preview-card .render-stage { | |
| height: 340px; | |
| margin: 0; | |
| } | |
| .preview-card .packing-svg { | |
| max-width: 315px; | |
| max-height: 315px; | |
| } | |
| @media (max-width: 720px) { | |
| .contain, | |
| .submit-shell, | |
| .schema-shell, | |
| .family-button-shell { | |
| width: min(100% - 22px, 1180px); | |
| } | |
| .hero-stage { | |
| padding-top: 26px; | |
| } | |
| .hero-stage h1 { | |
| font-size: 30px; | |
| } | |
| .family-title-card, | |
| .section-head { | |
| display: block; | |
| } | |
| .submit-flow { | |
| grid-template-columns: 1fr; | |
| } | |
| .guide-grid { | |
| grid-template-columns: 1fr; | |
| } | |
| .site-nav { | |
| padding: 7px 11px !important; | |
| } | |
| .site-nav-link.submit-link { | |
| margin-left: 0 !important; | |
| } | |
| .record-grid { | |
| grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); | |
| } | |
| .record-modal { | |
| padding: 12px; | |
| } | |
| .modal-head { | |
| padding: 16px 54px 12px 14px; | |
| } | |
| .modal-layout { | |
| display: block; | |
| padding: 14px; | |
| } | |
| .modal-visual { | |
| margin-bottom: 14px; | |
| } | |
| .modal-visual .render-stage { | |
| height: 240px; | |
| } | |
| .modal-visual .packing-svg { | |
| max-width: 220px; | |
| max-height: 220px; | |
| } | |
| .modal-details { | |
| grid-template-columns: 1fr; | |
| gap: 3px; | |
| } | |
| .modal-details dd { | |
| margin-bottom: 8px; | |
| } | |
| .leaderboard-stat-grid { | |
| grid-template-columns: repeat(2, minmax(0, 1fr)); | |
| } | |
| .render-stage { | |
| height: 154px; | |
| } | |
| .packing-svg { | |
| max-width: 140px; | |
| max-height: 140px; | |
| } | |
| } | |
| """ | |
| APP_JS = """ | |
| () => { | |
| const cleanHomeUrl = () => `${window.location.origin}${window.location.pathname}`; | |
| const SVG_DOWNLOAD_STYLE = ` | |
| .shape-item { | |
| fill: #999999; | |
| stroke: #000000; | |
| stroke-width: 1.5px; | |
| stroke-linejoin: round; | |
| vector-effect: non-scaling-stroke; | |
| } | |
| .shape-item.inner-tri { fill: #e69f00; } | |
| .shape-item.inner-cir { fill: #56b4e9; } | |
| .shape-item.inner-squ { fill: #009e73; } | |
| .shape-item.inner-pen { fill: #f0e442; } | |
| .shape-item.inner-hex { fill: #0072b2; } | |
| .shape-item.inner-oct { fill: #d55e00; } | |
| .shape-item.inner-dom { fill: #cc79a7; } | |
| .shape-container { | |
| fill: none; | |
| stroke: #000000; | |
| stroke-width: 2.6px; | |
| stroke-linejoin: round; | |
| vector-effect: non-scaling-stroke; | |
| } | |
| `; | |
| const sanitizedFileName = (name, extension) => { | |
| const base = (name || "packing-record") | |
| .replace(/@/g, "-") | |
| .replace(/[^a-zA-Z0-9._-]+/g, "-") | |
| .replace(/^-+|-+$/g, "") || "packing-record"; | |
| return base.toLowerCase().endsWith(`.${extension}`) ? base : `${base}.${extension}`; | |
| }; | |
| const serializePackingSvg = (svg) => { | |
| const clone = svg.cloneNode(true); | |
| clone.setAttribute("xmlns", "http://www.w3.org/2000/svg"); | |
| clone.setAttribute("width", "900"); | |
| clone.setAttribute("height", "900"); | |
| if (!clone.getAttribute("viewBox")) { | |
| const box = svg.getBBox ? svg.getBBox() : null; | |
| if (box) { | |
| clone.setAttribute("viewBox", `${box.x} ${box.y} ${box.width} ${box.height}`); | |
| } | |
| } | |
| const style = document.createElementNS("http://www.w3.org/2000/svg", "style"); | |
| style.textContent = SVG_DOWNLOAD_STYLE; | |
| clone.insertBefore(style, clone.firstChild); | |
| return `<?xml version="1.0" encoding="UTF-8"?>\n${new XMLSerializer().serializeToString(clone)}`; | |
| }; | |
| const triggerFileDownload = (blob, filename) => { | |
| const url = URL.createObjectURL(blob); | |
| const link = document.createElement("a"); | |
| link.href = url; | |
| link.download = filename; | |
| document.body.appendChild(link); | |
| link.click(); | |
| link.remove(); | |
| window.setTimeout(() => URL.revokeObjectURL(url), 1000); | |
| }; | |
| const downloadSvg = (svg, filenameBase) => { | |
| const source = serializePackingSvg(svg); | |
| triggerFileDownload(new Blob([source], {type: "image/svg+xml;charset=utf-8"}), sanitizedFileName(filenameBase, "svg")); | |
| }; | |
| const downloadPng = (svg, filenameBase) => { | |
| const source = serializePackingSvg(svg); | |
| const svgBlob = new Blob([source], {type: "image/svg+xml;charset=utf-8"}); | |
| const url = URL.createObjectURL(svgBlob); | |
| const image = new Image(); | |
| image.onload = () => { | |
| const size = 900; | |
| const canvas = document.createElement("canvas"); | |
| canvas.width = size; | |
| canvas.height = size; | |
| const context = canvas.getContext("2d"); | |
| context.clearRect(0, 0, size, size); | |
| context.drawImage(image, 0, 0, size, size); | |
| URL.revokeObjectURL(url); | |
| canvas.toBlob((blob) => { | |
| if (blob) { | |
| triggerFileDownload(blob, sanitizedFileName(filenameBase, "png")); | |
| } | |
| }, "image/png"); | |
| }; | |
| image.onerror = () => { | |
| URL.revokeObjectURL(url); | |
| window.alert("Could not prepare this rendering for download."); | |
| }; | |
| image.src = url; | |
| }; | |
| const handleImageDownload = (event) => { | |
| const button = event.target && event.target.closest | |
| ? event.target.closest("[data-download-image]") | |
| : null; | |
| if (!button) { | |
| return; | |
| } | |
| event.preventDefault(); | |
| event.stopPropagation(); | |
| if (event.stopImmediatePropagation) { | |
| event.stopImmediatePropagation(); | |
| } | |
| const scope = button.closest(".modal-panel, .preview-card, .record-card, .family-card, .packing-shell") || document; | |
| const svg = scope.querySelector("svg.packing-svg"); | |
| if (!svg) { | |
| window.alert("No coordinate rendering is available for this record yet."); | |
| return; | |
| } | |
| const format = button.getAttribute("data-download-image"); | |
| const filenameBase = button.getAttribute("data-download-filename") | |
| || svg.getAttribute("aria-label") | |
| || "packing-record"; | |
| if (format === "png") { | |
| downloadPng(svg, filenameBase); | |
| } else { | |
| downloadSvg(svg, filenameBase); | |
| } | |
| }; | |
| const normalizedLabels = (element) => { | |
| if (!element) { | |
| return []; | |
| } | |
| return [ | |
| element.getAttribute("aria-label"), | |
| element.innerText, | |
| element.textContent, | |
| ].map((value) => (value || "").replace(/\\s+/g, " ").trim().toLowerCase()).filter(Boolean); | |
| }; | |
| const isInsideBenchmarkUi = (element) => Boolean( | |
| element.closest(".packing-shell, .site-nav, .submit-shell, .schema-shell, .record-modal, .modal-panel") | |
| ); | |
| const hideGradioChrome = () => { | |
| Array.from(document.querySelectorAll("footer, button, a")).forEach((element) => { | |
| if (isInsideBenchmarkUi(element)) { | |
| return; | |
| } | |
| const labels = normalizedLabels(element).join(" "); | |
| const text = (element.innerText || element.textContent || "").replace(/\\s+/g, "").trim(); | |
| const rect = element.getBoundingClientRect ? element.getBoundingClientRect() : null; | |
| const iconOnlyTopRight = rect | |
| && rect.top >= 0 | |
| && rect.top < 84 | |
| && rect.right > window.innerWidth - 120 | |
| && rect.width <= 84 | |
| && rect.height <= 84 | |
| && Boolean(element.querySelector && element.querySelector("svg")); | |
| const chromeText = /settings|more|menu|useviaapi|builtwithgradio/.test(labels.replace(/\\s+/g, "")) | |
| || /^(\\.\\.\\.|…|⋯|⋮)$/.test(text); | |
| if (chromeText || iconOnlyTopRight || element.tagName.toLowerCase() === "footer") { | |
| element.style.setProperty("display", "none", "important"); | |
| element.setAttribute("aria-hidden", "true"); | |
| } | |
| }); | |
| }; | |
| const panelIds = { | |
| home: "home-panel", | |
| leaderboard: "leaderboard-panel", | |
| submit: "submit-entry-panel", | |
| }; | |
| const panelElements = (id) => Array.from(document.querySelectorAll(`[id="${id}"]`)); | |
| const setPanelVisible = (id, visible) => { | |
| const elements = panelElements(id); | |
| if (!elements.length) { | |
| return; | |
| } | |
| elements.forEach((element) => { | |
| if (visible) { | |
| element.style.setProperty("display", "block", "important"); | |
| } else { | |
| element.style.setProperty("display", "none", "important"); | |
| } | |
| }); | |
| }; | |
| const applyRoute = (route) => { | |
| const selected = route === "leaderboard" || route === "submit" ? route : "home"; | |
| if (document.body) { | |
| document.body.dataset.packingRoute = selected; | |
| } | |
| Object.entries(panelIds).forEach(([name, id]) => setPanelVisible(id, name === selected)); | |
| document.querySelectorAll("[data-route]").forEach((element) => { | |
| element.classList.toggle("active", element.getAttribute("data-route") === selected); | |
| }); | |
| hideGradioChrome(); | |
| }; | |
| const currentRoute = () => { | |
| const hash = (window.location.hash || "").replace(/^#/, ""); | |
| if (hash === "home" || hash === "home-panel") { | |
| return "home"; | |
| } | |
| if (hash === "leaderboard" || hash === "leaderboard-panel") { | |
| return "leaderboard"; | |
| } | |
| if (hash === "submit" || hash === "submit-entry-panel") { | |
| return "submit"; | |
| } | |
| if (hash === "leaderboard-table" || hash.startsWith("leaderboard-author-")) { | |
| return "leaderboard"; | |
| } | |
| const view = new URLSearchParams(window.location.search).get("view"); | |
| if (view === "leaderboard" || view === "submit") { | |
| return view; | |
| } | |
| return (document.body && document.body.dataset.packingRoute) || "home"; | |
| }; | |
| const syncRoute = () => applyRoute(currentRoute()); | |
| const routeFromClick = (event) => { | |
| const control = event.target && event.target.closest | |
| ? event.target.closest("[data-route], .site-nav-link") | |
| : null; | |
| if (!control) { | |
| return; | |
| } | |
| const route = control.getAttribute("data-route"); | |
| if (!route) { | |
| return; | |
| } | |
| if (route === "home") { | |
| event.preventDefault(); | |
| event.stopPropagation(); | |
| if (event.stopImmediatePropagation) { | |
| event.stopImmediatePropagation(); | |
| } | |
| window.location.assign(cleanHomeUrl()); | |
| return; | |
| } | |
| if (route === "leaderboard" || route === "submit") { | |
| event.preventDefault(); | |
| event.stopPropagation(); | |
| if (event.stopImmediatePropagation) { | |
| event.stopImmediatePropagation(); | |
| } | |
| window.history.pushState(null, "", `${cleanHomeUrl()}#${panelIds[route]}`); | |
| applyRoute(route); | |
| window.setTimeout(syncRoute, 40); | |
| } | |
| }; | |
| document.addEventListener("click", handleImageDownload, true); | |
| document.addEventListener("click", routeFromClick, true); | |
| window.addEventListener("popstate", syncRoute); | |
| window.addEventListener("hashchange", syncRoute); | |
| document.addEventListener("DOMContentLoaded", syncRoute); | |
| syncRoute(); | |
| [40, 140, 400, 900, 1800, 3200].forEach((delay) => window.setTimeout(syncRoute, delay)); | |
| new MutationObserver(syncRoute).observe(document.documentElement || document, {childList: true, subtree: true}); | |
| } | |
| """ | |
| APP_HEAD = f""" | |
| <script> | |
| ({APP_JS})(); | |
| </script> | |
| <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%224%22%20fill%3D%22%23fffdf7%22%20stroke%3D%22%23151515%22%20stroke-width%3D%225%22%2F%3E%3Cpath%20d%3D%22M32%2016%2051%2048H13Z%22%20fill%3D%22%23e69f00%22%20stroke%3D%22%23151515%22%20stroke-width%3D%224%22%20stroke-linejoin%3D%22round%22%2F%3E%3C%2Fsvg%3E"> | |
| <link rel="shortcut icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2248%22%20height%3D%2248%22%20rx%3D%224%22%20fill%3D%22%23fffdf7%22%20stroke%3D%22%23151515%22%20stroke-width%3D%225%22%2F%3E%3Cpath%20d%3D%22M32%2016%2051%2048H13Z%22%20fill%3D%22%23e69f00%22%20stroke%3D%22%23151515%22%20stroke-width%3D%224%22%20stroke-linejoin%3D%22round%22%2F%3E%3C%2Fsvg%3E"> | |
| """ | |
| SAMPLE_JSON = """{ | |
| "schema_version": "packing-benchmark/v1", | |
| "case": "triincir@3", | |
| "item": {"type": "regular_polygon", "sides": 3, "side_length": 1}, | |
| "container": {"type": "circle", "radius": 0.9535486885675039}, | |
| "placements": [ | |
| {"x": -0.48390173508543094, "y": -0.09165750515220272, "rotation_radians": 2.1788614979094425}, | |
| {"x": 0.3742168507072296, "y": 0.03886972736029847, "rotation_radians": 2.1788160455636896}, | |
| {"x": -0.23841900077460812, "y": 0.43093650446493803, "rotation_radians": 3.2260428170876376} | |
| ] | |
| }""" | |
| CIRCLE_SQUARE_JSON = """{ | |
| "schema_version": "packing-benchmark/v1", | |
| "case": "cirinsqu@4", | |
| "item": {"type": "circle", "radius": 0.5}, | |
| "container": {"type": "rectangle", "width": 2.0, "height": 2.0}, | |
| "placements": [ | |
| {"x": -0.5, "y": -0.5, "rotation_radians": 0.0}, | |
| {"x": 0.5, "y": -0.5, "rotation_radians": 0.0}, | |
| {"x": -0.5, "y": 0.5, "rotation_radians": 0.0}, | |
| {"x": 0.5, "y": 0.5, "rotation_radians": 0.0} | |
| ] | |
| }""" | |
| RECTANGLE_JSON = """{ | |
| "schema_version": "packing-benchmark/v1", | |
| "case": "rectinrect@2", | |
| "item": {"type": "rectangle", "width": 2.0, "height": 1.0}, | |
| "container": {"type": "rectangle", "width": 2.0, "height": 2.0}, | |
| "placements": [ | |
| {"x": 0.0, "y": -0.5, "rotation_radians": 0.0}, | |
| {"x": 0.0, "y": 0.5, "rotation_radians": 0.0} | |
| ] | |
| }""" | |
| PYTHON_GENERATOR_SNIPPET = """import json | |
| def placement(x, y, rotation=0.0): | |
| return {"x": float(x), "y": float(y), "rotation_radians": float(rotation)} | |
| solution = { | |
| "schema_version": "packing-benchmark/v1", | |
| "case": "cirinsqu@4", | |
| "item": {"type": "circle", "radius": 0.5}, | |
| "container": {"type": "rectangle", "width": 2.0, "height": 2.0}, | |
| "placements": [ | |
| placement(-0.5, -0.5), | |
| placement(0.5, -0.5), | |
| placement(-0.5, 0.5), | |
| placement(0.5, 0.5), | |
| ], | |
| } | |
| print(json.dumps(solution, indent=2))""" | |
| JAVASCRIPT_GENERATOR_SNIPPET = """const placement = (x, y, rotation = 0) => ({ | |
| x, | |
| y, | |
| rotation_radians: rotation, | |
| }); | |
| const solution = { | |
| schema_version: "packing-benchmark/v1", | |
| case: "rectinrect@2", | |
| item: {type: "rectangle", width: 2.0, height: 1.0}, | |
| container: {type: "rectangle", width: 2.0, height: 2.0}, | |
| placements: [ | |
| placement(0, -0.5), | |
| placement(0, 0.5), | |
| ], | |
| }; | |
| console.log(JSON.stringify(solution, null, 2));""" | |
| SCHEMA_TEXT = """Canonical submission JSON: | |
| { | |
| "schema_version": "packing-benchmark/v1", | |
| "case": "triintri@1", | |
| "item": { | |
| "type": "regular_polygon", | |
| "sides": 3, | |
| "side_length": 1 | |
| }, | |
| "container": { | |
| "type": "regular_polygon", | |
| "sides": 3, | |
| "side_length": 1, | |
| "orientation_radians": 0 | |
| }, | |
| "placements": [ | |
| {"x": 0, "y": 0, "rotation_radians": 0} | |
| ] | |
| } | |
| Supported shapes: | |
| - regular_polygon: sides plus side_length or circumradius | |
| - circle: radius or diameter | |
| - rectangle: width and height | |
| If redundant dimensions are included, they must agree. For example, | |
| side_length and circumradius must describe the same regular polygon. | |
| The metric is computed from the geometry that is actually verified. | |
| Coordinate convention: | |
| - origin at the container center | |
| - item placements are item centers | |
| - rotations are radians counterclockwise | |
| - touching is legal; overlap and protrusion are rejected | |
| """ | |
| EXAMPLES_MD = f"""### How Submission Works | |
| Paste one canonical coordinate JSON object, click **Verify**, then click **Submit Entry** if it passes. | |
| The geometry tolerance is fixed by the evaluator and is not user-selectable. For an existing case, a submission must improve the current top metric by at least `0.0001` to be accepted as a new record. Cases with no current record can be submitted through `n = {SUBMISSION_MAX_NEW_CASE_N}`. In these tables, smaller metric values are better. | |
| ### Test Locally With The Open Verifier | |
| The verifier code is public at [{VERIFIER_REPO_URL}]({VERIFIER_REPO_URL}). It is dependency-free Python and exposes the same geometry check used by this Space. | |
| ```bash | |
| python -m pip install git+{VERIFIER_REPO_URL}.git | |
| packing-verifier verify solution.json | |
| packing-verifier verify solution.json --json | |
| ``` | |
| The local verifier checks geometry and reports the leaderboard metric. The Space still applies the live record gate when you submit: existing cases must improve the current top metric by at least `0.0001`. | |
| ### Three Triangles In A Circle Example | |
| This prefilled example is a verified `triincir@3` coordinate layout and a good shape for checking the schema: | |
| ```json | |
| {SAMPLE_JSON} | |
| ``` | |
| ### Submission Checklist | |
| - The `case` suffix must match the number of placements, for example `triincir@3` has three placements. | |
| - Use container-centered coordinates. | |
| - Use radians for `rotation_radians`. | |
| - Click **Verify** before submitting; the preview is rendered from the same canonical JSON that is archived. | |
| - Existing cases must beat the current top metric by at least `0.0001`. | |
| - Cases with no current record can be submitted when `n <= {SUBMISSION_MAX_NEW_CASE_N}`. | |
| """ | |
| SCHEMA_DOCS_MD = """### Canonical Fields | |
| Required top-level fields: | |
| ```json | |
| { | |
| "case": "triintri@1", | |
| "item": {"type": "regular_polygon", "sides": 3, "side_length": 1}, | |
| "container": {"type": "regular_polygon", "sides": 3, "side_length": 1}, | |
| "placements": [{"x": 0, "y": 0, "rotation_radians": 0}] | |
| } | |
| ``` | |
| Supported shape specs: | |
| - `regular_polygon`: `sides` plus `side_length` or `circumradius` | |
| - `circle`: `radius` or `diameter` | |
| - `rectangle`: `width` and `height` | |
| The verifier uses a fixed geometry tolerance. Existing cases must improve the current top metric by at least `0.0001` before they can be submitted as records. Cases with no current record can be submitted through `n = 100`. | |
| """ + f""" | |
| ### Four Circles In A Square | |
| ```json | |
| {CIRCLE_SQUARE_JSON} | |
| ``` | |
| ### Two Rectangles In A Rectangle | |
| ```json | |
| {RECTANGLE_JSON} | |
| ``` | |
| """ | |
| MONTHS = ( | |
| "January", | |
| "February", | |
| "March", | |
| "April", | |
| "May", | |
| "June", | |
| "July", | |
| "August", | |
| "September", | |
| "October", | |
| "November", | |
| "December", | |
| ) | |
| def esc(value: Any) -> str: | |
| return html.escape("" if value is None else str(value), quote=True) | |
| def code_block(code: str, language: str = "json") -> str: | |
| return f'<pre class="code-block"><code data-language="{esc(language)}">{esc(code)}</code></pre>' | |
| def submission_guide_html() -> str: | |
| return f""" | |
| <div class="submission-guide"> | |
| <div class="guide-grid"> | |
| <section class="guide-card wide"> | |
| <h3>Canonical Coordinate JSON</h3> | |
| <p> | |
| A submission is one JSON object. The container is centered at the origin, every placement is an item center, | |
| rotations are counterclockwise radians, and the number after <code>@</code> in <code>case</code> must match | |
| the number of placements. | |
| </p> | |
| <ul> | |
| <li><strong>regular_polygon</strong>: use <code>sides</code> plus <code>side_length</code> or <code>circumradius</code>.</li> | |
| <li><strong>circle</strong>: use <code>radius</code> or <code>diameter</code>.</li> | |
| <li><strong>rectangle</strong>: use <code>width</code> and <code>height</code>. Use this for square containers too.</li> | |
| </ul> | |
| <p> | |
| Redundant dimensions must agree. If both <code>side_length</code> and <code>circumradius</code> are present, | |
| the verifier rejects the JSON unless they describe the same polygon. | |
| </p> | |
| {code_block(SAMPLE_JSON)} | |
| </section> | |
| <section class="guide-card"> | |
| <h3>Example: Four Circles In A Square</h3> | |
| <p>This is a compact sanity check for circle placements and square containers.</p> | |
| {code_block(CIRCLE_SQUARE_JSON)} | |
| </section> | |
| <section class="guide-card"> | |
| <h3>Example: Two Rectangles</h3> | |
| <p>Rectangles use the same center and rotation convention as polygons.</p> | |
| {code_block(RECTANGLE_JSON)} | |
| </section> | |
| <section class="guide-card"> | |
| <h3>Generate JSON With Python</h3> | |
| <p>Use this pattern when exporting coordinates from a solver or notebook.</p> | |
| {code_block(PYTHON_GENERATOR_SNIPPET, "python")} | |
| </section> | |
| <section class="guide-card"> | |
| <h3>Generate JSON With JavaScript</h3> | |
| <p>This produces the same canonical shape from a browser, Node script, or visualization tool.</p> | |
| {code_block(JAVASCRIPT_GENERATOR_SNIPPET, "javascript")} | |
| </section> | |
| </div> | |
| </div> | |
| """ | |
| def setup_title(setup: str) -> str: | |
| for record in cached_reference_records(): | |
| if record.get("setup") == setup and record.get("title"): | |
| return str(record["title"]) | |
| return setup | |
| def setup_updated(setup: str) -> str: | |
| update = cached_family_updates().get(setup) | |
| if isinstance(update, dict): | |
| text = str(update.get("text") or "").strip() | |
| if text: | |
| return text | |
| for record in cached_reference_records(): | |
| if record.get("setup") != setup: | |
| continue | |
| meta = record.get("friedman_reference") | |
| if isinstance(meta, dict) and meta.get("family_updated"): | |
| return str(meta["family_updated"]) | |
| if record.get("friedman_family_updated"): | |
| return str(record["friedman_family_updated"]) | |
| return "" | |
| def setup_update_date_info(setup: str) -> dict[str, Any] | None: | |
| update = cached_family_updates().get(setup) | |
| if isinstance(update, dict): | |
| return update | |
| updated = setup_updated(setup) | |
| return parse_friedman_date_text(updated, "Erich Friedman Packing Center index") if updated else None | |
| def setup_choices() -> list[str]: | |
| choices = { | |
| str(record["setup"]) | |
| for record in cached_reference_records() | |
| if record.get("setup") | |
| } | |
| choices.update( | |
| str(record["setup"]) | |
| for record in cached_verified_records() | |
| if record.get("verified") and record.get("setup") | |
| ) | |
| return sorted(choices, key=lambda setup: (setup_title(setup).lower(), setup.lower())) | |
| def is_analytical(record: dict[str, Any]) -> bool: | |
| text = f"{record.get('reference_text', '')} {record.get('metric_expression', '')}".lower() | |
| expression = str(record.get("metric_expression") or "") | |
| exact_tokens = ("√", "pi", "π", "cos", "sin", "tan", "/", "^") | |
| proof_tokens = ("trivial", "proved", "proven", "optimal") | |
| return any(token in text for token in proof_tokens) or any(token in expression.lower() for token in exact_tokens) | |
| def effective_record_date(record: dict[str, Any]) -> dict[str, Any]: | |
| info = record.get("record_date") | |
| if isinstance(info, dict): | |
| return info | |
| if record.get("record_type") == "reference" or record.get("frontend_seed") or is_trivial_record(record): | |
| return date_from_friedman_record(record) | |
| return date_from_submission(record) | |
| def display_date(record: dict[str, Any]) -> str: | |
| return display_date_info(effective_record_date(record)) | |
| def record_date_with_source(record: dict[str, Any]) -> str: | |
| info = effective_record_date(record) | |
| text = display_date_info(info) | |
| source = str(info.get("source") or "").strip() if isinstance(info, dict) else "" | |
| if source and text != "date not listed": | |
| return f"{esc(text)} <span class=\"date-source\">({esc(source)})</span>" | |
| return esc(text) | |
| def is_recent_record(record: dict[str, Any]) -> bool: | |
| return is_recent_date_info(effective_record_date(record)) | |
| def friedman_reference(record: dict[str, Any]) -> dict[str, Any]: | |
| meta = record.get("friedman_reference") | |
| if isinstance(meta, dict): | |
| return meta | |
| return { | |
| "title": record.get("title") or record.get("friedman_title"), | |
| "metric_symbol": record.get("metric_symbol") or record.get("friedman_metric_symbol"), | |
| "metric_value": record.get("metric_value") or record.get("friedman_metric_value"), | |
| "metric_expression": record.get("metric_expression") or record.get("friedman_metric_expression"), | |
| "credit": record.get("submitted_by") or record.get("friedman_credit"), | |
| "date": record.get("friedman_date"), | |
| "source_page": record.get("source_url") or record.get("friedman_source_url"), | |
| "source_image": record.get("source_image") or record.get("friedman_source_image"), | |
| "source_image_url": record.get("external_image_url") or record.get("friedman_external_image_url"), | |
| "reference_text": record.get("reference_text") or record.get("friedman_reference_text"), | |
| "analytical_or_proved": is_analytical(record), | |
| } | |
| def reference_date(record: dict[str, Any]) -> str: | |
| meta = friedman_reference(record) | |
| date = str(meta.get("date") or "").strip() | |
| if date: | |
| return date | |
| return display_date({"reference_text": meta.get("reference_text", "")}) | |
| def reference_credit(record: dict[str, Any]) -> str: | |
| meta = friedman_reference(record) | |
| return str(meta.get("credit") or "unknown").strip() or "unknown" | |
| def source_image_name(record: dict[str, Any]) -> str: | |
| meta = friedman_reference(record) | |
| return str(meta.get("source_image") or "").strip() | |
| def author_name(record: dict[str, Any]) -> str: | |
| return str(record.get("submitted_by") or "unknown").strip() or "unknown" | |
| def display_author(record: dict[str, Any]) -> str: | |
| try: | |
| if int(record.get("n") or 0) == 1: | |
| return "Trivial" | |
| except (TypeError, ValueError): | |
| pass | |
| if record.get("record_type") == "reference": | |
| return reference_credit(record) | |
| author = author_name(record) | |
| if record.get("frontend_seed"): | |
| prior = reference_credit(record) | |
| if prior not in {"unknown", "Erich Friedman Packing Center"}: | |
| return prior | |
| return author | |
| def author_credit_html(author: str) -> str: | |
| if author.strip().lower() == "trivial": | |
| return '<span class="trivial-badge">Trivial</span>' | |
| return f"by <strong>{esc(author)}</strong>" | |
| def existing_author_choices() -> list[str]: | |
| seen: dict[str, str] = {} | |
| for record in [*cached_reference_records(), *cached_verified_records()]: | |
| name = display_author(record) | |
| normalized = name.strip() | |
| if not normalized or normalized.lower() in {"unknown", "anonymous"}: | |
| continue | |
| seen.setdefault(normalized.casefold(), normalized) | |
| return sorted(seen.values(), key=lambda value: value.casefold()) | |
| def metric_symbol(record: dict[str, Any]) -> str: | |
| return str(record.get("metric_symbol") or "s") | |
| def metric_value(record: dict[str, Any]) -> str: | |
| value = record.get("metric_value") | |
| if value is None: | |
| value = record.get("side") | |
| if value is None: | |
| return "not reported" | |
| try: | |
| return f"{float(value):.5f}" | |
| except (TypeError, ValueError): | |
| return str(value) | |
| def numeric_metric(record: dict[str, Any]) -> float | None: | |
| value = record.get("metric_value") | |
| if value is None: | |
| value = record.get("side") | |
| try: | |
| parsed = float(value) | |
| except (TypeError, ValueError): | |
| return None | |
| return parsed if math.isfinite(parsed) else None | |
| def compact_expression(record: dict[str, Any]) -> str: | |
| expression = str(record.get("metric_expression") or "").strip() | |
| if record.get("metric_value_source") == "exact_expression" and "=" in expression: | |
| value = numeric_metric(record) | |
| if value is not None: | |
| expression = f"{expression.split('=', 1)[0].strip()} = {value:.5f}" | |
| expression = re.sub(r"\s+", " ", expression) | |
| if len(expression) > 92: | |
| expression = expression[:89].rstrip() + "..." | |
| return expression | |
| def shape_points(shape: dict[str, Any]) -> list[tuple[float, float]]: | |
| if shape["kind"] == "circle": | |
| cx, cy = shape["center"] | |
| r = shape["radius"] | |
| return [(cx - r, cy - r), (cx + r, cy + r)] | |
| return list(shape["vertices"]) | |
| def inline_solution_svg(solution: dict[str, Any]) -> str: | |
| solution = normalize_solution(solution) | |
| container = make_container_shape(solution["container"]) | |
| shapes = [make_item_shape(solution["item"], placement) for placement in solution["placements"]] | |
| points = shape_points(container) | |
| for shape in shapes: | |
| points.extend(shape_points(shape)) | |
| xs = [x for x, _ in points] | |
| ys = [y for _, y in points] | |
| minx, maxx = min(xs), max(xs) | |
| miny, maxy = min(ys), max(ys) | |
| span = max(maxx - minx, maxy - miny, 1.0e-9) | |
| pad = span * 0.075 | |
| view = f"{minx - pad:.12g} {-maxy - pad:.12g} {maxx - minx + 2 * pad:.12g} {maxy - miny + 2 * pad:.12g}" | |
| item_stroke = max(span / 360.0, 0.004) | |
| container_stroke = item_stroke * 2.2 | |
| item_class = item_class_from_spec(solution["item"]) | |
| def pts(poly: list[tuple[float, float]]) -> str: | |
| return " ".join(f"{x:.12g},{-y:.12g}" for x, y in poly) | |
| body = [ | |
| f'<svg class="packing-svg" viewBox="{view}" preserveAspectRatio="xMidYMid meet" role="img" aria-label="{esc(solution_case(solution))}">', | |
| f" <title>{esc(solution_case(solution))}</title>", | |
| " <g>", | |
| ] | |
| for shape in shapes: | |
| if shape["kind"] == "circle": | |
| cx, cy = shape["center"] | |
| body.append( | |
| f' <circle class="shape-item {item_class}" cx="{cx:.12g}" cy="{-cy:.12g}" r="{shape["radius"]:.12g}" stroke-width="{item_stroke:.12g}"/>' | |
| ) | |
| else: | |
| body.append(f' <polygon class="shape-item {item_class}" points="{pts(shape["vertices"])}" stroke-width="{item_stroke:.12g}"/>') | |
| if container["kind"] == "circle": | |
| cx, cy = container["center"] | |
| body.append( | |
| f' <circle class="shape-container" cx="{cx:.12g}" cy="{-cy:.12g}" r="{container["radius"]:.12g}" stroke-width="{container_stroke:.12g}"/>' | |
| ) | |
| else: | |
| body.append(f' <polygon class="shape-container" points="{pts(container["vertices"])}" stroke-width="{container_stroke:.12g}"/>') | |
| body.extend([" </g>", "</svg>"]) | |
| return "\n".join(body) | |
| def source_link(record: dict[str, Any]) -> str: | |
| meta = friedman_reference(record) | |
| url = str(meta.get("source_page") or record.get("source_url") or "").strip() | |
| if not url: | |
| return "" | |
| return f'<a href="{esc(url)}" target="_blank" rel="noopener noreferrer">page</a>' | |
| def coordinate_records_by_case() -> dict[str, dict[str, Any]]: | |
| best: dict[str, dict[str, Any]] = {} | |
| for record in cached_verified_records(): | |
| if not record.get("verified") or not record.get("solution_path"): | |
| continue | |
| case = str(record.get("case") or "") | |
| if not case: | |
| continue | |
| value = record.get("metric_value") | |
| if value is None: | |
| value = record.get("side") | |
| try: | |
| metric = float(value) | |
| except (TypeError, ValueError): | |
| metric = float("inf") | |
| current = best.get(case) | |
| current_value = current.get("metric_value") if current else None | |
| if current_value is None and current: | |
| current_value = current.get("side") | |
| try: | |
| current_metric = float(current_value) if current_value is not None else float("inf") | |
| except (TypeError, ValueError): | |
| current_metric = float("inf") | |
| if current is None or metric < current_metric: | |
| best[case] = record | |
| return best | |
| def visual_record_for(record: dict[str, Any], coordinates: dict[str, dict[str, Any]]) -> dict[str, Any]: | |
| visual_record = record | |
| if record.get("record_type") != "verified": | |
| visual_record = coordinates.get(str(record.get("case") or ""), record) | |
| return visual_record | |
| def record_visual(record: dict[str, Any], coordinates: dict[str, dict[str, Any]]) -> str: | |
| visual_record = visual_record_for(record, coordinates) | |
| if visual_record.get("record_type") == "verified" or visual_record.get("verified"): | |
| try: | |
| solution = STORE.solution_for_record(visual_record) | |
| return f'<div class="render-stage verified-stage">{inline_solution_svg(solution)}</div>' | |
| except Exception as exc: | |
| return f'<div class="render-stage verified-stage"><div class="empty-state">render unavailable: {esc(exc)}</div></div>' | |
| return '<div class="render-stage"><div class="placeholder">coordinate JSON not available yet</div></div>' | |
| def download_actions(filename: str) -> str: | |
| safe = esc(filename or "packing-record") | |
| return f""" | |
| <div class="download-actions" aria-label="Download rendering"> | |
| <button class="download-btn" type="button" data-download-image="svg" data-download-filename="{safe}">Download SVG</button> | |
| <button class="download-btn" type="button" data-download-image="png" data-download-filename="{safe}">Download PNG</button> | |
| </div> | |
| """ | |
| def detail_row(label: str, value: str) -> str: | |
| value = value.strip() | |
| if not value: | |
| return "" | |
| return f"<dt>{esc(label)}</dt><dd>{value}</dd>" | |
| def metric_text_from_values(symbol: Any, value: Any) -> str: | |
| try: | |
| return f"{esc(symbol or 's')} = {float(value):.5f}" | |
| except (TypeError, ValueError): | |
| return f"{esc(symbol or 's')} = {esc(value)}" | |
| def previous_bests_table(record: dict[str, Any]) -> str: | |
| previous = record.get("previous_bests") | |
| if not isinstance(previous, list) or not previous: | |
| return "" | |
| rows = [] | |
| for item in previous: | |
| if not isinstance(item, dict): | |
| continue | |
| date_info = item.get("date") | |
| date_text = display_date_info(date_info if isinstance(date_info, dict) else None) | |
| source_url = str(item.get("source_url") or "").strip() | |
| source = str(item.get("source") or "previous record").strip() | |
| source_cell = f'<a href="{esc(source_url)}" target="_blank" rel="noopener noreferrer">{esc(source)}</a>' if source_url else esc(source) | |
| rows.append( | |
| "<tr>" | |
| f"<td>{esc(item.get('author') or 'unknown')}</td>" | |
| f"<td>{esc(date_text)}</td>" | |
| f"<td>{metric_text_from_values(item.get('metric_symbol') or metric_symbol(record), item.get('metric_value'))}</td>" | |
| f"<td>{source_cell}</td>" | |
| "</tr>" | |
| ) | |
| if not rows: | |
| return "" | |
| return ( | |
| '<table class="previous-bests-table">' | |
| "<thead><tr><th>Author</th><th>Date</th><th>Metric</th><th>Source</th></tr></thead>" | |
| f"<tbody>{''.join(rows)}</tbody></table>" | |
| ) | |
| def visual_provenance(record: dict[str, Any], visual_record: dict[str, Any]) -> str: | |
| source_case = str(visual_record.get("monotone_upper_bound_from_case") or "").strip() | |
| if source_case: | |
| visual_metric = metric_value(visual_record) | |
| shown_metric = metric_value(record) | |
| suffix = "" | |
| if visual_metric != shown_metric: | |
| suffix = f" Coordinate JSON evaluator metric: {esc(metric_symbol(visual_record))} = {esc(visual_metric)}; Friedman reported metric: {esc(metric_symbol(record))} = {esc(shown_metric)}." | |
| return ( | |
| f"Verified monotone upper-bound layout derived by deleting items from {esc(source_case)}; " | |
| "the Friedman-listed finder remains credited for this row." | |
| ) + suffix | |
| if visual_record.get("frontend_seed"): | |
| visual_metric = metric_value(visual_record) | |
| shown_metric = metric_value(record) | |
| notes = str(visual_record.get("notes") or "").lower() | |
| suffix = "" | |
| if visual_metric != shown_metric: | |
| suffix = f" Coordinate JSON evaluator metric: {esc(metric_symbol(visual_record))} = {esc(visual_metric)}; Friedman reported metric: {esc(metric_symbol(record))} = {esc(shown_metric)}." | |
| if "image-seeded" in notes or "image seeded" in notes: | |
| return "Image-seeded from the Friedman source image and verified for rendering." + suffix | |
| if visual_record is record or visual_record.get("id") == record.get("id"): | |
| return "Verified coordinate layout credited under the public attribution policy." + suffix | |
| return "Verified coordinate rendering for the listed reference." + suffix | |
| if visual_record is record or visual_record.get("id") == record.get("id"): | |
| if visual_record.get("frontend_seed"): | |
| return "Generated verified coordinate layout; no Friedman coordinate record was listed for this case." | |
| return "Submitted coordinate JSON." | |
| return "Coordinate rendering attached to this case." | |
| def display_metric_record(record: dict[str, Any], visual_record: dict[str, Any]) -> dict[str, Any]: | |
| return record | |
| def record_detail_rows(record: dict[str, Any], visual_record: dict[str, Any], source: str, image_name: str, expression: str, analytical: Any) -> list[str]: | |
| rows: list[str] = [] | |
| rows.append(detail_row("Rendering", esc(visual_provenance(record, visual_record)))) | |
| rows.append(detail_row("Record date", record_date_with_source(record))) | |
| if record.get("record_type") == "reference" and visual_record.get("verified"): | |
| if is_trivial_record(record): | |
| rows.append( | |
| detail_row( | |
| "Coordinate JSON", | |
| "used only for rendering; the exact trivial value is shown as the record", | |
| ) | |
| ) | |
| else: | |
| rows.append( | |
| detail_row( | |
| "Coordinate JSON", | |
| f"{esc(metric_symbol(visual_record))} = {esc(metric_value(visual_record))} from the stored evaluator", | |
| ) | |
| ) | |
| rows.append( | |
| detail_row( | |
| "Friedman reference", | |
| f"{esc(metric_symbol(record))} = {esc(metric_value(record))} by {esc(reference_credit(record))}, {esc(reference_date(record))}", | |
| ) | |
| ) | |
| if record.get("record_type") == "verified": | |
| database_inserted_at = str(record.get("database_inserted_at") or record.get("submitted_at") or "").strip() | |
| database_info = date_from_submission({"submitted_at": database_inserted_at}) | |
| rows.append(detail_row("Database entry", esc(display_date_info(database_info)))) | |
| notes = str(record.get("notes") or "").strip() | |
| if notes: | |
| rows.append(detail_row("Notes", esc(notes))) | |
| rows.append(detail_row("Previous bests", previous_bests_table(record))) | |
| rows.append(detail_row("Formula", esc(expression))) | |
| if image_name: | |
| rows.append(detail_row("Source image", esc(image_name))) | |
| if source: | |
| rows.append(detail_row("Source", source)) | |
| if analytical: | |
| rows.append(detail_row("Status", "analytical/proved")) | |
| reference_text = str(friedman_reference(record).get("reference_text") or "").strip() | |
| rows.append(detail_row("Reference text", esc(reference_text))) | |
| return rows | |
| def record_modal( | |
| record: dict[str, Any], | |
| visual_record: dict[str, Any], | |
| display_record: dict[str, Any], | |
| coordinates: dict[str, dict[str, Any]], | |
| source: str, | |
| image_name: str, | |
| expression: str, | |
| analytical: Any, | |
| anchor: str, | |
| modal_id: str, | |
| visible_author: str, | |
| ) -> str: | |
| rows = record_detail_rows(record, visual_record, source, image_name, expression, analytical) | |
| visual_controls = download_actions(str(record.get("case") or modal_id)) if visual_record.get("verified") or visual_record.get("record_type") == "verified" else "" | |
| return f""" | |
| <section class="record-modal" id="{esc(modal_id)}" aria-label="{esc(record.get("case"))} record information"> | |
| <a class="modal-backdrop" href="#{esc(anchor)}" aria-label="Close record information"></a> | |
| <div class="modal-panel" role="dialog" aria-modal="true" aria-labelledby="{esc(modal_id)}-title"> | |
| <a class="modal-close" href="#{esc(anchor)}" aria-label="Close record information">x</a> | |
| <div class="modal-head"> | |
| <div class="modal-case">{esc(record.get("case"))}</div> | |
| <h3 id="{esc(modal_id)}-title">{esc(setup_title(str(record.get("setup") or "")))}</h3> | |
| <div class="modal-subtitle">n={esc(record.get("n"))} {author_credit_html(visible_author)}</div> | |
| </div> | |
| <div class="modal-layout"> | |
| <div class="modal-visual"> | |
| {record_visual(record, coordinates)} | |
| {visual_controls} | |
| </div> | |
| <div> | |
| <div class="modal-metric"> | |
| <strong>{esc(metric_symbol(display_record))} = {esc(metric_value(display_record))}</strong> | |
| <span>{esc(expression)}</span> | |
| </div> | |
| <dl class="modal-details">{''.join(rows)}</dl> | |
| </div> | |
| </div> | |
| </div> | |
| </section> | |
| """ | |
| def record_card(record: dict[str, Any], coordinates: dict[str, dict[str, Any]]) -> str: | |
| verified = record.get("record_type") == "verified" | |
| visual_record = visual_record_for(record, coordinates) | |
| display_record = display_metric_record(record, visual_record) | |
| source = source_link(record) | |
| expression = compact_expression(record) | |
| image_name = source_image_name(record) | |
| analytical = friedman_reference(record).get("analytical_or_proved") | |
| visible_author = display_author(record) | |
| card_class = "verified" if verified else "reference" | |
| if is_recent_record(record): | |
| card_class += " recent-record" | |
| recent = '<span class="recent-dot" title="New in the last 7 days"></span>' if is_recent_record(record) else "" | |
| anchor = f"{record.get('setup')}-{record.get('n')}" | |
| modal_id = f"modal-{anchor}" | |
| return f""" | |
| <article class="record-card {card_class}" id="{esc(anchor)}"> | |
| <a class="record-open" href="#{esc(modal_id)}" aria-label="Open {esc(record.get("case"))} record information"> | |
| <div class="record-top"> | |
| <div class="record-case">{esc(record.get("case"))}{recent}</div> | |
| </div> | |
| {record_visual(record, coordinates)} | |
| <div class="record-body"> | |
| <div class="metric"><strong>{esc(metric_symbol(display_record))} = {esc(metric_value(display_record))}</strong><span>n={esc(record.get("n"))}</span></div> | |
| <div class="expression">{esc(expression)}</div> | |
| <div class="record-author">{author_credit_html(visible_author)}</div> | |
| </div> | |
| </a> | |
| </article> | |
| {record_modal(record, visual_record, display_record, coordinates, source, image_name, expression, analytical, anchor, modal_id, visible_author)} | |
| """ | |
| def setup_summary(setup: str) -> dict[str, Any]: | |
| records = cached_public_records(setup, False) | |
| coordinate_count = sum( | |
| 1 | |
| for record in cached_verified_records() | |
| if record.get("verified") and record.get("solution_path") and record.get("setup") == setup | |
| ) | |
| n_values = [int(r.get("n", 0)) for r in records if r.get("n") is not None] | |
| return { | |
| "setup": setup, | |
| "title": setup_title(setup), | |
| "records": records, | |
| "count": len(records), | |
| "verified": sum(1 for r in records if r.get("record_type") == "verified"), | |
| "coordinate_count": coordinate_count, | |
| "analytic": sum(1 for r in records if is_analytical(r)), | |
| "updated": setup_updated(setup), | |
| "updated_recent": is_recent_date_info(setup_update_date_info(setup)), | |
| "n_range": f"{min(n_values)}-{max(n_values)}" if n_values else "not listed", | |
| } | |
| def shape_phrase(code: str, plural: bool = False) -> str: | |
| names = { | |
| "cir": ("circle", "circles"), | |
| "dom": ("domino", "dominoes"), | |
| "tri": ("triangle", "triangles"), | |
| "squ": ("square", "squares"), | |
| "pen": ("regular pentagon", "regular pentagons"), | |
| "hex": ("regular hexagon", "regular hexagons"), | |
| "oct": ("regular octagon", "regular octagons"), | |
| "rect": ("rectangle", "rectangles"), | |
| } | |
| singular, many = names.get(code, (code, code + "s")) | |
| return many if plural else singular | |
| def parse_setup_codes(setup: str) -> tuple[str, str]: | |
| if "in" not in setup: | |
| return setup, "" | |
| return tuple(setup.split("in", 1)) # type: ignore[return-value] | |
| def inner_class(setup: str) -> str: | |
| item_code, _ = parse_setup_codes(setup) | |
| return f"inner-{re.sub(r'[^A-Za-z0-9_-]', '', item_code).lower()}" | |
| def item_class_from_spec(spec: dict[str, Any]) -> str: | |
| kind = str(spec.get("type") or "").strip().lower() | |
| if kind == "regular_polygon": | |
| sides = int(spec.get("sides", 0) or 0) | |
| code = {3: "tri", 4: "squ", 5: "pen", 6: "hex", 8: "oct"}.get(sides, "unknown") | |
| elif kind == "circle": | |
| code = "cir" | |
| elif kind == "rectangle": | |
| width = float(spec.get("width", 0) or 0) | |
| height = float(spec.get("height", 0) or 0) | |
| code = "dom" if width > 0 and height > 0 and abs(max(width, height) / min(width, height) - 2.0) < 1.0e-6 else "squ" | |
| else: | |
| code = "unknown" | |
| return f"inner-{code}" | |
| def family_description(summary: dict[str, Any]) -> str: | |
| item_code, container_code = parse_setup_codes(str(summary["setup"])) | |
| item = shape_phrase(item_code, plural=True) | |
| container = shape_phrase(container_code) | |
| updated = f" Friedman lists this family as updated {esc(summary['updated'])}." if summary.get("updated") else "" | |
| return ( | |
| f"This page tracks the smallest known container metric for packing n equal {esc(item)} " | |
| f"inside a {esc(container)}. The number shown on each card is the verified coordinate metric " | |
| f"for current coordinate records, or the listed reference metric when that is the better value. " | |
| f"Click a card to view the coordinate JSON metric, source information, and previous bests.{updated}" | |
| ) | |
| def family_preview(setup: str, coordinates: dict[str, dict[str, Any]]) -> str: | |
| record = coordinates.get(f"{setup}@10") | |
| if record is None: | |
| records = [ | |
| candidate | |
| for case, candidate in coordinates.items() | |
| if case.startswith(f"{setup}@") | |
| ] | |
| records.sort(key=lambda candidate: abs(int(candidate.get("n", 0)) - 10)) | |
| record = records[0] if records else None | |
| if record is None: | |
| return '<div class="render-stage family-render"><div class="placeholder">coordinate JSON not available yet</div></div>' | |
| try: | |
| return f'<div class="render-stage family-render">{inline_solution_svg(STORE.solution_for_record(record))}</div>' | |
| except Exception as exc: | |
| return f'<div class="render-stage family-render"><div class="empty-state">render unavailable: {esc(exc)}</div></div>' | |
| def family_card(summary: dict[str, Any], coordinates: dict[str, dict[str, Any]]) -> str: | |
| setup = str(summary["setup"]) | |
| cls = inner_class(setup) | |
| recent = '<span class="recent-dot" title="Updated in the last 7 days"></span>' if summary.get("updated_recent") else "" | |
| return f""" | |
| <a class="family-card front-family-card {esc(cls)}" href="?family={esc(setup)}" aria-label="Open {esc(summary["title"])} records"> | |
| {family_preview(setup, coordinates)} | |
| <div class="family-card-top"> | |
| <div> | |
| <div class="family-code">{esc(setup)}</div> | |
| <h3>{esc(summary["title"])}{recent}</h3> | |
| </div> | |
| </div> | |
| </a> | |
| """ | |
| def front_family_card_html(setup: str, coordinates: dict[str, dict[str, Any]]) -> str: | |
| return family_card({"setup": setup, "title": setup_title(setup)}, coordinates) | |
| def family_rows_html(summaries: list[dict[str, Any]], coordinates: dict[str, dict[str, Any]]) -> str: | |
| container_order = {"tri": 0, "squ": 1, "pen": 2, "hex": 3, "oct": 4, "cir": 5, "dom": 6} | |
| rows: dict[str, list[dict[str, Any]]] = {} | |
| for summary in summaries: | |
| _, container_code = parse_setup_codes(str(summary["setup"])) | |
| rows.setdefault(container_code, []).append(summary) | |
| body = [] | |
| for container_code in sorted(rows, key=lambda code: (container_order.get(code, 99), shape_phrase(code))): | |
| cards = "".join( | |
| family_card(summary, coordinates) | |
| for summary in sorted(rows[container_code], key=lambda item: (parse_setup_codes(str(item["setup"]))[0], str(item["setup"]))) | |
| ) | |
| body.append( | |
| f""" | |
| <section class="family-row"> | |
| <div class="family-grid">{cards}</div> | |
| </section> | |
| """ | |
| ) | |
| return f'<div class="family-matrix">{"".join(body)}</div>' | |
| def family_page_html(setup: str | None = None) -> str: | |
| choices = setup_choices() | |
| setup = setup if setup in choices else (choices[0] if choices else "") | |
| summary = setup_summary(setup) if setup else {"records": [], "setup": "", "title": ""} | |
| coordinates = coordinate_records_by_case() | |
| setup = str(summary["setup"]) | |
| records = summary["records"] | |
| cards = "".join(record_card(record, coordinates) for record in records) | |
| return f""" | |
| <main class="packing-shell"> | |
| {top_nav("home")} | |
| <section class="section"> | |
| <div class="contain"> | |
| <div class="family-title-card"> | |
| <div> | |
| <div class="family-code">{esc(setup)}</div> | |
| <h2>{esc(summary["title"])}</h2> | |
| <p class="family-subtitle">{family_description(summary)}</p> | |
| </div> | |
| </div> | |
| <div class="record-grid">{cards}</div> | |
| </div> | |
| </section> | |
| </main> | |
| """ | |
| def top_nav(active: str = "home") -> str: | |
| def nav_class(route: str, extra: str = "") -> str: | |
| classes = ["site-nav-link"] | |
| if route == active: | |
| classes.append("active") | |
| if extra: | |
| classes.append(extra) | |
| return " ".join(classes) | |
| return f""" | |
| <nav class="site-nav" aria-label="Site navigation"> | |
| <a class="{nav_class("home")}" href="/" data-route="home">Home</a> | |
| <a class="{nav_class("leaderboard")}" href="#leaderboard-panel" data-route="leaderboard">Leaderboard</a> | |
| <a class="{nav_class("submit", "submit-link")}" href="#submit-entry-panel" data-route="submit">Submit Entry</a> | |
| </nav> | |
| """ | |
| def directory_html() -> str: | |
| choices = setup_choices() | |
| summaries = [setup_summary(setup) for setup in choices] | |
| coordinates = coordinate_records_by_case() | |
| family_rows = family_rows_html(summaries, coordinates) | |
| return f""" | |
| <main class="packing-shell" id="top"> | |
| {top_nav("home")} | |
| <section class="hero-stage"> | |
| <div class="contain"> | |
| <div> | |
| <h1>Packing Benchmark</h1> | |
| <p class="hero-copy"> | |
| verified shape packing records, heavily inspired by | |
| <a href="https://erich-friedman.github.io/packing/index.html" target="_blank" rel="noopener noreferrer">Erich Friedman's Packing Center</a>. | |
| </p> | |
| </div> | |
| </div> | |
| </section> | |
| <section class="section" id="families"> | |
| <div class="contain"> | |
| <div class="section-head"> | |
| <div> | |
| <h2>Choose a family</h2> | |
| <p class="section-note"> | |
| Choose a family to view its verified packing records. | |
| </p> | |
| </div> | |
| </div> | |
| {family_rows} | |
| </div> | |
| </section> | |
| </main> | |
| """ | |
| def browse_html() -> str: | |
| return directory_html() | |
| def loading_html() -> str: | |
| return """ | |
| <main class="packing-shell"> | |
| <nav class="site-nav" aria-label="Site navigation"> | |
| <a class="site-nav-link active" href="/" data-route="home">Home</a> | |
| <a class="site-nav-link" href="#leaderboard-panel" data-route="leaderboard">Leaderboard</a> | |
| <a class="site-nav-link submit-link" href="#submit-entry-panel" data-route="submit">Submit Entry</a> | |
| </nav> | |
| <section class="hero-stage"> | |
| <div class="contain"> | |
| <h1>Packing Benchmark</h1> | |
| <p class="hero-copy">Loading records...</p> | |
| </div> | |
| </section> | |
| </main> | |
| """ | |
| def home_page_for_request(request: gr.Request): | |
| try: | |
| query = dict(request.query_params) if request else {} | |
| except Exception: | |
| query = {} | |
| setup = str(query.get("family") or "").strip() | |
| if setup in setup_choices(): | |
| return family_page_html(setup) | |
| return gr.update() | |
| def condensed_case_links(cases: list[str]) -> str: | |
| grouped: dict[str, list[int]] = {} | |
| for case in cases: | |
| if "@" not in case: | |
| continue | |
| setup, n_text = case.rsplit("@", 1) | |
| try: | |
| n = int(n_text) | |
| except ValueError: | |
| continue | |
| grouped.setdefault(setup, []).append(n) | |
| links = [] | |
| for setup in sorted(grouped, key=lambda value: (setup_title(value).lower(), value)): | |
| values = sorted(set(grouped[setup])) | |
| n_text = ",".join(str(value) for value in values) | |
| label = f"{setup}@{{{n_text}}}" | |
| href = f"?family={setup}#{setup}-{values[0]}" | |
| links.append(f'<a href="{esc(href)}">{esc(label)}</a>') | |
| return '<div class="case-links">' + "; ".join(links) + "</div>" | |
| def slug_id(value: str) -> str: | |
| slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-") | |
| return slug or "author" | |
| def sorted_case_names(cases: list[str]) -> list[str]: | |
| def key(case: str) -> tuple[str, int, str]: | |
| if "@" not in case: | |
| return (case.lower(), -1, case) | |
| setup, n_text = case.rsplit("@", 1) | |
| try: | |
| n = int(n_text) | |
| except ValueError: | |
| n = -1 | |
| return (setup_title(setup).lower(), n, case) | |
| return sorted(set(cases), key=key) | |
| def case_link(case: str) -> str: | |
| if "@" not in case: | |
| return esc(case) | |
| setup, n_text = case.rsplit("@", 1) | |
| href = f"?family={setup}#{setup}-{n_text}" | |
| return f'<a href="{esc(href)}">{esc(case)}</a>' | |
| SHAPE_CLASS_ORDER = ("tri", "squ", "pen", "hex", "oct", "cir", "dom", "rect") | |
| def shape_class_sort_key(code: str) -> tuple[int, str]: | |
| try: | |
| index = SHAPE_CLASS_ORDER.index(code) | |
| except ValueError: | |
| index = len(SHAPE_CLASS_ORDER) | |
| return (index, shape_phrase(code, plural=True)) | |
| def leaderboard_shape_label(code: str) -> str: | |
| return shape_phrase(code, plural=True).replace("regular ", "") | |
| def setup_item_code(record: dict[str, Any]) -> str: | |
| setup = str(record.get("setup") or "") | |
| if not setup and record.get("case") and "@" in str(record.get("case")): | |
| setup = str(record["case"]).split("@", 1)[0] | |
| item_code, _ = parse_setup_codes(setup) | |
| return item_code or "other" | |
| def leaderboard_class_columns(rows: dict[str, dict[str, Any]]) -> list[str]: | |
| codes = { | |
| str(code) | |
| for stats in rows.values() | |
| for code, count in dict(stats.get("class_counts", {})).items() | |
| if int(count) > 0 | |
| } | |
| return sorted(codes, key=shape_class_sort_key) | |
| def leaderboard_author_modal(author: str, stats: dict[str, Any], rank: int, modal_id: str) -> str: | |
| cases = sorted_case_names([str(case) for case in stats.get("cases", [])]) | |
| family_count = len({case.rsplit("@", 1)[0] for case in cases if "@" in case}) | |
| all_links = "".join(case_link(case) for case in cases) | |
| grouped_links = condensed_case_links(cases) | |
| class_counts = dict(stats.get("class_counts", {})) | |
| class_badges = "".join( | |
| f'<span><strong>{int(class_counts.get(code, 0))}</strong>{esc(leaderboard_shape_label(code))}</span>' | |
| for code in sorted(class_counts, key=shape_class_sort_key) | |
| if int(class_counts.get(code, 0)) > 0 | |
| ) | |
| return f""" | |
| <section class="record-modal leaderboard-modal" id="{esc(modal_id)}" aria-label="{esc(author)} leaderboard details"> | |
| <a class="modal-backdrop" href="#leaderboard-table" aria-label="Close leaderboard details"></a> | |
| <div class="modal-panel" role="dialog" aria-modal="true" aria-labelledby="{esc(modal_id)}-title"> | |
| <a class="modal-close" href="#leaderboard-table" aria-label="Close leaderboard details">x</a> | |
| <div class="modal-head"> | |
| <div class="modal-case">Leaderboard</div> | |
| <h3 id="{esc(modal_id)}-title">{esc(author)}</h3> | |
| <div class="modal-subtitle">Rank #{rank}</div> | |
| </div> | |
| <div class="modal-layout"> | |
| <div> | |
| <div class="leaderboard-stat-grid"> | |
| <div class="leaderboard-stat"><strong>{int(stats["total_top"])}</strong><span>total top records</span></div> | |
| <div class="leaderboard-stat"><strong>{int(stats["verified"])}</strong><span>verified submissions</span></div> | |
| <div class="leaderboard-stat"><strong>{family_count}</strong><span>families</span></div> | |
| </div> | |
| <div class="leaderboard-class-strip">{class_badges}</div> | |
| {grouped_links} | |
| <div class="leaderboard-full-list" aria-label="Complete record list">{all_links}</div> | |
| </div> | |
| </div> | |
| </div> | |
| </section> | |
| """ | |
| def leaderboard_html() -> str: | |
| rows: dict[str, dict[str, Any]] = {} | |
| coordinates = coordinate_records_by_case() | |
| for record in cached_public_records("", False): | |
| author = display_author(record) | |
| if author.strip().lower() == "trivial": | |
| continue | |
| entry = rows.setdefault(author, {"total_top": 0, "verified": 0, "cases": [], "class_counts": {}}) | |
| entry["total_top"] += 1 | |
| item_code = setup_item_code(record) | |
| entry["class_counts"][item_code] = int(entry["class_counts"].get(item_code, 0)) + 1 | |
| if record.get("record_type") == "verified": | |
| entry["verified"] += 1 | |
| entry["cases"].append(str(record.get("case"))) | |
| class_columns = leaderboard_class_columns(rows) | |
| class_headers = "".join(f"<th>{esc(leaderboard_shape_label(code).title())}</th>" for code in class_columns) | |
| total_top_max = max((int(stats["total_top"]) for stats in rows.values()), default=0) | |
| class_maxima = { | |
| code: max((int(dict(stats.get("class_counts", {})).get(code, 0)) for stats in rows.values()), default=0) | |
| for code in class_columns | |
| } | |
| sorted_rows = sorted(rows.items(), key=lambda item: (-int(item[1]["total_top"]), item[0].lower())) | |
| body_parts = [] | |
| modal_parts = [] | |
| for rank, (author, stats) in enumerate(sorted_rows, start=1): | |
| modal_id = f"leaderboard-author-{rank}-{slug_id(author)}" | |
| total_top = int(stats["total_top"]) | |
| total_cell_class = ' class="leaderboard-best"' if total_top == total_top_max and total_top > 0 else "" | |
| class_cells = "".join( | |
| ( | |
| f'<td class="leaderboard-best"><strong>{value}</strong></td>' | |
| if value == class_maxima.get(code, 0) and value > 0 | |
| else f"<td>{value}</td>" | |
| ) | |
| for code in class_columns | |
| for value in [int(dict(stats.get("class_counts", {})).get(code, 0))] | |
| ) | |
| body_parts.append( | |
| f""" | |
| <tr> | |
| <td>{rank}</td> | |
| <td><a class="leaderboard-author-link" href="#{esc(modal_id)}"><strong>{esc(author)}</strong></a></td> | |
| <td{total_cell_class}>{f"<strong>{total_top}</strong>" if total_cell_class else total_top}</td> | |
| {class_cells} | |
| </tr> | |
| """ | |
| ) | |
| modal_parts.append(leaderboard_author_modal(author, stats, rank, modal_id)) | |
| body = "\n".join(body_parts) | |
| modals = "\n".join(modal_parts) | |
| return f""" | |
| <main class="packing-shell"> | |
| {top_nav("leaderboard")} | |
| <section class="section"> | |
| <div class="contain"> | |
| <div class="section-head"> | |
| <div> | |
| <h2>Leaderboard</h2> | |
| </div> | |
| </div> | |
| <table class="leaderboard-table" id="leaderboard-table"> | |
| <thead> | |
| <tr><th>#</th><th>Author</th><th>Total top</th>{class_headers}</tr> | |
| </thead> | |
| <tbody>{body}</tbody> | |
| </table> | |
| {modals} | |
| </div> | |
| </section> | |
| </main> | |
| """ | |
| def submit_schema_intro_html() -> str: | |
| return f""" | |
| <main class="packing-shell"> | |
| {top_nav("submit")} | |
| <section class="section submit-hero"> | |
| <div class="contain"> | |
| <div class="section-head"> | |
| <div> | |
| <h2>Submit Entry</h2> | |
| <p class="section-note"> | |
| Paste one canonical coordinate JSON object. Existing cases must beat the current top metric by at least 0.0001; new no-record cases are accepted through n={SUBMISSION_MAX_NEW_CASE_N}. | |
| The open-source local verifier is available at <a href="{esc(VERIFIER_REPO_URL)}" target="_blank" rel="noopener noreferrer">github.com/Nathan-Roll1/packing-verifier</a>. | |
| </p> | |
| </div> | |
| </div> | |
| </div> | |
| </section> | |
| </main> | |
| """ | |
| def load_submission(json_text: str) -> dict[str, Any]: | |
| if not json_text or not json_text.strip(): | |
| raise ValueError("Paste canonical coordinate JSON.") | |
| return load_solution_json(json_text) | |
| def record_metric_float(record: dict[str, Any]) -> float | None: | |
| value = record.get("metric_value") | |
| if value is None: | |
| value = record.get("side") | |
| try: | |
| metric = float(value) | |
| except (TypeError, ValueError): | |
| return None | |
| return metric if math.isfinite(metric) else None | |
| def current_top_for_case(case: str) -> dict[str, Any] | None: | |
| candidates = [record for record in cached_public_records("", False) if str(record.get("case")) == case] | |
| candidates = [record for record in candidates if record_metric_float(record) is not None] | |
| if not candidates: | |
| return None | |
| return min(candidates, key=lambda record: record_metric_float(record) or float("inf")) | |
| def submitted_metric_for_result(result: dict[str, Any], current: dict[str, Any] | None) -> tuple[str, float | None]: | |
| symbol = str(result.get("metric_symbol") or (current or {}).get("metric_symbol") or "s") | |
| try: | |
| metric = float(result.get("metric_value")) | |
| except (TypeError, ValueError): | |
| try: | |
| side = float(result.get("side")) | |
| except (TypeError, ValueError): | |
| return symbol, None | |
| metric = side * 0.5 if symbol == "r" else side | |
| if not math.isfinite(metric): | |
| return symbol, None | |
| return symbol, metric | |
| def submission_gate(result: dict[str, Any]) -> tuple[bool, str]: | |
| if not result.get("ok"): | |
| return False, "Geometry verification failed." | |
| try: | |
| submitted_n = int(result.get("n") or 0) | |
| except (TypeError, ValueError): | |
| return False, "The evaluator could not determine the number of submitted items." | |
| current = current_top_for_case(str(result.get("case") or "")) | |
| symbol, submitted_metric = submitted_metric_for_result(result, current) | |
| if submitted_metric is None: | |
| return False, "The evaluator could not compute a submitted metric." | |
| if current is None: | |
| if submitted_n > SUBMISSION_MAX_NEW_CASE_N: | |
| return ( | |
| False, | |
| f"No current top record exists for this case, and new no-record cases are accepted only through n={SUBMISSION_MAX_NEW_CASE_N}.", | |
| ) | |
| return True, f"No current top record exists for this case; valid new cases can be submitted through n={SUBMISSION_MAX_NEW_CASE_N}." | |
| current_symbol = str(current.get("metric_symbol") or symbol) | |
| if current_symbol != symbol: | |
| return False, f"Submitted metric symbol {symbol!r} does not match current record metric symbol {current_symbol!r}." | |
| current_metric = record_metric_float(current) | |
| if current_metric is None: | |
| return True, "No comparable current top metric exists; a valid geometry can be submitted." | |
| improvement = current_metric - submitted_metric | |
| if improvement >= SUBMISSION_MIN_IMPROVEMENT: | |
| return ( | |
| True, | |
| f"Improves the current top {symbol} metric by {improvement:.10f}; required improvement is at least {SUBMISSION_MIN_IMPROVEMENT:.4f}.", | |
| ) | |
| return ( | |
| False, | |
| f"Current top {symbol} metric is {current_metric:.10f}. Submitted {symbol} metric is {submitted_metric:.10f}. " | |
| f"Improvement is {improvement:.10f}; required improvement is at least {SUBMISSION_MIN_IMPROVEMENT:.4f}.", | |
| ) | |
| def result_markdown(result: dict[str, Any], gate: tuple[bool, str] | None = None) -> str: | |
| if result["ok"]: | |
| metric_symbol_text = result.get("metric_symbol") or "s" | |
| metric_value_text = result.get("metric_value") | |
| try: | |
| metric_line = f"- Container metric: `{metric_symbol_text} = {float(metric_value_text):.10f}`\n" | |
| except (TypeError, ValueError): | |
| metric_line = "" | |
| text = ( | |
| "### Verification Passed\n\n" | |
| f"- Case: `{result['case']}`\n" | |
| f"- Items: `{result['n']}`\n" | |
| f"{metric_line}" | |
| f"- Container side/diameter: `{result['side']:.10f}`\n" | |
| f"- Density: `{result['density']:.6f}`\n" | |
| f"- Max boundary excess: `{result['max_boundary_excess']:.3e}`\n" | |
| f"- Max pair overlap depth: `{result['max_pair_overlap_depth']:.3e}`\n" | |
| ) | |
| if gate is not None: | |
| passed, message = gate | |
| status = "Passed" if passed else "Needs improvement" | |
| text += f"\n### Record Gate\n\n- Status: `{status}`\n- {message}\n" | |
| return text | |
| errors = "\n".join(f"- {e}" for e in result["errors"]) | |
| return "### Verification Failed\n\n" + errors | |
| def empty_report_markdown() -> str: | |
| return f"### Ready To Verify\n\nPaste canonical JSON, then run the verifier. Existing cases must improve the current top metric by at least `0.0001`; cases with no current record can be submitted through `n = {SUBMISSION_MAX_NEW_CASE_N}`." | |
| def empty_preview_html() -> str: | |
| return """ | |
| <div class="preview-card"> | |
| <div class="render-stage"> | |
| <div class="placeholder">verified geometry preview</div> | |
| </div> | |
| </div> | |
| """ | |
| def supported_gradio_kwargs(component: Any, **kwargs: Any) -> dict[str, Any]: | |
| try: | |
| parameters = inspect.signature(component.__init__).parameters | |
| except (TypeError, ValueError): | |
| return kwargs | |
| return {key: value for key, value in kwargs.items() if key in parameters} | |
| def supported_call_kwargs(callable_obj: Any, **kwargs: Any) -> dict[str, Any]: | |
| try: | |
| parameters = inspect.signature(callable_obj).parameters | |
| except (TypeError, ValueError): | |
| return {} | |
| return {key: value for key, value in kwargs.items() if key in parameters} | |
| def preview_html(solution: dict[str, Any]) -> str: | |
| filename = solution_case(solution) or "submission-preview" | |
| return f""" | |
| <div class="preview-card"> | |
| <div class="render-stage verified-stage">{inline_solution_svg(solution)}</div> | |
| {download_actions(filename)} | |
| </div> | |
| """ | |
| def verify_only(json_text: str): | |
| try: | |
| solution = normalize_solution(load_submission(json_text)) | |
| result = verify_solution(solution, tolerance=DEFAULT_TOLERANCE).as_dict() | |
| gate = submission_gate(result) if result["ok"] else None | |
| pretty = json.dumps(solution, indent=2, sort_keys=True) | |
| preview = preview_html(solution) if result["ok"] else "" | |
| return result_markdown(result, gate), preview, pretty | |
| except Exception as exc: | |
| return f"### Verification Failed\n\n- {exc}", empty_preview_html(), json_text | |
| def submit_solution( | |
| json_text: str, | |
| submitter: str, | |
| notes: str, | |
| source_url: str, | |
| ): | |
| try: | |
| solution = normalize_solution(load_submission(json_text)) | |
| preflight = verify_solution(solution, tolerance=DEFAULT_TOLERANCE).as_dict() | |
| gate_ok, gate_message = submission_gate(preflight) | |
| if not gate_ok: | |
| return ( | |
| result_markdown(preflight, (gate_ok, gate_message)), | |
| preview_html(solution), | |
| json.dumps(solution, indent=2, sort_keys=True), | |
| gr.update(), | |
| gr.update(), | |
| gr.update(), | |
| ) | |
| record, result = STORE.append_verified_submission( | |
| solution, | |
| submitter=submitter, | |
| notes=notes, | |
| source_url=source_url, | |
| tolerance=DEFAULT_TOLERANCE, | |
| ) | |
| stored = STORE.solution_for_record(record) | |
| pretty = json.dumps(stored, indent=2, sort_keys=True) | |
| sync_status = record.get("sync_status", "dataset sync disabled") | |
| clear_page_caches() | |
| current = current_top_for_case(str(record.get("case") or result.get("case") or "")) | |
| leaderboard_updated = bool(current and str(current.get("id")) == str(record.get("id"))) | |
| leaderboard_status = ( | |
| f"\n\n### Leaderboard Updated\n\nRecord `{record['id']}` is now the current public top for `{record['case']}`." | |
| if leaderboard_updated | |
| else ( | |
| "\n\n### Leaderboard Not Changed\n\n" | |
| "The entry was archived, but another row is still the current public top for this case." | |
| ) | |
| ) | |
| message = ( | |
| result_markdown(result, (gate_ok, gate_message)) | |
| + f"\n\nSaved as record `{record['id']}`." | |
| + leaderboard_status | |
| + f"\n\nDataset sync: `{sync_status}`." | |
| ) | |
| refreshed_home = family_page_html(str(record.get("setup") or result.get("setup") or "")) if record.get("setup") or result.get("setup") else directory_html() | |
| return ( | |
| message, | |
| preview_html(stored), | |
| pretty, | |
| leaderboard_html(), | |
| gr.update(choices=existing_author_choices(), value=submitter), | |
| refreshed_home, | |
| ) | |
| except Exception as exc: | |
| return f"### Submission Rejected\n\n- {exc}", empty_preview_html(), json_text, gr.update(), gr.update(), gr.update() | |
| THEME = gr.themes.Base() | |
| def prewarm_pages() -> None: | |
| directory_html() | |
| for setup in setup_choices(): | |
| family_page_html(setup) | |
| with gr.Blocks( | |
| **supported_gradio_kwargs( | |
| gr.Blocks, | |
| title="Packing Benchmark", | |
| analytics_enabled=False, | |
| head=APP_HEAD, | |
| footer_links=[], | |
| ) | |
| ) as demo: | |
| browse_page = gr.HTML(directory_html(), elem_id="home-panel") | |
| leaderboard_page = gr.HTML(leaderboard_html(), elem_id="leaderboard-panel") | |
| with gr.Group(elem_id="submit-entry-panel", elem_classes=["submit-entry-panel"]): | |
| gr.HTML(submit_schema_intro_html()) | |
| with gr.Group(elem_classes=["submit-shell"]): | |
| with gr.Row(elem_classes=["submit-layout"]): | |
| with gr.Column(scale=7, elem_classes=["submit-editor"]): | |
| with gr.Group(elem_classes=["submit-panel"]): | |
| gr.HTML('<div class="submit-panel-title">Paste JSON</div>') | |
| gr.HTML(f'<p class="submit-panel-note">Paste one canonical coordinate JSON object. The evaluator uses a fixed tolerance, requires a 0.0001 metric improvement for existing cases, and accepts new no-record cases through n={SUBMISSION_MAX_NEW_CASE_N}.</p>') | |
| json_code = gr.Textbox( | |
| **supported_gradio_kwargs( | |
| gr.Textbox, | |
| value=SAMPLE_JSON, | |
| label="Coordinate JSON", | |
| lines=18, | |
| max_lines=30, | |
| show_copy_button=True, | |
| ) | |
| ) | |
| with gr.Column(scale=5, elem_classes=["submit-meta"]): | |
| with gr.Group(elem_classes=["submit-panel"]): | |
| gr.HTML('<div class="submit-panel-title">Author</div>') | |
| gr.HTML('<p class="submit-panel-note">Choose an existing credited author or type a new name.</p>') | |
| submitter = gr.Dropdown( | |
| **supported_gradio_kwargs( | |
| gr.Dropdown, | |
| choices=existing_author_choices(), | |
| label="Author", | |
| value=None, | |
| allow_custom_value=True, | |
| filterable=True, | |
| info="Start typing to search existing authors. New names are accepted.", | |
| ) | |
| ) | |
| source_url = gr.Textbox(label="Source URL", placeholder="Optional") | |
| notes = gr.Textbox(label="Notes", lines=3, placeholder="Optional method or provenance note") | |
| with gr.Row(elem_classes=["submit-actions"]): | |
| verify_btn = gr.Button("Verify", variant="secondary") | |
| submit_btn = gr.Button("Submit Entry", variant="primary") | |
| with gr.Row(elem_classes=["submit-layout"]): | |
| with gr.Column(scale=5, elem_classes=["submit-results"]): | |
| with gr.Group(elem_classes=["submit-results-card"]): | |
| gr.HTML('<div class="submit-panel-title">Verification</div>') | |
| report = gr.Markdown(value=empty_report_markdown(), elem_classes=["verification-report"]) | |
| with gr.Column(scale=4, elem_classes=["submit-results"]): | |
| with gr.Group(elem_classes=["submit-results-card"]): | |
| gr.HTML('<div class="submit-panel-title">Preview</div>') | |
| preview = gr.HTML(value=empty_preview_html(), label="Browser render") | |
| with gr.Column(scale=5, elem_classes=["submit-results"]): | |
| with gr.Group(elem_classes=["submit-results-card"]): | |
| with gr.Accordion("Normalized JSON", open=False): | |
| normalized_json = gr.Textbox( | |
| **supported_gradio_kwargs( | |
| gr.Textbox, | |
| label="Verifier-normalized payload", | |
| lines=12, | |
| show_copy_button=True, | |
| ) | |
| ) | |
| with gr.Group(elem_classes=["submit-docs"]): | |
| with gr.Accordion("Submission Documentation", open=False): | |
| gr.Markdown(EXAMPLES_MD + "\n\n" + SCHEMA_DOCS_MD) | |
| demo.load(home_page_for_request, outputs=[browse_page], show_progress="hidden") | |
| verify_btn.click(verify_only, inputs=[json_code], outputs=[report, preview, normalized_json]) | |
| submit_btn.click( | |
| submit_solution, | |
| inputs=[json_code, submitter, notes, source_url], | |
| outputs=[report, preview, normalized_json, leaderboard_page, submitter, browse_page], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch( | |
| theme=THEME, | |
| css=CSS, | |
| js=APP_JS, | |
| server_name="0.0.0.0", | |
| ssr_mode=False, | |
| **supported_call_kwargs(demo.launch, show_api=False, footer_links=[], favicon_path=str(FAVICON_PATH)), | |
| ) | |