v0.5: deep quality refactor (P0+P1+P2)

- Split dr-chief-editor (Phase 3 read-only) vs new dr-editor-in-chief (Opus, Phase 4 lead)
- New dr-translator (en->zh) and new humanizer-cn / output-hygiene / en-zh-translation skills
- Switch to English working language (Phase 2-3), final Chinese translation (Phase 4)
- /dr-init: add report title proposals + word budget mode
- /dr-frame: bilingual framework
- /dr-finalize: new chain editor->translator->polisher->reporter
- report-template.py: widows/orphans/keepWithNext, 3-color hierarchy, confidentiality banner
- dr-reporter: mandatory citations backfill + output hygiene check
- dr-pm: batch-level context compression via manifest.batches_summary
- mckinsey-method: SCQA only for Executive Summary + chapter intros (no explicit labels)
- length-budget: 4 word-budget modes + en/zh 1:1.4 ratio
This commit is contained in:
kai
2026-04-21 13:02:54 +08:00
parent 4a38f6bed1
commit a092af4398
20 changed files with 3376 additions and 1246 deletions
+238 -237
View File
@@ -1,24 +1,22 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Deep Research 中文 PDF 报告模板(ReportLab 基础版
Deep Research 中文 PDF 报告模板(ReportLab v0.5
v0.5 升级点(对比 v0.4):
- 封面:主标题 + 副标题 + 保密标识(红色)+ 编制日期(参考 9MW1911 风格)
- 分页规则:widows=2, orphans=2, keepWithNext 防孤行寡行
- 表格:splitByRow=True, repeatRows=1 防断页
- 颜色层次:h1 深蓝 / h2 蓝 / h3 深灰
- 段落首行缩进 2 字符,行高 × 1.7
- 参考文献:自动解析 "## 参考文献" / "## References" 段落
用法:
python3 report-template.py \
--input projects/<slug>/phase4/final.md \
uv run python3 report-template.py \
--input projects/<slug>/phase4/final_zh.md \
--manifest projects/<slug>/manifest.json \
--output projects/<slug>/phase4/final.pdf \
--fonts-dir .opencode/templates/fonts
依赖:
pip install reportlab markdown-it-py
设计原则:
1. 字体集中注册,样式集中管理(StyleSheet),避免字号不一
2. 思源宋 = 正文;思源黑 = 标题/UI;霞鹜文楷 = 引文/摘要
3. Markdown → ReportLab Flowables,保留结构化信息
4. 基础版支持:封面 / 目录 / 正文(h1-h3 / 段落 / 列表 / 引用 / 表格 / 图片)/ 参考文献
5. 基础版暂不支持:PDF 书签、交叉引用、附录自动生成(后续补齐)
"""
from __future__ import annotations
@@ -29,14 +27,14 @@ import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Tuple
from typing import List, Optional
try:
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT, TA_RIGHT
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, StyleSheet1
from reportlab.lib.units import cm, mm
from reportlab.lib.units import cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
@@ -52,48 +50,45 @@ try:
TableStyle,
)
except ImportError:
print("❌ 缺少依赖:pip install reportlab", file=sys.stderr)
print("ERROR: missing reportlab. Run: uv sync", file=sys.stderr)
sys.exit(1)
# ============================================================
# 字体注册
# Font registration
# ============================================================
FONT_MAP = {
# 逻辑名 -> 文件名(优先 ttf/ 子目录的 TrueType 转换版,兼容 ReportLab
"SrcSerif": "ttf/SourceHanSerifSC-Regular.ttf",
"SrcSerif-Bold": "ttf/SourceHanSerifSC-Bold.ttf",
"SrcSans-Light": "ttf/SourceHanSansSC-Light.ttf",
"SrcSans-Medium": "ttf/SourceHanSansSC-Medium.ttf",
"SrcSans-Bold": "ttf/SourceHanSansSC-Bold.ttf",
"SrcSans-Heavy": "ttf/SourceHanSansSC-Heavy.ttf",
"Kai": "LXGWWenKai-Regular.ttf",
"SrcSerif": "SourceHanSerifSC-Regular.otf",
"SrcSerif-Bold": "SourceHanSerifSC-Bold.otf",
"SrcSans-Light": "SourceHanSansSC-Light.otf",
"SrcSans-Medium": "SourceHanSansSC-Medium.otf",
"SrcSans-Bold": "SourceHanSansSC-Bold.otf",
"SrcSans-Heavy": "SourceHanSansSC-Heavy.otf",
"Kai": "LXGWWenKai-Regular.ttf",
}
def register_fonts(fonts_dir: Path) -> None:
"""注册所有中文字体。失败则 exit(1)。"""
missing = []
for logical, filename in FONT_MAP.items():
font_path = fonts_dir / filename
if not font_path.exists():
missing.append(str(font_path))
for logical, fname in FONT_MAP.items():
path = fonts_dir / fname
if not path.exists():
missing.append(str(path))
continue
try:
pdfmetrics.registerFont(TTFont(logical, str(font_path)))
pdfmetrics.registerFont(TTFont(logical, str(path)))
except Exception as e:
print(f"❌ 字体注册失败:{logical} ({font_path}): {e}", file=sys.stderr)
print(f"ERROR: font registration failed {logical} ({path}): {e}", file=sys.stderr)
sys.exit(1)
if missing:
print("❌ 缺少字体文件:", file=sys.stderr)
print("ERROR: missing fonts:", file=sys.stderr)
for m in missing:
print(f" - {m}", file=sys.stderr)
print("\n请运行:bash .opencode/templates/fonts/download-fonts.sh", file=sys.stderr)
print(f" - {m}", file=sys.stderr)
print("\nRun: bash .opencode/templates/fonts/download-fonts.sh", file=sys.stderr)
sys.exit(1)
# 注册字体族(粗体自动映射)
pdfmetrics.registerFontFamily(
"SrcSerif",
normal="SrcSerif",
@@ -111,56 +106,57 @@ def register_fonts(fonts_dir: Path) -> None:
# ============================================================
# 样式表(集中管理)
# StyleSheet (centralized styles)
# ============================================================
def build_styles() -> StyleSheet1:
"""构建所有段落样式。字号、行高在此唯一定义。"""
ss = StyleSheet1()
# 正文
# Body
ss.add(ParagraphStyle(
name="body",
fontName="SrcSerif",
fontSize=10.5,
leading=18,
alignment=TA_JUSTIFY,
firstLineIndent=21, # 首行缩进 2 字符
spaceBefore=2,
spaceAfter=2,
firstLineIndent=21,
spaceBefore=3,
spaceAfter=3,
textColor=colors.HexColor("#1a1a1a"),
wordWrap="CJK",
allowWidows=0,
allowOrphans=0,
))
# 一级标题(章)
# H1 (chapter) - page break before, deep blue
ss.add(ParagraphStyle(
name="h1",
fontName="SrcSans-Bold",
fontSize=18,
leading=28,
alignment=TA_LEFT,
spaceBefore=20,
spaceAfter=12,
spaceBefore=0,
spaceAfter=14,
textColor=colors.HexColor("#1e3a8a"),
keepWithNext=True,
keepWithNext=1,
wordWrap="CJK",
))
# 二级标题(section
# H2 (section) - blue, no page break, keep with next
ss.add(ParagraphStyle(
name="h2",
fontName="SrcSans-Bold",
fontSize=14,
leading=22,
alignment=TA_LEFT,
spaceBefore=14,
spaceBefore=16,
spaceAfter=8,
textColor=colors.HexColor("#1e40af"),
keepWithNext=True,
textColor=colors.HexColor("#2c5282"),
keepWithNext=1,
wordWrap="CJK",
))
# 三级标题(sub-section
# H3 (subsection) - dark gray
ss.add(ParagraphStyle(
name="h3",
fontName="SrcSans-Medium",
@@ -170,11 +166,11 @@ def build_styles() -> StyleSheet1:
spaceBefore=10,
spaceAfter=6,
textColor=colors.HexColor("#374151"),
keepWithNext=True,
keepWithNext=1,
wordWrap="CJK",
))
# 引文 / 摘要(霞鹜文楷)
# Quote - Kai (Wenkai), light background
ss.add(ParagraphStyle(
name="quote",
fontName="Kai",
@@ -186,14 +182,14 @@ def build_styles() -> StyleSheet1:
spaceBefore=6,
spaceAfter=6,
textColor=colors.HexColor("#4b5563"),
borderWidth=0,
borderPadding=8,
borderColor=colors.HexColor("#d1d5db"),
backColor=colors.HexColor("#f9fafb"),
wordWrap="CJK",
allowWidows=0,
allowOrphans=0,
))
# 图表标题
# Caption (figure/table title)
ss.add(ParagraphStyle(
name="caption",
fontName="SrcSans-Medium",
@@ -201,12 +197,12 @@ def build_styles() -> StyleSheet1:
leading=13,
alignment=TA_CENTER,
spaceBefore=4,
spaceAfter=10,
spaceAfter=12,
textColor=colors.HexColor("#6b7280"),
wordWrap="CJK",
))
# 脚注 / 参考文献
# Footnote (references)
ss.add(ParagraphStyle(
name="footnote",
fontName="SrcSerif",
@@ -214,31 +210,23 @@ def build_styles() -> StyleSheet1:
leading=13,
alignment=TA_JUSTIFY,
leftIndent=20,
firstLineIndent=-20, # 悬挂缩进
firstLineIndent=-20, # hanging indent
spaceAfter=4,
textColor=colors.HexColor("#374151"),
wordWrap="CJK",
allowWidows=0,
allowOrphans=0,
))
# 页眉页脚
ss.add(ParagraphStyle(
name="header-footer",
fontName="SrcSans-Light",
fontSize=8,
leading=12,
alignment=TA_CENTER,
textColor=colors.HexColor("#9ca3af"),
))
# 封面大标题
# Cover - main title (heavy, centered, large)
ss.add(ParagraphStyle(
name="cover-title",
fontName="SrcSans-Heavy",
fontSize=32,
leading=42,
fontSize=28,
leading=40,
alignment=TA_CENTER,
spaceBefore=12,
spaceAfter=12,
spaceBefore=10,
spaceAfter=10,
textColor=colors.HexColor("#0f172a"),
wordWrap="CJK",
))
@@ -246,15 +234,29 @@ def build_styles() -> StyleSheet1:
ss.add(ParagraphStyle(
name="cover-subtitle",
fontName="SrcSans-Medium",
fontSize=16,
fontSize=15,
leading=24,
alignment=TA_CENTER,
spaceBefore=8,
spaceBefore=6,
spaceAfter=30,
textColor=colors.HexColor("#475569"),
wordWrap="CJK",
))
# Cover - confidentiality marker (red)
ss.add(ParagraphStyle(
name="cover-confidential",
fontName="SrcSans-Bold",
fontSize=11,
leading=16,
alignment=TA_CENTER,
spaceBefore=8,
spaceAfter=8,
textColor=colors.HexColor("#dc2626"),
wordWrap="CJK",
))
# Cover - meta info (date, version, author)
ss.add(ParagraphStyle(
name="cover-meta",
fontName="SrcSerif",
@@ -265,34 +267,46 @@ def build_styles() -> StyleSheet1:
wordWrap="CJK",
))
# 列表
# Summary (Executive Summary)
ss.add(ParagraphStyle(
name="summary",
fontName="SrcSerif",
fontSize=11,
leading=20,
alignment=TA_JUSTIFY,
firstLineIndent=22,
spaceBefore=4,
spaceAfter=4,
textColor=colors.HexColor("#1a1a1a"),
wordWrap="CJK",
allowWidows=0,
allowOrphans=0,
))
# Bullet list
ss.add(ParagraphStyle(
name="bullet",
parent=ss["body"],
firstLineIndent=0,
leftIndent=20,
bulletIndent=6,
leftIndent=24,
bulletIndent=8,
))
return ss
# ============================================================
# Markdown 轻量解析(基础版)
# Markdown parser (lightweight)
# ============================================================
@dataclass
class Block:
kind: str # h1 / h2 / h3 / p / quote / bullet / image / table / hr
content: str # 原始 Markdown 内容
content: str
meta: Optional[dict] = None
def parse_markdown(md_text: str) -> List[Block]:
"""
极简 Markdown 解析器,输出扁平 Block 列表。
不支持嵌套结构,复杂情况后续可接 markdown-it-py。
"""
blocks: List[Block] = []
lines = md_text.split("\n")
i = 0
@@ -300,27 +314,26 @@ def parse_markdown(md_text: str) -> List[Block]:
line = lines[i]
stripped = line.strip()
# 空行
if not stripped:
i += 1
continue
# 水平线 / 分页
# hr / page break
if stripped in ("---", "***", "___"):
blocks.append(Block(kind="hr", content=""))
i += 1
continue
# 标题
# Heading
if stripped.startswith("#"):
m = re.match(r"^(#{1,6})\s+(.+)$", stripped)
if m:
level = min(len(m.group(1)), 3) # h4+ 降级为 h3
level = min(len(m.group(1)), 3)
blocks.append(Block(kind=f"h{level}", content=m.group(2).strip()))
i += 1
continue
# 图片
# Image
m = re.match(r"^!\[([^\]]*)\]\(([^)]+)\)", stripped)
if m:
blocks.append(Block(
@@ -331,7 +344,7 @@ def parse_markdown(md_text: str) -> List[Block]:
i += 1
continue
# 引用
# Blockquote
if stripped.startswith(">"):
quote_lines = []
while i < len(lines) and lines[i].strip().startswith(">"):
@@ -340,39 +353,36 @@ def parse_markdown(md_text: str) -> List[Block]:
blocks.append(Block(kind="quote", content="\n".join(quote_lines)))
continue
# 无序列表
# Unordered list
if re.match(r"^[-*+]\s+", stripped):
item_lines = []
while i < len(lines) and re.match(r"^[-*+]\s+", lines[i].strip()):
item_lines.append(re.sub(r"^[-*+]\s+", "", lines[i].strip()))
i += 1
for item in item_lines:
item = re.sub(r"^[-*+]\s+", "", lines[i].strip())
blocks.append(Block(kind="bullet", content=item))
continue
# 有序列表
if re.match(r"^\d+\.\s+", stripped):
item_lines = []
while i < len(lines) and re.match(r"^\d+\.\s+", lines[i].strip()):
item_lines.append(re.sub(r"^\d+\.\s+", "", lines[i].strip()))
i += 1
for idx, item in enumerate(item_lines, 1):
blocks.append(Block(kind="bullet", content=f"{idx}. {item}"))
continue
# 表格(简单识别:有 |
# Ordered list
if re.match(r"^\d+\.\s+", stripped):
idx = 1
while i < len(lines) and re.match(r"^\d+\.\s+", lines[i].strip()):
item = re.sub(r"^\d+\.\s+", "", lines[i].strip())
blocks.append(Block(kind="bullet", content=f"{idx}. {item}"))
i += 1
idx += 1
continue
# Table
if "|" in line and i + 1 < len(lines) and re.match(r"^\s*\|?\s*:?-+:?\s*\|", lines[i + 1]):
table_lines = [line]
i += 1
# 跳过分隔线
i += 1
while i < len(lines) and "|" in lines[i]:
i += 1 # skip separator
while i < len(lines) and "|" in lines[i] and lines[i].strip():
table_lines.append(lines[i])
i += 1
blocks.append(Block(kind="table", content="\n".join(table_lines)))
continue
# 普通段落(合并连续行)
# Paragraph (merge continuation lines)
para_lines = [line]
i += 1
while i < len(lines) and lines[i].strip() and not (
@@ -389,32 +399,28 @@ def parse_markdown(md_text: str) -> List[Block]:
def md_inline_to_rl(text: str) -> str:
"""Markdown inline → ReportLab mini HTML."""
# 粗体 **text**
text = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", text)
# 斜体 *text*
text = re.sub(r"(?<!\*)\*([^*]+)\*(?!\*)", r"<i>\1</i>", text)
# 行内代码 `code`
text = re.sub(r"`([^`]+)`", r'<font face="Courier">\1</font>', text)
# 引用标签 [src_001] → 上标
text = re.sub(r"\[(src_\d+)\]", r"<super><font size=8>[\1]</font></super>", text)
# 链接 [text](url) 保留 text
text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1", text)
return text
# ============================================================
# 文档模板与渲染
# Document builders
# ============================================================
@dataclass
class Manifest:
slug: str
topic: str
subtitle: str
report_title: str
report_subtitle: str
author: str
date: str
type: str
version: str
type: str
confidentiality: str
disclaimer: str
@classmethod
@@ -422,85 +428,134 @@ class Manifest:
data = json.loads(path.read_text(encoding="utf-8"))
return cls(
slug=data.get("slug", ""),
topic=data.get("topic", "未命名研究"),
subtitle=data.get("subtitle", ""),
report_title=data.get("report_title") or data.get("topic", "未命名研究报告"),
report_subtitle=data.get("report_subtitle", ""),
author=data.get("author", "Deep Research 系统"),
date=data.get("date", ""),
type=data.get("type", ""),
version=data.get("version", "1.0"),
disclaimer=data.get("disclaimer", ""),
type=data.get("type", ""),
confidentiality=data.get("confidentiality", ""),
disclaimer=data.get("disclaimer", "本报告基于公开信息与 AI 辅助研究生成,仅供参考,不构成投资或医疗建议。"),
)
def make_page_decorator(manifest: Manifest, styles: StyleSheet1):
"""生成普通页的页眉页脚绘制函数。"""
def make_page_decorator(manifest: Manifest):
"""Returns function drawing header/footer for normal pages."""
short_title = manifest.report_title[:30]
def draw(canvas, doc):
canvas.saveState()
# 页眉
# Header: short title left, report type right, gray separator
canvas.setFont("SrcSans-Light", 8)
canvas.setFillColor(colors.HexColor("#9ca3af"))
canvas.drawString(2 * cm, A4[1] - 1.2 * cm, manifest.topic[:30])
canvas.drawRightString(A4[0] - 2 * cm, A4[1] - 1.2 * cm, manifest.type)
canvas.drawString(2 * cm, A4[1] - 1.2 * cm, short_title)
if manifest.type:
canvas.drawRightString(A4[0] - 2 * cm, A4[1] - 1.2 * cm, manifest.type)
canvas.setStrokeColor(colors.HexColor("#e5e7eb"))
canvas.setLineWidth(0.5)
canvas.line(2 * cm, A4[1] - 1.4 * cm, A4[0] - 2 * cm, A4[1] - 1.4 * cm)
# 页脚
# Footer: page number centered
canvas.setFont("SrcSans-Light", 8)
canvas.drawCentredString(A4[0] / 2, 1.2 * cm, f"{doc.page}")
canvas.restoreState()
return draw
def build_cover(manifest: Manifest, styles: StyleSheet1) -> List:
"""封面页 flowables。"""
story = []
story.append(Spacer(1, 4 * cm))
story.append(Paragraph(manifest.topic, styles["cover-title"]))
if manifest.subtitle:
story.append(Paragraph(manifest.subtitle, styles["cover-subtitle"]))
story.append(Spacer(1, 6 * cm))
story.append(Paragraph(f"<b>类型</b>{manifest.type}", styles["cover-meta"]))
story.append(Paragraph(f"<b>作者</b>{manifest.author}", styles["cover-meta"]))
story.append(Paragraph(f"<b>日期</b>{manifest.date}", styles["cover-meta"]))
story.append(Paragraph(f"<b>版本</b>v{manifest.version}", styles["cover-meta"]))
story.append(Paragraph(manifest.report_title, styles["cover-title"]))
if manifest.report_subtitle:
story.append(Paragraph(manifest.report_subtitle, styles["cover-subtitle"]))
story.append(Spacer(1, 5 * cm))
if manifest.confidentiality:
story.append(Paragraph(manifest.confidentiality, styles["cover-confidential"]))
story.append(Spacer(1, 2 * cm))
story.append(Paragraph(f"类型:{manifest.type}", styles["cover-meta"]))
story.append(Paragraph(f"作者:{manifest.author}", styles["cover-meta"]))
story.append(Paragraph(f"编制日期:{manifest.date}", styles["cover-meta"]))
story.append(Paragraph(f"版本:v{manifest.version}", styles["cover-meta"]))
story.append(PageBreak())
return story
def build_disclaimer(manifest: Manifest, styles: StyleSheet1) -> List:
"""免责声明页。"""
story = []
story.append(Paragraph("免责声明", styles["h1"]))
story.append(Spacer(1, 0.5 * cm))
disclaimer = manifest.disclaimer or (
"本报告基于公开信息与 AI 辅助研究生成,仅供参考,不构成投资、医疗或法律建议。"
"数据截至报告生成日,使用者应自行核实关键数据并评估时效性。"
)
story.append(Paragraph(disclaimer, styles["body"]))
story.append(Paragraph(manifest.disclaimer, styles["body"]))
story.append(PageBreak())
return story
def render_table(md_table: str, styles: StyleSheet1) -> Table:
rows = []
for line in md_table.strip().split("\n"):
line = line.strip().strip("|")
cells = [c.strip() for c in line.split("|")]
rows.append([Paragraph(md_inline_to_rl(c), styles["body"]) for c in cells])
table = Table(rows, repeatRows=1, splitByRow=True)
table.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e0e7ff")),
("FONTNAME", (0, 0), (-1, 0), "SrcSans-Bold"),
("FONTSIZE", (0, 0), (-1, -1), 9.5),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#cbd5e1")),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("LEFTPADDING", (0, 0), (-1, -1), 6),
("RIGHTPADDING", (0, 0), (-1, -1), 6),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
]))
return table
def build_body(blocks: List[Block], base_dir: Path, styles: StyleSheet1) -> List:
"""正文 flowables。"""
"""
Render markdown blocks to flowables.
v0.5 upgrade: h1 triggers PageBreak; h2/h3 use keepWithNext; tables splitByRow.
"""
story = []
first_h1 = True
# Track whether we're in a special section that uses different body style
in_summary = False
for block in blocks:
if block.kind == "h1":
# h1 前强制分页(每章新起一页)
story.append(PageBreak())
story.append(Paragraph(md_inline_to_rl(block.content), styles["h1"]))
# PageBreak before every h1 EXCEPT the very first
if not first_h1:
story.append(PageBreak())
first_h1 = False
# Check if this is Executive Summary / 执行摘要 - use summary style for following body
content = block.content
if any(keyword in content for keyword in ["执行摘要", "Executive Summary", "管理层摘要"]):
in_summary = True
else:
in_summary = False
story.append(Paragraph(md_inline_to_rl(content), styles["h1"]))
elif block.kind == "h2":
story.append(Paragraph(md_inline_to_rl(block.content), styles["h2"]))
elif block.kind == "h3":
story.append(Paragraph(md_inline_to_rl(block.content), styles["h3"]))
elif block.kind == "p":
story.append(Paragraph(md_inline_to_rl(block.content), styles["body"]))
style = styles["summary"] if in_summary else styles["body"]
story.append(Paragraph(md_inline_to_rl(block.content), style))
elif block.kind == "quote":
story.append(Paragraph(md_inline_to_rl(block.content), styles["quote"]))
elif block.kind == "bullet":
story.append(Paragraph("" + md_inline_to_rl(block.content), styles["bullet"]))
elif block.kind == "hr":
story.append(PageBreak())
story.append(Spacer(1, 0.3 * cm))
elif block.kind == "image":
img_path = base_dir / block.content
if img_path.exists():
@@ -521,85 +576,26 @@ def build_body(blocks: List[Block], base_dir: Path, styles: StyleSheet1) -> List
))
elif block.kind == "table":
try:
table_flow = render_table(block.content, styles)
story.append(table_flow)
story.append(render_table(block.content, styles))
except Exception as e:
story.append(Paragraph(f"[表格渲染失败: {e}]", styles["caption"]))
return story
def render_table(md_table: str, styles: StyleSheet1) -> Table:
"""Markdown 表格 → ReportLab Table。自动计算均匀列宽,避免负宽度问题。"""
rows = []
body_style = ParagraphStyle(
name="table-body",
fontName="SrcSerif",
fontSize=9,
leading=14,
wordWrap="CJK",
)
header_style = ParagraphStyle(
name="table-header",
fontName="SrcSans-Bold",
fontSize=9,
leading=14,
wordWrap="CJK",
)
num_cols = 0
for i, line in enumerate(md_table.strip().split("\n")):
line = line.strip().strip("|")
# 跳过分隔行(如 :---: | --- 等)
if re.match(r"^[\s\-:|]+$", line):
continue
cells = [c.strip() for c in line.split("|")]
if not any(cells):
continue
num_cols = max(num_cols, len(cells))
# 第一行(表头)用 header_style
style = header_style if not rows else body_style
rows.append([Paragraph(md_inline_to_rl(c), style) for c in cells])
if not rows:
return Table([[Paragraph("", body_style)]])
# 可用宽度:A4(595pt) - 左右各2cm边距 = 595 - 4*28.35 ≈ 481pt
available_width = 17 * cm # 约 481pt,保守取 17cm
col_width = available_width / max(num_cols, 1)
col_widths = [col_width] * num_cols
# 统一列数(补齐短行)
for row in rows:
while len(row) < num_cols:
row.append(Paragraph("", body_style))
table = Table(rows, colWidths=col_widths, repeatRows=1)
table.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e0e7ff")),
("FONTNAME", (0, 0), (-1, 0), "SrcSans-Bold"),
("FONTSIZE", (0, 0), (-1, -1), 9),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#cbd5e1")),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("LEFTPADDING", (0, 0), (-1, -1), 4),
("RIGHTPADDING", (0, 0), (-1, -1), 4),
("TOPPADDING", (0, 0), (-1, -1), 3),
("BOTTOMPADDING", (0, 0), (-1, -1), 3),
]))
return table
# ============================================================
# 主入口
# Main
# ============================================================
def main():
parser = argparse.ArgumentParser(description="Deep Research ReportLab PDF 生成器")
parser.add_argument("--input", required=True, help="输入 Markdown 路径")
parser.add_argument("--manifest", required=True, help="manifest.json 路径")
parser.add_argument("--output", required=True, help="输出 PDF 路径")
parser = argparse.ArgumentParser(description="Deep Research PDF Generator (v0.5)")
parser.add_argument("--input", required=True, help="Input markdown (final_zh.md)")
parser.add_argument("--manifest", required=True, help="manifest.json path")
parser.add_argument("--output", required=True, help="Output PDF path")
parser.add_argument(
"--fonts-dir",
default=".opencode/templates/fonts",
help="字体目录(默认 .opencode/templates/fonts",
help="Fonts directory",
)
args = parser.parse_args()
@@ -608,65 +604,70 @@ def main():
output_path = Path(args.output)
fonts_dir = Path(args.fonts_dir)
# 校验输入
for p, label in [(md_path, "Markdown"), (manifest_path, "Manifest"), (fonts_dir, "字体目录")]:
# Validate inputs
for p, label in [(md_path, "Markdown"), (manifest_path, "Manifest"), (fonts_dir, "Fonts dir")]:
if not p.exists():
print(f" {label} 不存在:{p}", file=sys.stderr)
print(f"ERROR: {label} not found: {p}", file=sys.stderr)
sys.exit(1)
# 注册字体
# Register fonts and build styles
register_fonts(fonts_dir)
styles = build_styles()
manifest = Manifest.load(manifest_path)
# 解析 Markdown
# Parse markdown
md_text = md_path.read_text(encoding="utf-8")
blocks = parse_markdown(md_text)
# 构建文档
# Build document
doc = BaseDocTemplate(
str(output_path),
pagesize=A4,
leftMargin=2 * cm,
rightMargin=2 * cm,
leftMargin=2.2 * cm,
rightMargin=2.2 * cm,
topMargin=2 * cm,
bottomMargin=2 * cm,
title=manifest.topic,
title=manifest.report_title,
author=manifest.author,
subject=manifest.type,
)
# 两个 Frame:封面(无页眉页脚) / 正文
# Frames
cover_frame = Frame(
2 * cm, 2 * cm,
A4[0] - 4 * cm, A4[1] - 4 * cm,
id="cover",
)
normal_frame = Frame(
2 * cm, 2 * cm,
A4[0] - 4 * cm, A4[1] - 4 * cm,
2.2 * cm, 2 * cm,
A4[0] - 4.4 * cm, A4[1] - 4 * cm,
id="normal",
)
decorator = make_page_decorator(manifest, styles)
decorator = make_page_decorator(manifest)
doc.addPageTemplates([
PageTemplate(id="cover", frames=[cover_frame]),
PageTemplate(id="normal", frames=[normal_frame], onPage=decorator),
])
# 构建 story
# Assemble story
story: List = []
story.extend(build_cover(manifest, styles))
story.append(NextPageTemplate("normal"))
story.extend(build_disclaimer(manifest, styles))
story.extend(build_body(blocks, md_path.parent, styles))
# 出稿
# Build
doc.build(story)
# Report
size = output_path.stat().st_size
print(f"PDF 生成成功:{output_path}")
print(f" 文件大小:{size / 1024:.1f} KB")
print(f" 字体数量:{len(FONT_MAP)}")
print(f" Block 数:{len(blocks)}")
print(f"PDF generated: {output_path}")
print(f" Size: {size / 1024:.1f} KB")
print(f" Fonts: {len(FONT_MAP)}")
print(f" Blocks: {len(blocks)}")
if size < 500 * 1024:
print(f" WARNING: PDF size < 500KB, fonts may not be properly embedded", file=sys.stderr)
if __name__ == "__main__":