280 lines
12 KiB
Python
280 lines
12 KiB
Python
"""从 Markdown 生成 API Word 手册,沿用既有手册的样式与页面设置。
|
||
|
||
使用文档技能提供的 Python 运行;本工具不启动模型、不调用业务 API。
|
||
DOCX 输出后仍须通过 render_docx.py 渲染并逐页检查,不把保存成功当作排版验收。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
from copy import deepcopy
|
||
import hashlib
|
||
import io
|
||
import json
|
||
from pathlib import Path
|
||
import re
|
||
from zipfile import ZipFile
|
||
|
||
from docx import Document
|
||
from docx.enum.style import WD_STYLE_TYPE
|
||
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
|
||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||
from docx.oxml import OxmlElement
|
||
from docx.oxml.ns import qn
|
||
from docx.shared import Inches, Pt, RGBColor
|
||
|
||
|
||
def set_font(run, *, code=False, size=None, bold=None, color="000000"):
|
||
if code:
|
||
run.font.name = "Consolas"
|
||
run.font.color.rgb = RGBColor.from_string(color)
|
||
if size is not None:
|
||
run.font.size = Pt(size)
|
||
if bold is not None:
|
||
run.bold = bold
|
||
fonts = run._element.get_or_add_rPr().get_or_add_rFonts()
|
||
fonts.set(qn("w:eastAsia"), "Microsoft YaHei")
|
||
|
||
|
||
def inline(paragraph, text, *, size=None, bold=None, color="000000"):
|
||
for token in re.split(r"(`[^`]+`|\*\*[^*]+\*\*)", text):
|
||
if not token:
|
||
continue
|
||
code = token.startswith("`") and token.endswith("`")
|
||
strong = token.startswith("**") and token.endswith("**")
|
||
if strong:
|
||
inline(paragraph, token[2:-2], size=size, bold=True, color=color)
|
||
continue
|
||
shown = token[1:-1] if code else token[2:-2] if strong else token
|
||
run = paragraph.add_run(shown)
|
||
set_font(run, code=code, size=(min(size or 10, 9) if code else size),
|
||
bold=True if strong else bold, color=color)
|
||
|
||
|
||
def word_wrap(paragraph):
|
||
# 允许长 API 标识在单元格内换行,不向真实参数中插入零宽字符。
|
||
value = OxmlElement("w:wordWrap")
|
||
value.set(qn("w:val"), "0")
|
||
paragraph._p.get_or_add_pPr().append(value)
|
||
|
||
|
||
def columns(header):
|
||
n = len(header)
|
||
if n == 2:
|
||
if header[0] == "接口":
|
||
return [2.7, 3.8]
|
||
return [1.95, 4.55]
|
||
if n == 3:
|
||
if header[0] == "方法":
|
||
return [0.65, 5.05, 0.8]
|
||
if header[0] == "HTTP":
|
||
return [0.5, 2.0, 4.0]
|
||
if "JSON" in header[1] or "请求" in header[1]:
|
||
return [2.25, 2.2, 2.05]
|
||
return [2.1, 1.55, 2.85]
|
||
if n == 4:
|
||
if header[0] == "方法和路径":
|
||
return [2.0, 1.3, 1.2, 2.0]
|
||
if header[0] == "profile":
|
||
return [2.15, 1.55, 1.25, 1.55]
|
||
if header[2] == "默认值":
|
||
return [2.2, 0.85, 1.0, 2.45]
|
||
return [1.9, 0.85, 0.9, 2.85]
|
||
if n == 5:
|
||
return [1.75, 0.75, 0.55, 1.05, 2.4]
|
||
raise ValueError(f"Unsupported table column count: {n}")
|
||
|
||
|
||
def add_table(doc, rows, table_pattern):
|
||
widths = columns(rows[0])
|
||
table = doc.add_table(rows=1, cols=len(widths))
|
||
table._tbl.replace(table._tbl.tblPr, deepcopy(table_pattern["properties"]))
|
||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||
table.autofit = False
|
||
for col, width in zip(table.columns, widths, strict=True):
|
||
col.width = Inches(width)
|
||
for row_index, values in enumerate(rows):
|
||
row = table.rows[0] if row_index == 0 else table.add_row()
|
||
for child in list(row._tr.get_or_add_trPr()):
|
||
row._tr.trPr.remove(child)
|
||
row._tr.trPr.append(OxmlElement("w:cantSplit"))
|
||
if row_index == 0:
|
||
row._tr.trPr.append(OxmlElement("w:tblHeader"))
|
||
for cell, width, value in zip(row.cells, widths, values, strict=True):
|
||
cell.width = Inches(width)
|
||
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
|
||
fill = OxmlElement("w:shd")
|
||
fill.set(qn("w:fill"), table_pattern["header_fill"] if row_index == 0 else table_pattern["body_fills"][(row_index - 1) % 2])
|
||
cell._tc.get_or_add_tcPr().append(fill)
|
||
paragraph = cell.paragraphs[0]
|
||
pf = paragraph.paragraph_format
|
||
pf.space_before = Pt(0)
|
||
pf.space_after = Pt(1)
|
||
pf.line_spacing = 1.13
|
||
pf.keep_together = True
|
||
pf.keep_with_next = False
|
||
paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
||
word_wrap(paragraph)
|
||
inline(paragraph, value, size=9, bold=row_index == 0,
|
||
color=table_pattern["header_color"] if row_index == 0 else "000000")
|
||
spacer = doc.add_paragraph()
|
||
spacer.paragraph_format.space_after = Pt(3)
|
||
spacer.paragraph_format.space_before = Pt(0)
|
||
spacer.paragraph_format.line_spacing = 1
|
||
set_font(spacer.add_run(""), size=1)
|
||
return table
|
||
|
||
|
||
def parse_table(lines, index):
|
||
rows = []
|
||
while index < len(lines) and lines[index].startswith("|"):
|
||
line = lines[index]
|
||
if not re.fullmatch(r"\|[\s:|\-]+", line):
|
||
row = [cell.replace(r"\|", "|").strip() for cell in re.split(r"(?<!\\)\|", line.strip().strip("|"))]
|
||
if rows and len(row) != len(rows[0]):
|
||
raise ValueError(f"Markdown table columns differ at line {index + 1}")
|
||
rows.append(row)
|
||
index += 1
|
||
return rows, index
|
||
|
||
|
||
def add_code(doc, language, content):
|
||
if language == "json":
|
||
content = json.dumps(json.loads(content), ensure_ascii=False, indent=2)
|
||
lines = content.splitlines() or [""]
|
||
for index, line in enumerate(lines):
|
||
paragraph = doc.add_paragraph(style="Code")
|
||
pf = paragraph.paragraph_format
|
||
pf.keep_together = True
|
||
pf.keep_with_next = line.rstrip().endswith((":", "{", "["))
|
||
pf.space_before = Pt(4 if index == 0 else 0)
|
||
pf.space_after = Pt(6 if index == len(lines) - 1 else 0)
|
||
pf.line_spacing = 1.1
|
||
word_wrap(paragraph)
|
||
set_font(paragraph.add_run(line or " "), code=True, size=9)
|
||
|
||
|
||
def reference_audit(reference):
|
||
doc = Document(reference)
|
||
return {
|
||
"reference": str(reference.resolve()),
|
||
"sha256": hashlib.sha256(reference.read_bytes()).hexdigest(),
|
||
"sections": [{
|
||
"width_in": section.page_width.inches,
|
||
"height_in": section.page_height.inches,
|
||
"top_in": section.top_margin.inches,
|
||
"bottom_in": section.bottom_margin.inches,
|
||
"left_in": section.left_margin.inches,
|
||
"right_in": section.right_margin.inches,
|
||
} for section in doc.sections],
|
||
"styles": [{
|
||
"name": name,
|
||
"font": doc.styles[name].font.name,
|
||
"size_pt": doc.styles[name].font.size.pt if doc.styles[name].font.size else None,
|
||
} for name in ("Normal", "Title", "Heading 1", "Heading 2", "Code") if name in doc.styles],
|
||
"editable": ["word/document.xml body", "docProps/core.xml metadata"],
|
||
"preserve": ["styles", "section geometry", "numbering", "headers", "footers"],
|
||
}
|
||
|
||
|
||
def build(source, reference, target):
|
||
if target.resolve() == reference.resolve():
|
||
raise ValueError("Output must not overwrite retained reference")
|
||
audit = reference_audit(reference)
|
||
doc = Document(reference)
|
||
title_bold = any(run.bold for p in doc.paragraphs if p.style.name == "Title" for run in p.runs)
|
||
if "Code" not in doc.styles:
|
||
code_style = doc.styles.add_style("Code", WD_STYLE_TYPE.PARAGRAPH)
|
||
code_style.base_style = doc.styles["Normal"]
|
||
code_style.font.name = "Consolas"
|
||
code_style.font.size = Pt(9)
|
||
code_style.font.color.rgb = RGBColor(0, 0, 0)
|
||
code_style.paragraph_format.line_spacing = 1.1
|
||
if not doc.tables:
|
||
raise ValueError("Reference document must contain a table style pattern")
|
||
sample = doc.tables[0]
|
||
def fill_of(cell, default):
|
||
node = cell._tc.get_or_add_tcPr().find(qn("w:shd"))
|
||
return node.get(qn("w:fill"), default) if node is not None else default
|
||
header_color = sample.rows[0].cells[0].paragraphs[0].runs[0].font.color.rgb
|
||
table_pattern = dict(
|
||
properties=deepcopy(sample._tbl.tblPr),
|
||
header_fill=fill_of(sample.rows[0].cells[0], "E8EBEF"),
|
||
header_color=str(header_color) if header_color else "000000",
|
||
body_fills=[fill_of(sample.rows[min(i, len(sample.rows) - 1)].cells[0], "FFFFFF") for i in (1, 2)],
|
||
)
|
||
body = doc._element.body
|
||
for element in list(body):
|
||
if element.tag != qn("w:sectPr"):
|
||
body.remove(element)
|
||
lines = source.read_text(encoding="utf-8-sig").splitlines()
|
||
index, headings, table_count = 0, [], 0
|
||
while index < len(lines):
|
||
line = lines[index]
|
||
if line.startswith("```"):
|
||
language = line[3:].strip()
|
||
index += 1
|
||
content = []
|
||
while index < len(lines) and not lines[index].startswith("```"):
|
||
content.append(lines[index])
|
||
index += 1
|
||
if index >= len(lines):
|
||
raise ValueError("Unclosed Markdown code block")
|
||
add_code(doc, language, "\n".join(content))
|
||
elif line.startswith("|"):
|
||
rows, index = parse_table(lines, index)
|
||
add_table(doc, rows, table_pattern)
|
||
table_count += 1
|
||
continue
|
||
elif match := re.fullmatch(r"(#{1,4}) (.+)", line):
|
||
level, title = len(match[1]), match[2]
|
||
paragraph = doc.add_paragraph(style="Title" if level == 1 else f"Heading {min(level - 1, 3)}")
|
||
inline(paragraph, title, bold=True if level == 1 and title_bold else None)
|
||
headings.append(title)
|
||
elif line.strip():
|
||
paragraph = doc.add_paragraph(style="Normal")
|
||
paragraph.paragraph_format.widow_control = True
|
||
inline(paragraph, line)
|
||
index += 1
|
||
doc.core_properties.title = headings[0]
|
||
doc.core_properties.subject = "业务 API 参数 返回值 模型调度与原生音画调用"
|
||
# 页面及字段完全来源于保留模板;渲染器另读副本,不回写既有用户文档。
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
doc.save(target)
|
||
# python-docx会重序列化部分未编辑XML;仅保留三个明确编辑槽,其余包内容逐字节复用。
|
||
edited = {"word/document.xml", "word/styles.xml", "docProps/core.xml"}
|
||
with ZipFile(target) as generated, ZipFile(reference) as retained:
|
||
unexpected = set(generated.namelist()) - set(retained.namelist())
|
||
if unexpected:
|
||
raise ValueError(f"Unexpected new package parts: {sorted(unexpected)}")
|
||
replacements = {name: generated.read(name) for name in edited}
|
||
output = io.BytesIO()
|
||
with ZipFile(output, "w") as archive:
|
||
for info in retained.infolist():
|
||
archive.writestr(info, replacements.get(info.filename, retained.read(info.filename)))
|
||
target.write_bytes(output.getvalue())
|
||
assert hashlib.sha256(reference.read_bytes()).hexdigest() == audit["sha256"]
|
||
return {**audit, "output": str(target.resolve()), "source": str(source.resolve()),
|
||
"headings": len(headings), "tables": table_count,
|
||
"bytes": target.stat().st_size}
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument("source", type=Path)
|
||
parser.add_argument("--reference", type=Path, required=True)
|
||
parser.add_argument("--output", type=Path, required=True)
|
||
parser.add_argument("--audit", type=Path)
|
||
parser.add_argument("--overwrite", action="store_true")
|
||
args = parser.parse_args()
|
||
if args.output.exists() and not args.overwrite:
|
||
parser.error("Output already exists; choose a new file or explicitly --overwrite")
|
||
report = build(args.source, args.reference, args.output)
|
||
if args.audit:
|
||
args.audit.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
print(json.dumps({k: report[k] for k in ("output", "headings", "tables", "bytes")}, ensure_ascii=False))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|