@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.
- package/CHANGELOG.md +133 -0
- package/LICENSE +21 -0
- package/NOTICE.md +35 -0
- package/README.md +108 -2
- package/README_EN.md +105 -0
- package/UPSTREAM.json +106 -0
- package/cordis.patch.yml +12 -0
- package/docs/capability-examples.md +581 -0
- package/docs/examples/README.md +32 -0
- package/docs/examples/bad_scan.md +10 -0
- package/docs/examples/broken-proof.lean +9 -0
- package/docs/examples/claims.md +7 -0
- package/docs/examples/knapsack.json +10 -0
- package/docs/examples/matrix.json +1 -0
- package/docs/examples/points.csv +21 -0
- package/docs/examples/qp.json +8 -0
- package/docs/examples/research-ws/project/GOALS.yaml +4 -0
- package/docs/examples/research-ws/workstreams/ws-lsa/report.md +13 -0
- package/docs/examples/research-ws/workstreams/ws-lsa/reviews/r1.json +1 -0
- package/docs/examples/research-ws/workstreams/ws-lsa/status.yaml +1 -0
- package/docs/examples/source.csv +4 -0
- package/lib/core/error.d.ts +20 -0
- package/lib/core/error.js +25 -0
- package/lib/core/gates.d.ts +42 -0
- package/lib/core/gates.js +217 -0
- package/lib/core/glossary.d.ts +101 -0
- package/lib/core/glossary.js +243 -0
- package/lib/core/graph.d.ts +118 -0
- package/lib/core/graph.js +460 -0
- package/lib/core/index.d.ts +120 -0
- package/lib/core/index.js +197 -0
- package/lib/core/paper.d.ts +163 -0
- package/lib/core/paper.js +73 -0
- package/lib/core/paths.d.ts +2 -0
- package/lib/core/paths.js +12 -0
- package/lib/core/sage.d.ts +61 -0
- package/lib/core/sage.js +212 -0
- package/lib/core/skills.d.ts +11 -0
- package/lib/core/skills.js +110 -0
- package/lib/tool/index.d.ts +21 -0
- package/lib/tool/index.js +1144 -0
- package/package.json +92 -4
- package/skills/after-ocr/SKILL.md +123 -0
- package/skills/after-ocr/references/audit-schema.md +94 -0
- package/skills/after-ocr/references/error-taxonomy.md +179 -0
- package/skills/after-ocr/scripts/merge_audit_logs.py +329 -0
- package/skills/after-ocr/scripts/scan_markdown_ocr.py +350 -0
- package/skills/after-ocr/tests/test_scripts.py +84 -0
- package/skills/discover-math-problems/SKILL.md +115 -0
- package/skills/discover-math-problems/references/artifact-contract.md +93 -0
- package/skills/discover-math-problems/references/autonomous-research-protocol.md +86 -0
- package/skills/discover-math-problems/references/conjecture-generation-protocol.md +63 -0
- package/skills/discover-math-problems/references/extremal-graph-variants.md +53 -0
- package/skills/graph-theory-paper-reading/SKILL.md +600 -0
- package/skills/invariant-computation/SKILL.md +169 -0
- package/skills/invariant-computation/examples/invariant_summary.example.json +51 -0
- package/skills/invariant-computation/manifest.yaml +46 -0
- package/skills/invariant-computation/references/INDEX.md +20 -0
- package/skills/invariant-computation/references/failure_modes.md +40 -0
- package/skills/invariant-computation/references/method_route_map.md +177 -0
- package/skills/invariant-computation/references/source_notes.md +19 -0
- package/skills/invariant-computation/references/tool_catalog.md +65 -0
- package/skills/invariant-computation/references/validation_checks.md +52 -0
- package/skills/invariant-computation/schema/invariant_summary.schema.json +260 -0
- package/skills/lean-formalization/SKILL.md +111 -0
- package/skills/lean-formalization/lean-runtime/config/env.example +5 -0
- package/skills/lean-formalization/lean-runtime/config/lean_agent.example.toml +28 -0
- package/skills/lean-formalization/lean-runtime/config/numina_runtime.example.toml +12 -0
- package/skills/lean-formalization/lean-runtime/examples/smoke/LocalLeanSmoke.lean +7 -0
- package/skills/lean-formalization/lean-runtime/prompts/complete_sorries.md +3 -0
- package/skills/lean-formalization/lean-runtime/prompts/formalize_statement.md +3 -0
- package/skills/lean-formalization/lean-runtime/prompts/prove_theorem.md +3 -0
- package/skills/lean-formalization/lean-runtime/prompts/repair_lean_file.md +3 -0
- package/skills/lean-formalization/lean-runtime/references/backend_adapter_checklist.md +36 -0
- package/skills/lean-formalization/lean-runtime/references/direct_lean_workflow.md +48 -0
- package/skills/lean-formalization/lean-runtime/references/failure_taxonomy.md +17 -0
- package/skills/lean-formalization/lean-runtime/references/interactive_orchestration.md +83 -0
- package/skills/lean-formalization/lean-runtime/references/lean_agent_capability_map.md +116 -0
- package/skills/lean-formalization/lean-runtime/references/lean_lsp_mcp_adapter.md +219 -0
- package/skills/lean-formalization/lean-runtime/references/lean_runtime_configuration.md +92 -0
- package/skills/lean-formalization/lean-runtime/references/numina_reverse_analysis.md +80 -0
- package/skills/lean-formalization/lean-runtime/references/numina_runtime.md +41 -0
- package/skills/lean-formalization/lean-runtime/references/numina_subagent_troubleshooting.md +77 -0
- package/skills/lean-formalization/lean-runtime/references/review_checklist.md +10 -0
- package/skills/lean-formalization/lean-runtime/references/specialist_agent_patterns.md +65 -0
- package/skills/lean-formalization/lean-runtime/schemas/config.schema.json +12 -0
- package/skills/lean-formalization/lean-runtime/schemas/result.schema.json +33 -0
- package/skills/lean-formalization/lean-runtime/schemas/task.schema.json +30 -0
- package/skills/lean-formalization/lean-runtime/scripts/ai4m_lean.py +222 -0
- package/skills/lean-formalization/lean-runtime/scripts/check_lean_project.py +134 -0
- package/skills/lean-formalization/lean-runtime/scripts/common.py +296 -0
- package/skills/lean-formalization/lean-runtime/scripts/configure_lean.py +222 -0
- package/skills/lean-formalization/lean-runtime/scripts/detect_sorry.py +49 -0
- package/skills/lean-formalization/lean-runtime/scripts/direct_task.py +100 -0
- package/skills/lean-formalization/lean-runtime/scripts/extract_minimal_failure.py +74 -0
- package/skills/lean-formalization/lean-runtime/scripts/numina_runtime.py +414 -0
- package/skills/lean-formalization/lean-runtime/scripts/smoke_test.py +75 -0
- package/skills/lean-formalization/lean-runtime/scripts/tool_status.py +79 -0
- package/skills/lean-formalization/lean-runtime/scripts/validate_patch.py +81 -0
- package/skills/lean-formalization/lean-runtime/scripts/verify_delivery.py +484 -0
- package/skills/lean-formalization/lean-runtime/tests/fixtures/after_bad.lean +4 -0
- package/skills/lean-formalization/lean-runtime/tests/fixtures/after_statement_changed.lean +4 -0
- package/skills/lean-formalization/lean-runtime/tests/fixtures/before.lean +4 -0
- package/skills/lean-formalization/lean-runtime/tests/fixtures/failure.lean +7 -0
- package/skills/lean-formalization/lean-runtime/tests/test_check_lean_project.py +59 -0
- package/skills/lean-formalization/lean-runtime/tests/test_cli.py +377 -0
- package/skills/lean-formalization/lean-runtime/tests/test_common_config.py +84 -0
- package/skills/lean-formalization/lean-runtime/tests/test_configure_lean.py +138 -0
- package/skills/lean-formalization/lean-runtime/tests/test_detect_sorry.py +24 -0
- package/skills/lean-formalization/lean-runtime/tests/test_direct_task.py +69 -0
- package/skills/lean-formalization/lean-runtime/tests/test_numina_runtime.py +168 -0
- package/skills/lean-formalization/lean-runtime/tests/test_validate_patch.py +29 -0
- package/skills/lean-setup/SKILL.md +99 -0
- package/skills/least-squares/README.md +85 -0
- package/skills/least-squares/SKILL.md +613 -0
- package/skills/least-squares/examples.md +380 -0
- package/skills/math-beamer/SKILL.md +325 -0
- package/skills/math-beamer/references/build-and-layout-audit.md +63 -0
- package/skills/math-beamer/references/math-domain-patterns.md +56 -0
- package/skills/math-beamer/references/template-policy.md +43 -0
- package/skills/math-beamer/references/template-source-index.md +51 -0
- package/skills/math-beamer/templates/catalog.yaml +235 -0
- package/skills/math-beamer/templates/packs/algebra-number-theory-talk/main.tex +45 -0
- package/skills/math-beamer/templates/packs/algebra-number-theory-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/algorithm-talk/main.tex +43 -0
- package/skills/math-beamer/templates/packs/algorithm-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/analysis-core-talk/main.tex +49 -0
- package/skills/math-beamer/templates/packs/analysis-core-talk/template.yaml +19 -0
- package/skills/math-beamer/templates/packs/backup-heavy-talk/main.tex +40 -0
- package/skills/math-beamer/templates/packs/backup-heavy-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/beamerposter-a0/main.tex +45 -0
- package/skills/math-beamer/templates/packs/beamerposter-a0/template.yaml +12 -0
- package/skills/math-beamer/templates/packs/combinatorics-graph-talk/main.tex +53 -0
- package/skills/math-beamer/templates/packs/combinatorics-graph-talk/template.yaml +18 -0
- package/skills/math-beamer/templates/packs/control-systems-talk/main.tex +51 -0
- package/skills/math-beamer/templates/packs/control-systems-talk/template.yaml +18 -0
- package/skills/math-beamer/templates/packs/course-lecture-zh/main.tex +43 -0
- package/skills/math-beamer/templates/packs/course-lecture-zh/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/data-experiment-results/main.tex +45 -0
- package/skills/math-beamer/templates/packs/data-experiment-results/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/dynamical-systems-talk/main.tex +42 -0
- package/skills/math-beamer/templates/packs/dynamical-systems-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/geometry-topology-talk/main.tex +43 -0
- package/skills/math-beamer/templates/packs/geometry-topology-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/information-coding-crypto-talk/main.tex +49 -0
- package/skills/math-beamer/templates/packs/information-coding-crypto-talk/template.yaml +18 -0
- package/skills/math-beamer/templates/packs/logic-foundations-category-talk/main.tex +51 -0
- package/skills/math-beamer/templates/packs/logic-foundations-category-talk/template.yaml +18 -0
- package/skills/math-beamer/templates/packs/numerical-analysis-talk/main.tex +51 -0
- package/skills/math-beamer/templates/packs/numerical-analysis-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/optimization-talk/main.tex +58 -0
- package/skills/math-beamer/templates/packs/optimization-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/pde-analysis-talk/main.tex +49 -0
- package/skills/math-beamer/templates/packs/pde-analysis-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/probability-statistics-talk/main.tex +52 -0
- package/skills/math-beamer/templates/packs/probability-statistics-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/reading-group-paper/main.tex +46 -0
- package/skills/math-beamer/templates/packs/reading-group-paper/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/seminar-minimal-en/main.tex +60 -0
- package/skills/math-beamer/templates/packs/seminar-minimal-en/template.yaml +13 -0
- package/skills/math-beamer/templates/packs/seminar-minimal-zh/main.tex +60 -0
- package/skills/math-beamer/templates/packs/seminar-minimal-zh/template.yaml +13 -0
- package/skills/math-beamer/templates/packs/theorem-proof-talk/main.tex +60 -0
- package/skills/math-beamer/templates/packs/theorem-proof-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/thesis-defense/main.tex +42 -0
- package/skills/math-beamer/templates/packs/thesis-defense/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/workshop-tutorial/main.tex +32 -0
- package/skills/math-beamer/templates/packs/workshop-tutorial/template.yaml +9 -0
- package/skills/math-beamer/templates/preview-gallery.md +32 -0
- package/skills/math-beamer/templates/previews/algebra-number-theory-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/algebra-number-theory-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/algorithm-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/algorithm-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/analysis-core-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/analysis-core-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/backup-heavy-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/backup-heavy-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/beamerposter-a0-content.png +0 -0
- package/skills/math-beamer/templates/previews/beamerposter-a0-cover.png +0 -0
- package/skills/math-beamer/templates/previews/combinatorics-graph-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/combinatorics-graph-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/control-systems-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/control-systems-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/course-lecture-zh-content.png +0 -0
- package/skills/math-beamer/templates/previews/course-lecture-zh-cover.png +0 -0
- package/skills/math-beamer/templates/previews/data-experiment-results-content.png +0 -0
- package/skills/math-beamer/templates/previews/data-experiment-results-cover.png +0 -0
- package/skills/math-beamer/templates/previews/dynamical-systems-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/dynamical-systems-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/geometry-topology-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/geometry-topology-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/information-coding-crypto-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/information-coding-crypto-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/logic-foundations-category-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/logic-foundations-category-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/numerical-analysis-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/numerical-analysis-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/optimization-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/optimization-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/pde-analysis-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/pde-analysis-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/probability-statistics-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/probability-statistics-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/reading-group-paper-content.png +0 -0
- package/skills/math-beamer/templates/previews/reading-group-paper-cover.png +0 -0
- package/skills/math-beamer/templates/previews/seminar-minimal-en-content.png +0 -0
- package/skills/math-beamer/templates/previews/seminar-minimal-en-cover.png +0 -0
- package/skills/math-beamer/templates/previews/seminar-minimal-zh-content.png +0 -0
- package/skills/math-beamer/templates/previews/seminar-minimal-zh-cover.png +0 -0
- package/skills/math-beamer/templates/previews/theorem-proof-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/theorem-proof-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/thesis-defense-content.png +0 -0
- package/skills/math-beamer/templates/previews/thesis-defense-cover.png +0 -0
- package/skills/math-beamer/templates/previews/workshop-tutorial-content.png +0 -0
- package/skills/math-beamer/templates/previews/workshop-tutorial-cover.png +0 -0
- package/skills/math-beamer/templates/review-report.md +54 -0
- package/skills/math-beamer/templates/slide-source-ledger.md +22 -0
- package/skills/math-beamer/templates/source-packet.md +50 -0
- package/skills/math-glossary/SKILL.md +347 -0
- package/skills/math-glossary/references/glossary-schema.md +71 -0
- package/skills/math-glossary/references/glossary-usage-guide.md +176 -0
- package/skills/math-glossary/references/glossary-web-template.md +127 -0
- package/skills/math-glossary/references/glossary.schema.json +76 -0
- package/skills/math-glossary/references/user-manual.md +435 -0
- package/skills/math-glossary/requirements-ai.txt +3 -0
- package/skills/math-glossary/requirements.txt +3 -0
- package/skills/math-glossary/scripts/glossary_backup.py +42 -0
- package/skills/math-glossary/scripts/glossary_build.py +467 -0
- package/skills/math-glossary/scripts/glossary_enrich_examples.py +283 -0
- package/skills/math-glossary/scripts/glossary_export.py +333 -0
- package/skills/math-glossary/scripts/glossary_web.py +1265 -0
- package/skills/math-paper-reading/README.md +163 -0
- package/skills/math-paper-reading/SKILL.md +48 -0
- package/skills/math-paper-reading/agent_router.md +36 -0
- package/skills/math-paper-reading/references/proof_pattern_taxonomy.md +123 -0
- package/skills/math-paper-reading/references/quality_rubric.md +36 -0
- package/skills/math-paper-reading/skill_base.md +627 -0
- package/skills/math-paper-reading/skill_literature_search.md +866 -0
- package/skills/math-paper-reading/skill_paper_deep_read.md +1024 -0
- package/skills/math-paper-reading/skill_pathway_proof.md +718 -0
- package/skills/math-paper-reading/skill_reference_manager.md +746 -0
- package/skills/matlab-runner/SKILL.md +217 -0
- package/skills/matlab-runner/examples/README.md +33 -0
- package/skills/matlab-runner/examples/matrix_report.m +28 -0
- package/skills/matlab-runner/examples/plot_damped_sine.m +64 -0
- package/skills/matlab-runner/examples/test_vector_norm.m +12 -0
- package/skills/matlab-runner/references/client-setup.md +24 -0
- package/skills/matlab-runner/references/file-session-safety.md +86 -0
- package/skills/matlab-runner/references/numerical-safety.md +126 -0
- package/skills/matlab-runner/references/resource-safety.md +125 -0
- package/skills/mixed-integer-programming/SKILL.md +119 -0
- package/skills/mixed-integer-programming/lp-examples.md +251 -0
- package/skills/mixed-integer-programming/mip-examples-verified.md +118 -0
- package/skills/open-problem-research-pipeline/SKILL.md +76 -0
- package/skills/open-problem-research-pipeline/skill_literature_analysis.md +201 -0
- package/skills/open-problem-research-pipeline/skill_literature_proof_framework.md +206 -0
- package/skills/open-problem-research-pipeline/skill_literature_search.md +172 -0
- package/skills/open-problem-research-pipeline/skill_qskill.md +177 -0
- package/skills/osqp-solver/SKILL.md +245 -0
- package/skills/osqp-solver/references/citation.md +25 -0
- package/skills/osqp-solver/references/dual-infeasible-example.json +14 -0
- package/skills/osqp-solver/references/feasible-example.json +21 -0
- package/skills/osqp-solver/references/primal-infeasible-example.json +17 -0
- package/skills/osqp-solver/references/python-api.md +95 -0
- package/skills/osqp-solver/references/verification.md +94 -0
- package/skills/osqp-solver/scripts/check_osqp_environment.py +120 -0
- package/skills/osqp-solver/scripts/solve_qp.py +943 -0
- package/skills/paper-writing/SKILL.md +115 -0
- package/skills/paper-writing/skill_claim_evidence_ledger.md +55 -0
- package/skills/paper-writing/skill_formula_environment_and_readability.md +41 -0
- package/skills/paper-writing/skill_latex_build_and_layout_audit.md +73 -0
- package/skills/paper-writing/skill_notation_and_variable_consistency.md +42 -0
- package/skills/paper-writing/skill_paper_skeleton_and_logical_architecture.md +54 -0
- package/skills/paper-writing/skill_proof_obligation_and_assumption_audit.md +57 -0
- package/skills/paper-writing/templates/claim-evidence-ledger.md +23 -0
- package/skills/paper-writing/templates/proof-obligation-ledger.md +22 -0
- package/skills/paper-writing/templates/rapid-prototype-paper-skeleton.md +46 -0
- package/skills/paper-writing/templates/source-packet.md +37 -0
- package/skills/paper-writing/templates/submission-readiness.md +41 -0
- package/skills/proof-blueprint-review/SKILL.md +129 -0
- package/skills/proof-blueprint-review/references/agent-mediated-proof-protocol.md +57 -0
- package/skills/proof-blueprint-review/references/generation-agent.md +45 -0
- package/skills/proof-blueprint-review/references/proof-acceptance-contract.md +41 -0
- package/skills/proof-blueprint-review/references/verification-agent.md +37 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""为 glossary.json 中缺少 examples 的术语批量生成中英文例句。
|
|
2
|
+
|
|
3
|
+
AI 补全是显式可选能力。脚本不提供固定代理、模型或占位密钥;调用者必须通过
|
|
4
|
+
命令行参数或环境变量配置 OpenAI-compatible client。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import importlib.util
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import tempfile
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _load_terms(path: Path) -> list[dict[str, Any]]:
|
|
20
|
+
with path.open("r", encoding="utf-8") as handle:
|
|
21
|
+
terms = json.load(handle)
|
|
22
|
+
if not isinstance(terms, list):
|
|
23
|
+
raise ValueError("glossary.json 顶层必须是术语对象数组")
|
|
24
|
+
for index, term in enumerate(terms, 1):
|
|
25
|
+
if not isinstance(term, dict):
|
|
26
|
+
raise ValueError(f"第 {index} 条术语必须是 JSON 对象")
|
|
27
|
+
if not term.get("term_id") or not term.get("en") or not term.get("cn"):
|
|
28
|
+
raise ValueError(
|
|
29
|
+
f"第 {index} 条术语必须包含非空 term_id、en 和 cn"
|
|
30
|
+
)
|
|
31
|
+
return terms
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _atomic_json_dump(terms: list[dict[str, Any]], path: Path) -> None:
|
|
35
|
+
descriptor, temporary_name = tempfile.mkstemp(
|
|
36
|
+
prefix=f".{path.name}.",
|
|
37
|
+
suffix=".tmp",
|
|
38
|
+
dir=path.parent,
|
|
39
|
+
)
|
|
40
|
+
try:
|
|
41
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
42
|
+
json.dump(terms, handle, ensure_ascii=False, indent=2)
|
|
43
|
+
handle.write("\n")
|
|
44
|
+
handle.flush()
|
|
45
|
+
os.fsync(handle.fileno())
|
|
46
|
+
os.replace(temporary_name, path)
|
|
47
|
+
except Exception:
|
|
48
|
+
try:
|
|
49
|
+
os.unlink(temporary_name)
|
|
50
|
+
except FileNotFoundError:
|
|
51
|
+
pass
|
|
52
|
+
raise
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _build_prompt(terms_batch: list[dict[str, Any]]) -> str:
|
|
56
|
+
term_lines = []
|
|
57
|
+
for term in terms_batch:
|
|
58
|
+
field_hint = ""
|
|
59
|
+
if term.get("field"):
|
|
60
|
+
field = term["field"]
|
|
61
|
+
if isinstance(field, list):
|
|
62
|
+
field = " / ".join(str(item) for item in field)
|
|
63
|
+
field_hint = f",所属子领域:{field}"
|
|
64
|
+
term_lines.append(
|
|
65
|
+
f"- {term['en']} → {term['cn']}({term.get('pos', '')})"
|
|
66
|
+
f"{field_hint}"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
return f"""请为以下数学术语分别生成一个中英文对照的例句。
|
|
70
|
+
|
|
71
|
+
术语列表:
|
|
72
|
+
{chr(10).join(term_lines)}
|
|
73
|
+
|
|
74
|
+
要求:
|
|
75
|
+
1. 每个术语生成一个英文例句和一个中文翻译
|
|
76
|
+
2. 例句应体现该术语在数学文献中的典型用法,自然、简练
|
|
77
|
+
3. 中文翻译应为地道的中文学术表达
|
|
78
|
+
4. 严格按以下 JSON 格式输出,只输出 JSON,不要其它文字,不要用代码围栏包裹:
|
|
79
|
+
|
|
80
|
+
{{"results": [
|
|
81
|
+
{{"en": "英文术语", "example_en": "英文例句", "example_cn": "中文例句"}},
|
|
82
|
+
...
|
|
83
|
+
]}}
|
|
84
|
+
|
|
85
|
+
共 {len(terms_batch)} 条术语,每条必须都有例句。"""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def call_examples_batch(
|
|
89
|
+
terms_batch: list[dict[str, Any]],
|
|
90
|
+
client: Any,
|
|
91
|
+
model: str,
|
|
92
|
+
) -> dict[str, Any]:
|
|
93
|
+
"""通过已配置的 OpenAI-compatible client 生成一批例句。"""
|
|
94
|
+
response = client.chat.completions.create(
|
|
95
|
+
model=model,
|
|
96
|
+
messages=[{"role": "user", "content": _build_prompt(terms_batch)}],
|
|
97
|
+
temperature=0.3,
|
|
98
|
+
max_tokens=4096,
|
|
99
|
+
)
|
|
100
|
+
text = (response.choices[0].message.content or "").strip()
|
|
101
|
+
if "```json" in text:
|
|
102
|
+
text = text.split("```json", 1)[1].split("```", 1)[0].strip()
|
|
103
|
+
elif "```" in text:
|
|
104
|
+
text = text.split("```", 1)[1].split("```", 1)[0].strip()
|
|
105
|
+
result = json.loads(text)
|
|
106
|
+
if not isinstance(result, dict) or not isinstance(result.get("results"), list):
|
|
107
|
+
raise ValueError("模型返回结果缺少 results 数组")
|
|
108
|
+
return result
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _build_client(api_key: str, api_base: str | None):
|
|
112
|
+
try:
|
|
113
|
+
from openai import OpenAI
|
|
114
|
+
except ImportError as exc:
|
|
115
|
+
raise ImportError(
|
|
116
|
+
"例句补全需要可选依赖 openai;请先审阅并安装 requirements-ai.txt。"
|
|
117
|
+
) from exc
|
|
118
|
+
kwargs = {"api_key": api_key}
|
|
119
|
+
if api_base:
|
|
120
|
+
kwargs["base_url"] = api_base
|
|
121
|
+
return OpenAI(**kwargs)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _load_export_function():
|
|
125
|
+
export_path = Path(__file__).resolve().with_name("glossary_export.py")
|
|
126
|
+
spec = importlib.util.spec_from_file_location(
|
|
127
|
+
"math_glossary_export",
|
|
128
|
+
export_path,
|
|
129
|
+
)
|
|
130
|
+
if spec is None or spec.loader is None:
|
|
131
|
+
raise RuntimeError(f"无法加载导出脚本: {export_path}")
|
|
132
|
+
module = importlib.util.module_from_spec(spec)
|
|
133
|
+
spec.loader.exec_module(module)
|
|
134
|
+
return module.export_to_excel
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _refresh_excel(glossary_path: Path) -> Path:
|
|
138
|
+
export_to_excel = _load_export_function()
|
|
139
|
+
exported = Path(export_to_excel(glossary_path, glossary_path.parent))
|
|
140
|
+
for candidate in glossary_path.parent.glob("glossary_*.xlsx"):
|
|
141
|
+
if candidate.resolve() != exported.resolve():
|
|
142
|
+
candidate.unlink()
|
|
143
|
+
print(f"已删除旧 Excel: {candidate.name}")
|
|
144
|
+
return exported
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def enrich_glossary(
|
|
148
|
+
glossary_path: str | os.PathLike[str],
|
|
149
|
+
*,
|
|
150
|
+
api_key: str,
|
|
151
|
+
model: str,
|
|
152
|
+
api_base: str | None = None,
|
|
153
|
+
batch_size: int = 20,
|
|
154
|
+
export_excel: bool = True,
|
|
155
|
+
delay_seconds: float = 1.0,
|
|
156
|
+
client: Any | None = None,
|
|
157
|
+
) -> tuple[int, int]:
|
|
158
|
+
"""补全例句并返回 ``(updated, missing_before)``。"""
|
|
159
|
+
if batch_size < 1:
|
|
160
|
+
raise ValueError("batch_size 必须大于 0")
|
|
161
|
+
|
|
162
|
+
path = Path(glossary_path).expanduser().resolve()
|
|
163
|
+
terms = _load_terms(path)
|
|
164
|
+
missing = [
|
|
165
|
+
term
|
|
166
|
+
for term in terms
|
|
167
|
+
if not term.get("examples")
|
|
168
|
+
]
|
|
169
|
+
print(f"总计 {len(terms)} 条,缺例句 {len(missing)} 条")
|
|
170
|
+
if not missing:
|
|
171
|
+
print("所有术语都已有例句。")
|
|
172
|
+
return 0, 0
|
|
173
|
+
|
|
174
|
+
if not api_key:
|
|
175
|
+
raise ValueError("必须通过 --api-key 或 MATH_GLOSSARY_API_KEY 提供密钥")
|
|
176
|
+
if not model:
|
|
177
|
+
raise ValueError("必须通过 --model 或 MATH_GLOSSARY_MODEL 提供模型名")
|
|
178
|
+
|
|
179
|
+
configured_client = client or _build_client(api_key, api_base)
|
|
180
|
+
updated = 0
|
|
181
|
+
for offset in range(0, len(missing), batch_size):
|
|
182
|
+
batch = missing[offset : offset + batch_size]
|
|
183
|
+
batch_number = offset // batch_size + 1
|
|
184
|
+
total_batches = (len(missing) + batch_size - 1) // batch_size
|
|
185
|
+
print(
|
|
186
|
+
f"批次 {batch_number}/{total_batches}:"
|
|
187
|
+
f"处理 {batch[0]['en']} ... {batch[-1]['en']}"
|
|
188
|
+
)
|
|
189
|
+
try:
|
|
190
|
+
result = call_examples_batch(batch, configured_client, model)
|
|
191
|
+
except Exception as exc:
|
|
192
|
+
print(f" 错误:{exc}")
|
|
193
|
+
print(" 跳过此批,继续下一批。")
|
|
194
|
+
continue
|
|
195
|
+
|
|
196
|
+
result_map = {
|
|
197
|
+
str(item.get("en", "")).strip(): item
|
|
198
|
+
for item in result["results"]
|
|
199
|
+
if isinstance(item, dict)
|
|
200
|
+
}
|
|
201
|
+
for term in batch:
|
|
202
|
+
generated = result_map.get(term["en"])
|
|
203
|
+
if not generated:
|
|
204
|
+
print(f" 未匹配:{term['en']}")
|
|
205
|
+
continue
|
|
206
|
+
example_en = str(generated.get("example_en", "")).strip()
|
|
207
|
+
example_cn = str(generated.get("example_cn", "")).strip()
|
|
208
|
+
if not example_en or not example_cn:
|
|
209
|
+
print(f" 返回例句不完整:{term['en']}")
|
|
210
|
+
continue
|
|
211
|
+
term["examples"] = [{"en": example_en, "cn": example_cn}]
|
|
212
|
+
term["updated_at"] = time.strftime("%Y-%m-%d")
|
|
213
|
+
updated += 1
|
|
214
|
+
print(f" 已更新:{term['en']}")
|
|
215
|
+
|
|
216
|
+
if offset + batch_size < len(missing) and delay_seconds > 0:
|
|
217
|
+
time.sleep(delay_seconds)
|
|
218
|
+
|
|
219
|
+
terms.sort(
|
|
220
|
+
key=lambda term: (
|
|
221
|
+
term.get("en", "").lower(),
|
|
222
|
+
term.get("cn", "").lower(),
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
for index, term in enumerate(terms, 1):
|
|
226
|
+
term["idx"] = index
|
|
227
|
+
_atomic_json_dump(terms, path)
|
|
228
|
+
|
|
229
|
+
if export_excel:
|
|
230
|
+
exported = _refresh_excel(path)
|
|
231
|
+
print(f"已导出 Excel: {exported}")
|
|
232
|
+
print(f"更新了 {updated}/{len(missing)} 条术语的例句")
|
|
233
|
+
return updated, len(missing)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
237
|
+
parser = argparse.ArgumentParser(
|
|
238
|
+
description="通过显式配置的 OpenAI-compatible API 补全术语例句。"
|
|
239
|
+
)
|
|
240
|
+
parser.add_argument("glossary", help="glossary.json 路径")
|
|
241
|
+
parser.add_argument(
|
|
242
|
+
"--api-key",
|
|
243
|
+
default=os.environ.get("MATH_GLOSSARY_API_KEY"),
|
|
244
|
+
help="API 密钥;也可用 MATH_GLOSSARY_API_KEY",
|
|
245
|
+
)
|
|
246
|
+
parser.add_argument(
|
|
247
|
+
"--api-base",
|
|
248
|
+
default=os.environ.get("MATH_GLOSSARY_API_BASE"),
|
|
249
|
+
help="可选 endpoint;也可用 MATH_GLOSSARY_API_BASE",
|
|
250
|
+
)
|
|
251
|
+
parser.add_argument(
|
|
252
|
+
"--model",
|
|
253
|
+
default=os.environ.get("MATH_GLOSSARY_MODEL"),
|
|
254
|
+
help="模型名;也可用 MATH_GLOSSARY_MODEL",
|
|
255
|
+
)
|
|
256
|
+
parser.add_argument("--batch-size", type=int, default=20)
|
|
257
|
+
parser.add_argument(
|
|
258
|
+
"--no-export",
|
|
259
|
+
action="store_true",
|
|
260
|
+
help="更新 JSON 后不导出 Excel",
|
|
261
|
+
)
|
|
262
|
+
return parser
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def main(argv: list[str] | None = None) -> int:
|
|
266
|
+
args = build_parser().parse_args(argv)
|
|
267
|
+
try:
|
|
268
|
+
enrich_glossary(
|
|
269
|
+
args.glossary,
|
|
270
|
+
api_key=args.api_key or "",
|
|
271
|
+
api_base=args.api_base,
|
|
272
|
+
model=args.model or "",
|
|
273
|
+
batch_size=args.batch_size,
|
|
274
|
+
export_excel=not args.no_export,
|
|
275
|
+
)
|
|
276
|
+
except (ImportError, OSError, ValueError, json.JSONDecodeError) as exc:
|
|
277
|
+
print(f"错误:{exc}")
|
|
278
|
+
return 2
|
|
279
|
+
return 0
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
if __name__ == "__main__":
|
|
283
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""术语库 Excel 导入导出工具。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import tempfile
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
REQUIRED_FIELDS = ("term_id", "en", "cn")
|
|
15
|
+
FORMULA_PREFIXES = ("=", "+", "-", "@", "\t", "\r")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _load_terms(glossary_path: str | os.PathLike[str]) -> list[dict[str, Any]]:
|
|
19
|
+
path = Path(glossary_path)
|
|
20
|
+
with path.open("r", encoding="utf-8") as handle:
|
|
21
|
+
terms = json.load(handle)
|
|
22
|
+
if not isinstance(terms, list):
|
|
23
|
+
raise ValueError("glossary.json 顶层必须是术语对象数组")
|
|
24
|
+
for index, term in enumerate(terms, 1):
|
|
25
|
+
if not isinstance(term, dict):
|
|
26
|
+
raise ValueError(f"第 {index} 条术语必须是 JSON 对象")
|
|
27
|
+
missing = [field for field in REQUIRED_FIELDS if not term.get(field)]
|
|
28
|
+
if missing:
|
|
29
|
+
raise ValueError(
|
|
30
|
+
f"第 {index} 条术语缺少必填字段: {', '.join(missing)}"
|
|
31
|
+
)
|
|
32
|
+
return terms
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _atomic_json_dump(
|
|
36
|
+
terms: list[dict[str, Any]],
|
|
37
|
+
output_path: str | os.PathLike[str],
|
|
38
|
+
) -> None:
|
|
39
|
+
destination = Path(output_path)
|
|
40
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
descriptor, temporary_name = tempfile.mkstemp(
|
|
42
|
+
prefix=f".{destination.name}.",
|
|
43
|
+
suffix=".tmp",
|
|
44
|
+
dir=destination.parent,
|
|
45
|
+
)
|
|
46
|
+
try:
|
|
47
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
48
|
+
json.dump(terms, handle, ensure_ascii=False, indent=2)
|
|
49
|
+
handle.write("\n")
|
|
50
|
+
handle.flush()
|
|
51
|
+
os.fsync(handle.fileno())
|
|
52
|
+
os.replace(temporary_name, destination)
|
|
53
|
+
except Exception:
|
|
54
|
+
try:
|
|
55
|
+
os.unlink(temporary_name)
|
|
56
|
+
except FileNotFoundError:
|
|
57
|
+
pass
|
|
58
|
+
raise
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _openpyxl():
|
|
62
|
+
try:
|
|
63
|
+
import openpyxl
|
|
64
|
+
except ImportError as exc:
|
|
65
|
+
raise ImportError(
|
|
66
|
+
"缺少 openpyxl。请先审阅依赖,再安装 requirements.txt。"
|
|
67
|
+
) from exc
|
|
68
|
+
return openpyxl
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _excel_safe(value: Any) -> Any:
|
|
72
|
+
"""Prevent user-controlled text from becoming an Excel formula."""
|
|
73
|
+
if isinstance(value, str) and value.startswith(FORMULA_PREFIXES):
|
|
74
|
+
return f"'{value}"
|
|
75
|
+
return value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _cell_text(value: Any) -> str:
|
|
79
|
+
if value is None:
|
|
80
|
+
return ""
|
|
81
|
+
text = str(value).strip()
|
|
82
|
+
if (
|
|
83
|
+
len(text) > 1
|
|
84
|
+
and text.startswith("'")
|
|
85
|
+
and text[1:].startswith(FORMULA_PREFIXES)
|
|
86
|
+
):
|
|
87
|
+
return text[1:]
|
|
88
|
+
return text
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def export_to_excel(
|
|
92
|
+
glossary_path: str | os.PathLike[str],
|
|
93
|
+
output_dir: str | os.PathLike[str],
|
|
94
|
+
) -> str:
|
|
95
|
+
"""将 glossary.json 原子导出为 Excel 文件,供人工审阅。"""
|
|
96
|
+
openpyxl = _openpyxl()
|
|
97
|
+
from openpyxl.styles import Alignment, Font, PatternFill
|
|
98
|
+
|
|
99
|
+
terms = _load_terms(glossary_path)
|
|
100
|
+
destination_dir = Path(output_dir)
|
|
101
|
+
destination_dir.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
output_path = destination_dir / (
|
|
103
|
+
f"glossary_{datetime.now().strftime('%Y-%m-%d')}.xlsx"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
workbook = openpyxl.Workbook()
|
|
107
|
+
worksheet = workbook.active
|
|
108
|
+
worksheet.title = "术语库"
|
|
109
|
+
|
|
110
|
+
headers = [
|
|
111
|
+
"序号",
|
|
112
|
+
"英文术语",
|
|
113
|
+
"中文译名",
|
|
114
|
+
"词性",
|
|
115
|
+
"子领域",
|
|
116
|
+
"来源",
|
|
117
|
+
"例句(英文)",
|
|
118
|
+
"例句(中文)",
|
|
119
|
+
"创建时间",
|
|
120
|
+
"更新时间",
|
|
121
|
+
]
|
|
122
|
+
header_font = Font(bold=True, size=11)
|
|
123
|
+
header_fill = PatternFill(
|
|
124
|
+
start_color="D9E1F2",
|
|
125
|
+
end_color="D9E1F2",
|
|
126
|
+
fill_type="solid",
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
for column, header in enumerate(headers, 1):
|
|
130
|
+
cell = worksheet.cell(row=1, column=column, value=header)
|
|
131
|
+
cell.font = header_font
|
|
132
|
+
cell.fill = header_fill
|
|
133
|
+
cell.alignment = Alignment(horizontal="center")
|
|
134
|
+
|
|
135
|
+
for row_index, term in enumerate(terms, 2):
|
|
136
|
+
examples = term.get("examples", [])
|
|
137
|
+
if not isinstance(examples, list):
|
|
138
|
+
raise ValueError(f"{term['term_id']} 的 examples 必须是数组")
|
|
139
|
+
examples_en = "; ".join(
|
|
140
|
+
example.get("en", "")
|
|
141
|
+
for example in examples
|
|
142
|
+
if isinstance(example, dict)
|
|
143
|
+
)
|
|
144
|
+
examples_cn = "; ".join(
|
|
145
|
+
example.get("cn", "")
|
|
146
|
+
for example in examples
|
|
147
|
+
if isinstance(example, dict)
|
|
148
|
+
)
|
|
149
|
+
field_value = term.get("field", "")
|
|
150
|
+
if isinstance(field_value, list):
|
|
151
|
+
field_value = " / ".join(str(item) for item in field_value)
|
|
152
|
+
|
|
153
|
+
values = [
|
|
154
|
+
term.get("idx", row_index - 1),
|
|
155
|
+
term.get("en", ""),
|
|
156
|
+
term.get("cn", ""),
|
|
157
|
+
term.get("pos", ""),
|
|
158
|
+
field_value,
|
|
159
|
+
term.get("source", ""),
|
|
160
|
+
examples_en,
|
|
161
|
+
examples_cn,
|
|
162
|
+
term.get("created_at", ""),
|
|
163
|
+
term.get("updated_at", ""),
|
|
164
|
+
]
|
|
165
|
+
for column, value in enumerate(values, 1):
|
|
166
|
+
worksheet.cell(
|
|
167
|
+
row=row_index,
|
|
168
|
+
column=column,
|
|
169
|
+
value=_excel_safe(value),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
for column, width in enumerate(
|
|
173
|
+
[6, 22, 18, 10, 12, 20, 30, 30, 12, 12],
|
|
174
|
+
1,
|
|
175
|
+
):
|
|
176
|
+
worksheet.column_dimensions[
|
|
177
|
+
openpyxl.utils.get_column_letter(column)
|
|
178
|
+
].width = width
|
|
179
|
+
|
|
180
|
+
descriptor, temporary_name = tempfile.mkstemp(
|
|
181
|
+
prefix=f".{output_path.stem}.",
|
|
182
|
+
suffix=".xlsx",
|
|
183
|
+
dir=destination_dir,
|
|
184
|
+
)
|
|
185
|
+
os.close(descriptor)
|
|
186
|
+
try:
|
|
187
|
+
workbook.save(temporary_name)
|
|
188
|
+
workbook.close()
|
|
189
|
+
os.replace(temporary_name, output_path)
|
|
190
|
+
except Exception:
|
|
191
|
+
workbook.close()
|
|
192
|
+
try:
|
|
193
|
+
os.unlink(temporary_name)
|
|
194
|
+
except FileNotFoundError:
|
|
195
|
+
pass
|
|
196
|
+
raise
|
|
197
|
+
return str(output_path)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _parse_field(value: Any) -> list[str]:
|
|
201
|
+
if value is None:
|
|
202
|
+
return []
|
|
203
|
+
if isinstance(value, list):
|
|
204
|
+
return [str(item).strip() for item in value if str(item).strip()]
|
|
205
|
+
return [
|
|
206
|
+
part.strip()
|
|
207
|
+
for part in _cell_text(value).split("/")
|
|
208
|
+
if part.strip()
|
|
209
|
+
]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def import_from_excel(
|
|
213
|
+
excel_path: str | os.PathLike[str],
|
|
214
|
+
output_json_path: str | os.PathLike[str],
|
|
215
|
+
) -> list[dict[str, Any]]:
|
|
216
|
+
"""从 Excel 导入术语并原子写入 JSON。"""
|
|
217
|
+
openpyxl = _openpyxl()
|
|
218
|
+
workbook = openpyxl.load_workbook(excel_path, read_only=True)
|
|
219
|
+
worksheet = workbook.active
|
|
220
|
+
terms: list[dict[str, Any]] = []
|
|
221
|
+
today = datetime.now().strftime("%Y-%m-%d")
|
|
222
|
+
|
|
223
|
+
try:
|
|
224
|
+
for row in worksheet.iter_rows(min_row=2, values_only=True):
|
|
225
|
+
if not row or len(row) < 3 or not row[1]:
|
|
226
|
+
continue
|
|
227
|
+
|
|
228
|
+
en_value = _cell_text(row[1])
|
|
229
|
+
cn_value = _cell_text(row[2])
|
|
230
|
+
if not en_value or not cn_value:
|
|
231
|
+
continue
|
|
232
|
+
|
|
233
|
+
examples_en_raw = (
|
|
234
|
+
_cell_text(row[6]) if len(row) > 6 else ""
|
|
235
|
+
)
|
|
236
|
+
examples_cn_raw = (
|
|
237
|
+
_cell_text(row[7]) if len(row) > 7 else ""
|
|
238
|
+
)
|
|
239
|
+
english_examples = [
|
|
240
|
+
item.strip()
|
|
241
|
+
for item in examples_en_raw.split(";")
|
|
242
|
+
if item.strip()
|
|
243
|
+
]
|
|
244
|
+
chinese_examples = [
|
|
245
|
+
item.strip()
|
|
246
|
+
for item in examples_cn_raw.split(";")
|
|
247
|
+
if item.strip()
|
|
248
|
+
]
|
|
249
|
+
examples = [
|
|
250
|
+
{
|
|
251
|
+
"en": example,
|
|
252
|
+
"cn": (
|
|
253
|
+
chinese_examples[index]
|
|
254
|
+
if index < len(chinese_examples)
|
|
255
|
+
else ""
|
|
256
|
+
),
|
|
257
|
+
}
|
|
258
|
+
for index, example in enumerate(english_examples)
|
|
259
|
+
]
|
|
260
|
+
|
|
261
|
+
terms.append(
|
|
262
|
+
{
|
|
263
|
+
"term_id": "",
|
|
264
|
+
"en": en_value,
|
|
265
|
+
"cn": cn_value,
|
|
266
|
+
"pos": (
|
|
267
|
+
_cell_text(row[3]) if len(row) > 3 else ""
|
|
268
|
+
),
|
|
269
|
+
"field": _parse_field(
|
|
270
|
+
row[4] if len(row) > 4 else None
|
|
271
|
+
),
|
|
272
|
+
"source": (
|
|
273
|
+
_cell_text(row[5]) if len(row) > 5 else ""
|
|
274
|
+
),
|
|
275
|
+
"examples": examples,
|
|
276
|
+
"created_at": (
|
|
277
|
+
_cell_text(row[8])
|
|
278
|
+
if len(row) > 8 and row[8]
|
|
279
|
+
else today
|
|
280
|
+
),
|
|
281
|
+
"updated_at": today,
|
|
282
|
+
}
|
|
283
|
+
)
|
|
284
|
+
finally:
|
|
285
|
+
workbook.close()
|
|
286
|
+
|
|
287
|
+
terms.sort(
|
|
288
|
+
key=lambda term: (
|
|
289
|
+
term.get("en", "").lower(),
|
|
290
|
+
term.get("cn", "").lower(),
|
|
291
|
+
)
|
|
292
|
+
)
|
|
293
|
+
occurrences: dict[str, int] = {}
|
|
294
|
+
for index, term in enumerate(terms, 1):
|
|
295
|
+
base_id = term["en"].lower()
|
|
296
|
+
occurrence = occurrences.get(base_id, 0)
|
|
297
|
+
term["term_id"] = base_id if occurrence == 0 else f"{base_id}__{occurrence}"
|
|
298
|
+
occurrences[base_id] = occurrence + 1
|
|
299
|
+
term["idx"] = index
|
|
300
|
+
|
|
301
|
+
_atomic_json_dump(terms, output_json_path)
|
|
302
|
+
return terms
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
306
|
+
parser = argparse.ArgumentParser(
|
|
307
|
+
description="在 glossary.json 与审阅用 Excel 之间转换。"
|
|
308
|
+
)
|
|
309
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
310
|
+
|
|
311
|
+
export_parser = subparsers.add_parser("export", help="JSON 导出为 Excel")
|
|
312
|
+
export_parser.add_argument("glossary", help="glossary.json 路径")
|
|
313
|
+
export_parser.add_argument("output_dir", help="Excel 输出目录")
|
|
314
|
+
|
|
315
|
+
import_parser = subparsers.add_parser("import", help="Excel 导入为 JSON")
|
|
316
|
+
import_parser.add_argument("excel", help="输入 .xlsx 路径")
|
|
317
|
+
import_parser.add_argument("output_json", help="输出 glossary.json 路径")
|
|
318
|
+
return parser
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def main(argv: list[str] | None = None) -> int:
|
|
322
|
+
args = build_parser().parse_args(argv)
|
|
323
|
+
if args.command == "export":
|
|
324
|
+
result = export_to_excel(args.glossary, args.output_dir)
|
|
325
|
+
print(f"Exported to: {result}")
|
|
326
|
+
else:
|
|
327
|
+
terms = import_from_excel(args.excel, args.output_json)
|
|
328
|
+
print(f"Imported {len(terms)} terms to: {args.output_json}")
|
|
329
|
+
return 0
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
if __name__ == "__main__":
|
|
333
|
+
raise SystemExit(main())
|