from __future__ import annotations import json import tempfile from pathlib import Path from zipfile import ZipFile import gradio as gr import pandas as pd import plotly.graph_objects as go from src.domain import DEFAULT_SOLVER_SECONDS, ConstraintConfig, PromptVariant from src.explain import numeric_reasons, status_label from src.i18n import TEXTS, t from src.metrics import family_summary, kpi_snapshot, summarize from src.model_registry import all_methods from src.pipeline import ( evaluate_problem, interactive_problems, load_problems, load_results, load_sample, problem_by_id, result_to_downloads, ) from src.plots import empty_plot, family_bars, format_leaderboard, kpi_html, method_bars, solution_plot from src.validation import ValidationReport ROOT = Path(__file__).resolve().parents[1] SAMPLE_PREVIEW = ROOT / "examples" / "sample_preview.json" CSS = """ .gradio-container {max-width: 1280px !important; margin: 0 auto;} .dark .gradio-container {color: var(--body-text-color);} .aria-header h1 {margin-bottom: 0.2rem;} .aria-header p {opacity: 0.85;} .kpi-grid {display:grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px;} .kpi-card {background: linear-gradient(180deg, #eef2ff, #ffffff); border: 1px solid #c7d2fe; border-radius: 16px; padding: 14px 16px;} .kpi-label {font-size: 0.8rem; color: #3730a3; margin: 0;} .kpi-value {font-size: 1.55rem; font-weight: 700; color: #312e81; margin: 4px 0;} .kpi-sub {margin: 0; font-size: 0.78rem; color: #334155;} .rtl-mode {direction: rtl; text-align: right;} """ def _preview_payload() -> dict: if SAMPLE_PREVIEW.exists(): return json.loads(SAMPLE_PREVIEW.read_text(encoding="utf-8")) return {} def _empty_plot() -> go.Figure: return empty_plot("—") def _variant_choices(lang: str) -> list[str]: return [t(lang, "template"), t(lang, "json"), t(lang, "missing")] def _parse_variant(value: str) -> PromptVariant: if value in {PromptVariant.JSON.value, t("en", "json"), t("fa", "json")}: return PromptVariant.JSON if value in {PromptVariant.MISSING_BUDGET.value, t("en", "missing"), t("fa", "missing")}: return PromptVariant.MISSING_BUDGET return PromptVariant.TEMPLATE def _problem_choices() -> list[str]: return [item.problem_id for item in interactive_problems()] def apply_language(lang: str): rtl = lang == "fa" preview = _preview_payload() header = ( f"
" f"

{t(lang, 'title')}

{t(lang, 'subtitle')}

{t(lang, 'kind')}

" ) return ( gr.update(value=header), gr.update(value=t(lang, "run_sample")), gr.update(value=t(lang, "cancel")), gr.update(value=t(lang, "reset")), gr.update(value=t(lang, "load_sample")), gr.update(label=t(lang, "problem")), gr.update(label=t(lang, "variant"), choices=_variant_choices(lang), value=_variant_choices(lang)[0]), gr.update(label=t(lang, "time_limit")), gr.update(value=t(lang, "sample_note")), gr.update(value=preview.get("kpi_html", "")), gr.update(open=False, label=t(lang, "advanced")), gr.update(value=t(lang, "method_body"), rtl=rtl), gr.update(value=t(lang, "upload_hint")), gr.update(label=t(lang, "custom_text")), gr.update(label=t(lang, "custom_schema")), gr.update(label=t(lang, "direct_json")), ) def _load_problem_fields(problem_id: str): problem = problem_by_id(problem_id) return ( problem.prompt_en, problem.prompt_fa, problem.prompt_json, json.dumps(problem.schema_payload, indent=2, ensure_ascii=False), problem.gold_status, problem.gold_objective, problem.family.value, problem.split.value, problem.difficulty.value, problem.language, problem.template_id, ) def load_sample_ui(): ids = _problem_choices() fields = _load_problem_fields(ids[0]) return (ids[0], *fields) def run_live(lang, problem_id, variant, time_limit, custom_text, schema_text, direct_text): problem = problem_by_id(problem_id) schema = None if schema_text and str(schema_text).strip(): try: schema = json.loads(schema_text) except json.JSONDecodeError as exc: raise gr.Error(f"schema JSON: {exc}") from exc direct = None if direct_text and str(direct_text).strip(): try: direct = json.loads(direct_text) except json.JSONDecodeError as exc: raise gr.Error(f"direct-answer JSON: {exc}") from exc result = evaluate_problem( problem, lang=lang, variant=_parse_variant(variant), config=ConstraintConfig(solver_seconds=float(time_limit)), custom_text=custom_text or None, custom_schema=schema, custom_solution=direct, ) if result.get("error"): raise gr.Error(result["error"]) validation: ValidationReport | None = result["validation"] reasons = "\n".join(f"- {line}" for line in numeric_reasons(problem, result["rows"], validation, lang)) kpis = kpi_snapshot(result["table"]) status = ( f"**{t(lang, 'status')}:** {result['status_label']}\n\n" f"{t(lang, 'live_note')}\n\n" f"Gold `{problem.gold_status}` / {problem.gold_objective}. Validator " f"{'ok' if validation is None or validation.ok else 'failed'}." ) tmp = Path(tempfile.mkdtemp(prefix="orbench-")) files = result_to_downloads(result, tmp) zip_path = tmp / f"{result['run_id']}_tables.zip" with ZipFile(zip_path, "w") as zipped: for key, path in files.items(): zipped.write(path, arcname=Path(path).name) live_table = format_leaderboard(result["table"]) summary = result["summary"] fam = family_summary(result["table"]) plot = solution_plot(problem.family.value, result.get("solution") or {}, t(lang, "sol_plot")) method_fig = method_bars(summary, t(lang, "method_plot")) family_fig = family_bars(fam, t(lang, "family_plot")) violated = pd.DataFrame( [{"method_id": row.method_id, "status": row.status, "violated": ", ".join(row.violated), "notes": row.notes} for row in result["rows"]] ) facts = pd.DataFrame( [ {"field": "family", "value": problem.family.value}, {"field": "split", "value": problem.split.value}, {"field": "difficulty", "value": problem.difficulty.value}, {"field": "template_id", "value": problem.template_id}, {"field": "gold_status", "value": problem.gold_status}, {"field": "gold_objective", "value": problem.gold_objective}, {"field": "cover_or_hard", "value": str(problem.schema_payload.get("cover_required") or "")}, ] ) return ( kpi_html(kpis, lang), status, reasons, live_table, summary, violated, facts, plot, method_fig, family_fig, str(zip_path), files["report"], result["prompt"], json.dumps(result["schema"], indent=2, ensure_ascii=False), ) def filter_catalog(family, split, language, difficulty, evaluated_only): frame = load_results() if frame.empty: return pd.DataFrame(), pd.DataFrame(), _empty_plot(), _empty_plot() view = frame.copy() if family and family != "all": view = view.loc[view["family"] == family] if split and split != "all": view = view.loc[view["split"] == split] if language and language != "all": view = view.loc[view["language"] == language] if difficulty and difficulty != "all": view = view.loc[view["difficulty"] == difficulty] if evaluated_only: view = view.loc[view["evaluated"] == True] # noqa: E712 summary = summarize(view) fam = family_summary(view) return format_leaderboard(view), summary, method_bars(summary, "Filtered methods"), family_bars(fam, "Filtered families") def compare_interactive(lang, time_limit): rows = [] for problem in interactive_problems(): result = evaluate_problem(problem, lang=lang, config=ConstraintConfig(solver_seconds=min(6.0, float(time_limit)))) for row in result["rows"]: if row.method_id in {"structured-solver", "heuristic", "template-extractor+solver"}: rows.append(row.model_dump()) frame = pd.DataFrame(rows) return format_leaderboard(frame), summarize(frame) def registry_table() -> pd.DataFrame: return pd.DataFrame( [ { "method_id": item.method_id, "kind": item.kind.value, "evaluated": item.evaluated, "version": item.version, "notes": item.notes or item.reason_if_skipped, } for item in all_methods() ] ) def solve_sample_api(): pack = load_sample() result = evaluate_problem(pack["problem"], lang="en", config=ConstraintConfig(solver_seconds=6)) structured = result["table"].loc[result["table"]["method_id"] == "structured-solver"].iloc[0] return result["status"], float(structured.get("feasible") or 0), float(structured.get("objective") or 0), float(result["seconds"]) def build_demo() -> gr.Blocks: pack = load_sample() preview = _preview_payload() ids = _problem_choices() recorded = load_results() preview_kpis = preview.get("kpis") or kpi_snapshot(recorded) if not recorded.empty else { "n_problems": 100, "structured_feasible": 0.0, "heuristic_gap": None, "template_fidelity": None, "n_methods_evaluated": 5, "n_methods_listed": 10, } with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="purple"), css=CSS) as demo: lang = gr.Radio(["en", "fa"], value="en", label=TEXTS["en"]["language"]) header = gr.HTML() with gr.Row(): run_btn = gr.Button(t("en", "run_sample"), variant="primary") cancel_btn = gr.Button(t("en", "cancel"), variant="stop") reset_btn = gr.Button(t("en", "reset")) load_btn = gr.Button(t("en", "load_sample")) note = gr.Markdown(t("en", "sample_note")) kpis = gr.HTML(preview.get("kpi_html") or kpi_html(preview_kpis, "en")) status = gr.Markdown(t("en", "empty")) with gr.Tabs(): with gr.Tab("Data"): hint = gr.Markdown(t("en", "upload_hint")) problem = gr.Dropdown(choices=ids, value=ids[0] if ids else None, label=t("en", "problem")) with gr.Row(): prompt_en = gr.Textbox(value=pack["problem"].prompt_en, label="prompt_en", lines=8) prompt_fa = gr.Textbox(value=pack["problem"].prompt_fa, label="prompt_fa", lines=8) prompt_json = gr.Code(value=pack["problem"].prompt_json, language="json", label="prompt_json") custom_text = gr.Textbox(label=t("en", "custom_text"), lines=4) schema_text = gr.Code( value=json.dumps(pack["problem"].schema_payload, indent=2, ensure_ascii=False), language="json", label=t("en", "custom_schema"), ) direct_text = gr.Textbox(label=t("en", "direct_json"), lines=4, placeholder='{"orders":[],"assignments":[],"starts":[]}') with gr.Tab("Constraints"): variant = gr.Radio(choices=_variant_choices("en"), value=_variant_choices("en")[0], label=t("en", "variant")) with gr.Accordion(t("en", "advanced"), open=False) as advanced: time_limit = gr.Slider(3, 20, value=DEFAULT_SOLVER_SECONDS, step=1, label=t("en", "time_limit")) facts = gr.Dataframe( value=pd.DataFrame( [ {"field": "family", "value": pack["problem"].family.value}, {"field": "gold_status", "value": pack["problem"].gold_status}, {"field": "gold_objective", "value": pack["problem"].gold_objective}, ] ), label="Instance facts", ) meta = gr.Markdown( f"family `{pack['problem'].family.value}` · split `{pack['problem'].split.value}` · " f"difficulty `{pack['problem'].difficulty.value}` · template `{pack['problem'].template_id}`" ) with gr.Tab("Results"): reasons = gr.Markdown() live_table = gr.Dataframe(label="Per-method cells (not_evaluated is not a score)") violated = gr.Dataframe(label="Violated constraints / skip reasons") sol_plot = gr.Plot(value=_empty_plot()) method_plot = gr.Plot(value=_empty_plot()) live_summary = gr.Dataframe(label="Evaluated-method summary") with gr.Row(): zip_out = gr.File(label="CSV / JSON bundle") json_out = gr.File(label="JSON report") with gr.Tab("Scenario comparison"): with gr.Row(): family_f = gr.Dropdown(["all", "inventory", "assignment", "scheduling"], value="all", label="family") split_f = gr.Dropdown(["all", "development", "test"], value="all", label="split") lang_f = gr.Dropdown(["all", "en", "fa"], value="all", label="prompt language") diff_f = gr.Dropdown(["all", "easy", "medium", "hard", "infeasible"], value="all", label="difficulty") eval_only = gr.Checkbox(value=False, label="hide not_evaluated rows") filter_btn = gr.Button("Filter recorded catalog") compare_btn = gr.Button("Re-run 20 interactive problems") board = gr.Dataframe(label="Recorded leaderboard", value=format_leaderboard(recorded) if not recorded.empty else None) board_summary = gr.Dataframe(label="Catalog summary") family_plot = gr.Plot(value=_empty_plot()) catalog_plot = gr.Plot(value=_empty_plot()) interactive_tbl = gr.Dataframe(label="Interactive re-run") interactive_sum = gr.Dataframe(label="Interactive summary") with gr.Tab("Method and limits"): method = gr.Markdown(t("en", "method_body")) registry = gr.Dataframe(value=registry_table(), label="Versioned method registry") gr.Markdown( "Organization: [AriaAICompany](https://huggingface.co/AriaAICompany) · " "Dataset: [or-bench-problems](https://huggingface.co/datasets/AriaAICompany/or-bench-problems) · " "Site: [aria-ai.ir](https://aria-ai.ir/)" ) hidden_gold_status = gr.Textbox(visible=False, value=pack["problem"].gold_status) hidden_gold_obj = gr.Number(visible=False, value=pack["problem"].gold_objective or 0) hidden_family = gr.Textbox(visible=False, value=pack["problem"].family.value) hidden_split = gr.Textbox(visible=False, value=pack["problem"].split.value) hidden_diff = gr.Textbox(visible=False, value=pack["problem"].difficulty.value) hidden_plang = gr.Textbox(visible=False, value=pack["problem"].language) hidden_tmpl = gr.Textbox(visible=False, value=pack["problem"].template_id) outputs_lang = [ header, run_btn, cancel_btn, reset_btn, load_btn, problem, variant, time_limit, note, kpis, advanced, method, hint, custom_text, schema_text, direct_text, ] lang.change(apply_language, inputs=[lang], outputs=outputs_lang) demo.load(apply_language, inputs=[lang], outputs=outputs_lang) problem.change( _load_problem_fields, inputs=[problem], outputs=[ prompt_en, prompt_fa, prompt_json, schema_text, hidden_gold_status, hidden_gold_obj, hidden_family, hidden_split, hidden_diff, hidden_plang, hidden_tmpl, ], ) load_btn.click( load_sample_ui, outputs=[ problem, prompt_en, prompt_fa, prompt_json, schema_text, hidden_gold_status, hidden_gold_obj, hidden_family, hidden_split, hidden_diff, hidden_plang, hidden_tmpl, ], ) reset_btn.click( load_sample_ui, outputs=[ problem, prompt_en, prompt_fa, prompt_json, schema_text, hidden_gold_status, hidden_gold_obj, hidden_family, hidden_split, hidden_diff, hidden_plang, hidden_tmpl, ], ) run_event = run_live event = run_btn.click( run_live, inputs=[lang, problem, variant, time_limit, custom_text, schema_text, direct_text], outputs=[ kpis, status, reasons, live_table, live_summary, violated, facts, sol_plot, method_plot, family_plot, zip_out, json_out, custom_text, schema_text, ], ) cancel_btn.click(lambda: None, cancels=[event]) filter_btn.click( filter_catalog, inputs=[family_f, split_f, lang_f, diff_f, eval_only], outputs=[board, board_summary, catalog_plot, family_plot], ) compare_btn.click(compare_interactive, inputs=[lang, time_limit], outputs=[interactive_tbl, interactive_sum]) api_status = gr.Textbox(visible=False) api_feas = gr.Number(visible=False) api_obj = gr.Number(visible=False) api_sec = gr.Number(visible=False) api_btn = gr.Button("solve_sample_api", visible=False) api_btn.click(solve_sample_api, outputs=[api_status, api_feas, api_obj, api_sec], api_name="solve_sample") _ = run_event _ = meta demo.queue(default_concurrency_limit=1) return demo