Skip to content

duyunzhoudyz/dyz-gongwen-skills / skills/gongwen-format

gongwen-format

Verified

按 GB/T 9704-2012 把公文正文排成 Word,有红头、信函、纪要、命令(令)、白头、材料、简报七种版式,支持联合行文版头、附件另面、预印红头纸套打;检查、修复 docx 的页边距、字体、行距、页码;把核稿意见写成 Word 批注;无 Python 时给手动设置清单。用户说“排版”“套红头”“转成 Word”“按国标调格式”“格式乱了帮我改”“页码怎么设”时使用。只管格式不改内容:起草转对应起草 skill,压缩改写转 gongwen-polish,去 AI 味转 gongwen-humanize,去免责对冲转 gongwen-direct,核稿转 gongwen-review。

FileKindSize
README.mdmarkdown10.0 KB
SKILL.mdskill md21.1 KB
assets/gbt9704_params.jsonconfig20.0 KB
evals/evals.jsonconfig18.7 KB
evals/files/交接卡-平安建设总结-正文.txtmarkdown965 B
evals/files/信函-正文.txtmarkdown611 B
evals/files/信函-版式信息.jsonconfig166 B
evals/files/医院-单位画像.mdmarkdown805 B
evals/files/医院-院内通知-正文.txtmarkdown700 B
evals/files/卫健简报-两篇稿件.txtmarkdown1016 B
evals/files/国企-单位画像.mdmarkdown624 B
evals/files/国企-通知-正文.txtmarkdown646 B
evals/files/学校-监考安排-正文.txtmarkdown688 B
evals/files/学校-通知-正文.txtmarkdown585 B
evals/files/年终总结-正文.txtmarkdown1.2 KB
evals/files/核稿意见.jsonconfig1.4 KB
evals/files/格式混乱的情况报告.docxbinary36.3 KB
evals/files/涉密材料-正文.txtmarkdown221 B
evals/files/白头请示-正文.txtmarkdown701 B
evals/files/社区-情况报告-正文.txtmarkdown577 B
evals/files/简报-正文.txtmarkdown1.0 KB
evals/files/简报-版式信息.jsonconfig364 B
evals/files/红头通知-正文.txtmarkdown1.5 KB
evals/files/红头通知-版式信息.jsonconfig284 B
evals/files/纪要-正文.txtmarkdown910 B
evals/files/纪要-版式信息.jsonconfig119 B
evals/files/请示-缺落款-正文.txtmarkdown339 B
evals/files/高校-单位画像.mdmarkdown509 B
evals/files/高校-请示-正文.txtmarkdown603 B
evals/trigger.jsonconfig1.9 KB
manifest.jsonconfig976 B
references/_shared/README.mdmarkdown110 B
references/_shared/guardrails.mdmarkdown12.6 KB
references/_shared/profiles/roles.mdmarkdown16.1 KB
references/_shared/profiles/units/dangzheng.mdmarkdown7.9 KB
references/_shared/profiles/units/gaoxiao.mdmarkdown11.2 KB
references/_shared/profiles/units/guoqi.mdmarkdown12.7 KB
references/_shared/profiles/units/jiceng.mdmarkdown9.3 KB
references/_shared/profiles/units/shequ.mdmarkdown8.8 KB
references/_shared/profiles/units/yiyuan.mdmarkdown13.2 KB
references/_shared/profiles/units/zhongxiaoxue.mdmarkdown10.6 KB
references/_shared/rules/doc-types.mdmarkdown28.1 KB
references/_shared/rules/gbt15834.mdmarkdown13.3 KB
references/_shared/rules/gbt15835.mdmarkdown10.6 KB
references/_shared/rules/gbt9704.mdmarkdown17.2 KB
references/_shared/rules/jianfu.mdmarkdown12.5 KB
references/_shared/rules/tiaoli.mdmarkdown15.3 KB
references/_shared/style/ai-tone.mdmarkdown10.2 KB
references/_shared/style/defensive.mdmarkdown8.1 KB
references/_shared/style/output-format.mdmarkdown9.0 KB
references/check-items.mdmarkdown16.1 KB
references/layouts.mdmarkdown20.8 KB
references/manual-setup.mdmarkdown13.9 KB
references/meta-fields.mdmarkdown11.6 KB
scripts/annotate_docx.pyscript9.7 KB
scripts/build_docx.pyscript76.1 KB
scripts/check_docx.pyscript74.7 KB
scripts/extract_docx.pyscript16.2 KB
scripts/fix_docx.pyscript28.3 KB
scripts/gw_docx.pyscript50.0 KB
scripts/gw_fonts.pyscript24.2 KB
scripts/gw_format.pyscript15.9 KB
scripts/gw_layout.pyscript56.6 KB
scripts/gw_verify.pyscript6.1 KB
scripts/preview_docx.pyscript11.1 KB
scripts/secret_check.pyscript8.9 KB

scripts/gw_format.py

View on GitHub
# -*- coding: utf-8 -*-
"""按角色设置段落和文字格式\u3002build_docx.py 生成时\u3001fix_docx.py 修复时共用同一套规则\uff0c保证结果一致\u3002"""
from __future__ import annotations

import re
from typing import List, Optional, Sequence, Set

import gw_docx as D
from gw_layout import ATTENDANCE_RE, text_width_chars

ATTACH_NUM_RE = re.compile(r"^\d{1,2}\s*[..]\s*")
ATTACH_LABEL_RE = re.compile(r"^附\s*件\s*[\uff1a:]\s*")


def _font_runs(paragraph, ctx: D.Ctx, font_role: str, size_name, *, start: int = 0, end: Optional[int] = None,
               bold: Optional[bool] = None, color: Optional[str] = None, black: bool = True) -> Set[str]:
    """给 [start, end) 范围内的 run 设字体字号\uff08按字符位置取 run\uff0c不拆分\uff09\u3002"""
    changes: Set[str] = set()
    name = ctx.font(font_role)
    size = ctx.size(size_name)
    pos = 0
    for run in paragraph.runs:
        length = len(run.text)
        in_range = length == 0 or (pos >= start and (end is None or pos < end))
        if in_range:
            rpr = run._r.get_or_add_rPr()
            if D.set_rpr(rpr, font=name):
                changes.add("字体")
            if D.set_rpr(rpr, size=size):
                changes.add("字号")
            if bold is not None and D.set_rpr(rpr, bold=bold):
                changes.add("加粗")
            if color:
                if D.set_rpr(rpr, color=color):
                    changes.add("颜色")
            elif black and D.set_rpr(rpr, black=True):
                changes.add("颜色")
        pos += length
    return changes


def _ensure_split(paragraph, offset: int) -> bool:
    """确保 offset 处是 run 边界\uff1b返回是否成功\u3002"""
    if offset <= 0:
        return True
    pos = 0
    for run in paragraph.runs:
        length = len(run.text)
        if pos == offset:
            return True
        if pos < offset < pos + length:
            return D.split_run(run, offset - pos) is not None
        pos += length
    return pos == offset or offset >= pos


def strip_leading_spaces(paragraph) -> bool:
    """删除段首用于缩进的空格\uff08半角\u3001全角空格和制表符\uff09\uff0c缩进改由段落格式实现\u3002"""
    changed = False
    for run in paragraph.runs:
        text = run.text
        if not text:
            continue
        new = text.lstrip("  \t")
        if new != text:
            if not D.run_splittable(run):
                return changed
            run.text = new
            changed = True
        if new:
            break
    return changed


def offset_leading_spaces(paragraph) -> float:
    """行首有空格的顶格段落\uff08称呼\u3001主送机关\uff09\uff1a--keep-text 不删空格\uff0c改用等宽的负左缩进抵消\uff0c视觉上仍然顶格\u3002返回抵消的字数\u3002"""
    text = D.direct_text(paragraph)
    lead = text[:len(text) - len(text.lstrip("  "))]
    width = sum(1.0 if ch == " " else 0.5 for ch in lead)
    if width:
        D.set_para(paragraph, left=-width)
    return width


def apply_role(paragraph, role: str, ctx: D.Ctx, *, split: int = -1, black: bool = True) -> Set[str]:
    """按角色设置格式\uff0c返回发生变化的类别集合\uff08段落格式\u3001字体\u3001字号\u3001加粗\u3001颜色\uff09\u3002

    split\uff1a层次标题与正文同段时\uff0c标题部分的结束位置\uff1b-1 表示整段都是标题\u3002
    署名和成文日期的缩进由 layout_signature_block 统一计算\uff0c这里只设字体\u3002
    """
    changes: Set[str] = set()
    line = ctx.line_pt
    text = D.direct_text(paragraph)

    def para(**kw):
        if D.set_para(paragraph, **kw):
            changes.add("段落格式")

    if role == "body":
        el = ctx.el("body")
        para(align=el["align"], first_line=el["first_line_chars"], line_exact=line, before_pt=0, after_pt=0, snap=True)
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], black=black)
    elif role in ("h1", "h2", "h3", "h4"):
        el = ctx.el(role)
        body = ctx.el("body")
        end = len(text) if split is None or split < 0 else split
        # 独占一行、末尾不带句号的标题设“与下段同页”,标题不落在页末;与正文同段的、以句号结尾的条目不设
        standalone = end >= len(text) and text.rstrip()[-1:] not in "\u3002\uff1b\uff01\uff1f.;!?"
        para(align=body["align"], first_line=el["first_line_chars"], line_exact=line, before_pt=0, after_pt=0,
             outline=el["outline_level"], snap=True, keep_next=True if standalone else None)
        if end < len(text) and not _ensure_split(paragraph, end):
            end = len(text)  # 拆不开时整段按标题处理
        bold = bool(el.get("bold", False))  # 层次标题默认不加粗;三级标题可按单位规定加粗
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], start=0, end=end, bold=bold, black=black)
        if end < len(text):
            changes |= _font_runs(paragraph, ctx, body["font"], body["size"], start=end, black=black,
                                  bold=False if bold else None)
    elif role == "title":
        el = ctx.el("title")
        para(align=el["align"], line_exact=line, before_pt=0, after_pt=0, snap=False)
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], bold=False, black=black)
    elif role in ("subtitle", "title_note"):
        el = ctx.el("subtitle")
        para(align=el["align"], line_exact=line, before_pt=0, after_pt=0, snap=True)
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], bold=False, black=black)
    elif role == "table_caption":
        # 表题:居中,不缩进,与表格同页
        el = ctx.el("table")
        para(align="center", line_exact=line, before_pt=0, after_pt=0, snap=True, keep_next=True)
        changes |= _font_runs(paragraph, ctx, el["caption_font"], el["caption_size"], bold=False, black=black)
    elif role in ("recipient", "salutation"):  # 称呼(讲话稿“同志们:”)同主送机关:顶格,不缩进
        el = ctx.el("recipient")
        para(align=el["align"], line_exact=line, before_pt=0, after_pt=0, snap=True)
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], black=black)
    elif role == "attendance":
        el = ctx.el("attendance")
        m = ATTENDANCE_RE.match(text)
        label_end = m.end() if m else 0
        label_w = text_width_chars(text[:label_end]) if m else 3
        para(align="justify", left=el["left_chars"] + label_w, hanging=label_w, line_exact=line,
             before_pt=0, after_pt=0, snap=True)
        if label_end and _ensure_split(paragraph, label_end):
            changes |= _font_runs(paragraph, ctx, el["label_font"], el["size"], start=0, end=label_end, black=black)
            changes |= _font_runs(paragraph, ctx, el["font"], el["size"], start=label_end, black=black)
        else:
            changes |= _font_runs(paragraph, ctx, el["font"], el["size"], black=black)
    elif role == "attachment":
        el = ctx.el("attachment")
        base = el["left_chars"]
        m_label = ATTACH_LABEL_RE.match(text)
        if m_label:
            rest = text[m_label.end():]
            m_num = ATTACH_NUM_RE.match(rest)
            num_w = text_width_chars(m_num.group(0)) if m_num else 0
            label_w = 3
            para(align="left", left=base + label_w + num_w, hanging=label_w + num_w, line_exact=line,
                 before_pt=0, after_pt=0, snap=True)
        else:
            m_num = ATTACH_NUM_RE.match(text)
            num_w = text_width_chars(m_num.group(0)) if m_num else 0
            para(align="left", left=base + 3 + num_w, hanging=num_w if num_w else None, line_exact=line,
                 before_pt=0, after_pt=0, snap=True)
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], black=black)
    elif role == "note":
        el = ctx.el("note")
        para(align="left", first_line=el["first_line_chars"], line_exact=line, before_pt=0, after_pt=0, snap=True)
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], black=black)
    elif role in ("signature", "date"):
        el = ctx.el("signature_noseal")
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], black=black)
    elif role in ("copy_no", "secret", "urgency"):
        el = ctx.el(role)
        para(align=el["align"], line_exact=line, before_pt=0, after_pt=0, snap=True)
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], black=black)
    elif role == "issuer":
        # 版头标志只统一字体,保留原有字号、颜色和位置
        el = ctx.el("issuer")
        name = ctx.font(el["font"])
        for run in paragraph.runs:
            if D.set_rpr(run._r.get_or_add_rPr(), font=name):
                changes.add("字体")
    elif role == "docno":
        # 发文字号用仿宋;同一行有签发人时,“签发人:”用仿宋、姓名用楷体(7.2.6)
        el = ctx.el("docno")
        sg = ctx.el("signer")
        m = re.search(r"签发人\s*[\uff1a:]\s*", text)
        name_start = m.end() if m and _ensure_split(paragraph, m.end()) else len(text)
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], start=0, end=name_start, black=False)
        if name_start < len(text):
            changes |= _font_runs(paragraph, ctx, sg["name_font"], sg["size"], start=name_start, black=False)
    elif role == "lingno":
        # 命令(令)格式的令号:居中,三号仿宋(10.2)
        el = ctx.el("order")
        para(align="center", line_exact=line, before_pt=0, after_pt=0, snap=True)
        changes |= _font_runs(paragraph, ctx, el["number_font"], el["number_size"], black=black)
    elif role == "attach_label":
        # 附件另面编排的“附件”“附件1”:三号黑体,顶格(7.3.7)
        el = ctx.el("attach_page")
        para(align="left", line_exact=line, before_pt=0, after_pt=0, snap=True, keep_next=True)
        changes |= _font_runs(paragraph, ctx, el["label_font"], el["label_size"], bold=False, black=black)
    elif role in ("cc", "print", "banji_main", "brief_foot"):
        el = ctx.el("banji")
        changes |= _font_runs(paragraph, ctx, el["font"], el["size"], black=black)
    return changes


def ensure_upward_docno_indent(paragraph, doc, ctx: D.Ctx) -> bool:
    """上行文发文字号居左空一字\uff087.2.5\uff09\uff1a行首空白和左缩进合计不足一字时\uff0c补足左缩进\uff1b不改文字\u3002
    居中的改为左对齐\u3001左缩进一字\u3002返回是否有改动\u3002"""
    need = float(ctx.el("docno")["left_chars_upward"])
    have = D.leading_offset_chars(paragraph, doc)
    centered = D.para_align(paragraph, doc) in ("center", "right") and not paragraph.text.startswith("\t")
    if have >= need - 0.1 and not centered:
        return False
    left = D.para_left_chars(paragraph, doc)
    new_left = need if centered else left + (need - have)
    return D.set_para(paragraph, align="left", left=max(0.0, new_left), reset_indent=True, line_exact=ctx.line_pt,
                      before_pt=0, after_pt=0)


def layout_signature_block(sig_paras: Sequence, date_para, ctx: D.Ctx, *, seal: bool,
                           before_lines: Optional[int] = None) -> List[Set[str]]:
    """排署名和成文日期\uff0c返回每段的改动类别\uff08顺序为各署名段\u3001成文日期段\uff09\u3002

    - 加盖印章\uff087.3.5.1\uff09\uff1a成文日期右空四字\uff0c署名以成文日期为准居中\u3002两段都设为居中对齐\u3001
      左右缩进相同\uff0c中心点完全一致\uff1b中心点按\u201c右空四字加日期宽度的一半\u201d估算\uff0c日期右空字数是近似值\u3002
    - 不加盖印章\uff087.3.5.2\uff09\uff1a署名右空二字\uff0c左对齐\u3001左缩进 = 28 − 2 − 署名字数\uff1b成文日期左对齐\u3001
      左缩进 = 署名左缩进 + 2\uff0c首字比署名首字右移二字\uff08用左缩进定位\uff0c不受日期中半角数字宽度影响\uff09\u3002
      日期加 2 字后会超出\u201c右空二字\u201d时\uff0c日期右对齐\u3001右空二字\uff0c署名左缩进 = 28 − 2 − 日期字数 − 2\u3002
    before_lines\uff1a第一个要素前的段前空行数\uff08修复已有文档时用段前距代替插入空段\uff09\u3002
    """
    width = float(D.pv(ctx.params, "grid.chars_per_line"))
    sig_w = [text_width_chars(D.direct_text(p)) for p in sig_paras]
    date_w = text_width_chars(D.direct_text(date_para)) if date_para is not None else 0.0
    # 每段的 (对齐, 左缩进, 右缩进)
    places: List[tuple] = []
    if seal:
        el = ctx.el("signature_seal")
        r_date = float(el["date_right_chars"])
        if date_para is None:
            places = [("right", None, r_date) for _ in sig_w]
        else:
            # 居中区域取以中心点为轴、尽量宽的对称区间,给半角数字的实际宽度留余量,避免日期回行
            center = width - r_date - date_w / 2
            need = max(sig_w + [date_w]) / 2 + 0.5
            half = width - center
            if half < need:  # 署名太长,以日期为准居中会超出版心:整体左移
                center, half = width - need, need
            left = max(0.0, center - half)
            right = max(0.0, width - center - half)
            places = [("center", left, right) for _ in sig_w] + [("center", left, right)]
    else:
        el = ctx.el("signature_noseal")
        r_sig = float(el["sign_right_chars"])
        shift = float(el["date_shift_chars"])
        if sig_w and date_para is not None:
            w_max = max(sig_w)
            start = width - r_sig - w_max
            if date_w + shift > w_max:  # 日期较长:日期右空二字,署名相应左移
                start = width - r_sig - date_w - shift
                date_place = ("right", None, r_sig)
            else:
                date_place = ("left", start + shift, None)
            places = [("left", max(0.0, start), None) for _ in sig_w] + [date_place]
        else:
            places = [("right", None, r_sig) for _ in sig_w] + ([("right", None, r_sig)] if date_para is not None else [])
    targets = list(sig_paras) + ([date_para] if date_para is not None else [])
    result: List[Set[str]] = []
    line = ctx.line_pt
    for k, (p, (align, left, right)) in enumerate(zip(targets, places)):
        changes: Set[str] = set()
        before = (before_lines or 0) * line if k == 0 and before_lines else 0
        if D.set_para(p, align=align, left=round(left, 2) if left else None, right=round(right, 2) if right else None,
                      line_exact=line, before_pt=before, after_pt=0, snap=True, keep_lines=True):
            changes.add("段落格式")
        changes |= _font_runs(p, ctx, el["font"], el["size"])
        result.append(changes)
    return result


def keep_signoff_together(paragraphs: Sequence, first_idx: int, last_idx: int, attach_first_idx: Optional[int] = None) -> int:
    """落款不单独成页\uff1a从正文最后一段起\uff0c经附件说明\u3001空行\u3001署名到成文日期\uff08有附注时到附注\uff09\uff0c依次设\u201c与下段同页\u201d\u3002
    正文最后一段不设\u201c段中不分页\u201d\uff0c换页时至少有一行正文随落款下移\uff1b附件说明与正文末段\u3001落款连在一起\uff0c不被分页割裂\u3002

    paragraphs 为正文段落列表\uff0cfirst_idx 为第一个署名\uff08或日期\uff09段的下标\uff0clast_idx 为链条最后一段的下标\uff1b
    attach_first_idx 为附件说明第一行的下标\uff08有附件说明时传入\uff0c它在署名之前\uff09\u3002返回设置的段数\u3002
    """
    if attach_first_idx is not None and attach_first_idx < first_idx:
        first_idx = attach_first_idx
    count = 0
    for j in range(first_idx, last_idx):
        if D.set_para(paragraphs[j], reset_indent=False, keep_next=True):
            count += 1
    j = first_idx - 1
    while j >= 0:
        if D.set_para(paragraphs[j], reset_indent=False, keep_next=True):
            count += 1
        if paragraphs[j].text.strip():
            break
        j -= 1
    return count
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