Skip to content

Tasdax123/claude-fidelity-translator / plugins/fidelity-translator/skills/fidelity-translator

fidelity-translator

Verified

scripts/build_docx.py

View on GitHub
#!/usr/bin/env python3
"""Assemble translated chunks into a .docx using a configurable house style.

Default style is `formal-monochrome` (Times New Roman, black on white, bordered
tables, monochrome callouts with hazard icon) — calibrated for regulatory /
aerospace / pharma documents that must visually resemble the source family
rather than a modern Microsoft Office document.

Alternative built-in styles:
  - `modern` — Calibri / Aptos, blue Heading 1, banded tables, coloured callouts
  - `custom` — fully driven by a JSON style spec via --style-config

Callout rendering supports any source-language hazard label that maps through
`references/hazard_mappings.yaml` (or via --hazard-mapping passed at runtime).
"""
import argparse, json, re, sys
from pathlib import Path
from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

# ---- House style presets ----------------------------------------------------

STYLES = {
    "formal-monochrome": {
        "body_font": "Times New Roman",
        "body_size_pt": 12,
        "heading_font": "Times New Roman",
        "heading_sizes": {1: 16, 2: 14, 3: 13, 4: 12},
        "heading_color": "000000",
        "callout_border": True,
        "callout_icon_max_cm": 1.6,
        "table_style": "Table Grid",
        "table_borders": True,
        "table_shading": False,
    },
    "modern": {
        "body_font": "Calibri",
        "body_size_pt": 11,
        "heading_font": "Calibri",
        "heading_sizes": {1: 20, 2: 16, 3: 13, 4: 12},
        "heading_color": "2F5496",   # Word default Heading 1 blue
        "callout_border": True,
        "callout_icon_max_cm": 1.4,
        "table_style": "Light Grid Accent 1",
        "table_borders": True,
        "table_shading": True,
    },
}

# Hazard labels Hub: keys are upper-case canonical English; values are the labels
# (in many languages) that should be rendered as a callout. The actual target-
# language label written into the callout is the SAME WORD found in the source
# markdown (because the translator has already rendered it correctly in the
# target language); we only need to recognise the callout block here.
DEFAULT_HAZARD_WORDS = {
    "DANGER", "WARNING", "CAUTION", "NOTE", "NOTICE", "ATTENTION",
    "ACHTUNG", "VORSICHT", "HINWEIS", "GEFAHR",
    "AVERTISSEMENT", "AVERTISSEMENT", "MISE EN GARDE",
    "ADVERTENCIA", "PRECAUCIÓN", "PRECAUCION", "NOTA", "PELIGRO",
    "AVISO", "CUIDADO",
    "AVVERTENZA", "AVVERTIMENTO", "ATTENZIONE",
    "УВАГА", "ПОПЕРЕДЖЕННЯ", "ПРИМІТКА", "НЕБЕЗПЕКА",
    "ВНИМАНИЕ", "ОСТОРОЖНО", "ПРИМЕЧАНИЕ", "ОПАСНОСТЬ",
    "警告", "注意", "危险", "危險", "備考", "備註",
    "경고", "주의", "위험",
}

# ---- Regex --------------------------------------------------------------------

H_RE = re.compile(r"^(#{1,6})\s+(.*)")
LIST_RE = re.compile(r"^(\s*)([-*+]|\d+\.)\s+(.*)")
IMG_RE = re.compile(r"!\[(?P<alt>[^\]]*)\]\((?P<path>[^)]+)\)")
TABLE_SEP_RE = re.compile(r"^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)+\|?\s*$")
INLINE_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
INLINE_ITAL_RE = re.compile(r"(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)")
HR_RE = re.compile(r"^-{3,}\s*$")


def _callout_re(hazard_words):
    """Build a callout regex that matches `> **LABEL!** body...` in any language."""
    escaped = sorted(hazard_words, key=len, reverse=True)
    alt = "|".join(re.escape(w) for w in escaped)
    return re.compile(rf"^>\s*\*\*({alt})!?\*\*\s*(.*)", re.IGNORECASE)


# ---- Cell / table helpers ----------------------------------------------------

def _set_cell_border(cell, color="000000", size_pt=4):
    tc = cell._tc; tcPr = tc.get_or_add_tcPr()
    tcBorders = OxmlElement("w:tcBorders")
    for side in ("top", "left", "bottom", "right"):
        b = OxmlElement(f"w:{side}")
        b.set(qn("w:val"), "single"); b.set(qn("w:sz"), str(size_pt)); b.set(qn("w:color"), color)
        tcBorders.append(b)
    tcPr.append(tcBorders)


def _bordered_table(doc, rows, cols, style_cfg):
    t = doc.add_table(rows=rows, cols=cols)
    t.style = style_cfg["table_style"]; t.alignment = WD_ALIGN_PARAGRAPH.LEFT
    if style_cfg["table_borders"]:
        for r in t.rows:
            for c in r.cells:
                _set_cell_border(c)
                for p in c.paragraphs:
                    p.paragraph_format.space_before = Pt(0)
                    p.paragraph_format.space_after = Pt(0)
    return t


def _make_run(p, text, style_cfg, bold=False, italic=False, size=None):
    r = p.add_run(text); r.bold = bold; r.italic = italic
    r.font.name = style_cfg["body_font"]
    r.font.size = size or Pt(style_cfg["body_size_pt"])
    return r


def add_runs(paragraph, text, style_cfg, base_bold=False, base_italic=False):
    pos = 0
    for m in INLINE_BOLD_RE.finditer(text):
        if m.start() > pos:
            _add_italic_segment(paragraph, text[pos:m.start()], style_cfg, base_bold, base_italic)
        _make_run(paragraph, m.group(1), style_cfg, bold=True, italic=base_italic)
        pos = m.end()
    if pos < len(text):
        _add_italic_segment(paragraph, text[pos:], style_cfg, base_bold, base_italic)


def _add_italic_segment(paragraph, text, style_cfg, base_bold=False, base_italic=False):
    pos = 0
    for m in INLINE_ITAL_RE.finditer(text):
        if m.start() > pos:
            _make_run(paragraph, text[pos:m.start()], style_cfg, bold=base_bold, italic=base_italic)
        _make_run(paragraph, m.group(1), style_cfg, bold=base_bold, italic=True)
        pos = m.end()
    if pos < len(text):
        _make_run(paragraph, text[pos:], style_cfg, bold=base_bold, italic=base_italic)


def add_heading(doc, text, level, style_cfg):
    """Emit a real Word Heading style so the outline / nav pane / TOC work,
    then override colour and font to match the chosen house style."""
    sizes = style_cfg["heading_sizes"]
    p = doc.add_paragraph(style=f"Heading {level}")
    p.paragraph_format.space_before = Pt(12 if level <= 2 else 8)
    p.paragraph_format.space_after = Pt(6)
    p.paragraph_format.keep_with_next = True
    r = p.add_run(text); r.bold = True
    r.font.name = style_cfg["heading_font"]
    r.font.size = Pt(sizes.get(level, 12))
    rPr = r._element.get_or_add_rPr()
    color = OxmlElement("w:color"); color.set(qn("w:val"), style_cfg["heading_color"])
    rPr.append(color)
    rFonts = OxmlElement("w:rFonts")
    rFonts.set(qn("w:ascii"), style_cfg["heading_font"])
    rFonts.set(qn("w:hAnsi"), style_cfg["heading_font"])
    rFonts.set(qn("w:cs"), style_cfg["heading_font"])
    rPr.append(rFonts)


def add_callout(doc, label, text, style_cfg, icon_path=None):
    t = _bordered_table(doc, rows=1, cols=2, style_cfg=style_cfg)
    t.columns[0].width = Cm(2.5); t.columns[1].width = Cm(14.0)
    left = t.rows[0].cells[0]; right = t.rows[0].cells[1]
    left.width = Cm(2.5); right.width = Cm(14.0)
    left.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    right.vertical_alignment = WD_ALIGN_VERTICAL.TOP
    left.text = ""
    if icon_path and Path(icon_path).exists():
        lp = left.paragraphs[0]; lp.alignment = WD_ALIGN_PARAGRAPH.CENTER
        try:
            lp.add_run().add_picture(str(icon_path), width=Cm(style_cfg["callout_icon_max_cm"]))
        except Exception:
            pass
    right.text = ""
    lp = right.paragraphs[0]; lp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    lp.paragraph_format.space_before = Pt(0); lp.paragraph_format.space_after = Pt(2)
    _make_run(lp, f"{label.upper()}!", style_cfg, bold=True)
    bp = right.add_paragraph(); bp.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
    bp.paragraph_format.space_before = Pt(0); bp.paragraph_format.space_after = Pt(0)
    add_runs(bp, text, style_cfg)
    doc.add_paragraph()


def insert_image(doc, image_path, style_cfg, labels=None, max_width_cm=12.0, align="center"):
    p = doc.add_paragraph()
    p.alignment = {"center": WD_ALIGN_PARAGRAPH.CENTER, "left": WD_ALIGN_PARAGRAPH.LEFT,
                   "right": WD_ALIGN_PARAGRAPH.RIGHT}.get(align, WD_ALIGN_PARAGRAPH.CENTER)
    run = p.add_run()
    try:
        run.add_picture(str(image_path), width=Cm(max_width_cm))
    except Exception as e:
        wp = doc.add_paragraph()
        _make_run(wp, f"[image could not be embedded: {Path(image_path).name} — {e}]",
                  style_cfg, italic=True)
        return
    if labels:
        # Labels-table header is generic; the translator emits language pair via labels.json
        src_header = labels[0].get("source_label_header", "Source")
        tgt_header = labels[0].get("target_label_header", "Target")
        t = _bordered_table(doc, rows=len(labels)+1, cols=2, style_cfg=style_cfg)
        h0 = t.rows[0].cells[0].paragraphs[0]; _make_run(h0, src_header, style_cfg, bold=True)
        h1 = t.rows[0].cells[1].paragraphs[0]; _make_run(h1, tgt_header, style_cfg, bold=True)
        for i, lbl in enumerate(labels, start=1):
            c0 = t.rows[i].cells[0].paragraphs[0]; _make_run(c0, lbl.get("source", ""), style_cfg)
            c1 = t.rows[i].cells[1].paragraphs[0]; _make_run(c1, lbl.get("target", ""), style_cfg)
        doc.add_paragraph()


def render_markdown(doc, md_text, work_dir, style_cfg, callout_re):
    lines = md_text.splitlines()
    i = 0
    while i < len(lines):
        line = lines[i]; stripped = line.strip()
        if HR_RE.match(stripped):
            p = doc.add_paragraph(); pPr = p._p.get_or_add_pPr()
            pBdr = OxmlElement("w:pBdr"); b = OxmlElement("w:bottom")
            b.set(qn("w:val"), "single"); b.set(qn("w:sz"), "6")
            b.set(qn("w:space"), "1"); b.set(qn("w:color"), "000000")
            pBdr.append(b); pPr.append(pBdr); i += 1; continue
        if not stripped: i += 1; continue
        if stripped.startswith("@@IMAGE"):
            m_dir = re.match(r"@@IMAGE\s+path=(\S+)(?:\s+width=([\d.]+)cm)?(?:\s+align=(\w+))?\s*@@", stripped)
            if m_dir:
                p_path = (work_dir / m_dir.group(1)).resolve()
                width = float(m_dir.group(2)) if m_dir.group(2) else 12.0
                align = m_dir.group(3) or "center"
                insert_image(doc, p_path, style_cfg, max_width_cm=width, align=align)
            i += 1; continue
        m_img = IMG_RE.match(stripped)
        if m_img:
            img_abs = (work_dir / m_img.group("path")).resolve()
            lbl_path = img_abs.with_suffix(".labels.json"); labels = None
            if lbl_path.exists():
                try: labels = json.loads(lbl_path.read_text(encoding="utf-8"))
                except Exception: labels = None
            insert_image(doc, img_abs, style_cfg, labels=labels); i += 1; continue
        m_h = H_RE.match(stripped)
        if m_h:
            add_heading(doc, m_h.group(2), min(len(m_h.group(1)), 4), style_cfg); i += 1; continue
        m_c = callout_re.match(stripped)
        if m_c:
            label = m_c.group(1); body = [m_c.group(2)]; i += 1
            while i < len(lines) and lines[i].strip().startswith(">"):
                body.append(lines[i].strip().lstrip(">").strip()); i += 1
            icon = work_dir / "callout_icon.png"
            add_callout(doc, label, " ".join(body).strip(), style_cfg,
                        icon_path=icon if icon.exists() else None)
            continue
        if "|" in stripped and i+1 < len(lines) and TABLE_SEP_RE.match(lines[i+1]):
            header_cells = [c.strip() for c in stripped.strip("|").split("|")]
            i += 2; rows = []
            while i < len(lines) and "|" in lines[i].strip():
                rows.append([c.strip() for c in lines[i].strip().strip("|").split("|")]); i += 1
            t = _bordered_table(doc, rows=len(rows)+1, cols=len(header_cells), style_cfg=style_cfg)
            for j, h in enumerate(header_cells):
                t.rows[0].cells[j].text = ""
                p = t.rows[0].cells[j].paragraphs[0]
                p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(0)
                add_runs(p, h, style_cfg, base_bold=True)
            for r, rc in enumerate(rows, start=1):
                for j, val in enumerate(rc[:len(header_cells)]):
                    cell = t.rows[r].cells[j]; cell.text = ""
                    p = cell.paragraphs[0]
                    p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(0)
                    add_runs(p, val, style_cfg)
            doc.add_paragraph(); continue
        m_l = LIST_RE.match(line)
        if m_l:
            bullet = m_l.group(2)
            indent = m_l.group(1)
            level = (len(indent) // 2) if indent else 0
            if bullet.endswith("."):
                p = doc.add_paragraph()
                p.paragraph_format.left_indent = Cm(0.6 + 0.6 * level)
                p.paragraph_format.first_line_indent = Cm(-0.6)
                p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(2)
                pr = p.add_run(f"{bullet} ")
                pr.font.name = style_cfg["body_font"]; pr.font.size = Pt(style_cfg["body_size_pt"])
                add_runs(p, m_l.group(3), style_cfg)
            else:
                p = doc.add_paragraph()
                p.paragraph_format.left_indent = Cm(0.6 + 0.6 * level)
                p.paragraph_format.first_line_indent = Cm(-0.4)
                p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(2)
                pr = p.add_run("•  ")
                pr.font.name = style_cfg["body_font"]; pr.font.size = Pt(style_cfg["body_size_pt"])
                add_runs(p, m_l.group(3), style_cfg)
            i += 1; continue
        # Plain paragraph
        para_lines = [stripped]; i += 1
        while i < len(lines) and lines[i].strip() and not H_RE.match(lines[i].strip()) \
                and not LIST_RE.match(lines[i]) and not IMG_RE.match(lines[i].strip()) \
                and not callout_re.match(lines[i].strip()) \
                and not lines[i].strip().startswith("@@IMAGE") and not HR_RE.match(lines[i].strip()):
            if "|" in lines[i] and i+1 < len(lines) and TABLE_SEP_RE.match(lines[i+1]): break
            para_lines.append(lines[i].strip()); i += 1
        p = doc.add_paragraph(); p.paragraph_format.space_after = Pt(6)
        add_runs(p, " ".join(para_lines), style_cfg)


def add_preface(doc, style_cfg, preface_md=None, manifest=None, glossary_path=None):
    add_heading(doc, "Translation Notice", level=1, style_cfg=style_cfg)
    if preface_md and Path(preface_md).exists():
        render_markdown(doc, Path(preface_md).read_text(encoding="utf-8"),
                        Path("."), style_cfg, callout_re=_callout_re(DEFAULT_HAZARD_WORDS))
    else:
        m = manifest or {}
        src = m.get("source", "")
        src_lang = m.get("source_language", "the source language")
        tgt_lang = m.get("target_language", "the target language")
        p = doc.add_paragraph()
        _make_run(p, "This is an unofficial working translation of ", style_cfg)
        _make_run(p, Path(src).name if src else "the source document", style_cfg, italic=True)
        _make_run(p, f" from {src_lang} into {tgt_lang}, prepared with the fidelity-translator skill (Anthropic Claude Opus 4.6).", style_cfg)
        p2 = doc.add_paragraph()
        _make_run(p2,
            "This document is NOT a certified or sworn translation. In case of discrepancy, "
            "the original source prevails. Technical terms have been translated against the "
            f"project glossary at {glossary_path or '<glossary not configured>'}. "
            "Engineering diagrams retain original labels; target-language equivalents are listed below each diagram.",
            style_cfg, italic=True)
    doc.add_page_break()


def set_document_defaults(doc, style_cfg):
    style = doc.styles["Normal"]
    style.font.name = style_cfg["body_font"]
    style.font.size = Pt(style_cfg["body_size_pt"])
    color_hex = style_cfg["heading_color"]
    rgb = RGBColor(int(color_hex[:2], 16), int(color_hex[2:4], 16), int(color_hex[4:6], 16))
    for sname in ("Heading 1", "Heading 2", "Heading 3", "Heading 4"):
        try:
            s = doc.styles[sname]
            s.font.name = style_cfg["heading_font"]
            s.font.color.rgb = rgb
        except KeyError:
            pass


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("work_dir")
    ap.add_argument("output")
    ap.add_argument("--preface", default=None)
    ap.add_argument("--house-style", default="formal-monochrome", choices=list(STYLES) + ["custom"])
    ap.add_argument("--style-config", default=None,
                    help="JSON file with style overrides; used when --house-style=custom")
    ap.add_argument("--hazard-words", default=None,
                    help="JSON file with additional hazard label words to recognise")
    args = ap.parse_args()

    if args.house_style == "custom":
        if not args.style_config:
            sys.stderr.write("ERROR: --house-style=custom requires --style-config <file.json>\n"); sys.exit(2)
        style_cfg = json.loads(Path(args.style_config).read_text(encoding="utf-8"))
    else:
        style_cfg = dict(STYLES[args.house_style])

    hazard_words = set(DEFAULT_HAZARD_WORDS)
    if args.hazard_words:
        hazard_words |= set(json.loads(Path(args.hazard_words).read_text(encoding="utf-8")))
    callout_re = _callout_re(hazard_words)

    work_dir = Path(args.work_dir).resolve()
    manifest = json.loads((work_dir / "manifest.json").read_text(encoding="utf-8"))
    glossary_path = manifest.get("glossary_path")

    doc = Document()
    set_document_defaults(doc, style_cfg)
    add_preface(doc, style_cfg, args.preface, manifest, glossary_path)

    order_file = work_dir / "translated" / "order.json"
    if order_file.exists():
        order = json.loads(order_file.read_text(encoding="utf-8"))
    else:
        order = sorted([p.stem for p in (work_dir / "translated").glob("*.md")])

    for chunk_id in order:
        md_path = work_dir / "translated" / f"{chunk_id}.md"
        if not md_path.exists():
            sys.stderr.write(f"WARN: missing chunk {chunk_id}\n"); continue
        render_markdown(doc, md_path.read_text(encoding="utf-8"), work_dir, style_cfg, callout_re)
        doc.add_page_break()

    Path(args.output).parent.mkdir(parents=True, exist_ok=True)
    doc.save(args.output)
    print(f"Wrote {args.output} ({args.house_style} style, {len(order)} chunks)")


if __name__ == "__main__":
    main()
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall