mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-12-04 03:40:22 +08:00
1.1.73: adapt DSH 0.2.1-rc.2, Apache-2.0, lab-only default-deny.
This commit is contained in:
1 parent
8df4406a7c
commit
1ea067189c
114 files changed
+21198
-5183
No files matched your search
@@ -0,0 +1,617 @@
|
||||
#!/usr/bin/env python3
|
||||
"""autopilot — drives paper-pipeline without any human input.
|
||||
|
||||
The agent's whole job each turn is three commands:
|
||||
|
||||
python autopilot.py start --dir <folder> --direction "..." # once
|
||||
python autopilot.py next --dir <folder> # what to do now
|
||||
python autopilot.py done --dir <folder> # I did it
|
||||
|
||||
`next` prints a complete work order: the goal, the exact artifact paths that
|
||||
must exist when the step is finished, the pass criteria, and where to find the
|
||||
bare-tool procedure. `done` refuses to advance if the declared artifacts are
|
||||
missing or empty — that is what stops the pipeline from quietly skipping work.
|
||||
|
||||
Nothing here ever asks the user a question. Anything that would normally be a
|
||||
question becomes a recorded decision (see `decide`) or a recorded degradation
|
||||
(see `skip`).
|
||||
|
||||
Standard library only; Python 3.8+.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
STATE = "PAPER_STATE.json"
|
||||
SCHEMA = "paper-pipeline/1.2"
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# steps: id, name, group, required artifacts (relative paths; a trailing "/"
|
||||
# means "this directory must contain at least one file"), gate summary
|
||||
# --------------------------------------------------------------------------
|
||||
S = [
|
||||
("00", "总控进度判断", "项目与检索", [], "已确定当前步"),
|
||||
("01", "项目初始化", "项目与检索",
|
||||
["01_项目初始化/BRIEF.md"], "目标刊、篇幅、作者占位符已写死"),
|
||||
("02", "检索式生成", "项目与检索",
|
||||
["02_检索式生成/SEARCH_STRINGS.md"], "检索式可执行且返回非零结果"),
|
||||
("03", "检索与导出", "项目与检索",
|
||||
["03_检索与导出/SEARCH_LOG.md", "refs/"], "导出条数与日志一致"),
|
||||
("04", "选题与空白识别", "项目与检索",
|
||||
["04_选题与空白识别/TOPIC.md"], "无「已有人做过」的硬伤"),
|
||||
("05", "对标库深度学习", "文献与证据",
|
||||
["05_对标库深度学习/BENCHMARK.md"], "≥5 篇,每篇写明借鉴点"),
|
||||
("06", "文献筛选分类", "文献与证据",
|
||||
["06_文献筛选分类/SELECTION.csv"], "每条有纳入/排除理由"),
|
||||
("07", "导入引用库取全文", "文献与证据",
|
||||
["07_导入引用库取全文/PDF_STATUS.md", "refs/"], "缺失项有清单"),
|
||||
("08", "文献精读", "文献与证据",
|
||||
["08_文献精读/NOTES/"], "每篇留下可引用条目"),
|
||||
("09", "论文框架搭建", "框架与写作",
|
||||
["09_论文框架搭建/OUTLINE.md"], "到三级标题,每节标图表号"),
|
||||
("10", "图表制作与引用", "框架与写作",
|
||||
["10_图表制作与引用/FIGPLAN.md", "figures/"], "图号连续、引用顺序正确"),
|
||||
("11", "摘要与引言", "框架与写作",
|
||||
["manuscript/00_abstract.md", "manuscript/01_intro.md"], "引言每段有出处"), ("12", "方法与结果", "框架与写作",
|
||||
["manuscript/02_methods.md", "manuscript/03_results.md",
|
||||
"data/", "12_方法与结果/model_verify.json"],
|
||||
"每个数字能追到 data/ 里的源文件;数据带溯源;模型自检通过"),
|
||||
("13", "讨论与结论", "框架与写作",
|
||||
["manuscript/04_discussion.md", "manuscript/05_conclusions.md"],
|
||||
"不与结果整句重复;局限逐条列明"),
|
||||
("14", "目标期刊选择", "投稿与返修",
|
||||
["14_目标期刊选择/JOURNALS.csv"], "有来源;已排除掠夺性刊"),
|
||||
("15", "目标期刊格式学习", "投稿与返修",
|
||||
["15_目标期刊格式学习/FORMAT_CHECKLIST.md"], "逐条对照过"),
|
||||
("16", "润色与语言打磨", "投稿与返修",
|
||||
["16_润色与语言打磨/scan_report.json"], "去 AI 痕迹判定项全过"),
|
||||
("17", "图片版权", "投稿与返修",
|
||||
["17_图片版权/RIGHTS.md"], "每张图来源与版权状态有记录"),
|
||||
("18", "Cover Letter", "投稿与返修",
|
||||
["18_CoverLetter/Cover_Letter.md"], "每个卖点正文里找得到"),
|
||||
("19", "终稿去 AI 痕迹与合规声明", "投稿与返修",
|
||||
["19_去AI痕迹/scan_after.json", "19_去AI痕迹/statement.md",
|
||||
"19_去AI痕迹/diff_check.md"],
|
||||
"判定项全过;数字/引用/图号对得上;声明已写"),
|
||||
("20", "投稿前总检", "投稿与返修",
|
||||
["20_投稿前总检/PRESUBMIT_CHECK.md", "submission/",
|
||||
"refs/citation_verify.json"],
|
||||
"引用与数字零上下文复核通过;所有引用已核验(无查不到/无撤稿)"),
|
||||
("21", "返修与回复", "投稿与返修",
|
||||
["21_返修/Response_Letter.md", "21_返修/CHANGES.md"],
|
||||
"每条意见有回复与改动位置"),
|
||||
]
|
||||
IDS = [s[0] for s in S]
|
||||
NAME = {s[0]: s[1] for s in S}
|
||||
GROUP = {s[0]: s[2] for s in S}
|
||||
ARTS = {s[0]: s[3] for s in S}
|
||||
GATE = {s[0]: s[4] for s in S}
|
||||
|
||||
|
||||
def _check_step_table() -> list[str]:
|
||||
"""Validate the step table itself before anything depends on it.
|
||||
|
||||
A duplicate id makes IDS.index() always return the first occurrence, so the
|
||||
pipeline silently stops advancing and loops on the same step forever. That
|
||||
happened once; this makes it impossible to ship again.
|
||||
"""
|
||||
problems = []
|
||||
expected = [f"{i:02d}" for i in range(len(S))]
|
||||
if IDS != expected:
|
||||
dupes = sorted({x for x in IDS if IDS.count(x) > 1})
|
||||
problems.append(
|
||||
f"步骤编号必须是连续的 00..{len(S) - 1:02d};"
|
||||
+ (f"重复的编号:{dupes};" if dupes else "")
|
||||
+ f"实际得到 {IDS}")
|
||||
if not S:
|
||||
problems.append("步骤表是空的")
|
||||
for sid, name, _g, arts, _gate in S:
|
||||
if not arts and sid != "00":
|
||||
problems.append(f"第 {sid} 步没有声明任何必需产出,done 无法核查")
|
||||
for a in arts:
|
||||
if not re.match(r"^[0-9]{2}_|^refs/|^manuscript/|^figures/|^data/|"
|
||||
r"^submission/|^journal_papers/", a):
|
||||
problems.append(f"第 {sid} 步的产出路径不像流水线目录:{a}")
|
||||
return problems
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# intake inference: pick a default venue / type / length from the direction so
|
||||
# the pipeline never has to stop and ask.
|
||||
# --------------------------------------------------------------------------
|
||||
VENUES = [
|
||||
# (keywords, venue, publisher, quartile, oa_note, length_words,
|
||||
# figures, refs, style_note)
|
||||
(("magnetorheological", "mre", "smart material", "adaptive structure"),
|
||||
"Smart Materials and Structures", "IOP", "Q2",
|
||||
"订阅制,可免费发表", "7000", "10", "40",
|
||||
"IOP 编号引用;方法要写到别人能复现"),
|
||||
(("vibration", "rotor", "absorber", "damper", "dynamic", "modal"),
|
||||
"Mechanical Systems and Signal Processing", "Elsevier", "Q1",
|
||||
"订阅制,可免费发表", "9000", "12", "50",
|
||||
"Elsevier 编号引用;验证与不确定度必须成节"),
|
||||
(("vibration", "rotor", "bearing", "absorber", "damper"),
|
||||
"Journal of Sound and Vibration", "Elsevier", "Q1/Q2",
|
||||
"订阅制,可免费发表", "8000", "12", "45",
|
||||
"重物理机理与解析对照"),
|
||||
(("machine tool", "spindle", "manufacturing", "machining", "additive"),
|
||||
"The International Journal of Advanced Manufacturing Technology",
|
||||
"Springer", "Q2", "订阅制,可免费发表", "7000", "10", "40",
|
||||
"Springer 编号引用;强调工艺可用性"),
|
||||
(("control", "anfis", "neural", "fuzzy", "adaptive"),
|
||||
"Journal of Vibration and Control", "SAGE", "Q2",
|
||||
"订阅制,可免费发表", "8000", "10", "45",
|
||||
"SAGE 编号引用;控制律要收敛性论证"),
|
||||
(("thermal", "heat transfer", "conjugate"),
|
||||
"International Journal of Thermal Sciences", "Elsevier", "Q1/Q2",
|
||||
"订阅制,可免费发表", "8000", "10", "45",
|
||||
"重实验或高保真数值验证"),
|
||||
(("fatigue", "fracture", "stress", "strain"),
|
||||
"International Journal of Fatigue", "Elsevier", "Q1",
|
||||
"订阅制,可免费发表", "8000", "10", "45",
|
||||
"重统计与分散性处理"),
|
||||
(("review", "survey", "overview"),
|
||||
"Mechanical Systems and Signal Processing", "Elsevier", "Q1",
|
||||
"订阅制,可免费发表", "12000", "14", "120",
|
||||
"综述:检索策略必须可复现"),
|
||||
]
|
||||
FALLBACK_VENUE = (
|
||||
"The International Journal of Advanced Manufacturing Technology",
|
||||
"Springer", "Q2", "订阅制,可免费发表", "7000", "10", "40",
|
||||
"未匹配到更具体的刊,落地到工程刊通用口径")
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def _utf8() -> None:
|
||||
for s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
s.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _die(msg: str, code: int = 2) -> None:
|
||||
print(msg, file=sys.stderr)
|
||||
raise SystemExit(code)
|
||||
|
||||
|
||||
def _path(root: str, rel: str) -> str:
|
||||
return os.path.join(root, rel.replace("/", os.sep))
|
||||
|
||||
|
||||
def _load(root: str) -> dict:
|
||||
p = os.path.join(root, STATE)
|
||||
if not os.path.isfile(p):
|
||||
_die(f"{p} 不存在。先跑:autopilot.py start --dir \"{root}\" "
|
||||
f"--direction \"<方向>\"")
|
||||
with io.open(p, encoding="utf-8") as fh:
|
||||
return json.load(fh)
|
||||
|
||||
|
||||
def _save(root: str, st: dict) -> None:
|
||||
st["updated_at"] = _now()
|
||||
with io.open(os.path.join(root, STATE), "w", encoding="utf-8") as fh:
|
||||
json.dump(st, fh, ensure_ascii=False, indent=1)
|
||||
with io.open(os.path.join(root, "PIPELINE.md"), "w", encoding="utf-8") as fh:
|
||||
fh.write(_human(st))
|
||||
with io.open(os.path.join(root, "DECISIONS.md"), "w", encoding="utf-8") as fh:
|
||||
fh.write(_decisions(st))
|
||||
|
||||
|
||||
def _human(st: dict) -> str:
|
||||
b = st.get("brief") or {}
|
||||
L = [f"# 论文流水线 · {st.get('title') or '(未命名)'}", ""]
|
||||
L.append(f"- **方向**:{st.get('direction') or '(未填)'}")
|
||||
for k, lab in (("type", "论文类型"), ("venue", "目标刊"),
|
||||
("quartile", "分区"), ("length_limit", "篇幅"),
|
||||
("figure_limit", "图表"), ("ref_limit", "参考文献"),
|
||||
("has_experiment", "实验数据"), ("authors", "作者")):
|
||||
if b.get(k):
|
||||
L.append(f"- **{lab}**:{b[k]}")
|
||||
L.append(f"- **模式**:{st.get('mode', 'autopilot(全自动,不询问)')}")
|
||||
L.append(f"- **更新**:{st.get('updated_at', '')}")
|
||||
L.append("")
|
||||
done = st.get("completed", [])
|
||||
cur = st.get("current")
|
||||
L.append(f"**进度 {len(done)}/{len(S)}** 当前:"
|
||||
+ (f"第 {cur} 步 · {NAME.get(cur, '')}" if cur else "全部完成"))
|
||||
L.append("")
|
||||
L.append("| 步 | 名称 | 组 | 状态 | 闸门 | 产出 |")
|
||||
L.append("|---:|---|---|---|---|---|")
|
||||
for sid, name, group, _a, _g in S:
|
||||
rec = (st.get("steps") or {}).get(sid) or {}
|
||||
if sid in done and rec.get("degraded"):
|
||||
status = "降级完成"
|
||||
elif sid in done:
|
||||
status = "已完成"
|
||||
elif sid == cur:
|
||||
status = "进行中"
|
||||
else:
|
||||
status = "未开始"
|
||||
arts = rec.get("artifacts") or []
|
||||
a = "、".join(f"`{x}`" for x in arts[:2]) + ("…" if len(arts) > 2 else "")
|
||||
L.append(f"| {sid} | {name} | {group} | {status} | "
|
||||
f"{rec.get('gate', '')} | {a} |")
|
||||
L.append("")
|
||||
log = st.get("log") or []
|
||||
if log:
|
||||
L.append("## 日志")
|
||||
L.append("")
|
||||
for e in log[-40:]:
|
||||
L.append(f"- `{e.get('at','')}` **{e.get('event','')}** "
|
||||
f"{e.get('step','')} {e.get('note','')}".rstrip())
|
||||
L.append("")
|
||||
return "\n".join(L)
|
||||
|
||||
|
||||
def _decisions(st: dict) -> str:
|
||||
L = ["# 自动决策记录 · DECISIONS", "",
|
||||
"流水线在运行中自己做的决定都记在这里。",
|
||||
"**用户不需要在开始时回答任何问题**;想改哪一条,直接改这个文件,"
|
||||
"流水线下一轮会读到。", ""]
|
||||
ds = st.get("decisions") or []
|
||||
if not ds:
|
||||
L.append("(还没有记录)")
|
||||
for i, d in enumerate(ds, 1):
|
||||
L.append(f"## D{i:02d} · {d.get('q','')}")
|
||||
L.append("")
|
||||
L.append(f"- **选择**:{d.get('choice','')}")
|
||||
L.append(f"- **理由**:{d.get('why','')}")
|
||||
L.append(f"- **怎么改**:{d.get('how_to_change','改这一行即可,流水线下一轮会读到')}")
|
||||
L.append(f"- **时间/步骤**:{d.get('at','')} · 第 {d.get('step','')} 步")
|
||||
L.append("")
|
||||
return "\n".join(L)
|
||||
|
||||
|
||||
def _infer_venue(direction: str) -> tuple:
|
||||
low = direction.lower()
|
||||
best, score = None, 0
|
||||
for kws, *rest in VENUES:
|
||||
s = sum(1 for k in kws if k in low)
|
||||
if s > score:
|
||||
best, score = rest, s
|
||||
if best is None:
|
||||
best = list(FALLBACK_VENUE)
|
||||
score = 0
|
||||
return tuple(best), score
|
||||
|
||||
|
||||
def _check_artifacts(root: str, rels: list[str]) -> list[str]:
|
||||
"""Return the list of declared artifacts that are missing or empty."""
|
||||
bad = []
|
||||
for rel in rels:
|
||||
p = _path(root, rel)
|
||||
if rel.endswith("/"):
|
||||
if not os.path.isdir(p):
|
||||
bad.append(rel + " (目录不存在)")
|
||||
continue
|
||||
files = [f for _d, _s, fs in os.walk(p) for f in fs]
|
||||
if not files:
|
||||
bad.append(rel + " (目录为空)")
|
||||
else:
|
||||
if not os.path.isfile(p):
|
||||
bad.append(rel + " (文件不存在)")
|
||||
elif os.path.getsize(p) < 40:
|
||||
bad.append(rel + f" (只有 {os.path.getsize(p)} 字节,基本是空文件)")
|
||||
return bad
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- commands
|
||||
def cmd_start(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
os.makedirs(root, exist_ok=True)
|
||||
sp = os.path.join(root, STATE)
|
||||
if os.path.isfile(sp) and not a.force:
|
||||
_die(f"{sp} 已存在。要重来加 --force。")
|
||||
if not (a.direction or "").strip():
|
||||
_die("必须给 --direction。全自动模式下这是唯一必需的输入。")
|
||||
|
||||
(venue, pub, quart, oa, length, figs, refs, style), score = \
|
||||
_infer_venue(a.direction)
|
||||
direction = a.direction.strip()
|
||||
title = a.title or direction[:40]
|
||||
|
||||
steps = {}
|
||||
log = [{"at": _now(), "event": "start", "step": "00",
|
||||
"note": f"方向:{direction}"}]
|
||||
decisions = [
|
||||
{"at": _now(), "step": "01", "q": "投哪个刊?",
|
||||
"choice": f"{venue}({pub},{quart})",
|
||||
"why": (f"从方向关键词匹配到该刊(匹配度 {score});{oa}。"
|
||||
"Q4 刊多为全 OA 且收费,订阅制 Q1–Q3 刊通常免费,故选此档。"),
|
||||
"how_to_change": "改这里,或直接改 14_目标期刊选择/JOURNALS.csv"},
|
||||
{"at": _now(), "step": "01", "q": "论文类型?",
|
||||
"choice": "research article",
|
||||
"why": "方向描述的是具体工作而非领域综述。",
|
||||
"how_to_change": "改为 review 会让第 09–13 步切换成综述骨架"},
|
||||
{"at": _now(), "step": "01", "q": "篇幅与图表上限?",
|
||||
"choice": f"{length} words / {figs} figures / {refs} refs",
|
||||
"why": f"取 {venue} 的常见量级。",
|
||||
"how_to_change": "改这里"},
|
||||
{"at": _now(), "step": "01", "q": "有没有真实实验数据?",
|
||||
"choice": a.has_experiment or "simulation-only",
|
||||
"why": ("用户未声明有实验数据,按计算/仿真研究处理,"
|
||||
"并在摘要与范围声明中写明。"),
|
||||
"how_to_change": "有数据就把这里改成 yes,第 12 步会加确认小节"},
|
||||
{"at": _now(), "step": "01", "q": "作者与单位?",
|
||||
"choice": a.authors or "占位符(待用户补真实作者/单位/邮箱/ORCID)",
|
||||
"why": "全自动模式不臆造真实人物信息。",
|
||||
"how_to_change": "投稿前必须替换,第 20 步会提醒"},
|
||||
]
|
||||
|
||||
for sid, name, _g, _arts, _gate in S:
|
||||
os.makedirs(os.path.join(root, f"{sid}_{name}"), exist_ok=True)
|
||||
for extra in ("refs", "data", "figures", "manuscript", "submission",
|
||||
"journal_papers"):
|
||||
os.makedirs(os.path.join(root, extra), exist_ok=True)
|
||||
|
||||
st = {
|
||||
"schema": SCHEMA, "title": title, "direction": direction,
|
||||
"mode": "autopilot", "created_at": _now(), "updated_at": _now(),
|
||||
"current": "01", "completed": ["00"], "steps": steps,
|
||||
"decisions": decisions, "log": log,
|
||||
"brief": {
|
||||
"type": "research article", "venue": venue, "publisher": pub,
|
||||
"quartile": quart, "oa_note": oa, "length_limit": f"{length} words",
|
||||
"figure_limit": f"{figs} figures", "ref_limit": f"{refs} refs",
|
||||
"style_note": style,
|
||||
"has_experiment": a.has_experiment or "simulation-only",
|
||||
"authors": a.authors or
|
||||
"占位符(待用户补真实作者/单位/邮箱/ORCID)",
|
||||
},
|
||||
}
|
||||
_save(root, st)
|
||||
print(f"[ok] 项目已建立:{root}")
|
||||
print(f"[ok] 自动定下目标刊:{venue}({pub},{quart},{oa})")
|
||||
print(f"[ok] 篇幅 {length} words · {figs} figures · {refs} refs")
|
||||
print(f"[ok] 自动决策 {len(decisions)} 条 → DECISIONS.md")
|
||||
print("\n下一步:python autopilot.py next --dir \"%s\"" % root)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_next(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
sid = st.get("current")
|
||||
if not sid:
|
||||
print("全部步骤已完成。跑 `autopilot.py check` 做终检。")
|
||||
return 0
|
||||
b = st.get("brief") or {}
|
||||
arts = ARTS[sid]
|
||||
print("=" * 66)
|
||||
print(f"工单 · 第 {sid} 步 · {NAME[sid]}({GROUP[sid]})")
|
||||
print("=" * 66)
|
||||
print(f"目标刊:{b.get('venue','')} 类型:{b.get('type','')} "
|
||||
f"篇幅:{b.get('length_limit','')}")
|
||||
print()
|
||||
print("【必须产出】完成前这些文件必须存在且非空:")
|
||||
for rel in arts:
|
||||
p = _path(root, rel)
|
||||
present = (os.path.isdir(p) if rel.endswith("/") else os.path.isfile(p))
|
||||
print(f" - {rel} [{'已存在' if present else '待创建'}]")
|
||||
if not arts:
|
||||
print(" (本步无强制产出)")
|
||||
print()
|
||||
print(f"【通过标准】{GATE[sid]}")
|
||||
print()
|
||||
print("【怎么做】读技能目录下的 references/pipeline_steps.md 里 "
|
||||
f"「{sid} · {NAME[sid]}」那一节,")
|
||||
print(" 按里面的「有技能时」或「裸做」流程执行。")
|
||||
if sid in ("16", "19"):
|
||||
print(" → 另外必须读 references/deai_protocol.md")
|
||||
if sid == "10":
|
||||
print(" → 另外必须读 references/figure_standards.md")
|
||||
if sid == "12":
|
||||
print(" → 另外必须读 references/simulation_vv.md")
|
||||
if sid in ("14", "18", "20", "21"):
|
||||
print(" → 另外必须读 references/submission_and_compliance.md")
|
||||
if sid == "15":
|
||||
print(" → 另外必须读 references/venue_playbooks.md")
|
||||
if sid in ("02", "03", "07", "08", "19", "20"):
|
||||
print(" → 文献相关步骤必须用 scripts/litsearch.py 做真实检索与核验,"
|
||||
"见 references/literature_and_verification.md")
|
||||
if sid in ("10", "12"):
|
||||
print(" → 数据必须真跑出来:scripts/simulate.py check / run / provenance,"
|
||||
"见 references/simulation_and_data.md")
|
||||
print(" 禁止手写 data/ 里的数字;每个数据文件都要有 .prov.json")
|
||||
print()
|
||||
print("【完成后】python autopilot.py done --dir \"%s\"" % root)
|
||||
print(" (缺文件会被拒绝前进;确实做不了就用 skip 并写清原因)")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_done(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
sid = a.step or st.get("current")
|
||||
if sid not in IDS:
|
||||
_die(f"--step 必须是 00..{IDS[-1]} 之一,收到 {sid!r}")
|
||||
need = ARTS[sid] + list(a.extra or [])
|
||||
bad = _check_artifacts(root, need)
|
||||
if bad and not a.force:
|
||||
print(f"[拒绝] 第 {sid} 步声明的产出还没齐:", file=sys.stderr)
|
||||
for x in bad:
|
||||
print(f" - {x}", file=sys.stderr)
|
||||
print("\n先把它们做出来;确实做不了就用:\n"
|
||||
f' python autopilot.py skip --dir "{root}" --step {sid} '
|
||||
f'--reason "<为什么>"', file=sys.stderr)
|
||||
return 1
|
||||
if bad and a.force:
|
||||
print(f"[warn] --force 跳过了产出检查,仍缺:{bad}")
|
||||
|
||||
rec = st.setdefault("steps", {}).setdefault(sid, {})
|
||||
rec["artifacts"] = need
|
||||
rec["gate"] = "通过"
|
||||
rec["gate_note"] = a.note or "自检通过"
|
||||
rec["finished_at"] = _now()
|
||||
if sid not in st["completed"]:
|
||||
st["completed"].append(sid)
|
||||
st["completed"] = sorted(set(st["completed"]), key=IDS.index)
|
||||
i = IDS.index(sid)
|
||||
st["current"] = IDS[i + 1] if i + 1 < len(IDS) else None
|
||||
st["log"].append({"at": _now(), "event": "done", "step": sid,
|
||||
"note": f"{len(need)} 个产出"})
|
||||
_save(root, st)
|
||||
print(f"[ok] 第 {sid} 步完成({len(need)} 个产出已核)")
|
||||
print(f" 进度 {len(st['completed'])}/{len(S)}"
|
||||
+ (f" → 下一步 第 {st['current']} 步 · {NAME[st['current']]}"
|
||||
if st["current"] else " → 全部完成"))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_skip(a) -> int:
|
||||
"""Record a step that could not be completed. Keeps the pipeline moving."""
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
sid = a.step or st.get("current")
|
||||
if sid not in IDS:
|
||||
_die(f"--step 必须是 00..{IDS[-1]} 之一")
|
||||
if not (a.reason or "").strip():
|
||||
_die("--reason 必填。降级必须写清为什么,否则就是掩盖。")
|
||||
rec = st.setdefault("steps", {}).setdefault(sid, {})
|
||||
rec["degraded"] = True
|
||||
rec["degrade_reason"] = a.reason
|
||||
rec["gate"] = "降级"
|
||||
rec["gate_note"] = a.reason
|
||||
if sid not in st["completed"]:
|
||||
st["completed"].append(sid)
|
||||
st["completed"] = sorted(set(st["completed"]), key=IDS.index)
|
||||
i = IDS.index(sid)
|
||||
st["current"] = IDS[i + 1] if i + 1 < len(IDS) else None
|
||||
st.setdefault("degraded", []).append({"step": sid, "reason": a.reason,
|
||||
"at": _now()})
|
||||
st["log"].append({"at": _now(), "event": "skip", "step": sid,
|
||||
"note": a.reason})
|
||||
_save(root, st)
|
||||
print(f"[!] 第 {sid} 步已降级:{a.reason}")
|
||||
print(" ⚠️ 降级项必须在最终交付说明里列出来,不能静默吞掉。")
|
||||
if st["current"]:
|
||||
print(f" → 继续第 {st['current']} 步 · {NAME[st['current']]}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_decide(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
st.setdefault("decisions", []).append({
|
||||
"at": _now(), "step": a.step or st.get("current") or "",
|
||||
"q": a.question, "choice": a.choice, "why": a.why or "",
|
||||
"how_to_change": a.how_to_change or "改 DECISIONS.md 里这一条即可",
|
||||
})
|
||||
st["log"].append({"at": _now(), "event": "decide",
|
||||
"step": a.step or st.get("current") or "",
|
||||
"note": f"{a.question} → {a.choice}"})
|
||||
_save(root, st)
|
||||
print(f"[ok] 已记录决策:{a.question} → {a.choice}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_check(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
print(f"自检 · {st.get('title')}")
|
||||
print()
|
||||
problems = 0
|
||||
for sid, name, _g, arts, _gate in S:
|
||||
rec = (st.get("steps") or {}).get(sid) or {}
|
||||
if sid in st.get("completed", []):
|
||||
if rec.get("degraded"):
|
||||
print(f" [降级] {sid} {name}:{rec.get('degrade_reason','')}")
|
||||
problems += 1
|
||||
continue
|
||||
bad = _check_artifacts(root, arts)
|
||||
if bad:
|
||||
print(f" [缺件] {sid} {name}:{bad}")
|
||||
problems += 1
|
||||
else:
|
||||
print(f" [ok ] {sid} {name}")
|
||||
elif sid == st.get("current"):
|
||||
print(f" [当前] {sid} {name}")
|
||||
print()
|
||||
if problems:
|
||||
print(f"发现 {problems} 处问题。降级项必须在交付说明里列明。")
|
||||
else:
|
||||
print("已完成的步骤产出齐全。")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_status(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
sys.stdout.write(_human(st))
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_utf8()
|
||||
broken = _check_step_table()
|
||||
if broken:
|
||||
print("[致命] 步骤表本身有问题,流水线不能运行:", file=sys.stderr)
|
||||
for b in broken:
|
||||
print(f" - {b}", file=sys.stderr)
|
||||
print("\n这通常意味着 autopilot.py 的步骤表被改坏了。"
|
||||
"先修好再跑,否则进度会卡住或错位。", file=sys.stderr)
|
||||
return 3
|
||||
ap = argparse.ArgumentParser(prog="autopilot",
|
||||
description="全自动论文流水线驱动")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
s = sub.add_parser("start", help="建立项目并自动推断所有参数")
|
||||
s.add_argument("--dir", required=True)
|
||||
s.add_argument("--direction", required=True,
|
||||
help="论文方向/题目——全自动模式下唯一必需的输入")
|
||||
s.add_argument("--title", default="")
|
||||
s.add_argument("--has-experiment", dest="has_experiment", default="")
|
||||
s.add_argument("--authors", default="")
|
||||
s.add_argument("--force", action="store_true")
|
||||
s.set_defaults(func=cmd_start)
|
||||
|
||||
n = sub.add_parser("next", help="打印当前步的工单")
|
||||
n.add_argument("--dir", required=True)
|
||||
n.set_defaults(func=cmd_next)
|
||||
|
||||
d = sub.add_parser("done", help="声明本步完成(会核查产出是否存在)")
|
||||
d.add_argument("--dir", required=True)
|
||||
d.add_argument("--step", default=None)
|
||||
d.add_argument("--extra", nargs="*", default=[])
|
||||
d.add_argument("--note", default="")
|
||||
d.add_argument("--force", action="store_true")
|
||||
d.set_defaults(func=cmd_done)
|
||||
|
||||
k = sub.add_parser("skip", help="降级某步并记录原因(保证流程继续)")
|
||||
k.add_argument("--dir", required=True)
|
||||
k.add_argument("--step", default=None)
|
||||
k.add_argument("--reason", required=True)
|
||||
k.set_defaults(func=cmd_skip)
|
||||
|
||||
de = sub.add_parser("decide", help="记录一条自动决策")
|
||||
de.add_argument("--dir", required=True)
|
||||
de.add_argument("--question", required=True)
|
||||
de.add_argument("--choice", required=True)
|
||||
de.add_argument("--why", default="")
|
||||
de.add_argument("--how-to-change", dest="how_to_change", default="")
|
||||
de.add_argument("--step", default=None)
|
||||
de.set_defaults(func=cmd_decide)
|
||||
|
||||
c = sub.add_parser("check", help="核对已完成步骤的产出是否齐全")
|
||||
c.add_argument("--dir", required=True)
|
||||
c.set_defaults(func=cmd_check)
|
||||
|
||||
st = sub.add_parser("status", help="显示完整进度")
|
||||
st.add_argument("--dir", required=True)
|
||||
st.set_defaults(func=cmd_status)
|
||||
|
||||
a = ap.parse_args()
|
||||
return a.func(a)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,430 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""把分章 md 编译为学位论文格式的 Word 文档(thesis-pipeline)
|
||||
|
||||
排版参数全部来自 thesis.json(字体、字号、行距、页边距、图宽、章节顺序),
|
||||
学校模板到手后改 thesis.json,不要改本脚本。
|
||||
|
||||
md 语法支持:# 标题、正文、- 列表、1. 有序列表、| 表格 |、```代码```、
|
||||
 + 紧随的 **图 x-y 题注**、$行内公式$、$$行间公式 \tag{2-1}$$、(GB/T 7714)[n] 引用。
|
||||
LaTeX 公式由 math2unicode.py 转为 Unicode 文本(python-docx 无法生成 OMML 公式)。
|
||||
|
||||
用法:
|
||||
python build_docx.py --config thesis.json --manuscript manuscript/ --out deliverables/论文.docx
|
||||
python build_docx.py --config thesis.json # 用 thesis.json 里的 manuscript_order
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from docx import Document
|
||||
from docx.enum.table import WD_TABLE_ALIGNMENT
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
|
||||
from docx.oxml import OxmlElement
|
||||
from docx.oxml.ns import qn
|
||||
from docx.shared import Cm, Pt, RGBColor
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from math2unicode import convert_text, WARNINGS # noqa: E402
|
||||
|
||||
BLACK = RGBColor(0, 0, 0)
|
||||
GREY = RGBColor(0x59, 0x59, 0x59)
|
||||
BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
|
||||
TAG_RE = re.compile(r"^(.*?) ((\d+[-.]\d+|[A-Z]?\d+))$")
|
||||
|
||||
|
||||
class Cfg:
|
||||
"""把 thesis.json 读成带默认值的配置对象。"""
|
||||
|
||||
def __init__(self, path: Path | None):
|
||||
d = {}
|
||||
if path and path.exists():
|
||||
d = json.loads(path.read_text(encoding="utf-8"))
|
||||
self.raw = d
|
||||
p = d.get("page", {})
|
||||
self.margin = (p.get("margin_top_cm", 2.54), p.get("margin_bottom_cm", 2.54),
|
||||
p.get("margin_left_cm", 2.8), p.get("margin_right_cm", 2.8))
|
||||
f = d.get("fonts", {})
|
||||
self.f_body = f.get("body_cn", "宋体")
|
||||
self.f_latin = f.get("body_latin", "Times New Roman")
|
||||
self.f_head = f.get("heading_cn", "黑体")
|
||||
self.f_code = f.get("code_latin", "Consolas")
|
||||
s = d.get("sizes", {})
|
||||
self.s_body = s.get("body_pt", 12)
|
||||
self.s_h1 = s.get("h1_pt", 16)
|
||||
self.s_h2 = s.get("h2_pt", 14)
|
||||
self.s_h3 = s.get("h3_pt", 12)
|
||||
self.s_cap = s.get("caption_pt", 10.5)
|
||||
self.s_ref = s.get("ref_pt", 10.5)
|
||||
self.s_math = s.get("formula_pt", 11.5)
|
||||
self.line = d.get("line_spacing_pt", 22)
|
||||
self.indent = d.get("first_line_indent_chars", 2)
|
||||
self.fig_w = d.get("figure_width_cm", 15.2)
|
||||
self.order = d.get("manuscript_order", [])
|
||||
self.title = d.get("title", "论文")
|
||||
self.author = d.get("author", {})
|
||||
|
||||
|
||||
def set_font(run, cn, latin, size, bold=False, color=BLACK):
|
||||
run.font.name = latin
|
||||
run.font.size = Pt(size)
|
||||
run.font.bold = bold
|
||||
run.font.color.rgb = color
|
||||
rPr = run._element.get_or_add_rPr()
|
||||
rFonts = rPr.find(qn("w:rFonts"))
|
||||
if rFonts is None:
|
||||
rFonts = OxmlElement("w:rFonts")
|
||||
rPr.append(rFonts)
|
||||
rFonts.set(qn("w:ascii"), latin)
|
||||
rFonts.set(qn("w:hAnsi"), latin)
|
||||
rFonts.set(qn("w:eastAsia"), cn)
|
||||
return run
|
||||
|
||||
|
||||
def para_fmt(p, cfg: Cfg, indent=0, line=None, before=0, after=0,
|
||||
align=WD_ALIGN_PARAGRAPH.JUSTIFY, keep_next=False):
|
||||
pf = p.paragraph_format
|
||||
pf.line_spacing_rule = WD_LINE_SPACING.EXACTLY
|
||||
pf.line_spacing = Pt(line if line is not None else cfg.line)
|
||||
pf.space_before = Pt(before)
|
||||
pf.space_after = Pt(after)
|
||||
p.alignment = align
|
||||
if indent:
|
||||
pPr = p._element.get_or_add_pPr()
|
||||
ind = pPr.find(qn("w:ind"))
|
||||
if ind is None:
|
||||
ind = OxmlElement("w:ind")
|
||||
pPr.append(ind)
|
||||
ind.set(qn("w:firstLineChars"), str(int(indent * 100)))
|
||||
ind.set(qn("w:firstLine"), str(int(indent * cfg.s_body * 20)))
|
||||
if keep_next:
|
||||
pPr = p._element.get_or_add_pPr()
|
||||
pPr.append(OxmlElement("w:keepNext"))
|
||||
return p
|
||||
|
||||
|
||||
def add_rich(p, text, cfg: Cfg, cn=None, size=None):
|
||||
cn = cn or cfg.f_body
|
||||
size = size or cfg.s_body
|
||||
pos = 0
|
||||
for m in BOLD_RE.finditer(text):
|
||||
if m.start() > pos:
|
||||
set_font(p.add_run(text[pos:m.start()]), cn, cfg.f_latin, size)
|
||||
set_font(p.add_run(m.group(1)), cn, cfg.f_latin, size, bold=True)
|
||||
pos = m.end()
|
||||
if pos < len(text):
|
||||
set_font(p.add_run(text[pos:]), cn, cfg.f_latin, size)
|
||||
if not text:
|
||||
set_font(p.add_run(""), cn, cfg.f_latin, size)
|
||||
return p
|
||||
|
||||
|
||||
def new_doc(cfg: Cfg) -> Document:
|
||||
doc = Document()
|
||||
st = doc.styles["Normal"]
|
||||
st.font.name = cfg.f_latin
|
||||
st.font.size = Pt(cfg.s_body)
|
||||
st.element.rPr.rFonts.set(qn("w:eastAsia"), cfg.f_body)
|
||||
sec = doc.sections[0]
|
||||
sec.page_width, sec.page_height = Cm(21.0), Cm(29.7)
|
||||
t, b, l, r = cfg.margin
|
||||
sec.top_margin, sec.bottom_margin = Cm(t), Cm(b)
|
||||
sec.left_margin, sec.right_margin = Cm(l), Cm(r)
|
||||
# 页脚页码
|
||||
footer = sec.footer
|
||||
fp = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
|
||||
fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
run = fp.add_run()
|
||||
set_font(run, cfg.f_body, cfg.f_latin, 9, color=GREY)
|
||||
fld = OxmlElement("w:fldSimple")
|
||||
fld.set(qn("w:instr"), "PAGE")
|
||||
run._element.addnext(fld)
|
||||
return doc
|
||||
|
||||
|
||||
def add_cover(doc: Document, cfg: Cfg):
|
||||
for _ in range(3):
|
||||
para_fmt(doc.add_paragraph(), cfg, line=20)
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=40, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run(f"{cfg.raw.get('type', '本科')}毕业论文"), cfg.f_head, cfg.f_latin,
|
||||
22, bold=True)
|
||||
for seg in re.split(r"[::]", cfg.title) or [cfg.title]:
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=40, before=24, after=6, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run(seg), cfg.f_head, cfg.f_latin, 18, bold=True)
|
||||
a = cfg.author
|
||||
rows = [("作 者", a.get("name", "〔待填〕")), ("学 号", a.get("sid", "〔待填〕")),
|
||||
("专 业", a.get("major", "〔待填〕")), ("指导教师", a.get("advisor", "〔待填〕")),
|
||||
("学 院", a.get("school", "〔待填〕")), ("完成日期", a.get("date", "〔待填〕"))]
|
||||
tbl = doc.add_table(rows=len(rows), cols=2)
|
||||
tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
for i, (k, v) in enumerate(rows):
|
||||
for j, txt in enumerate((k, v)):
|
||||
cell = tbl.cell(i, j)
|
||||
cell.text = ""
|
||||
pp = cell.paragraphs[0]
|
||||
para_fmt(pp, cfg, line=26,
|
||||
align=WD_ALIGN_PARAGRAPH.RIGHT if j == 0 else WD_ALIGN_PARAGRAPH.LEFT)
|
||||
set_font(pp.add_run(txt), cfg.f_body, cfg.f_latin, cfg.s_body)
|
||||
doc.add_page_break()
|
||||
|
||||
|
||||
def render_table(doc, rows, cfg: Cfg):
|
||||
if not rows:
|
||||
return
|
||||
ncol = max(len(r) for r in rows)
|
||||
tbl = doc.add_table(rows=len(rows), cols=ncol)
|
||||
tbl.style = "Table Grid"
|
||||
tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
for i, row in enumerate(rows):
|
||||
for j in range(ncol):
|
||||
txt = (row[j] if j < len(row) else "").replace("**", "")
|
||||
cell = tbl.cell(i, j)
|
||||
cell.text = ""
|
||||
pp = cell.paragraphs[0]
|
||||
para_fmt(pp, cfg, line=14,
|
||||
align=WD_ALIGN_PARAGRAPH.CENTER if (i == 0 or j == 0)
|
||||
else WD_ALIGN_PARAGRAPH.LEFT)
|
||||
set_font(pp.add_run(txt), cfg.f_body, cfg.f_latin, 9, bold=(i == 0))
|
||||
para_fmt(doc.add_paragraph(), cfg, line=6)
|
||||
|
||||
|
||||
def render_code(doc, lines, cfg: Cfg):
|
||||
for ln in lines:
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=12, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.6)
|
||||
set_font(p.add_run(ln if ln else " "), cfg.f_body, cfg.f_code, 9,
|
||||
color=RGBColor(0x1F, 0x3A, 0x5F))
|
||||
para_fmt(doc.add_paragraph(), cfg, line=6)
|
||||
|
||||
|
||||
def render_image(doc, path: Path, caption: str, cfg: Cfg):
|
||||
if not path.exists():
|
||||
print(f" !! 图片缺失,跳过:{path}")
|
||||
return
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=14, before=6, after=2, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
p.add_run().add_picture(str(path), width=Cm(cfg.fig_w))
|
||||
if caption:
|
||||
cp = doc.add_paragraph()
|
||||
para_fmt(cp, cfg, line=16, after=10, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(cp.add_run(caption), cfg.f_body, cfg.f_latin, cfg.s_cap)
|
||||
|
||||
|
||||
def render_formula(doc, line: str, cfg: Cfg):
|
||||
"""行间公式:公式居中,编号右对齐(右制表位略小于版心宽度,否则会换行)。"""
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=20, before=6, after=6, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
m = TAG_RE.match(line.strip())
|
||||
body, tag = (m.group(1).strip(), m.group(2)) if m else (line.strip(), "")
|
||||
text_w = 21.0 - cfg.margin[2] - cfg.margin[3]
|
||||
pPr = p._element.get_or_add_pPr()
|
||||
tabs = OxmlElement("w:tabs")
|
||||
tab = OxmlElement("w:tab")
|
||||
tab.set(qn("w:val"), "right")
|
||||
tab.set(qn("w:pos"), str(int((text_w - 1.0) * 567)))
|
||||
tabs.append(tab)
|
||||
pPr.append(tabs)
|
||||
p.paragraph_format.left_indent = Cm(2.4)
|
||||
set_font(p.add_run(body), cfg.f_body, cfg.f_latin, cfg.s_math)
|
||||
if tag:
|
||||
set_font(p.add_run(f"\t({tag})"), cfg.f_body, cfg.f_latin, cfg.s_math - 0.5)
|
||||
|
||||
|
||||
def render_md(doc, text: str, cfg: Cfg, base: Path):
|
||||
lines = text.split("\n")
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
ln = lines[i]
|
||||
s = ln.strip()
|
||||
|
||||
if s.startswith("```"):
|
||||
i += 1
|
||||
buf = []
|
||||
while i < len(lines) and not lines[i].strip().startswith("```"):
|
||||
buf.append(lines[i])
|
||||
i += 1
|
||||
i += 1
|
||||
render_code(doc, buf, cfg)
|
||||
continue
|
||||
|
||||
if s.startswith("|") and i + 1 < len(lines) and \
|
||||
re.match(r"^\|[\s:\-\|]+\|$", lines[i + 1].strip()):
|
||||
rows = []
|
||||
while i < len(lines) and lines[i].strip().startswith("|"):
|
||||
cells = [c.strip() for c in lines[i].strip().strip("|").split("|")]
|
||||
if not re.match(r"^[\s:\-]+$", "".join(cells)):
|
||||
rows.append(cells)
|
||||
i += 1
|
||||
render_table(doc, rows, cfg)
|
||||
continue
|
||||
|
||||
m = re.match(r"^!\[(.*?)\]\((.*?)\)$", s)
|
||||
if m:
|
||||
render_image(doc, (base / m.group(2)).resolve(), m.group(1), cfg)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if s in ("---", "***", "___"):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=8, after=4)
|
||||
pPr = p._element.get_or_add_pPr()
|
||||
pbdr = OxmlElement("w:pBdr")
|
||||
bottom = OxmlElement("w:bottom")
|
||||
bottom.set(qn("w:val"), "single")
|
||||
bottom.set(qn("w:sz"), "6")
|
||||
bottom.set(qn("w:color"), "AAAAAA")
|
||||
pbdr.append(bottom)
|
||||
pPr.append(pbdr)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
m = re.match(r"^(#{2,4})\s+(.*)$", s)
|
||||
if m:
|
||||
level = len(m.group(1)) - 1
|
||||
txt = m.group(2).replace("**", "")
|
||||
p = doc.add_paragraph()
|
||||
if level == 1:
|
||||
para_fmt(p, cfg, line=30, before=16, after=10,
|
||||
align=WD_ALIGN_PARAGRAPH.CENTER, keep_next=True)
|
||||
set_font(p.add_run(txt), cfg.f_head, cfg.f_latin, cfg.s_h1, bold=True)
|
||||
elif level == 2:
|
||||
para_fmt(p, cfg, line=26, before=12, after=6,
|
||||
align=WD_ALIGN_PARAGRAPH.LEFT, keep_next=True)
|
||||
set_font(p.add_run(txt), cfg.f_head, cfg.f_latin, cfg.s_h2, bold=True)
|
||||
else:
|
||||
para_fmt(p, cfg, line=24, before=8, after=4,
|
||||
align=WD_ALIGN_PARAGRAPH.LEFT, keep_next=True)
|
||||
set_font(p.add_run(txt), cfg.f_head, cfg.f_latin, cfg.s_h3, bold=True)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if not s:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 图题/表题
|
||||
if re.match(r"^\*\*(图|表)\s", s) and s.endswith("**"):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=16, before=2, after=8, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run(s.strip("*")), cfg.f_body, cfg.f_latin, cfg.s_cap)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 行间公式(转换后形如 "E/Eₛ = C₁ ρ̄ⁿ (2-2)")
|
||||
if re.search(r"([\dA-Z]+[-.]\d+)$", s) and " " in s and \
|
||||
not s.startswith(("**", "|", "[")):
|
||||
render_formula(doc, s, cfg)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if s.startswith(">"):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=20, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.8)
|
||||
add_rich(p, s.lstrip("> ").strip(), cfg, size=cfg.s_cap)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
m = re.match(r"^(\d+)\.\s+(.*)$", s)
|
||||
if m:
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=cfg.line, after=2, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.75)
|
||||
add_rich(p, f"{m.group(1)}. {m.group(2)}", cfg)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if re.match(r"^[-*]\s+", s):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=cfg.line, after=2, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.75)
|
||||
add_rich(p, "· " + re.sub(r"^[-*]\s+", "", s), cfg)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 参考文献条目(悬挂缩进)
|
||||
if re.match(r"^\[\d+\]", s) or re.match(r"^E\d+\.", s):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, line=16, after=2, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.95)
|
||||
p.paragraph_format.first_line_indent = Cm(-0.95)
|
||||
add_rich(p, s, cfg, size=cfg.s_ref)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, cfg, indent=cfg.indent, line=cfg.line, after=2)
|
||||
add_rich(p, s, cfg)
|
||||
i += 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="编译 md 为学位论文格式 Word")
|
||||
ap.add_argument("--config", default="thesis.json", help="排版配置")
|
||||
ap.add_argument("--manuscript", default="manuscript", help="分章 md 目录")
|
||||
ap.add_argument("--out", default="", help="输出 docx 路径")
|
||||
args = ap.parse_args()
|
||||
|
||||
cfg_path = Path(args.config)
|
||||
cfg = Cfg(cfg_path)
|
||||
man = Path(args.manuscript)
|
||||
if not man.is_dir():
|
||||
print(f"找不到目录 {man}")
|
||||
return 1
|
||||
|
||||
order = cfg.order or [p.name for p in sorted(man.glob("*.md"))]
|
||||
parts, missing = [], []
|
||||
for name in order:
|
||||
p = man / name
|
||||
if p.exists():
|
||||
parts.append(p.read_text(encoding="utf-8").strip())
|
||||
else:
|
||||
missing.append(name)
|
||||
if missing:
|
||||
print(f"!! thesis.json 的 manuscript_order 里这些文件不存在:{missing}")
|
||||
if not parts:
|
||||
print("没有可编译的 md 文件")
|
||||
return 1
|
||||
full = "\n\n".join(parts)
|
||||
|
||||
# 公式转换(保护代码块)
|
||||
segs = re.split(r"(```.*?```)", full, flags=re.S)
|
||||
full = "".join(seg if seg.startswith("```") else convert_text(seg) for seg in segs)
|
||||
|
||||
doc = new_doc(cfg)
|
||||
add_cover(doc, cfg)
|
||||
render_md(doc, full, cfg, man)
|
||||
|
||||
out = Path(args.out) if args.out else Path("deliverables") / f"{cfg.title[:20] or '论文'}.docx"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
doc.save(str(out))
|
||||
|
||||
cjk = len(re.findall(r"[\u4e00-\u9fff]", full))
|
||||
print(f"已生成 Word:{out}")
|
||||
print(f" 文件大小:{out.stat().st_size / 1024:.0f} KB | 全文中文字符:{cjk}")
|
||||
if WARNINGS:
|
||||
print(f" !! 未转换的 LaTeX 命令:{sorted(set(WARNINGS))}")
|
||||
else:
|
||||
print(" 公式转换:无残留 LaTeX 命令")
|
||||
if "$" in full:
|
||||
print(f" !! 仍有 {full.count('$')} 个 $ 未转换")
|
||||
print(f" 下一步:python scripts/docx_to_pdf.py \"{out}\"")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""生成 GB/T 7714—2015 参考文献表(thesis-pipeline)
|
||||
|
||||
以「正文首次引用顺序」为权威编号:扫描 manuscript/ 下所有 md,按引用号 [n] 首次
|
||||
出现的位置排序,把 refs.csv 里的条目排成顺序编码制列表。
|
||||
未被正文引用的条目自动移入"延伸阅读",不占编号。
|
||||
|
||||
`refs.csv` 的列名支持中英文别名(作者/author、标题/title 等),因此不必严格照抄模板。
|
||||
|
||||
用法:
|
||||
python build_refs.py --csv refs.csv --manuscript manuscript/ --out 05_稿件/参考文献.md
|
||||
python build_refs.py ... --check # 只做一致性检查,不写文件
|
||||
|
||||
退出码:0 正常;1 有阻塞问题(如引用号找不到对应条目)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
CITE = re.compile(r"\[(\d+(?:\s*[,,\-–]\s*\d+)*)\]")
|
||||
|
||||
# 列名别名(统一转小写后匹配)
|
||||
ALIAS = {
|
||||
"id": ["id", "编号", "key"],
|
||||
"authors": ["作者", "authors", "author", "作者列表"],
|
||||
"year": ["年份", "year", "年"],
|
||||
"title": ["标题", "title", "题名", "题目"],
|
||||
"journal": ["期刊", "journal", "来源", "出版物", "会议", "container"],
|
||||
"volume": ["卷", "volume", "vol", "卷号"],
|
||||
"issue": ["期", "issue", "number", "no"],
|
||||
"pages": ["页", "pages", "page", "页码"],
|
||||
"doi": ["doi", "DOI"],
|
||||
"type": ["类型", "type", "文献类型"],
|
||||
"note": ["备注", "note", "notes", "说明"],
|
||||
}
|
||||
|
||||
|
||||
def pick_col(fieldnames: list[str], key: str) -> str | None:
|
||||
low = {f.lower().strip(): f for f in fieldnames}
|
||||
for cand in ALIAS[key]:
|
||||
if cand.lower() in low:
|
||||
return low[cand.lower()]
|
||||
return None
|
||||
|
||||
|
||||
def load_refs(path: Path) -> list[dict]:
|
||||
with open(path, encoding="utf-8-sig", newline="") as f:
|
||||
rd = csv.DictReader(f)
|
||||
cols = {k: pick_col(rd.fieldnames or [], k) for k in ALIAS}
|
||||
rows = []
|
||||
for i, r in enumerate(rd, 1):
|
||||
def g(key):
|
||||
c = cols.get(key)
|
||||
return (r.get(c) or "").strip() if c else ""
|
||||
rows.append({
|
||||
"id": g("id") or f"R{i:03d}",
|
||||
"authors": g("authors"), "year": g("year"), "title": g("title"),
|
||||
"journal": g("journal"), "volume": g("volume"), "issue": g("issue"),
|
||||
"pages": g("pages"), "doi": g("doi"),
|
||||
"type": (g("type") or "journal").lower(),
|
||||
"note": g("note"),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def split_authors(raw: str) -> list[str]:
|
||||
if not raw:
|
||||
return []
|
||||
parts = re.split(r"[;;]", raw) if re.search(r"[;;]", raw) else re.split(r",", raw)
|
||||
return [p.strip() for p in parts if p.strip()]
|
||||
|
||||
|
||||
def fmt_authors(raw: str) -> str:
|
||||
names = split_authors(raw)
|
||||
if not names:
|
||||
return "佚名"
|
||||
if len(names) > 3:
|
||||
return ", ".join(names[:3]) + ", 等"
|
||||
return ", ".join(names)
|
||||
|
||||
|
||||
TYPE_TAG = {"journal": "J", "conference": "C", "book": "M", "thesis": "D",
|
||||
"standard": "S", "report": "R", "patent": "P", "web": "EB/OL"}
|
||||
|
||||
|
||||
def fmt_entry(r: dict, num: int) -> str:
|
||||
tag = TYPE_TAG.get(r["type"], "J")
|
||||
authors = fmt_authors(r["authors"])
|
||||
title = r["title"].rstrip(".")
|
||||
year = r["year"] or "s.a."
|
||||
doi = r["doi"]
|
||||
body = f"[{num}] {authors}. {title}[{tag}]."
|
||||
if r["type"] == "standard":
|
||||
return body + (f" {year}." if year != "s.a." else "")
|
||||
if r["type"] in ("book", "thesis"):
|
||||
return body + f" {year}."
|
||||
src = r["journal"]
|
||||
tail = f"{src}, {year}" if src else year
|
||||
if r["volume"]:
|
||||
tail += f", {r['volume']}"
|
||||
if r["issue"]:
|
||||
tail += f"({r['issue']})"
|
||||
if r["pages"]:
|
||||
tail += f": {r['pages']}"
|
||||
out = f"[{num}] {authors}. {title}[{tag}]. {tail}."
|
||||
if doi and doi.lower() not in ("nan", "none", "无doi", ""):
|
||||
out += f" DOI: {doi}."
|
||||
if r["note"]:
|
||||
out += f" ({r['note']})" if "核实" in r["note"] else ""
|
||||
return out
|
||||
|
||||
|
||||
def used_numbers(manuscript: Path) -> tuple[list[int], dict[int, int]]:
|
||||
"""返回(首现顺序的编号列表, {编号: 首次位置})。"""
|
||||
text = "\n\n".join(p.read_text(encoding="utf-8") for p in sorted(manuscript.glob("*.md")))
|
||||
first: dict[int, int] = {}
|
||||
for m in CITE.finditer(text):
|
||||
for part in re.split(r"[,,]", m.group(1)):
|
||||
part = part.strip()
|
||||
mm = re.match(r"^(\d+)\s*[-–]\s*(\d+)$", part)
|
||||
nums = (range(int(mm.group(1)), int(mm.group(2)) + 1) if mm
|
||||
else ([int(part)] if part.isdigit() else []))
|
||||
for n in nums:
|
||||
if n >= 1 and n not in first:
|
||||
first[n] = m.start()
|
||||
order = sorted(first, key=lambda n: first[n])
|
||||
return order, first
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="生成 GB/T 7714 参考文献表")
|
||||
ap.add_argument("--csv", required=True, help="参考文献总表 refs.csv")
|
||||
ap.add_argument("--manuscript", required=True, help="分章 md 目录")
|
||||
ap.add_argument("--out", default="", help="输出 md 路径")
|
||||
ap.add_argument("--check", action="store_true", help="只检查,不写文件")
|
||||
args = ap.parse_args()
|
||||
|
||||
csv_path = Path(args.csv)
|
||||
man = Path(args.manuscript)
|
||||
if not csv_path.exists():
|
||||
print(f"找不到 {csv_path}")
|
||||
return 1
|
||||
if not man.is_dir():
|
||||
print(f"找不到目录 {man}")
|
||||
return 1
|
||||
|
||||
refs = load_refs(csv_path)
|
||||
by_id = {r["id"]: r for r in refs}
|
||||
order, first = used_numbers(man)
|
||||
max_ref = max(int(re.sub(r"\D", "", r["id"]) or 0) for r in refs) if refs else 0
|
||||
|
||||
print(f"refs.csv 条目 {len(refs)} | 正文引用号 {len(order)} 个 | 最大编号 {max(order) if order else 0}")
|
||||
|
||||
# 正文编号 -> 条目:按 id 里的数字对齐(R001/L001/T001 等)
|
||||
def entry_for(n: int) -> dict | None:
|
||||
for r in refs:
|
||||
digits = re.sub(r"\D", "", r["id"])
|
||||
if digits.isdigit() and int(digits) == n:
|
||||
return r
|
||||
return None
|
||||
|
||||
missing = [n for n in order if entry_for(n) is None]
|
||||
if missing:
|
||||
print(f"\n!! 以下引用号在 refs.csv 中找不到对应条目:{missing}")
|
||||
print(" 请检查 refs.csv 的 id 是否与正文编号一致(如 L001..Ln 对应 [1]..[n])。")
|
||||
|
||||
used_ids = {entry_for(n)["id"] for n in order if entry_for(n)}
|
||||
unused = [r for r in refs if r["id"] not in used_ids]
|
||||
|
||||
lines = ["## 参考文献", "",
|
||||
f"(按 GB/T 7714—2015 顺序编码制编排,正文引用 {len(order)} 条;"
|
||||
f"延伸阅读 {len(unused)} 条)", ""]
|
||||
for n in order:
|
||||
r = entry_for(n)
|
||||
if r:
|
||||
lines.append(fmt_entry(r, n))
|
||||
if unused:
|
||||
lines += ["", f"### 延伸阅读(正文未直接引用,共 {len(unused)} 条)", ""]
|
||||
for i, r in enumerate(unused, 1):
|
||||
lines.append(fmt_entry(r, i).replace(f"[{i}]", f"E{i}", 1))
|
||||
lines += ["", "> 本表由 thesis-pipeline 的 build_refs.py 生成;编号由正文引用顺序决定,"
|
||||
"请勿手工改动编号。核验引用请跑 check_refs.py。", ""]
|
||||
|
||||
if args.check:
|
||||
print("检查模式:未写文件。")
|
||||
return 0 if not missing else 1
|
||||
|
||||
out = Path(args.out) if args.out else Path("参考文献.md")
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text("\n".join(lines), encoding="utf-8")
|
||||
print(f"已生成 {out}")
|
||||
print(f" 正文引用 {len(order)} 条 + 延伸阅读 {len(unused)} 条")
|
||||
print(" 下一步:python scripts/check_refs.py --manuscript <manuscript> --refs "
|
||||
f"{out}")
|
||||
return 0 if not missing else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env python3
|
||||
"""探测本机环境:装了哪些工具、哪些技能,以及没有时该走哪条裸做路径。
|
||||
|
||||
python check_env.py # 人可读报告
|
||||
python check_env.py --json env.json # 机器可读
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
TOOLS = {
|
||||
"python": ("Python 解释器", True),
|
||||
"pandoc": ("Markdown → DOCX/LaTeX", False),
|
||||
"git": ("版本管理", False),
|
||||
"node": ("Node.js 运行时", False),
|
||||
"npx": ("Node 包运行器", False),
|
||||
"yt-dlp": ("视频下载(video-reader 用)", False),
|
||||
"ffmpeg": ("音视频处理(抽帧/转写用)", False),
|
||||
"latexmk": ("LaTeX 编译", False),
|
||||
"pdflatex": ("LaTeX 编译", False),
|
||||
"tectonic": ("LaTeX 编译", False),
|
||||
"libreoffice": ("Office 转换", False),
|
||||
"soffice": ("Office 转换", False),
|
||||
}
|
||||
|
||||
PY_LIBS = [
|
||||
("numpy", "数值计算"),
|
||||
("scipy", "科学计算"),
|
||||
("matplotlib", "绘图"),
|
||||
("pandas", "表格与数据"),
|
||||
("docx", "DOCX 生成(python-docx)"),
|
||||
("reportlab", "PDF 生成"),
|
||||
("openpyxl", "Excel 读写"),
|
||||
("PIL", "图像处理(Pillow)"),
|
||||
("cv2", "视频抽帧(OpenCV)"),
|
||||
("fitz", "PDF 解析(PyMuPDF)"),
|
||||
("requests", "HTTP 请求"),
|
||||
("whisper", "语音转写(openai-whisper)"),
|
||||
("faster_whisper", "语音转写(faster-whisper)"),
|
||||
]
|
||||
|
||||
SKILL_ROOTS = {
|
||||
"dsh": "~/.dsh/skills",
|
||||
"codex": "~/.codex/skills",
|
||||
"claude": "~/.claude/skills",
|
||||
"cursor": "~/.cursor/skills",
|
||||
"windsurf": "~/.windsurf/skills",
|
||||
"gemini": "~/.gemini/skills",
|
||||
"project(./skills)": "./skills",
|
||||
"project(./.agent/skills)": "./.agent/skills",
|
||||
"project(./.claude/skills)": "./.claude/skills",
|
||||
}
|
||||
|
||||
|
||||
def _stdout_utf8() -> None:
|
||||
for s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
s.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def scan_skills() -> dict[str, list[str]]:
|
||||
found: dict[str, list[str]] = {}
|
||||
for label, raw in SKILL_ROOTS.items():
|
||||
root = os.path.abspath(os.path.expanduser(raw))
|
||||
if not os.path.isdir(root):
|
||||
continue
|
||||
names = sorted(
|
||||
d for d in os.listdir(root)
|
||||
if os.path.isfile(os.path.join(root, d, "SKILL.md"))
|
||||
)
|
||||
if names:
|
||||
found[label] = names
|
||||
return found
|
||||
|
||||
|
||||
def probe() -> dict:
|
||||
tools = {}
|
||||
for name, (desc, required) in TOOLS.items():
|
||||
p = shutil.which(name)
|
||||
tools[name] = {"path": p or "", "desc": desc, "required": required,
|
||||
"ok": bool(p)}
|
||||
libs = {}
|
||||
for mod, desc in PY_LIBS:
|
||||
try:
|
||||
__import__(mod)
|
||||
libs[mod] = {"desc": desc, "ok": True}
|
||||
except Exception:
|
||||
libs[mod] = {"desc": desc, "ok": False}
|
||||
return {
|
||||
"python_version": sys.version.split()[0],
|
||||
"executable": sys.executable,
|
||||
"platform": sys.platform,
|
||||
"tools": tools,
|
||||
"python_libs": libs,
|
||||
"skills": {k: len(v) for k, v in scan_skills().items()},
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_stdout_utf8()
|
||||
ap = argparse.ArgumentParser(prog="check_env")
|
||||
ap.add_argument("--json", dest="json_out", default="")
|
||||
a = ap.parse_args()
|
||||
env = probe()
|
||||
|
||||
print(f"Python {env['python_version']} ({env['executable']})")
|
||||
print(f"平台 {env['platform']}\n")
|
||||
|
||||
print("外部工具")
|
||||
for name, info in env["tools"].items():
|
||||
mark = "OK " if info["ok"] else ("缺失 * " if info["required"] else "缺失 ")
|
||||
where = info["path"] or f"({info['desc']})"
|
||||
print(f" {mark} {name:14s} {where}")
|
||||
|
||||
print("\nPython 库")
|
||||
for mod, info in env["python_libs"].items():
|
||||
print(f" {'OK ' if info['ok'] else '缺失 '} {mod:16s} {info['desc']}")
|
||||
|
||||
print("\n技能目录")
|
||||
if env["skills"]:
|
||||
for label, n in env["skills"].items():
|
||||
print(f" {label:26s} {n} 个技能")
|
||||
else:
|
||||
print(" 未发现任何 SKILL.md 目录 —— 走「裸做」路径也能跑完整条流水线")
|
||||
|
||||
miss_req = [n for n, i in env["tools"].items() if i["required"] and not i["ok"]]
|
||||
print("\n结论")
|
||||
if miss_req:
|
||||
print(f" [!] 必需工具缺失:{', '.join(miss_req)}")
|
||||
else:
|
||||
print(" [ok] 必需工具齐全")
|
||||
|
||||
hard = [m for m, i in env["python_libs"].items() if not i["ok"]]
|
||||
if hard:
|
||||
print(f" [i] 缺少的库(按需装):{', '.join(hard)}")
|
||||
print(" [i] 没有 pandoc/LaTeX 时:DOCX 用 python-docx 直接生成,"
|
||||
"PDF 用 reportlab 或浏览器打印,不影响交付")
|
||||
|
||||
if a.json_out:
|
||||
with io.open(a.json_out, "w", encoding="utf-8") as fh:
|
||||
json.dump(env, fh, ensure_ascii=False, indent=1)
|
||||
print(f"\n[ok] JSON:{a.json_out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,260 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""引用一致性校验(thesis-pipeline)
|
||||
|
||||
校验四件事:
|
||||
1. 悬空引用——正文引了 [n],但参考文献表没有第 n 条;
|
||||
2. 孤立条目——文献表有第 n 条,但正文从未引用(顺序编码制下属规范问题);
|
||||
3. **引用内容匹配**——正文里"[n]"前面提到的作者姓氏,是否与文献表第 n 条的
|
||||
作者一致。这一项专治"多次重编号后引用号错位指向错误文献",
|
||||
纸质校对几乎查不出来;
|
||||
4. 引用号出现顺序是否大体随正文推进(顺序编码制的惯例)。
|
||||
|
||||
用法:
|
||||
python check_refs.py --manuscript <manuscript/> --refs <参考文献.md>
|
||||
python check_refs.py --manuscript manuscript/ --refs 05_稿件/参考文献.md --json out.json
|
||||
|
||||
退出码:0 = 全部通过;1 = 有 FAIL 级问题。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 引用号:支持 [3]、[3,6]、[3-5]、[3,6]
|
||||
CITE = re.compile(r"\[(\d+(?:\s*[,,\-–]\s*\d+)*)\]")
|
||||
# 文献条目:[12] 作者. 题名...
|
||||
REF_LINE = re.compile(r"^\[(\d+)\]\s*(.*)$")
|
||||
|
||||
# 拉丁人名(后随 "等" / "et al." 时最可靠)
|
||||
NAME_LATIN = re.compile(
|
||||
r"([A-Z][A-Za-z'’\-]{1,}(?:\s+(?:van|von|de|der|di|del)\b)?)"
|
||||
r"\s*(?:等|et\s+al\.?)"
|
||||
)
|
||||
# 中文人名:2-4 个汉字 + 「等」
|
||||
NAME_CN = re.compile(r"([\u4e00-\u9fff]{2,4})\s*等")
|
||||
|
||||
# 中文姓氏首字表(用于判定前面确实是个人名,显著降低误判)
|
||||
CN_SURNAME = set("赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜"
|
||||
"戚谢邹喻柏水窦章云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐"
|
||||
"费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康伍余元卜顾孟平黄"
|
||||
"和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计伏成戴谈宋茅庞熊纪舒屈项祝董梁"
|
||||
"杜阮蓝闵席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡凌霍"
|
||||
"虞万支柯昝管卢莫房裘缪干解应宗丁宣邓郁单杭洪包诸左石崔吉龚程邢滑"
|
||||
"裴陆荣翁荀羊惠甄曲封芮羿储靳汲邴糜松井段富巫乌焦巴弓牧隗山谷车侯"
|
||||
"宓蓬全郗班仰秋仲伊宫宁仇栾暴甘钭历戎祖武符刘景詹束龙叶幸司韶郜黎"
|
||||
"蓟薄印宿白怀蒲邰从鄂索咸籍赖卓蔺屠蒙池乔阴胥能苍双闻莘党翟谭贡劳"
|
||||
"逄姬申扶堵冉宰郦雍卻璩桑桂濮牛寿通边扈燕冀郏浦尚农温别庄晏柴瞿阎"
|
||||
"充慕连茹习宦艾鱼容向古易慎戈廖庾终暨居衡步都耿满弘匡国文寇广禄阙"
|
||||
"东欧殳沃利蔚越夔隆师巩厍聂晁勾敖融冷訾辛阚那简饶空曾毋沙乜养鞠须"
|
||||
"丰巢关蒯相查后荆红游竺权逯盖益桓公")
|
||||
|
||||
# 中文里高频出现在句尾、容易被误当作人名的词(简称/名词结尾)
|
||||
CN_STOPWORDS = {
|
||||
"影响", "研究", "分析", "方法", "性能", "结果", "结论", "文献", "标准", "模型",
|
||||
"结构", "材料", "工艺", "参数", "数据", "系统", "设计", "实验", "仿真", "数值",
|
||||
"问题", "特征", "规律", "机理", "行为", "作用", "意义", "价值", "关系", "变化",
|
||||
"讨论", "证明", "表明", "指出", "报道", "提出", "建立", "完成", "实现", "开展",
|
||||
"测试", "测量", "表征", "评价", "优化", "验证", "对比", "比较", "综述", "进展",
|
||||
"非常规", "双重", "相关", "典型", "常见", "重要", "主要", "关键", "基础", "理论",
|
||||
}
|
||||
|
||||
|
||||
def expand(token: str) -> list[int]:
|
||||
"""展开 [3,6] / [3-5] 为编号列表,保持出现顺序。"""
|
||||
out: list[int] = []
|
||||
for part in re.split(r"[,,]", token):
|
||||
part = part.strip()
|
||||
m = re.match(r"^(\d+)\s*[-–]\s*(\d+)$", part)
|
||||
if m:
|
||||
a, b = int(m.group(1)), int(m.group(2))
|
||||
out.extend(range(a, b + 1) if a <= b else range(a, b - 1, -1))
|
||||
elif part.isdigit():
|
||||
v = int(part)
|
||||
if v >= 1: # [0] 是代码里的下标(如 polyfit(...)[0]),不是引用
|
||||
out.append(v)
|
||||
return out
|
||||
|
||||
|
||||
def parse_refs(path: Path) -> dict[int, dict]:
|
||||
"""解析参考文献表,返回 {编号: {raw, authors}}。"""
|
||||
refs: dict[int, dict] = {}
|
||||
if not path.exists():
|
||||
return refs
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
m = REF_LINE.match(line.strip())
|
||||
if not m:
|
||||
continue
|
||||
num = int(m.group(1))
|
||||
body = m.group(2)
|
||||
# 作者在第一个 "." 之前(GB/T 7714 体例)
|
||||
authors_blob = body.split(".", 1)[0]
|
||||
names: list[str] = []
|
||||
for chunk in re.split(r"[,,;;]", authors_blob):
|
||||
chunk = chunk.strip()
|
||||
if not chunk:
|
||||
continue
|
||||
# 拉丁:"Gonabadi H." -> Gonabadi ; 中文:"张(Zhang)等" -> 张
|
||||
latin = re.match(r"^([A-Z][A-Za-z'’\-]+)", chunk)
|
||||
cn = re.match(r"^([\u4e00-\u9fff]{2,4})", chunk)
|
||||
if latin:
|
||||
names.append(latin.group(1))
|
||||
elif cn:
|
||||
names.append(cn.group(1))
|
||||
refs[num] = {"raw": body, "authors": names}
|
||||
return refs
|
||||
|
||||
|
||||
def read_manuscript(dirpath: Path) -> str:
|
||||
files = sorted(dirpath.glob("*.md"))
|
||||
return "\n\n".join(p.read_text(encoding="utf-8") for p in files)
|
||||
|
||||
|
||||
def extract_surname_before(text: str, pos: int) -> str:
|
||||
"""取引用号之前、同一句内**最靠近**引用号的人名。
|
||||
|
||||
实际行文形如「Dziewit 等则同时研究了……的影响[5]」,人名与引用号之间隔着
|
||||
若干字,因此不能要求名字紧贴引用号。做法:截出同句片段,用 finditer 找出
|
||||
全部「人名+等」,取位置最靠后的一个。
|
||||
|
||||
宁可漏检也不误报——误报会让这一校验失去可信度。
|
||||
"""
|
||||
left = text[max(0, pos - 90):pos]
|
||||
for sep in ("。", ";", ";", "!", "?", "\n"):
|
||||
i = left.rfind(sep)
|
||||
if i >= 0:
|
||||
left = left[i + 1:]
|
||||
|
||||
best_pos, best_name = -1, ""
|
||||
for m in NAME_LATIN.finditer(left):
|
||||
if m.start() >= best_pos:
|
||||
best_pos, best_name = m.start(), m.group(1)
|
||||
for m in NAME_CN.finditer(left):
|
||||
if m.start() < best_pos:
|
||||
continue
|
||||
name = m.group(1)
|
||||
if name in CN_STOPWORDS or name[0] not in CN_SURNAME:
|
||||
continue
|
||||
best_pos, best_name = m.start(), name
|
||||
return best_name
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="引用一致性校验")
|
||||
ap.add_argument("--manuscript", required=True, help="分章 md 所在目录")
|
||||
ap.add_argument("--refs", required=True, help="参考文献表 md 文件")
|
||||
ap.add_argument("--json", default="", help="可选:输出 JSON 报告")
|
||||
ap.add_argument("--max-report", type=int, default=12, help="每类问题最多列出几条")
|
||||
args = ap.parse_args()
|
||||
|
||||
man_dir = Path(args.manuscript)
|
||||
refs_path = Path(args.refs)
|
||||
text = read_manuscript(man_dir)
|
||||
refs = parse_refs(refs_path)
|
||||
|
||||
used: list[int] = []
|
||||
for m in CITE.finditer(text):
|
||||
used.extend(expand(m.group(1)))
|
||||
used_set = set(used)
|
||||
defined = set(refs)
|
||||
|
||||
dangling = sorted(used_set - defined)
|
||||
orphan = sorted(i for i in defined - used_set if defined and i <= max(defined))
|
||||
|
||||
# ---- 引用内容匹配 ----
|
||||
misaligned: list[dict] = []
|
||||
checked = 0
|
||||
for m in CITE.finditer(text):
|
||||
nums = expand(m.group(1))
|
||||
if len(nums) != 1:
|
||||
continue # 多号引用(如 [3,6])前的名字可能只对应其中一个,跳过
|
||||
n = nums[0]
|
||||
if n not in refs:
|
||||
continue
|
||||
surname = extract_surname_before(text, m.start())
|
||||
if not surname:
|
||||
continue
|
||||
checked += 1
|
||||
authors = refs[n]["authors"]
|
||||
if not authors:
|
||||
continue
|
||||
# 中文姓氏取首字比对;拉丁取完整姓氏(允许前缀匹配,兼容缩写)
|
||||
if re.fullmatch(r"[\u4e00-\u9fff]{2,4}", surname):
|
||||
hit = any(a.startswith(surname[0]) for a in authors)
|
||||
else:
|
||||
hit = any(a.lower() == surname.lower() or
|
||||
a.lower().startswith(surname.lower()[:4]) for a in authors)
|
||||
if not hit:
|
||||
misaligned.append({"ref": n, "surname_in_text": surname,
|
||||
"authors_in_ref": authors,
|
||||
"context": text[max(0, m.start() - 120):m.end()].replace("\n", " ")})
|
||||
|
||||
# ---- 引用顺序 ----
|
||||
first_pos: dict[int, int] = {}
|
||||
for m in CITE.finditer(text):
|
||||
for n in expand(m.group(1)):
|
||||
first_pos.setdefault(n, m.start())
|
||||
seq = [n for n, _ in sorted(first_pos.items(), key=lambda kv: kv[1])]
|
||||
inversions = sum(1 for i in range(len(seq) - 1) if seq[i + 1] < seq[i])
|
||||
|
||||
# ---- 输出 ----
|
||||
print("=" * 70)
|
||||
print("引用一致性校验")
|
||||
print("=" * 70)
|
||||
print(f"正文引用号 {len(used_set)} 个 | 文献表 {len(defined)} 条 | "
|
||||
f"可做内容比对 {checked} 处")
|
||||
print()
|
||||
|
||||
problems = 0
|
||||
tag = lambda ok: "PASS" if ok else "FAIL" # noqa: E731
|
||||
print(f"[{tag(not dangling)}] 悬空引用:{len(dangling)} 处"
|
||||
+ (f" -> {dangling[:args.max_report]}" if dangling else ""))
|
||||
problems += bool(dangling)
|
||||
|
||||
print(f"[{tag(not orphan)}] 孤立条目:{len(orphan)} 条"
|
||||
+ (f" -> {orphan[:args.max_report]}" if orphan else ""))
|
||||
if orphan:
|
||||
print(" (顺序编码制下建议把未引用条目移入「延伸阅读」,不占编号)")
|
||||
problems += bool(orphan)
|
||||
|
||||
print(f"[{tag(not misaligned)}] 引用内容匹配:{len(misaligned)} 处可疑"
|
||||
+ ("(正文提到的作者与文献表作者不一致)" if misaligned else ""))
|
||||
for it in misaligned[:args.max_report]:
|
||||
print(f" [{it['ref']}] 正文写的是「{it['surname_in_text']}」,"
|
||||
f"文献表作者为 {it['authors_in_ref'][:3]}")
|
||||
print(f" 上下文:...{it['context'][-70:]}")
|
||||
problems += bool(misaligned)
|
||||
|
||||
order_ok = inversions == 0
|
||||
print(f"[{'PASS' if order_ok else 'WARN'}] 引用顺序:{inversions} 处逆序"
|
||||
+ ("(顺序编码制下建议按首次出现顺序编号)" if inversions else ""))
|
||||
if inversions:
|
||||
print(f" 实际顺序前 20 个编号:{seq[:20]}")
|
||||
|
||||
print()
|
||||
print("结论:" + ("全部通过" if problems == 0 else f"{problems} 项需要处理"))
|
||||
|
||||
if args.json:
|
||||
Path(args.json).write_text(json.dumps({
|
||||
"used": sorted(used_set), "defined": sorted(defined),
|
||||
"dangling": dangling, "orphan": orphan,
|
||||
"misaligned": misaligned, "inversions": inversions,
|
||||
"order": seq,
|
||||
}, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
print(f"JSON 报告:{args.json}")
|
||||
|
||||
return 0 if problems == 0 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""用 Word COM 把 docx 导出为 PDF(Word 未注册时回退到 WPS COM)。
|
||||
|
||||
用法:
|
||||
python docx_to_pdf.py [输入.docx] [输出.pdf]
|
||||
python docx_to_pdf.py --help
|
||||
|
||||
不传输入时自动找当前目录 `deliverables/` 下的 docx;该目录恰好一个 docx 才自动选中,
|
||||
多个则列出候选让你显式指定。输出默认与输入同名 `.pdf`。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WD_FORMAT_PDF = 17
|
||||
|
||||
CANDIDATES = ["Word.Application", "KWPS.Application", "WPS.Application"]
|
||||
|
||||
|
||||
def resolve_src() -> Path | None:
|
||||
"""定位待转换的 docx:显式参数 > deliverables/ 下唯一的 docx。"""
|
||||
if len(sys.argv) > 1:
|
||||
return Path(sys.argv[1])
|
||||
for base in (Path.cwd() / "deliverables", Path.cwd()):
|
||||
if not base.is_dir():
|
||||
continue
|
||||
cands = sorted(p for p in base.glob("*.docx") if not p.name.startswith("~$"))
|
||||
if len(cands) == 1:
|
||||
return cands[0]
|
||||
if len(cands) > 1:
|
||||
print(f"{base} 下有多个 docx,请显式指定要转换哪一个:")
|
||||
for p in cands:
|
||||
print(f" {p.name}")
|
||||
return None
|
||||
print("找不到待转换的 docx。用法:python docx_to_pdf.py [输入.docx] [输出.pdf]")
|
||||
return None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help"):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
src = resolve_src()
|
||||
if src is None:
|
||||
return 2
|
||||
dst = Path(sys.argv[2]) if len(sys.argv) > 2 else src.with_suffix(".pdf")
|
||||
if not src.exists():
|
||||
print(f"找不到输入文件:{src}")
|
||||
return 1
|
||||
|
||||
import win32com.client as win32 # 延迟导入,避免无 pywin32 时脚本不可读
|
||||
|
||||
last_err = None
|
||||
for progid in CANDIDATES:
|
||||
app = None
|
||||
try:
|
||||
print(f"尝试通过 {progid} 转换 ...")
|
||||
app = win32.DispatchEx(progid)
|
||||
try:
|
||||
app.Visible = False
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
app.DisplayAlerts = 0
|
||||
except Exception:
|
||||
pass
|
||||
doc = app.Documents.Open(str(src), ReadOnly=True, AddToRecentFiles=False)
|
||||
try:
|
||||
# 导出前尝试更新目录/页码域
|
||||
try:
|
||||
doc.Fields.Update()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
for toc in doc.TablesOfContents:
|
||||
toc.Update()
|
||||
except Exception:
|
||||
pass
|
||||
doc.SaveAs(str(dst), FileFormat=WD_FORMAT_PDF)
|
||||
finally:
|
||||
doc.Close(SaveChanges=False)
|
||||
app.Quit()
|
||||
if dst.exists() and dst.stat().st_size > 10_000:
|
||||
print(f"已生成 PDF:{dst}")
|
||||
print(f" 文件大小:{dst.stat().st_size / 1024:.0f} KB")
|
||||
return 0
|
||||
print(f" {progid} 未产出有效 PDF,继续尝试下一个")
|
||||
except Exception as e: # noqa: BLE001
|
||||
last_err = e
|
||||
print(f" {progid} 失败:{type(e).__name__}: {e}")
|
||||
finally:
|
||||
try:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"\n全部 COM 通道均失败。最后一次错误:{last_err}")
|
||||
print("说明:本机 Word/WPS 未注册或不可用。可改用 PyMuPDF 渲染方案。")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""论文配图工具(thesis-pipeline 第 6 步)
|
||||
|
||||
解决中文论文配图的三个常见坑:
|
||||
1. 中文字体缺失导致图上出现方块——本工具自动探测可用中文字体并在缺失时明确告警;
|
||||
2. 只出 PNG 导致放大后模糊——本工具同时输出 PNG(300dpi) 与 PDF(矢量);
|
||||
3. 配色不适合黑白打印——默认用 Okabe-Ito 色盲友好方案。
|
||||
|
||||
图定义用 JSON 描述(见 --example 输出的模板),支持折线图、柱状图、散点图、
|
||||
双轴图与"多子图"组合。复杂图建议直接用 matplotlib 写脚本,用本工具的
|
||||
setup_style() / save() 保证字体与输出规范。
|
||||
|
||||
用法:
|
||||
python figure_kit.py --example > figspec.json # 生成模板
|
||||
python figure_kit.py --spec figspec.json --data data.csv --out figures/
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt # noqa: E402
|
||||
import numpy as np # noqa: E402
|
||||
import pandas as pd # noqa: E402
|
||||
from matplotlib import font_manager # noqa: E402
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
CJK_CANDIDATES = ["SimHei", "Microsoft YaHei", "SimSun", "Noto Sans CJK SC",
|
||||
"Source Han Sans SC", "WenQuanYi Zen Hei", "PingFang SC",
|
||||
"Heiti SC", "Songti SC"]
|
||||
# Okabe-Ito 色盲友好配色
|
||||
COLORS = ["#0072B2", "#E69F00", "#009E73", "#CC79A7", "#56B4E9",
|
||||
"#D55E00", "#F0E442", "#999999"]
|
||||
|
||||
|
||||
def pick_cjk() -> str:
|
||||
avail = {f.name for f in font_manager.fontManager.ttflist}
|
||||
for n in CJK_CANDIDATES:
|
||||
if n in avail:
|
||||
return n
|
||||
print("!! 未找到中文字体:图上中文会显示为方块。", file=sys.stderr)
|
||||
print(" 安装任一:SimHei / Microsoft YaHei / Noto Sans CJK SC,"
|
||||
"或改用英文标注。", file=sys.stderr)
|
||||
return "DejaVu Sans"
|
||||
|
||||
|
||||
def setup_style() -> str:
|
||||
cjk = pick_cjk()
|
||||
plt.rcParams.update({
|
||||
"font.sans-serif": [cjk, "DejaVu Sans"],
|
||||
"font.family": "sans-serif",
|
||||
"axes.unicode_minus": False,
|
||||
"mathtext.default": "regular",
|
||||
"axes.formatter.use_mathtext": True,
|
||||
"figure.dpi": 120,
|
||||
"savefig.dpi": 300, # 学位论文图 ≥300 dpi
|
||||
"savefig.bbox": "tight",
|
||||
"axes.linewidth": 0.9,
|
||||
"axes.labelsize": 11,
|
||||
"axes.titlesize": 12,
|
||||
"xtick.labelsize": 9.5,
|
||||
"ytick.labelsize": 9.5,
|
||||
"legend.fontsize": 9,
|
||||
"legend.frameon": False,
|
||||
"lines.linewidth": 1.7,
|
||||
})
|
||||
return cjk
|
||||
|
||||
|
||||
def save(fig, outdir: Path, name: str):
|
||||
outdir.mkdir(parents=True, exist_ok=True)
|
||||
for ext in ("png", "pdf"):
|
||||
fig.savefig(outdir / f"{name}.{ext}")
|
||||
plt.close(fig)
|
||||
print(f" ok {name}.png / .pdf")
|
||||
|
||||
|
||||
EXAMPLE = {
|
||||
"figures": [
|
||||
{
|
||||
"name": "fig4-1_示例折线",
|
||||
"kind": "line",
|
||||
"size": [7.2, 3.0],
|
||||
"x": "strain", "y": ["stress_bcc", "stress_fcc"],
|
||||
"labels": ["BCC", "FCC"],
|
||||
"xlabel": "应变 ε", "ylabel": "应力 σ / MPa",
|
||||
"title": "应力–应变曲线",
|
||||
"logy": False, "grid": True
|
||||
},
|
||||
{
|
||||
"name": "fig4-2_示例柱状",
|
||||
"kind": "bar",
|
||||
"size": [5.0, 3.0],
|
||||
"x": "group", "y": ["value"],
|
||||
"ylabel": "数值", "title": "分组对比",
|
||||
"yerr": "std"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def plot_line(ax, df, spec):
|
||||
for i, col in enumerate(spec["y"]):
|
||||
if col not in df.columns:
|
||||
print(f" !! 列 {col} 不存在,跳过")
|
||||
continue
|
||||
if spec.get("x") and spec["x"] in df.columns:
|
||||
ax.plot(df[spec["x"]], df[col], color=COLORS[i % len(COLORS)],
|
||||
label=(spec.get("labels") or spec["y"])[i])
|
||||
else:
|
||||
ax.plot(df[col], color=COLORS[i % len(COLORS)],
|
||||
label=(spec.get("labels") or spec["y"])[i])
|
||||
if spec.get("logy"):
|
||||
ax.set_yscale("log")
|
||||
if spec.get("logx"):
|
||||
ax.set_xscale("log")
|
||||
|
||||
|
||||
def plot_bar(ax, df, spec):
|
||||
ycols = [c for c in spec["y"] if c in df.columns]
|
||||
if not ycols:
|
||||
raise ValueError(f"指定的 y 列在数据中都不存在:{spec['y']};实际列 {list(df.columns)}")
|
||||
xcol = spec.get("x")
|
||||
if xcol:
|
||||
if xcol not in df.columns:
|
||||
raise ValueError(f"指定的 x 列 '{xcol}' 不存在;实际列 {list(df.columns)}")
|
||||
x = np.arange(len(df))
|
||||
w = 0.8 / len(ycols)
|
||||
for i, col in enumerate(ycols):
|
||||
err = None
|
||||
if spec.get("yerr") and spec["yerr"] in df.columns:
|
||||
# 必须转成 ndarray:直接传 Series 会按索引对齐到 x 数组,
|
||||
# 索引不匹配时 matplotlib 抛 "incompatible dimensions"
|
||||
err = np.asarray(df[spec["yerr"]], dtype=float)
|
||||
ax.bar(x + i * w, np.asarray(df[col], dtype=float), width=w, yerr=err,
|
||||
capsize=3, color=COLORS[i % len(COLORS)],
|
||||
label=(spec.get("labels") or ycols)[i], edgecolor="white", lw=0.8)
|
||||
ax.set_xticks(x + w * (len(ycols) - 1) / 2)
|
||||
ax.set_xticklabels(df[xcol].astype(str))
|
||||
if spec.get("labels") or len(ycols) > 1:
|
||||
ax.legend()
|
||||
else:
|
||||
# 无 x 列:每个 y 列各作一个分组,画均值柱 + 标准差误差棒
|
||||
means = [float(np.asarray(df[c], dtype=float).mean()) for c in ycols]
|
||||
errs = [float(np.asarray(df[c], dtype=float).std(ddof=1)) if len(df) > 1 else 0.0
|
||||
for c in ycols]
|
||||
ax.bar(range(len(ycols)), means, yerr=errs, capsize=3,
|
||||
color=[COLORS[i % len(COLORS)] for i in range(len(ycols))],
|
||||
edgecolor="white", lw=0.8)
|
||||
ax.set_xticks(range(len(ycols)))
|
||||
ax.set_xticklabels([(spec.get("labels") or ycols)[i] for i in range(len(ycols))])
|
||||
|
||||
|
||||
def plot_scatter(ax, df, spec):
|
||||
for i, col in enumerate(spec["y"]):
|
||||
ax.scatter(df[spec["x"]], df[col], s=16, color=COLORS[i % len(COLORS)],
|
||||
label=(spec.get("labels") or spec["y"])[i], alpha=0.85)
|
||||
if spec.get("labels"):
|
||||
ax.legend()
|
||||
|
||||
|
||||
KINDS = {"line": plot_line, "bar": plot_bar, "scatter": plot_scatter}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="论文配图工具")
|
||||
ap.add_argument("--example", action="store_true", help="打印图定义模板")
|
||||
ap.add_argument("--spec", help="图定义 JSON")
|
||||
ap.add_argument("--data", help="数据 CSV")
|
||||
ap.add_argument("--out", default="figures", help="输出目录")
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.example:
|
||||
print(json.dumps(EXAMPLE, ensure_ascii=False, indent=1))
|
||||
return 0
|
||||
|
||||
if not args.spec or not args.data:
|
||||
print("需要 --spec 与 --data;先用 --example 看模板。")
|
||||
return 1
|
||||
|
||||
cjk = setup_style()
|
||||
print(f"中文字体:{cjk}")
|
||||
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
|
||||
df = pd.read_csv(args.data, encoding="utf-8-sig")
|
||||
outdir = Path(args.out)
|
||||
print(f"数据 {len(df)} 行 | 生成 {len(spec.get('figures', []))} 幅图")
|
||||
|
||||
for fs in spec.get("figures", []):
|
||||
kind = fs.get("kind", "line")
|
||||
fn = KINDS.get(kind)
|
||||
if not fn:
|
||||
print(f" !! 未知图型 {kind},跳过 {fs.get('name')}")
|
||||
continue
|
||||
size = fs.get("size", [7.2, 3.0])
|
||||
fig, ax = plt.subplots(figsize=size)
|
||||
fn(ax, df, fs)
|
||||
if fs.get("xlabel"):
|
||||
ax.set_xlabel(fs["xlabel"])
|
||||
if fs.get("ylabel"):
|
||||
ax.set_ylabel(fs["ylabel"])
|
||||
if fs.get("title"):
|
||||
ax.set_title(fs["title"])
|
||||
if fs.get("grid", True):
|
||||
ax.grid(alpha=0.25, lw=0.6)
|
||||
if kind == "line" and len(fs.get("y", [])) > 1:
|
||||
ax.legend()
|
||||
fig.tight_layout()
|
||||
save(fig, outdir, fs.get("name", "figure"))
|
||||
|
||||
print(f"\n输出目录:{outdir.resolve()}")
|
||||
print("提示:图题建议写在 md 里(**图 4-1 标题**),不要画进图内,便于排版统一。")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""交付前总检(thesis-pipeline 第 20 步)
|
||||
|
||||
把本项目真实踩过的坑固化成自动检查项,任一项 FAIL 就不要交付。
|
||||
|
||||
检查清单:
|
||||
1 章节目录完整性(封面/目录/摘要/各章/参考文献/致谢)
|
||||
2 正文字数达标(按 thesis.json 的 targets.words 的 90% 计)
|
||||
3 图编号连续 + 图片文件存在
|
||||
4 表数量与编号
|
||||
5 参考文献:悬空引用 / 孤立条目 / 引用内容匹配(调用 check_refs.py)
|
||||
6 小节编号连续 + 正文小节交叉引用不悬空
|
||||
7 成品 docx 无 LaTeX / $ / 反引号残留
|
||||
8 正文数字与 data/ 下数据文件的一致性抽查(防"模型改了正文没改")
|
||||
9 作者占位符集中列出
|
||||
10 交付件存在(docx/pdf)且 pdf 页数、嵌入图数可读
|
||||
11 输出 SHA-256 哈希表
|
||||
|
||||
用法:
|
||||
python final_check.py --dir <项目目录> --write
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
CITE = re.compile(r"\[(\d+(?:\s*[,,\-–]\s*\d+)*)\]")
|
||||
PLACEHOLDER = re.compile(r"〔[^〕]{0,30}待填[^〕]{0,20}〕|〔待填[^〕]*〕")
|
||||
SUBREF = re.compile(r"(\d)\.(\d+)\s*节")
|
||||
LATEX_CMD = re.compile(
|
||||
r"\\(?:frac|tfrac|dfrac|sqrt|bar|hat|tilde|vec|mathrm|mathbf|mathit|text|"
|
||||
r"left|right|rho|sigma|theta|alpha|beta|gamma|delta|varepsilon|epsilon|"
|
||||
r"lambda|mu|eta|kappa|chi|times|cdot|approx|leq|geq|infty|partial|sum|"
|
||||
r"int|tag|quad|qquad|begin|end|underbrace)\b")
|
||||
|
||||
results: list[tuple[str, bool, str]] = []
|
||||
|
||||
|
||||
def check(name: str, ok: bool, detail: str = "") -> None:
|
||||
results.append((name, ok, detail))
|
||||
|
||||
|
||||
def read_all(paths) -> str:
|
||||
return "\n\n".join(p.read_text(encoding="utf-8") for p in paths)
|
||||
|
||||
|
||||
def docx_text(path: Path) -> str:
|
||||
try:
|
||||
from docx import Document
|
||||
except ImportError:
|
||||
return ""
|
||||
d = Document(str(path))
|
||||
out = [p.text for p in d.paragraphs]
|
||||
for t in d.tables:
|
||||
for row in t.rows:
|
||||
for c in row.cells:
|
||||
out.append(c.text)
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def expand(tok: str) -> set[int]:
|
||||
out: set[int] = set()
|
||||
for part in re.split(r"[,,]", tok):
|
||||
part = part.strip()
|
||||
m = re.match(r"^(\d+)\s*[-–]\s*(\d+)$", part)
|
||||
if m:
|
||||
out.update(range(int(m.group(1)), int(m.group(2)) + 1))
|
||||
elif part.isdigit() and int(part) >= 1:
|
||||
out.add(int(part))
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="交付前总检")
|
||||
ap.add_argument("--dir", required=True, help="项目目录")
|
||||
ap.add_argument("--write", action="store_true", help="写出报告与哈希表")
|
||||
args = ap.parse_args()
|
||||
|
||||
root = Path(args.dir).resolve()
|
||||
man = root / "manuscript"
|
||||
figs = root / "figures"
|
||||
data = root / "data"
|
||||
deliv = root / "deliverables"
|
||||
refs_md = None
|
||||
for cand in [root / "05_稿件" / "参考文献.md", root / "参考文献.md"]:
|
||||
if cand.exists():
|
||||
refs_md = cand
|
||||
break
|
||||
|
||||
cfg = {}
|
||||
cfgp = root / "thesis.json"
|
||||
if cfgp.exists():
|
||||
config = json.loads(cfgp.read_text(encoding="utf-8"))
|
||||
cfg = config
|
||||
targets = cfg.get("targets", {})
|
||||
|
||||
md_files = sorted(man.glob("*.md")) if man.is_dir() else []
|
||||
if not md_files:
|
||||
print(f"找不到分章 md({man})")
|
||||
return 1
|
||||
full = read_all(md_files)
|
||||
|
||||
# 1 章节完整性
|
||||
need = cfg.get("required_sections",
|
||||
["摘要", "Abstract", "第 1 章", "参考文献", "致谢"])
|
||||
missing = [s for s in need if s not in full and (refs_md is None or s not in refs_md.read_text(encoding="utf-8"))]
|
||||
check("章节完整性", not missing, "齐全" if not missing else f"缺失:{missing}")
|
||||
|
||||
# 2 字数
|
||||
body_only = re.sub(r"```.*?```", "", full, flags=re.S)
|
||||
cjk = len(re.findall(r"[\u4e00-\u9fff]", body_only))
|
||||
want = int(targets.get("words", 15000) * 0.9)
|
||||
check(f"正文字数 ≥ {want}", cjk >= want, f"实际 {cjk} 中文字符")
|
||||
|
||||
# 3 图
|
||||
fig_names = re.findall(r"!\[[^\]]*\]\(figures/([^)]+)\)", full)
|
||||
fig_nums = re.findall(r"!\[[^\]]*\]\(figures/fig(\d+)-(\d+)_", full)
|
||||
ch_map: dict[str, list[int]] = {}
|
||||
for ch, n in fig_nums:
|
||||
ch_map.setdefault(ch, []).append(int(n))
|
||||
bad_seq = {c: v for c, v in ch_map.items() if v != list(range(1, len(v) + 1))}
|
||||
check("图编号连续", not bad_seq, "连续" if not bad_seq else f"异常:{bad_seq}")
|
||||
miss_img = [f for f in fig_names if not (figs / f).exists()]
|
||||
check("图片文件存在", not miss_img,
|
||||
f"{len(fig_names)}/{len(fig_names)} 存在" if not miss_img else f"缺失 {miss_img[:4]}")
|
||||
|
||||
# 4 表
|
||||
tabs = sorted({t for t in re.findall(r"\*\*表\s*([\d\-]+)", full)})
|
||||
check("表编号存在", len(tabs) >= 2, f"{len(tabs)} 张表")
|
||||
|
||||
# 5 参考文献(调用 check_refs.py)
|
||||
if refs_md:
|
||||
cp = subprocess.run(
|
||||
[sys.executable, str(HERE / "check_refs.py"), "--manuscript", str(man),
|
||||
"--refs", str(refs_md)],
|
||||
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
||||
out = cp.stdout or ""
|
||||
dangling = "悬空引用:0 处" in out
|
||||
orphan = "孤立条目:0 条" in out
|
||||
mis = "引用内容匹配:0 处可疑" in out
|
||||
check("参考文献一致(悬空/孤立/内容匹配)", dangling and orphan and mis,
|
||||
"三项全通过" if (dangling and orphan and mis)
|
||||
else "见 check_refs.py 输出:" + " ".join(
|
||||
l for l in out.splitlines() if l.startswith("[")))
|
||||
else:
|
||||
check("参考文献一致", False, "找不到参考文献.md")
|
||||
|
||||
# 6 小节编号与交叉引用
|
||||
secs = set(re.findall(r"^#{2,4}\s+(\d+\.\d+)", full, re.M))
|
||||
refs_secs = {f"{a}.{b}" for a, b in SUBREF.findall(full)}
|
||||
dangling_sec = sorted(s for s in refs_secs if s not in secs)
|
||||
seq_ok = True
|
||||
for ch in {s.split(".")[0] for s in secs}:
|
||||
nums = sorted(int(s.split(".")[1]) for s in secs if s.startswith(ch + "."))
|
||||
if nums and nums != list(range(1, len(nums) + 1)):
|
||||
seq_ok = False
|
||||
check("小节编号连续", seq_ok, "连续" if seq_ok else "存在跳号(如 4.7 后直接 4.10)")
|
||||
check("小节交叉引用不悬空", not dangling_sec,
|
||||
"全部有对应小节" if not dangling_sec else f"悬空:{dangling_sec}")
|
||||
|
||||
# 7 成品残留
|
||||
docx = None
|
||||
if deliv.is_dir():
|
||||
docs = sorted(deliv.glob("*.docx"))
|
||||
docx = docs[0] if docs else None
|
||||
if docx:
|
||||
dt = docx_text(docx)
|
||||
# 附录里贴的代码天然含 $、\frac 等字样(如 python 的 polyfit(...)[0]),
|
||||
# 因此先剔除"代码行"再判定残留。代码行的特征:含 = 赋值 / import / def /
|
||||
# print( ,或含代码围栏标记。
|
||||
CODEISH = re.compile(r"(^\s*(import|from|def|class|print|return|for|while|if)\b"
|
||||
r"|=|\[0\]|\bplt\.|\bnp\.|\bpd\.)")
|
||||
plain = [l for l in dt.splitlines() if not CODEISH.search(l)]
|
||||
pt = "\n".join(plain)
|
||||
dols, latex, bt = pt.count("$"), len(LATEX_CMD.findall(pt)), dt.count("```")
|
||||
check("成品无公式/标记残留(docx)", dols == 0 and latex == 0 and bt == 0,
|
||||
f"$ {dols},LaTeX {latex},反引号块 {bt}")
|
||||
else:
|
||||
check("成品无公式/标记残留(docx)", False, "deliverables/ 下没有 docx")
|
||||
|
||||
# 8 数字一致性抽查:正文里出现的数字能否在 data/ 找到同值
|
||||
if data.is_dir():
|
||||
nums_in_data = set()
|
||||
for f in data.glob("*.csv"):
|
||||
try:
|
||||
txt = f.read_text(encoding="utf-8-sig", errors="ignore")
|
||||
except Exception:
|
||||
continue
|
||||
for m in re.finditer(r"\d+\.\d{1,4}", txt):
|
||||
nums_in_data.add(m.group(0))
|
||||
body_nums = set(re.findall(r"(?<![\d.])(\d+\.\d{1,4})(?![\d])", body_only))
|
||||
# 只抽查"看起来像结果"的数值(>=0.1 且非年份/非百分比)
|
||||
sample = {n for n in body_nums if float(n) >= 0.1}
|
||||
if sample:
|
||||
hit = sum(1 for n in sample if n in nums_in_data)
|
||||
ratio = hit / len(sample)
|
||||
check("正文数字与 data/ 一致性抽查", ratio >= 0.6,
|
||||
f"{hit}/{len(sample)} 可在 data/ 找到同值(阈值 60%;偏低通常意味着模型改过而正文数字未回填)")
|
||||
else:
|
||||
check("正文数字与 data/ 一致性抽查", True, "正文未发现需抽查的数值")
|
||||
else:
|
||||
check("正文数字与 data/ 一致性抽查", False, "没有 data/ 目录")
|
||||
|
||||
# 9 占位符
|
||||
ph = sorted(set(PLACEHOLDER.findall(full)))
|
||||
check("作者占位符已集中标注", True, f"{len(ph)} 处待替换")
|
||||
|
||||
# 10 交付件
|
||||
for ext in ("docx", "pdf"):
|
||||
f = None
|
||||
if deliv.is_dir():
|
||||
cands = sorted(deliv.glob(f"*.{ext}"))
|
||||
f = cands[0] if cands else None
|
||||
check(f"交付件 .{ext} 存在", bool(f),
|
||||
f"{f.stat().st_size/1024:.0f} KB" if f else "缺失")
|
||||
if deliv.is_dir():
|
||||
pdfs = sorted(deliv.glob("*.pdf"))
|
||||
if pdfs:
|
||||
try:
|
||||
import pymupdf
|
||||
d = pymupdf.open(str(pdfs[0]))
|
||||
n_img = sum(len(p.get_images(full=True)) for p in d)
|
||||
check("PDF 页数与嵌入图可读", d.page_count > 0,
|
||||
f"{d.page_count} 页 / {n_img} 图(md 中引用 {len(fig_names)} 图)")
|
||||
except Exception as e: # noqa: BLE001
|
||||
check("PDF 页数与嵌入图可读", False, f"PyMuPDF 读取失败:{e}")
|
||||
|
||||
# 输出
|
||||
lines = [f"# 交付前总检报告", "",
|
||||
f"项目:`{root}`", f"生成:由 thesis-pipeline/scripts/final_check.py", "",
|
||||
"| 检查项 | 结果 | 说明 |", "|---|---|---|"]
|
||||
npass = 0
|
||||
for name, ok, detail in results:
|
||||
npass += bool(ok)
|
||||
lines.append(f"| {name} | {'✅ 通过' if ok else '❌ 未通过'} | {detail} |")
|
||||
lines += ["", f"**{npass}/{len(results)} 项通过。**", ""]
|
||||
if ph:
|
||||
lines += ["## 待替换的占位符", ""] + [f"- `{x}`" for x in ph] + [""]
|
||||
report = "\n".join(lines)
|
||||
print(report)
|
||||
|
||||
if args.write:
|
||||
outdir = root / "20_投稿前总检"
|
||||
outdir.mkdir(parents=True, exist_ok=True)
|
||||
(outdir / "CHECK_REPORT.md").write_text(report, encoding="utf-8")
|
||||
hashes = []
|
||||
for base in (data, figs, deliv):
|
||||
if not base.is_dir():
|
||||
continue
|
||||
for p in sorted(base.rglob("*")):
|
||||
if p.is_file() and p.suffix.lower() in (".csv", ".json", ".png", ".pdf", ".docx"):
|
||||
hashes.append((str(p.relative_to(root)),
|
||||
hashlib.sha256(p.read_bytes()).hexdigest(),
|
||||
p.stat().st_size))
|
||||
hl = ["# 交付物哈希表(SHA-256)", "",
|
||||
"重跑 `python scripts/final_check.py --dir . --write` 可刷新。", "",
|
||||
"| 文件 | 字节 | SHA-256 |", "|---|---|---|"]
|
||||
hl += [f"| `{r}` | {s} | `{h}` |" for r, h, s in hashes]
|
||||
deliv.mkdir(parents=True, exist_ok=True)
|
||||
(deliv / "HASHES.txt").write_text("\n".join(hl), encoding="utf-8")
|
||||
print(f"\n已写出:{outdir / 'CHECK_REPORT.md'}")
|
||||
print(f"已写出:{deliv / 'HASHES.txt'}({len(hashes)} 个文件)")
|
||||
|
||||
return 0 if npass == len(results) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,315 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""LaTeX 数学式 -> Unicode 文本转换(供 docx 构建使用)。
|
||||
|
||||
学位论文正文需要人眼可读的公式。python-docx 无法排版真正的数学公式
|
||||
(OMML),因此本模块把 md 源中的 LaTeX 片段转换为 Unicode 字符表示,
|
||||
使其在 Word/WPS 中可直接阅读、可复制、可打印。
|
||||
|
||||
处理能力:
|
||||
- 希腊字母与常用算符:\\rho -> ρ,\\times -> ×,\\approx -> ≈ 等
|
||||
- 上标/下标:M^2 -> M²,C_1 -> C₁(无对应 Unicode 时用 ^(...) / _(...))
|
||||
- 常用修饰:\\bar{x} -> x̄,\\tilde{x} -> x̃,\\hat{x} -> x̂
|
||||
- 分数:\\frac{a}{b} -> (a)/(b);\\tfrac 同
|
||||
- 根号:\\sqrt{x} -> √(x)
|
||||
- 函数名与排版命令:\\mathrm/\\text/\\left/\\right/\\displaystyle/\\quad 等直接剥离
|
||||
- 行间公式的 \\tag{2-1} -> (2-1)
|
||||
|
||||
不支持任意嵌套的复杂公式(如多重分式嵌套、矩阵)。若遇到无法处理的结构,
|
||||
保留其原文并在控制台打印警告,由人工核对——不静默产生错误公式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
GREEK = {
|
||||
"alpha": "α", "beta": "β", "gamma": "γ", "Gamma": "Γ", "delta": "δ",
|
||||
"Delta": "Δ", "epsilon": "ε", "varepsilon": "ε", "zeta": "ζ", "eta": "η",
|
||||
"theta": "θ", "Theta": "Θ", "iota": "ι", "kappa": "κ", "lambda": "λ",
|
||||
"Lambda": "Λ", "mu": "μ", "nu": "ν", "xi": "ξ", "Xi": "Ξ", "pi": "π",
|
||||
"Pi": "Π", "rho": "ρ", "sigma": "σ", "Sigma": "Σ", "tau": "τ",
|
||||
"upsilon": "υ", "phi": "φ", "varphi": "φ", "chi": "χ", "psi": "ψ",
|
||||
"Psi": "Ψ", "omega": "ω", "Omega": "Ω",
|
||||
}
|
||||
|
||||
OPS = {
|
||||
"times": "×", "cdot": "·", "pm": "±", "mp": "∓", "approx": "≈",
|
||||
"neq": "≠", "leq": "≤", "le": "≤", "geq": "≥", "ge": "≥",
|
||||
"ll": "≪", "gg": "≫", "sim": "~", "simeq": "≃", "equiv": "≡",
|
||||
"propto": "∝", "infty": "∞", "partial": "∂", "nabla": "∇",
|
||||
"rightarrow": "→", "to": "→", "leftarrow": "←", "Rightarrow": "⇒",
|
||||
"in": "∈", "notin": "∉", "subset": "⊂", "cup": "∪", "cap": "∩",
|
||||
"sum": "Σ", "prod": "Π", "int": "∫", "circ": "∘", "ast": "*",
|
||||
"sqrt": "√", "angle": "∠", "perp": "⊥", "parallel": "∥",
|
||||
"quad": " ", "qquad": " ", "enspace": " ", "qquad": " ",
|
||||
",": " ", ";": " ", "!": "", " ": " ",
|
||||
}
|
||||
|
||||
# 直接剥离的排版命令
|
||||
STRIP_CMDS = [
|
||||
"mathrm", "mathbf", "mathit", "mathsf", "mathtt", "text", "textrm",
|
||||
"operatorname", "mathcal", "mathbb", "mathfrak",
|
||||
"left", "right", "big", "Big", "bigg", "Bigg", "displaystyle",
|
||||
"textstyle", "limits", "nolimits", "mathstrut", "phantom",
|
||||
"underbrace", "overbrace", "underset", "overset",
|
||||
]
|
||||
|
||||
FUNCS = ["ln", "log", "exp", "sin", "cos", "tan", "max", "min", "clamp",
|
||||
"arccos", "arcsin", "arctan", "det", "dim"]
|
||||
|
||||
SUP = {"0": "⁰", "1": "¹", "2": "²", "3": "³", "4": "⁴", "5": "⁵",
|
||||
"6": "⁶", "7": "⁷", "8": "⁸", "9": "⁹", "+": "⁺", "-": "⁻",
|
||||
"=": "⁼", "(": "⁽", ")": "⁾", "n": "ⁿ", "i": "ⁱ", "*": "*",
|
||||
"ε": "ᵋ", "β": "ᵝ", "γ": "ᵞ", "δ": "ᵟ", "φ": "ᵠ", "χ": "ᵡ",
|
||||
"a": "ᵃ", "b": "ᵇ", "c": "ᶜ", "d": "ᵈ", "e": "ᵉ", "f": "ᶠ",
|
||||
"g": "ᵍ", "h": "ʰ", "j": "ʲ", "k": "ᵏ", "l": "ˡ", "m": "ᵐ",
|
||||
"o": "ᵒ", "p": "ᵖ", "r": "ʳ", "s": "ˢ", "t": "ᵗ", "u": "ᵘ",
|
||||
"v": "ᵛ", "w": "ʷ", "x": "ˣ", "y": "ʸ", "z": "ᶻ"}
|
||||
|
||||
SUB = {"0": "₀", "1": "₁", "2": "₂", "3": "₃", "4": "₄", "5": "₅",
|
||||
"6": "₆", "7": "₇", "8": "₈", "9": "₉", "+": "₊", "-": "₋",
|
||||
"=": "₌", "(": "₍", ")": "₎", "a": "ₐ", "e": "ₑ", "i": "ᵢ",
|
||||
"o": "ₒ", "r": "ᵣ", "s": "ₛ", "t": "ₜ", "x": "ₓ", "y": "ᵧ",
|
||||
"β": "ᵦ", "γ": "ᵧ", "ρ": "ᵨ", "φ": "ᵩ", "χ": "ᵪ"}
|
||||
|
||||
WARNINGS: list[str] = []
|
||||
|
||||
|
||||
def _script(ch: str, table: dict[str, str]) -> str | None:
|
||||
return table.get(ch)
|
||||
|
||||
|
||||
def _brace_group(s: str, i: int) -> tuple[str, int]:
|
||||
"""从 s[i] == '{' 开始取配对花括号内的内容。返回 (内容, 新位置)。"""
|
||||
if i >= len(s) or s[i] != "{":
|
||||
return "", i
|
||||
depth = 0
|
||||
for j in range(i, len(s)):
|
||||
if s[j] == "{":
|
||||
depth += 1
|
||||
elif s[j] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return s[i + 1:j], j + 1
|
||||
return s[i + 1:], len(s)
|
||||
|
||||
|
||||
def _one_token(s: str, i: int) -> tuple[str, int]:
|
||||
"""取一个"原子":{...} 组、单个字符,或反斜杠命令。"""
|
||||
if i >= len(s):
|
||||
return "", i
|
||||
if s[i] == "{":
|
||||
return _brace_group(s, i)
|
||||
if s[i] == "\\":
|
||||
m = re.match(r"\\([a-zA-Z]+)", s[i:])
|
||||
if m:
|
||||
return "\\" + m.group(1), i + m.end()
|
||||
return s[i:i + 2], i + 2
|
||||
return s[i], i + 1
|
||||
|
||||
|
||||
def _to_script(content: str, table: dict[str, str], marker: str) -> str:
|
||||
"""把内容转成 Unicode 上下标。
|
||||
|
||||
优先整体转换;含无法映射的字符时,尝试"最内层可映射子串"策略:
|
||||
例如上标内容 "ε_D" 无法整体映射,但去掉 "_D" 后的 "ε" 也不可映射,
|
||||
此时退化为 marker(内容)。对下标内容 "bond",因字母 b/n/d 无下标
|
||||
字形,退化为 _(bond)。
|
||||
"""
|
||||
out = []
|
||||
content = content.strip()
|
||||
# _one_token 在解析 "^" / "_" 后可能返回带花括号的组(如 "{\mathrm{bond}}")
|
||||
# 或未配对的 "{bond}",这里统一剥掉最外层花括号,否则后续的
|
||||
# "纯字母" 判断会因存在 {} 而失败,退化成 _(bond) 形式。
|
||||
while len(content) >= 2 and content.startswith("{") and content.endswith("}"):
|
||||
content = content[1:-1].strip()
|
||||
# 仅当内容里确实还有未处理的 LaTeX 命令(反斜杠)时才递归展开,
|
||||
# 否则会把已解析的 "_σ" 再次映射成下标而导致信息丢失。
|
||||
if "\\" in content:
|
||||
content = latex_to_unicode(content)
|
||||
content = re.sub(r"\\[a-zA-Z]+", "", content)
|
||||
content = content.strip()
|
||||
if not content:
|
||||
return ""
|
||||
for ch in content:
|
||||
rep = _script(ch, table)
|
||||
if rep is None:
|
||||
# 尝试把内容里的 "^..." 或 "_..." 剥掉后重试(处理 ^{ n} 这类)
|
||||
cleaned = re.sub(r"[\^_]\s*\(?[^)]*\)?", "", content).strip()
|
||||
if cleaned and cleaned != content:
|
||||
return _to_script(cleaned, table, marker)
|
||||
# 纯字母或单个希腊字母内容:用 marker + 内容(如 _(bond) -> _bond、
|
||||
# _σ -> _σ)。Unicode 没有 σ/ε 的下标字形,加括号反而更差,故不加。
|
||||
if re.fullmatch(r"[a-zA-Z]+|[\u0370-\u03ff]", content):
|
||||
rep2 = table.get(content) or table.get(GREEK.get(content, ""))
|
||||
if rep2 is not None:
|
||||
return rep2
|
||||
return f"{marker}{content}"
|
||||
return f"{marker}({content})"
|
||||
out.append(rep)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _simplify_frac(s: str) -> str:
|
||||
"""把 (a)/(b) 化简为 a/b —— 仅当 a、b 不含低优先运算符时。"""
|
||||
for _ in range(6):
|
||||
m = re.search(r"\(([^()]*)\)/\(([^()]*)\)", s)
|
||||
if not m:
|
||||
break
|
||||
a, b = m.group(1).strip(), m.group(2).strip()
|
||||
if any(op in a for op in "+- ") or any(op in b for op in "+- "):
|
||||
break
|
||||
s = s[:m.start()] + f"{a}/{b}" + s[m.end():]
|
||||
return s
|
||||
|
||||
|
||||
def latex_to_unicode(expr: str) -> str:
|
||||
"""把一段 LaTeX 数学式转换为 Unicode 文本。"""
|
||||
s = expr.strip()
|
||||
# 0a) 定积分上下限:先把 \int_a^b 展开成可读形式,避免上下标互相覆盖。
|
||||
# 例如 "\int_0^{\varepsilon_D}" -> "(从 0 到 ε_D 的积分)"
|
||||
def _int_limit(m):
|
||||
lo = m.group(1).strip()
|
||||
hi = m.group(2).strip()
|
||||
lo_t = latex_to_unicode(lo) if "\\" in lo else lo
|
||||
hi_t = latex_to_unicode(hi) if "\\" in hi else hi
|
||||
return f"(从 {lo_t} 到 {hi_t} 积分) "
|
||||
s = re.sub(r"\\int\s*_(\{[^}]*\}|[0-9a-zA-Z])\s*\^\s*(\{[^}]*\}|[0-9a-zA-Z])",
|
||||
_int_limit, s)
|
||||
|
||||
# 0b) 清除间距类命令(\, \; \! 等)——必须在上下标解析之前做,
|
||||
# 否则 "^{\,n}" 的内容会变成 "\,n",无法映射为上标。
|
||||
s = re.sub(r"\\[,;!>]", "", s)
|
||||
s = re.sub(r"\\(?:quad|qquad|enspace|thinspace|medspace|thickspace)\b", " ", s)
|
||||
|
||||
# 1) 处理 \frac{a}{b} / \tfrac / \dfrac(可能嵌套,循环到不动点)
|
||||
for _ in range(6):
|
||||
m = re.search(r"\\(?:dfrac|tfrac|frac)\s*\{", s)
|
||||
if not m:
|
||||
break
|
||||
start = m.start()
|
||||
a, p = _brace_group(s, s.index("{", m.start()))
|
||||
# 跳过空白后取第二个组
|
||||
while p < len(s) and s[p].isspace():
|
||||
p += 1
|
||||
if p >= len(s) or s[p] != "{":
|
||||
break
|
||||
b, p2 = _brace_group(s, p)
|
||||
s = s[:start] + f"({a})/({b})" + s[p2:]
|
||||
|
||||
# 2) 处理 \sqrt{x} -> √(x)
|
||||
for _ in range(4):
|
||||
m = re.search(r"\\sqrt\s*\{", s)
|
||||
if not m:
|
||||
break
|
||||
c, p = _brace_group(s, s.index("{", m.start()))
|
||||
s = s[:m.start()] + f"√({c})" + s[p:]
|
||||
|
||||
# 3) 剥离排版命令(保留其内容)
|
||||
for cmd in STRIP_CMDS:
|
||||
s = re.sub(r"\\" + cmd + r"\s*", "", s)
|
||||
s = re.sub(r"\\begin\{[^}]*\}|\\end\{[^}]*\}", "", s)
|
||||
|
||||
# 4) 修饰符:\bar{x} \tilde{x} \hat{x} \dot{x} \vec{x}
|
||||
marks = {"bar": "\u0304", "tilde": "\u0303", "hat": "\u0302",
|
||||
"dot": "\u0307", "vec": "\u20d7", "overline": "\u0305"}
|
||||
for _ in range(6):
|
||||
m = re.search(r"\\(bar|tilde|hat|dot|vec|overline)\s*\{", s)
|
||||
if not m:
|
||||
break
|
||||
c, p = _brace_group(s, s.index("{", m.start()))
|
||||
comb = marks[m.group(1)]
|
||||
s = s[:m.start()] + c + comb + s[p:]
|
||||
|
||||
# 5) 上下标
|
||||
out = []
|
||||
i = 0
|
||||
while i < len(s):
|
||||
ch = s[i]
|
||||
if ch in "^_":
|
||||
table = SUP if ch == "^" else SUB
|
||||
marker = "^" if ch == "^" else "_"
|
||||
nxt, i2 = _one_token(s, i + 1)
|
||||
if nxt.startswith("\\") and nxt[1:] in GREEK:
|
||||
nxt = GREEK[nxt[1:]]
|
||||
elif len(nxt) == 1 and nxt.isalpha() and nxt not in table:
|
||||
out.append(marker + nxt)
|
||||
i = i2
|
||||
continue
|
||||
out.append(_to_script(nxt, table, marker))
|
||||
i = i2
|
||||
continue
|
||||
out.append(ch)
|
||||
i += 1
|
||||
s = "".join(out)
|
||||
|
||||
# 6) 希腊字母
|
||||
for name, sym in GREEK.items():
|
||||
s = re.sub(r"\\" + name + r"(?![a-zA-Z])", sym, s)
|
||||
|
||||
# 7) 函数名:\ln -> ln,\max -> max
|
||||
for fn in FUNCS:
|
||||
s = re.sub(r"\\" + fn + r"\b", fn, s)
|
||||
|
||||
# 8) 算符与符号
|
||||
for name in sorted(OPS, key=len, reverse=True):
|
||||
s = re.sub(r"\\" + re.escape(name) + r"(?![a-zA-Z])", OPS[name], s)
|
||||
|
||||
# 9) 剩余未知命令:保留原名并告警
|
||||
for m in re.finditer(r"\\[a-zA-Z]+", s):
|
||||
if m.group(0) not in ("\\",):
|
||||
WARNINGS.append(m.group(0))
|
||||
s = re.sub(r"\\,|\\;|\\!|\\ ", " ", s)
|
||||
|
||||
# 10) 清理多余花括号与空白
|
||||
s = s.replace("{", "").replace("}", "")
|
||||
s = _simplify_frac(s)
|
||||
s = re.sub(r"[ \t]{2,}", " ", s).strip()
|
||||
return s
|
||||
|
||||
|
||||
_TAG = re.compile(r"\\tag\{([^}]*)\}")
|
||||
|
||||
|
||||
def convert_display(block: str) -> str:
|
||||
"""转换行间公式:\\tag{2-1} -> (2-1),其余转 Unicode。"""
|
||||
tags = _TAG.findall(block)
|
||||
body = _TAG.sub("", block)
|
||||
conv = latex_to_unicode(body)
|
||||
if tags:
|
||||
return f"{conv} ({tags[0].strip()})"
|
||||
return conv
|
||||
|
||||
|
||||
INLINE = re.compile(r"(?<!\$)\$([^$\n]+)\$(?!\$)")
|
||||
DISPLAY = re.compile(r"\$\$(.+?)\$\$", re.S)
|
||||
|
||||
|
||||
def convert_text(text: str) -> str:
|
||||
"""对整篇文本做公式转换(先处理 $$...$$,再处理 $...$)。"""
|
||||
text = DISPLAY.sub(lambda m: "\n" + convert_display(m.group(1)) + "\n", text)
|
||||
text = INLINE.sub(lambda m: latex_to_unicode(m.group(1)), text)
|
||||
return text
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
samples = [
|
||||
r"\bar{\rho} = \frac{\rho^*}{\rho_s} = \eta \, \left(\frac{d}{a}\right)^{2}",
|
||||
r"\frac{E^*}{E_s} = C_1 \, \bar{\rho}^{\,n}",
|
||||
r"\mathrm{SEA} = \frac{\displaystyle\int_0^{\varepsilon_D} \sigma \, \mathrm{d}\varepsilon}{\bar{\rho}\,\rho_s}",
|
||||
r"n \approx 2",
|
||||
r"30 \times 30 \times 30",
|
||||
r"f_{\mathrm{bond}}(t) = 1 - \kappa \, \frac{t - t_{\mathrm{ref}}}{t_{\mathrm{ref}}}",
|
||||
]
|
||||
for s in samples:
|
||||
print("IN :", s)
|
||||
print("OUT:", latex_to_unicode(s))
|
||||
print()
|
||||
if WARNINGS:
|
||||
print("未处理的命令:", sorted(set(WARNINGS)))
|
||||
@@ -0,0 +1,369 @@
|
||||
#!/usr/bin/env python3
|
||||
"""paper-pipeline state machine.
|
||||
|
||||
Keeps the pipeline's progress in the *project folder* rather than in any one
|
||||
agent's context, so the run survives a new session, a different AI, or a
|
||||
different machine. Standard library only; Python 3.8+.
|
||||
|
||||
python pipeline_state.py init --dir <folder> --title "..." --direction "..."
|
||||
python pipeline_state.py status --dir <folder>
|
||||
python pipeline_state.py next --dir <folder>
|
||||
python pipeline_state.py advance --dir <folder> --step 07 --artifacts a.md b.csv
|
||||
python pipeline_state.py gate --dir <folder> --step 07 --pass --note "..."
|
||||
python pipeline_state.py gate --dir <folder> --step 07 --fail --note "缺 3 篇全文"
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# ---------------------------------------------------------------- step table
|
||||
STEPS = [
|
||||
("00", "总控进度判断", "项目与检索"),
|
||||
("01", "项目初始化", "项目与检索"),
|
||||
("02", "检索式生成", "项目与检索"),
|
||||
("03", "检索与导出", "项目与检索"),
|
||||
("04", "选题与空白识别", "项目与检索"),
|
||||
("05", "对标库深度学习", "文献与证据"),
|
||||
("06", "文献筛选分类", "文献与证据"),
|
||||
("07", "导入引用库取全文", "文献与证据"),
|
||||
("08", "文献精读", "文献与证据"),
|
||||
("09", "综述/论文框架搭建", "框架与写作"),
|
||||
("10", "图表制作与引用", "框架与写作"),
|
||||
("11", "摘要与引言", "框架与写作"),
|
||||
("12", "方法与结果", "框架与写作"),
|
||||
("13", "讨论与结论", "框架与写作"),
|
||||
("14", "目标期刊选择", "投稿与返修"),
|
||||
("15", "目标期刊格式学习", "投稿与返修"),
|
||||
("16", "润色与语言打磨", "投稿与返修"),
|
||||
("17", "图片版权", "投稿与返修"),
|
||||
("18", "Cover Letter", "投稿与返修"),
|
||||
("19", "终稿去 AI 痕迹与合规声明", "投稿与返修"),
|
||||
("20", "投稿前总检", "投稿与返修"),
|
||||
("21", "返修与回复", "投稿与返修"),
|
||||
]
|
||||
IDS = [s[0] for s in STEPS]
|
||||
NAME = {s[0]: s[1] for s in STEPS}
|
||||
GROUP = {s[0]: s[2] for s in STEPS}
|
||||
|
||||
STATE_FILE = "PAPER_STATE.json"
|
||||
HUMAN_FILE = "PIPELINE.md"
|
||||
SCHEMA = "paper-pipeline/1.1"
|
||||
# 1.0 had 21 steps (00-20) with no dedicated de-AI step; 1.1 inserts step 19.
|
||||
LEGACY_SCHEMAS = {"paper-pipeline/1.0": (
|
||||
"旧版 1.0 是 21 步(00-20),没有独立的「终稿去 AI 痕迹」步,"
|
||||
"且第 19 步当时是「投稿前总检」。1.1 在第 19 位插入了去 AI 痕迹步,"
|
||||
"原 19/20 顺延为 20/21。请核对已完成步骤的含义后再继续。")}
|
||||
|
||||
|
||||
def _stdout_utf8() -> None:
|
||||
for stream in ("stdout", "stderr"):
|
||||
s = getattr(sys, stream)
|
||||
try:
|
||||
s.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def _load(root: str) -> dict:
|
||||
p = os.path.join(root, STATE_FILE)
|
||||
if not os.path.isfile(p):
|
||||
_die(f"{p} 不存在。先跑 init:\n"
|
||||
f' python pipeline_state.py init --dir "{root}" '
|
||||
f'--title "<题目>" --direction "<方向>"')
|
||||
with io.open(p, encoding="utf-8") as fh:
|
||||
st = json.load(fh)
|
||||
legacy = LEGACY_SCHEMAS.get(st.get("schema", ""))
|
||||
if legacy:
|
||||
print(f"[!] 读到旧版状态文件 schema={st.get('schema')}。\n {legacy}",
|
||||
file=sys.stderr)
|
||||
return st
|
||||
|
||||
|
||||
def _save(root: str, st: dict) -> None:
|
||||
st["updated_at"] = _now()
|
||||
with io.open(os.path.join(root, STATE_FILE), "w", encoding="utf-8") as fh:
|
||||
json.dump(st, fh, ensure_ascii=False, indent=1)
|
||||
with io.open(os.path.join(root, HUMAN_FILE), "w", encoding="utf-8") as fh:
|
||||
fh.write(render_human(st))
|
||||
|
||||
|
||||
def _die(msg: str, code: int = 2) -> None:
|
||||
print(msg, file=sys.stderr)
|
||||
raise SystemExit(code)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- render
|
||||
def render_human(st: dict) -> str:
|
||||
L = []
|
||||
L.append(f"# 论文流水线进度 · {st.get('title') or '(未命名)'}")
|
||||
L.append("")
|
||||
L.append(f"- 方向:{st.get('direction') or '(未填)'}")
|
||||
b = st.get("brief") or {}
|
||||
if b:
|
||||
for k in ("type", "venue", "quartile", "length_limit", "figure_limit",
|
||||
"has_experiment", "authors"):
|
||||
if b.get(k):
|
||||
L.append(f"- {k}:{b[k]}")
|
||||
L.append(f"- 模式:{st.get('mode', 'autopilot')}")
|
||||
L.append(f"- 更新:{st.get('updated_at', '')}")
|
||||
L.append("")
|
||||
done = st.get("completed", [])
|
||||
cur = st.get("current")
|
||||
L.append(f"**进度 {len(done)}/21** 当前:{cur or '完成'}"
|
||||
+ (f"({NAME.get(cur, '')})" if cur else ""))
|
||||
L.append("")
|
||||
L.append("| 步 | 名称 | 组 | 状态 | 闸门 | 产出 |")
|
||||
L.append("|---:|---|---|---|---|---|")
|
||||
for sid, name, group in STEPS:
|
||||
rec = (st.get("steps") or {}).get(sid) or {}
|
||||
if sid in done:
|
||||
status = "已完成"
|
||||
elif sid == cur:
|
||||
status = "进行中"
|
||||
else:
|
||||
status = "未开始"
|
||||
gate = rec.get("gate") or ""
|
||||
arts = rec.get("artifacts") or []
|
||||
art_s = "、".join(f"`{a}`" for a in arts[:3]) + ("…" if len(arts) > 3 else "")
|
||||
L.append(f"| {sid} | {name} | {group} | {status} | {gate} | {art_s} |")
|
||||
L.append("")
|
||||
log = st.get("log") or []
|
||||
if log:
|
||||
L.append("## 操作日志")
|
||||
L.append("")
|
||||
for e in log[-25:]:
|
||||
L.append(f"- `{e.get('at','')}` {e.get('event','')} "
|
||||
f"{e.get('step','')} {e.get('note','')}".rstrip())
|
||||
L.append("")
|
||||
return "\n".join(L)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- commands
|
||||
def cmd_init(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
os.makedirs(root, exist_ok=True)
|
||||
p = os.path.join(root, STATE_FILE)
|
||||
if os.path.isfile(p) and not a.force:
|
||||
_die(f"{p} 已存在。要重建加 --force(会丢失已有进度记录)。")
|
||||
if a.start not in IDS:
|
||||
_die(f"--start 必须是 00..20 之一,收到 {a.start!r}")
|
||||
st = {
|
||||
"schema": SCHEMA,
|
||||
"title": a.title or "",
|
||||
"direction": a.direction or "",
|
||||
"mode": a.mode,
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
"current": a.start,
|
||||
"completed": [s for s in IDS if s < a.start],
|
||||
"steps": {},
|
||||
"brief": {
|
||||
"type": a.type or "",
|
||||
"venue": a.venue or "",
|
||||
"quartile": a.quartile or "",
|
||||
"length_limit": a.length or "",
|
||||
"figure_limit": a.figures or "",
|
||||
"has_experiment": a.has_experiment or "",
|
||||
"authors": a.authors or "占位符(待补真实作者/单位/邮箱/ORCID)",
|
||||
},
|
||||
"log": [{"at": _now(), "event": "init", "step": a.start,
|
||||
"note": f"从第 {a.start} 步开始"}],
|
||||
}
|
||||
for sid, name, group in STEPS:
|
||||
os.makedirs(os.path.join(root, f"{sid}_{name}"), exist_ok=True)
|
||||
for extra in ("refs", "data", "figures", "manuscript"):
|
||||
os.makedirs(os.path.join(root, extra), exist_ok=True)
|
||||
_save(root, st)
|
||||
print(f"[ok] 项目初始化:{root}")
|
||||
print(f"[ok] 当前步骤 {a.start} · {NAME[a.start]} · {GROUP[a.start]}")
|
||||
print(f"[ok] 已建 {len(STEPS)} 个步骤文件夹 + refs/ data/ figures/ manuscript/")
|
||||
if not st["brief"]["venue"]:
|
||||
print("[!] 目标期刊还没定 —— 第 01 步必须定下来,否则后面的格式与选刊全靠猜")
|
||||
if not st["brief"]["has_experiment"]:
|
||||
print("[!] 有无真实实验数据还没写 —— 第 01 步必须写清楚:"
|
||||
"没有就必须在摘要和范围声明里写明是仿真/计算研究")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_status(a) -> int:
|
||||
st = _load(os.path.abspath(a.dir))
|
||||
sys.stdout.write(render_human(st))
|
||||
nxt = st.get("current")
|
||||
if nxt:
|
||||
print(f"\n>>> 下一步:第 {nxt} 步 · {NAME[nxt]} · {GROUP[nxt]}")
|
||||
else:
|
||||
print("\n>>> 21 步已全部完成。")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_next(a) -> int:
|
||||
st = _load(os.path.abspath(a.dir))
|
||||
s = st.get("current")
|
||||
if not s:
|
||||
print("21 步已全部完成。")
|
||||
return 0
|
||||
print(f"{s}\t{NAME[s]}\t{GROUP[s]}")
|
||||
bn = st.get("blocked")
|
||||
if bn:
|
||||
print(f"[!] 上一步闸门未过:{bn}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_advance(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
s = a.step
|
||||
if s not in IDS:
|
||||
_die(f"--step 必须是 00..20 之一,收到 {s!r}")
|
||||
rec = st.setdefault("steps", {}).setdefault(s, {})
|
||||
rec.setdefault("gate", "未检查")
|
||||
rec["artifacts"] = list(a.artifacts or rec.get("artifacts") or [])
|
||||
rec["finished_at"] = _now()
|
||||
if s not in st["completed"]:
|
||||
st["completed"].append(s)
|
||||
st["completed"] = sorted(set(st["completed"]), key=IDS.index)
|
||||
i = IDS.index(s)
|
||||
st["current"] = IDS[i + 1] if i + 1 < len(IDS) else None
|
||||
st["log"].append({"at": _now(), "event": "advance", "step": s,
|
||||
"note": f"{len(rec['artifacts'])} 个产出"})
|
||||
_save(root, st)
|
||||
# 闸门提醒
|
||||
if rec.get("gate") in (None, "", "未检查", "未通过"):
|
||||
print(f"[!] 第 {s} 步已标记完成,但闸门状态是「{rec.get('gate')}」——"
|
||||
f"请跑 gate --pass 或 gate --fail 把结论记下来")
|
||||
print(f"[ok] 第 {s} 步完成 → 下一步 "
|
||||
+ (f"第 {st['current']} 步 · {NAME[st['current']]}" if st["current"] else "(全部完成)"))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_gate(a) -> int:
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
s = a.step
|
||||
if s not in IDS:
|
||||
_die(f"--step 必须是 00..20 之一,收到 {s!r}")
|
||||
rec = st.setdefault("steps", {}).setdefault(s, {})
|
||||
if a.passed and a.failed:
|
||||
_die("--pass 和 --fail 只能选一个")
|
||||
if not (a.passed or a.failed):
|
||||
_die("必须给 --pass 或 --fail")
|
||||
rec["gate"] = "通过" if a.passed else "未通过"
|
||||
rec["gate_note"] = a.note or ""
|
||||
rec["gate_at"] = _now()
|
||||
if a.failed:
|
||||
st["blocked"] = f"第 {s} 步闸门未通过:{a.note or ''}"
|
||||
if s in st["completed"]:
|
||||
st["completed"].remove(s)
|
||||
st["current"] = s
|
||||
else:
|
||||
st.pop("blocked", None)
|
||||
st["log"].append({"at": _now(), "event": "gate",
|
||||
"step": s, "note": f"{rec['gate']} {a.note or ''}".strip()})
|
||||
_save(root, st)
|
||||
print(f"[ok] 第 {s} 步闸门:{rec['gate']}"
|
||||
+ (f" —— {rec['gate_note']}" if rec["gate_note"] else ""))
|
||||
if a.failed:
|
||||
print(f"[!] 已回退到第 {s} 步重做。修完再 advance。")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_brief(a) -> int:
|
||||
"""Record or amend the project brief without rebuilding the project."""
|
||||
root = os.path.abspath(a.dir)
|
||||
st = _load(root)
|
||||
b = st.setdefault("brief", {})
|
||||
changed = []
|
||||
for k, v in (("type", a.type), ("venue", a.venue), ("quartile", a.quartile),
|
||||
("length_limit", a.length), ("figure_limit", a.figures),
|
||||
("has_experiment", a.has_experiment), ("authors", a.authors)):
|
||||
if v is not None:
|
||||
b[k] = v
|
||||
changed.append(k)
|
||||
if a.title is not None:
|
||||
st["title"] = a.title
|
||||
changed.append("title")
|
||||
if a.direction is not None:
|
||||
st["direction"] = a.direction
|
||||
changed.append("direction")
|
||||
if a.mode is not None:
|
||||
st["mode"] = a.mode
|
||||
changed.append("mode")
|
||||
st["log"].append({"at": _now(), "event": "brief", "step": st.get("current") or "",
|
||||
"note": "更新 " + "、".join(changed)})
|
||||
_save(root, st)
|
||||
print(f"[ok] 已更新:{'、'.join(changed) if changed else '(没有变化)'}")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_stdout_utf8()
|
||||
ap = argparse.ArgumentParser(prog="pipeline_state",
|
||||
description="paper-pipeline 进度管理(跨会话续跑)")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
i = sub.add_parser("init", help="建立新项目")
|
||||
i.add_argument("--dir", required=True)
|
||||
i.add_argument("--title", default="")
|
||||
i.add_argument("--direction", default="")
|
||||
i.add_argument("--type", default="", help="research article / review / ...")
|
||||
i.add_argument("--venue", default="")
|
||||
i.add_argument("--quartile", default="", help="如 Q2")
|
||||
i.add_argument("--length", default="", help="篇幅上限,如 8000 words")
|
||||
i.add_argument("--figures", default="", help="图表数量上限,如 8 figures / 6 tables")
|
||||
i.add_argument("--has-experiment", dest="has_experiment", default="",
|
||||
help="yes / no / simulation-only")
|
||||
i.add_argument("--authors", default="")
|
||||
i.add_argument("--mode", default="autopilot", choices=["autopilot", "checkpoint"])
|
||||
i.add_argument("--start", default="01", help="从第几步开始,默认 01")
|
||||
i.add_argument("--force", action="store_true")
|
||||
i.set_defaults(func=cmd_init)
|
||||
|
||||
for nm, fn, hlp in (("status", cmd_status, "显示完整进度"),
|
||||
("next", cmd_next, "只输出下一步")):
|
||||
p = sub.add_parser(nm, help=hlp)
|
||||
p.add_argument("--dir", required=True)
|
||||
p.set_defaults(func=fn)
|
||||
|
||||
ad = sub.add_parser("advance", help="标记某步完成并前进")
|
||||
ad.add_argument("--dir", required=True)
|
||||
ad.add_argument("--step", required=True)
|
||||
ad.add_argument("--artifacts", nargs="*", default=[])
|
||||
ad.set_defaults(func=cmd_advance)
|
||||
|
||||
g = sub.add_parser("gate", help="记录某步闸门结论")
|
||||
g.add_argument("--dir", required=True)
|
||||
g.add_argument("--step", required=True)
|
||||
g.add_argument("--pass", dest="passed", action="store_true")
|
||||
g.add_argument("--fail", dest="failed", action="store_true")
|
||||
g.add_argument("--note", default="")
|
||||
g.set_defaults(func=cmd_gate)
|
||||
|
||||
b = sub.add_parser("brief", help="补充/修改项目基本信息")
|
||||
b.add_argument("--dir", required=True)
|
||||
b.add_argument("--title")
|
||||
b.add_argument("--direction")
|
||||
b.add_argument("--type")
|
||||
b.add_argument("--venue")
|
||||
b.add_argument("--quartile")
|
||||
b.add_argument("--length")
|
||||
b.add_argument("--figures")
|
||||
b.add_argument("--has-experiment", dest="has_experiment")
|
||||
b.add_argument("--authors")
|
||||
b.add_argument("--mode", choices=["autopilot", "checkpoint"])
|
||||
b.set_defaults(func=cmd_brief)
|
||||
|
||||
a = ap.parse_args()
|
||||
return a.func(a)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,598 @@
|
||||
#!/usr/bin/env python3
|
||||
"""去 AI 痕迹自测 · anti-AI-trace scan (v2).
|
||||
|
||||
Measures the signatures that distinguish machine-written academic prose from
|
||||
human-written prose, then prints a concrete fix for each failure. Standard
|
||||
library only.
|
||||
|
||||
python prose_scan.py <file-or-folder> [...]
|
||||
python prose_scan.py manuscript/ --strict # final-pass mode (step 19)
|
||||
python prose_scan.py manuscript/ --json report.json
|
||||
|
||||
Exit code 0 = all gates pass, 1 = at least one gate failed.
|
||||
|
||||
Threshold calibration
|
||||
---------------------
|
||||
Every gate is calibrated so that a manuscript that has already passed a human
|
||||
reviewer audit does NOT fail. An earlier version of this script counted ordinary
|
||||
scientific connectives (therefore, thus, in particular, for example) as AI
|
||||
markers and reported 17 per 100 sentences on such a manuscript - all false
|
||||
positives. The lists below are deliberately narrow.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Gates. A metric is gated only when published evidence supports it AND it does
|
||||
# not fire on legitimate scientific prose. See references/deai_protocol.md §3.1
|
||||
# for the evidence grade of each feature.
|
||||
# --------------------------------------------------------------------------
|
||||
GATES = {
|
||||
# strongest single published signal (sentence-length uniformity)
|
||||
"sent_cv": (">", 0.40, "句子长度变异系数 (burstiness)"),
|
||||
"conn_rate": ("<", 2.0, "AI 式附加衔接词 (每 100 句)"),
|
||||
"rep_open": ("<=", 4, "同一句首最长重复次数"),
|
||||
"dup_sent": ("==", 0, "跨文件完全重复的整句"),
|
||||
"excess_vocab": ("<", 8.0, "LLM 高频词 (每 1000 词)"),
|
||||
"superficial_ing": ("<", 2.0, "句尾 -ing 附加评论 (每 100 段)"),
|
||||
"promo": ("<", 1.0, "宣传性词汇 (每 1000 词)"),
|
||||
"vague_attr": ("<", 1.5, "模糊归因 (每 100 段)"),
|
||||
"hedge_stack": ("==", 0, "叠加式模糊限定"),
|
||||
}
|
||||
|
||||
# Advisory: real signals, but a global threshold would misjudge them, because
|
||||
# the legitimate range depends on genre and on the target journal. Report the
|
||||
# number; compare it against a baseline built from the target journal
|
||||
# (deai_protocol.md §2), not against a fixed cut-off.
|
||||
ADVISORY = {
|
||||
# NOTE: paragraph-length uniformity has NO published effect size behind it
|
||||
# (the one quantitative comparison found was n=4/group, p=0.974). Varying
|
||||
# paragraph length is still good style - it is simply not evidence of AI.
|
||||
"para_cv": (">", 0.45, "段落长度变异系数(证据不足,仅参考)"),
|
||||
"rule3_rate": ("<", 2.0, "规则三连 (每 100 段)(无同行评审频次研究)"),
|
||||
"nominal_rate": ("<", 8.0, "名词化词尾 (每 100 词)"),
|
||||
"passive_rate": ("<", 45.0, "被动语态占比 (%)"),
|
||||
"conn_open": ("<", 12.0, "以衔接词开头的段落 (%)"),
|
||||
"neg_par": ("<", 1.0, "否定式平行结构 (每 100 段)"),
|
||||
}
|
||||
|
||||
# Reported with a number and NO verdict: genre- and length-dependent, or the
|
||||
# human range is so wide that any threshold would be arbitrary.
|
||||
INFORMATIONAL = [
|
||||
("em_dash_per_1000w", "破折号密度 (次/千词) [人类区间 0.33-17.12,不要一律清零]"),
|
||||
("msttr", "词汇多样性 MSTTR (1000 词窗口)"),
|
||||
("ttr", "裸 TTR(随篇幅下降,仅供同长度文本比较)"),
|
||||
("sent_mean", "句均长 (词)"),
|
||||
("sent_sd", "句长标准差 (词) [参考:AI 7.08 vs 人类 14.01,另一语料]"),
|
||||
("para_mean", "段落均长 (词)"),
|
||||
("en_dash", "en dash (–) 数量"),
|
||||
]
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Word lists
|
||||
# --------------------------------------------------------------------------
|
||||
# Additive, throat-clearing connectors that mark machine-written prose.
|
||||
# Ordinary academic connectives (therefore, thus, hence, in particular, for
|
||||
# example, as a result, on the other hand) are normal scientific English and
|
||||
# are deliberately NOT counted.
|
||||
CONNECTORS = [
|
||||
"moreover", "furthermore", "additionally", "in addition", "besides",
|
||||
"notably", "importantly", "it is worth noting", "it should be noted",
|
||||
"it is important to note", "in conclusion", "in summary", "overall",
|
||||
"significantly", "crucially", "interestingly",
|
||||
]
|
||||
|
||||
# Words statistically over-represented in LLM output. Drawn from the
|
||||
# excess-vocabulary literature - principally Kobak, Gonzalez-Marquez, Horvat &
|
||||
# Lause, "Delving into LLM-assisted writing in biomedical publications through
|
||||
# excess vocabulary", Science Advances 11(27):eadt3813 (2025), arXiv:2406.07016,
|
||||
# which analysed 14,448,711 PubMed abstracts; supplemented by Liang et al.
|
||||
# (arXiv:2404.01268) and by field observation.
|
||||
#
|
||||
# Evidence note: "leverage", "testament" and "robust" are widely repeated as
|
||||
# LLM markers but were NOT confirmed in either excess-vocabulary study. They are
|
||||
# kept because they are also generic filler words worth removing on their own
|
||||
# merits - but do not cite them as evidence of AI authorship.
|
||||
EXCESS_VOCAB = [
|
||||
"delve", "delves", "delving", "underscore", "underscores", "underscoring",
|
||||
"showcase", "showcases", "showcasing", "surpass", "surpasses", "surpassing",
|
||||
"intricate", "intricacies", "pivotal", "realm", "leverage", "leveraging",
|
||||
"meticulous", "meticulously", "testament", "boast", "boasts", "boasting",
|
||||
"garner", "garnered", "comprehend", "comprehending", "aligns", "aligning",
|
||||
"advancements", "exemplifies", "exemplify", "interplay", "nuanced",
|
||||
"pioneering", "profound", "seamlessly", "seamless", "vibrant", "encompass",
|
||||
"encompasses", "encompassing", "groundbreaking", "unparalleled",
|
||||
"multifaceted", "holistic", "synergy", "synergies", "myriad", "plethora",
|
||||
"utilize", "utilizing", "utilization", "endeavor", "paramount",
|
||||
"commendable", "tapestry", "beacon", "landscape of", "navigate",
|
||||
"navigating", "foster", "fostering", "facilitate", "facilitating",
|
||||
"crucial", "robustly", "notably", "importantly", "significantly",
|
||||
"cutting-edge", "state-of-the-art", "in today's", "ever-evolving",
|
||||
"rapidly evolving", "plays a vital role", "plays a crucial role",
|
||||
"sheds light", "shed light", "paves the way", "holds promise",
|
||||
"opens new avenues", "a growing body of", "it is worth noting",
|
||||
]
|
||||
|
||||
# Promotional / inflated language. Same source family; stricter than the list
|
||||
# above because these are unambiguously inappropriate in a research paper.
|
||||
PROMO = [
|
||||
"groundbreaking", "revolutionary", "game-changing", "game changer",
|
||||
"paradigm shift", "unprecedented", "world-class", "state-of-the-art",
|
||||
"cutting-edge", "breakthrough", "remarkable", "stunning", "exciting",
|
||||
"powerful", "elegant solution", "seamless", "effortless", "best-in-class",
|
||||
]
|
||||
|
||||
# Vague attribution - claims with no traceable source.
|
||||
VAGUE_ATTR = [
|
||||
"studies have shown", "research has shown", "researchers have found",
|
||||
"it is widely believed", "it is generally accepted", "many researchers",
|
||||
"several studies", "numerous studies", "some studies", "it has been reported",
|
||||
"experts agree", "it is well known", "it is commonly known",
|
||||
"there is a growing consensus", "evidence suggests",
|
||||
]
|
||||
|
||||
# Stacked hedges - two or more in one clause.
|
||||
HEDGES = ["may", "might", "could", "possibly", "potentially", "perhaps",
|
||||
"arguably", "presumably", "apparently", "somewhat", "rather",
|
||||
"fairly", "relatively", "seemingly", "likely", "probably"]
|
||||
|
||||
# Sentence-final "-ing" clause that adds commentary rather than content.
|
||||
SUPERFICIAL_ING = re.compile(
|
||||
r",\s+(?:thereby\s+|thus\s+)?(?:highlight|underscor|emphasiz|emphasiz|"
|
||||
r"demonstrat|illustrat|showcas|reflect|indicat|suggest|reveal|confirm|"
|
||||
r"pav|foster|facilitat|enabl|allow|provid)(?:ing|ing)\b[^.]{4,80}\.",
|
||||
re.I)
|
||||
|
||||
NEG_PAR = re.compile(
|
||||
r"\b(?:not only\b[^.]{0,80}\bbut also\b|it is not (?:just|merely|only)\b"
|
||||
r"[^.]{0,80}\bit is\b|rather than (?:merely|just|simply)\b)", re.I)
|
||||
|
||||
RULE3 = re.compile(
|
||||
r"\b([\w\-]+(?:\s+[\w\-]+){0,3}),\s+([\w\-]+(?:\s+[\w\-]+){0,3}),?\s+and\s+"
|
||||
r"([\w\-]+(?:\s+[\w\-]+){0,3})\b")
|
||||
|
||||
NOMINAL = re.compile(
|
||||
r"\b\w{5,}(?:tion|sion|ment|ance|ence|ency|ancy|ility|ness|ization|isation)\b",
|
||||
re.I)
|
||||
|
||||
PASSIVE = re.compile(
|
||||
r"\b(?:is|are|was|were|be|been|being|has been|have been|had been)\s+"
|
||||
r"(?:\w+ly\s+)?(\w+(?:ed|en))\b", re.I)
|
||||
|
||||
RE_HEAD = re.compile(r"^\s{0,3}#{1,6}\s")
|
||||
RE_TABLE = re.compile(r"^\s*\|")
|
||||
RE_CODE = re.compile(r"^\s*```")
|
||||
RE_FIG = re.compile(r"^\s*(图|表|Figure|Table|Fig\.)\s*\d")
|
||||
RE_EQ = re.compile(r"^\s*\$\$|^\s*\\\[|^\s*=+\s*$")
|
||||
CJK = re.compile(r"[\u4e00-\u9fff]")
|
||||
LIST_ITEM = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s")
|
||||
|
||||
|
||||
def _stdout_utf8() -> None:
|
||||
for s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
s.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def load(paths: list[str]) -> dict[str, str]:
|
||||
files: dict[str, str] = {}
|
||||
for p in paths:
|
||||
if os.path.isdir(p):
|
||||
for dirpath, _dirs, names in os.walk(p):
|
||||
for n in sorted(names):
|
||||
if n.lower().endswith((".md", ".txt", ".markdown")):
|
||||
fp = os.path.join(dirpath, n)
|
||||
with io.open(fp, encoding="utf-8", errors="replace") as fh:
|
||||
files[fp] = fh.read()
|
||||
elif os.path.isfile(p):
|
||||
with io.open(p, encoding="utf-8", errors="replace") as fh:
|
||||
files[p] = fh.read()
|
||||
else:
|
||||
print(f"[warn] 找不到 {p}", file=sys.stderr)
|
||||
return files
|
||||
|
||||
|
||||
def prose_only(text: str) -> list[str]:
|
||||
out, in_code = [], False
|
||||
for raw in text.splitlines():
|
||||
line = raw.rstrip()
|
||||
if RE_CODE.match(line):
|
||||
in_code = not in_code
|
||||
continue
|
||||
if in_code:
|
||||
continue
|
||||
if (not line.strip() or RE_HEAD.match(line) or RE_TABLE.match(line)
|
||||
or RE_FIG.match(line) or RE_EQ.match(line) or LIST_ITEM.match(line)):
|
||||
out.append("")
|
||||
continue
|
||||
out.append(line)
|
||||
return out
|
||||
|
||||
|
||||
def paragraphs(lines: list[str]) -> list[str]:
|
||||
paras, cur = [], []
|
||||
for line in lines:
|
||||
if line.strip():
|
||||
cur.append(line.strip())
|
||||
elif cur:
|
||||
paras.append(" ".join(cur))
|
||||
cur = []
|
||||
if cur:
|
||||
paras.append(" ".join(cur))
|
||||
return [p for p in paras if len(p) > 40]
|
||||
|
||||
|
||||
def sentences(paras: list[str]) -> list[str]:
|
||||
out = []
|
||||
for p in paras:
|
||||
for s in re.split(r"(?<=[。!?;!?;])\s*|(?<=[.])\s+(?=[A-Z(])", p):
|
||||
s = s.strip()
|
||||
if len(s) > 15:
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
|
||||
def length(s: str) -> int:
|
||||
if len(CJK.findall(s)) > len(s) * 0.25:
|
||||
return len(CJK.findall(s))
|
||||
return len(re.findall(r"[A-Za-z0-9][A-Za-z0-9'\-]*", s))
|
||||
|
||||
|
||||
def words(text: str) -> list[str]:
|
||||
return re.findall(r"[A-Za-z][A-Za-z'\-]*", text.lower())
|
||||
|
||||
|
||||
def cv(vals: list[int]) -> float:
|
||||
if len(vals) < 3:
|
||||
return 0.0
|
||||
m = statistics.fmean(vals)
|
||||
return statistics.pstdev(vals) / m if m else 0.0
|
||||
|
||||
|
||||
def _count_phrases(low: str, phrases: list[str]) -> tuple[int, dict[str, int]]:
|
||||
hits = {}
|
||||
total = 0
|
||||
for ph in phrases:
|
||||
n = low.count(ph)
|
||||
if n:
|
||||
hits[ph] = n
|
||||
total += n
|
||||
return total, hits
|
||||
|
||||
|
||||
def analyse(files: dict[str, str]) -> dict:
|
||||
all_paras, all_sents, per_file = [], [], {}
|
||||
for path, text in files.items():
|
||||
ps = paragraphs(prose_only(text))
|
||||
ss = sentences(ps)
|
||||
per_file[os.path.basename(path)] = {
|
||||
"paragraphs": len(ps), "sentences": len(ss),
|
||||
"words": sum(length(p) for p in ps)}
|
||||
all_paras += ps
|
||||
all_sents += ss
|
||||
|
||||
body = "\n".join(all_paras)
|
||||
low = body.lower()
|
||||
n_words = max(1, len(words(body)))
|
||||
n_paras = max(1, len(all_paras))
|
||||
n_sents = max(1, len(all_sents))
|
||||
|
||||
em = body.count("\u2014")
|
||||
|
||||
r3 = sum(1 for s in all_sents if RULE3.search(s))
|
||||
conn, conn_hits = _count_phrases(low, CONNECTORS)
|
||||
exc, exc_hits = _count_phrases(low, EXCESS_VOCAB)
|
||||
promo, promo_hits = _count_phrases(low, PROMO)
|
||||
vague, vague_hits = _count_phrases(low, VAGUE_ATTR)
|
||||
ing = len(SUPERFICIAL_ING.findall(body))
|
||||
negp = len(NEG_PAR.findall(body))
|
||||
nominal = len(NOMINAL.findall(body))
|
||||
passive = len(PASSIVE.findall(body))
|
||||
|
||||
hedge_stack = 0
|
||||
hedge_examples = []
|
||||
for s in all_sents:
|
||||
sl = s.lower()
|
||||
present = [h for h in HEDGES
|
||||
if re.search(rf"\b{re.escape(h)}\b", sl)]
|
||||
if len(present) >= 3:
|
||||
hedge_stack += 1
|
||||
if len(hedge_examples) < 5:
|
||||
hedge_examples.append((s[:110], present))
|
||||
|
||||
opens: dict[str, int] = {}
|
||||
for s in all_sents:
|
||||
k = " ".join(s.split()[:3]) if not CJK.search(s) else s[:6]
|
||||
opens[k] = opens.get(k, 0) + 1
|
||||
top_open = max(opens.items(), key=lambda kv: kv[1]) if opens else ("", 0)
|
||||
|
||||
conn_open = sum(1 for p in all_paras
|
||||
if any(p.lower().lstrip().startswith(c) for c in CONNECTORS))
|
||||
conn_open_pct = 100.0 * conn_open / n_paras
|
||||
|
||||
wl = words(body)
|
||||
ttr = (len(set(wl)) / len(wl)) if wl else 0.0
|
||||
# Plain TTR falls as a text grows, so it is not comparable across papers.
|
||||
# MSTTR (mean segmental TTR over 1000-word windows) is length-robust and is
|
||||
# the number to quote.
|
||||
win = 1000
|
||||
if len(wl) >= win:
|
||||
segs = [wl[i:i + win] for i in range(0, len(wl) - win + 1, win)]
|
||||
msttr = statistics.fmean(len(set(s)) / win for s in segs)
|
||||
else:
|
||||
msttr = ttr
|
||||
|
||||
seen: dict[str, str] = {}
|
||||
dups: list[dict] = []
|
||||
for path, text in files.items():
|
||||
for s in sentences(paragraphs(prose_only(text))):
|
||||
key = re.sub(r"\s+", " ", s.strip().lower())
|
||||
if len(key) < 60:
|
||||
continue
|
||||
if key in seen and seen[key] != path:
|
||||
dups.append({"sentence": s.strip()[:120],
|
||||
"in": [os.path.basename(seen[key]),
|
||||
os.path.basename(path)]})
|
||||
else:
|
||||
seen.setdefault(key, path)
|
||||
|
||||
sents_sorted = sorted(all_sents, key=len, reverse=True)
|
||||
sent_lens = [length(s) for s in all_sents]
|
||||
metrics = {
|
||||
"files": len(files),
|
||||
"paragraphs": len(all_paras),
|
||||
"sentences": len(all_sents),
|
||||
"words": n_words,
|
||||
"para_cv": round(cv([length(p) for p in all_paras]), 3),
|
||||
"sent_cv": round(cv(sent_lens), 3),
|
||||
"sent_sd": round(statistics.pstdev(sent_lens), 2) if len(sent_lens) > 2 else 0.0,
|
||||
"para_mean": round(statistics.fmean([length(p) for p in all_paras]), 1) if all_paras else 0,
|
||||
"sent_mean": round(statistics.fmean(sent_lens), 1) if sent_lens else 0,
|
||||
"em_dash": em,
|
||||
"em_dash_per_1000w": round(1000.0 * em / n_words, 2),
|
||||
"en_dash": body.count("\u2013"),
|
||||
"rule3_count": r3,
|
||||
"rule3_rate": round(100.0 * r3 / n_paras, 2),
|
||||
"connector_count": conn,
|
||||
"connector_rate": round(100.0 * conn / n_sents, 2),
|
||||
"connector_hits": conn_hits,
|
||||
"excess_vocab_count": exc,
|
||||
"excess_vocab": round(1000.0 * exc / n_words, 2),
|
||||
"excess_hits": dict(sorted(exc_hits.items(), key=lambda kv: -kv[1])[:20]),
|
||||
"promo_count": promo,
|
||||
"promo": round(1000.0 * promo / n_words, 2),
|
||||
"promo_hits": promo_hits,
|
||||
"vague_attr_count": vague,
|
||||
"vague_attr": round(100.0 * vague / n_paras, 2),
|
||||
"vague_hits": vague_hits,
|
||||
"superficial_ing_count": ing,
|
||||
"superficial_ing": round(100.0 * ing / n_paras, 2),
|
||||
"hedge_stack_count": hedge_stack,
|
||||
"hedge_stack": hedge_stack,
|
||||
"hedge_examples": hedge_examples,
|
||||
"negative_parallelism": negp,
|
||||
"neg_par": round(100.0 * negp / n_paras, 2),
|
||||
"nominal_count": nominal,
|
||||
"nominal_rate": round(100.0 * nominal / n_words, 2),
|
||||
"passive_count": passive,
|
||||
"passive_rate": round(100.0 * passive / max(1, len(all_sents)), 2),
|
||||
"conn_open_pct": round(conn_open_pct, 2),
|
||||
"conn_open": round(conn_open_pct, 2),
|
||||
"ttr": round(ttr, 3),
|
||||
"msttr": round(msttr, 3),
|
||||
"repeat_opening_max": top_open[1],
|
||||
"repeat_opening_key": top_open[0],
|
||||
"dup_sentences": len(dups),
|
||||
"dup_examples": dups[:5],
|
||||
"longest_sentence": sents_sorted[0][:160] if sents_sorted else "",
|
||||
"per_file": per_file,
|
||||
}
|
||||
return metrics
|
||||
|
||||
|
||||
def _test(v, op: str, thr) -> bool:
|
||||
if op == ">":
|
||||
return v > thr
|
||||
if op == "<":
|
||||
return v < thr
|
||||
if op == "==":
|
||||
return v == thr
|
||||
return v <= thr
|
||||
|
||||
|
||||
# Gate key -> metric key, where the two names differ. Anything not listed here
|
||||
# must appear in the metrics dict under its own name; _rows() refuses to run
|
||||
# otherwise, so a typo can never silently report 0 (which would read as PASS).
|
||||
ALIAS = {
|
||||
"conn_rate": "connector_rate",
|
||||
"rep_open": "repeat_opening_max",
|
||||
"dup_sent": "dup_sentences",
|
||||
}
|
||||
|
||||
|
||||
def _rows(m: dict, table: dict, attr: str) -> list[tuple]:
|
||||
out = []
|
||||
for key, (op, thr, label) in table.items():
|
||||
mk = ALIAS.get(key, key)
|
||||
if mk not in m:
|
||||
raise KeyError(
|
||||
f"gate '{key}' maps to metric '{mk}', which analyse() does not "
|
||||
f"produce - fix the name rather than letting it read as 0/PASS")
|
||||
v = m[mk]
|
||||
out.append((key, f"{v} {'>' if op == '>' else '<' if op == '<' else '=='} {thr}",
|
||||
label, _test(v, op, thr)))
|
||||
return out
|
||||
|
||||
|
||||
FIXES = {
|
||||
"para_cv": "把长段拆开、把相邻短段合并,让段落长短交错",
|
||||
"sent_cv": "长句断成短句;偶尔用短判断句独立成段",
|
||||
"em_dash": "断句,不要用破折号串联(A——也就是 B——导致 C 改成两句话)",
|
||||
"conn_rate": "直接删掉 moreover / furthermore / additionally 这类词,让句子自己承接",
|
||||
"rep_open": "换主语或换语序;同一句式不要连续三段都用",
|
||||
"dup_sent": "讨论里的重复句改写或删除;跨节不要复制粘贴整句",
|
||||
"excess_vocab": "换成领域内的具体动词或名词(delve into → 直接说「测量/推导/比较」)",
|
||||
"superficial_ing": "把句尾 -ing 评论改成独立事实句,或直接删(它通常没带来新信息)",
|
||||
"promo": "删掉宣传腔;把 groundbreaking 换成具体的量(提升了多少、在什么条件下)",
|
||||
"vague_attr": "替换成具体引用(作者+年份+文献号),查不到就删掉这句话",
|
||||
"hedge_stack": "一句话里最多留一个限定词;may potentially 之类直接删一个",
|
||||
"rule3_rate": "删掉最弱一项留两项,或拆成两句各说一件事",
|
||||
"nominal_rate": "把 -tion/-ment 名词化还原成动词(perform an evaluation of → evaluate)",
|
||||
"passive_rate": "方法可保留被动,结果与讨论改主动",
|
||||
"conn_open": "段落不要用衔接词开头;用上一段的内容做主语",
|
||||
"ttr": "换掉重复用词,用同义的专业表达",
|
||||
"neg_par": "「不是 X 而是 Y」这种结构连用会像模板,改成直接陈述 Y",
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_stdout_utf8()
|
||||
ap = argparse.ArgumentParser(prog="prose_scan")
|
||||
ap.add_argument("paths", nargs="+")
|
||||
ap.add_argument("--json", dest="json_out", default="")
|
||||
ap.add_argument("--strict", action="store_true",
|
||||
help="终稿模式:额外把参考项也当作提醒重点列出")
|
||||
ap.add_argument("--top", type=int, default=20, help="列出前 N 个高频 AI 词")
|
||||
ap.add_argument("--baseline", default="",
|
||||
help="目标期刊基线 JSON(由本脚本对期刊文章跑一次得到),"
|
||||
"给出后会把本稿与之对照")
|
||||
ap.add_argument("--save-baseline", action="store_true",
|
||||
help="把本次结果存成基线(对期刊文章目录跑时用)")
|
||||
a = ap.parse_args()
|
||||
|
||||
files = load(a.paths)
|
||||
if not files:
|
||||
print("[fail] 没有可读的 .md/.txt 文件", file=sys.stderr)
|
||||
return 1
|
||||
m = analyse(files)
|
||||
rows = _rows(m, GATES, "gates")
|
||||
adv = _rows(m, ADVISORY, "advisory")
|
||||
failed = [r[0] for r in rows if not r[3]]
|
||||
|
||||
print("去 AI 痕迹自测" + ("(终稿模式)" if a.strict else ""))
|
||||
print()
|
||||
print(f"文件 {m['files']} 个 · 段 {m['paragraphs']} · 句 {m['sentences']} · 词 {m['words']}")
|
||||
print(f"段落均长 {m['para_mean']} 词 · 句均长 {m['sent_mean']} 词\n")
|
||||
|
||||
print("## 判定项")
|
||||
print()
|
||||
print("| 指标 | 实测 | 门槛 | 结果 |")
|
||||
print("|---|---|---|---|")
|
||||
for _k, val, label, ok in rows:
|
||||
print(f"| {label} | {val} | {'PASS' if ok else '**FAIL**'} |")
|
||||
print()
|
||||
|
||||
print("## 参考项(不计入判定,但终稿值得看一眼)")
|
||||
print()
|
||||
print("| 指标 | 实测 | 参考门槛 | 状态 |")
|
||||
print("|---|---|---|---|")
|
||||
for _k, val, label, ok in adv:
|
||||
print(f"| {label} | {val} | {'OK' if ok else '偏高'} |")
|
||||
print()
|
||||
|
||||
print("## 观察项(只报数,不判定——随文体与篇幅变化,和自己以前的稿子比)")
|
||||
print()
|
||||
for k, label in INFORMATIONAL:
|
||||
print(f" {label}:{m.get(k, 'n/a')}")
|
||||
print()
|
||||
|
||||
if m["excess_hits"]:
|
||||
print(f"## LLM 高频词命中(共 {m['excess_vocab_count']} 次)")
|
||||
print()
|
||||
for w, n in list(m["excess_hits"].items())[:a.top]:
|
||||
print(f" {w} ×{n}")
|
||||
print()
|
||||
if m["promo_hits"]:
|
||||
print(f"## 宣传性词汇(共 {m['promo_count']} 次)")
|
||||
print()
|
||||
for w, n in m["promo_hits"].items():
|
||||
print(f" {w} ×{n}")
|
||||
print()
|
||||
if m["vague_hits"]:
|
||||
print(f"## 模糊归因(共 {m['vague_attr_count']} 次)")
|
||||
print()
|
||||
for w, n in m["vague_hits"].items():
|
||||
print(f" {w} ×{n}")
|
||||
print()
|
||||
if m["hedge_examples"]:
|
||||
print(f"## 叠加式模糊限定({m['hedge_stack_count']} 处)")
|
||||
print()
|
||||
for s, hs in m["hedge_examples"]:
|
||||
print(f" [{'+'.join(hs)}] {s}")
|
||||
print()
|
||||
if m["dup_examples"]:
|
||||
print("## 跨文件重复整句")
|
||||
print()
|
||||
for d in m["dup_examples"]:
|
||||
print(f" {d['in'][0]} ↔ {d['in'][1]}:{d['sentence']}")
|
||||
print()
|
||||
|
||||
print(f"最高频句首:「{m['repeat_opening_key']}」×{m['repeat_opening_max']}")
|
||||
print(f"以衔接词开头的段落:{m['conn_open_pct']}% · 被动语态:{m['passive_rate']}%")
|
||||
print()
|
||||
|
||||
if a.baseline:
|
||||
try:
|
||||
with io.open(a.baseline, encoding="utf-8") as fh:
|
||||
base = json.load(fh)
|
||||
keys = [k for k in ("sent_cv", "para_cv", "sent_mean", "sent_sd",
|
||||
"connector_rate", "em_dash_per_1000w", "msttr",
|
||||
"passive_rate", "nominal_rate", "ttr")]
|
||||
print(f"## 与期刊基线对照({os.path.basename(a.baseline)})")
|
||||
print()
|
||||
print("| 指标 | 本稿 | 期刊基线 | 偏离 |")
|
||||
print("|---|---|---|---|")
|
||||
for k in keys:
|
||||
if k not in base:
|
||||
continue
|
||||
b, v = base[k], m.get(k)
|
||||
if not isinstance(b, (int, float)) or not isinstance(v, (int, float)):
|
||||
continue
|
||||
if b == 0:
|
||||
dev = "n/a"
|
||||
else:
|
||||
pct = 100.0 * (v - b) / b
|
||||
dev = f"{pct:+.1f}%"
|
||||
if abs(pct) > 50:
|
||||
dev += " ← 明显偏离"
|
||||
print(f"| {k} | {v} | {b} | {dev} |")
|
||||
print()
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[warn] 读不到基线文件 {a.baseline}:{type(e).__name__}: {e}\n")
|
||||
|
||||
if failed:
|
||||
print("## 要改的地方(按这个动作改,不要只写「再润色一遍」)")
|
||||
print()
|
||||
for k in failed:
|
||||
print(f" - **{dict((r[0], r[2]) for r in rows)[k]}** → {FIXES.get(k, '')}")
|
||||
print()
|
||||
print(f"结果:{'全部通过' if not failed else '未通过 → ' + ', '.join(failed)}")
|
||||
|
||||
if a.json_out or a.save_baseline:
|
||||
m["gates"] = [{"key": k, "value": v, "label": l, "pass": ok}
|
||||
for k, v, l, ok in rows]
|
||||
m["advisory"] = [{"key": k, "value": v, "label": l, "ok": ok}
|
||||
for k, v, l, ok in adv]
|
||||
m["failed"] = failed
|
||||
m["all_pass"] = not failed
|
||||
target = a.json_out or "journal_baseline.json"
|
||||
with io.open(target, "w", encoding="utf-8") as fh:
|
||||
json.dump(m, fh, ensure_ascii=False, indent=1)
|
||||
print(f"[ok] {'期刊基线' if a.save_baseline else 'JSON 报告'}:{target}")
|
||||
if a.save_baseline:
|
||||
print(f" 用它对照自己的稿子:--baseline {target}")
|
||||
|
||||
return 0 if not failed else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,252 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""建立中文论文项目骨架(thesis-pipeline 第 1 步)
|
||||
|
||||
生成 22 个阶段目录 + 分章 md 模板 + refs.csv 模板 + thesis.json 排版配置。
|
||||
|
||||
用法:
|
||||
python scaffold.py --dir D:\\论文\\我的课题 --title "论文题目" --type 本科
|
||||
python scaffold.py --dir . --title "XXX" --type 硕士 --mode sci
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
STAGES = [
|
||||
"00_总控进度判断", "01_项目初始化", "02_检索式生成", "03_检索与导出",
|
||||
"04_选题与空白识别", "05_对标库深度学习", "06_文献筛选分类",
|
||||
"07_导入引用库取全文", "08_文献精读", "09_论文框架搭建",
|
||||
"10_图表制作与引用", "11_摘要与引言", "12_方法与结果", "13_讨论与结论",
|
||||
"14_目标期刊选择", "15_目标期刊格式学习", "16_润色与语言打磨",
|
||||
"17_图片版权", "18_Cover Letter", "19_终稿去 AI 痕迹与合规声明",
|
||||
"20_投稿前总检", "21_返修与回复",
|
||||
]
|
||||
|
||||
EXTRA = ["code", "data", "figures", "manuscript", "deliverables", "refs"]
|
||||
|
||||
# 按论文类型给字数与章节建议
|
||||
PROFILES = {
|
||||
"本科": dict(words=20000, chapters=5, abstract_cn=600, refs=40),
|
||||
"硕士": dict(words=35000, chapters=6, abstract_cn=800, refs=60),
|
||||
"博士": dict(words=60000, chapters=7, abstract_cn=1000, refs=100),
|
||||
"课程": dict(words=8000, chapters=4, abstract_cn=300, refs=15),
|
||||
"期刊": dict(words=12000, chapters=5, abstract_cn=300, refs=40), # SCI 模式另走 paper-pipeline
|
||||
}
|
||||
|
||||
THESIS_JSON = {
|
||||
"schema": "thesis-pipeline/1.0",
|
||||
"type": "本科",
|
||||
"title": "",
|
||||
"language": "zh-CN",
|
||||
"author": {"name": "〔待填:姓名〕", "sid": "〔待填:学号〕", "major": "〔待填:专业〕",
|
||||
"advisor": "〔待填:导师姓名/职称〕", "school": "〔待填:学院名称〕",
|
||||
"date": "〔待填:年 月 日〕"},
|
||||
"page": {"size": "A4", "margin_top_cm": 2.54, "margin_bottom_cm": 2.54,
|
||||
"margin_left_cm": 2.8, "margin_right_cm": 2.8},
|
||||
"fonts": {"body_cn": "宋体", "body_latin": "Times New Roman", "heading_cn": "黑体",
|
||||
"code_latin": "Consolas"},
|
||||
"sizes": {"body_pt": 12, "h1_pt": 16, "h2_pt": 14, "h3_pt": 12,
|
||||
"caption_pt": 10.5, "ref_pt": 10.5, "formula_pt": 11.5},
|
||||
"line_spacing_pt": 22,
|
||||
"first_line_indent_chars": 2,
|
||||
"figure_width_cm": 15.2,
|
||||
"manuscript_order": [
|
||||
"part0_摘要与目录.md", "part1_绪论.md", "part2_理论基础与模型.md",
|
||||
"part3_研究设计.md", "part4_结果与分析.md", "part5_结论展望与附录.md"
|
||||
],
|
||||
"reference_style": "GB/T 7714-2015 顺序编码制",
|
||||
"notes": [
|
||||
"本文件控制 Word/PDF 排版;学校模板到手后按模板改这里,不要改脚本。",
|
||||
"md 是唯一真源,docx/pdf 由 build_docx.py 生成,禁止反向编辑。"
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="建立中文论文项目骨架")
|
||||
ap.add_argument("--dir", required=True, help="项目目录(不存在则创建)")
|
||||
ap.add_argument("--title", required=True, help="论文题目")
|
||||
ap.add_argument("--type", default="本科", choices=list(PROFILES),
|
||||
help="论文类型,决定字数与章节数建议")
|
||||
ap.add_argument("--mode", default="thesis", choices=["thesis", "sci"],
|
||||
help="thesis=中文学位论文(本技能);sci=英文期刊(转 paper-pipeline)")
|
||||
ap.add_argument("--force", action="store_true", help="目录非空时仍继续")
|
||||
args = ap.parse_args()
|
||||
|
||||
root = Path(args.dir).resolve()
|
||||
if root.exists() and any(root.iterdir()) and not args.force:
|
||||
print(f"目录非空:{root}\n如需继续请加 --force(不会覆盖已存在的文件)")
|
||||
return 1
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
made = 0
|
||||
for d in STAGES + EXTRA:
|
||||
(root / d).mkdir(exist_ok=True)
|
||||
made += 1
|
||||
|
||||
prof = PROFILES[args.type]
|
||||
|
||||
# thesis.json
|
||||
cfg = json.loads(json.dumps(THESIS_JSON))
|
||||
cfg["type"] = args.type
|
||||
cfg["title"] = args.title
|
||||
cfg["mode"] = args.mode
|
||||
cfg["targets"] = prof
|
||||
cfg["created_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
(root / "thesis.json").write_text(
|
||||
json.dumps(cfg, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
|
||||
# 分章 md 模板(只补不覆盖)
|
||||
templates = {
|
||||
"part0_摘要与目录.md": f"""## 摘要
|
||||
|
||||
(写 300–500 字:研究对象、方法、主要结果 3–4 条、结论一句话。最后一段必须写明研究的范围与局限。)
|
||||
|
||||
**关键词**:关键词1;关键词2;关键词3;关键词4;关键词5
|
||||
|
||||
---
|
||||
|
||||
## Abstract
|
||||
|
||||
(与中文摘要对应,150–250 词。)
|
||||
|
||||
**Keywords**: keyword1; keyword2; keyword3; keyword4; keyword5
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
(用 `python scripts/final_check.py --dir .` 会提示缺失章节;目录可手写或由脚本生成。)
|
||||
""",
|
||||
"part1_绪论.md": f"""## 第 1 章 绪论
|
||||
|
||||
### 1.1 研究背景与意义
|
||||
|
||||
(说明领域现状、为什么做这个题。每个论断挂真实文献引用,如 [1]。)
|
||||
|
||||
### 1.2 国内外研究现状
|
||||
|
||||
(按主题分子节,不要按时间流水账。引用必须真实。)
|
||||
|
||||
### 1.3 现有研究的不足
|
||||
|
||||
(3 条以内,每条对应 1.4 节的一个研究内容。)
|
||||
|
||||
### 1.4 本文研究内容与技术路线
|
||||
|
||||
(列出研究内容,配技术路线图 图 1-1。)
|
||||
""",
|
||||
"part2_理论基础与模型.md": """## 第 2 章 理论基础与模型
|
||||
|
||||
(理论推导与模型假设。公式按标准 LaTeX 语法书写并编号;build_docx.py 会自动转成可读文本。)
|
||||
|
||||
### 2.1 理论基础
|
||||
### 2.2 模型假设
|
||||
### 2.3 控制方程
|
||||
""",
|
||||
"part3_研究设计.md": """## 第 3 章 研究设计
|
||||
|
||||
### 3.1 研究对象与参数
|
||||
|
||||
**表 3-1 参数设置**
|
||||
|
||||
| 参数 | 符号 | 取值 | 单位 | 依据 |
|
||||
|---|---|---|---|---|
|
||||
| | | | | |
|
||||
|
||||
### 3.2 方法
|
||||
### 3.3 数据分析方法
|
||||
### 3.4 可复现性说明
|
||||
|
||||
(数据由哪个脚本生成、随机种子、文件哈希。)
|
||||
""",
|
||||
"part4_结果与分析.md": """## 第 4 章 结果与分析
|
||||
|
||||
### 4.1 结果一
|
||||
|
||||
(图用 `` 插入,图题单独一行写成 `**图 4-1 标题**`。)
|
||||
|
||||
### 4.2 结果二
|
||||
### 4.3 讨论
|
||||
""",
|
||||
"part5_结论展望与附录.md": """## 第 5 章 结论与展望
|
||||
|
||||
### 5.1 主要结论
|
||||
|
||||
(逐条对应第 4 章的结果,不要出现第 4 章没有的结论。)
|
||||
|
||||
### 5.2 研究局限
|
||||
|
||||
(**第一条必须是最根本的局限**,不要放在最后轻描淡写。)
|
||||
|
||||
### 5.3 后续工作展望
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
(务必如实说明 AI 使用情况。)
|
||||
|
||||
---
|
||||
|
||||
## 附录 A 核心代码
|
||||
|
||||
## 附录 B 数据文件清单与复现方式
|
||||
""",
|
||||
}
|
||||
for name, body in templates.items():
|
||||
p = root / "manuscript" / name
|
||||
if not p.exists():
|
||||
p.write_text(body, encoding="utf-8", newline="\n")
|
||||
|
||||
# refs.csv 模板
|
||||
rc = root / "refs.csv"
|
||||
if not rc.exists():
|
||||
rc.write_text(
|
||||
"id,作者,年份,标题,期刊,DOI,类型,主题分类,是否核心,备注\n"
|
||||
'L001,"Smith J; Doe A",2024,"Paper title here","Journal Name",'
|
||||
'10.xxxx/xxxxx,journal,主题,是,"DOI 已经 Crossref 核实"\n',
|
||||
encoding="utf-8-sig")
|
||||
|
||||
# PIPELINE.md 起头
|
||||
pl = root / "PIPELINE.md"
|
||||
if not pl.exists():
|
||||
pl.write_text(
|
||||
f"""# 流水线进度 · {args.title}
|
||||
|
||||
- **类型**:{args.type} **模式**:{"中文学位论文" if args.mode == "thesis" else "SCI 英文期刊"}
|
||||
- **字数目标**:{prof['words']} **参考文献目标**:{prof['refs']}
|
||||
- **创建**:{cfg['created_at']}
|
||||
|
||||
进度表由 paper-pipeline 的 autopilot.py 维护;本文件可手工补充说明。
|
||||
|
||||
## 下一步
|
||||
|
||||
1. `python ~/.dsh/skills/paper-pipeline/scripts/autopilot.py start --dir . --direction "{args.title}"`
|
||||
2. 填 `refs.csv` 与 `manuscript/`,用 `scripts/build_refs.py` 生成编号
|
||||
3. 跑 `scripts/final_check.py --dir .` 直到全绿再交付
|
||||
""", encoding="utf-8")
|
||||
|
||||
print(f"已建立项目骨架:{root}")
|
||||
print(f" 目录 {made} 个 | 分章模板 {len(templates)} 个 | thesis.json / refs.csv / PIPELINE.md")
|
||||
print(f" 字数目标 {prof['words']},参考文章节数建议 {prof['chapters']}")
|
||||
print()
|
||||
print("提示:排版参数在 thesis.json,学校模板到手后改那里,不要改脚本。")
|
||||
if args.mode == "sci":
|
||||
print("注意:SCI 模式请改用 paper-pipeline 技能(它面向英文期刊全流程)。")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,419 @@
|
||||
#!/usr/bin/env python3
|
||||
"""selfcheck — audit a paper project for the things that make a manuscript unsafe.
|
||||
|
||||
`autopilot.py check` only verifies that each step produced its files. This goes
|
||||
further and looks at the *content*: leftover placeholders, numbers that appear
|
||||
in the prose but nowhere in the data, figures cited but not drawn, references
|
||||
cited but not listed, undisclosed degraded steps, and the de-AI gates.
|
||||
|
||||
python selfcheck.py --dir <project folder>
|
||||
python selfcheck.py --dir <project folder> --json report.json
|
||||
|
||||
Exit 0 = no blocking problem found. Exit 1 = at least one blocking problem.
|
||||
Standard library only plus the sibling prose_scan.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# Text that means somebody left the work unfinished.
|
||||
PLACEHOLDERS = [
|
||||
"TODO", "TBD", "FIXME", "XXX", "PLACEHOLDER", "待补", "待填", "占位",
|
||||
"此处", "lorem ipsum", "[insert", "<insert", "待确认", "未完成",
|
||||
]
|
||||
# These appear legitimately in the author field of an unpublished draft. In
|
||||
# BRIEF.md they are a warning (the pipeline itself scaffolds an author
|
||||
# placeholder); anywhere else they are still blocking.
|
||||
PLACEHOLDER_SOFT = {"占位", "待确认", "placeholder", "PLACEHOLDER"}
|
||||
|
||||
NUM_RE = re.compile(r"(?<![\w.])(\d+(?:\.\d+)?)(?:\s*%)?")
|
||||
FIG_CITE = re.compile(r"\b(?:Fig(?:ure)?\.?|图)\s*(\d+)", re.I)
|
||||
TAB_CITE = re.compile(r"\b(?:Tab(?:le)?\.?|表)\s*(\d+)", re.I)
|
||||
REF_CITE = re.compile(r"\[(\d+(?:\s*[,\u2013-]\s*\d+)*)\]")
|
||||
REF_ENTRY = re.compile(r"^\s*\[?(\d+)\]?[.)]?\s+\S", re.M)
|
||||
|
||||
|
||||
def _utf8() -> None:
|
||||
for s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
s.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def read(p: str) -> str:
|
||||
try:
|
||||
with io.open(p, encoding="utf-8", errors="replace") as fh:
|
||||
return fh.read()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def walk(root: str, exts=(".md", ".txt", ".csv", ".json")) -> list[str]:
|
||||
out = []
|
||||
for dp, dn, fn in os.walk(root):
|
||||
dn[:] = [d for d in dn if d not in ("__pycache__", ".git")]
|
||||
for f in fn:
|
||||
if f.lower().endswith(exts):
|
||||
out.append(os.path.join(dp, f))
|
||||
return out
|
||||
|
||||
|
||||
GENERATED = {"SELFCHECK.md", "PIPELINE.md", "DECISIONS.md",
|
||||
"PAPER_STATE.json", "_selfcheck_deai.json"}
|
||||
|
||||
|
||||
def collect_numbers(text: str) -> set[str]:
|
||||
"""Numeric tokens in the prose, normalised.
|
||||
|
||||
Figure numbers, table numbers and reference indices are stripped first:
|
||||
'Figure 5' and '[12]' are cross-references, not measurements, and counting
|
||||
them would bury the real findings under false positives.
|
||||
"""
|
||||
text = FIG_CITE.sub(" ", text)
|
||||
text = TAB_CITE.sub(" ", text)
|
||||
text = REF_CITE.sub(" ", text)
|
||||
out = set()
|
||||
for m in NUM_RE.finditer(text):
|
||||
tok = m.group(1)
|
||||
try:
|
||||
v = float(tok)
|
||||
except ValueError:
|
||||
continue
|
||||
if v < 3: # 0/1/2 are almost always enumeration
|
||||
continue
|
||||
if 1900 <= v <= 2100 and "." not in tok: # years
|
||||
continue
|
||||
out.add(tok)
|
||||
return out
|
||||
|
||||
|
||||
def _traceable(prose_tok: str, data: set[str], data_sorted: list[str]) -> bool:
|
||||
"""A prose number is traceable if the data contains it exactly, or contains
|
||||
a more precise value that rounds to it (182.5 <- 182.5485)."""
|
||||
if prose_tok in data:
|
||||
return True
|
||||
for d in data_sorted:
|
||||
if d.startswith(prose_tok) and len(d) > len(prose_tok):
|
||||
return True
|
||||
# '24.8' should match '24.81' in either direction once both are short
|
||||
if len(prose_tok) >= 4 and prose_tok.startswith(d):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def expand_cites(raw: str) -> set[int]:
|
||||
"""'[3, 7-9]' -> {3,7,8,9}"""
|
||||
out: set[int] = set()
|
||||
for chunk in re.split(r"\s*,\s*", raw.strip()):
|
||||
m = re.fullmatch(r"(\d+)\s*[\u2013-]\s*(\d+)", chunk)
|
||||
if m:
|
||||
a, b = int(m.group(1)), int(m.group(2))
|
||||
if 0 < b - a < 60:
|
||||
out.update(range(a, b + 1))
|
||||
elif chunk.isdigit():
|
||||
out.add(int(chunk))
|
||||
return out
|
||||
|
||||
|
||||
BIB_NAMES = ("references.md", "06_references.md", "99_references.md",
|
||||
"bibliography.md", "refs.md")
|
||||
|
||||
|
||||
def audit(root: str) -> dict:
|
||||
rep: dict = {"dir": root, "blocking": [], "warnings": [], "info": {}}
|
||||
|
||||
ms = os.path.join(root, "manuscript")
|
||||
mfiles = sorted(walk(ms)) if os.path.isdir(ms) else []
|
||||
bib_file = ""
|
||||
for cand in BIB_NAMES:
|
||||
p = os.path.join(ms, cand)
|
||||
if os.path.isfile(p):
|
||||
bib_file = p
|
||||
break
|
||||
# the reference list is not prose: its bracketed numbers are bibliography
|
||||
# indices, not measurements, and would poison every downstream check
|
||||
body_files = [f for f in mfiles if f != bib_file]
|
||||
prose = "\n".join(read(f) for f in body_files)
|
||||
rep["info"]["manuscript_files"] = [os.path.basename(f) for f in body_files]
|
||||
rep["info"]["bibliography_file"] = os.path.basename(bib_file) if bib_file else ""
|
||||
|
||||
# ---- 1. placeholders -------------------------------------------------
|
||||
for f in walk(root):
|
||||
base = os.path.basename(f)
|
||||
if base in GENERATED:
|
||||
continue # our own outputs quote the findings
|
||||
if os.sep + "journal_papers" + os.sep in f:
|
||||
continue
|
||||
t = read(f)
|
||||
for ph in PLACEHOLDERS:
|
||||
if ph.lower() in t.lower():
|
||||
msg = f"{os.path.relpath(f, root)} 含占位文本「{ph}」"
|
||||
if ph in PLACEHOLDER_SOFT and base == "BRIEF.md":
|
||||
rep["warnings"].append(msg + "(作者字段,投稿前替换即可)")
|
||||
else:
|
||||
rep["blocking"].append(msg)
|
||||
|
||||
# ---- 2. numbers traceable to data ------------------------------------
|
||||
data_dir = os.path.join(root, "data")
|
||||
data_text = ""
|
||||
if os.path.isdir(data_dir):
|
||||
data_text = "\n".join(read(f) for f in walk(data_dir))
|
||||
figs_dir = os.path.join(root, "figures")
|
||||
for sub in ("10_图表制作与引用", "03_检索与导出"):
|
||||
d = os.path.join(root, sub)
|
||||
if os.path.isdir(d):
|
||||
data_text += "\n".join(read(f) for f in walk(d))
|
||||
if data_text:
|
||||
in_data = collect_numbers(data_text)
|
||||
data_sorted = sorted(in_data, key=len, reverse=True)
|
||||
in_prose = collect_numbers(prose)
|
||||
untraced = sorted((t for t in in_prose
|
||||
if not _traceable(t, in_data, data_sorted)),
|
||||
key=lambda x: -len(x))[:40]
|
||||
rep["info"]["numbers_in_prose"] = len(in_prose)
|
||||
rep["info"]["numbers_in_data"] = len(in_data)
|
||||
rep["info"]["untraced_numbers"] = untraced
|
||||
if untraced:
|
||||
pct = 100.0 * len(untraced) / max(1, len(in_prose))
|
||||
sev = rep["warnings"] if pct <= 40 else rep["blocking"]
|
||||
sev.append(
|
||||
f"正文有 {len(untraced)} 个数字({pct:.0f}%)在 data/ 里找不到"
|
||||
f"——逐个核对这些是计算值还是笔误:{untraced[:12]}")
|
||||
else:
|
||||
rep["warnings"].append("没有 data/ 目录或为空,无法核对正文数字来源")
|
||||
|
||||
# ---- 3. figures cited vs drawn ---------------------------------------
|
||||
cited_figs = sorted({int(x) for x in FIG_CITE.findall(prose)})
|
||||
cited_tabs = sorted({int(x) for x in TAB_CITE.findall(prose)})
|
||||
drawn = set()
|
||||
for d in (figs_dir, os.path.join(root, "10_图表制作与引用")):
|
||||
if os.path.isdir(d):
|
||||
for f in os.listdir(d):
|
||||
m = re.search(r"(?:fig|figure|图)\s*0*(\d+)", f, re.I)
|
||||
if m:
|
||||
drawn.add(int(m.group(1)))
|
||||
rep["info"]["figures_cited"] = cited_figs
|
||||
rep["info"]["figures_drawn"] = sorted(drawn)
|
||||
missing_fig = [n for n in cited_figs if drawn and n not in drawn]
|
||||
if missing_fig:
|
||||
rep["blocking"].append(f"正文引用但找不到图件文件:Figure {missing_fig}")
|
||||
if cited_figs != sorted(set(cited_figs)):
|
||||
rep["warnings"].append("图号有重复引用")
|
||||
if cited_figs:
|
||||
gaps = [n for n in range(1, max(cited_figs) + 1) if n not in cited_figs]
|
||||
if gaps:
|
||||
rep["warnings"].append(f"图号不连续,缺:{gaps}")
|
||||
rep["info"]["tables_cited"] = cited_tabs
|
||||
|
||||
# ---- 4. references cited vs listed -----------------------------------
|
||||
cited: set[int] = set()
|
||||
for raw in REF_CITE.findall(prose):
|
||||
cited |= expand_cites(raw)
|
||||
bib_text = read(bib_file) if bib_file else ""
|
||||
listed: set[int] = set()
|
||||
if bib_text:
|
||||
listed = {int(x) for x in REF_ENTRY.findall(bib_text)}
|
||||
rep["info"]["refs_cited"] = sorted(cited)
|
||||
rep["info"]["refs_listed"] = len(listed)
|
||||
if listed:
|
||||
never = sorted(listed - cited)
|
||||
undef = sorted(cited - listed)
|
||||
if undef:
|
||||
rep["blocking"].append(f"正文引用了但参考文献表里没有:[{undef}]")
|
||||
if never:
|
||||
rep["warnings"].append(
|
||||
f"参考文献表里列出但正文从未引用:[{never}]——多数刊要求删除")
|
||||
elif cited:
|
||||
rep["warnings"].append(
|
||||
"正文有编号引用,但没找到参考文献文件"
|
||||
f"(manuscript/{BIB_NAMES[0]}),无法核对")
|
||||
|
||||
# ---- 5. degraded steps must be disclosed -----------------------------
|
||||
stp = os.path.join(root, "PAPER_STATE.json")
|
||||
if os.path.isfile(stp):
|
||||
try:
|
||||
st = json.loads(read(stp))
|
||||
except ValueError:
|
||||
st = {}
|
||||
deg = st.get("degraded") or []
|
||||
rep["info"]["degraded_steps"] = deg
|
||||
if deg:
|
||||
deliv = ""
|
||||
for cand in ("submission/README.md", "README.md",
|
||||
"20_投稿前总检/PRESUBMIT_CHECK.md"):
|
||||
p = os.path.join(root, cand.replace("/", os.sep))
|
||||
if os.path.isfile(p):
|
||||
deliv += read(p)
|
||||
undisclosed = [d for d in deg
|
||||
if d.get("reason", "")[:20] not in deliv]
|
||||
rep["info"]["undisclosed_degradations"] = undisclosed
|
||||
if undisclosed:
|
||||
rep["blocking"].append(
|
||||
f"有 {len(undisclosed)} 处降级步骤没有写进交付说明"
|
||||
"——降级可以,瞒着不行")
|
||||
else:
|
||||
rep["warnings"].append("没有 PAPER_STATE.json,无法核对降级记录")
|
||||
|
||||
# ---- 6. de-AI gates --------------------------------------------------
|
||||
scan = os.path.join(HERE, "prose_scan.py")
|
||||
if mfiles and os.path.isfile(scan):
|
||||
import subprocess
|
||||
p = subprocess.run([sys.executable, scan, ms, "--json",
|
||||
os.path.join(root, "_selfcheck_deai.json")],
|
||||
capture_output=True, text=True, encoding="utf-8",
|
||||
errors="replace")
|
||||
rep["info"]["deai_exit"] = p.returncode
|
||||
try:
|
||||
d = json.loads(read(os.path.join(root, "_selfcheck_deai.json")))
|
||||
rep["info"]["deai_failed"] = d.get("failed", [])
|
||||
if d.get("failed"):
|
||||
rep["blocking"].append(
|
||||
f"去 AI 痕迹判定项未过:{d['failed']}"
|
||||
"(跑 prose_scan.py 看具体怎么改)")
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
# ---- 6b. data provenance --------------------------------------------
|
||||
# References being real is only half the problem: the numbers must come
|
||||
# from an actual run. Every data file carries a .prov.json recording the
|
||||
# model, its hash, the parameters and the seed - so hand-edited data, or
|
||||
# data from a superseded model, is caught rather than trusted.
|
||||
sim = os.path.join(HERE, "simulate.py")
|
||||
ddir = os.path.join(root, "data")
|
||||
data_files = []
|
||||
if os.path.isdir(ddir):
|
||||
for dp, _dn, fn in os.walk(ddir):
|
||||
data_files += [os.path.join(dp, f) for f in fn
|
||||
if f.endswith((".csv", ".json"))
|
||||
and not f.endswith(".prov.json")]
|
||||
if data_files and os.path.isfile(sim):
|
||||
import subprocess
|
||||
p = subprocess.run([sys.executable, sim, "provenance", "--data", ddir],
|
||||
capture_output=True, text=True, encoding="utf-8",
|
||||
errors="replace")
|
||||
rep["info"]["data_files"] = len(data_files)
|
||||
rep["info"]["provenance_exit"] = p.returncode
|
||||
if p.returncode != 0:
|
||||
lines = [l.strip() for l in p.stdout.splitlines()
|
||||
if l.strip().startswith("[")]
|
||||
rep["blocking"].append(
|
||||
f"data/ 里有 {len(data_files)} 个数据文件,但溯源核查未通过 —— "
|
||||
"无法证明这些数字是真跑出来的。跑 "
|
||||
"`python scripts/simulate.py provenance --data data/` 看详情。"
|
||||
+ (" 例如:" + ";".join(lines[:3]) if lines else ""))
|
||||
else:
|
||||
rep["info"]["provenance"] = "all data files verified"
|
||||
elif not data_files:
|
||||
rep["warnings"].append(
|
||||
"没有 data/ 数据文件 —— 如果是计算/仿真研究,"
|
||||
"必须用 `python scripts/simulate.py run` 真跑出来,"
|
||||
"不能手写数字")
|
||||
|
||||
# ---- 7. citation verification report --------------------------------
|
||||
# A manuscript may only cite literature that was actually retrieved and
|
||||
# checked. litsearch.py writes the evidence; this insists that it exists
|
||||
# and that nothing inside it is unresolved.
|
||||
vr = os.path.join(root, "refs", "citation_verify.json")
|
||||
if not os.path.isfile(vr):
|
||||
rep["blocking"].append(
|
||||
"没有 refs/citation_verify.json —— 参考文献从未核验过。"
|
||||
"必须跑:python scripts/litsearch.py verify "
|
||||
"--refs manuscript/references.md --out refs/citation_verify.json")
|
||||
else:
|
||||
try:
|
||||
v = json.loads(read(vr))
|
||||
except ValueError:
|
||||
v = None
|
||||
if v is None:
|
||||
rep["blocking"].append("refs/citation_verify.json 不是合法 JSON")
|
||||
else:
|
||||
rep["info"]["citation_tally"] = v.get("tally", {})
|
||||
rep["info"]["citation_verified_at"] = v.get("verified_at", "")
|
||||
bad = [r for r in v.get("results", [])
|
||||
if r.get("verdict") in ("NOT_FOUND", "RETRACTED", "UNVERIFIED")]
|
||||
if bad:
|
||||
rep["blocking"].append(
|
||||
f"有 {len(bad)} 条参考文献没通过核验(查不到 / 已撤稿 / "
|
||||
f"未能确认),这些绝对不能引用:"
|
||||
+ "、".join(f"[{b.get('n')}]" for b in bad[:12]))
|
||||
retr = [r for r in v.get("results", [])
|
||||
if r.get("verdict") == "RETRACTED"]
|
||||
if retr:
|
||||
rep["blocking"].append(
|
||||
f"**引用了 {len(retr)} 篇已被撤稿的文献** —— "
|
||||
"必须删除或替换,这类引用会直接导致拒稿")
|
||||
fix = [r for r in v.get("results", []) if r.get("verdict") == "FIX"]
|
||||
if fix:
|
||||
rep["warnings"].append(
|
||||
f"{len(fix)} 条参考文献元数据与注册库不符(年份/作者/刊名/DOI),"
|
||||
"按报告里的 fix 字段改正")
|
||||
|
||||
return rep
|
||||
|
||||
|
||||
def render(rep: dict) -> str:
|
||||
L = [f"# 自检报告 · {rep['dir']}", ""]
|
||||
info = rep.get("info", {})
|
||||
L.append(f"- 正文文件:{', '.join(info.get('manuscript_files') or ['无'])}")
|
||||
if info.get("numbers_in_prose"):
|
||||
L.append(f"- 正文数字 {info['numbers_in_prose']} 个,"
|
||||
f"data/ 中数字 {info['numbers_in_data']} 个")
|
||||
if info.get("figures_cited"):
|
||||
L.append(f"- 引用图号 {info['figures_cited']};"
|
||||
f"已有图件 {info.get('figures_drawn') or '未找到'}")
|
||||
if info.get("refs_cited"):
|
||||
L.append(f"- 引用文献 {len(info['refs_cited'])} 条;"
|
||||
f"文献表 {info.get('refs_listed', 0)} 条")
|
||||
L.append("")
|
||||
if rep["blocking"]:
|
||||
L.append(f"## ✗ 阻断问题({len(rep['blocking'])} 条)")
|
||||
L.append("")
|
||||
for x in rep["blocking"]:
|
||||
L.append(f"- {x}")
|
||||
L.append("")
|
||||
if rep["warnings"]:
|
||||
L.append(f"## ! 需要人工看一眼({len(rep['warnings'])} 条)")
|
||||
L.append("")
|
||||
for x in rep["warnings"]:
|
||||
L.append(f"- {x}")
|
||||
L.append("")
|
||||
if not rep["blocking"]:
|
||||
L.append("## ✓ 没有发现阻断问题")
|
||||
L.append("")
|
||||
L.append("> 说明:本报告只查**可自动核对的项**。它不能替代人工核对"
|
||||
"(例如数字是否算对、引用内容是否与原文一致)。"
|
||||
"自动通过不等于论文正确。")
|
||||
return "\n".join(L)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_utf8()
|
||||
ap = argparse.ArgumentParser(prog="selfcheck")
|
||||
ap.add_argument("--dir", required=True)
|
||||
ap.add_argument("--json", dest="json_out", default="")
|
||||
a = ap.parse_args()
|
||||
root = os.path.abspath(a.dir)
|
||||
if not os.path.isdir(root):
|
||||
print(f"[fail] 找不到目录 {root}", file=sys.stderr)
|
||||
return 1
|
||||
rep = audit(root)
|
||||
out = render(rep)
|
||||
print(out)
|
||||
with io.open(os.path.join(root, "SELFCHECK.md"), "w", encoding="utf-8") as fh:
|
||||
fh.write(out + "\n")
|
||||
if a.json_out:
|
||||
with io.open(a.json_out, "w", encoding="utf-8") as fh:
|
||||
json.dump(rep, fh, ensure_ascii=False, indent=1)
|
||||
print(f"[ok] {a.json_out}")
|
||||
return 1 if rep["blocking"] else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,335 @@
|
||||
#!/usr/bin/env python3
|
||||
"""selftest — prove the pipeline works on this machine, without a human.
|
||||
|
||||
Builds a throwaway project in a temp directory, drives `autopilot.py` through
|
||||
all 22 steps with minimal fixture content, then runs `selfcheck.py` and asserts
|
||||
that the loop advanced every step and that the refusal mechanism actually
|
||||
refuses.
|
||||
|
||||
python selftest.py
|
||||
|
||||
Exit 0 = the install is functional. Exit 1 = something is broken.
|
||||
Standard library only.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
AUTO = os.path.join(HERE, "autopilot.py")
|
||||
SELF = os.path.join(HERE, "selfcheck.py")
|
||||
|
||||
|
||||
def _utf8() -> None:
|
||||
for s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
s.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run(*args, expect=None):
|
||||
p = subprocess.run([sys.executable, *args], capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace")
|
||||
if expect is not None and p.returncode != expect:
|
||||
print(f"!! exit {p.returncode} (expected {expect}) for {' '.join(args[1:4])}")
|
||||
print(p.stdout[-700:])
|
||||
print(p.stderr[-700:])
|
||||
return p
|
||||
|
||||
|
||||
# Minimal structurally-valid content for every declared artifact. The text is
|
||||
# deliberately bland: this test checks the plumbing, not the prose.
|
||||
BIG = ("# Fixture\n\n" + ("This is filler content for the pipeline self test. " * 4)
|
||||
+ "\n")
|
||||
|
||||
BODY = {
|
||||
"01_项目初始化/BRIEF.md":
|
||||
"# BRIEF\n\nvenue: Journal of Vibration and Control (SAGE, Q2)\n"
|
||||
"type: research article\nlength: 8000 words\nfigures: 10\n"
|
||||
"experiment: none (computational study)\n"
|
||||
"authors: 占位符(投稿前替换)\n",
|
||||
"02_检索式生成/SEARCH_STRINGS.md":
|
||||
"# Search strings\n\nbroad: (rotor OR shaft) AND vibration\n"
|
||||
"medium: (magnetorheological elastomer) AND absorber AND rotor\n"
|
||||
"narrow: \"magnetorheological elastomer\" AND \"dynamic vibration absorber\"\n",
|
||||
"03_检索与导出/SEARCH_LOG.md":
|
||||
"# Search log\n\nOpenAlex 2026-09-20 hits 412 exported 412\n"
|
||||
"Crossref 2026-09-20 hits 96 after dedup 61\n",
|
||||
"04_选题与空白识别/TOPIC.md":
|
||||
"# Topic\n\n1. Adaptive MRE absorber for rotor vibration.\n"
|
||||
" gap: tuning is usually fixed\ng risk: reluctance network, not a field solve\n",
|
||||
"05_对标库深度学习/BENCHMARK.md":
|
||||
"# Benchmarks\n\n1. A 2024 borrow the tolerance declaration\n"
|
||||
"2. B 2023 borrow the parameter table\n3. C 2022\n4. D 2021\n5. E 2020\n",
|
||||
"06_文献筛选分类/SELECTION.csv":
|
||||
"title,year,include,reason,class\nRotor vibration control,2024,Y,relevant,mechanism\n"
|
||||
"Unrelated work,2019,N,off topic,-\n",
|
||||
"07_导入引用库取全文/PDF_STATUS.md":
|
||||
"# PDF status\n\nhave 18, missing 3, list below\n",
|
||||
"08_文献精读/NOTES/n01.md":
|
||||
"# Note 01\n\n- key figure 62 percent reduction (p. 4, Table 2)\n- limit: single speed\n",
|
||||
"09_论文框架搭建/OUTLINE.md":
|
||||
"# Outline\n\n1 Introduction [Fig.1]\n2 Methods [Tab.1]\n"
|
||||
"3 Results [Fig.2]\n4 Discussion\n5 Conclusions\n",
|
||||
"10_图表制作与引用/FIGPLAN.md":
|
||||
"# Figure plan\n\nFig.1 architecture (own work)\nFig.2 material response (own work)\n"
|
||||
"Fig.3 sweep (own work)\nFig.4 verification (own work)\nFig.5 control (own work)\n",
|
||||
"manuscript/00_abstract.md":
|
||||
"# Abstract\n\nThe peak amplitude falls from 182.5485 um to 24.8135 um, a reduction "
|
||||
"of 86.4 percent. The controller uses more mean power than the best constant current.\n",
|
||||
"manuscript/01_intro.md":
|
||||
"# 1 Introduction\n\nRotor vibration limits the operating range of rotating "
|
||||
"machinery [1]. Passive absorbers cannot adapt to varying speed [2].\n",
|
||||
"manuscript/02_methods.md":
|
||||
"# 2 Methods\n\nThe shaft is a clamped-clamped beam of 350 mm span. The absorber is "
|
||||
"a 0.400 kg mass on a four-layer MRE pad. Mesh convergence used three grids of "
|
||||
"120000, 480000 and 1900000 elements.\n",
|
||||
"manuscript/03_results.md":
|
||||
"# 3 Results\n\nThe bare rotor peaks at 182.5485 um. The de-energized configuration "
|
||||
"reaches 101.9053 um. The best constant current gives 35.8675 um. The controller "
|
||||
"gives 24.8135 um.\n",
|
||||
"manuscript/04_discussion.md":
|
||||
"# 4 Discussion\n\nThe reduction is comparable to published adaptive absorbers [1]. "
|
||||
"The thermal result refutes the 1.0 A design current.\n",
|
||||
"manuscript/05_conclusions.md":
|
||||
"# 5 Conclusions\n\nAn adaptive MRE absorber with speed-scheduled current reduces "
|
||||
"the peak synchronous response. The result is a simulation prediction and has not "
|
||||
"been experimentally verified.\n",
|
||||
"manuscript/references.md":
|
||||
"# References\n\n[1] A. Rahman et al. (2024). Rotor vibration control. "
|
||||
"J. Sound Vib.\n[2] B. Li (2023). Tunable absorbers. Mech. Syst. Signal Process.\n",
|
||||
"14_目标期刊选择/JOURNALS.csv":
|
||||
"journal,issn,quartile,apc,risk\nJournal of Vibration and Control,1077-5463,Q2,"
|
||||
"subscription free to publish,low\n",
|
||||
"15_目标期刊格式学习/FORMAT_CHECKLIST.md":
|
||||
"# Format checklist\n\n- [x] abstract under 250 words\n- [x] 6 keywords\n"
|
||||
"- [x] numbered citations\n- [x] CRediT statement\n",
|
||||
"16_润色与语言打磨/scan_report.json":
|
||||
'{"all_pass": true, "failed": [], "gates": ['
|
||||
'{"key": "sent_cv", "value": 0.61, "pass": true}, '
|
||||
'{"key": "excess_vocab", "value": 0.0, "pass": true}, '
|
||||
'{"key": "conn_rate", "value": 0.4, "pass": true}], '
|
||||
'"note": "fixture written by selftest.py"}\n',
|
||||
"17_图片版权/RIGHTS.md":
|
||||
"# Rights\n\nAll figures generated by project scripts, no third-party rights.\n",
|
||||
"18_CoverLetter/Cover_Letter.md":
|
||||
"# Cover letter\n\nWe submit the enclosed manuscript. The peak amplitude is reduced "
|
||||
"by 86.4 percent. AI use is disclosed in the Acknowledgements.\n",
|
||||
"19_去AI痕迹/scan_after.json":
|
||||
'{"all_pass": true, "failed": [], "note": "fixture written by selftest.py"}\n',
|
||||
"19_去AI痕迹/statement.md":
|
||||
"# AI use statement\n\n**Use of generative AI.** The authors used an AI assistant "
|
||||
"for language editing and structuring. All scientific content and conclusions are "
|
||||
"the authors' own.\n",
|
||||
"19_去AI痕迹/diff_check.md":
|
||||
"# Edit comparison\n\n| before | after | number unchanged |\n|---|---|---|\n"
|
||||
"| peak falls to 24.8135 um | peak falls to 24.8135 um | yes |\n",
|
||||
"20_投稿前总检/PRESUBMIT_CHECK.md":
|
||||
"# Pre-submission check\n\n- [x] citations verified\n- [x] numbers traced\n"
|
||||
"- [x] figure numbers consecutive\n\n## Degraded steps\n\nnone\n",
|
||||
# step 20 requires the citation verification report; a real run produces it
|
||||
# with `litsearch.py verify`
|
||||
"refs/citation_verify.json":
|
||||
'{"refs_file": "manuscript/references.md", "verified_at": "fixture", '
|
||||
'"tally": {"VERIFIED": 2}, "blocking": 0, "results": ['
|
||||
'{"n": 1, "verdict": "VERIFIED", "problems": [], "fix": {}}, '
|
||||
'{"n": 2, "verdict": "VERIFIED", "problems": [], "fix": {}}]}\n',
|
||||
"21_返修/Response_Letter.md":
|
||||
"# Response to reviewers\n\nComment 1.1 addressed; see the revised Section 3.\n",
|
||||
"21_返修/CHANGES.md":
|
||||
"# Change log\n\n| comment | change | location |\n|---|---|---|\n",
|
||||
# shared directories have to be non-empty too.
|
||||
# NOTE: data/ is NOT written here. The self test generates it by actually
|
||||
# running the reference model, so the fixture exercises the provenance
|
||||
# chain instead of hand-writing numbers - which is the whole point.
|
||||
"refs/export.ris": "TY - JOUR\nTI - Rotor vibration control\nPY - 2024\nER -\n",
|
||||
"12_方法与结果/model_verify.json":
|
||||
'{"model": "rotor_mre_dva", "version": "1.0.0", "passed": true, '
|
||||
'"n_checks": 7, "n_passed": 7, "checks": [], '
|
||||
'"note": "produced by simulate.py check during the self test"}\n',
|
||||
"figures/fig01_architecture.pdf": "%PDF-1.4 fixture for the pipeline self test\n",
|
||||
"figures/fig02_material.pdf": "%PDF-1.4 fixture for the pipeline self test\n",
|
||||
"figures/fig03_sweep.pdf": "%PDF-1.4 fixture for the pipeline self test\n",
|
||||
"figures/fig04_verification.pdf": "%PDF-1.4 fixture for the pipeline self test\n",
|
||||
"figures/fig05_control.pdf": "%PDF-1.4 fixture for the pipeline self test\n",
|
||||
"submission/README.md":
|
||||
"# Submission package\n\nProduced by the paper-pipeline self test. "
|
||||
"Degraded steps: none.\n",
|
||||
}
|
||||
|
||||
|
||||
def write(root: str, rel: str, body: str) -> None:
|
||||
p = os.path.join(root, rel.replace("/", os.sep))
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with io.open(p, "w", encoding="utf-8") as fh:
|
||||
fh.write(body)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_utf8()
|
||||
root = os.path.join(tempfile.gettempdir(), "paper_pipeline_selftest")
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
failures: list[str] = []
|
||||
|
||||
print("paper-pipeline self test\n")
|
||||
print(f"work dir: {root}\n")
|
||||
|
||||
# --- 0. the step table must be sane ---------------------------------
|
||||
# A duplicate step id makes IDS.index() return the first occurrence, so the
|
||||
# pipeline loops on one step forever instead of failing loudly.
|
||||
sys.path.insert(0, HERE)
|
||||
try:
|
||||
import autopilot as A
|
||||
st_problems = A._check_step_table()
|
||||
except Exception as e: # noqa: BLE001
|
||||
st_problems = [f"import autopilot failed: {type(e).__name__}: {e}"]
|
||||
if st_problems:
|
||||
print(" [!!] step table is broken:")
|
||||
for x in st_problems:
|
||||
print(f" {x}")
|
||||
failures.extend(st_problems)
|
||||
else:
|
||||
print(f" [ok] step table sane: {len(A.S)} steps, ids "
|
||||
f"{A.IDS[0]}..{A.IDS[-1]}, no duplicates")
|
||||
|
||||
# --- 1. start -------------------------------------------------------
|
||||
p = run(AUTO, "start", "--dir", root,
|
||||
"--direction", "adaptive magnetorheological elastomer vibration "
|
||||
"absorber with ANFIS control for rotor vibration",
|
||||
expect=0)
|
||||
if p.returncode != 0:
|
||||
return 1
|
||||
for line in p.stdout.splitlines():
|
||||
if line.startswith("[ok]"):
|
||||
print(" " + line)
|
||||
print()
|
||||
|
||||
# --- 2. generate real data through the simulation chain -------------
|
||||
# data/ must be produced by an actual run, not written by hand, so the test
|
||||
# exercises simulate.py and the provenance sidecars it emits.
|
||||
SIM = os.path.join(HERE, "simulate.py")
|
||||
data_dir = os.path.join(root, "data")
|
||||
os.makedirs(data_dir, exist_ok=True)
|
||||
produced = []
|
||||
if os.path.isfile(SIM):
|
||||
for study, name in (("material_law", "material_law"),
|
||||
("speed_sweep", "speed_sweep"),
|
||||
("monte_carlo", "monte_carlo")):
|
||||
args = [sys.executable, SIM, "run", "--model", "rotor_mre_dva",
|
||||
"--study", study, "--out", os.path.join(data_dir,
|
||||
f"{name}.csv")]
|
||||
if study == "monte_carlo":
|
||||
args += ["--seed", "0", "--n", "60"]
|
||||
p = subprocess.run(args, capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace")
|
||||
if p.returncode == 0:
|
||||
produced.append(f"{name}.csv")
|
||||
else:
|
||||
failures.append(f"simulate.py run {study} failed: "
|
||||
f"{p.stderr.strip()[:200]}")
|
||||
if produced:
|
||||
print(f" [ok] simulation produced real data: {', '.join(produced)}")
|
||||
p = subprocess.run([sys.executable, SIM, "provenance",
|
||||
"--data", data_dir], capture_output=True,
|
||||
text=True, encoding="utf-8", errors="replace")
|
||||
if p.returncode == 0:
|
||||
print(" [ok] data provenance verified")
|
||||
else:
|
||||
failures.append("provenance check failed on freshly "
|
||||
"generated data")
|
||||
else:
|
||||
failures.append("no data was produced by the simulation chain")
|
||||
else:
|
||||
failures.append(f"simulate.py not found at {SIM}")
|
||||
|
||||
# --- 3. the refusal mechanism must actually refuse ------------------
|
||||
p = run(AUTO, "done", "--dir", root, expect=1)
|
||||
if p.returncode != 1:
|
||||
failures.append("done did not refuse to advance on a missing artifact")
|
||||
else:
|
||||
print(" [ok] refuses to advance when the artifact is missing")
|
||||
|
||||
write(root, "01_项目初始化/BRIEF.md", "x\n")
|
||||
p = run(AUTO, "done", "--dir", root, expect=1)
|
||||
if p.returncode != 1:
|
||||
failures.append("done did not refuse an empty stub artifact")
|
||||
else:
|
||||
print(" [ok] refuses to advance on a stub artifact")
|
||||
|
||||
# --- 3. drive every step -------------------------------------------
|
||||
advanced = 0
|
||||
for _ in range(40):
|
||||
p = run(AUTO, "next", "--dir", root)
|
||||
if "全部步骤已完成" in p.stdout:
|
||||
break
|
||||
step = None
|
||||
for line in p.stdout.splitlines():
|
||||
if line.startswith("工单 · 第 "):
|
||||
step = line.split("第 ")[1].split(" 步")[0].strip()
|
||||
break
|
||||
if step is None:
|
||||
failures.append("could not parse the work order from `next`")
|
||||
break
|
||||
for rel, body in BODY.items():
|
||||
write(root, rel, body)
|
||||
p = run(AUTO, "done", "--dir", root)
|
||||
if p.returncode != 0:
|
||||
failures.append(f"step {step} could not be completed")
|
||||
break
|
||||
advanced += 1
|
||||
|
||||
# `start` pre-completes step 00, so the loop drives the remaining 21.
|
||||
print(f" [ok] advanced {advanced}/21 steps with no human input"
|
||||
if advanced == 21 else f" [!!] advanced only {advanced}/21 steps")
|
||||
if advanced != 21:
|
||||
failures.append(f"only {advanced}/21 steps advanced")
|
||||
|
||||
# --- 4. check + selfcheck ------------------------------------------
|
||||
p = run(AUTO, "check", "--dir", root)
|
||||
if "[缺件]" in p.stdout or "[降级]" in p.stdout:
|
||||
failures.append("autopilot check reports missing or degraded steps")
|
||||
else:
|
||||
print(" [ok] every completed step still has its artifacts")
|
||||
|
||||
p = run(SELF, "--dir", root)
|
||||
if p.returncode == 0:
|
||||
print(" [ok] selfcheck found no blocking problem")
|
||||
else:
|
||||
for line in p.stdout.splitlines():
|
||||
if line.startswith("- "):
|
||||
print(" " + line[:150])
|
||||
failures.append("selfcheck reported blocking problems on a clean fixture")
|
||||
|
||||
# --- 5. degradation must be recorded and disclosed ------------------
|
||||
d2 = os.path.join(tempfile.gettempdir(), "paper_pipeline_selftest_skip")
|
||||
shutil.rmtree(d2, ignore_errors=True)
|
||||
run(AUTO, "start", "--dir", d2, "--direction", "test direction for skip")
|
||||
run(AUTO, "skip", "--dir", d2, "--step", "01", "--reason", "selftest")
|
||||
st = os.path.join(d2, "PAPER_STATE.json")
|
||||
with io.open(st, encoding="utf-8") as fh:
|
||||
blob = fh.read()
|
||||
if '"degraded"' in blob and "selftest" in blob:
|
||||
print(" [ok] degradation is recorded in the state file")
|
||||
else:
|
||||
failures.append("skip did not record the degradation")
|
||||
shutil.rmtree(d2, ignore_errors=True)
|
||||
|
||||
print()
|
||||
if failures:
|
||||
print("FAILED:")
|
||||
for x in failures:
|
||||
print(f" - {x}")
|
||||
return 1
|
||||
print("PASS — the pipeline runs end to end on this machine.")
|
||||
print(f" (the throwaway project is at {root})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,307 @@
|
||||
#!/usr/bin/env python3
|
||||
"""simulate — run real simulations and stamp their output with provenance.
|
||||
|
||||
This is the data half of the pipeline. Without it a manuscript's citations
|
||||
could be verified while its numbers were not, because nothing forced the
|
||||
numbers to come from an actual run.
|
||||
|
||||
python simulate.py list
|
||||
python simulate.py check --model rotor_mre_dva
|
||||
python simulate.py run --model rotor_mre_dva --study speed_sweep \
|
||||
--out data/speed_sweep.csv
|
||||
python simulate.py provenance --data data/
|
||||
|
||||
Every file written by `run` gets a sidecar `<file>.prov.json` recording the
|
||||
model, its version, the exact parameter set, the random seed, the SHA-256 of
|
||||
the model source at run time, and the verification report that was valid then.
|
||||
`provenance` re-checks all of that, so data that was hand-edited, generated by
|
||||
a superseded model, or never verified is caught rather than trusted.
|
||||
|
||||
Standard library plus numpy.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
MODELS_DIR = os.path.join(os.path.dirname(HERE), "models")
|
||||
sys.path.insert(0, MODELS_DIR)
|
||||
|
||||
try:
|
||||
import numpy as np # noqa: F401
|
||||
except ImportError: # pragma: no cover
|
||||
print("simulate needs numpy: pip install numpy", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def _utf8() -> None:
|
||||
for s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
s.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _sha256(path: str) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as fh:
|
||||
for chunk in iter(lambda: fh.read(1 << 16), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def available_models() -> dict[str, str]:
|
||||
if not os.path.isdir(MODELS_DIR):
|
||||
return {}
|
||||
out = {}
|
||||
for f in sorted(os.listdir(MODELS_DIR)):
|
||||
if f.endswith(".py") and not f.startswith("_"):
|
||||
out[f[:-3]] = os.path.join(MODELS_DIR, f)
|
||||
return out
|
||||
|
||||
|
||||
def load_model(name: str):
|
||||
models = available_models()
|
||||
if name not in models:
|
||||
raise SystemExit(f"[fail] 没有模型 {name!r};可用:{list(models)}")
|
||||
sys.path.insert(0, MODELS_DIR)
|
||||
mod = __import__(name)
|
||||
for attr in ("NAME", "VERSION", "PARAMS", "STUDIES"):
|
||||
if not hasattr(mod, attr):
|
||||
raise SystemExit(
|
||||
f"[fail] 模型 {name} 缺少必需属性 {attr},"
|
||||
"写法见 models/README.md")
|
||||
return mod, models[name]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- commands
|
||||
def cmd_list(a) -> int:
|
||||
models = available_models()
|
||||
if not models:
|
||||
print(f"[fail] {MODELS_DIR} 下没有模型", file=sys.stderr)
|
||||
return 1
|
||||
print(f"可用模型({MODELS_DIR})\n")
|
||||
for name, path in models.items():
|
||||
try:
|
||||
mod, _ = load_model(name)
|
||||
print(f" {mod.NAME:18s} v{mod.VERSION:8s} {name}.py")
|
||||
print(f" {getattr(mod, 'DESCRIPTION', '')}")
|
||||
print(f" 研究:{', '.join(mod.STUDIES)}")
|
||||
except SystemExit:
|
||||
print(f" {name:18s} (加载失败)")
|
||||
print()
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_check(a) -> int:
|
||||
mod, path = load_model(a.model)
|
||||
print(f"模型:{mod.NAME} v{mod.VERSION}")
|
||||
print(f"源码:{path}")
|
||||
print(f"SHA-256:{_sha256(path)[:16]}…\n")
|
||||
r = mod.verify(verbose=True)
|
||||
if a.out:
|
||||
os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
|
||||
payload = dict(r)
|
||||
payload["source_path"] = path
|
||||
payload["source_sha256"] = _sha256(path)
|
||||
payload["checked_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
with io.open(a.out, "w", encoding="utf-8") as fh:
|
||||
json.dump(payload, fh, ensure_ascii=False, indent=1)
|
||||
print(f"\n[ok] 自检报告:{a.out}")
|
||||
if not r["passed"]:
|
||||
print("\n[阻止] 模型自检未通过 —— 用它产生的数据不能写进论文。",
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_run(a) -> int:
|
||||
mod, path = load_model(a.model)
|
||||
if a.study not in mod.STUDIES:
|
||||
raise SystemExit(f"[fail] 模型没有研究 {a.study!r};"
|
||||
f"可用:{list(mod.STUDIES)}")
|
||||
|
||||
# Refuse to produce data from a model that does not pass its own checks.
|
||||
if not a.skip_verify:
|
||||
r = mod.verify(verbose=False)
|
||||
if not r["passed"]:
|
||||
bad = [c["check"] for c in r["checks"] if not c["pass"]]
|
||||
print("[阻止] 模型自检未通过,拒绝产生数据:", file=sys.stderr)
|
||||
for b in bad:
|
||||
print(f" - {b}", file=sys.stderr)
|
||||
print("先修模型,或确认是有意为之再加 --skip-verify。",
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
verify_info = {"passed": True, "n_checks": r["n_checks"],
|
||||
"n_passed": r["n_passed"]}
|
||||
print(f"[ok] 模型自检 {r['n_passed']}/{r['n_checks']} 通过")
|
||||
else:
|
||||
verify_info = {"passed": None, "note": "自检被 --skip-verify 跳过"}
|
||||
print("[warn] 跳过了模型自检 —— 这份数据不能直接进论文")
|
||||
|
||||
ctx = dict(mod.PARAMS)
|
||||
ctx["params"] = dict(mod.PARAMS)
|
||||
for kv in (a.set or []):
|
||||
if "=" not in kv:
|
||||
raise SystemExit(f"[fail] --set 需要 key=value,收到 {kv!r}")
|
||||
k, v = kv.split("=", 1)
|
||||
try:
|
||||
ctx["params"][k] = float(v) if "." in v or "e" in v.lower() else int(v)
|
||||
except ValueError:
|
||||
ctx["params"][k] = v
|
||||
if a.seed is not None:
|
||||
ctx["seed"] = a.seed
|
||||
if a.n is not None:
|
||||
ctx["n"] = a.n
|
||||
if a.current is not None:
|
||||
ctx["I_A"] = a.current
|
||||
|
||||
t0 = time.time()
|
||||
print(f"[run] {mod.NAME}.{a.study} …")
|
||||
out = mod.STUDIES[a.study](ctx)
|
||||
dt = time.time() - t0
|
||||
rows, cols = out["rows"], out["columns"]
|
||||
print(f"[ok] {len(rows)} 行,用时 {dt:.1f}s")
|
||||
|
||||
dest = a.out
|
||||
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
|
||||
with io.open(dest, "w", encoding="utf-8", newline="") as fh:
|
||||
w = csv.DictWriter(fh, fieldnames=cols, extrasaction="ignore")
|
||||
w.writeheader()
|
||||
for r in rows:
|
||||
w.writerow(r)
|
||||
print(f"[ok] {dest}")
|
||||
|
||||
prov = {
|
||||
"schema": "paper-pipeline/provenance/1.0",
|
||||
"file": os.path.basename(dest),
|
||||
"file_sha256": _sha256(dest),
|
||||
"model": mod.NAME,
|
||||
"model_version": mod.VERSION,
|
||||
"model_source": os.path.relpath(path, os.path.dirname(HERE)),
|
||||
"model_sha256": _sha256(path),
|
||||
"study": a.study,
|
||||
"parameters": ctx["params"],
|
||||
"seed": ctx.get("seed"),
|
||||
"rows": len(rows),
|
||||
"columns": cols,
|
||||
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"runtime_s": round(dt, 3),
|
||||
"verification": verify_info,
|
||||
"environment": {"python": sys.version.split()[0],
|
||||
"platform": platform.platform(),
|
||||
"numpy": __import__("numpy").__version__},
|
||||
}
|
||||
pp = dest + ".prov.json"
|
||||
with io.open(pp, "w", encoding="utf-8") as fh:
|
||||
json.dump(prov, fh, ensure_ascii=False, indent=1)
|
||||
print(f"[ok] {pp}")
|
||||
print(f" 文件指纹 {prov['file_sha256'][:16]}… "
|
||||
f"模型指纹 {prov['model_sha256'][:16]}…")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_provenance(a) -> int:
|
||||
roots = a.data if isinstance(a.data, list) else [a.data]
|
||||
files = []
|
||||
for r in roots:
|
||||
if os.path.isdir(r):
|
||||
for dp, _dn, fn in os.walk(r):
|
||||
for f in fn:
|
||||
if f.endswith((".csv", ".json")) and not f.endswith(".prov.json"):
|
||||
files.append(os.path.join(dp, f))
|
||||
elif os.path.isfile(r):
|
||||
files.append(r)
|
||||
print(f"检查 {len(files)} 个数据文件\n")
|
||||
ok = warn = bad = 0
|
||||
for f in sorted(files):
|
||||
pp = f + ".prov.json"
|
||||
if not os.path.isfile(pp):
|
||||
print(f" [缺溯源] {os.path.relpath(f)} —— 没有 .prov.json,"
|
||||
"无法证明这份数据是真跑出来的")
|
||||
bad += 1
|
||||
continue
|
||||
try:
|
||||
with io.open(pp, encoding="utf-8") as fh:
|
||||
p = json.load(fh)
|
||||
except ValueError:
|
||||
print(f" [坏溯源] {os.path.relpath(f)} —— .prov.json 不是合法 JSON")
|
||||
bad += 1
|
||||
continue
|
||||
problems = []
|
||||
if p.get("file_sha256") and _sha256(f) != p["file_sha256"]:
|
||||
problems.append("数据文件在生成之后被改动过(指纹不符)")
|
||||
src = p.get("model_source")
|
||||
if src:
|
||||
# stored relative to the skill root (the parent of scripts/)
|
||||
sp = os.path.join(os.path.dirname(HERE), src)
|
||||
if os.path.isfile(sp):
|
||||
if _sha256(sp) != p.get("model_sha256"):
|
||||
problems.append("模型源码已改动,这份数据是用旧版本跑的,需要重跑")
|
||||
else:
|
||||
problems.append(f"找不到模型源码 {src}")
|
||||
v = p.get("verification") or {}
|
||||
if v.get("passed") is False:
|
||||
problems.append("生成时模型自检未通过")
|
||||
elif v.get("passed") is None:
|
||||
problems.append("生成时跳过了模型自检")
|
||||
if problems:
|
||||
for x in problems:
|
||||
print(f" [有问题] {os.path.relpath(f)} —— {x}")
|
||||
bad += 1
|
||||
else:
|
||||
print(f" [ok ] {os.path.relpath(f)} "
|
||||
f"({p.get('model')}.{p.get('study')}, {p.get('rows')} 行, "
|
||||
f"{p.get('generated_at')})")
|
||||
ok += 1
|
||||
print(f"\n可溯源 {ok} · 有问题 {bad} · 警告 {warn}")
|
||||
if bad:
|
||||
print("**有数据无法证明是真跑出来的 —— 不能用来写论文。**")
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_utf8()
|
||||
ap = argparse.ArgumentParser(prog="simulate",
|
||||
description="真实仿真与数据溯源")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
sub.add_parser("list", help="列出可用模型").set_defaults(func=cmd_list)
|
||||
|
||||
c = sub.add_parser("check", help="跑模型自检(解析解对照 + 收敛性)")
|
||||
c.add_argument("--model", required=True)
|
||||
c.add_argument("--out", default="")
|
||||
c.set_defaults(func=cmd_check)
|
||||
|
||||
r = sub.add_parser("run", help="跑一个研究并写带溯源的数据文件")
|
||||
r.add_argument("--model", required=True)
|
||||
r.add_argument("--study", required=True)
|
||||
r.add_argument("--out", required=True)
|
||||
r.add_argument("--set", action="append", default=[],
|
||||
help="覆盖参数,可重复:--set m2_kg=0.5")
|
||||
r.add_argument("--seed", type=int, default=None)
|
||||
r.add_argument("--n", type=int, default=None)
|
||||
r.add_argument("--current", type=float, default=None)
|
||||
r.add_argument("--skip-verify", action="store_true",
|
||||
help="跳过模型自检(产生警告,数据不可直接进论文)")
|
||||
r.set_defaults(func=cmd_run)
|
||||
|
||||
p = sub.add_parser("provenance", help="核查数据文件的溯源信息")
|
||||
p.add_argument("--data", nargs="+", required=True)
|
||||
p.set_defaults(func=cmd_provenance)
|
||||
|
||||
a = ap.parse_args()
|
||||
return a.func(a)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""统计分章 md 的中文字数与图表编号连续性(中文论文第 20 步总检用)。
|
||||
|
||||
从单项目硬编码版(只认 `manuscript/` 与 `figures/figN-M_`)提炼为通用版:
|
||||
用 `--dir` 指向任意手稿目录,图号/表号的书写形式由正则给出,判定结果可用
|
||||
退出码驱动 CI 或 `final_check.py`。
|
||||
|
||||
统计口径
|
||||
--------
|
||||
* 中文字数:只数汉字 `[\\u4e00-\\u9fff]`;先剔除图片嵌入 `` 与
|
||||
HTML 注释,公式文本、图题、表题仍计入(与 Word 字数统计对齐)。
|
||||
* 图:图片嵌入的文件名里抓 `fig4-1` / `4-1` / `图4-1` 三种写法。
|
||||
* 表:抓行首 `**表 4-1` 形式的题注(必须行首,避免把加粗收尾误判成题注),
|
||||
以及正文里的 `表 4-1`。
|
||||
* 连续性:按章号分组,组内序号必须从 1 起连续;重号、跳号都算不通过。
|
||||
|
||||
用法
|
||||
----
|
||||
python scripts/wordcount.py --dir manuscript
|
||||
python scripts/wordcount.py --dir manuscript --min 20000 --json report.json
|
||||
python scripts/wordcount.py --dir manuscript --fig-pattern "fig{n}-{m}_"
|
||||
|
||||
退出码:0 全部通过;1 有连续性问题或字数未达标;2 参数/IO 错误。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
CJK = re.compile(r"[\u4e00-\u9fff]")
|
||||
IMG = re.compile(r"!\[[^\]]*\]\(([^)]+)\)")
|
||||
HTML_COMMENT = re.compile(r"<!--.*?-->", re.S)
|
||||
|
||||
# 图号来源:图片路径里的 figN-M / N-M,或正文里的「图 N-M」「图N-M」
|
||||
FIG_IN_PATH = re.compile(r"(?:fig)?(\d+)\s*[-–—.]\s*(\d+)", re.I)
|
||||
FIG_IN_TEXT = re.compile(r"图\s*(\d+)\s*[-–—.]\s*(\d+)")
|
||||
# 表号:加粗题注 `**表 4-1`、或正文「表 4-1」
|
||||
TAB_IN_TEXT = re.compile(r"表\s*(\d+)\s*[-–—.]\s*(\d+)")
|
||||
|
||||
|
||||
def read_text(path: str) -> str:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def body_chars(text: str) -> int:
|
||||
"""剔除图片嵌入与 HTML 注释后的汉字数。"""
|
||||
stripped = IMG.sub("", text)
|
||||
stripped = HTML_COMMENT.sub("", stripped)
|
||||
return len(CJK.findall(stripped))
|
||||
|
||||
|
||||
def collect(text: str):
|
||||
"""返回 (嵌图号, 正文图引用号, 表题号, 正文表引用号),元素为 'N-M' 字符串。"""
|
||||
embeds, fig_refs, tab_caps, tab_refs = [], [], [], []
|
||||
for m in IMG.finditer(text):
|
||||
target = m.group(1)
|
||||
hit = re.search(r"(\d+)\s*[-–—.]\s*(\d+)", os.path.basename(target))
|
||||
if hit:
|
||||
embeds.append(f"{hit.group(1)}-{hit.group(2)}")
|
||||
for m in FIG_IN_TEXT.finditer(text):
|
||||
fig_refs.append(f"{m.group(1)}-{m.group(2)}")
|
||||
for m in TAB_IN_TEXT.finditer(text):
|
||||
tab_refs.append(f"{m.group(1)}-{m.group(2)}")
|
||||
# 加粗题注单独记一份,便于区分「题注」与「正文提及」。
|
||||
# 必须锚在行首:正文里「...** 表 4-12 中的 ...」这种"加粗结束后提到表号"的写法
|
||||
# 会把加粗收尾的 ** 误当题注起始,产生假重号(真实项目里踩过)。
|
||||
for m in re.finditer(r"^[ \t]{0,3}\*\*\s*表\s*(\d+)\s*[-–—.]\s*(\d+)", text, re.M):
|
||||
tab_caps.append(f"{m.group(1)}-{m.group(2)}")
|
||||
return embeds, fig_refs, tab_caps, tab_refs
|
||||
|
||||
|
||||
def continuity(ids, label: str):
|
||||
"""按章号分组检查序号连续;返回 (问题列表, 摘要)。"""
|
||||
problems = []
|
||||
by_ch: dict[int, list[int]] = {}
|
||||
for i in ids:
|
||||
ch, no = i.split("-")
|
||||
by_ch.setdefault(int(ch), []).append(int(no))
|
||||
for ch in sorted(by_ch):
|
||||
nums = sorted(set(by_ch[ch]))
|
||||
dups = sorted({n for n in by_ch[ch] if by_ch[ch].count(n) > 1})
|
||||
if dups:
|
||||
problems.append(f"{label} {ch}-{dups} 重号(同一编号被引用多次属正常,仅作提示)")
|
||||
if not nums:
|
||||
continue
|
||||
missing = [n for n in range(1, max(nums) + 1) if n not in by_ch[ch]]
|
||||
if missing:
|
||||
problems.append(f"{label} 第 {ch} 章缺号:{missing}(已见 {nums})")
|
||||
summary = " ".join(f"{c}:1..{max(by_ch[c])}" for c in sorted(by_ch)) if by_ch else "(无)"
|
||||
return problems, summary
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="统计分章 md 的中文字数与图表编号连续性",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="示例:python scripts/wordcount.py --dir manuscript --min 20000",
|
||||
)
|
||||
ap.add_argument("--dir", default="manuscript", help="分章 md 目录(默认 manuscript)")
|
||||
ap.add_argument("--glob", default="*.md", help="文件匹配模式(默认 *.md)")
|
||||
ap.add_argument("--min", type=int, default=0, help="字数下限;0 表示不设闸门")
|
||||
ap.add_argument("--json", dest="json_out", default="", help="把结果写成 JSON")
|
||||
ap.add_argument("--quiet", action="store_true", help="只输出合计与问题")
|
||||
ap.add_argument("--allow-gap", action="store_true", help="有缺号也返回 0(仅报告)")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not os.path.isdir(args.dir):
|
||||
print(f"[wordcount] 目录不存在:{args.dir}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
files = sorted(glob.glob(os.path.join(args.dir, args.glob)))
|
||||
if not files:
|
||||
print(f"[wordcount] {args.dir} 下没有匹配 {args.glob} 的文件", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
rows, total = [], 0
|
||||
fig_all, tab_all, fig_ref_all, tab_ref_all = [], [], [], []
|
||||
for path in files:
|
||||
text = read_text(path)
|
||||
cjk = body_chars(text)
|
||||
embeds, fig_refs, tab_caps, tab_refs = collect(text)
|
||||
total += cjk
|
||||
fig_all += embeds
|
||||
tab_all += tab_caps
|
||||
fig_ref_all += fig_refs
|
||||
tab_ref_all += tab_refs
|
||||
rows.append({
|
||||
"file": os.path.basename(path),
|
||||
"chars": cjk,
|
||||
"figures": len(embeds),
|
||||
"tables": len(tab_caps),
|
||||
"fig_ids": sorted(set(embeds)),
|
||||
"tab_ids": sorted(set(tab_caps)),
|
||||
})
|
||||
|
||||
if not args.quiet:
|
||||
print(f"{'文件':<36}{'中文字符':>10}{'图':>5}{'表':>5}")
|
||||
print("-" * 58)
|
||||
for r in rows:
|
||||
print(f"{r['file']:<36}{r['chars']:>10}{r['figures']:>5}{r['tables']:>5}")
|
||||
print("-" * 58)
|
||||
print(f"{'合计':<36}{total:>10}{len(set(fig_all)):>5}{len(set(tab_all)):>5}")
|
||||
|
||||
problems: list[str] = []
|
||||
fig_problems, fig_summary = continuity(fig_all, "图")
|
||||
tab_problems, tab_summary = continuity(tab_all, "表")
|
||||
problems += fig_problems
|
||||
problems += tab_problems
|
||||
|
||||
# 图表「有编号但正文从未提及」= 悬空题注;「正文提及但无对应题注」= 悬空引用
|
||||
orphan_fig = sorted(set(fig_all) - set(fig_ref_all))
|
||||
missing_fig = sorted(set(fig_ref_all) - set(fig_all))
|
||||
orphan_tab = sorted(set(tab_all) - set(tab_ref_all))
|
||||
missing_tab = sorted(set(tab_ref_all) - set(tab_all))
|
||||
|
||||
if total < args.min:
|
||||
problems.append(f"字数 {total} 低于下限 {args.min}")
|
||||
|
||||
print()
|
||||
print(f"图编号(题注):{fig_summary}")
|
||||
print(f"表编号(题注):{tab_summary}")
|
||||
if orphan_fig:
|
||||
print(f"图题注未被正文提及:{orphan_fig}")
|
||||
if missing_fig:
|
||||
print(f"正文提到但无图:{missing_fig}")
|
||||
if orphan_tab:
|
||||
print(f"表题注未被正文提及:{orphan_tab}")
|
||||
if missing_tab:
|
||||
print(f"正文提到但无表:{missing_tab}")
|
||||
|
||||
if problems:
|
||||
print()
|
||||
print("问题:")
|
||||
for p in problems:
|
||||
print(" - " + p)
|
||||
|
||||
if args.json_out:
|
||||
with open(args.json_out, "w", encoding="utf-8") as f:
|
||||
json.dump({
|
||||
"dir": os.path.abspath(args.dir),
|
||||
"files": rows,
|
||||
"total_chars": total,
|
||||
"figures": sorted(set(fig_all)),
|
||||
"tables": sorted(set(tab_all)),
|
||||
"problems": problems,
|
||||
"orphan_figures": orphan_fig,
|
||||
"missing_figures": missing_fig,
|
||||
"orphan_tables": orphan_tab,
|
||||
"missing_tables": missing_tab,
|
||||
"pass": not problems,
|
||||
}, f, ensure_ascii=False, indent=1)
|
||||
print(f"\n[wordcount] JSON 报告:{args.json_out}")
|
||||
|
||||
hard_fail = [p for p in problems if "缺号" in p or "低于下限" in p]
|
||||
if hard_fail and not args.allow_gap:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user