from __future__ import annotations import json import tempfile from pathlib import Path from zipfile import ZipFile import gradio as gr import pandas as pd from src.domain import FAMILIES, ReviewState from src.evidence import finding_facts from src.generator import scenario_by_id, scenarios from src.i18n import TEXTS, t from src.pipeline import evaluate_catalog, load_sample, result_to_downloads, run_pipeline from src.plots import compare_figure, diff_figure, empty_plot, finding_figure, kpi_html, render_diff_html ROOT = Path(__file__).resolve().parents[1] SAMPLE_PREVIEW = ROOT / "examples" / "sample_preview.json" CSS = """ .gradio-container {max-width: 1360px !important; margin: 0 auto;} .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;} .ltr-id {direction: ltr; text-align: left; font-family: ui-monospace, Consolas, monospace;} .diff-view {background:#0f172a; color:#e2e8f0; border-radius:12px; padding:12px; max-height:420px; overflow:auto; font-size:12px; line-height:1.45;} .diff-view .add {background:#14532d; color:#bbf7d0;} .diff-view .del {background:#7f1d1d; color:#fecaca;} .diff-view .find {background:#1e3a8a; color:#dbeafe;} .diff-view .hit {background:#6d28d9; color:#f5f3ff; outline:1px solid #c4b5fd;} .diff-view .meta, .diff-view .hunk {color:#93c5fd;} """ def _preview_payload() -> dict: if SAMPLE_PREVIEW.exists(): return json.loads(SAMPLE_PREVIEW.read_text(encoding="utf-8")) return {} def _scenario_choices() -> list[str]: return [item.scenario_id for item in scenarios()] def _family_choices(lang: str) -> list[str]: return [t(lang, "family_all"), *FAMILIES] def _feedback_choices(lang: str) -> list[str]: return [t(lang, "correct"), t(lang, "false_positive"), t(lang, "insufficient"), t(lang, "needs_review")] 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, "scenario")), gr.update(label=t(lang, "family"), choices=_family_choices(lang), value=_family_choices(lang)[0]), gr.update(value=t(lang, "sample_note")), gr.update(value=preview.get("kpi_html") or kpi_html(preview.get("kpis") or {}, lang)), 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, "diff_label")), gr.update(label=t(lang, "related_label")), gr.update(label=t(lang, "feedback"), choices=_feedback_choices(lang), value=_feedback_choices(lang)[3]), gr.update(value=t(lang, "mark_fp")), ) def _scenario_fields(scenario_id: str): item = scenario_by_id(scenario_id) pack = load_sample(scenario_id) return item.description, item.description_fa, pack["diff"], pack["related"] def load_sample_ui(scenario_id: str): return _scenario_fields(scenario_id) def reset_defaults(): return _scenario_fields("S01") + ("S01", None, None) def _detail_markdown(result: dict, finding_id: str, lang: str) -> str: findings = result.get("findings") or [] item = next((row for row in findings if row.finding_id == finding_id), None) if item is None: if findings: item = findings[0] else: return t(lang, "empty") facts = finding_facts(item) refs = "\n".join(f"- {ref}" for ref in item.references) or "- —" patch = f"\n\n```python\n{item.patch}\n```" if item.patch else "" return ( f"**{item.finding_id} · {item.family} · {item.review_state.value}**\n\n" f"`{item.evidence_locator}` · {item.cwe} · `{item.rule_id}`\n\n" f"**{t(lang, 'observed')}.** {facts['observed']}\n\n" f"**{t(lang, 'inference')}.** {facts['inference']}\n\n" f"**{t(lang, 'action')}.** {facts['action']}\n\n" f"{refs}{patch}" ) def _filter_family(findings: list, family: str, lang: str) -> list: if not family or family == t(lang, "family_all") or family == t("en", "family_all"): return findings return [item for item in findings if item.family == family] def run_live(lang, scenario_id, family, diff_text, related_text, diff_file, related_file, previous_state): result = run_pipeline( scenario_id=scenario_id, diff_text=diff_text or "", related_text=related_text or "", lang=lang, diff_path=diff_file, related_path=related_file, ) if result.get("error") and result["verdict"].value == "invalid_input": raise gr.Error(result["error"]) reason_md = "\n".join(f"- {line}" for line in result["reasons"]) status = f"**{t(lang, 'status')}:** {result['status_label']}\n\n{t(lang, 'live_note')}\n\n{result['narrative']}" tmp = Path(tempfile.mkdtemp(prefix="codereview-")) files = result_to_downloads(result, tmp) zip_path = tmp / f"{result['run_id']}_bundle.zip" with ZipFile(zip_path, "w") as zipped: for path in files.values(): zipped.write(path, arcname=Path(path).name) history = pd.DataFrame() if previous_state: history = pd.DataFrame( [ {"run": "previous", **previous_state.get("kpis", {})}, {"run": "current", **result["kpis"]}, ] ) visible = _filter_family(result["findings"], family, lang) finding_ids = [item.finding_id for item in visible] or ["—"] selected = finding_ids[0] detail = _detail_markdown({"findings": visible} if visible else result, selected, lang) catalog = pd.DataFrame(evaluate_catalog()) file_rows = [] if result.get("change"): file_rows = [{"path": item.path, "changed": item.changed_line_count} for item in result["change"].files] diff_html = render_diff_html(diff_text or (result.get("change") and ""), visible, selected) if result.get("change") and not (diff_text or "").strip(): pack = load_sample(scenario_id) diff_html = render_diff_html(pack["diff"], visible, selected) elif (diff_text or "").strip(): diff_html = render_diff_html(diff_text, visible, selected) return ( kpi_html(result["kpis"], lang), status, reason_md, pd.DataFrame(_rows(visible)), pd.DataFrame(result["unknown_rows"]), pd.DataFrame(result["baseline_rows"]), catalog, finding_figure(visible, t(lang, "finding_plot")), compare_figure(len(result["findings"]), len(result["baseline"]), result["kpis"]["baseline_extra"], t(lang, "compare_plot")), diff_figure(file_rows, t(lang, "diff_plot")), gr.update(choices=finding_ids, value=selected), detail, diff_html, str(zip_path), files["report"], history, {"kpis": result["kpis"], "result": result, "diff": diff_text}, json.dumps([item.model_dump() for item in result["validation"].issues], indent=2), ) def _rows(findings) -> list[dict]: from src.pipeline import _finding_rows return _finding_rows(findings) def select_finding(lang, finding_id, state): if not state or not state.get("result"): return t(lang, "empty"), "
" result = state["result"] detail = _detail_markdown(result, finding_id, lang) diff_text = state.get("diff") or "" if not diff_text and result.get("scenario"): diff_text = load_sample(result["scenario"].scenario_id)["diff"] html_diff = render_diff_html(diff_text, result.get("findings") or [], finding_id) return detail, html_diff def mark_false_positive(lang, finding_id, state): if not state or not state.get("result"): return t(lang, "empty"), pd.DataFrame() result = state["result"] updated = [] for item in result["findings"]: if item.finding_id == finding_id: updated.append(item.model_copy(update={"review_state": ReviewState.FALSE_POSITIVE})) else: updated.append(item) result["findings"] = updated state["result"] = result detail = _detail_markdown(result, finding_id, lang) return detail, pd.DataFrame(_rows(updated)) def build_demo() -> gr.Blocks: preview = _preview_payload() first = scenarios()[0] pack = load_sample(first.scenario_id) preview_kpis = preview.get("kpis") or { "n_findings_review": 1, "n_confirmed": 1, "n_insufficient": 0, "n_unknown": 0, "n_files": 1, "n_changed_lines": 2, "n_patches_valid": 1, "baseline_extra": 0, "elapsed_ms": 20, "n_related": 1, } with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="blue"), 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.Row(): with gr.Column(scale=1): scenario = gr.Dropdown(choices=_scenario_choices(), value=first.scenario_id, label=t("en", "scenario")) family = gr.Dropdown(choices=_family_choices("en"), value=_family_choices("en")[0], label=t("en", "family")) desc_en = gr.Textbox(value=first.description, label="Scenario (EN)", lines=5) desc_fa = gr.Textbox(value=first.description_fa, label="سناریو", lines=4, rtl=True) findings = gr.Dataframe(label="Findings") finding_pick = gr.Dropdown(choices=["—"], value="—", label="Finding") fp_btn = gr.Button(t("en", "mark_fp")) with gr.Column(scale=1): reasons = gr.Markdown() diff_html = gr.HTML(value="
") detail = gr.Markdown() with gr.Column(scale=1): issues = gr.Code(language="json", label="Validation issues") feedback = gr.Radio(choices=_feedback_choices("en"), value=_feedback_choices("en")[3], label=t("en", "feedback")) with gr.Row(): zip_out = gr.File(label="CSV / JSON bundle") json_out = gr.File(label="JSON report") with gr.Tabs(): with gr.Tab("Data"): hint = gr.Markdown(t("en", "upload_hint")) with gr.Accordion(t("en", "advanced"), open=False) as advanced: diff_file = gr.File(label=t("en", "diff_file"), file_types=[".diff", ".patch", ".txt"]) related_file = gr.File(label=t("en", "related_file"), file_types=[".txt", ".py"]) diff_box = gr.Code(value=pack["diff"], language="python", label=t("en", "diff_label"), lines=14) related_box = gr.Code(value=pack["related"], language="python", label=t("en", "related_label"), lines=8) with gr.Tab("Findings"): finding_plot = gr.Plot(value=empty_plot("—")) with gr.Tab("Evidence"): unknowns = gr.Dataframe(label="Unknown / insufficient context") with gr.Tab("Compare"): baseline = gr.Dataframe(label="Keyword-only baseline") compare_plot = gr.Plot(value=empty_plot("—")) file_plot = gr.Plot(value=empty_plot("—")) catalog = gr.Dataframe(label="Recorded catalog (10 scenarios × 2 methods)") history = gr.Dataframe(label="Previous vs current KPIs") with gr.Tab("Method and limits"): method_md = gr.Markdown(t("en", "method_body")) gr.Markdown( "Organization: [AriaAICompany](https://huggingface.co/AriaAICompany) · " "Dataset: [code-review-lab](https://huggingface.co/datasets/AriaAICompany/code-review-lab) · " "Site: [aria-ai.ir](https://aria-ai.ir/) · " "Not live penetration testing." ) previous = gr.State(None) outputs_lang = [ header, run_btn, cancel_btn, reset_btn, load_btn, scenario, family, note, kpis, advanced, method_md, hint, diff_box, related_box, feedback, fp_btn, ] lang.change(apply_language, inputs=[lang], outputs=outputs_lang) demo.load(apply_language, inputs=[lang], outputs=outputs_lang) scenario.change(_scenario_fields, inputs=[scenario], outputs=[desc_en, desc_fa, diff_box, related_box]) load_btn.click(load_sample_ui, inputs=[scenario], outputs=[desc_en, desc_fa, diff_box, related_box]) reset_btn.click(reset_defaults, outputs=[desc_en, desc_fa, diff_box, related_box, scenario, diff_file, related_file]) outputs_run = [ kpis, status, reasons, findings, unknowns, baseline, catalog, finding_plot, compare_plot, file_plot, finding_pick, detail, diff_html, zip_out, json_out, history, previous, issues, ] click = run_btn.click( run_live, inputs=[lang, scenario, family, diff_box, related_box, diff_file, related_file, previous], outputs=outputs_run, ) cancel_btn.click(None, cancels=[click]) finding_pick.change(select_finding, inputs=[lang, finding_pick, previous], outputs=[detail, diff_html]) fp_btn.click(mark_false_positive, inputs=[lang, finding_pick, previous], outputs=[detail, findings]) return demo