@orbit-build/cli 0.4.4 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/commands/math-draft.md +11 -0
  2. package/dist/index.js +271 -40
  3. package/package.json +4 -2
  4. package/skills/math-model-draft/SKILL.md +216 -0
  5. package/skills/math-model-draft/agents/openai.yaml +6 -0
  6. package/skills/math-model-draft/assets/project-template/code/always/__init__.py +1 -0
  7. package/skills/math-model-draft/assets/project-template/code/always/config.py +17 -0
  8. package/skills/math-model-draft/assets/project-template/code/always/data.py +23 -0
  9. package/skills/math-model-draft/assets/project-template/code/always/plotting.py +24 -0
  10. package/skills/math-model-draft/assets/project-template/code/always/validation.py +20 -0
  11. package/skills/math-model-draft/assets/project-template/code/finalize.py +55 -0
  12. package/skills/math-model-draft/assets/project-template/code/requirements.txt +11 -0
  13. package/skills/math-model-draft/assets/project-template/paper/AI/345/267/245/345/205/267/344/275/277/347/224/250/350/257/246/346/203/205.tex +34 -0
  14. package/skills/math-model-draft/assets/project-template/paper/ai-use-log.md +7 -0
  15. package/skills/math-model-draft/assets/project-template/paper/contest-profile.json +25 -0
  16. package/skills/math-model-draft/assets/project-template/paper/main.tex +53 -0
  17. package/skills/math-model-draft/assets/project-template/paper/sections/abstract.tex +6 -0
  18. package/skills/math-model-draft/assets/project-template/paper/sections/ai-disclosure.tex +3 -0
  19. package/skills/math-model-draft/assets/project-template/paper/sections/appendix.tex +9 -0
  20. package/skills/math-model-draft/assets/project-template/paper/sections/assumptions.tex +5 -0
  21. package/skills/math-model-draft/assets/project-template/paper/sections/data.tex +19 -0
  22. package/skills/math-model-draft/assets/project-template/paper/sections/evaluation.tex +9 -0
  23. package/skills/math-model-draft/assets/project-template/paper/sections/problem-analysis.tex +3 -0
  24. package/skills/math-model-draft/assets/project-template/paper/sections/problem-restatement.tex +3 -0
  25. package/skills/math-model-draft/assets/project-template/paper/sections/references.tex +6 -0
  26. package/skills/math-model-draft/assets/project-template/paper/sections/source-code.tex +1 -0
  27. package/skills/math-model-draft/assets/project-template/paper/sections/support-files.tex +3 -0
  28. package/skills/math-model-draft/references/code-and-output-style.md +91 -0
  29. package/skills/math-model-draft/references/cumcm-compliance.md +56 -0
  30. package/skills/math-model-draft/references/latex-figures-tables.md +60 -0
  31. package/skills/math-model-draft/references/modeling-quality.md +91 -0
  32. package/skills/math-model-draft/references/paper-architecture.md +125 -0
  33. package/skills/math-model-draft/references/paper-revision.md +76 -0
  34. package/skills/math-model-draft/references/project-architecture.md +65 -0
  35. package/skills/math-model-draft/scripts/audit_paper.py +185 -0
  36. package/skills/math-model-draft/scripts/bootstrap_project.py +275 -0
  37. package/skills/math-model-draft/scripts/build_paper.py +226 -0
  38. package/skills/math-model-draft/scripts/capture_environment.py +46 -0
  39. package/skills/math-model-draft/scripts/clean_project.py +46 -0
  40. package/skills/math-model-draft/scripts/finalize_project.py +49 -0
  41. package/skills/math-model-draft/scripts/inspect_inputs.py +193 -0
  42. package/skills/math-model-draft/scripts/package_support.py +52 -0
  43. package/skills/math-model-draft/scripts/project_utils.py +106 -0
  44. package/skills/math-model-draft/scripts/validate_project.py +313 -0
@@ -0,0 +1,226 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ from project_utils import iter_regular_files, load_profile, numeric_limit
10
+
11
+
12
+ EXCLUDED_PARTS = {"__pycache__", ".pytest_cache", ".mypy_cache", "build"}
13
+ CODE_SUFFIXES = {".py", ".r", ".jl", ".m", ".cpp", ".c", ".h"}
14
+ BUILD_ARTIFACT_SUFFIXES = {
15
+ ".aux",
16
+ ".bbl",
17
+ ".bcf",
18
+ ".blg",
19
+ ".fdb_latexmk",
20
+ ".fls",
21
+ ".log",
22
+ ".out",
23
+ ".pdf",
24
+ ".run.xml",
25
+ ".toc",
26
+ ".xdv",
27
+ }
28
+
29
+
30
+ def tex_path(path: str) -> str:
31
+ return path.replace("\\", "/").replace("%", r"\%").replace("#", r"\#")
32
+
33
+
34
+ def tex_text(value: str) -> str:
35
+ escaped = value.replace("\\", "/")
36
+ for character, replacement in (("&", r"\&"), ("%", r"\%"), ("$", r"\$"), ("#", r"\#"), ("_", r"\_"), ("{", r"\{"), ("}", r"\}"), ("~", r"\textasciitilde{}"), ("^", r"\textasciicircum{}")):
37
+ escaped = escaped.replace(character, replacement)
38
+ return escaped
39
+
40
+
41
+ def tex_breakable_path(value: str) -> str:
42
+ escaped = tex_text(value)
43
+ escaped = escaped.replace("/", "/\\allowbreak{}")
44
+ escaped = escaped.replace(r"\_", r"\_\allowbreak{}")
45
+ escaped = escaped.replace("-", "-\\allowbreak{}")
46
+ return f"\\texttt{{{escaped}}}"
47
+
48
+
49
+ def generate_appendices(root: Path, profile: dict[str, object]) -> None:
50
+ sections = root / "paper" / "sections"
51
+ sections.mkdir(parents=True, exist_ok=True)
52
+ paper_profile = profile["paper"]
53
+ assert isinstance(paper_profile, dict)
54
+
55
+ support_path = sections / "support-files.tex"
56
+ if bool(paper_profile.get("include_support_file_list")):
57
+ support = []
58
+ for directory in ("code", "results", "figures"):
59
+ support.extend(path.relative_to(root).as_posix() for path in iter_regular_files(root, directory, EXCLUDED_PARTS))
60
+ ai_pdf = root / "paper" / "AI工具使用详情.pdf"
61
+ if ai_pdf.is_file():
62
+ support.append("paper/AI工具使用详情.pdf")
63
+ rows = ["\\begin{itemize}"] + [f" \\item {tex_breakable_path(path)}" for path in sorted(set(support))] + ["\\end{itemize}"]
64
+ support_path.write_text("\n".join(rows) + "\n", encoding="utf-8")
65
+ else:
66
+ support_path.write_text("% Disabled by paper/contest-profile.json.\n", encoding="utf-8")
67
+
68
+ source_path = sections / "source-code.tex"
69
+ if bool(paper_profile.get("include_source_appendix")):
70
+ listings = []
71
+ for path in iter_regular_files(root, "code", EXCLUDED_PARTS):
72
+ if path.suffix.lower() not in CODE_SUFFIXES:
73
+ continue
74
+ relative = (Path("..") / path.relative_to(root)).as_posix()
75
+ display = path.relative_to(root).as_posix()
76
+ listings.extend([f"\\noindent\\textbf{{程序文件}}\\quad {tex_breakable_path(display)}\\par", "\\VerbatimInput[fontsize=\\scriptsize,breaklines=true," f"breakanywhere=true]{{{tex_path(relative)}}}"])
77
+ source_path.write_text("\n\n".join(listings) + "\n", encoding="utf-8")
78
+ else:
79
+ source_path.write_text("% Disabled by paper/contest-profile.json.\n", encoding="utf-8")
80
+
81
+
82
+ def find_engine() -> tuple[list[str], str]:
83
+ latexmk = shutil.which("latexmk")
84
+ if latexmk:
85
+ return [latexmk, "-xelatex", "-interaction=nonstopmode", "-halt-on-error", "-file-line-error", "-outdir=build", "main.tex"], "latexmk"
86
+ xelatex = shutil.which("xelatex")
87
+ if xelatex:
88
+ return [xelatex, "-interaction=nonstopmode", "-halt-on-error", "-file-line-error", "-output-directory=build", "main.tex"], "xelatex"
89
+ raise SystemExit("Neither latexmk nor xelatex is available on PATH (TeX Live required).")
90
+
91
+
92
+ def run(command: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:
93
+ return subprocess.run(command, cwd=cwd, text=True, encoding="utf-8", errors="replace", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False)
94
+
95
+
96
+ def audit_log(log_path: Path, strict_layout: bool) -> None:
97
+ if not log_path.is_file():
98
+ raise SystemExit(f"TeX log is missing: {log_path}")
99
+ log = log_path.read_text(encoding="utf-8", errors="replace")
100
+ checks: dict[str, tuple[str, ...]] = {
101
+ "undefined cross-reference or citation": (r"LaTeX Warning:.*(?:undefined|multiply defined)", r"There were undefined references"),
102
+ "missing glyph": (r"Missing character:",),
103
+ "overfull box": (r"Overfull \\[hv]box",),
104
+ }
105
+ if strict_layout:
106
+ checks["underfull box"] = (r"Underfull \\[hv]box",)
107
+ failures = [label for label, patterns in checks.items() if any(re.search(pattern, log, re.IGNORECASE) for pattern in patterns)]
108
+ if failures:
109
+ log_lines = log.splitlines()
110
+ hit_indices = [index for index, line in enumerate(log_lines) if re.search(r"(?:Overfull|Underfull|Missing character|undefined|multiply defined)", line, re.IGNORECASE)]
111
+ selected: set[int] = set()
112
+ for index in hit_indices[-6:]:
113
+ selected.update(range(max(0, index - 3), min(len(log_lines), index + 4)))
114
+ diagnostics = "\n".join(log_lines[index] for index in sorted(selected))
115
+ raise SystemExit("TeX quality audit failed: " + ", ".join(failures) + f". Inspect {log_path}\n{diagnostics}")
116
+
117
+
118
+ def clear_entry_build_artifacts(paper: Path, source_name: str) -> None:
119
+ """Remove only deterministic outputs for one TeX entry point."""
120
+ build = paper / "build"
121
+ stem = Path(source_name).stem
122
+ for suffix in BUILD_ARTIFACT_SUFFIXES:
123
+ target = build / f"{stem}{suffix}"
124
+ if target.is_symlink():
125
+ raise SystemExit(f"Symbolic TeX build artifacts are not allowed: {target}")
126
+ if target.is_file():
127
+ target.unlink()
128
+
129
+
130
+ def tex_failure_diagnostics(log_path: Path, process_output: str) -> str:
131
+ """Extract actionable file/line errors instead of dumping latexmk noise."""
132
+ sources = []
133
+ if log_path.is_file():
134
+ sources.append(log_path.read_text(encoding="utf-8", errors="replace"))
135
+ sources.append(process_output)
136
+ lines = "\n".join(sources).splitlines()
137
+ hits: list[int] = []
138
+ patterns = (
139
+ r"^\s*[^\s].*:\d+:\s*(?:LaTeX Error|Package .* Error|Undefined control sequence|Missing \$|Extra alignment|File .* not found)",
140
+ r"^\s*!\s+(?:LaTeX Error|Package .* Error|Undefined control sequence|Missing \$|Extra alignment|Emergency stop)",
141
+ r"^\s*\*\*\* \(job aborted",
142
+ )
143
+ for index, line in enumerate(lines):
144
+ if any(re.search(pattern, line, re.IGNORECASE) for pattern in patterns):
145
+ hits.append(index)
146
+ if not hits:
147
+ return "\n".join(process_output.splitlines()[-24:])
148
+ selected: set[int] = set()
149
+ for index in hits[:4]:
150
+ selected.update(range(max(0, index - 2), min(len(lines), index + 5)))
151
+ return "\n".join(lines[index] for index in sorted(selected))
152
+
153
+
154
+ def build_tex(paper: Path, source_name: str, output_name: str, strict_layout: bool) -> tuple[str, Path]:
155
+ source = paper / source_name
156
+ if source.is_symlink():
157
+ raise SystemExit(f"Symbolic TeX entry points are not allowed: {source}")
158
+ clear_entry_build_artifacts(paper, source_name)
159
+ command, engine = find_engine()
160
+ command[-1] = source_name
161
+ completed = run(command, paper)
162
+ if completed.returncode == 0 and engine == "xelatex":
163
+ completed = run(command, paper)
164
+ if completed.returncode != 0:
165
+ stem = Path(source_name).stem
166
+ log_path = paper / "build" / f"{stem}.log"
167
+ diagnostics = tex_failure_diagnostics(log_path, completed.stdout)
168
+ raise SystemExit(
169
+ f"TeX build failed ({engine}, {source_name}). "
170
+ f"Repair the first reported source error and rerun the finalizer.\n{diagnostics}"
171
+ )
172
+ stem = Path(source_name).stem
173
+ built = paper / "build" / f"{stem}.pdf"
174
+ audit_log(paper / "build" / f"{stem}.log", strict_layout)
175
+ if not built.is_file():
176
+ raise SystemExit(f"TeX reported success but did not create {built}")
177
+ final = paper / output_name
178
+ shutil.copy2(built, final)
179
+ return engine, final
180
+
181
+
182
+ def check_size(path: Path, maximum_mb: float | None, label: str) -> float:
183
+ size_mb = path.stat().st_size / (1024 * 1024)
184
+ if maximum_mb is not None and size_mb > maximum_mb:
185
+ raise SystemExit(f"{label} is {size_mb:.2f} MB; active profile limit is {maximum_mb:g} MB.")
186
+ return size_mb
187
+
188
+
189
+ def main() -> None:
190
+ parser = argparse.ArgumentParser(description="Build the paper and AI-use disclosure with local TeX Live.")
191
+ parser.add_argument("project_root", type=Path)
192
+ parser.add_argument("--strict-layout", action="store_true", help="fail on both overfull and underfull boxes")
193
+ args = parser.parse_args()
194
+ root = args.project_root.resolve()
195
+ paper = root / "paper"
196
+ if not (paper / "main.tex").is_file():
197
+ raise SystemExit(f"Missing paper entry point: {paper / 'main.tex'}")
198
+ try:
199
+ profile = load_profile(root)
200
+ pdf_limit = numeric_limit(profile["paper"], "max_pdf_mb")
201
+ except (ValueError, TypeError) as error:
202
+ raise SystemExit(str(error)) from error
203
+ (paper / "build").mkdir(parents=True, exist_ok=True)
204
+
205
+ ai_profile = profile["ai"]
206
+ assert isinstance(ai_profile, dict)
207
+ ai_message = ""
208
+ if bool(ai_profile.get("used")) and bool(ai_profile.get("details_pdf_required")):
209
+ ai_source = paper / "AI工具使用详情.tex"
210
+ if not ai_source.is_file():
211
+ raise SystemExit("Active profile requires paper/AI工具使用详情.tex")
212
+ _, ai_pdf = build_tex(paper, ai_source.name, "AI工具使用详情.pdf", args.strict_layout)
213
+ ai_size = check_size(ai_pdf, pdf_limit, "AI disclosure")
214
+ ai_message = f"\n AI disclosure: {ai_pdf} ({ai_size:.2f} MB)"
215
+
216
+ try:
217
+ generate_appendices(root, profile)
218
+ except ValueError as error:
219
+ raise SystemExit(str(error)) from error
220
+ engine, final = build_tex(paper, "main.tex", "main.pdf", args.strict_layout)
221
+ size_mb = check_size(final, pdf_limit, "Paper PDF")
222
+ print(f"[OK] Paper built with {engine}: {final} ({size_mb:.2f} MB){ai_message}")
223
+
224
+
225
+ if __name__ == "__main__":
226
+ main()
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import importlib.metadata
5
+ import json
6
+ import platform
7
+ import sys
8
+ from pathlib import Path
9
+
10
+
11
+ def main() -> None:
12
+ parser = argparse.ArgumentParser(description="Capture the reproducibility environment.")
13
+ parser.add_argument("project_root", type=Path)
14
+ args = parser.parse_args()
15
+ root = args.project_root.resolve()
16
+ requirements = root / "code" / "requirements.txt"
17
+ requested: list[str] = []
18
+ if requirements.is_file():
19
+ for raw in requirements.read_text(encoding="utf-8").splitlines():
20
+ line = raw.strip()
21
+ if line and not line.startswith("#"):
22
+ requested.append(line)
23
+ packages: dict[str, str | None] = {}
24
+ for requirement in requested:
25
+ name = requirement.split(";", 1)[0].strip()
26
+ for marker in ("==", ">=", "<=", "~=", "!=", ">", "<", "["):
27
+ name = name.split(marker, 1)[0].strip()
28
+ try:
29
+ packages[name] = importlib.metadata.version(name)
30
+ except importlib.metadata.PackageNotFoundError:
31
+ packages[name] = None
32
+ payload = {
33
+ "schema_version": 1,
34
+ "python": sys.version,
35
+ "executable": sys.executable,
36
+ "platform": platform.platform(),
37
+ "packages": packages,
38
+ }
39
+ output = root / "results" / "environment.json"
40
+ output.parent.mkdir(parents=True, exist_ok=True)
41
+ output.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
42
+ print(f"[OK] Environment captured: {output}")
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+
8
+ CACHE_DIR_NAMES = {"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache"}
9
+ TEX_CACHE_SUFFIXES = {".aux", ".bbl", ".bcf", ".blg", ".fdb_latexmk", ".fls", ".log", ".out", ".run.xml", ".synctex.gz", ".toc", ".xdv"}
10
+
11
+
12
+ def targets(root: Path) -> list[Path]:
13
+ found: set[Path] = set()
14
+ for path in root.rglob("*"):
15
+ if path.is_symlink():
16
+ continue
17
+ if path.is_dir() and path.name in CACHE_DIR_NAMES:
18
+ found.add(path)
19
+ elif path.is_file() and any(path.name.endswith(suffix) for suffix in TEX_CACHE_SUFFIXES):
20
+ if "paper" in path.relative_to(root).parts:
21
+ found.add(path)
22
+ page_review = root / "paper" / "build" / "page-review"
23
+ if page_review.is_dir() and not page_review.is_symlink():
24
+ found.add(page_review)
25
+ return sorted(found, key=lambda path: (len(path.parts), str(path)), reverse=True)
26
+
27
+
28
+ def main() -> None:
29
+ parser = argparse.ArgumentParser(description="Remove only deterministic caches and temporary PDF page renders.")
30
+ parser.add_argument("project_root", type=Path)
31
+ parser.add_argument("--apply", action="store_true", help="perform deletion; default is dry run")
32
+ args = parser.parse_args()
33
+ root = args.project_root.resolve()
34
+ selected = targets(root)
35
+ for path in selected:
36
+ print(f"[{'REMOVE' if args.apply else 'DRY-RUN'}] {path.relative_to(root)}")
37
+ if args.apply:
38
+ if path.is_dir():
39
+ shutil.rmtree(path)
40
+ elif path.exists():
41
+ path.unlink()
42
+ print(f"[OK] {'Removed' if args.apply else 'Identified'} {len(selected)} cache/render target(s); final PDFs and source artifacts preserved")
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+
9
+ SCRIPT_ROOT = Path(__file__).resolve().parent
10
+
11
+
12
+ def run(script: str, root: Path, *flags: str) -> None:
13
+ command = [sys.executable, str(SCRIPT_ROOT / script), str(root), *flags]
14
+ completed = subprocess.run(command, check=False)
15
+ if completed.returncode:
16
+ raise SystemExit(f"Finalization stopped because {script} failed with exit code {completed.returncode}.")
17
+
18
+
19
+ def main() -> None:
20
+ parser = argparse.ArgumentParser(description="One-command execution, build, audit, package, and strict validation.")
21
+ parser.add_argument("project_root", type=Path)
22
+ parser.add_argument("--run-code", action="store_true", help="run code/run_all.py before building")
23
+ parser.add_argument("--strict-layout", action="store_true", help="fail on TeX underfull boxes as well as overfull boxes")
24
+ parser.add_argument("--render-pages", action="store_true", help="render every final PDF page for visual review")
25
+ parser.add_argument("--clean", action="store_true", help="remove deterministic caches after validation")
26
+ args = parser.parse_args()
27
+ root = args.project_root.resolve()
28
+ if args.run_code:
29
+ entry = root / "code" / "run_all.py"
30
+ if not entry.is_file():
31
+ raise SystemExit(f"Missing code entry point: {entry}")
32
+ completed = subprocess.run([sys.executable, str(entry)], cwd=root / "code", check=False)
33
+ if completed.returncode:
34
+ raise SystemExit("code/run_all.py failed; paper was not rebuilt from stale evidence.")
35
+ run("capture_environment.py", root)
36
+ run("build_paper.py", root, *(["--strict-layout"] if args.strict_layout else []))
37
+ audit_flags = ["--fail-on-errors"]
38
+ if args.render_pages:
39
+ audit_flags.append("--render-pages")
40
+ run("audit_paper.py", root, *audit_flags)
41
+ run("package_support.py", root)
42
+ run("validate_project.py", root, "--strict")
43
+ if args.clean:
44
+ run("clean_project.py", root, "--apply")
45
+ print(f"[OK] Complete modeling-paper delivery finalized: {root / 'paper' / 'main.pdf'}")
46
+
47
+
48
+ if __name__ == "__main__":
49
+ main()
@@ -0,0 +1,193 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import hashlib
6
+ import json
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import zipfile
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from xml.etree import ElementTree
14
+
15
+
16
+ SUPPORTED = {".pdf", ".doc", ".docx", ".csv", ".tsv", ".xls", ".xlsx"}
17
+
18
+
19
+ def sha256(path: Path) -> str:
20
+ digest = hashlib.sha256()
21
+ with path.open("rb") as stream:
22
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
23
+ digest.update(chunk)
24
+ return digest.hexdigest()
25
+
26
+
27
+ def result(status: str, **details: Any) -> dict[str, Any]:
28
+ return {"status": status, **details}
29
+
30
+
31
+ def inspect_delimited(path: Path) -> dict[str, Any]:
32
+ delimiter = "\t" if path.suffix.lower() == ".tsv" else ","
33
+ for encoding in ("utf-8-sig", "gb18030"):
34
+ rows = columns = nonblank = 0
35
+ preview: list[list[str]] = []
36
+ try:
37
+ with path.open("r", encoding=encoding, newline="") as stream:
38
+ for row in csv.reader(stream, delimiter=delimiter):
39
+ rows += 1
40
+ columns = max(columns, len(row))
41
+ nonblank += sum(bool(cell.strip()) for cell in row)
42
+ if len(preview) < 20:
43
+ preview.append(row[:20])
44
+ return result("ok", rows=rows, columns=columns, blank=nonblank == 0, encoding=encoding, preview=preview)
45
+ except UnicodeDecodeError:
46
+ continue
47
+ return result("manual_review", reason="text encoding could not be resolved")
48
+
49
+
50
+ def inspect_xlsx(path: Path) -> dict[str, Any]:
51
+ try:
52
+ import openpyxl
53
+ except ImportError:
54
+ return inspect_xlsx_xml(path)
55
+ workbook = openpyxl.load_workbook(path, read_only=True, data_only=False)
56
+ sheets: list[dict[str, Any]] = []
57
+ try:
58
+ for sheet in workbook.worksheets:
59
+ nonblank = sum(cell.value not in (None, "") for row in sheet.iter_rows() for cell in row)
60
+ preview = [[cell.value for cell in row[:20]] for row in list(sheet.iter_rows(max_row=20))[:20]]
61
+ sheets.append({"name": sheet.title, "rows": sheet.max_row, "columns": sheet.max_column, "nonblank_cells": nonblank, "blank": nonblank == 0, "preview": preview})
62
+ finally:
63
+ workbook.close()
64
+ return result("ok", sheets=sheets, blank=all(item["blank"] for item in sheets))
65
+
66
+
67
+ def inspect_xlsx_xml(path: Path) -> dict[str, Any]:
68
+ try:
69
+ with zipfile.ZipFile(path) as archive:
70
+ workbook = ElementTree.fromstring(archive.read("xl/workbook.xml"))
71
+ namespace = {"x": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
72
+ names = [node.attrib.get("name", "unknown") for node in workbook.findall("x:sheets/x:sheet", namespace)]
73
+ worksheets = sorted(name for name in archive.namelist() if name.startswith("xl/worksheets/sheet") and name.endswith(".xml"))
74
+ sheets = []
75
+ for index, member in enumerate(worksheets):
76
+ sheet_root = ElementTree.fromstring(archive.read(member))
77
+ cells = sheet_root.findall(".//x:c", namespace)
78
+ nonblank = sum(cell.find("x:f", namespace) is not None or cell.find("x:v", namespace) is not None or bool(cell.findall(".//x:t", namespace)) for cell in cells)
79
+ sheets.append({"name": names[index] if index < len(names) else member, "nonblank_cells": nonblank, "blank": nonblank == 0})
80
+ return result("ok", sheets=sheets, blank=all(item["blank"] for item in sheets), inspection="OOXML fallback")
81
+ except (KeyError, zipfile.BadZipFile, ElementTree.ParseError) as error:
82
+ return result("manual_review", reason=f"invalid XLSX container: {error}")
83
+
84
+
85
+ def inspect_xls(path: Path) -> dict[str, Any]:
86
+ try:
87
+ import xlrd
88
+ except ImportError:
89
+ return result("dependency_missing", dependency="xlrd", reason="install code/requirements.txt")
90
+ try:
91
+ workbook = xlrd.open_workbook(path, on_demand=True)
92
+ sheets = []
93
+ for sheet in workbook.sheets():
94
+ nonblank = sum(bool(str(sheet.cell_value(row, col)).strip()) for row in range(sheet.nrows) for col in range(sheet.ncols))
95
+ sheets.append({"name": sheet.name, "rows": sheet.nrows, "columns": sheet.ncols, "nonblank_cells": nonblank, "blank": nonblank == 0})
96
+ workbook.release_resources()
97
+ return result("ok", sheets=sheets, blank=all(item["blank"] for item in sheets))
98
+ except (OSError, xlrd.XLRDError) as error:
99
+ return result("manual_review", reason=f"legacy workbook could not be read: {error}")
100
+
101
+
102
+ def inspect_docx(path: Path) -> dict[str, Any]:
103
+ try:
104
+ with zipfile.ZipFile(path) as archive:
105
+ root = ElementTree.fromstring(archive.read("word/document.xml"))
106
+ except (KeyError, zipfile.BadZipFile, ElementTree.ParseError) as error:
107
+ return result("manual_review", reason=f"invalid DOCX container: {error}")
108
+ text = "".join(node.text or "" for node in root.iter() if node.tag.endswith("}t")).strip()
109
+ return result("ok", characters=len(text), blank=not text, text_excerpt=text[:50000])
110
+
111
+
112
+ def inspect_doc(path: Path) -> dict[str, Any]:
113
+ tool = shutil.which("antiword")
114
+ if not tool:
115
+ return result("dependency_missing", dependency="antiword or LibreOffice", reason="legacy .doc requires conversion or extraction")
116
+ completed = subprocess.run([tool, str(path)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
117
+ text = completed.stdout.decode("utf-8", errors="replace").strip()
118
+ return result("ok" if completed.returncode == 0 else "manual_review", characters=len(text), blank=not text, text_excerpt=text[:50000])
119
+
120
+
121
+ def inspect_pdf(path: Path) -> dict[str, Any]:
122
+ try:
123
+ from pypdf import PdfReader
124
+ except ImportError:
125
+ pdfinfo = shutil.which("pdfinfo")
126
+ if not pdfinfo:
127
+ return result("dependency_missing", dependency="pypdf or Poppler", reason="cannot inspect PDF text/scans")
128
+ completed = subprocess.run([pdfinfo, str(path)], text=True, encoding="utf-8", errors="replace", stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False)
129
+ match = re.search(r"^Pages:\s+(\d+)", completed.stdout, re.MULTILINE)
130
+ return result("manual_review", pages=int(match.group(1)) if match else None, reason="text/scanned status not inspected")
131
+ try:
132
+ reader = PdfReader(path)
133
+ extracted = "".join((page.extract_text() or "") for page in reader.pages[: min(5, len(reader.pages))]).strip()
134
+ except Exception as error: # pypdf exposes several parser-specific exceptions.
135
+ return result("manual_review", reason=f"PDF extraction failed: {error}")
136
+ likely_scanned = len(extracted) < max(80, min(300, len(reader.pages) * 30))
137
+ return result("requires_ocr" if likely_scanned else "ok", pages=len(reader.pages), sampled_characters=len(extracted), likely_scanned=likely_scanned, text_excerpt=extracted[:50000])
138
+
139
+
140
+ def inspect_file(path: Path) -> dict[str, Any]:
141
+ suffix = path.suffix.lower()
142
+ if suffix in {".csv", ".tsv"}:
143
+ return inspect_delimited(path)
144
+ if suffix == ".xlsx":
145
+ return inspect_xlsx(path)
146
+ if suffix == ".xls":
147
+ return inspect_xls(path)
148
+ if suffix == ".docx":
149
+ return inspect_docx(path)
150
+ if suffix == ".doc":
151
+ return inspect_doc(path)
152
+ if suffix == ".pdf":
153
+ return inspect_pdf(path)
154
+ return result("unsupported", reason=f"unsupported extension {suffix or '[none]'}")
155
+
156
+
157
+ def main() -> None:
158
+ parser = argparse.ArgumentParser(description="Inventory immutable question inputs.")
159
+ parser.add_argument("project_root", type=Path)
160
+ parser.add_argument("--refresh-baseline", action="store_true")
161
+ args = parser.parse_args()
162
+ root = args.project_root.resolve()
163
+ question = root / "question"
164
+ if not question.is_dir() or question.is_symlink():
165
+ raise SystemExit(f"Missing or unsafe question directory: {question}")
166
+
167
+ entries = []
168
+ for path in sorted(question.rglob("*")):
169
+ if path.is_symlink():
170
+ raise SystemExit(f"Symbolic links are not allowed in immutable input: {path}")
171
+ if path.is_file():
172
+ details = inspect_file(path)
173
+ entries.append({"path": path.relative_to(root).as_posix(), "size_bytes": path.stat().st_size, "sha256": sha256(path), "supported": path.suffix.lower() in SUPPORTED, "status": details["status"], "details": details})
174
+
175
+ paper = root / "paper"
176
+ paper.mkdir(parents=True, exist_ok=True)
177
+ inventory = paper / "input-inventory.json"
178
+ inventory.write_text(json.dumps({"schema_version": 1, "files": entries}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
179
+ baseline = paper / "question-fingerprint.json"
180
+ baseline_state = "preserved"
181
+ if args.refresh_baseline or not baseline.exists():
182
+ baseline.write_text(json.dumps({"schema_version": 1, "files": [{"path": item["path"], "sha256": item["sha256"]} for item in entries]}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
183
+ baseline_state = "created" if not args.refresh_baseline else "refreshed explicitly"
184
+ print(f"[OK] Inspected {len(entries)} question file(s): {inventory}")
185
+ print(f" Fingerprint baseline {baseline_state}: {baseline}")
186
+ for item in entries:
187
+ blank = item["details"].get("blank")
188
+ note = " (blank; preserve only)" if blank else ""
189
+ print(f" [{item['status']}] {item['path']}: {item['size_bytes']} bytes{note}")
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import zipfile
5
+ from pathlib import Path
6
+
7
+ from project_utils import iter_regular_files, load_profile, numeric_limit
8
+
9
+
10
+ EXCLUDED_PARTS = {"__pycache__", ".pytest_cache", ".mypy_cache", "build"}
11
+
12
+
13
+ def main() -> None:
14
+ parser = argparse.ArgumentParser(description="Package reproducible support files safely.")
15
+ parser.add_argument("project_root", type=Path)
16
+ args = parser.parse_args()
17
+ root = args.project_root.resolve()
18
+ output = root / "paper" / "support-materials.zip"
19
+ try:
20
+ profile = load_profile(root)
21
+ support_profile = profile["support"]
22
+ assert isinstance(support_profile, dict)
23
+ limit = numeric_limit(support_profile, "max_archive_mb")
24
+ candidates = [path for directory in ("code", "results", "figures") for path in iter_regular_files(root, directory, EXCLUDED_PARTS)]
25
+ except (ValueError, TypeError) as error:
26
+ raise SystemExit(str(error)) from error
27
+
28
+ ai_profile = profile["ai"]
29
+ assert isinstance(ai_profile, dict)
30
+ if bool(ai_profile.get("used")) and bool(ai_profile.get("details_pdf_required")):
31
+ ai_pdf = root / "paper" / "AI工具使用详情.pdf"
32
+ if not ai_pdf.is_file() or ai_pdf.is_symlink():
33
+ raise SystemExit("Active profile requires a built paper/AI工具使用详情.pdf")
34
+ candidates.append(ai_pdf)
35
+ if bool(support_profile.get("include_ai_log")):
36
+ log = root / "paper" / "ai-use-log.md"
37
+ if log.is_file() and not log.is_symlink():
38
+ candidates.append(log)
39
+
40
+ output.parent.mkdir(parents=True, exist_ok=True)
41
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
42
+ for path in sorted(set(candidates)):
43
+ archive.write(path, path.relative_to(root).as_posix())
44
+ size_mb = output.stat().st_size / (1024 * 1024)
45
+ if limit is not None and size_mb > limit:
46
+ output.unlink()
47
+ raise SystemExit(f"Support archive would be {size_mb:.2f} MB; active profile limit is {limit:g} MB.")
48
+ print(f"[OK] Packaged {len(set(candidates))} support file(s): {output} ({size_mb:.2f} MB)")
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()