"""从 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"(?= 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()