Skip to content

XiaoMaColtAI/math-modeling-skill / tools/docx

DOCX工具

Verified

创建、编辑、校验和转换 Word DOCX,支持把完整 LaTeX 论文转换为 DOCX,以及数学建模论文模板、原生公式、三线表、修订和批注。

FileKindSize
LICENSE.txtmarkdown1.4 KB
SKILL.mdskill md6.6 KB
scripts/__init__.pyscript1 B
scripts/accept_changes.pyscript4.9 KB
scripts/check_env.pyscript972 B
scripts/comment.pyscript11.2 KB
scripts/equations.pyscript49.9 KB
scripts/inspect_template_format.pyscript7.2 KB
scripts/office/helpers/__init__.pyscript0 B
scripts/office/helpers/merge_runs.pyscript5.4 KB
scripts/office/helpers/simplify_redlines.pyscript5.6 KB
scripts/office/pack.pyscript4.9 KB
scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsdother73.2 KB
scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsdother6.8 KB
scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsdother50.1 KB
scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsdother624 B
scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsdother148.5 KB
scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsdother1.2 KB
scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsdother8.7 KB
scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsdother14.4 KB
scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsdother81.7 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsdother1.2 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsdother7.2 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsdother6.2 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsdother1.2 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsdother880 B
scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsdother2.5 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsdother3.4 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsdother7.3 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsdother22.8 KB
scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsdother1.3 KB
scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsdother236.6 KB
scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsdother25.5 KB
scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsdother24.7 KB
scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsdother535 B
scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsdother5.6 KB
scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsdother3.9 KB
scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsdother167.4 KB
scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsdother4.5 KB
scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsdother1.9 KB
scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsdother2.5 KB
scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsdother2.8 KB
scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsdother1.3 KB
scripts/office/schemas/mce/mc.xsdother3.1 KB
scripts/office/schemas/microsoft/wml-2010.xsdother25.9 KB
scripts/office/schemas/microsoft/wml-2012.xsdother3.7 KB
scripts/office/schemas/microsoft/wml-2018.xsdother901 B
scripts/office/schemas/microsoft/wml-cex-2018.xsdother1.7 KB
scripts/office/schemas/microsoft/wml-cid-2016.xsdother1002 B
scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsdother600 B
scripts/office/schemas/microsoft/wml-symex-2015.xsdother745 B
scripts/office/soffice.pyscript5.3 KB
scripts/office/unpack.pyscript4.0 KB
scripts/office/validate.pyscript3.8 KB
scripts/office/validators/__init__.pyscript336 B
scripts/office/validators/base.pyscript34.2 KB
scripts/office/validators/docx.pyscript16.0 KB
scripts/office/validators/pptx.pyscript9.6 KB
scripts/office/validators/redlining.pyscript8.7 KB
scripts/paper_format.pyscript19.9 KB
scripts/self_check.pyscript4.2 KB
scripts/templates/comments.xmlconfig2.5 KB
scripts/templates/commentsExtended.xmlconfig2.5 KB
scripts/templates/commentsExtensible.xmlconfig2.6 KB
scripts/templates/commentsIds.xmlconfig2.6 KB
scripts/templates/people.xmlconfig115 B

scripts/inspect_template_format.py

View on GitHub
#!/usr/bin/env python3
"""Extract a compact formatting profile from a DOCX template."""

import argparse
import json
import zipfile
from collections import Counter
from pathlib import Path

from lxml import etree

W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
NS = {"w": W_NS, "a": A_NS}


def xpath_string(element, expression):
    if element is None:
        return ""
    return element.xpath(f"string({expression})", namespaces=NS)


def half_points_to_points(value):
    if not value:
        return ""
    return f"{int(value) / 2:g}pt"


def line_to_multiple(value, rule):
    if not value:
        return ""
    if rule == "auto":
        return f"{int(value) / 240:g}"
    return value


def text_of(paragraph):
    return "".join(paragraph.xpath(".//w:t/text()", namespaces=NS)).strip()


def paragraph_profile(paragraph):
    p_pr = paragraph.find("w:pPr", NS)
    runs = []
    for run in paragraph.findall("w:r", NS):
        text = "".join(run.xpath(".//w:t/text()", namespaces=NS)).strip()
        if not text:
            continue
        r_pr = run.find("w:rPr", NS)
        size = xpath_string(r_pr, "w:sz/@w:val")
        runs.append(
            {
                "text": text[:40],
                "fontEastAsia": xpath_string(r_pr, "w:rFonts/@w:eastAsia")
                or xpath_string(r_pr, "w:rFonts/@w:eastAsiaTheme"),
                "fontAscii": xpath_string(r_pr, "w:rFonts/@w:ascii")
                or xpath_string(r_pr, "w:rFonts/@w:asciiTheme"),
                "size": half_points_to_points(size),
                "bold": r_pr.find("w:b", NS) is not None if r_pr is not None else False,
            }
        )

    line = xpath_string(p_pr, "w:spacing/@w:line")
    line_rule = xpath_string(p_pr, "w:spacing/@w:lineRule")
    return {
        "text": text_of(paragraph),
        "alignment": xpath_string(p_pr, "w:jc/@w:val"),
        "firstLineDxa": xpath_string(p_pr, "w:ind/@w:firstLine"),
        "firstLineChars": xpath_string(p_pr, "w:ind/@w:firstLineChars"),
        "line": line,
        "lineRule": line_rule,
        "lineMultiple": line_to_multiple(line, line_rule),
        "runs": runs,
    }


def extract_theme_fonts(zip_file):
    theme_names = [
        name
        for name in zip_file.namelist()
        if name.startswith("word/theme/") and name.endswith(".xml")
    ]
    if not theme_names:
        return {}

    root = etree.fromstring(zip_file.read(theme_names[0]))
    result = {}
    for label in ("majorFont", "minorFont"):
        node = root.find(f".//a:{label}", NS)
        if node is None:
            continue
        latin = xpath_string(node, "a:latin/@typeface")
        hans = ""
        for font in node.findall("a:font", NS):
            if font.get("script") == "Hans":
                hans = font.get("typeface", "")
                break
        result[label] = {"latin": latin, "hans": hans}
    return result


def extract_table_profiles(root):
    tables = []
    for table in root.xpath("//w:tbl", namespaces=NS):
        tbl_pr = table.find("w:tblPr", NS)
        borders = {}
        border_node = table.find("w:tblPr/w:tblBorders", NS)
        if border_node is not None:
            for child in border_node:
                borders[child.tag.rsplit("}", 1)[1]] = {
                    "val": child.get(f"{{{W_NS}}}val", ""),
                    "size": child.get(f"{{{W_NS}}}sz", ""),
                }

        rows = []
        for row in table.xpath("./w:tr", namespaces=NS):
            cells = []
            for cell in row.xpath("./w:tc", namespaces=NS):
                cells.append("".join(cell.xpath(".//w:t/text()", namespaces=NS)).strip())
            rows.append(cells)

        tables.append(
            {
                "alignment": xpath_string(tbl_pr, "w:jc/@w:val"),
                "style": xpath_string(tbl_pr, "w:tblStyle/@w:val"),
                "borders": borders,
                "rows": rows,
            }
        )
    return tables


def infer_roles(paragraphs):
    samples = {}
    for profile in paragraphs:
        text = profile["text"]
        if not text:
            continue
        first_run = profile["runs"][0] if profile["runs"] else {}
        size = first_run.get("size", "")
        bold = first_run.get("bold", False)
        align = profile["alignment"]
        first_line_chars = profile["firstLineChars"]

        if text == "论文题目":
            samples["paperTitle"] = profile
        elif text == "摘 要":
            samples["abstractTitle"] = profile
        elif text.startswith("关键词"):
            samples["keywords"] = profile
        elif first_line_chars == "200" and size == "12pt":
            samples.setdefault("bodyParagraph", profile)
        elif align == "center" and size == "16pt" and bold:
            samples.setdefault("level1Heading", profile)
        elif size == "12pt" and not bold and align == "":
            samples.setdefault("level2Heading", profile)
        elif (
            size == "12pt"
            and align == "both"
            and any(keyword in text for keyword in ("建立", "求解", "优点", "缺点", "改进"))
        ):
            samples.setdefault("level3ModelHeading", profile)
    return samples


def extract_profile(template_path):
    with zipfile.ZipFile(template_path) as docx:
        document = etree.fromstring(docx.read("word/document.xml"))
        paragraphs = [
            paragraph_profile(p)
            for p in document.xpath("//w:body/w:p", namespaces=NS)
            if text_of(p)
        ]

        sect = document.find(".//w:sectPr", NS)
        page = {
            "widthDxa": xpath_string(sect, "w:pgSz/@w:w"),
            "heightDxa": xpath_string(sect, "w:pgSz/@w:h"),
            "marginTopDxa": xpath_string(sect, "w:pgMar/@w:top"),
            "marginRightDxa": xpath_string(sect, "w:pgMar/@w:right"),
            "marginBottomDxa": xpath_string(sect, "w:pgMar/@w:bottom"),
            "marginLeftDxa": xpath_string(sect, "w:pgMar/@w:left"),
            "headerDxa": xpath_string(sect, "w:pgMar/@w:header"),
            "footerDxa": xpath_string(sect, "w:pgMar/@w:footer"),
            "docGridLinePitch": xpath_string(sect, "w:docGrid/@w:linePitch"),
        }

        size_counter = Counter(
            run["size"]
            for paragraph in paragraphs
            for run in paragraph["runs"]
            if run["size"]
        )

        return {
            "template": str(template_path),
            "page": page,
            "themeFonts": extract_theme_fonts(docx),
            "commonRunSizes": dict(size_counter.most_common()),
            "roleSamples": infer_roles(paragraphs),
            "tables": extract_table_profiles(document),
        }


def main():
    parser = argparse.ArgumentParser(
        description="Extract page, paragraph, run, and table formatting from a DOCX template."
    )
    parser.add_argument("template", help="Path to the .docx template")
    parser.add_argument("--output", "-o", help="Optional JSON output path")
    args = parser.parse_args()

    profile = extract_profile(Path(args.template))
    rendered = json.dumps(profile, ensure_ascii=False, indent=2)
    if args.output:
        Path(args.output).write_text(rendered + "\n", encoding="utf-8")
    else:
        print(rendered)


if __name__ == "__main__":
    main()
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: 198kUpdated Claude CodeCodexVerifiedInstall
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: 198kUpdated Claude CodeCodexVerifiedInstall
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: 198kUpdated Claude CodeCodexVerifiedInstall
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: 198kUpdated Claude CodeCodexVerifiedInstall