fix(codex): 完善独立运行与文档转换兼容性
This commit is contained in:
@@ -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}")
|
||||
|
||||
Reference in New Issue
Block a user