Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ jobs:
run: uv python install 3.14
- name: Install dependencies
run: uv sync --locked
- name: Install CJK font for PDF export
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends fonts-noto-cjk
- name: Lint and format
run: |
uv run ruff check src tests
Expand Down
1 change: 1 addition & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ dependencies = [
# AMP heartbeat 直投平台 Kafka(wt.ioa.pub:19092)。纯 Python,无需编译。
# 未安装时 amp.py 自动退化为只写本地 NDJSON,由 Fluent Bit 转发。
"kafka-python>=3.0",
"reportlab>=5.1.0",
]

# Production Wutong wheels are intentionally not a repository dependency:
Expand Down
186 changes: 186 additions & 0 deletions backend/src/agent_attack_lab/battle_pdf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
"""战局清单的 PDF 导出。

与问卷报告共用排版基建(字体解析、配色、页脚)——这些是通用的 PDF 元件,
真正的报告差异在表格列与文案上。战局数据量比问卷大,所以固定按创建时间倒序取前 N 条,
并在页首写清"共 N 条",避免导出后看不出截断。
"""

from __future__ import annotations

import io
from datetime import datetime
from typing import Any

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.platypus import (
BaseDocTemplate,
Frame,
PageTemplate,
Paragraph,
Spacer,
Table,
TableStyle,
)

from agent_attack_lab.survey_pdf import (
ACCENT,
FILL,
FONT_BOLD,
FONT_NAME,
INK,
RULE,
PdfFontUnavailable,
_footer,
_SectionTitle,
_styles,
ensure_font,
)

__all__ = ["MAX_ROWS", "PdfFontUnavailable", "build_battles_pdf"]

MAX_ROWS = 500
EMPTY_CELL = "—"

STATUS_LABELS = {
"pending": "待开始",
"running": "进行中",
"completed": "已完成",
"failed": "失败",
}
DIFFICULTY_LABELS = {"low": "低", "mid": "中", "high": "高"}
VERDICT_LABELS = {
"attacker_won": "攻击方胜",
"defender_won": "防守方胜",
"undetermined": "未判定",
}


def _cell(value: Any, fallback: str = EMPTY_CELL) -> str:
text = "" if value is None else str(value).strip()
return text or fallback


def _clip(text: str, limit: int) -> str:
return text if len(text) <= limit else text[: limit - 1] + "…"


def _table(rows: list[dict[str, Any]]) -> Table:
head_style = ParagraphStyle(
"th", fontName=FONT_BOLD, fontSize=8.6, leading=11, textColor=colors.white
)
cell_style = ParagraphStyle(
"td", fontName=FONT_NAME, fontSize=8.4, leading=11.5, textColor=INK
)
header = [
Paragraph("战局", head_style),
Paragraph("对抗主题", head_style),
Paragraph("创建时间", head_style),
Paragraph("状态", head_style),
Paragraph("难度", head_style),
Paragraph("裁决", head_style),
]
body = [header]
for row in rows:
code = _cell(row.get("code") or row.get("id"))
raw = _cell(row.get("createdAt"), "")
stamp = f"{raw[5:10]} {raw[11:16]}" if len(raw) >= 16 else raw
body.append(
[
Paragraph(code, cell_style),
Paragraph(_clip(_cell(row.get("topic")), 60), cell_style),
Paragraph(stamp or EMPTY_CELL, cell_style),
Paragraph(
STATUS_LABELS.get(str(row.get("status")), _cell(row.get("status"))),
cell_style,
),
Paragraph(
DIFFICULTY_LABELS.get(
str(row.get("difficulty")), _cell(row.get("difficulty"))
),
cell_style,
),
Paragraph(
VERDICT_LABELS.get(str(row.get("verdict")), EMPTY_CELL), cell_style
),
]
)
# 合计 174mm:A4 210mm 减左右各 18mm,超出会压到页边距外。
table = Table(
body,
colWidths=[26 * mm, 58 * mm, 24 * mm, 20 * mm, 16 * mm, 30 * mm],
repeatRows=1,
)
table.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), ACCENT),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, FILL]),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("TOPPADDING", (0, 0), (-1, -1), 5),
("BOTTOMPADDING", (0, 0), (-1, -1), 5),
("LEFTPADDING", (0, 0), (-1, -1), 5),
("RIGHTPADDING", (0, 0), (-1, -1), 5),
("GRID", (0, 0), (-1, -1), 0.4, RULE),
]
)
)
return table


def build_battles_pdf(
rows: list[dict[str, Any]],
total: int | None = None,
generated_at: str | None = None,
) -> bytes:
"""把战局列表渲染成 PDF。``total`` 为库里的总数,用于页首标注是否被截断。"""
ensure_font()
styles = _styles()
buffer = io.BytesIO()
doc = BaseDocTemplate(
buffer,
pagesize=A4,
leftMargin=18 * mm,
rightMargin=18 * mm,
topMargin=18 * mm,
bottomMargin=22 * mm,
title="攻防战局清单",
author="智能体攻防实验室",
)
frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id="body")
doc.addPageTemplates([PageTemplate(id="report", frames=[frame], onPage=_footer)])
width = doc.width
stamp = generated_at or datetime.now().strftime("%Y-%m-%d %H:%M")
shown = len(rows)
library_total = shown if total is None else total
truncated = library_total > shown

story: list[Any] = [
Paragraph("攻防战局清单", styles["title"]),
Spacer(1, 6),
Paragraph(
f"智能体攻防实验室 · 共 {library_total} 场"
+ (f"(本表列出最近 {shown} 场)" if truncated else "")
+ f" · 生成于 {stamp}",
styles["subtitle"],
),
Spacer(1, 14),
_SectionTitle("战局列表", width),
Spacer(1, 6),
]

if not rows:
story.append(Paragraph("当前没有任何战局记录。", styles["body"]))
else:
story += [
_table(rows),
Spacer(1, 6),
Paragraph(
"按创建时间倒序;标题过长会截断,完整内容见后台对应战局详情。",
styles["small"],
),
]
doc.build(story)
return buffer.getvalue()
28 changes: 28 additions & 0 deletions backend/src/agent_attack_lab/routers/battles.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,34 @@ def list_battles(
]


@router.get(
"/api/battles/export.pdf",
summary="导出战局清单 PDF",
description="按创建时间倒序导出最近战局,用于材料与存档;与 CSV 导出并存。",
tags=["战局接口"],
dependencies=[Depends(security.read_auth_dependency)],
)
def export_battles_pdf() -> Response:
from agent_attack_lab import battle_pdf

total = state.battle_store.count()
rows = state.battle_store.list(limit=battle_pdf.MAX_ROWS, offset=0)
try:
payload = battle_pdf.build_battles_pdf(rows, total=total)
except battle_pdf.PdfFontUnavailable as exc: # 由 survey_pdf 透出的同一异常类型
raise HTTPException(status_code=503, detail=str(exc)) from exc
return Response(
content=payload,
media_type="application/pdf",
headers={
"Content-Disposition": 'attachment; filename="battles.pdf"',
"Content-Length": str(len(payload)),
"X-Total-Count": str(total),
"Cache-Control": "no-store",
},
)


@router.get(
"/battles/{battle_id}/events",
summary="查询战局回放事件",
Expand Down
42 changes: 41 additions & 1 deletion backend/src/agent_attack_lab/routers/survey.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
页面由本服务托管在 ``/survey``,与提交接口同源,避免 file:// 打开时的跨域问题。
提交接口公开(问卷要发给人填),但有速率限制与字段长度约束;
读取与导出接口要求后台身份:浏览器登录会话或 ``x-api-key`` 二者其一。

导出有两种:CSV(机器读,字段齐全)与 PDF(人读,按报告排版)。
PDF 依赖中文字体,缺失时返回 503 并说明如何指定,而不是产出乱码文件。
"""

from __future__ import annotations
Expand All @@ -11,7 +14,7 @@
from typing import Any, Literal

from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import HTMLResponse, PlainTextResponse
from fastapi.responses import HTMLResponse, PlainTextResponse, Response
from pydantic import BaseModel, Field

from agent_attack_lab import security, survey
Expand Down Expand Up @@ -43,6 +46,13 @@
Willingness = Literal[
"敢,有授权就敢用", "有条件敢用(需补充验证)", "不敢,只能当参考", "完全不会用"
]
# all=完整报告;summary=结论与分布;detail=逐份明细。材料排版时可分开提交。
SurveyPart = Literal["all", "summary", "detail"]
_PART_FILENAME = {
"all": "survey-report.pdf",
"summary": "survey-summary.pdf",
"detail": "survey-detail.pdf",
}


class SurveySubmission(BaseModel):
Expand Down Expand Up @@ -113,3 +123,33 @@ def export_survey_csv() -> PlainTextResponse:
"Cache-Control": "no-store",
},
)


@router.get(
"/api/survey/export.pdf",
dependencies=[Depends(security.check_browser_or_api_auth)],
)
def export_survey_pdf(part: SurveyPart = "all") -> Response:
"""按报告格式导出问卷结果(默认汇总 + 明细一体;可只取 summary 或 detail)。"""
rows = survey.load_all()
try:
from agent_attack_lab import survey_pdf
except ImportError as exc: # reportlab 未安装时给出可执行的提示
raise HTTPException(
status_code=503,
detail=f"PDF 导出依赖不可用:{exc}。请在 backend 下执行 uv sync --locked",
) from exc
try:
payload = survey_pdf.build_survey_pdf(rows, part=part)
except survey_pdf.PdfFontUnavailable as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
return Response(
content=payload,
media_type="application/pdf",
headers={
"Content-Disposition": f'attachment; filename="{_PART_FILENAME[part]}"',
"Content-Length": str(len(payload)),
"X-Total-Count": str(len(rows)),
"Cache-Control": "no-store",
},
)
Loading
Loading