XiaoMaColtAI/math-modeling-skill / tools/docx
DOCX工具
Verified创建、编辑、校验和转换 Word DOCX,支持把完整 LaTeX 论文转换为 DOCX,以及数学建模论文模板、原生公式、三线表、修订和批注。
scripts/self_check.py
View on GitHub#!/usr/bin/env python3
"""One-command sanity check for DOCX paper helpers."""
import importlib.util
import os
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path
from lxml import etree
ROOT = Path(os.environ.get("MATH_MODELING_SKILL_ROOT", Path(__file__).resolve().parents[3]))
SCRIPTS = ROOT / "tools" / "docx" / "scripts"
W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
M_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"
def find_template() -> Path:
"""定位官方论文模板;优先精确路径,回退到目录内首个 .docx,找不到则报错。"""
template_dir = ROOT / "references" / "roles" / "论文手" / "references"
preferred = template_dir / "论文模板.docx"
if preferred.exists():
return preferred
for candidate in sorted(template_dir.glob("*.docx")):
return candidate
raise FileNotFoundError(f"未找到论文模板:{template_dir}")
def load(name):
spec = importlib.util.spec_from_file_location(name, SCRIPTS / f"{name}.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def check_env():
result = subprocess.run([sys.executable, str(SCRIPTS / "check_env.py")], check=False)
assert result.returncode == 0
def check_formula():
equations = load("equations")
root = etree.fromstring(equations.latex2omml(r"\frac{1}{n}\sum_{i=1}^{n}x_i^2"))
assert root.xpath(".//m:f", namespaces={"m": M_NS})
assert root.xpath(".//m:sSubSup", namespaces={"m": M_NS})
def check_three_line_table():
fmt = load("paper_format")
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "table.docx"
doc = fmt.new_document()
fmt.title(doc, "论文题目")
fmt.abstract_title(doc)
fmt.body(doc, "摘要正文。")
fmt.keywords(doc, "优化;预测")
fmt.heading1(doc, "一、问题重述")
fmt.heading2(doc, "1.1 问题背景")
fmt.body(doc, "这是正文。")
assert fmt.count_chinese_chars(doc) >= 6
fmt.equation(doc, r"x_i^2")
placeholder, latex = fmt.equation_placeholder(doc, r"x_i^2")
assert placeholder.startswith("EQ_")
assert latex == r"x_i^2"
fmt.three_line_table(doc, [["符号", "说明", "单位"], ["x", "变量", "-"]])
fmt.figure_caption(doc, "图1 测试图")
fmt.page_break(doc)
doc.save(path)
result = subprocess.run(
[sys.executable, str(SCRIPTS / "office" / "validate.py"), str(path)],
check=False,
)
assert result.returncode == 0
with zipfile.ZipFile(path) as zf:
document = etree.fromstring(zf.read("word/document.xml"))
keyword_paras = document.xpath("//w:p[.//w:t='关键词:']", namespaces={"w": W_NS})
assert keyword_paras and not "".join(keyword_paras[0].getprevious().xpath(".//w:t/text()", namespaces={"w": W_NS}))
chapter_break = document.xpath(
"//w:p[.//w:t='一、问题重述']/w:pPr/w:pageBreakBefore",
namespaces={"w": W_NS},
)
assert chapter_break
heading2_size = document.xpath(
"//w:p[.//w:t='1.1 问题背景']//w:sz/@w:val",
namespaces={"w": W_NS},
)
assert heading2_size == ["28"]
tbl_borders = document.xpath("//w:tbl[1]/w:tblPr/w:tblBorders/*", namespaces={"w": W_NS})
vals = {node.tag.rsplit("}", 1)[1]: node.get(f"{{{W_NS}}}val") for node in tbl_borders}
assert vals["top"] == "single"
assert vals["bottom"] == "single"
assert vals["insideV"] == "nil"
header_bottom = document.xpath(
"//w:tbl[1]/w:tr[1]/w:tc[1]/w:tcPr/w:tcBorders/w:bottom/@w:val",
namespaces={"w": W_NS},
)
assert header_bottom == ["single"]
def check_template_validate():
template = find_template()
result = subprocess.run(
[sys.executable, str(SCRIPTS / "office" / "validate.py"), str(template)],
check=False,
)
assert result.returncode == 0
def main():
check_env()
check_formula()
check_three_line_table()
check_template_validate()
print("self_check OK")
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| canvas-designanthropics/skillsCreate beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| docxanthropics/skillsUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| pdfanthropics/skillsUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| pptxanthropics/skillsUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |