Compare commits
2 Commits
c29a3e6af0
...
fc6afdea9d
| Author | SHA1 | Date | |
|---|---|---|---|
| fc6afdea9d | |||
| 74d28ea2d8 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -20,3 +20,7 @@ wheels/
|
||||
*.docx
|
||||
*.doc
|
||||
*.txt
|
||||
|
||||
.vscode/
|
||||
.tmp/
|
||||
*.toml
|
||||
|
||||
@@ -4,6 +4,7 @@ from .parser import parse_markdown
|
||||
from .body import body_to_paragraphs, replace_placeholder
|
||||
from .renderer import generate_thesis
|
||||
from .config import load_config, ThesisConfig
|
||||
from .references import references_to_paragraphs, format_gb7714
|
||||
|
||||
__all__ = [
|
||||
"parse_markdown",
|
||||
@@ -12,4 +13,6 @@ __all__ = [
|
||||
"generate_thesis",
|
||||
"load_config",
|
||||
"ThesisConfig",
|
||||
"references_to_paragraphs",
|
||||
"format_gb7714",
|
||||
]
|
||||
|
||||
@@ -6,7 +6,9 @@ Markdown 正文 → Word 段落转换。
|
||||
"""
|
||||
|
||||
import re
|
||||
from copy import deepcopy
|
||||
from docx import Document
|
||||
from docx.oxml.ns import qn
|
||||
|
||||
_PAT_HEADING = re.compile(r"^(#{1,6})\s+(.+)$", re.MULTILINE)
|
||||
|
||||
@@ -84,6 +86,11 @@ def replace_placeholder(
|
||||
placeholder_style = para.style.name if para.style else None
|
||||
parent = para._element.getparent()
|
||||
idx = list(parent).index(para._element)
|
||||
|
||||
# 保存原段落的编号属性(numPr),用于继承自动编号
|
||||
orig_pPr = para._element.find(qn("w:pPr"))
|
||||
numPr = orig_pPr.find(qn("w:numPr")) if orig_pPr is not None else None
|
||||
|
||||
parent.remove(para._element)
|
||||
|
||||
for pd_data in reversed(paragraphs):
|
||||
@@ -93,15 +100,24 @@ def replace_placeholder(
|
||||
# 尝试应用样式,逐步降级
|
||||
applied = _apply_style(new_p, doc, style_name)
|
||||
if not applied and style_name.startswith("Heading"):
|
||||
# 标题样式找不到
|
||||
new_p.style = doc.styles["Normal"]
|
||||
elif not applied:
|
||||
# 正文样式找不到 → 尝试占位符自身的样式
|
||||
if placeholder_style:
|
||||
_apply_style(new_p, doc, placeholder_style)
|
||||
if new_p.style.name == "Normal" and placeholder_style:
|
||||
new_p.style = doc.styles[placeholder_style]
|
||||
|
||||
# 继承原段落的编号属性(自动编号)
|
||||
if numPr is not None:
|
||||
new_pPr = new_p._element.find(qn("w:pPr"))
|
||||
if new_pPr is None:
|
||||
new_pPr = new_p._element.makeelement(qn("w:pPr"), {})
|
||||
new_p._element.insert(0, new_pPr)
|
||||
existing = new_pPr.find(qn("w:numPr"))
|
||||
if existing is not None:
|
||||
new_pPr.remove(existing)
|
||||
new_pPr.append(deepcopy(numPr))
|
||||
|
||||
parent.insert(idx, new_p._element)
|
||||
break
|
||||
|
||||
|
||||
@@ -6,17 +6,15 @@ import tomllib
|
||||
|
||||
@dataclass
|
||||
class ThesisConfig:
|
||||
"""论文配置数据(学生信息、元数据等,不包含正文内容)。"""
|
||||
"""论文配置数据。
|
||||
|
||||
student_name: str = "<None>"
|
||||
student_id: str = "<None>"
|
||||
college: str = "<None>"
|
||||
major: str = "<None>"
|
||||
class_: str = "<None>"
|
||||
advisor: str = "<None>"
|
||||
advisor_title: str = "<None>"
|
||||
title: str = "<None>"
|
||||
``metadata`` 直接透传 TOML 的 ``[metadata]`` 节,不再为每个变量声明字段。
|
||||
新增模板变量只需改 TOML,无需修改 Python。
|
||||
"""
|
||||
|
||||
metadata: dict = field(default_factory=dict)
|
||||
|
||||
# 以下字段仍有业务逻辑,保留为显式属性
|
||||
title_from_md: bool = True
|
||||
body_start_keywords: list[str] = field(default_factory=lambda: ["绪论", "引言"])
|
||||
body_end_keywords: list[str] = field(
|
||||
@@ -24,19 +22,11 @@ class ThesisConfig:
|
||||
)
|
||||
body_style: str = "Body Text Indent"
|
||||
level_offset: int = -1
|
||||
reference_style: str = "列出段落1"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转成模板渲染用的扁平字典,排除 options 命名空间。"""
|
||||
return {
|
||||
"student_name": self.student_name,
|
||||
"student_id": self.student_id,
|
||||
"college": self.college,
|
||||
"major": self.major,
|
||||
"class": self.class_,
|
||||
"advisor": self.advisor,
|
||||
"advisor_title": self.advisor_title,
|
||||
"title": self.title,
|
||||
}
|
||||
"""透传 metadata(模板变量来源)。"""
|
||||
return self.metadata
|
||||
|
||||
|
||||
def load_config(path: str | Path) -> ThesisConfig:
|
||||
@@ -49,14 +39,7 @@ def load_config(path: str | Path) -> ThesisConfig:
|
||||
opts = raw.get("options", {})
|
||||
|
||||
return ThesisConfig(
|
||||
student_name=meta.get("student_name", "<None>"),
|
||||
student_id=meta.get("student_id", "<None>"),
|
||||
college=meta.get("college", "<None>"),
|
||||
major=meta.get("major", "<None>"),
|
||||
class_=meta.get("class", "<None>"),
|
||||
advisor=meta.get("advisor", "<None>"),
|
||||
advisor_title=meta.get("advisor_title", "<None>"),
|
||||
title=meta.get("title", "<None>"),
|
||||
metadata=meta,
|
||||
title_from_md=opts.get("title_from_md", True),
|
||||
body_start_keywords=opts.get("body_start_keywords", ["绪论", "引言"]),
|
||||
body_end_keywords=opts.get(
|
||||
@@ -64,4 +47,5 @@ def load_config(path: str | Path) -> ThesisConfig:
|
||||
),
|
||||
body_style=opts.get("body_style", "Body Text Indent"),
|
||||
level_offset=opts.get("level_offset", -1),
|
||||
reference_style=opts.get("reference_style", "列出段落1"),
|
||||
)
|
||||
|
||||
114
transit/references.py
Normal file
114
transit/references.py
Normal file
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
GB 7714 《文后参考文献著录规则》顺序编码制 — 参考文献解析与格式化。
|
||||
|
||||
将 Markdown 中 ``[N] ... [TYPE] ...`` 格式的参考文献逐条解析,
|
||||
按文献类型(书 M、期刊 J、会议 C、学位论文 D、标准 S、电子资源 EB/OL 等)
|
||||
重新编排为符合 GB 7714 规范的格式,并输出为独立段落。
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
# 单行匹配: [N] 开头
|
||||
_RE_LINE = re.compile(r"^\[(\d+)\]\s*(.*)$")
|
||||
# 文献类型标记: [M] [J] [C] [D] [S] [EB/OL] [P] [N]
|
||||
_RE_TYPE = re.compile(r"\[(\w+(?:/\w+)?)\]")
|
||||
|
||||
|
||||
# GB 7714 中各文献类型的标准格式模板(仅用于说明,实际格式化直接拼接)
|
||||
TYPE_LABELS: dict[str, str] = {
|
||||
"M": "专著",
|
||||
"J": "期刊文章",
|
||||
"C": "会议论文",
|
||||
"D": "学位论文",
|
||||
"S": "标准",
|
||||
"EB/OL": "电子资源",
|
||||
"P": "专利",
|
||||
"N": "报纸文章",
|
||||
}
|
||||
|
||||
|
||||
def parse_reference_line(line: str) -> Optional[dict]:
|
||||
"""解析单行参考文献,提取序号、作者+标题、文献类型、来源信息。
|
||||
|
||||
期望格式::
|
||||
|
||||
[N] Authors. Title[TYPE]. Source info.
|
||||
"""
|
||||
line = line.strip()
|
||||
m = _RE_LINE.match(line)
|
||||
if not m:
|
||||
return None
|
||||
|
||||
number = int(m.group(1))
|
||||
rest = m.group(2).strip()
|
||||
|
||||
# 定位文献类型标记 [TYPE]
|
||||
tm = _RE_TYPE.search(rest)
|
||||
if not tm:
|
||||
return None
|
||||
|
||||
before_type = rest[: tm.start()].strip().rstrip(".")
|
||||
doc_type = tm.group(1)
|
||||
after_type = rest[tm.end() :].strip().lstrip(".").strip()
|
||||
|
||||
return {
|
||||
"number": number,
|
||||
"before_type": before_type, # "Authors. Title"
|
||||
"doc_type": doc_type, # "M", "J", "EB/OL", …
|
||||
"after_type": after_type, # 来源信息
|
||||
}
|
||||
|
||||
|
||||
def _normalize_period(text: str) -> str:
|
||||
"""确保文本以英文句点结尾(GB 7714 要求)。"""
|
||||
text = text.rstrip()
|
||||
if text and not text.endswith("."):
|
||||
text += "."
|
||||
return text
|
||||
|
||||
|
||||
def format_gb7714(ref: dict) -> str:
|
||||
"""按 GB 7714 重新编排一条参考文献(不含序号前缀,由 Word 样式自动编号)。
|
||||
|
||||
格式::
|
||||
|
||||
Authors. Title[TYPE]. Source.
|
||||
"""
|
||||
bt = ref["before_type"]
|
||||
dt = ref["doc_type"]
|
||||
at = ref["after_type"]
|
||||
formatted = f"{bt}[{dt}]. {at}"
|
||||
return _normalize_period(formatted)
|
||||
|
||||
|
||||
def references_to_paragraphs(
|
||||
ref_text: str,
|
||||
ref_style: str = "列出段落1",
|
||||
) -> list[dict]:
|
||||
"""将参考文献原始文本转换为格式化段落列表。
|
||||
|
||||
返回的每个元素::
|
||||
|
||||
{"text": str, "level": 0, "style": ref_style}
|
||||
|
||||
每条参考文献为一个独立段落。
|
||||
"""
|
||||
if not ref_text or ref_text == "<None>":
|
||||
return [{"text": "<None>", "level": 0, "style": ref_style}]
|
||||
|
||||
lines = [l.strip() for l in ref_text.strip().split("\n") if l.strip()]
|
||||
paragraphs: list[dict] = []
|
||||
|
||||
for line in lines:
|
||||
ref = parse_reference_line(line)
|
||||
if ref:
|
||||
formatted = format_gb7714(ref)
|
||||
else:
|
||||
# 无法解析时,至少去掉 [N] 前缀
|
||||
fallback = re.sub(r"^\[\d+\]\s*", "", line)
|
||||
formatted = _normalize_period(fallback)
|
||||
|
||||
paragraphs.append({"text": formatted, "level": 0, "style": ref_style})
|
||||
|
||||
return paragraphs
|
||||
@@ -12,9 +12,11 @@ from docx import Document
|
||||
from .config import load_config, ThesisConfig
|
||||
from .parser import parse_markdown
|
||||
from .body import body_to_paragraphs, replace_placeholder
|
||||
from .references import references_to_paragraphs
|
||||
|
||||
|
||||
_TEXT_FIELDS = [
|
||||
# 解析器可能产生的字段(用于填充报告)
|
||||
_PARSER_FIELDS = [
|
||||
"title",
|
||||
"abstact_cn_context",
|
||||
"abstract_cn_keywords",
|
||||
@@ -23,13 +25,7 @@ _TEXT_FIELDS = [
|
||||
"acknowledgement",
|
||||
"reference",
|
||||
"appendix",
|
||||
"student_name",
|
||||
"student_id",
|
||||
"college",
|
||||
"major",
|
||||
"class",
|
||||
"advisor",
|
||||
"advisor_title",
|
||||
"body_md",
|
||||
]
|
||||
|
||||
|
||||
@@ -80,12 +76,11 @@ def generate_thesis(
|
||||
body_end_kw=config.body_end_keywords,
|
||||
)
|
||||
|
||||
# 3. 合并配置 → 上下文(配置优先)
|
||||
# 3. 合并配置 → 上下文(配置填充解析器未产生的空白)
|
||||
for k, v in config.to_dict().items():
|
||||
if k == "title" and config.title_from_md and context.get("title"):
|
||||
continue # 以 markdown 标题为准
|
||||
if v != "<None>":
|
||||
context[k] = v
|
||||
context.setdefault(k, v)
|
||||
|
||||
# 4. 用 defaultdict 兜底缺失键
|
||||
ctx = defaultdict(lambda: "<None>", context)
|
||||
@@ -97,8 +92,13 @@ def generate_thesis(
|
||||
if body_md else []
|
||||
)
|
||||
|
||||
# 6. 占位符
|
||||
# 6. 解析参考文献为段落列表
|
||||
ref_text = ctx.get("reference", "")
|
||||
ref_paragraphs = references_to_paragraphs(ref_text, ref_style=config.reference_style)
|
||||
|
||||
# 7. 占位符(替代模板变量,后处理时替换)
|
||||
ctx["body_placeholder"] = "__CONTEXT_PLACEHOLDER__"
|
||||
ctx["reference"] = "__REFERENCE_PLACEHOLDER__"
|
||||
|
||||
# 7. 渲染模板
|
||||
doc = DocxTemplate(str(template_path))
|
||||
@@ -108,28 +108,33 @@ def generate_thesis(
|
||||
temp_path = Path(output_path).with_suffix(".tmp")
|
||||
doc.save(str(temp_path))
|
||||
|
||||
# 9. 正文注入
|
||||
# 9. 正文注入+参考文献注入
|
||||
final_doc = Document(str(temp_path))
|
||||
replace_placeholder(
|
||||
final_doc, "__CONTEXT_PLACEHOLDER__", body_paragraphs,
|
||||
default_body_style=config.body_style,
|
||||
)
|
||||
replace_placeholder(
|
||||
final_doc, "__REFERENCE_PLACEHOLDER__", ref_paragraphs,
|
||||
default_body_style=config.reference_style,
|
||||
)
|
||||
final_doc.save(str(output_path))
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
print(f"[完成] 论文生成完成: {output_path}")
|
||||
|
||||
# 10. 字段填充报告
|
||||
# 10. 字段填充报告(动态收集所有模板与解析字段)
|
||||
report_fields = list(dict.fromkeys([*config.metadata.keys(), *_PARSER_FIELDS]))
|
||||
print("\n--- 字段填充情况 ---")
|
||||
for key in _TEXT_FIELDS:
|
||||
val = ctx[key]
|
||||
for key in report_fields:
|
||||
val = ctx.get(key, "<None>")
|
||||
if val == "<None>":
|
||||
print(f" [缺失] {key}")
|
||||
else:
|
||||
preview = str(val)[:60].replace("\n", " ")
|
||||
print(f" [OK] {key}: {preview}...")
|
||||
|
||||
missing = [k for k in _TEXT_FIELDS if ctx[k] == "<None>"]
|
||||
missing = [k for k in report_fields if ctx.get(k, "<None>") == "<None>"]
|
||||
if missing:
|
||||
print("\n[警告] 以下字段缺失,已填充 '<None>':")
|
||||
for f in missing:
|
||||
|
||||
Reference in New Issue
Block a user