"""Generate authenticated Word downloads from the canonical SOP Markdown files. Run with the bundled document Python runtime, then render/inspect all outputs. """ from pathlib import Path import hashlib import json import re from docx import Document from docx.shared import Cm, Pt, RGBColor from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT from docx.oxml import OxmlElement from docx.oxml.ns import qn ROOT = Path(__file__).resolve().parents[1] SOURCE = ROOT / 'content/docs' OUTPUT = ROOT / 'content/word' OUTPUT.mkdir(exist_ok=True) def plain(text): text = re.sub(r'\[([^\]]+)\]\([^)]*\)', r'\1', text) return text.replace('**', '').replace('`', '').replace('- [ ] ', '□ ').strip() def style_run(run, bold=False, size=None): run.font.name = 'Arial' run.font.color.rgb = RGBColor(0, 0, 0) run.bold = bold if size: run.font.size = Pt(size) fonts = run._element.get_or_add_rPr().get_or_add_rFonts() fonts.set(qn('w:eastAsia'), 'SimSun') def add_inline(paragraph, text): text = re.sub(r'\[([^\]]+)\]\([^)]*\)', r'\1', text) parts = re.split(r'(\*\*[^*]+\*\*)', text) for part in parts: bold = part.startswith('**') and part.endswith('**') run = paragraph.add_run(part[2:-2] if bold else part.replace('`', '')) style_run(run, bold=bold) def initialize(title): doc = Document() for border in doc.styles.element.xpath('.//w:pBdr'): border.getparent().remove(border) for fonts in doc.styles.element.xpath('.//w:rFonts'): for attribute in ['asciiTheme', 'hAnsiTheme', 'eastAsiaTheme', 'cstheme']: fonts.attrib.pop(qn('w:' + attribute), None) section = doc.sections[0] section.page_width = Cm(21) section.page_height = Cm(29.7) section.top_margin = Cm(2) section.bottom_margin = Cm(2) section.left_margin = Cm(2) section.right_margin = Cm(2) section.header_distance = Cm(.8) section.footer_distance = Cm(.8) for grid in section._sectPr.findall(qn('w:docGrid')): section._sectPr.remove(grid) for name in ['Normal', 'Title', 'Heading 1', 'Heading 2', 'Heading 3', 'Heading 4']: style = doc.styles[name] style.font.name = 'Arial' style.font.color.rgb = RGBColor(0, 0, 0) style._element.get_or_add_rPr().get_or_add_rFonts().set(qn('w:eastAsia'), 'SimSun') style.paragraph_format.space_before = Pt(0) style.paragraph_format.space_after = Pt(6) style.paragraph_format.line_spacing = 1.2 snap = OxmlElement('w:snapToGrid'); snap.set(qn('w:val'), '0'); style._element.get_or_add_pPr().append(snap) doc.styles['Normal'].font.size = Pt(10.5) doc.styles['Normal'].paragraph_format.widow_control = True doc.styles['Title'].font.size = Pt(22) doc.styles['Title'].paragraph_format.space_after = Pt(16) for name, size in [('Heading 1', 16), ('Heading 2', 13), ('Heading 3', 11.5), ('Heading 4', 11)]: doc.styles[name].font.size = Pt(size) doc.styles[name].font.bold = True doc.styles[name].paragraph_format.keep_with_next = True doc.styles[name].paragraph_format.space_before = Pt(14) doc.styles[name].paragraph_format.space_after = Pt(7) title_paragraph = doc.add_paragraph(style='Title') style_run(title_paragraph.add_run(title), size=22) intro = doc.add_paragraph('可使用 Word 或 WPS 填写。填写完成后上传到需求记录,或通过系统关联文档链接。' if '模板' in title else '本规范用于明确需求、开发、验收与发布过程中的职责和交付要求。配套模板可在系统“流程与规范”中查看。') intro.paragraph_format.space_after = Pt(14) footer = section.footer.paragraphs[0] footer.alignment = WD_ALIGN_PARAGRAPH.RIGHT style_run(footer.add_run('第 '), size=9) field = OxmlElement('w:fldSimple'); field.set(qn('w:instr'), 'PAGE'); footer._p.append(field) style_run(footer.add_run(' 页'), size=9) doc.core_properties.author = '需有序' doc.core_properties.title = title doc.core_properties.subject = '业务协作模板' if '模板' in title else '软件开发流程管理规范' return doc def add_table(doc, lines): rows = [[plain(cell) for cell in line.strip().strip('|').split('|')] for line in lines] rows = [row for row in rows if not all(re.fullmatch(r':?-+:?', cell.replace(' ', '')) for cell in row)] if not rows: return columns = len(rows[0]) weights = [max(8, min(34, max(len(row[i]) if i < len(row) else 0 for row in rows))) for i in range(columns)] total = sum(weights) widths = [17 * weight / total for weight in weights] if rows[0] == ['验收编号', '关联功能', '场景/操作', '预期结果', '验收结果', '证据/缺陷编号']: widths = [1.8, 1.8, 3.9, 3.9, 2.2, 3.4] for row in rows[1:]: row[4] = row[4].replace('/', '\n') elif rows[0] == ['日期及文档版本', '变更内容及原因', '影响评估', '调整后的范围及计划', '确认人']: widths = [2.5, 4.3, 3.7, 4.5, 2] rows[0][0] = '日期及\n文档版本' elif rows[0] == ['角色', '主要职责', '主要交付或确认事项']: widths = [3, 7, 7] table = doc.add_table(rows=1, cols=columns) table.alignment = WD_TABLE_ALIGNMENT.CENTER table.autofit = False for column, width in zip(table.columns, widths): column.width = Cm(width) props = table._tbl.tblPr borders = OxmlElement('w:tblBorders') for edge in ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']: item = OxmlElement('w:' + edge) for key, value in [('val', 'single'), ('sz', '4'), ('color', 'D9D9D9')]: item.set(qn('w:' + key), value) borders.append(item) props.append(borders) for index, row in enumerate(rows): cells = table.rows[0].cells if index == 0 else table.add_row().cells table.rows[index]._tr.get_or_add_trPr().append(OxmlElement('w:cantSplit')) for col, cell in enumerate(cells): cell.width = Cm(widths[col]) cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER cell_props = cell._tc.get_or_add_tcPr() margins = OxmlElement('w:tcMar') for edge in ['top', 'left', 'bottom', 'right']: item = OxmlElement('w:' + edge); item.set(qn('w:w'), '95'); item.set(qn('w:type'), 'dxa'); margins.append(item) cell_props.append(margins) if index == 0: fill = OxmlElement('w:shd'); fill.set(qn('w:fill'), 'E8EFF7'); cell_props.append(fill) para = cell.paragraphs[0] para.paragraph_format.line_spacing = 1.25 para.paragraph_format.space_after = Pt(3) para.paragraph_format.space_before = Pt(3) value = row[col] if col < len(row) else '' style_run(para.add_run(value), bold=index == 0, size=9.5) if index == 0 or (len(value) < 8 and columns > 2): para.alignment = WD_ALIGN_PARAGRAPH.CENTER if index == 0: repeat = OxmlElement('w:tblHeader'); table.rows[0]._tr.get_or_add_trPr().append(repeat) doc.add_paragraph().paragraph_format.space_after = Pt(2) def build(path): source = path.read_text() lines = source.splitlines() title = plain(lines[0].lstrip('# ')) title = re.sub(r'^附件\d+[::]\s*', '', title) doc = initialize(title) fenced = False index = 1 while index < len(lines): line = lines[index] stripped = line.strip() if stripped.startswith('```'): fenced = not fenced; index += 1; continue if not stripped: index += 1; continue if not fenced and stripped.startswith('|'): group = [] while index < len(lines) and lines[index].strip().startswith('|'): group.append(lines[index]); index += 1 add_table(doc, group); continue heading = re.match(r'^(#{2,5})\s+(.+)$', stripped) if heading: doc.add_heading(plain(heading[2]), min(len(heading[1]) - 1, 4)) elif fenced and (re.match(r'^[一二三四五六七八九十]+、', stripped) or (stripped.startswith('【') and stripped.endswith('】'))): doc.add_heading(plain(stripped.strip('【】')), 2) else: text = stripped if text.startswith('> '): text = text[2:] if text.startswith('- [ ] '): text = '□ ' + text[6:] elif text.startswith('- '): text = '• ' + text[2:] if fenced and text.endswith(':'): text += '【填写】' paragraph = doc.add_paragraph() add_inline(paragraph, text) if fenced and line.startswith(' '): paragraph.paragraph_format.left_indent = Cm(.5) paragraph.paragraph_format.space_after = Pt(7) elif fenced: paragraph.paragraph_format.space_after = Pt(6) index += 1 destination = OUTPUT / (path.stem + '.docx') doc.save(destination) return {'source': path.name, 'sourceSha256': hashlib.sha256(path.read_bytes()).hexdigest(), 'file': destination.name, 'fileSha256': hashlib.sha256(destination.read_bytes()).hexdigest()} manifest = [build(path) for path in sorted(SOURCE.glob('*.md'))] assert len(manifest) == 8 (OUTPUT / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n') print(json.dumps({'generated': len(manifest), 'directory': str(OUTPUT)}, ensure_ascii=False))