@louisultra/dsh-verymath 0.0.0-stage → 0.3.2

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 (284) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE.md +35 -0
  4. package/README.md +108 -2
  5. package/README_EN.md +105 -0
  6. package/UPSTREAM.json +106 -0
  7. package/cordis.patch.yml +12 -0
  8. package/docs/capability-examples.md +581 -0
  9. package/docs/examples/README.md +32 -0
  10. package/docs/examples/bad_scan.md +10 -0
  11. package/docs/examples/broken-proof.lean +9 -0
  12. package/docs/examples/claims.md +7 -0
  13. package/docs/examples/knapsack.json +10 -0
  14. package/docs/examples/matrix.json +1 -0
  15. package/docs/examples/points.csv +21 -0
  16. package/docs/examples/qp.json +8 -0
  17. package/docs/examples/research-ws/project/GOALS.yaml +4 -0
  18. package/docs/examples/research-ws/workstreams/ws-lsa/report.md +13 -0
  19. package/docs/examples/research-ws/workstreams/ws-lsa/reviews/r1.json +1 -0
  20. package/docs/examples/research-ws/workstreams/ws-lsa/status.yaml +1 -0
  21. package/docs/examples/source.csv +4 -0
  22. package/lib/core/error.d.ts +20 -0
  23. package/lib/core/error.js +25 -0
  24. package/lib/core/gates.d.ts +42 -0
  25. package/lib/core/gates.js +217 -0
  26. package/lib/core/glossary.d.ts +101 -0
  27. package/lib/core/glossary.js +243 -0
  28. package/lib/core/graph.d.ts +118 -0
  29. package/lib/core/graph.js +460 -0
  30. package/lib/core/index.d.ts +120 -0
  31. package/lib/core/index.js +197 -0
  32. package/lib/core/paper.d.ts +163 -0
  33. package/lib/core/paper.js +73 -0
  34. package/lib/core/paths.d.ts +2 -0
  35. package/lib/core/paths.js +12 -0
  36. package/lib/core/sage.d.ts +61 -0
  37. package/lib/core/sage.js +212 -0
  38. package/lib/core/skills.d.ts +11 -0
  39. package/lib/core/skills.js +110 -0
  40. package/lib/tool/index.d.ts +21 -0
  41. package/lib/tool/index.js +1144 -0
  42. package/package.json +92 -4
  43. package/skills/after-ocr/SKILL.md +123 -0
  44. package/skills/after-ocr/references/audit-schema.md +94 -0
  45. package/skills/after-ocr/references/error-taxonomy.md +179 -0
  46. package/skills/after-ocr/scripts/merge_audit_logs.py +329 -0
  47. package/skills/after-ocr/scripts/scan_markdown_ocr.py +350 -0
  48. package/skills/after-ocr/tests/test_scripts.py +84 -0
  49. package/skills/discover-math-problems/SKILL.md +115 -0
  50. package/skills/discover-math-problems/references/artifact-contract.md +93 -0
  51. package/skills/discover-math-problems/references/autonomous-research-protocol.md +86 -0
  52. package/skills/discover-math-problems/references/conjecture-generation-protocol.md +63 -0
  53. package/skills/discover-math-problems/references/extremal-graph-variants.md +53 -0
  54. package/skills/graph-theory-paper-reading/SKILL.md +600 -0
  55. package/skills/invariant-computation/SKILL.md +169 -0
  56. package/skills/invariant-computation/examples/invariant_summary.example.json +51 -0
  57. package/skills/invariant-computation/manifest.yaml +46 -0
  58. package/skills/invariant-computation/references/INDEX.md +20 -0
  59. package/skills/invariant-computation/references/failure_modes.md +40 -0
  60. package/skills/invariant-computation/references/method_route_map.md +177 -0
  61. package/skills/invariant-computation/references/source_notes.md +19 -0
  62. package/skills/invariant-computation/references/tool_catalog.md +65 -0
  63. package/skills/invariant-computation/references/validation_checks.md +52 -0
  64. package/skills/invariant-computation/schema/invariant_summary.schema.json +260 -0
  65. package/skills/lean-formalization/SKILL.md +111 -0
  66. package/skills/lean-formalization/lean-runtime/config/env.example +5 -0
  67. package/skills/lean-formalization/lean-runtime/config/lean_agent.example.toml +28 -0
  68. package/skills/lean-formalization/lean-runtime/config/numina_runtime.example.toml +12 -0
  69. package/skills/lean-formalization/lean-runtime/examples/smoke/LocalLeanSmoke.lean +7 -0
  70. package/skills/lean-formalization/lean-runtime/prompts/complete_sorries.md +3 -0
  71. package/skills/lean-formalization/lean-runtime/prompts/formalize_statement.md +3 -0
  72. package/skills/lean-formalization/lean-runtime/prompts/prove_theorem.md +3 -0
  73. package/skills/lean-formalization/lean-runtime/prompts/repair_lean_file.md +3 -0
  74. package/skills/lean-formalization/lean-runtime/references/backend_adapter_checklist.md +36 -0
  75. package/skills/lean-formalization/lean-runtime/references/direct_lean_workflow.md +48 -0
  76. package/skills/lean-formalization/lean-runtime/references/failure_taxonomy.md +17 -0
  77. package/skills/lean-formalization/lean-runtime/references/interactive_orchestration.md +83 -0
  78. package/skills/lean-formalization/lean-runtime/references/lean_agent_capability_map.md +116 -0
  79. package/skills/lean-formalization/lean-runtime/references/lean_lsp_mcp_adapter.md +219 -0
  80. package/skills/lean-formalization/lean-runtime/references/lean_runtime_configuration.md +92 -0
  81. package/skills/lean-formalization/lean-runtime/references/numina_reverse_analysis.md +80 -0
  82. package/skills/lean-formalization/lean-runtime/references/numina_runtime.md +41 -0
  83. package/skills/lean-formalization/lean-runtime/references/numina_subagent_troubleshooting.md +77 -0
  84. package/skills/lean-formalization/lean-runtime/references/review_checklist.md +10 -0
  85. package/skills/lean-formalization/lean-runtime/references/specialist_agent_patterns.md +65 -0
  86. package/skills/lean-formalization/lean-runtime/schemas/config.schema.json +12 -0
  87. package/skills/lean-formalization/lean-runtime/schemas/result.schema.json +33 -0
  88. package/skills/lean-formalization/lean-runtime/schemas/task.schema.json +30 -0
  89. package/skills/lean-formalization/lean-runtime/scripts/ai4m_lean.py +222 -0
  90. package/skills/lean-formalization/lean-runtime/scripts/check_lean_project.py +134 -0
  91. package/skills/lean-formalization/lean-runtime/scripts/common.py +296 -0
  92. package/skills/lean-formalization/lean-runtime/scripts/configure_lean.py +222 -0
  93. package/skills/lean-formalization/lean-runtime/scripts/detect_sorry.py +49 -0
  94. package/skills/lean-formalization/lean-runtime/scripts/direct_task.py +100 -0
  95. package/skills/lean-formalization/lean-runtime/scripts/extract_minimal_failure.py +74 -0
  96. package/skills/lean-formalization/lean-runtime/scripts/numina_runtime.py +414 -0
  97. package/skills/lean-formalization/lean-runtime/scripts/smoke_test.py +75 -0
  98. package/skills/lean-formalization/lean-runtime/scripts/tool_status.py +79 -0
  99. package/skills/lean-formalization/lean-runtime/scripts/validate_patch.py +81 -0
  100. package/skills/lean-formalization/lean-runtime/scripts/verify_delivery.py +484 -0
  101. package/skills/lean-formalization/lean-runtime/tests/fixtures/after_bad.lean +4 -0
  102. package/skills/lean-formalization/lean-runtime/tests/fixtures/after_statement_changed.lean +4 -0
  103. package/skills/lean-formalization/lean-runtime/tests/fixtures/before.lean +4 -0
  104. package/skills/lean-formalization/lean-runtime/tests/fixtures/failure.lean +7 -0
  105. package/skills/lean-formalization/lean-runtime/tests/test_check_lean_project.py +59 -0
  106. package/skills/lean-formalization/lean-runtime/tests/test_cli.py +377 -0
  107. package/skills/lean-formalization/lean-runtime/tests/test_common_config.py +84 -0
  108. package/skills/lean-formalization/lean-runtime/tests/test_configure_lean.py +138 -0
  109. package/skills/lean-formalization/lean-runtime/tests/test_detect_sorry.py +24 -0
  110. package/skills/lean-formalization/lean-runtime/tests/test_direct_task.py +69 -0
  111. package/skills/lean-formalization/lean-runtime/tests/test_numina_runtime.py +168 -0
  112. package/skills/lean-formalization/lean-runtime/tests/test_validate_patch.py +29 -0
  113. package/skills/lean-setup/SKILL.md +99 -0
  114. package/skills/least-squares/README.md +85 -0
  115. package/skills/least-squares/SKILL.md +613 -0
  116. package/skills/least-squares/examples.md +380 -0
  117. package/skills/math-beamer/SKILL.md +325 -0
  118. package/skills/math-beamer/references/build-and-layout-audit.md +63 -0
  119. package/skills/math-beamer/references/math-domain-patterns.md +56 -0
  120. package/skills/math-beamer/references/template-policy.md +43 -0
  121. package/skills/math-beamer/references/template-source-index.md +51 -0
  122. package/skills/math-beamer/templates/catalog.yaml +235 -0
  123. package/skills/math-beamer/templates/packs/algebra-number-theory-talk/main.tex +45 -0
  124. package/skills/math-beamer/templates/packs/algebra-number-theory-talk/template.yaml +9 -0
  125. package/skills/math-beamer/templates/packs/algorithm-talk/main.tex +43 -0
  126. package/skills/math-beamer/templates/packs/algorithm-talk/template.yaml +9 -0
  127. package/skills/math-beamer/templates/packs/analysis-core-talk/main.tex +49 -0
  128. package/skills/math-beamer/templates/packs/analysis-core-talk/template.yaml +19 -0
  129. package/skills/math-beamer/templates/packs/backup-heavy-talk/main.tex +40 -0
  130. package/skills/math-beamer/templates/packs/backup-heavy-talk/template.yaml +9 -0
  131. package/skills/math-beamer/templates/packs/beamerposter-a0/main.tex +45 -0
  132. package/skills/math-beamer/templates/packs/beamerposter-a0/template.yaml +12 -0
  133. package/skills/math-beamer/templates/packs/combinatorics-graph-talk/main.tex +53 -0
  134. package/skills/math-beamer/templates/packs/combinatorics-graph-talk/template.yaml +18 -0
  135. package/skills/math-beamer/templates/packs/control-systems-talk/main.tex +51 -0
  136. package/skills/math-beamer/templates/packs/control-systems-talk/template.yaml +18 -0
  137. package/skills/math-beamer/templates/packs/course-lecture-zh/main.tex +43 -0
  138. package/skills/math-beamer/templates/packs/course-lecture-zh/template.yaml +9 -0
  139. package/skills/math-beamer/templates/packs/data-experiment-results/main.tex +45 -0
  140. package/skills/math-beamer/templates/packs/data-experiment-results/template.yaml +9 -0
  141. package/skills/math-beamer/templates/packs/dynamical-systems-talk/main.tex +42 -0
  142. package/skills/math-beamer/templates/packs/dynamical-systems-talk/template.yaml +9 -0
  143. package/skills/math-beamer/templates/packs/geometry-topology-talk/main.tex +43 -0
  144. package/skills/math-beamer/templates/packs/geometry-topology-talk/template.yaml +9 -0
  145. package/skills/math-beamer/templates/packs/information-coding-crypto-talk/main.tex +49 -0
  146. package/skills/math-beamer/templates/packs/information-coding-crypto-talk/template.yaml +18 -0
  147. package/skills/math-beamer/templates/packs/logic-foundations-category-talk/main.tex +51 -0
  148. package/skills/math-beamer/templates/packs/logic-foundations-category-talk/template.yaml +18 -0
  149. package/skills/math-beamer/templates/packs/numerical-analysis-talk/main.tex +51 -0
  150. package/skills/math-beamer/templates/packs/numerical-analysis-talk/template.yaml +9 -0
  151. package/skills/math-beamer/templates/packs/optimization-talk/main.tex +58 -0
  152. package/skills/math-beamer/templates/packs/optimization-talk/template.yaml +9 -0
  153. package/skills/math-beamer/templates/packs/pde-analysis-talk/main.tex +49 -0
  154. package/skills/math-beamer/templates/packs/pde-analysis-talk/template.yaml +9 -0
  155. package/skills/math-beamer/templates/packs/probability-statistics-talk/main.tex +52 -0
  156. package/skills/math-beamer/templates/packs/probability-statistics-talk/template.yaml +9 -0
  157. package/skills/math-beamer/templates/packs/reading-group-paper/main.tex +46 -0
  158. package/skills/math-beamer/templates/packs/reading-group-paper/template.yaml +9 -0
  159. package/skills/math-beamer/templates/packs/seminar-minimal-en/main.tex +60 -0
  160. package/skills/math-beamer/templates/packs/seminar-minimal-en/template.yaml +13 -0
  161. package/skills/math-beamer/templates/packs/seminar-minimal-zh/main.tex +60 -0
  162. package/skills/math-beamer/templates/packs/seminar-minimal-zh/template.yaml +13 -0
  163. package/skills/math-beamer/templates/packs/theorem-proof-talk/main.tex +60 -0
  164. package/skills/math-beamer/templates/packs/theorem-proof-talk/template.yaml +9 -0
  165. package/skills/math-beamer/templates/packs/thesis-defense/main.tex +42 -0
  166. package/skills/math-beamer/templates/packs/thesis-defense/template.yaml +9 -0
  167. package/skills/math-beamer/templates/packs/workshop-tutorial/main.tex +32 -0
  168. package/skills/math-beamer/templates/packs/workshop-tutorial/template.yaml +9 -0
  169. package/skills/math-beamer/templates/preview-gallery.md +32 -0
  170. package/skills/math-beamer/templates/previews/algebra-number-theory-talk-content.png +0 -0
  171. package/skills/math-beamer/templates/previews/algebra-number-theory-talk-cover.png +0 -0
  172. package/skills/math-beamer/templates/previews/algorithm-talk-content.png +0 -0
  173. package/skills/math-beamer/templates/previews/algorithm-talk-cover.png +0 -0
  174. package/skills/math-beamer/templates/previews/analysis-core-talk-content.png +0 -0
  175. package/skills/math-beamer/templates/previews/analysis-core-talk-cover.png +0 -0
  176. package/skills/math-beamer/templates/previews/backup-heavy-talk-content.png +0 -0
  177. package/skills/math-beamer/templates/previews/backup-heavy-talk-cover.png +0 -0
  178. package/skills/math-beamer/templates/previews/beamerposter-a0-content.png +0 -0
  179. package/skills/math-beamer/templates/previews/beamerposter-a0-cover.png +0 -0
  180. package/skills/math-beamer/templates/previews/combinatorics-graph-talk-content.png +0 -0
  181. package/skills/math-beamer/templates/previews/combinatorics-graph-talk-cover.png +0 -0
  182. package/skills/math-beamer/templates/previews/control-systems-talk-content.png +0 -0
  183. package/skills/math-beamer/templates/previews/control-systems-talk-cover.png +0 -0
  184. package/skills/math-beamer/templates/previews/course-lecture-zh-content.png +0 -0
  185. package/skills/math-beamer/templates/previews/course-lecture-zh-cover.png +0 -0
  186. package/skills/math-beamer/templates/previews/data-experiment-results-content.png +0 -0
  187. package/skills/math-beamer/templates/previews/data-experiment-results-cover.png +0 -0
  188. package/skills/math-beamer/templates/previews/dynamical-systems-talk-content.png +0 -0
  189. package/skills/math-beamer/templates/previews/dynamical-systems-talk-cover.png +0 -0
  190. package/skills/math-beamer/templates/previews/geometry-topology-talk-content.png +0 -0
  191. package/skills/math-beamer/templates/previews/geometry-topology-talk-cover.png +0 -0
  192. package/skills/math-beamer/templates/previews/information-coding-crypto-talk-content.png +0 -0
  193. package/skills/math-beamer/templates/previews/information-coding-crypto-talk-cover.png +0 -0
  194. package/skills/math-beamer/templates/previews/logic-foundations-category-talk-content.png +0 -0
  195. package/skills/math-beamer/templates/previews/logic-foundations-category-talk-cover.png +0 -0
  196. package/skills/math-beamer/templates/previews/numerical-analysis-talk-content.png +0 -0
  197. package/skills/math-beamer/templates/previews/numerical-analysis-talk-cover.png +0 -0
  198. package/skills/math-beamer/templates/previews/optimization-talk-content.png +0 -0
  199. package/skills/math-beamer/templates/previews/optimization-talk-cover.png +0 -0
  200. package/skills/math-beamer/templates/previews/pde-analysis-talk-content.png +0 -0
  201. package/skills/math-beamer/templates/previews/pde-analysis-talk-cover.png +0 -0
  202. package/skills/math-beamer/templates/previews/probability-statistics-talk-content.png +0 -0
  203. package/skills/math-beamer/templates/previews/probability-statistics-talk-cover.png +0 -0
  204. package/skills/math-beamer/templates/previews/reading-group-paper-content.png +0 -0
  205. package/skills/math-beamer/templates/previews/reading-group-paper-cover.png +0 -0
  206. package/skills/math-beamer/templates/previews/seminar-minimal-en-content.png +0 -0
  207. package/skills/math-beamer/templates/previews/seminar-minimal-en-cover.png +0 -0
  208. package/skills/math-beamer/templates/previews/seminar-minimal-zh-content.png +0 -0
  209. package/skills/math-beamer/templates/previews/seminar-minimal-zh-cover.png +0 -0
  210. package/skills/math-beamer/templates/previews/theorem-proof-talk-content.png +0 -0
  211. package/skills/math-beamer/templates/previews/theorem-proof-talk-cover.png +0 -0
  212. package/skills/math-beamer/templates/previews/thesis-defense-content.png +0 -0
  213. package/skills/math-beamer/templates/previews/thesis-defense-cover.png +0 -0
  214. package/skills/math-beamer/templates/previews/workshop-tutorial-content.png +0 -0
  215. package/skills/math-beamer/templates/previews/workshop-tutorial-cover.png +0 -0
  216. package/skills/math-beamer/templates/review-report.md +54 -0
  217. package/skills/math-beamer/templates/slide-source-ledger.md +22 -0
  218. package/skills/math-beamer/templates/source-packet.md +50 -0
  219. package/skills/math-glossary/SKILL.md +347 -0
  220. package/skills/math-glossary/references/glossary-schema.md +71 -0
  221. package/skills/math-glossary/references/glossary-usage-guide.md +176 -0
  222. package/skills/math-glossary/references/glossary-web-template.md +127 -0
  223. package/skills/math-glossary/references/glossary.schema.json +76 -0
  224. package/skills/math-glossary/references/user-manual.md +435 -0
  225. package/skills/math-glossary/requirements-ai.txt +3 -0
  226. package/skills/math-glossary/requirements.txt +3 -0
  227. package/skills/math-glossary/scripts/glossary_backup.py +42 -0
  228. package/skills/math-glossary/scripts/glossary_build.py +467 -0
  229. package/skills/math-glossary/scripts/glossary_enrich_examples.py +283 -0
  230. package/skills/math-glossary/scripts/glossary_export.py +333 -0
  231. package/skills/math-glossary/scripts/glossary_web.py +1265 -0
  232. package/skills/math-paper-reading/README.md +163 -0
  233. package/skills/math-paper-reading/SKILL.md +48 -0
  234. package/skills/math-paper-reading/agent_router.md +36 -0
  235. package/skills/math-paper-reading/references/proof_pattern_taxonomy.md +123 -0
  236. package/skills/math-paper-reading/references/quality_rubric.md +36 -0
  237. package/skills/math-paper-reading/skill_base.md +627 -0
  238. package/skills/math-paper-reading/skill_literature_search.md +866 -0
  239. package/skills/math-paper-reading/skill_paper_deep_read.md +1024 -0
  240. package/skills/math-paper-reading/skill_pathway_proof.md +718 -0
  241. package/skills/math-paper-reading/skill_reference_manager.md +746 -0
  242. package/skills/matlab-runner/SKILL.md +217 -0
  243. package/skills/matlab-runner/examples/README.md +33 -0
  244. package/skills/matlab-runner/examples/matrix_report.m +28 -0
  245. package/skills/matlab-runner/examples/plot_damped_sine.m +64 -0
  246. package/skills/matlab-runner/examples/test_vector_norm.m +12 -0
  247. package/skills/matlab-runner/references/client-setup.md +24 -0
  248. package/skills/matlab-runner/references/file-session-safety.md +86 -0
  249. package/skills/matlab-runner/references/numerical-safety.md +126 -0
  250. package/skills/matlab-runner/references/resource-safety.md +125 -0
  251. package/skills/mixed-integer-programming/SKILL.md +119 -0
  252. package/skills/mixed-integer-programming/lp-examples.md +251 -0
  253. package/skills/mixed-integer-programming/mip-examples-verified.md +118 -0
  254. package/skills/open-problem-research-pipeline/SKILL.md +76 -0
  255. package/skills/open-problem-research-pipeline/skill_literature_analysis.md +201 -0
  256. package/skills/open-problem-research-pipeline/skill_literature_proof_framework.md +206 -0
  257. package/skills/open-problem-research-pipeline/skill_literature_search.md +172 -0
  258. package/skills/open-problem-research-pipeline/skill_qskill.md +177 -0
  259. package/skills/osqp-solver/SKILL.md +245 -0
  260. package/skills/osqp-solver/references/citation.md +25 -0
  261. package/skills/osqp-solver/references/dual-infeasible-example.json +14 -0
  262. package/skills/osqp-solver/references/feasible-example.json +21 -0
  263. package/skills/osqp-solver/references/primal-infeasible-example.json +17 -0
  264. package/skills/osqp-solver/references/python-api.md +95 -0
  265. package/skills/osqp-solver/references/verification.md +94 -0
  266. package/skills/osqp-solver/scripts/check_osqp_environment.py +120 -0
  267. package/skills/osqp-solver/scripts/solve_qp.py +943 -0
  268. package/skills/paper-writing/SKILL.md +115 -0
  269. package/skills/paper-writing/skill_claim_evidence_ledger.md +55 -0
  270. package/skills/paper-writing/skill_formula_environment_and_readability.md +41 -0
  271. package/skills/paper-writing/skill_latex_build_and_layout_audit.md +73 -0
  272. package/skills/paper-writing/skill_notation_and_variable_consistency.md +42 -0
  273. package/skills/paper-writing/skill_paper_skeleton_and_logical_architecture.md +54 -0
  274. package/skills/paper-writing/skill_proof_obligation_and_assumption_audit.md +57 -0
  275. package/skills/paper-writing/templates/claim-evidence-ledger.md +23 -0
  276. package/skills/paper-writing/templates/proof-obligation-ledger.md +22 -0
  277. package/skills/paper-writing/templates/rapid-prototype-paper-skeleton.md +46 -0
  278. package/skills/paper-writing/templates/source-packet.md +37 -0
  279. package/skills/paper-writing/templates/submission-readiness.md +41 -0
  280. package/skills/proof-blueprint-review/SKILL.md +129 -0
  281. package/skills/proof-blueprint-review/references/agent-mediated-proof-protocol.md +57 -0
  282. package/skills/proof-blueprint-review/references/generation-agent.md +45 -0
  283. package/skills/proof-blueprint-review/references/proof-acceptance-contract.md +41 -0
  284. package/skills/proof-blueprint-review/references/verification-agent.md +37 -0
@@ -0,0 +1,467 @@
1
+ """从结构化数据构建符合 math-glossary 合同的 glossary.json。
2
+
3
+ 本脚本只负责 CSV/TSV、JSON 和 YAML。PDF、OCR、MDX 与自由文本仍由
4
+ ``SKILL.md`` 中的 agent workflow 解析和人工复核。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import csv
11
+ import importlib.util
12
+ import json
13
+ import os
14
+ import re
15
+ import tempfile
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+ from typing import Any, Iterable
19
+
20
+
21
+ COLUMN_ALIASES = {
22
+ "term_id": ("term_id", "termid", "术语id"),
23
+ "en": ("en", "english", "term", "word", "keyword", "name", "英文", "术语"),
24
+ "cn": (
25
+ "cn",
26
+ "chinese",
27
+ "translation",
28
+ "definition",
29
+ "译名",
30
+ "中文",
31
+ "翻译",
32
+ ),
33
+ "pos": ("pos", "part_of_speech", "词性"),
34
+ "field": ("field", "domain", "discipline", "领域", "子领域", "学科"),
35
+ "source": ("source", "来源"),
36
+ "examples": ("examples", "例句", "示例"),
37
+ "created_at": ("created_at", "创建时间"),
38
+ "updated_at": ("updated_at", "更新时间"),
39
+ }
40
+ DATE_PATTERN = re.compile(r"^\d{4}-\d{2}-\d{2}$")
41
+
42
+
43
+ class GlossaryBuildError(ValueError):
44
+ """Raised when structured source data cannot satisfy the glossary contract."""
45
+
46
+
47
+ def _normalize_header(value: str) -> str:
48
+ return re.sub(r"[\s_-]+", "", value.strip().casefold())
49
+
50
+
51
+ def _decode_text(path: Path) -> str:
52
+ raw = path.read_bytes()
53
+ errors = []
54
+ for encoding in ("utf-8-sig", "utf-8", "gb18030"):
55
+ try:
56
+ return raw.decode(encoding)
57
+ except UnicodeDecodeError as exc:
58
+ errors.append(f"{encoding}: {exc}")
59
+ raise GlossaryBuildError(
60
+ f"无法解码 {path.name};已尝试 UTF-8/UTF-8 BOM/GB18030。"
61
+ ) from errors[-1]
62
+
63
+
64
+ def _detect_columns(
65
+ fieldnames: list[str],
66
+ explicit_en: str | None,
67
+ explicit_cn: str | None,
68
+ ) -> dict[str, str]:
69
+ normalized = {
70
+ _normalize_header(name): name
71
+ for name in fieldnames
72
+ if name is not None
73
+ }
74
+ result: dict[str, str] = {}
75
+ explicit = {"en": explicit_en, "cn": explicit_cn}
76
+ for canonical, aliases in COLUMN_ALIASES.items():
77
+ selected = explicit.get(canonical)
78
+ if selected:
79
+ key = _normalize_header(selected)
80
+ if key not in normalized:
81
+ raise GlossaryBuildError(
82
+ f"找不到显式指定的 {canonical} 列: {selected}"
83
+ )
84
+ result[canonical] = normalized[key]
85
+ continue
86
+ for alias in aliases:
87
+ match = normalized.get(_normalize_header(alias))
88
+ if match is not None:
89
+ result[canonical] = match
90
+ break
91
+ missing = [field for field in ("en", "cn") if field not in result]
92
+ if missing:
93
+ raise GlossaryBuildError(
94
+ "无法识别必需列 "
95
+ + ", ".join(missing)
96
+ + f";现有列为: {', '.join(fieldnames)}"
97
+ )
98
+ return result
99
+
100
+
101
+ def _records_from_csv(
102
+ path: Path,
103
+ *,
104
+ en_column: str | None,
105
+ cn_column: str | None,
106
+ ) -> list[tuple[dict[str, Any], str]]:
107
+ text = _decode_text(path)
108
+ try:
109
+ dialect = csv.Sniffer().sniff(text[:4096], delimiters=",\t;")
110
+ except csv.Error:
111
+ dialect = csv.excel_tab if path.suffix.lower() == ".tsv" else csv.excel
112
+ reader = csv.DictReader(text.splitlines(), dialect=dialect)
113
+ if not reader.fieldnames:
114
+ raise GlossaryBuildError(f"{path.name} 缺少表头")
115
+ columns = _detect_columns(reader.fieldnames, en_column, cn_column)
116
+ records = []
117
+ for row in reader:
118
+ if not row or not any(str(value or "").strip() for value in row.values()):
119
+ continue
120
+ canonical = {
121
+ field: row.get(column)
122
+ for field, column in columns.items()
123
+ }
124
+ records.append((canonical, f"{path.name}:line {reader.line_num}"))
125
+ return records
126
+
127
+
128
+ def _load_json_or_yaml(path: Path) -> Any:
129
+ text = _decode_text(path)
130
+ if path.suffix.lower() == ".json":
131
+ return json.loads(text)
132
+ try:
133
+ import yaml
134
+ except ImportError as exc:
135
+ raise ImportError(
136
+ "YAML 输入需要 PyYAML;请先审阅并安装 requirements.txt。"
137
+ ) from exc
138
+ return yaml.safe_load(text)
139
+
140
+
141
+ def _records_from_object(
142
+ data: Any,
143
+ path: Path,
144
+ ) -> list[tuple[dict[str, Any], str]]:
145
+ if isinstance(data, dict) and isinstance(data.get("terms"), list):
146
+ data = data["terms"]
147
+ if isinstance(data, list):
148
+ records = data
149
+ elif isinstance(data, dict):
150
+ records = []
151
+ for english, translation in data.items():
152
+ if isinstance(translation, dict):
153
+ record = dict(translation)
154
+ record.setdefault("en", english)
155
+ else:
156
+ record = {"en": english, "cn": translation}
157
+ records.append(record)
158
+ else:
159
+ raise GlossaryBuildError(
160
+ f"{path.name} 顶层必须是对象数组、terms 数组或 en→cn 对象"
161
+ )
162
+
163
+ output = []
164
+ for index, record in enumerate(records, 1):
165
+ if not isinstance(record, dict):
166
+ raise GlossaryBuildError(
167
+ f"{path.name}:record {index} 必须是对象"
168
+ )
169
+ output.append((record, f"{path.name}:record {index}"))
170
+ return output
171
+
172
+
173
+ def read_structured_source(
174
+ source_path: str | os.PathLike[str],
175
+ *,
176
+ en_column: str | None = None,
177
+ cn_column: str | None = None,
178
+ ) -> list[tuple[dict[str, Any], str]]:
179
+ path = Path(source_path).expanduser().resolve()
180
+ if not path.is_file():
181
+ raise FileNotFoundError(f"{path} 不存在或不是文件")
182
+ suffix = path.suffix.lower()
183
+ if suffix in {".csv", ".tsv"}:
184
+ return _records_from_csv(
185
+ path,
186
+ en_column=en_column,
187
+ cn_column=cn_column,
188
+ )
189
+ if suffix in {".json", ".yaml", ".yml"}:
190
+ return _records_from_object(_load_json_or_yaml(path), path)
191
+ raise GlossaryBuildError(
192
+ f"结构化建库 CLI 不支持 {suffix or '无扩展名'};"
193
+ "当前仅支持 CSV/TSV/JSON/YAML。"
194
+ )
195
+
196
+
197
+ def _record_value(record: dict[str, Any], field: str) -> Any:
198
+ normalized = {
199
+ _normalize_header(str(key)): value
200
+ for key, value in record.items()
201
+ }
202
+ for alias in COLUMN_ALIASES[field]:
203
+ key = _normalize_header(alias)
204
+ if key in normalized:
205
+ return normalized[key]
206
+ return None
207
+
208
+
209
+ def _field_list(value: Any) -> list[str]:
210
+ if value is None:
211
+ return []
212
+ if isinstance(value, list):
213
+ raw_items: Iterable[Any] = value
214
+ else:
215
+ raw_items = re.split(r"[/;,,;]", str(value))
216
+ seen = set()
217
+ output = []
218
+ for item in raw_items:
219
+ text = str(item).strip()
220
+ if text and text not in seen:
221
+ seen.add(text)
222
+ output.append(text)
223
+ return output
224
+
225
+
226
+ def _examples(value: Any) -> list[dict[str, str]]:
227
+ if not isinstance(value, list):
228
+ return []
229
+ output = []
230
+ for example in value:
231
+ if not isinstance(example, dict):
232
+ continue
233
+ english = str(example.get("en", "")).strip()
234
+ chinese = str(example.get("cn", "")).strip()
235
+ if english or chinese:
236
+ output.append({"en": english, "cn": chinese})
237
+ return output
238
+
239
+
240
+ def _trace_source(
241
+ location: str,
242
+ record_source: Any,
243
+ source_label: str | None,
244
+ ) -> str:
245
+ parts = []
246
+ for value in (source_label, record_source):
247
+ text = str(value or "").strip()
248
+ if text and text not in parts:
249
+ parts.append(text)
250
+ parts.append(location)
251
+ return "; ".join(parts)
252
+
253
+
254
+ def build_terms(
255
+ records: list[tuple[dict[str, Any], str]],
256
+ *,
257
+ source_label: str | None = None,
258
+ ) -> list[dict[str, Any]]:
259
+ today = datetime.now().strftime("%Y-%m-%d")
260
+ occurrences: dict[str, int] = {}
261
+ seen_pairs: set[tuple[str, str]] = set()
262
+ used_term_ids: set[str] = set()
263
+ terms = []
264
+
265
+ for record, location in records:
266
+ english = str(_record_value(record, "en") or "").strip()
267
+ chinese = str(_record_value(record, "cn") or "").strip()
268
+ if not english or not chinese:
269
+ raise GlossaryBuildError(
270
+ f"{location} 缺少非空英文术语或中文译名"
271
+ )
272
+ pair = (english.casefold(), chinese)
273
+ if pair in seen_pairs:
274
+ continue
275
+ seen_pairs.add(pair)
276
+
277
+ base_id = english.casefold()
278
+ provided_id = str(_record_value(record, "term_id") or "").strip()
279
+ if provided_id:
280
+ normalized_id = provided_id.casefold()
281
+ if normalized_id in used_term_ids:
282
+ raise GlossaryBuildError(
283
+ f"{location} 的 term_id 与已有记录重复: {provided_id}"
284
+ )
285
+ term_id = provided_id
286
+ used_term_ids.add(normalized_id)
287
+ if normalized_id == base_id:
288
+ occurrences[base_id] = max(
289
+ occurrences.get(base_id, 0),
290
+ 1,
291
+ )
292
+ else:
293
+ suffix = re.fullmatch(
294
+ re.escape(base_id) + r"__(\d+)",
295
+ normalized_id,
296
+ )
297
+ if suffix:
298
+ occurrences[base_id] = max(
299
+ occurrences.get(base_id, 0),
300
+ int(suffix.group(1)) + 1,
301
+ )
302
+ else:
303
+ occurrence = occurrences.get(base_id, 0)
304
+ while True:
305
+ candidate = (
306
+ base_id
307
+ if occurrence == 0
308
+ else f"{base_id}__{occurrence}"
309
+ )
310
+ if candidate.casefold() not in used_term_ids:
311
+ term_id = candidate
312
+ break
313
+ occurrence += 1
314
+ occurrences[base_id] = occurrence + 1
315
+ used_term_ids.add(term_id.casefold())
316
+
317
+ created_at = str(_record_value(record, "created_at") or today).strip()
318
+ updated_at = str(_record_value(record, "updated_at") or today).strip()
319
+ if not DATE_PATTERN.fullmatch(created_at):
320
+ created_at = today
321
+ if not DATE_PATTERN.fullmatch(updated_at):
322
+ updated_at = today
323
+
324
+ terms.append({
325
+ "term_id": term_id,
326
+ "en": english,
327
+ "cn": chinese,
328
+ "pos": str(_record_value(record, "pos") or "").strip(),
329
+ "field": _field_list(_record_value(record, "field")),
330
+ "source": _trace_source(
331
+ location,
332
+ _record_value(record, "source"),
333
+ source_label,
334
+ ),
335
+ "examples": _examples(_record_value(record, "examples")),
336
+ "created_at": created_at,
337
+ "updated_at": updated_at,
338
+ })
339
+
340
+ terms.sort(
341
+ key=lambda term: (
342
+ term["en"].casefold(),
343
+ term["cn"].casefold(),
344
+ )
345
+ )
346
+ for index, term in enumerate(terms, 1):
347
+ term["idx"] = index
348
+ return terms
349
+
350
+
351
+ def _atomic_json_dump(terms: list[dict[str, Any]], output: Path) -> None:
352
+ output.parent.mkdir(parents=True, exist_ok=True)
353
+ descriptor, temporary_name = tempfile.mkstemp(
354
+ prefix=f".{output.name}.",
355
+ suffix=".tmp",
356
+ dir=output.parent,
357
+ )
358
+ try:
359
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
360
+ json.dump(terms, handle, ensure_ascii=False, indent=2)
361
+ handle.write("\n")
362
+ handle.flush()
363
+ os.fsync(handle.fileno())
364
+ os.replace(temporary_name, output)
365
+ except Exception:
366
+ try:
367
+ os.unlink(temporary_name)
368
+ except FileNotFoundError:
369
+ pass
370
+ raise
371
+
372
+
373
+ def _load_export_function():
374
+ export_path = Path(__file__).resolve().with_name("glossary_export.py")
375
+ spec = importlib.util.spec_from_file_location(
376
+ "math_glossary_export",
377
+ export_path,
378
+ )
379
+ if spec is None or spec.loader is None:
380
+ raise RuntimeError(f"无法加载导出脚本: {export_path}")
381
+ module = importlib.util.module_from_spec(spec)
382
+ spec.loader.exec_module(module)
383
+ return module.export_to_excel
384
+
385
+
386
+ def build_parser() -> argparse.ArgumentParser:
387
+ parser = argparse.ArgumentParser(
388
+ description="从 CSV/TSV/JSON/YAML 构建 glossary.json。"
389
+ )
390
+ parser.add_argument("source", help="结构化来源文件")
391
+ parser.add_argument(
392
+ "--output",
393
+ help="输出 JSON;默认 <来源目录>/术语库/glossary.json",
394
+ )
395
+ parser.add_argument("--en-column", help="显式指定英文列名")
396
+ parser.add_argument("--cn-column", help="显式指定中文列名")
397
+ parser.add_argument(
398
+ "--source-label",
399
+ help="附加书名、项目名等来源标签",
400
+ )
401
+ parser.add_argument(
402
+ "--force",
403
+ action="store_true",
404
+ help="允许覆盖已存在的输出 JSON;覆盖前仍建议先备份",
405
+ )
406
+ parser.add_argument(
407
+ "--no-excel",
408
+ action="store_true",
409
+ help="只生成 JSON,不尝试导出 Excel",
410
+ )
411
+ return parser
412
+
413
+
414
+ def main(argv: list[str] | None = None) -> int:
415
+ args = build_parser().parse_args(argv)
416
+ source = Path(args.source).expanduser().resolve()
417
+ output = (
418
+ Path(args.output).expanduser().resolve()
419
+ if args.output
420
+ else source.parent / "术语库" / "glossary.json"
421
+ )
422
+ if output.exists() and not args.force:
423
+ print(f"错误:{output} 已存在;请先备份,并显式添加 --force。")
424
+ return 2
425
+
426
+ try:
427
+ records = read_structured_source(
428
+ source,
429
+ en_column=args.en_column,
430
+ cn_column=args.cn_column,
431
+ )
432
+ terms = build_terms(records, source_label=args.source_label)
433
+ if not terms:
434
+ raise GlossaryBuildError("来源文件没有可用术语")
435
+ _atomic_json_dump(terms, output)
436
+ except (
437
+ FileNotFoundError,
438
+ GlossaryBuildError,
439
+ ImportError,
440
+ json.JSONDecodeError,
441
+ OSError,
442
+ ) as exc:
443
+ print(f"错误:{exc}")
444
+ return 2
445
+
446
+ print(f"JSON 已完成:{output}({len(terms)} 条)")
447
+ if args.no_excel:
448
+ print("按 --no-excel 要求跳过 Excel;本次状态为 JSON 完成。")
449
+ return 0
450
+
451
+ try:
452
+ export_to_excel = _load_export_function()
453
+ exported = Path(export_to_excel(output, output.parent)).resolve()
454
+ except (ImportError, OSError, ValueError) as exc:
455
+ print(f"Excel 待完成:{exc}")
456
+ print("JSON 已安全保留;不得把本次状态表述为完整导出完成。")
457
+ return 3
458
+
459
+ for candidate in output.parent.glob("glossary_*.xlsx"):
460
+ if candidate.resolve() != exported:
461
+ candidate.unlink()
462
+ print(f"Excel 已完成:{exported}")
463
+ return 0
464
+
465
+
466
+ if __name__ == "__main__":
467
+ raise SystemExit(main())