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_THRESHOLD, SENSITIVE_TYPES from src.explain import finding_markdown, state_markdown from src.i18n import TEXTS, t from src.pipeline import evidence_table, findings_table, load_sample, load_uploaded, result_to_downloads, run_pipeline from src.plots import ( calibration_figure, compare_figure, empty_plot, finding_scatter, graph_figure, kpi_html, timeline_figure, ) ROOT = Path(__file__).resolve().parents[1] SAMPLE_PREVIEW = ROOT / "examples" / "sample_preview.json" CHANGE_CHOICES = ["all", *sorted(SENSITIVE_TYPES)] CSS = """ .gradio-container {max-width: 1320px !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, #e0f2fe, #ffffff); border: 1px solid #7dd3fc; border-radius: 16px; padding: 14px 16px;} .kpi-label {font-size: 0.8rem; color: #075985; margin: 0;} .kpi-value {font-size: 1.45rem; font-weight: 700; color: #0c4a6e; 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; unicode-bidi: isolate; font-family: ui-monospace, Consolas, monospace;} """ 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 _scenario_choices(lang: str) -> list[str]: return [ t(lang, "scenario_full"), t(lang, "scenario_maintenance"), t(lang, "scenario_exposure"), t(lang, "scenario_iam"), t(lang, "scenario_logging"), t(lang, "scenario_broken"), ] def _parse_scenario(value: str) -> str: mapping = {} for lang in ("en", "fa"): mapping[t(lang, "scenario_full")] = "full" mapping[t(lang, "scenario_maintenance")] = "maintenance" mapping[t(lang, "scenario_exposure")] = "exposure" mapping[t(lang, "scenario_iam")] = "iam" mapping[t(lang, "scenario_logging")] = "logging" mapping[t(lang, "scenario_broken")] = "broken" return mapping.get(value, "full") def _feedback_choices(lang: str) -> list[str]: return [t(lang, "correct"), t(lang, "false_positive"), t(lang, "insufficient"), t(lang, "needs_review")] def _file_path(value) -> str | None: if value is None: return None if isinstance(value, str): return value if isinstance(value, dict) and value.get("path"): return value["path"] return getattr(value, "name", None) or getattr(value, "path", None) def apply_language(lang: str): rtl = lang == "fa" header = ( f"
" f"

{t(lang, 'title')}

{t(lang, 'subtitle')}

{t(lang, 'kind')}

" ) preview = _preview_payload() 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"), choices=_scenario_choices(lang), value=_scenario_choices(lang)[0]), gr.update(label=t(lang, "threshold")), gr.update(label=t(lang, "hide_context")), gr.update(label=t(lang, "actor_filter")), gr.update(label=t(lang, "resource_filter")), gr.update(label=t(lang, "change_filter")), gr.update(value=t(lang, "sample_note")), gr.update(value=preview.get("kpi_html") or kpi_html(preview.get("kpis"), None, 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, "custom_logs")), gr.update(label=t(lang, "logs_file")), gr.update(label=t(lang, "feedback"), choices=_feedback_choices(lang), value=_feedback_choices(lang)[3]), gr.update(label=t(lang, "tab_data")), gr.update(label=t(lang, "tab_findings")), gr.update(label=t(lang, "tab_evidence")), gr.update(label=t(lang, "tab_compare")), gr.update(label=t(lang, "tab_method")), ) def load_sample_ui(scenario_label: str): pack = load_sample(_parse_scenario(scenario_label)) return pack["events"], pack["gold"], pack["full_events"] def reset_defaults(): pack = load_sample("full") return pack["events"], pack["gold"], pack["full_events"], DEFAULT_THRESHOLD, False, "", "", "all", "" def run_live( lang, scenario_label, threshold, hide_context, actor_filter, resource_filter, change_filter, preview, gold, full_events, extra, log_file, previous, ): scenario = _parse_scenario(scenario_label) uploaded, messages = load_uploaded(_file_path(log_file)) source = uploaded if not uploaded.empty else (full_events if isinstance(full_events, pd.DataFrame) and not full_events.empty else preview) if (source is None or getattr(source, "empty", True)) and scenario: pack = load_sample(scenario) source = pack["full_events"] gold = pack["gold"] result = run_pipeline( source, gold=gold, threshold=float(threshold or DEFAULT_THRESHOLD), lang=lang, extra_text=extra or "", hide_context=bool(hide_context), actor_filter=str(actor_filter or ""), resource_filter=str(resource_filter or ""), change_filter=str(change_filter or "all"), ) if result.get("error") and result["verdict"].value == "invalid_input": raise gr.Error(result["error"]) if messages: result["reasons"] = messages + result["reasons"] table = findings_table(result) baseline = next((row.model_dump() for row in result["comparison"] if row.method == "rule_severity" and row.split == "test"), {}) tmp = Path(tempfile.mkdtemp(prefix="ariact-")) 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: history = pd.DataFrame([{"run": "previous", **(previous.get("kpis") or {})}, {"run": "current", **result["kpis"].model_dump()}]) first = result["findings"][0] if result["findings"] else None status = f"**{t(lang, 'status')}:** {result['status_label']}" state = { "kpis": result["kpis"].model_dump(), "findings": [item.model_dump() for item in result["findings"]], "run_id": result["run_id"], } evidence = evidence_table(result, first.finding_id) if first else pd.DataFrame() account = first.account_alias if first else "" return ( kpi_html(result["kpis"], baseline, lang), status, "\n".join(f"- {line}" for line in result["reasons"]), finding_markdown(lang, first), state_markdown(lang, first), table, pd.DataFrame([row.model_dump() for row in result["comparison"]]), timeline_figure(result.get("events"), account, t(lang, "timeline_plot")), compare_figure([row.model_dump() for row in result["comparison"]], t(lang, "cmp_plot")), calibration_figure(result.get("calibration") or [], t(lang, "cal_plot")), finding_scatter(result["findings"], t(lang, "scatter_plot")), graph_figure(result["findings"], t(lang, "graph_plot")), str(zip_path), files["report"], history, evidence, result, state, ) def show_finding(evt: gr.SelectData, table, lang, result): if table is None or evt is None or not result: return t(lang, "empty_card"), t(lang, "empty_state"), pd.DataFrame(), _empty_plot() frame = pd.DataFrame(table) try: row = frame.iloc[evt.index[0] if isinstance(evt.index, tuple) else evt.index] except Exception: return t(lang, "empty_card"), t(lang, "empty_state"), pd.DataFrame(), _empty_plot() finding_id = str(row.get("finding_id") or "") match = next((item for item in result.get("findings") or [] if item.finding_id == finding_id), None) account = match.account_alias if match else "" return ( finding_markdown(lang, match), state_markdown(lang, match), evidence_table(result, finding_id), timeline_figure(result.get("events"), account, t(lang, "timeline_plot")), ) def build_demo() -> gr.Blocks: pack = load_sample("full") preview = _preview_payload() preview_kpis = preview.get("kpis") or { "n_raw": 0, "n_valid": 0, "n_dropped": 0, "n_changes": 0, "n_security_review": 0, "n_context": 0, "n_incomplete": 0, "parse_coverage": 0.0, "seconds": 0.0, "threshold": DEFAULT_THRESHOLD, } with gr.Blocks(theme=gr.themes.Soft(primary_hue="sky", secondary_hue="slate"), 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, None, "en")) status = gr.Markdown(t("en", "empty")) with gr.Row(): scenario = gr.Radio(choices=_scenario_choices("en"), value=_scenario_choices("en")[0], label=t("en", "scenario")) threshold = gr.Slider(1.5, 5.0, value=DEFAULT_THRESHOLD, step=0.5, label=t("en", "threshold")) hide_context = gr.Checkbox(value=False, label=t("en", "hide_context")) with gr.Row(): actor_filter = gr.Textbox(label=t("en", "actor_filter"), elem_classes=["ltr-id"]) resource_filter = gr.Textbox(label=t("en", "resource_filter"), elem_classes=["ltr-id"]) change_filter = gr.Dropdown(choices=CHANGE_CHOICES, value="all", label=t("en", "change_filter")) reasons = gr.Markdown() card = gr.Markdown(t("en", "empty_card")) state_md = gr.Markdown(t("en", "empty_state")) with gr.Tabs() as tabs: with gr.Tab(t("en", "tab_data")) as tab_data: hint = gr.Markdown(t("en", "upload_hint")) log_file = gr.File(label=t("en", "logs_file"), file_types=[".csv", ".json", ".jsonl", ".log", ".txt"]) events = gr.Dataframe(value=pack["events"], label="CloudTrail preview (first 400 of the generated pack)", wrap=True) gold = gr.Dataframe(value=pack["gold"], label="Lab change labels") full_events = gr.State(pack["full_events"]) with gr.Accordion(t("en", "advanced"), open=False) as advanced: extra = gr.Textbox(label=t("en", "custom_logs"), lines=5) with gr.Tab(t("en", "tab_findings")) as tab_findings: backlog = gr.Dataframe(label="Changes tagged for review, context, or insufficient evidence") scatter = gr.Plot(value=_empty_plot()) graph = gr.Plot(value=_empty_plot()) with gr.Tab(t("en", "tab_evidence")) as tab_evidence: feedback = gr.Radio(choices=_feedback_choices("en"), value=_feedback_choices("en")[3], label=t("en", "feedback")) timeline = gr.Plot(value=_empty_plot()) evidence = gr.Dataframe(label="Redacted evidence events") with gr.Row(): zip_out = gr.File(label="CSV / JSON bundle") json_out = gr.File(label="JSON report") with gr.Tab(t("en", "tab_compare")) as tab_compare: comparison = gr.Dataframe(label="AriaCloudTrail vs rule-severity vs role/time vs correlation vs maintenance-aware") cmp_plot = gr.Plot(value=_empty_plot()) cal_plot = gr.Plot(value=_empty_plot()) history = gr.Dataframe(label="Previous vs current KPIs") with gr.Tab(t("en", "tab_method")) as tab_method: method_md = gr.Markdown(t("en", "method_body")) gr.Markdown( "Organization: [AriaAICompany](https://huggingface.co/AriaAICompany) · " "Dataset: [cloudtrail-lab](https://huggingface.co/datasets/AriaAICompany/cloudtrail-lab) · " "Site: [aria-ai.ir](https://aria-ai.ir/)" ) result_state = gr.State(None) previous = gr.State(None) _ = feedback outputs_lang = [ header, run_btn, cancel_btn, reset_btn, load_btn, scenario, threshold, hide_context, actor_filter, resource_filter, change_filter, note, kpis, advanced, method_md, hint, extra, log_file, feedback, tab_data, tab_findings, tab_evidence, tab_compare, tab_method, ] lang.change(apply_language, inputs=[lang], outputs=outputs_lang) demo.load(apply_language, inputs=[lang], outputs=outputs_lang) load_btn.click(load_sample_ui, inputs=[scenario], outputs=[events, gold, full_events]) reset_btn.click( reset_defaults, outputs=[events, gold, full_events, threshold, hide_context, actor_filter, resource_filter, change_filter, extra], ) outputs_run = [ kpis, status, reasons, card, state_md, backlog, comparison, timeline, cmp_plot, cal_plot, scatter, graph, zip_out, json_out, history, evidence, result_state, previous, ] click = run_btn.click( run_live, inputs=[ lang, scenario, threshold, hide_context, actor_filter, resource_filter, change_filter, events, gold, full_events, extra, log_file, previous, ], outputs=outputs_run, ) cancel_btn.click(None, cancels=[click]) backlog.select(show_finding, inputs=[backlog, lang, result_state], outputs=[card, state_md, evidence, timeline]) _ = tabs return demo