fix(codex): 完善独立运行与文档转换兼容性

This commit is contained in:
zhiye.sun
2026-08-31 13:18:41 +08:00
parent 485e65dfd9
commit 5d7a77b8ba
7 changed files with 53 additions and 14 deletions
+2 -1
View File
@@ -12,7 +12,8 @@ description: 将 Markdown 文档转换为 Word .docx,保留常见标题、段
- 只接受存在的 `.md` 或 `.markdown` 文件。
- 默认在输入文件旁生成同名 `.docx`;文件已存在时停止,只有用户明确同意覆盖后才传入 `--force`。
- 用户提供 `.docx` 模板时可传入 `--template`,转换器沿用模板样式并在文档末尾追加内容,不替换模板中的占位符。
- 不自动下载图片、字体或依赖;远程图片保留为文字提示,本地缺失图片产生警告。
- 转换依赖 Python 包 `python-docx`。优先使用 Codex 工作区依赖运行时;环境缺失时停止并给出提示,不自动安装依赖。
- 不自动下载图片或字体;远程图片保留为文字提示,本地缺失图片产生警告。
- 不伪造修订记录、批注或目录。需要人工审阅留痕时应使用独立的文档修订流程。
## 转换流程
@@ -9,10 +9,6 @@ import sys
from dataclasses import dataclass, field
from pathlib import Path
from docx import Document
from docx.shared import Inches, Pt
@dataclass
class Result:
"""记录生成物与转换统计。"""
@@ -43,6 +39,10 @@ class Converter:
"""使用可预测的小型解析器转换常见 Markdown。"""
def __init__(self, source: Path, output: Path, template: Path | None) -> None:
# 第三方库在真正转换时才加载,使 --help、参数错误和能力探测不依赖本机预装包。
from docx import Document
self.document_type = Document
self.source = source
self.doc = Document(template) if template else Document()
self.result = Result(output)
@@ -61,12 +61,14 @@ class Converter:
self.add_line(lines[index])
index += 1
self.doc.save(self.result.output)
Document(self.result.output)
self.document_type(self.result.output)
return self.result
def add_code(self, lines: list[str], start: int) -> int:
"""读取围栏代码块;未闭合时输出其余内容并记录警告。"""
from docx.shared import Pt
index = start + 1
content: list[str] = []
while index < len(lines) and not lines[index].lstrip().startswith("```"):
@@ -101,6 +103,8 @@ class Converter:
def add_line(self, line: str) -> None:
"""识别标题、列表、引用、分隔线和普通段落。"""
from docx.shared import Inches
value = line.strip()
if not value:
return
@@ -158,6 +162,8 @@ class Converter:
def add_image(self, paragraph, alt: str, target: str) -> None:
"""只处理本地图片,防止转换过程产生隐式网络访问。"""
from docx.shared import Inches
if re.match(r"^[a-z][a-z0-9+.-]*://", target, re.I):
paragraph.add_run(f"[远程图片:{alt or target}]")
self.result.warnings.append(f"未下载远程图片:{target}")
@@ -193,9 +199,22 @@ def main(argv: list[str] | None = None) -> int:
print("错误:输出必须是可写的 .docx;覆盖需使用 --force", file=sys.stderr); return 1
if template and (not template.is_file() or template.suffix.lower() != ".docx"):
print("错误:模板必须是存在的 .docx 文件", file=sys.stderr); return 2
try:
converter = Converter(source, output, template)
except ModuleNotFoundError as error:
if error.name == "docx":
print(
"错误:缺少 python-docx。请使用 Codex 工作区依赖运行时,"
"或在已获授权的本地 Python 环境中安装 python-docx 后重试。",
file=sys.stderr,
)
return 3
raise
except (OSError, ValueError) as error:
print(f"错误:{error}", file=sys.stderr); return 1
output.parent.mkdir(parents=True, exist_ok=True)
try:
result = Converter(source, output, template).convert()
result = converter.convert()
except (OSError, ValueError) as error:
print(f"错误:{error}", file=sys.stderr); return 1
print(f"DOCX:{result.output}")