Spaces:
Running on Zero

Bigbearbo commited on
Commit
49d5bc8
·
verified ·
1 Parent(s): 1fdfa6c

Word-problem reader: Qwen3-8B v7 reader + program brain + hand-wired left brain

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +29 -7
  2. app.py +192 -0
  3. core.py +191 -0
  4. data/problems.json +0 -0
  5. hs/規則樹/engine.py +781 -0
  6. hs/規則樹/樹.json +359 -0
  7. hs/規則樹/葉子/問句/問擁有.剩下-01.json +14 -0
  8. hs/規則樹/葉子/問句/問擁有.有幾-01.json +17 -0
  9. hs/規則樹/葉子/問句/問擁有.總數是-01.json +17 -0
  10. hs/規則樹/葉子/問句/問擁有.量測-01.json +14 -0
  11. hs/規則樹/葉子/問句/問擁有.錢-01.json +15 -0
  12. hs/規則樹/葉子/問句/問每份.每人-01.json +14 -0
  13. hs/規則樹/葉子/問句/問總和.合計-01.json +45 -0
  14. hs/規則樹/葉子/擁有/擁有.地點-01.json +17 -0
  15. hs/規則樹/葉子/擁有/擁有.有-01.json +19 -0
  16. hs/規則樹/葉子/百分比分數/百分比.失去-01.json +17 -0
  17. hs/規則樹/葉子/百分比分數/百分比.被動-01.json +14 -0
  18. hs/規則樹/葉子/等組比率/均分.分存量-01.json +17 -0
  19. hs/規則樹/葉子/等組比率/均分.分給-01.json +17 -0
  20. hs/規則樹/葉子/等組比率/每組.每個有-01.json +17 -0
  21. hs/規則樹/葉子/等組比率/每組.每個裡有-01.json +17 -0
  22. hs/規則樹/葉子/等組比率/等組增加.組of-01.json +33 -0
  23. hs/規則樹/葉子/等組比率/等組擁有.組of-01.json +33 -0
  24. hs/規則樹/葉子/變化/增加.得到-01.json +18 -0
  25. hs/規則樹/葉子/變化/減少.減量-01.json +56 -0
  26. hs/規則樹/葉子/轉移/轉移.收到-01.json +26 -0
  27. hs/規則樹/葉子/轉移/轉移.給人-01.json +25 -0
  28. hs/規則樹/葉子/轉移/轉移.給到-01.json +32 -0
  29. hs/規則樹/葉子/量測/累計.移動-01.json +18 -0
  30. hs/規則樹/詞庫.json +137 -0
  31. hs/語法模組/api.py +39 -0
  32. hs/語法模組/單位/換算策略/10_題內定義.py +31 -0
  33. hs/語法模組/單位/換算策略/20_固定表同維度.py +26 -0
  34. hs/語法模組/單位/模組.py +143 -0
  35. hs/語法模組/單位/比率單位.py +90 -0
  36. hs/語法模組/單位/表.py +125 -0
  37. hs/語法模組/單位/補充表.json +24 -0
  38. hs/語法模組/單位/選單位策略/10_問句指定.py +16 -0
  39. hs/語法模組/單位/選單位策略/20_全同單位.py +15 -0
  40. hs/語法模組/單位/選單位策略/30_最小單位.py +27 -0
  41. hs/語法模組/核心.py +90 -0
  42. hs/語法模組/比較/solver/10_單一未知.py +98 -0
  43. hs/語法模組/比較/solver/50_精確線性.py +186 -0
  44. hs/語法模組/比較/solver/90_聯立預留.py +15 -0
  45. hs/語法模組/比較/模組.py +174 -0
  46. hs/語法模組/比較/關係卡.json +13 -0
  47. hs/語法模組/知識庫/基礎詞.json +0 -0
  48. hs/語法模組/知識庫/換算.json +0 -0
  49. hs/語法模組/知識庫/規則登記.json +0 -0
  50. hs/語法模組/移轉/模組.py +127 -0
README.md CHANGED
@@ -1,13 +1,35 @@
1
  ---
2
- title: Word Problem Reader
3
- emoji: 📚
4
- colorFrom: gray
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Word-problem reader
3
+ emoji: 📖
4
+ colorFrom: indigo
5
+ colorTo: blue
6
  sdk: gradio
 
 
7
  app_file: app.py
8
  pinned: false
9
+ license: cc-by-nc-4.0
10
+ models:
11
+ - Qwen/Qwen3-8B
12
+ - Bigbearbo/handwired-left-brain-1
13
+ short_description: Qwen3-8B reads word problems; program brain solves
14
  ---
15
 
16
+ # Word-problem reader (英文應用題讀題)
17
+
18
+ English word problem → **Qwen3-8B** (ZeroGPU, team v7 prompt, greedy, thinking off) writes Spiral information
19
+ sentences such as `have(reggie, usd, 48, start).` and `ask(have(reggie, usd, ?, now)).` → parser → **program brain**
20
+ (Python, CPU: blocks → equations → exact solve → Spiral prefix) → guards → **hand-wired left brain**
21
+ ([Bigbearbo/handwired-left-brain-1](https://huggingface.co/Bigbearbo/handwired-left-brain-1) v0.4) computes the prefix.
22
+ If the reading does not check out, the Space refuses and says which sentence it got stuck on.
23
+
24
+ Honest numbers (self-reported, not independently verified): on 168 GSM8K-train development questions, Qwen3-8B with
25
+ the v7 prompt (zero-shot, one read) got **10 right, 7 wrong, 151 refused**; one DeepSeek v7 read of the same questions
26
+ got 19 / 5 / 144. The team's main reader uses DeepSeek (paid API, not in this Space).
27
+
28
+ Random questions: `data/problems.json`, GSM8K **train** development questions only (held-out and fixed-evaluation ids
29
+ removed; GSM8K test not used), chosen where the DeepSeek v7 reading is answered correctly by the current program brain.
30
+
31
+ Files: `app.py` (UI + Qwen on ZeroGPU), `pipeline.py` (wiring, no Gradio), `core.py` (left-brain loader, from the
32
+ HandWired-LeftBrain-1 Space), `hs/` (unchanged copies of the team's 程式腦.py, 解析.py, 讀題_LLM.py, 讀題_提示v7.py,
33
+ v7守門.py, 探索模式.py and the knowledge files they read), `tools/` (how the bundle and data were built; local replay test).
34
+
35
+ License: cc-by-nc-4.0 for this Space's code and data. Qwen3-8B: Apache-2.0. GSM8K: MIT.
app.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Word-problem reader Space: Qwen3-8B (ZeroGPU) reads an English word problem into Spiral information sentences
3
+ with the team's v7 prompt -> program brain (Python, CPU) solves -> hand-wired left brain computes the prefix.
4
+ Written by: Claude subagent (讀題 Space), 2026-11-27."""
5
+ import json
6
+ import os
7
+ import random
8
+ import threading
9
+ import time
10
+
11
+ import gradio as gr
12
+ import spaces
13
+ import torch
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer
15
+
16
+ import pipeline
17
+
18
+ MODEL = "Qwen/Qwen3-8B"
19
+ tok = AutoTokenizer.from_pretrained(MODEL)
20
+ model = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.bfloat16)
21
+ model.to("cuda")
22
+
23
+
24
+ @spaces.GPU(duration=120)
25
+ def generate(prompt):
26
+ """One greedy read, thinking off (same settings as the team's offline comparison)."""
27
+ text = tok.apply_chat_template([{"role": "user", "content": prompt}], tokenize=False,
28
+ add_generation_prompt=True, enable_thinking=False)
29
+ enc = tok([text], return_tensors="pt").to("cuda")
30
+ with torch.no_grad():
31
+ out = model.generate(**enc, max_new_tokens=pipeline.MAX_NEW_TOKENS, do_sample=False)
32
+ return tok.decode(out[0, enc["input_ids"].shape[1]:], skip_special_tokens=True)
33
+
34
+
35
+ # ---------------------------------------------------------------- program brain (CPU) + hand-wired left brain
36
+ pipeline.init()
37
+ _LB = {"fn": None, "err": None}
38
+ _lb_lock = threading.Lock()
39
+ _lb_ready = threading.Event()
40
+
41
+
42
+ def _load_lb():
43
+ try:
44
+ import core # HandWired-LeftBrain-1 v0.4 package (downloaded from the Hub)
45
+ core.init()
46
+ core._solve_inner("What is 2 + 3?")
47
+
48
+ def lb(q):
49
+ with _lb_lock: # the network code is not thread-safe
50
+ return core._solve_inner(q)
51
+ _LB["fn"] = lb
52
+ except Exception as e: # noqa: BLE001
53
+ _LB["err"] = f"{type(e).__name__}: {e}"[:200]
54
+ _lb_ready.set()
55
+
56
+
57
+ threading.Thread(target=_load_lb, daemon=True).start()
58
+
59
+ # ---------------------------------------------------------------- data
60
+ DATA = json.load(open(os.path.join(os.path.dirname(__file__), "data", "problems.json"), encoding="utf-8"))
61
+ RANDOM_TYPE = "隨機抽題型 Random type"
62
+ LABELS = [t["label"] for t in DATA["types"]]
63
+ BY_Q = {" ".join(x["question"].split()): (x, t["label"]) for t in DATA["types"] for x in t["items"]}
64
+ N_ITEMS = len(BY_Q)
65
+
66
+
67
+ def random_question(kind):
68
+ types = DATA["types"] if kind in (None, "", RANDOM_TYPE) else [t for t in DATA["types"] if t["label"] == kind]
69
+ t = random.choice(types or DATA["types"])
70
+ x = random.choice(t["items"])
71
+ return x["question"], f"🎲 {t['label']}|{x['id']}(GSM8K train 開發題,有標答;按「送出」開始讀題)", ""
72
+
73
+
74
+ # ---------------------------------------------------------------- formatting
75
+ def _code(lines):
76
+ return "```\n" + ("\n".join(lines) if lines else "(none)") + "\n```"
77
+
78
+
79
+ def _vars(rows):
80
+ out = []
81
+ for r in rows or []:
82
+ out.append(" ".join(f"{k}: {v}" for k, v in r.items()) if isinstance(r, dict) else str(r))
83
+ return out
84
+
85
+
86
+ def trace_md(r, ref):
87
+ s = ["### 耗時 Seconds", "| 階段 stage | 秒 s |", "|---|---|"]
88
+ s += [f"| {k} | {v} |" for k, v in r["seconds"].items()]
89
+ s += ["", "### 1. 斷句 Sentences", _code([f"#{i} {x}" for i, x in enumerate(r["sentences"], 1)]),
90
+ "### 2. 讀題器原始回覆 Reader reply (Qwen3-8B, v7 prompt, greedy, thinking off)", _code([r["reply"]] if r["reply"] else []),
91
+ "### 3. 資訊句 Information sentences (after the reader's own checks)", _code(r["lines"]),
92
+ "### 4. 解析結果 Parsed (中文式螺旋語)", _code(r["parsed"].split("\n") if r["parsed"] else []),
93
+ "### 5. 程式腦 Program brain", f"狀態 status: `{r['brain_status'] or '-'}`",
94
+ "變數表 variables:", _code(_vars(r["variables"])), "方程 equations:", _code(r["equations"])]
95
+ if r["teaching"]:
96
+ s += ["步驟 steps:", _code(r["teaching"])]
97
+ s += [f"前綴 prefix: `{r['prefix'] or '-'}` 程式腦精確值 exact value: `{r['brain_value'] or '-'}`",
98
+ "### 6. 左腦 Left brain (hand-wired threshold networks)", _code(r["lb_steps"])]
99
+ if r["notes"]:
100
+ s += ["註記 notes:", _code(r["notes"])]
101
+ if r["stuck"] or r["refusal"]:
102
+ s += ["### 拒答 Refusal", f"原因 reason: {r['refusal']}", _code(r["stuck"])]
103
+ if ref:
104
+ s += ["### 參考 Reference (not this run): DeepSeek v7 reading of the same question, which the current brain answers correctly",
105
+ _code(ref["deepseek_v7_lines"])]
106
+ return "\n\n".join(s)
107
+
108
+
109
+ def answer_text(r, ref):
110
+ if r["answer"] is not None:
111
+ head = f"答案 Answer: {r['answer']}"
112
+ else:
113
+ head = "拒答 Refused(不猜)"
114
+ lines = [head]
115
+ if ref is not None:
116
+ mark = {"✓": "✓ 對 correct", "✗": "✗ 錯 wrong", "拒答": "拒答 refused"}[r["verdict"]]
117
+ lines.append(f"判分 {mark} (標答 reference: {ref['gold']})")
118
+ else:
119
+ lines.append("(自己打的題目,沒有標答 no reference answer)")
120
+ if r["answer"] is None:
121
+ lines.append("原因 reason: " + (r["refusal"] or r["status"]))
122
+ if r["stuck"]:
123
+ lines.append("卡在 stuck at: " + r["stuck"][0])
124
+ else:
125
+ lines.append(r["status"])
126
+ lines.append(f"耗時 {r['seconds'].get('合計 total')} s")
127
+ return "\n".join(lines)
128
+
129
+
130
+ def solve(question):
131
+ q = " ".join((question or "").split())
132
+ hit = BY_Q.get(q)
133
+ ref = hit[0] if hit else None
134
+ _lb_ready.wait(timeout=90)
135
+ r = pipeline.solve(q, generate, _LB["fn"], gold=ref["gold"] if ref else None, pid=ref["id"] if ref else "user")
136
+ if _LB["fn"] is None and r["lb_steps"]:
137
+ r["lb_steps"] = r["lb_steps"] + [f"(左腦沒載入:{_LB['err'] or 'still loading'};以上都由 Python 分數計算)"]
138
+ return answer_text(r, ref), trace_md(r, ref)
139
+
140
+
141
+ # ---------------------------------------------------------------- page
142
+ INTRO = ("# 英文應用題讀題 Word-problem reader\n"
143
+ "**Qwen3-8B** 讀英文應用題、寫成螺旋語資訊句 → **程式腦**(Python)列式求解 → **手搓左腦**(手填權重的門檻網路)算前綴;"
144
+ "讀不懂就拒答並指出卡在哪一句,不猜。Qwen3-8B reads the problem into Spiral information sentences, the program "
145
+ "brain solves them, the hand-wired left brain does the arithmetic; it refuses instead of guessing.")
146
+
147
+ NOTES = f"""
148
+ ---
149
+ ## 說明 About
150
+
151
+ **誠實數字 Honest numbers.** Qwen3-8B 零樣本 v7 讀法,在 168 題 GSM8K train 開發題對照:**對 10、錯 7、拒 151**;
152
+ 同題 DeepSeek v7 單讀 **19/5/144**。所以這裡大多數題目會拒答,這是預期的。團隊主讀題器用 DeepSeek(付費 API,不在這個 Space)。
153
+ 數字是團隊自己量的,未經第三方驗證。On 168 GSM8K-train development questions Qwen3-8B (zero-shot, v7 prompt) got 10 right,
154
+ 7 wrong, 151 refused; a single DeepSeek v7 read of the same questions got 19 / 5 / 144. Self-reported, not independently verified.
155
+
156
+ **隨機題 Random questions.** {N_ITEMS} 題,{len(LABELS)} 類,來自 GSM8K **train**(開發題;保留題、固定驗收題已用範圍守門排除;沒有用 GSM8K test)。
157
+ 挑的是「DeepSeek v7 讀法+現在的程式腦答對」的題,所以 Qwen 讀錯或拒答的原因多半在讀題,不在程式腦。題型是依資訊句概念與題目關鍵字自動分的,可能有分錯。
158
+ 自己打的題目也可以,只是沒有標答。
159
+
160
+ **做法 How it works.**
161
+ 1. 斷句後,v7 提示(約 {pipeline.prompt_chars():,} 字的概念表、規則與例子)+編號句子送給 Qwen3-8B(ZeroGPU,bf16,貪婪解碼,`enable_thinking=False`,最多 {pipeline.MAX_NEW_TOKENS} 個新 token)。單題約 8~11 秒(加上 ZeroGPU 排隊)。
162
+ 2. 回覆逐句轉成英文式資訊句,例 `have(reggie, usd, 48, start).`、`ask(have(reggie, usd, ?, now)).`;格式不對的句子標「未讀」。
163
+ 3. 程式腦(`程式腦.py`,CPU)把資訊句接成積木與方程、精確求解,輸出螺旋語前綴(例 `減 48 乘 2 5`)。
164
+ 4. 守門:資訊句裡的字面數沒用到、資訊句沒用到(抽掉測試)、非整數答案、語意守門、v7 守門 → 拒答。解析器遇到畸形輸出無限遞迴也算拒答。
165
+ 5. 前綴逐步交給手搓左腦([Bigbearbo/handwired-left-brain-1](https://huggingface.co/Bigbearbo/handwired-left-brain-1) v0.4)算整數加減乘除;左腦不收的(非整數、單位換算)標「Python 分數計算」。每一步也跟 Python 對照。
166
+
167
+ **限制 Limits.** 只讀一次(不做第二讀/自修);一次只服務一位使用者;ZeroGPU 有每日 GPU 配額,排隊時會比較慢。程式腦是團隊共用區 2026-11-27 的版本複本(`hs/`),之後主線更新不會自動同步。
168
+
169
+ **授權 License.** 本 Space 程式與資料 cc-by-nc-4.0;Qwen3-8B 是 Apache-2.0(Qwen team);GSM8K 是 MIT(OpenAI)。
170
+ """
171
+
172
+ with gr.Blocks(title="Word-problem reader") as demo:
173
+ gr.Markdown(INTRO)
174
+ with gr.Group():
175
+ with gr.Row(equal_height=True):
176
+ question = gr.Textbox(label="題目 Question (English)", lines=7, scale=3,
177
+ placeholder="Type an English word problem, or press 🎲 for a random one.")
178
+ answer = gr.Textbox(label="回答 Answer", lines=7, scale=2, interactive=False)
179
+ with gr.Row(equal_height=True):
180
+ kind = gr.Dropdown([RANDOM_TYPE] + LABELS, value=RANDOM_TYPE, label="題型 Question type", scale=3)
181
+ dice = gr.Button("🎲 隨機出題 Random question", scale=1)
182
+ go = gr.Button("送出 Solve", variant="primary", scale=1)
183
+ picked = gr.Markdown("")
184
+ with gr.Accordion("跑的過程 Pipeline trace", open=True):
185
+ trace = gr.Markdown("(送出後顯示:資訊句、解析結果、程式腦方程、左腦每一步、耗時)")
186
+ gr.Markdown(NOTES)
187
+
188
+ dice.click(random_question, inputs=kind, outputs=[question, picked, answer], api_name="random")
189
+ go.click(solve, inputs=question, outputs=[answer, trace], api_name="solve")
190
+ question.submit(solve, inputs=question, outputs=[answer, trace], api_name=False)
191
+
192
+ demo.queue(default_concurrency_limit=1).launch()
core.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Core logic of the demo (no Gradio import, so it can be tested alone). Model package v0.4: left brain = v0.3 pipeline #83
3
+ (unchanged) + spiral/ (word-problem reader + program brain, see spiral_tab.py)."""
4
+ import concurrent.futures as cf
5
+ import importlib
6
+ import json
7
+ import os
8
+ import sys
9
+ import time
10
+ from fractions import Fraction
11
+
12
+ REPO = "Bigbearbo/handwired-left-brain-1"
13
+ REVISION = "v0.4"
14
+ MAX_LEN = 300
15
+ TIMEOUT_S = 20 # normal questions
16
+ TIMEOUT_BIG_S = 240 # big-number mode: a big product took 30-55 s per question on the author's CPU (ladder tiers, then segment core)
17
+ PKG = None
18
+ BUILD_SECONDS = None
19
+ _lb = []
20
+ _pool = cf.ThreadPoolExecutor(max_workers=1) # one worker: the network code is not thread-safe
21
+
22
+ OFFICIAL7 = ["arithmetic__add_or_sub", "arithmetic__mul", "arithmetic__div", "arithmetic__mixed", "numbers__gcd",
23
+ "numbers__div_remainder", "algebra__linear_1d"]
24
+ # First-level modules used as examples: the fast ones (others, e.g. polynomial roots, can pass the time limit)
25
+ FAST_T1 = ["comparison__pair", "comparison__sort", "numbers__lcm", "numbers__is_factor", "numbers__base_conversion",
26
+ "numbers__place_value", "arithmetic__add_sub_multiple", "arithmetic__mul_div_multiple", "algebra__linear_2d",
27
+ "algebra__sequence_next_term"]
28
+
29
+
30
+ def get_pkg():
31
+ """Local package via LOCAL_PKG, else download the model package (tag v0.4) from the Hub."""
32
+ global PKG
33
+ if PKG:
34
+ return PKG
35
+ PKG = os.environ.get("LOCAL_PKG")
36
+ if not PKG:
37
+ import tempfile
38
+ from huggingface_hub import snapshot_download
39
+ # local_dir = real files, not the cache's symlinks: spiral/ code uses Path(__file__).resolve(), which would
40
+ # follow a cache symlink into blobs/ and lose its folder layout (FileNotFoundError on the first Space run)
41
+ PKG = snapshot_download(REPO, revision=REVISION,
42
+ local_dir=os.path.join(tempfile.gettempdir(), "handwired-left-brain-1-" + REVISION))
43
+ return PKG
44
+
45
+
46
+ def init():
47
+ """Load the package and wire pipeline #83 once; BUILD_SECONDS records the time."""
48
+ global BUILD_SECONDS
49
+ if _lb:
50
+ return BUILD_SECONDS
51
+ t0 = time.time()
52
+ pkg = get_pkg()
53
+ if pkg not in sys.path:
54
+ sys.path.insert(0, pkg)
55
+ lb = importlib.import_module("lb")
56
+ lb.init()
57
+ _lb.append(lb)
58
+ BUILD_SECONDS = round(time.time() - t0, 1)
59
+ return BUILD_SECONDS
60
+
61
+
62
+ def warm_up(extra=()):
63
+ """Run the example questions (and extra ones) once so their networks are built at startup, not on a click."""
64
+ global BUILD_SECONDS
65
+ t0 = time.time()
66
+ init()
67
+ for _, q in get_examples():
68
+ _solve_inner(q)
69
+ for q in extra:
70
+ _solve_inner(q)
71
+ BUILD_SECONDS = round(time.time() - t0, 1)
72
+ return BUILD_SECONDS
73
+
74
+
75
+ def _items(name):
76
+ d = json.load(open(os.path.join(get_pkg(), "data", name), encoding="utf-8"))
77
+ return d.get("items") or d.get("題")
78
+
79
+
80
+ def get_examples(per_module=1):
81
+ """Example questions: official 7 modules (train-easy file) + the fast first-level modules (level-1 file)."""
82
+ got, out = {}, []
83
+ srcs = [("official_train_easy_1400.json", OFFICIAL7), ("level1_train_easy_2000.json", FAST_T1)]
84
+ for name, mods in srcs:
85
+ for d in _items(name):
86
+ m = d.get("dataset_module") or d.get("模組")
87
+ if m in mods and len(got.setdefault(m, [])) < per_module and 12 <= len(d["question"]) <= 90:
88
+ got[m].append(d["question"])
89
+ out.append((m, d["question"]))
90
+ return out
91
+
92
+
93
+ def _dec(v, k):
94
+ n = abs(v.numerator) * 10 ** k // v.denominator
95
+ s = str(n).rjust(k + 1, "0")
96
+ return ("-" if v < 0 else "") + s[:-k] + "." + s[-k:]
97
+
98
+
99
+ def _fmt(v):
100
+ """Fraction -> 'a/b' (plus the exact decimal when the denominator is 2^i 5^j)."""
101
+ v = Fraction(v)
102
+ if v.denominator == 1:
103
+ return str(v.numerator)
104
+ den, k2, k5 = v.denominator, 0, 0
105
+ while den % 2 == 0:
106
+ den //= 2
107
+ k2 += 1
108
+ while den % 5 == 0:
109
+ den //= 5
110
+ k5 += 1
111
+ s = f"{v.numerator}/{v.denominator}"
112
+ if den == 1:
113
+ s += f" (= {_dec(v, max(k2, k5))})"
114
+ return s
115
+
116
+
117
+ def _official(v):
118
+ v = Fraction(v)
119
+ return str(v.numerator) if v.denominator == 1 else f"{v.numerator}/{v.denominator}"
120
+
121
+
122
+ def _result(question, answer="", status="", route="", tokens="", seconds=0.0, verdict=None, raw=""):
123
+ return {"question": question, "answer": answer, "raw": raw, "status": status, "route": route,
124
+ "tokens": tokens, "seconds": round(seconds, 3), "verdict": verdict}
125
+
126
+
127
+ def _solve_inner(question, gold=None):
128
+ lb = _lb[0]
129
+ g = None if gold is None else (gold if isinstance(gold, str) else _official(gold))
130
+ r = lb.solve(question, gold=g)
131
+ raw = ans = r["answer"]
132
+ try:
133
+ if ans:
134
+ ans = _fmt(Fraction(ans))
135
+ except (ValueError, ZeroDivisionError):
136
+ pass # non-numeric answers (True, "a", "2, 3, 23", "21*w + 16") stay as text
137
+ route = r["route"] + (f" [{r['module']}]" if r["module"] else "")
138
+ return _result(question, answer=ans, raw=raw, status=r["status"], route=route, tokens=r["tokens"],
139
+ seconds=r["seconds"], verdict=r["verdict"])
140
+
141
+
142
+ def solve(question, gold=None, big=False, limit=None):
143
+ """Returns a dict: answer, raw, status, route, tokens, seconds, verdict (never raises).
144
+ gold: reference answer (Fraction or official string); with it the pipeline also grades the answer.
145
+ limit: time limit in s (default TIMEOUT_S, or TIMEOUT_BIG_S in big mode); the UI raises it for slow types."""
146
+ t0 = time.time()
147
+ q = (question or "").strip()
148
+ if not q:
149
+ return _result(q, status="Refused: empty input.")
150
+ if len(q) > MAX_LEN:
151
+ return _result(q[:40] + "...", status=f"Refused: input longer than {MAX_LEN} characters.")
152
+ lim = limit or (TIMEOUT_BIG_S if big else TIMEOUT_S)
153
+ try:
154
+ init()
155
+ return _pool.submit(_solve_inner, q, gold).result(timeout=lim)
156
+ except cf.TimeoutError:
157
+ return _result(q, status=f"Refused: timed out after {lim} s.", seconds=time.time() - t0)
158
+ except Exception as e:
159
+ return _result(q, status="Refused: internal error (" + type(e).__name__ + ").", seconds=time.time() - t0)
160
+
161
+
162
+ # ---------------------------------------------------------------- word-problem tab (spiral/): reader + program brain + left brain
163
+ WP_TIMEOUT_S = 60
164
+
165
+
166
+ def _lb_for_wp(question):
167
+ """One integer operation for the word-problem tab, answered by the hand-wired left brain (runs in the worker)."""
168
+ return _solve_inner(question)
169
+
170
+
171
+ def _wp_run(fn, text):
172
+ import spiral_tab
173
+ spiral_tab.init(get_pkg())
174
+ return fn(text, _lb_for_wp)
175
+
176
+
177
+ def solve_word_problem(text, info=False):
178
+ """English word problem (info=False) or English-style information sentences (info=True) -> dict (never raises)."""
179
+ import spiral_tab
180
+ try:
181
+ init()
182
+ fn = spiral_tab.solve_info if info else spiral_tab.solve_question
183
+ return _pool.submit(_wp_run, fn, text).result(timeout=WP_TIMEOUT_S)
184
+ except cf.TimeoutError:
185
+ r = spiral_tab._empty(text)
186
+ r["status"] = f"Refused: timed out after {WP_TIMEOUT_S} s."
187
+ return r
188
+ except Exception as e:
189
+ r = spiral_tab._empty(text)
190
+ r["status"] = "Refused: internal error (" + type(e).__name__ + ")."
191
+ return r
data/problems.json ADDED
The diff for this file is too large to render. See raw diff
 
hs/規則樹/engine.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""規則樹讀題器(#306 框架,Claude 子代理 2026-11-24)。
2
+
3
+ 讀 樹.json(節點+句法片段)、詞庫.json(詞類樹)、葉子/**/*.json(說法葉子),把英文應用題讀成
4
+ 螺旋前綴式(加 減 乘 除 小 ...),格式跟 管線_87.translate 相同。
5
+
6
+ 走法:
7
+ 題目 → 正規化 → 切成敘述子句+最後一個問句
8
+ 每個子句:所有同種類葉子都比一次(記『比對成功』)→ 從優先層 1(最具體)往後找第一個有命中的層
9
+ → 這層命中 2 片以上=衝突,整題拒答並記兩個葉子 ID → 1 片=採用
10
+ 葉子 → 意思節點(或連結:依判別條件挑一個;挑不出就拒答)→ 意思節點的輸出模板改狀態
11
+ 問句的意思節點產生求解式;式子含未知量就拒答
12
+ 整題讀成才記『實際採用』。
13
+
14
+ 對外介面:
15
+ tree_translate(q) → {"en", "kind": "story", "module": None, "src": "規則樹"} 或 None
16
+ translate(q) → 跟 管線_87.translate 一樣:樹讀不了就交給既有 DeepMind 文法(管線_85)
17
+ trace(q) → 完整紀錄:走過的葉子、意思、衝突、拒答原因、狀態表 v0
18
+ load(...) → 載入一棵樹(merge.py 用來試新葉子、拿掉詞做泛化測試)
19
+ value(en) → 驗算用:把前綴式算成 Fraction(換單位 用詞庫係數,只供驗收對答案;
20
+ 正式管線的換算交左腦第二級①換算零件)
21
+ """
22
+
23
+ from fractions import Fraction
24
+ import json
25
+ from pathlib import Path
26
+ import re
27
+
28
+ HERE = Path(__file__).resolve().parent
29
+ TREE_PATH = HERE / '樹.json'
30
+ LEX_PATH = HERE / '詞庫.json'
31
+ LEAF_DIR = HERE / '葉子'
32
+ SRC = '規則樹'
33
+ SMALL = dict(zip('zero one two three four five six seven eight nine ten eleven twelve'.split(), range(13)))
34
+ UNITS19 = ('zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen '
35
+ 'sixteen seventeen eighteen nineteen').split()
36
+ TENS = dict(zip('twenty thirty forty fifty sixty seventy eighty ninety'.split(), range(20, 100, 10)))
37
+ PRONOUNS = {'he', 'she', 'they', 'him', 'her', 'them', 'it'}
38
+ IRREGULAR = {'children': 'child', 'people': 'person', 'men': 'man', 'women': 'woman', 'feet': 'foot',
39
+ 'teeth': 'tooth', 'mice': 'mouse', 'cookies': 'cookie', 'pies': 'pie', 'movies': 'movie',
40
+ 'tomatoes': 'tomato', 'potatoes': 'potato', 'shelves': 'shelf', 'loaves': 'loaf'}
41
+ REQUIRED = ('id', '上層', '種類', '優先層', '樣式', '正例', '反例', '作者', '建立')
42
+
43
+
44
+ class Refuse(Exception):
45
+ pass
46
+
47
+
48
+ # ---------------------------------------------------------------- 字面工具
49
+ def singular(word):
50
+ if word in IRREGULAR:
51
+ return IRREGULAR[word]
52
+ if word.endswith('ies') and len(word) > 3:
53
+ return word[:-3] + 'y'
54
+ if word.endswith(('xes', 'ches', 'shes', 'sses', 'zzes')):
55
+ return word[:-2]
56
+ if word.endswith('s') and not word.endswith(('ss', 'us', 'is')):
57
+ return word[:-1]
58
+ return word
59
+
60
+
61
+ def literal(text):
62
+ text = text.strip().lstrip('$')
63
+ if text in SMALL:
64
+ return str(SMALL[text])
65
+ text = text.replace(',', '')
66
+ whole, dot, dec = text.partition('.')
67
+ if not dot:
68
+ return str(int(whole))
69
+ return f'小 {int(whole + dec)} {len(dec)}'
70
+
71
+
72
+ def quantity(text):
73
+ """數量字串 → 式子(N dozen = 乘 N 12)。"""
74
+ text = text.strip()
75
+ if text.endswith(' dozen'):
76
+ return ('乘', literal(text.split()[0]), '12')
77
+ return literal(text)
78
+
79
+
80
+ def percent(text):
81
+ n = literal(re.sub(r' *(?:%|percent)$', '', text))
82
+ if n.startswith('小 '):
83
+ _, a, s = n.split()
84
+ return f'小 {a} {int(s) + 2}'
85
+ return f'小 {n} 2'
86
+
87
+
88
+ def has_decimal(expr):
89
+ if isinstance(expr, str):
90
+ return expr.startswith('小 ')
91
+ if expr[0] == '換單位':
92
+ return has_decimal(expr[1])
93
+ return any(has_decimal(x) for x in expr[1:])
94
+
95
+
96
+ def prefix(expr, decimals=None):
97
+ if decimals is None:
98
+ decimals = has_decimal(expr)
99
+ if isinstance(expr, str):
100
+ return f'小 {expr} 0' if decimals and not expr.startswith('小 ') else expr
101
+ if expr[0] == '換單位':
102
+ return f'換單位 {prefix(expr[1], decimals)} {expr[2]} {expr[3]}'
103
+ return ' '.join([expr[0]] + [prefix(x, decimals) for x in expr[1:]])
104
+
105
+
106
+ def has_unknown(expr):
107
+ if expr is None:
108
+ return True
109
+ if isinstance(expr, tuple):
110
+ return any(has_unknown(x) for x in (expr[1:2] if expr[0] == '換單位' else expr[1:]))
111
+ return False
112
+
113
+
114
+ def words_to_digits(text):
115
+ def tens(m):
116
+ return str(TENS[m[1]] + (UNITS19.index(m[2]) if m[2] else 0))
117
+ text = re.sub(rf"\b({'|'.join(TENS)})(?:-({'|'.join(UNITS19[1:10])}))?\b", tens, text)
118
+ return re.sub(rf"\b({'|'.join(UNITS19[13:])})\b", lambda m: str(UNITS19.index(m[1])), text)
119
+
120
+
121
+ def normalize(question):
122
+ t = ' '.join(question.replace('’', "'").split())
123
+ t = re.sub(r'\$ (?=\d)', '$', t)
124
+ t = re.sub(r' ([.,?!])', r'\1', t)
125
+ t = re.sub(r'([.?!])(?=[A-Za-z])', r'\1 ', t)
126
+ t = re.sub(r'(?<=[a-z0-9]) (?=(?:How|What) )', '. ', t)
127
+ t = t.lower()
128
+ t = re.sub(r'\b(\d[\d,]*(?:\.\d+)?) dollars?\b', r'$\1', t)
129
+ return words_to_digits(t)
130
+
131
+
132
+ def clause_text(sentence, tree=None):
133
+ """葉子正反例也用這個轉成跟讀題時一樣的子句寫法(給 tree 時連句首 then/so 一起去掉)。"""
134
+ t = normalize(sentence).strip().rstrip('.?!').strip()
135
+ return tree.lead.sub('', t).strip(' ,') if tree is not None else t
136
+
137
+
138
+ # ---------------------------------------------------------------- 詞類樹
139
+ class Lexicon:
140
+ def __init__(self, data, remove=None):
141
+ """remove:{詞類: [詞, ...]},泛化測試用(先拿掉,規則看不到)。"""
142
+ self.classes = data['類']
143
+ remove = remove or {}
144
+ self.words = {} # 類 → {lemma: entry}
145
+ for name, c in self.classes.items():
146
+ gone = set(remove.get(name, ()))
147
+ self.words[name] = {k: v for k, v in (c.get('詞') or {}).items() if k not in gone}
148
+ self.children = {}
149
+ for name, c in self.classes.items():
150
+ self.children.setdefault(c.get('上層'), []).append(name)
151
+ self.form = {} # 寫法 → [(類, lemma)]
152
+ for name, ws in self.words.items():
153
+ for lemma, e in ws.items():
154
+ for f in e.get('形', [lemma]):
155
+ self.form.setdefault(f, []).append((name, lemma))
156
+ self._rx = {}
157
+
158
+ def subtree(self, name, _seen=None):
159
+ """這個詞類+所有下層詞類。詞類可寫 "包含": [甲類, 乙類]=抽出來的聯集概念(例:減量動詞=失類∪給類),
160
+ 不用搬動原本的詞,原本的詞類照常可單獨用。"""
161
+ if name not in self.classes:
162
+ raise KeyError(f'詞庫沒有這個詞類:{name}')
163
+ seen = _seen if _seen is not None else set()
164
+ if name in seen:
165
+ return []
166
+ seen.add(name)
167
+ out = [name]
168
+ for ch in self.children.get(name, []) + list(self.classes[name].get('包含', [])):
169
+ out += self.subtree(ch, seen)
170
+ return out
171
+
172
+ def ancestors(self, name):
173
+ out = []
174
+ while name:
175
+ out.append(name)
176
+ name = self.classes[name].get('上層')
177
+ return out
178
+
179
+ def regex(self, name):
180
+ if name not in self._rx:
181
+ forms, opens = set(), []
182
+ for cls in self.subtree(name):
183
+ for e_lemma, e in self.words[cls].items():
184
+ forms.update(e.get('形', [e_lemma]))
185
+ if self.classes[cls].get('樣式'):
186
+ opens.append(self.classes[cls]['樣式'])
187
+ alts = [re.escape(f) for f in sorted(forms, key=len, reverse=True)] + opens
188
+ self._rx[name] = '(?:' + '|'.join(alts or ['(?!)']) + ')'
189
+ return self._rx[name]
190
+
191
+ def lookup(self, text, hint=None):
192
+ """寫法 → (類, lemma, 屬性);hint=槽的詞類(可多個),先找它的子樹。找不到回 None。"""
193
+ hits = self.form.get(text, [])
194
+ if hint:
195
+ allowed = {c for h in hint for c in self.subtree(h)}
196
+ inside = [h for h in hits if h[0] in allowed]
197
+ hits = inside or hits
198
+ if not hits:
199
+ return None
200
+ cls, lemma = hits[0]
201
+ return cls, lemma, self.words[cls][lemma]
202
+
203
+ def dimension(self, cls):
204
+ """單位詞所屬的維度類(例:長度單位);不是單位回 None。"""
205
+ anc = self.ancestors(cls)
206
+ return anc[-2] if len(anc) >= 2 and anc[-1] == '單位' else ('貨幣' if '貨幣' in anc else None)
207
+
208
+ def factor(self, lemma):
209
+ for cls, ws in self.words.items():
210
+ if lemma in ws and '係數' in ws[lemma]:
211
+ return Fraction(ws[lemma]['係數'])
212
+ raise KeyError(lemma)
213
+
214
+
215
+ # ---------------------------------------------------------------- 樹
216
+ class Tree:
217
+ def __init__(self, tree, lexicon, leaves):
218
+ self.tree = tree
219
+ self.lex = lexicon
220
+ self.nodes = {n['id']: n for n in tree['節點']}
221
+ self.frag = tree['片段']
222
+ self.lead = re.compile(self.expand(self.frag['前導']))
223
+ self.leaves = []
224
+ for leaf in leaves:
225
+ leaf = dict(leaf)
226
+ leaf['_rx'] = re.compile(self.expand(leaf['樣式']))
227
+ self.leaves.append(leaf)
228
+ self.by_id = {leaf['id']: leaf for leaf in self.leaves}
229
+ self.kinds = {}
230
+ for leaf in self.leaves:
231
+ self.kinds.setdefault(leaf['種類'], []).append(leaf)
232
+
233
+ def expand(self, text, depth=0):
234
+ if depth > 8:
235
+ raise ValueError('片段互相引用太深')
236
+
237
+ def slot(m):
238
+ name, classes = m[1], m[2]
239
+ body = '|'.join(self.class_rx(c) for c in classes.split('|'))
240
+ return f'(?P<{name}>{body})' if name else f'(?:{body})'
241
+
242
+ def frag(m):
243
+ return '(?:' + self.expand(self.frag[m[1]], depth + 1) + ')' if m[1] in self.frag else m[0]
244
+
245
+ text = re.sub(r'<(?:(\w+):)?([\w|]+)>', slot, text)
246
+ return re.sub(r'\{(\w+)\}', frag, text)
247
+
248
+ def class_rx(self, name):
249
+ if name in self.frag:
250
+ return '(?:' + self.expand(self.frag[name]) + ')'
251
+ return self.lex.regex(name)
252
+
253
+ def slot_classes(self, leaf):
254
+ return {m[1]: m[2].split('|') for m in re.finditer(r'<(\w+):([\w|]+)>', leaf['樣式'])}
255
+
256
+ def matches(self, kind, text):
257
+ out = []
258
+ for leaf in self.kinds.get(kind, []):
259
+ m = leaf['_rx'].fullmatch(text)
260
+ if m:
261
+ out.append((leaf, {k: v for k, v in m.groupdict().items() if v is not None}))
262
+ return out
263
+
264
+ def choose(self, kind, text, stats=None):
265
+ """回 (葉子, 欄位, 這句所有命中的葉子 ID);沒命中回 None;同層衝突丟 Refuse。"""
266
+ hits = self.matches(kind, text)
267
+ if not hits:
268
+ return None
269
+ top = min(leaf['優先層'] for leaf, _ in hits)
270
+ layer = [(leaf, g) for leaf, g in hits if leaf['優先層'] == top]
271
+ if len(layer) > 1:
272
+ ids = sorted(leaf['id'] for leaf, _ in layer)
273
+ if stats is not None:
274
+ stats.conflict(text, ids)
275
+ raise Refuse(f'衝突:同一優先層 {top} 有 {" 和 ".join(ids)} 都命中「{text}」')
276
+ leaf, g = layer[0]
277
+ g = dict(leaf.get('預設', {}), **g)
278
+ return leaf, g, [x['id'] for x, _ in hits]
279
+
280
+
281
+ def load(tree_path=TREE_PATH, lex_path=LEX_PATH, leaf_dir=LEAF_DIR, replace=(), drop=(), remove_words=None,
282
+ lex_patch=None):
283
+ """replace:要加入或替換的葉子(dict),drop:要拿掉的葉子 ID,remove_words:泛化測試拿掉的詞,
284
+ lex_patch:{詞類: 定義},試合併時先加進詞庫(不寫檔)。"""
285
+ tree = json.loads(Path(tree_path).read_text(encoding='utf-8'))
286
+ lex_data = json.loads(Path(lex_path).read_text(encoding='utf-8'))
287
+ if lex_patch:
288
+ lex_data['類'].update(lex_patch)
289
+ lex = Lexicon(lex_data, remove_words)
290
+ leaves = {}
291
+ for p in sorted(Path(leaf_dir).rglob('*.json')):
292
+ leaf = json.loads(p.read_text(encoding='utf-8'))
293
+ leaf['_檔'] = str(p)
294
+ leaves[leaf['id']] = leaf
295
+ for leaf in replace:
296
+ leaves[leaf['id']] = leaf
297
+ for i in drop:
298
+ leaves.pop(i, None)
299
+ return Tree(tree, lex, list(leaves.values()))
300
+
301
+
302
+ # ---------------------------------------------------------------- 狀態
303
+ class Story:
304
+ def __init__(self, tree):
305
+ self.t = tree
306
+ self.lex = tree.lex
307
+ self.items = {} # (主體, 物) → 式子(None=未知)
308
+ self.units = {} # (主體, 維度) → 存量的單位 lemma
309
+ self.attrs = {} # 物 → 詞庫屬性
310
+ self.rates = {} # 容器 → (物, 式子)
311
+ self.share = None
312
+ self.people = []
313
+ self.places = []
314
+ self.last_item = None
315
+ self.facts = []
316
+ self.query = None
317
+
318
+ # ---- 欄位轉換
319
+ def who(self, word, place=False):
320
+ if word is None:
321
+ return None
322
+ word = re.sub(r'^(?:the|a|an) ', '', word)
323
+ if word in PRONOUNS:
324
+ if len(self.people) != 1:
325
+ raise Refuse('代名詞沒有唯一先行詞')
326
+ return self.people[0]
327
+ bucket = self.places if place else self.people
328
+ if word not in self.people and word not in self.places:
329
+ bucket.append(word)
330
+ return word
331
+
332
+ def known(self, word):
333
+ """已經在題目出現過的人(代名詞有唯一先行詞也算)。"""
334
+ word = re.sub(r'^(?:the|a|an) ', '', word or '')
335
+ if word in PRONOUNS:
336
+ return len(self.people) == 1
337
+ return word in self.people
338
+
339
+ def what(self, text, n=None, hint=None):
340
+ """回 (物的鍵, 單位 lemma 或 None)。"""
341
+ if not isinstance(n, str):
342
+ n = None
343
+ if text in (None, '', 'them', 'it', 'more'):
344
+ if n is not None and n.startswith('$'):
345
+ return 'USD', 'dollar'
346
+ if self.last_item is None:
347
+ raise Refuse('物品沒有先行詞')
348
+ return self.last_item
349
+ if text in ('money',):
350
+ return 'USD', 'dollar'
351
+ word = text.split()[-1]
352
+ found = self.lex.lookup(word, hint) or self.lex.lookup(word)
353
+ if found:
354
+ cls, lemma, attrs = found
355
+ dim = self.lex.dimension(cls)
356
+ if dim == '貨幣':
357
+ key = ('USD', lemma)
358
+ elif dim:
359
+ key = (dim, lemma)
360
+ else:
361
+ key = (lemma, None)
362
+ self.attrs[lemma] = attrs
363
+ else:
364
+ key = (singular(word), None)
365
+ if n is not None and n.startswith('$'):
366
+ key = ('USD', 'dollar')
367
+ self.last_item = key
368
+ return key
369
+
370
+ def log(self, relation, subject, item, q, **extra):
371
+ self.facts.append(dict(relation=relation, subject=subject, item=item,
372
+ quantity=None if q is None else prefix(q, False), **extra))
373
+
374
+ def convert(self, expr, src, dst):
375
+ if src == dst or src is None or dst is None:
376
+ return expr
377
+ return ('換單位', expr, src, dst)
378
+
379
+ # ---- 模板值
380
+ def val(self, spec, g):
381
+ if isinstance(spec, list):
382
+ return [self.val(x, g) for x in spec]
383
+ if isinstance(spec, str) and spec.startswith('$'):
384
+ return g.get(spec[1:])
385
+ return spec
386
+
387
+ def apply(self, ops, g):
388
+ for op in ops:
389
+ spec = {k: self.val(v, g) for k, v in op.items()}
390
+ getattr(self, 'op_' + op['op'])(spec)
391
+
392
+ def amount(self, spec):
393
+ """模板的量:字串(槽值)或 [運算, 槽值, 槽值]。"""
394
+ if isinstance(spec, list):
395
+ if None in spec[1:]:
396
+ raise Refuse('模板的量缺欄位')
397
+ return (spec[0],) + tuple(quantity(x) for x in spec[1:])
398
+ if spec is None:
399
+ raise Refuse('沒有量')
400
+ return quantity(spec)
401
+
402
+ # ---- 敘述的 op
403
+ def op_擁有(self, s):
404
+ who = self.who(s['主體'])
405
+ item, unit = self.what(s['物'], s.get('量'))
406
+ key = (who, item)
407
+ if key in self.items:
408
+ raise Refuse('同一個量第二次給起始值')
409
+ self.items[key] = self.amount(s['量'])
410
+ self.units[key] = unit
411
+ self.log('擁有', who, item, self.items[key], **({'unit': unit} if unit else {}))
412
+
413
+ def op_變化(self, s):
414
+ who = self.who(s['主體'])
415
+ item, unit = self.what(s['物'], s.get('量'))
416
+ key = (who, item)
417
+ n = self.amount(s['量'])
418
+ if key not in self.items:
419
+ self.try_materialize_group_stock(key)
420
+ if key not in self.items:
421
+ missing = s.get('缺起點', '拒答')
422
+ if missing == '當起點' and s['方向'] == '加':
423
+ self.items[key], self.units[key] = n, unit
424
+ self.log('擁有', who, item, n, **({'unit': unit} if unit else {}))
425
+ return
426
+ if missing == '未知':
427
+ self.items[key], self.units[key] = None, unit
428
+ self.log('未知擁有', who, item, None)
429
+ else:
430
+ raise Refuse(f'{who} 的 {item} 沒有起始量')
431
+ n = self.convert(n, unit, self.units.get(key))
432
+ cur = self.items[key]
433
+ self.items[key] = None if cur is None else (s['方向'], cur, n)
434
+ self.log('變化', who, item, n, direction=s['方向'])
435
+
436
+ def op_每組(self, s):
437
+ box = self.what(s['容器'], hint=['容器'])[0]
438
+ item, unit = self.what(s['物'], s.get('量'))
439
+ if box in self.rates:
440
+ raise Refuse('同一種容器第二個比率')
441
+ self.rates[box] = (item, self.amount(s['量']))
442
+ self.log('每組', box, item, self.rates[box][1])
443
+
444
+ def op_均分(self, s):
445
+ who = self.who(s['主體'])
446
+ item, _ = self.what(s.get('物'), s.get('量'))
447
+ if s.get('量'):
448
+ total = self.amount(s['量'])
449
+ else:
450
+ self.try_materialize_group_stock((who, item))
451
+ if (who, item) not in self.items:
452
+ raise Refuse('均分全部,但沒有存量')
453
+ total = self.items[(who, item)]
454
+ if self.share:
455
+ raise Refuse('第二次均分')
456
+ count = quantity(s['份數'])
457
+ if count == '1':
458
+ raise Refuse('一份不是均分')
459
+ recv = singular(s['受者'].split()[-1])
460
+ self.share = (who, item, total, count, recv)
461
+ whole = self.attrs.get(item, {}).get('可切') is False
462
+ self.log('均分', who, item, total, recipients=count, recipient=recv, **({'整數': True} if whole else {}))
463
+
464
+ def op_百分比減(self, s):
465
+ item = self.what(s['物'])[0] if s.get('物') else (self.last_item[0] if self.last_item else None)
466
+ if s.get('主體'):
467
+ key = (self.who(s['主體']), item)
468
+ else:
469
+ keys = self.holders(item)
470
+ if len(keys) != 1:
471
+ raise Refuse('百分比找不到唯一持有者')
472
+ key = keys[0]
473
+ self.try_materialize_group_stock(key)
474
+ if key not in self.items or self.items[key] is None:
475
+ raise Refuse('百分比沒有已知存量')
476
+ cur = self.items[key]
477
+ part = ('乘', cur, percent(s['百分']))
478
+ self.items[key] = ('減', cur, part)
479
+ self.log('變化', key[0], key[1], part, direction='減')
480
+
481
+ # ---- 問句的 op
482
+ def stock(self, key):
483
+ if key in self.items:
484
+ return self.items[key]
485
+ who, item = key
486
+ derived = [('乘', self.items[(who, box)], k) for box, (it, k) in self.rates.items()
487
+ if it == item and (who, box) in self.items]
488
+ if len(derived) != 1:
489
+ raise Refuse(f'問的量找不到:{who} 的 {item}')
490
+ return derived[0]
491
+
492
+ def try_materialize_group_stock(self, key):
493
+ # Proof-of-concept only: keeps the derived inventory at first mutation.
494
+ # A complete design must track source dependencies and container updates.
495
+ if key in self.items:
496
+ return False
497
+ try:
498
+ computed = self.stock(key) # exactly one derivation or raises
499
+ except Refuse:
500
+ return False
501
+ self.items[key] = computed
502
+ self.units[key] = None # only countable item families are tested here
503
+ self.log('推導存量', key[0], key[1], computed, source='group_rate')
504
+ return True
505
+
506
+ def holders(self, item):
507
+ keys = [k for k in self.items if k[1] == item]
508
+ keys += [(w, item) for box, (it, _) in self.rates.items() if it == item
509
+ for (w, b) in list(self.items) if b == box and (w, item) not in keys]
510
+ return keys
511
+
512
+ def ask(self, relation, subject, item, expr, **extra):
513
+ if has_unknown(expr):
514
+ raise Refuse('答案依賴未知量')
515
+ self.query = dict(relation=relation, subject=subject, item=item, **extra)
516
+ return expr
517
+
518
+ def op_問擁有(self, s):
519
+ item, unit = self.what(s['物'], hint=['物品', '單位'])
520
+ if s.get('主體'):
521
+ key = (self.who(s['主體']), item)
522
+ else:
523
+ keys = self.holders(item)
524
+ if len(keys) != 1:
525
+ raise Refuse('沒指明主體,持有者不唯一')
526
+ key = keys[0]
527
+ if key[0] not in self.people + self.places:
528
+ raise Refuse('問的主體沒在題目出現')
529
+ expr = self.convert(self.stock(key), self.units.get(key), unit)
530
+ return self.ask('擁有', key[0], item, expr, **({'unit': unit} if unit else {}))
531
+
532
+ def op_問總和(self, s):
533
+ item, _ = self.what(s['物'])
534
+ names = [self.who(x) for x in s['主體們'] if x]
535
+ if not names:
536
+ names = [k[0] for k in self.holders(item)]
537
+ if len(names) < 2:
538
+ raise Refuse('they 找不到兩個以上持有者')
539
+ if len(set(names)) != len(names):
540
+ raise Refuse('總和重複主體')
541
+ total = self.stock((names[0], item))
542
+ for n in names[1:]:
543
+ total = ('加', total, self.stock((n, item)))
544
+ return self.ask('總和', names, item, total)
545
+
546
+ def op_問每份(self, s):
547
+ if not self.share:
548
+ raise Refuse('問每份但沒有均分')
549
+ who, item, total, count, recv = self.share
550
+ if s.get('物') and self.what(s['物'])[0] != item:
551
+ raise Refuse('問的物品跟均分的不同')
552
+ if singular(s['受者'].split()[-1]) != recv:
553
+ raise Refuse('問的受者跟均分的不同')
554
+ return self.ask('每份', who, item, ('除', total, count), recipient=recv)
555
+
556
+ # ---- 一個子句
557
+ def clause(self, kind, text, stats, used):
558
+ picked = self.t.choose(kind, text, stats)
559
+ if picked is None:
560
+ return None
561
+ leaf, g, hits = picked
562
+ meaning, g = self.resolve(leaf, g)
563
+ node = self.t.nodes[meaning]
564
+ used.append({'子句': text, '葉子': leaf['id'], '意思': meaning, '同句命中': hits})
565
+ result = None
566
+ for op in node['輸出']:
567
+ spec = {k: self.val(v, g) for k, v in op.items()}
568
+ result = getattr(self, 'op_' + op['op'])(spec)
569
+ return result if kind == '問句' else True
570
+
571
+ def resolve(self, leaf, g):
572
+ if '連結' not in leaf:
573
+ return leaf['上層'], g
574
+ ok = [link for link in leaf['連結'] if self.condition(link.get('條件', {}), g)]
575
+ if len(ok) != 1:
576
+ raise Refuse(f'{leaf["id"]} 一個說法兩種意思,判別條件挑出 {len(ok)} 個')
577
+ link = ok[0]
578
+ g = dict(g)
579
+ for a, b in link.get('改名', {}).items():
580
+ if a in g:
581
+ g[b] = g.pop(a)
582
+ return link['意思'], g
583
+
584
+ def condition(self, cond, g):
585
+ """條件:{"已知人物": 槽 或 [槽...], "非已知人物": ...},全部成立才算。"""
586
+ for name, slots in cond.items():
587
+ for slot in [slots] if isinstance(slots, str) else slots:
588
+ value = g.get(slot)
589
+ if name == '已知人物' and not self.known(value):
590
+ return False
591
+ if name == '非已知人物' and self.known(value):
592
+ return False
593
+ return True
594
+
595
+
596
+ # ---------------------------------------------------------------- 讀題
597
+ class Stats:
598
+ def __init__(self):
599
+ self.count = {}
600
+ self.conflicts = []
601
+
602
+ def row(self, i):
603
+ return self.count.setdefault(i, {'比對成功': 0, '實際採用': 0})
604
+
605
+ def matched(self, i):
606
+ self.row(i)['比對成功'] += 1
607
+
608
+ def adopted(self, i):
609
+ self.row(i)['實際採用'] += 1
610
+
611
+ def conflict(self, text, ids):
612
+ if len(self.conflicts) < 500:
613
+ self.conflicts.append({'子句': text, '葉子': ids})
614
+
615
+
616
+ def split_clauses(text):
617
+ parts = []
618
+ for p in re.split(r'(?<=[.?!]) ', text):
619
+ p = p.strip()
620
+ if not p:
621
+ continue
622
+ if p.endswith('?'):
623
+ m = re.match(r'^(.*?),? ((?:then )?how (?:many|much)\b.*)\?$', p)
624
+ if m and m[1] and not m[1].startswith('if '):
625
+ parts += [x for x in re.split(r', (?:and )?', m[1]) if x]
626
+ parts.append(m[2] + '?')
627
+ continue
628
+ parts.append(p)
629
+ else:
630
+ parts += [x for x in re.split(r'(?:,? and then |, then |,? but )', p.rstrip('.!')) if x]
631
+ return parts
632
+
633
+
634
+ def trace(question, tree=None, stats=None):
635
+ tree = tree or default_tree()
636
+ out = {'題目': question, '走過': [], 'en': None, '拒答': None}
637
+ text = normalize(question)
638
+ if len(text) > 2000 or text.count('?') != 1 or not text.endswith('?'):
639
+ out['拒答'] = '不是一個問句結尾的應用題'
640
+ return out
641
+ *facts, final = split_clauses(text)
642
+ if not 1 <= len(facts) <= 8:
643
+ out['拒答'] = '敘述句數不在 1~8'
644
+ return out
645
+ story = Story(tree)
646
+ used = []
647
+ if stats is not None:
648
+ # 『比對成功』每個子句都量(不管前面的子句有沒有讀成、會不會被更具體的葉子蓋過)
649
+ for kind, c in [('敘述', f) for f in facts] + [('問句', final.rstrip('?'))]:
650
+ c = tree.lead.sub('', c).strip(' ,')
651
+ for leaf, _ in tree.matches(kind, c):
652
+ stats.matched(leaf['id'])
653
+ try:
654
+ for f in facts:
655
+ f = tree.lead.sub('', f).strip(' ,')
656
+ if story.clause('敘述', f, stats, used) is None:
657
+ pieces = re.split(r',? and ', f)
658
+ if len(pieces) != 2 or any(story.clause('敘述', x, stats, used) is None for x in pieces):
659
+ raise Refuse(f'沒有葉子認得:「{f}」')
660
+ q = tree.lead.sub('', final.rstrip('?')).strip(' ,')
661
+ expr = story.clause('問句', q, stats, used)
662
+ if expr is None:
663
+ raise Refuse(f'沒有問句葉子認得:「{q}」')
664
+ except (Refuse, KeyError, ValueError, TypeError) as e:
665
+ out['拒答'] = str(e) if isinstance(e, Refuse) else f'內部錯誤(當拒答):{type(e).__name__} {e}'
666
+ out['走過'] = used
667
+ return out
668
+ out['走過'] = used
669
+ out['en'] = prefix(expr)
670
+ out['狀態表'] = state_table(story, question)
671
+ if stats is not None:
672
+ for u in used:
673
+ stats.adopted(u['葉子'])
674
+ return out
675
+
676
+
677
+ def state_table(story, question):
678
+ codes = {}
679
+
680
+ def code(name):
681
+ if isinstance(name, list):
682
+ return [code(x) for x in name]
683
+ if name not in codes:
684
+ codes[name] = chr(ord('A') + len(codes)) if len(codes) < 26 else f'S{len(codes)}'
685
+ return codes[name]
686
+
687
+ facts = []
688
+ for row in story.facts:
689
+ row = dict(row)
690
+ if row['relation'] == '每組':
691
+ row['container'] = row.pop('subject')
692
+ else:
693
+ row['subject'] = code(row['subject'])
694
+ facts.append(row)
695
+ query = dict(story.query, subject=code(story.query['subject']))
696
+ subjects = {}
697
+ for name, c in codes.items():
698
+ shown = re.search(rf"\b{re.escape(name)}\b", question, re.IGNORECASE)
699
+ subjects[c] = {'name': shown[0] if shown else name, 'kind': 'place' if name in story.places else 'person'}
700
+ return {'subjects': subjects, 'facts': facts, 'query': query}
701
+
702
+
703
+ _DEFAULT = None
704
+
705
+
706
+ def default_tree():
707
+ global _DEFAULT
708
+ if _DEFAULT is None:
709
+ _DEFAULT = load()
710
+ return _DEFAULT
711
+
712
+
713
+ def tree_translate(question, tree=None, stats=None, allow_convert=False):
714
+ """跟 管線_87.translate 的故事分支同格式。式子含 換單位 時,預設拒答(左腦換算零件還沒接進管線);
715
+ allow_convert=True 才放行。"""
716
+ r = trace(question, tree, stats)
717
+ if r['en'] is None or ('換單位' in r['en'] and not allow_convert):
718
+ return None
719
+ return {'en': r['en'], 'kind': 'story', 'module': None, 'src': SRC}
720
+
721
+
722
+ def translate(question):
723
+ """管線_87.translate 的替身:樹先讀,讀不了交給既有 DeepMind 文法。"""
724
+ found = tree_translate(question)
725
+ if found is not None:
726
+ return found
727
+ import sys
728
+ entry = str(HERE.parent / '總入口')
729
+ story = str(HERE.parent / '數學題轉螺旋語')
730
+ for p in (entry, story):
731
+ if p not in sys.path:
732
+ sys.path.insert(0, p)
733
+ import 管線_85 as previous
734
+ previous.install()
735
+ return previous.U.first_layer(question)
736
+
737
+
738
+ # ---------------------------------------------------------------- 驗算(只供驗收)
739
+ def value(en, lex=None):
740
+ if en is None:
741
+ return None
742
+ toks = en.split()
743
+ lex = lex or default_tree().lex
744
+ pos = 0
745
+
746
+ def nxt():
747
+ nonlocal pos
748
+ t = toks[pos]
749
+ pos += 1
750
+ if t in ('加', '減', '乘', '除'):
751
+ a, b = nxt(), nxt()
752
+ return a + b if t == '加' else a - b if t == '減' else a * b if t == '乘' else a / b
753
+ if t == '小':
754
+ n, s = toks[pos], toks[pos + 1]
755
+ pos += 2
756
+ return Fraction(int(n), 10 ** int(s))
757
+ if t == '負號':
758
+ return -nxt()
759
+ if t == '換單位':
760
+ v = nxt()
761
+ a, b = toks[pos], toks[pos + 1]
762
+ pos += 2
763
+ return v * lex.factor(a) / lex.factor(b)
764
+ return Fraction(t)
765
+
766
+ try:
767
+ v = nxt()
768
+ except (ValueError, ZeroDivisionError, IndexError, KeyError):
769
+ return 'invalid'
770
+ return v if pos == len(toks) else 'invalid'
771
+
772
+
773
+ if __name__ == '__main__':
774
+ import argparse
775
+ ap = argparse.ArgumentParser(description='規則樹讀一題,印出走過的葉子與輸出')
776
+ ap.add_argument('question')
777
+ ap.add_argument('--換算', action='store_true', help='放行含 換單位 的輸出')
778
+ a = ap.parse_args()
779
+ r = trace(a.question)
780
+ print(json.dumps(r, ensure_ascii=False, indent=1))
781
+ print('tree_translate →', tree_translate(a.question, allow_convert=a.換算))
hs/規則樹/樹.json ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "說明": "規則樹(#306)節點清單。樹照『意思』長:根 → 骨架類 → 意思節點(擁有輸出模板)→ 說法葉子(葉子/ 底下一片一個檔,只管字面比對)。片段=句法骨頭(數字、副詞、句尾旁註),不放具體的內容詞;內容詞一律在 詞庫.json。",
3
+ "版本": "v0 2026-11-24 Claude 子代理(規則樹框架);示範內容,正式規則由電腦Codex 搬入",
4
+ "片段": {
5
+ "數": "(?:[0-9]{1,3}(?:,[0-9]{3}){1,4}|[0-9]{1,15})(?:\\.[0-9]{1,8})?|zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve",
6
+ "量": "\\$[0-9][0-9,]*(?:\\.[0-9]+)?|(?:{數})(?: dozen)?",
7
+ "組數": "[1-9][0-9]{0,14}|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve",
8
+ "百分": "(?:100|[0-9]{1,2})(?:\\.[0-9]{1,8})? *(?:%|percent)",
9
+ "形": "(?:(?!(?:from|to|in|on|at|of|for|with|into|than|and|more|each|initially|originally|them|it|away|left)\\b)[a-z]+ ){0,2}?",
10
+ "副": "(?:(?:then|also|later|just|only|already|now|originally|initially|first) )?",
11
+ "冠": "(?:(?:the|a|an|his|her|their|its) )?",
12
+ "尾": "(?: (?:in|on|at|for|to|into|inside|during|this|last|today|yesterday|that day|at the [a-z]+)\\b[a-z' -]*)?",
13
+ "前導": "^(?:then|so|later|after that|now|also|next|finally|in the end|at the end),? ",
14
+ "還": "(?: (?:left|now|remaining|in all|altogether|in total|then|still|together|total|combined))?"
15
+ },
16
+ "節點": [
17
+ {
18
+ "id": "根",
19
+ "種類": "根",
20
+ "上層": null
21
+ },
22
+ {
23
+ "id": "骨架/擁有",
24
+ "種類": "骨架",
25
+ "上層": "根",
26
+ "說明": "誰有多少什麼(起始量)"
27
+ },
28
+ {
29
+ "id": "意思/擁有",
30
+ "種類": "意思",
31
+ "上層": "骨架/擁有",
32
+ "說明": "主體一開始有 量 個 物",
33
+ "輸出": [
34
+ {
35
+ "op": "擁有",
36
+ "主體": "$主體",
37
+ "物": "$物",
38
+ "量": "$量"
39
+ }
40
+ ],
41
+ "換說法測試": [
42
+ {
43
+ "名": "有/擁有/一開始有",
44
+ "答": "9",
45
+ "題組": [
46
+ "Mia has 9 marbles. How many marbles does Mia have?",
47
+ "Mia owns 9 marbles. How many marbles does Mia have?",
48
+ "Mia started with 9 marbles. How many marbles does Mia have?"
49
+ ]
50
+ }
51
+ ]
52
+ },
53
+ {
54
+ "id": "骨架/變化",
55
+ "種類": "骨架",
56
+ "上層": "根",
57
+ "說明": "一個主體自己的量增減(沒有對方)"
58
+ },
59
+ {
60
+ "id": "意思/增加",
61
+ "種類": "意思",
62
+ "上層": "骨架/變化",
63
+ "說明": "主體的 物 加 量;之前沒有就當起始量",
64
+ "輸出": [
65
+ {
66
+ "op": "變化",
67
+ "主體": "$主體",
68
+ "物": "$物",
69
+ "量": "$量",
70
+ "方向": "加",
71
+ "缺起點": "當起點"
72
+ }
73
+ ]
74
+ },
75
+ {
76
+ "id": "意思/減少",
77
+ "種類": "意思",
78
+ "上層": "骨架/變化",
79
+ "說明": "主體的 物 減 量;之前沒有就拒答",
80
+ "輸出": [
81
+ {
82
+ "op": "變化",
83
+ "主體": "$主體",
84
+ "物": "$物",
85
+ "量": "$量",
86
+ "方向": "減",
87
+ "缺起點": "拒答"
88
+ }
89
+ ]
90
+ },
91
+ {
92
+ "id": "骨架/轉移",
93
+ "種類": "骨架",
94
+ "上層": "根",
95
+ "說明": "東西從一個主體移到另一個主體(兩邊都變)"
96
+ },
97
+ {
98
+ "id": "意思/轉移",
99
+ "種類": "意思",
100
+ "上層": "骨架/轉移",
101
+ "說明": "給方 減 量、收方 加 量;收方起始量沒給就記成未知(問收方會拒答)",
102
+ "輸出": [
103
+ {
104
+ "op": "變化",
105
+ "主體": "$給方",
106
+ "物": "$物",
107
+ "量": "$量",
108
+ "方向": "減",
109
+ "缺起點": "拒答"
110
+ },
111
+ {
112
+ "op": "變化",
113
+ "主體": "$收方",
114
+ "物": "$物",
115
+ "量": "$量",
116
+ "方向": "加",
117
+ "缺起點": "未知"
118
+ }
119
+ ],
120
+ "換說法測試": [
121
+ {
122
+ "名": "給與收(問收方)",
123
+ "答": "13",
124
+ "題組": [
125
+ "Nora had 17 apples. Leo had 8 apples. Nora gives 5 apples to Leo. How many apples does Leo have now?",
126
+ "Nora had 17 apples. Leo had 8 apples. Nora gives Leo 5 apples. How many apples does Leo have now?",
127
+ "Nora had 17 apples. Leo had 8 apples. Leo receives 5 apples from Nora. How many apples does Leo have now?",
128
+ "Nora had 17 apples. Leo had 8 apples. Nora hands 5 apples to Leo. How many apples does Leo have now?"
129
+ ]
130
+ },
131
+ {
132
+ "名": "給與收(問給方,只換求解目標)",
133
+ "答": "12",
134
+ "題組": [
135
+ "Nora had 17 apples. Leo had 8 apples. Nora gives 5 apples to Leo. How many apples does Nora have now?",
136
+ "Nora had 17 apples. Leo had 8 apples. Leo receives 5 apples from Nora. How many apples does Nora have now?"
137
+ ]
138
+ }
139
+ ]
140
+ },
141
+ {
142
+ "id": "骨架/等組比率",
143
+ "種類": "骨架",
144
+ "上層": "根",
145
+ "說明": "每組一樣多、均分、比率"
146
+ },
147
+ {
148
+ "id": "意思/每組",
149
+ "種類": "意思",
150
+ "上層": "骨架/等組比率",
151
+ "說明": "每個 容器 裝 �� 個 物(比率,不屬於任何人)",
152
+ "輸出": [
153
+ {
154
+ "op": "每組",
155
+ "容器": "$容器",
156
+ "物": "$物",
157
+ "量": "$量"
158
+ }
159
+ ],
160
+ "換說法測試": [
161
+ {
162
+ "名": "每盒有/每盒裡有",
163
+ "答": "24",
164
+ "題組": [
165
+ "Sam has 4 boxes. Each box has 6 pencils. How many pencils does Sam have?",
166
+ "Sam has 4 boxes. Each box contains 6 pencils. How many pencils does Sam have?",
167
+ "Sam has 4 boxes. There are 6 pencils in each box. How many pencils does Sam have?"
168
+ ]
169
+ }
170
+ ]
171
+ },
172
+ {
173
+ "id": "意思/等組擁有",
174
+ "種類": "意思",
175
+ "上層": "骨架/等組比率",
176
+ "說明": "主體有 組數 個 容器,每個裝 量 個 物 → 擁有 乘 組數 量",
177
+ "輸出": [
178
+ {
179
+ "op": "擁有",
180
+ "主體": "$主體",
181
+ "物": "$物",
182
+ "量": [
183
+ "乘",
184
+ "$組數",
185
+ "$量"
186
+ ]
187
+ }
188
+ ],
189
+ "換說法測試": [
190
+ {
191
+ "名": "N 盒 of K 個",
192
+ "答": "24",
193
+ "題組": [
194
+ "Sam has 4 boxes of 6 pencils. How many pencils does Sam have?",
195
+ "Sam bought 4 boxes with 6 pencils each. How many pencils does Sam have?"
196
+ ]
197
+ }
198
+ ]
199
+ },
200
+ {
201
+ "id": "意思/等組增加",
202
+ "種類": "意思",
203
+ "上層": "骨架/等組比率",
204
+ "說明": "主體取得(買、收到、撿到…)組數 個 容器,每個裝 量 個 物 → 變化 加 乘 組數 量;之前沒有就當起始量。11-25 從 等組擁有 拆出:持有是狀態、取得是事件(Pro 第二輪實測:Sam has 5 apples. Sam bought 2 boxes of 6 apples 原本被當第二次起始值而拒答)",
205
+ "輸出": [
206
+ {
207
+ "op": "變化",
208
+ "主體": "$主體",
209
+ "物": "$物",
210
+ "量": [
211
+ "乘",
212
+ "$組數",
213
+ "$量"
214
+ ],
215
+ "方向": "加",
216
+ "缺起點": "當起點"
217
+ }
218
+ ],
219
+ "來源": "Claude 11-25(MathWorld:observation vs transfer;ARIS:observation vs positive)"
220
+ },
221
+ {
222
+ "id": "意思/均分",
223
+ "種類": "意思",
224
+ "上層": "骨架/等組比率",
225
+ "說明": "主體把 量 個 物(沒寫量=全部存量)平分給 份數 個 受者",
226
+ "輸出": [
227
+ {
228
+ "op": "均分",
229
+ "主體": "$主體",
230
+ "物": "$物",
231
+ "量": "$量",
232
+ "份數": "$份數",
233
+ "受者": "$受者"
234
+ }
235
+ ],
236
+ "換說法測試": [
237
+ {
238
+ "名": "分給/平分給",
239
+ "答": "4",
240
+ "題組": [
241
+ "Ivy shares 12 apples equally among 3 friends. How many apples does each friend get?",
242
+ "Ivy divides 12 apples among 3 friends. How many apples does each friend get?",
243
+ "Ivy splits 12 apples evenly between 3 friends. How many apples does each friend receive?"
244
+ ]
245
+ }
246
+ ]
247
+ },
248
+ {
249
+ "id": "骨架/百分比分數",
250
+ "種類": "骨架",
251
+ "上層": "根",
252
+ "說明": "百分比、幾分之幾"
253
+ },
254
+ {
255
+ "id": "意思/百分比減少",
256
+ "種類": "意思",
257
+ "上層": "骨架/百分比分數",
258
+ "說明": "主體的 物 少掉 百分 的部分:存量 減 存量×百分",
259
+ "輸出": [
260
+ {
261
+ "op": "百分比減",
262
+ "主體": "$主體",
263
+ "物": "$物",
264
+ "百分": "$百分"
265
+ }
266
+ ],
267
+ "換說法測試": [
268
+ {
269
+ "名": "賣掉 P% of them/of his",
270
+ "答": "30",
271
+ "題組": [
272
+ "Tom has 40 apples. He sold 25% of them. How many apples does Tom have left?",
273
+ "Tom has 40 apples. He sold 25 percent of his apples. How many apples does Tom have left?"
274
+ ]
275
+ }
276
+ ]
277
+ },
278
+ {
279
+ "id": "骨架/量測",
280
+ "種類": "骨架",
281
+ "上層": "根",
282
+ "說明": "長度、時間、重量等有單位的量;換算交給左腦第二級①換算零件(輸出 換單位 值 來源 目標),規則裡不算係數"
283
+ },
284
+ {
285
+ "id": "意思/累計量測",
286
+ "種類": "意思",
287
+ "上層": "骨架/量測",
288
+ "說明": "主體做某動作累計 量 單位(例:跑了 3 km);不同單位相加時自動插 換單位",
289
+ "輸出": [
290
+ {
291
+ "op": "變化",
292
+ "主體": "$主體",
293
+ "物": "$物",
294
+ "量": "$量",
295
+ "方向": "加",
296
+ "缺起點": "當起點"
297
+ }
298
+ ],
299
+ "換說法測試": [
300
+ {
301
+ "名": "公里+公尺,問公尺",
302
+ "答": "3500",
303
+ "題組": [
304
+ "Tom ran 3 kilometers. Then he ran 500 meters. How many meters did Tom run in all?",
305
+ "Tom ran 3 km. Then he ran 500 meters. How many meters did Tom run in all?"
306
+ ]
307
+ }
308
+ ]
309
+ },
310
+ {
311
+ "id": "骨架/問句",
312
+ "種類": "骨架",
313
+ "上層": "根",
314
+ "說明": "問句:決定求解目標"
315
+ },
316
+ {
317
+ "id": "意思/問擁有",
318
+ "種類": "意思",
319
+ "上層": "骨架/問句",
320
+ "說明": "問 主體(沒寫就找唯一持有者)現在有多少 物;問的單位跟存量不同時插 換單位",
321
+ "輸出": [
322
+ {
323
+ "op": "問擁有",
324
+ "主體": "$主體",
325
+ "物": "$物"
326
+ }
327
+ ]
328
+ },
329
+ {
330
+ "id": "意思/問總和",
331
+ "種類": "意思",
332
+ "上層": "骨架/問句",
333
+ "說明": "問幾個主體(they=全部持有者)合起來有多少 物",
334
+ "輸出": [
335
+ {
336
+ "op": "問總和",
337
+ "主體們": [
338
+ "$甲",
339
+ "$乙"
340
+ ],
341
+ "物": "$物"
342
+ }
343
+ ]
344
+ },
345
+ {
346
+ "id": "意思/問每份",
347
+ "種類": "意思",
348
+ "上層": "骨架/問句",
349
+ "說明": "均分後每個 受者 拿到多少",
350
+ "輸出": [
351
+ {
352
+ "op": "問每份",
353
+ "受者": "$受者",
354
+ "物": "$物"
355
+ }
356
+ ]
357
+ }
358
+ ]
359
+ }
hs/規則樹/葉子/問句/問擁有.剩下-01.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "問擁有.剩下-01",
3
+ "上層": "意思/問擁有",
4
+ "種類": "問句",
5
+ "優先層": 2,
6
+ "樣式": "how many {形}<物:物品> (?:are|were|is) (?:left|remaining|there|there now|now)(?: (?:now|in all|altogether|in total|left))?",
7
+ "說明": "How many 物 are left/there? 沒寫主體,找唯一持有者。",
8
+ "正例": [{"句": "How many apples are left", "欄位": {"物": "apples"}}],
9
+ "反例": ["How many apples does Tom have left"],
10
+ "題例": [{"題": "Tom has 40 apples. 25% of the apples were sold. How many apples are left?", "答": "30"}],
11
+ "來源": "nl2en_story_291 POOL",
12
+ "作者": "Claude 子代理(規則樹框架)",
13
+ "建立": "2026-11-24"
14
+ }
hs/規則樹/葉子/問句/問擁有.有幾-01.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "問擁有.有幾-01",
3
+ "上層": "意思/問擁有",
4
+ "種類": "問句",
5
+ "優先層": 2,
6
+ "樣式": "how many {形}<物:物品> (?:does|did|do|will|would) <主體:人> (?:have|has|own){還}",
7
+ "說明": "How many 物 does A have (left/now/in all)?",
8
+ "正例": [
9
+ {"句": "How many apples does Leo have now", "欄位": {"物": "apples", "主體": "leo"}},
10
+ {"句": "How many cookies did Paco have left"}
11
+ ],
12
+ "反例": ["How many more apples does Leo have than Nora", "How many apples do Nora and Leo have together"],
13
+ "題例": [{"題": "Mia has 9 marbles. How many marbles does Mia have?", "答": "9"}],
14
+ "來源": "nl2en_story_291 BALANCE/292 have",
15
+ "作者": "Claude 子代理(規則樹框架)",
16
+ "建立": "2026-11-24"
17
+ }
hs/規則樹/葉子/問句/問擁有.總數是-01.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "問擁有.總數是-01",
3
+ "上層": "意思/問擁有",
4
+ "種類": "問句",
5
+ "優先層": 2,
6
+ "樣式": "what is the (?:total )?number of {形}<物:物品> (?:that )?<主體:人> (?:has|had|have|owns){還}",
7
+ "說明": "What is the (total) number of 物 (that) A has? 跟 問擁有.有幾-01 同一個意思(多對一)。",
8
+ "正例": [
9
+ {"句": "What is the total number of apples that Leo has now", "欄位": {"物": "apples", "主體": "leo"}},
10
+ {"句": "What is the number of pencils Sam has"}
11
+ ],
12
+ "反例": ["What is the number of apples", "How many apples does Leo have"],
13
+ "題例": [{"題": "Nora had 17 apples. Leo had 8 apples. Nora gives 5 apples to Leo. What is the total number of apples that Leo has now?", "答": "13"}],
14
+ "來源": "示範提交(merge.py 提交)",
15
+ "作者": "Claude 子代理(規則樹框架)",
16
+ "建立": "2026-11-24"
17
+ }
hs/規則樹/葉子/問句/問擁有.量測-01.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "問擁有.量測-01",
3
+ "上層": "意思/問擁有",
4
+ "種類": "問句",
5
+ "優先層": 2,
6
+ "樣式": "how (?:many|much) <物:單位> (?:did|does|do|will) <主體:人> <動:移動動詞>{還}",
7
+ "說明": "How many 單位 did A run (in all)? 問的單位跟存量單位不同時,引擎插 換單位。",
8
+ "正例": [{"句": "How many meters did Tom run in all", "欄位": {"物": "meters", "主體": "tom"}}],
9
+ "反例": ["How many apples did Tom run"],
10
+ "題例": [{"題": "Tom ran 3 kilometers. Then he ran 500 meters. How many meters did Tom run in all?", "答": "3500"}],
11
+ "來源": "使用者 11-24 06:3x 詞類槽設計示範(單位)",
12
+ "作者": "Claude 子代理(規則樹框架)",
13
+ "建立": "2026-11-24"
14
+ }
hs/規則樹/葉子/問句/問擁有.錢-01.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "問擁有.錢-01",
3
+ "上層": "意思/問擁有",
4
+ "種類": "問句",
5
+ "優先層": 2,
6
+ "樣式": "how much(?: money)? (?:does|did|do|will) <主體:人> have{還}",
7
+ "預設": {"物": "money"},
8
+ "說明": "How much (money) does A have (left)? 物品固定是錢(預設欄位 物=money → USD)。",
9
+ "正例": [{"句": "How much money does Edward have left", "欄位": {"主體": "edward"}}],
10
+ "反例": ["How much money did Edward spend"],
11
+ "題例": [{"題": "Edward had $13. Edward spent $10 on lunch. How much money does Edward have left?", "答": "3"}],
12
+ "來源": "nl2en_story_291 CASH",
13
+ "作者": "Claude 子代理(規則樹框架)",
14
+ "建立": "2026-11-24"
15
+ }
hs/規則樹/葉子/問句/問每份.每人-01.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "問每份.每人-01",
3
+ "上層": "意思/問每份",
4
+ "種類": "問句",
5
+ "優先層": 2,
6
+ "樣式": "how many(?: {形}<物:物品>)? (?:does|did|will|would|can|should) each(?: of (?:his|her|their))? <受者:物品> <收類動詞|有類動詞>",
7
+ "說明": "How many 物 does each 受者 get/receive/have?",
8
+ "正例": [{"句": "How many apples does each friend get", "欄位": {"物": "apples", "受者": "friend"}}],
9
+ "反例": ["How many apples does each friend give"],
10
+ "題例": [{"題": "Ivy shares 12 apples equally among 3 friends. How many apples does each friend get?", "答": "4"}],
11
+ "來源": "nl2en_story_292 each 問句",
12
+ "作者": "Claude 子代理(規則樹框架)",
13
+ "建立": "2026-11-24"
14
+ }
hs/規則樹/葉子/問句/問總和.合計-01.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "問總和.合計-01",
3
+ "上層": "意思/問總和",
4
+ "種類": "問句",
5
+ "優先層": 1,
6
+ "樣式": "how many {形}<物:物品> (?:do|did|will) (?:<甲:人> and <乙:人>|they|both of them|the two of them) have{還}",
7
+ "說明": "合併 問總和.一起-01、問總和.他們-01(只差主詞那一段):How many 物 do A and B/they have (together)? 主詞是 A and B 就加這兩人;是 they/both of them 就沒有甲乙槽 → 全部持有者(至少 2 個)。",
8
+ "正例": [
9
+ {
10
+ "句": "How many apples do Nora and Leo have together",
11
+ "欄位": {
12
+ "物": "apples",
13
+ "甲": "nora",
14
+ "乙": "leo"
15
+ }
16
+ },
17
+ {
18
+ "句": "How many apples do they have in all",
19
+ "欄位": {
20
+ "物": "apples"
21
+ }
22
+ }
23
+ ],
24
+ "反例": [
25
+ "How many apples does Nora have",
26
+ "How many apples does he have"
27
+ ],
28
+ "題例": [
29
+ {
30
+ "題": "Nora had 17 apples. Leo had 8 apples. Nora gives 5 apples to Leo. How many apples do Nora and Leo have together?",
31
+ "答": "25"
32
+ },
33
+ {
34
+ "題": "Mia has 9 marbles. Leo has 4 marbles. How many marbles do they have altogether?",
35
+ "答": "13"
36
+ }
37
+ ],
38
+ "來源": "nl2en_story_291 SUM(含 they);merge.py 自動併",
39
+ "作者": "Claude 子代理(語法合併)",
40
+ "建立": "2026-11-24",
41
+ "合併自": [
42
+ "問總和.一起-01",
43
+ "問總和.他們-01"
44
+ ]
45
+ }
hs/規則樹/葉子/擁有/擁有.地點-01.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "擁有.地點-01",
3
+ "上層": "意思/擁有",
4
+ "種類": "敘述",
5
+ "優先層": 2,
6
+ "樣式": "there (?:are|were|is|was) <量:量> {形}<物:物品> (?:in|on|at|inside) {冠}<主體:地點>",
7
+ "說明": "地點當擁有者:There are N 物 in the 地點。",
8
+ "正例": [
9
+ {"句": "There are 26 children on the bus", "欄位": {"量": "26", "物": "children", "主體": "bus"}},
10
+ {"句": "There were 12 cookies in the jar"}
11
+ ],
12
+ "反例": ["There are 6 pencils in each box", "There are 26 children"],
13
+ "題例": [{"題": "There are 26 children on the bus. 5 children got off. How many children are there now?", "答": null}],
14
+ "來源": "nl2en_story_292 place 改寫成詞類槽",
15
+ "作者": "Claude 子代理(規則樹框架)",
16
+ "建立": "2026-11-24"
17
+ }
hs/規則樹/葉子/擁有/擁有.有-01.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "擁有.有-01",
3
+ "上層": "意思/擁有",
4
+ "種類": "敘述",
5
+ "優先層": 3,
6
+ "樣式": "<主體:人> {副}<動:有類動詞> <量:量>(?: {形}<物:物品>)?{尾}",
7
+ "說明": "A 有 N 個 物(has/owns/started with…,動詞從詞庫 有類動詞 來)。量是 $N 時物品=USD。",
8
+ "正例": [
9
+ {"句": "Mia has 9 marbles", "欄位": {"主體": "mia", "量": "9", "物": "marbles"}},
10
+ {"句": "Edward had $13"},
11
+ {"句": "Tom originally had 40 big red apples in his basket"},
12
+ {"句": "Sam started with 2 dozen eggs"}
13
+ ],
14
+ "反例": ["Mia has 9 more marbles than Leo", "Sam has 4 boxes of 6 pencils", "Mia has some marbles"],
15
+ "題例": [{"題": "Mia has 9 marbles. How many marbles does Mia have?", "答": "9"}],
16
+ "來源": "nl2en_story_291 initial/292 own 改寫成詞類槽",
17
+ "作者": "Claude 子代理(規則樹框架)",
18
+ "建立": "2026-11-24"
19
+ }
hs/規則樹/葉子/百分比分數/百分比.失去-01.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "百分比.失去-01",
3
+ "上層": "意思/百分比減少",
4
+ "種類": "敘述",
5
+ "優先層": 2,
6
+ "樣式": "<主體:人> {副}<動:失類動詞> <百分:百分> of (?:them|it|{冠}{形}<物:物品>)",
7
+ "說明": "A sold/used/ate P% of them(或 of his 物)→ 存量 減 存量×P%。",
8
+ "正例": [
9
+ {"句": "He sold 25% of them", "欄位": {"主體": "he", "百分": "25%"}},
10
+ {"句": "Tom used 40 percent of his apples"}
11
+ ],
12
+ "反例": ["He sold 25 of them", "He sold 120% of them"],
13
+ "題例": [{"題": "Tom has 40 apples. He sold 25% of them. How many apples does Tom have left?", "答": "30"}],
14
+ "來源": "nl2en_story_291 percent_remaining 改寫成詞類槽",
15
+ "作者": "Claude 子代理(規則樹框架)",
16
+ "建立": "2026-11-24"
17
+ }
hs/規則樹/葉子/百分比分數/百分比.被動-01.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "百分比.被動-01",
3
+ "上層": "意思/百分比減少",
4
+ "種類": "敘述",
5
+ "優先層": 2,
6
+ "樣式": "<百分:百分> of {冠}{形}<物:物品> (?:were|was) <動:失類動詞>",
7
+ "說明": "P% of the 物 were sold:沒寫主體,找這個物品唯一的持有者。",
8
+ "正例": [{"句": "25% of the apples were sold", "欄位": {"百分": "25%", "物": "apples"}}],
9
+ "反例": ["25 of the apples were sold"],
10
+ "題例": [{"題": "Tom has 40 apples. 25% of the apples were sold. How many apples does Tom have left?", "答": "30"}],
11
+ "來源": "Claude 子代理(規則樹框架)示範被動說法",
12
+ "作者": "Claude 子代理(規則樹框架)",
13
+ "建立": "2026-11-24"
14
+ }
hs/規則樹/葉子/等組比率/均分.分存量-01.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "均分.分存量-01",
3
+ "上層": "意思/均分",
4
+ "種類": "敘述",
5
+ "優先層": 2,
6
+ "樣式": "<主體:人> (?:wants to |will |is going to |needs to )?<動:分類動詞> (?:them|it|all of them|(?:all )?(?:the |his |her |their )(?!some\\b){形}<物:物品>) (?:(?:equally|evenly) )?(?:among|between) {冠}<份數:組數> <受者:物品>(?: (?:equally|evenly))?",
7
+ "說明": "A 把(全部)存量平分給 M 個 受者:沒寫數量,量=當時的存量。",
8
+ "正例": [
9
+ {"句": "She shares them equally among 3 friends", "欄位": {"主體": "she", "份數": "3", "受者": "friends"}},
10
+ {"句": "He divides all the cookies between his 2 sisters"}
11
+ ],
12
+ "反例": ["She shares 12 apples among 3 friends", "She shares some among 3 friends"],
13
+ "題例": [{"題": "Ivy has 12 apples. She shares them equally among 3 friends. How many apples does each friend get?", "答": "4"}],
14
+ "來源": "nl2en_story_292 share(all/them 分支)",
15
+ "作者": "Claude 子代理(規則樹框架)",
16
+ "建立": "2026-11-24"
17
+ }
hs/規則樹/葉子/等組比率/均分.分給-01.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "均分.分給-01",
3
+ "上層": "意思/均分",
4
+ "種類": "敘述",
5
+ "優先層": 2,
6
+ "樣式": "<主體:人> (?:wants to |will |is going to |needs to )?<動:分類動詞> <量:量> {形}<物:物品> (?:(?:equally|evenly) )?(?:among|between) {冠}<份數:組數> <受者:物品>(?: (?:equally|evenly))?",
7
+ "說明": "A 把 N 個 物 平分給 M 個 受者(寫了數量)。",
8
+ "正例": [
9
+ {"句": "Ivy shares 12 apples equally among 3 friends", "欄位": {"主體": "ivy", "量": "12", "物": "apples", "份數": "3", "受者": "friends"}},
10
+ {"句": "Randy wants to divide 378 bananas among his 6 friends"}
11
+ ],
12
+ "反例": ["Ivy shares some apples among 3 friends", "Ivy shares them equally among 3 friends"],
13
+ "題例": [{"題": "Ivy shares 12 apples equally among 3 friends. How many apples does each friend get?", "答": "4"}],
14
+ "來源": "nl2en_story_292 share(有數量的分支)",
15
+ "作者": "Claude 子代理(規則樹框架)",
16
+ "建立": "2026-11-24"
17
+ }
hs/規則樹/葉子/等組比率/每組.每個有-01.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "每組.每個有-01",
3
+ "上層": "意思/每組",
4
+ "種類": "敘述",
5
+ "優先層": 1,
6
+ "樣式": "each <容器:容器> <動:裝類動詞> <量:量> {形}<物:物品>",
7
+ "說明": "Each 容器 has/contains/holds N 物。容器、動詞都從詞庫來:加一種容器(例 crate)不用改這片。",
8
+ "正例": [
9
+ {"句": "Each box has 6 pencils", "欄位": {"容器": "box", "量": "6", "物": "pencils"}},
10
+ {"句": "Each basket contains 12 red apples"}
11
+ ],
12
+ "反例": ["Each friend has 6 pencils", "Each box has some pencils"],
13
+ "題例": [{"題": "Sam has 4 boxes. Each box has 6 pencils. How many pencils does Sam have?", "答": "24"}],
14
+ "來源": "nl2en_story_291 group_rate 改寫成詞類槽",
15
+ "作者": "Claude 子代理(規則樹框架)",
16
+ "建立": "2026-11-24"
17
+ }
hs/規則樹/葉子/等組比率/每組.每個裡有-01.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "每組.每個裡有-01",
3
+ "上層": "意思/每組",
4
+ "種類": "敘述",
5
+ "優先層": 1,
6
+ "樣式": "there (?:are|is|were|was) <量:量> {形}<物:物品> (?:in|on) each <容器:容器>",
7
+ "說明": "There are N 物 in each 容器:跟 每組.每個有-01 同一個意思(多對一),換說法測試保證兩種說法輸出一樣。",
8
+ "正例": [
9
+ {"句": "There are 6 pencils in each box", "欄位": {"量": "6", "物": "pencils", "容器": "box"}},
10
+ {"句": "There were 8 books on each shelf"}
11
+ ],
12
+ "反例": ["There are 6 pencils in the box", "There are 6 pencils in each friend"],
13
+ "題例": [{"題": "Sam has 4 boxes. There are 6 pencils in each box. How many pencils does Sam have?", "答": "24"}],
14
+ "來源": "nl2en_story_291 group_each 改寫",
15
+ "作者": "Claude 子代理(規則樹框架)",
16
+ "建立": "2026-11-24"
17
+ }
hs/規則樹/葉子/等組比率/等組增加.組of-01.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "等組增加.組of-01",
3
+ "上層": "意思/等組增加",
4
+ "種類": "敘述",
5
+ "優先層": 1,
6
+ "樣式": "<主體:人> {副}<動:得類動詞> <組數:組數> <容器:容器> (?:of|with|containing|holding) <量:量> {形}<物:物品>(?: each)?",
7
+ "說明": "A bought/received N 容器 of K 物 → A 的 物 加 乘 N K(取得=事件;沒有起始量就當起始量)。",
8
+ "正例": [
9
+ {
10
+ "句": "Sam bought 4 boxes with 6 pencils each"
11
+ },
12
+ {
13
+ "句": "Sam received 2 boxes of 6 apples"
14
+ }
15
+ ],
16
+ "反例": [
17
+ "Sam bought 4 friends of 6 pencils",
18
+ "Sam bought 4 boxes"
19
+ ],
20
+ "題例": [
21
+ {
22
+ "題": "Sam has 5 apples. Sam bought 2 boxes of 6 apples. How many apples does Sam have?",
23
+ "答": "17"
24
+ },
25
+ {
26
+ "題": "Sam bought 4 boxes of 6 pencils. How many pencils does Sam have?",
27
+ "答": "24"
28
+ }
29
+ ],
30
+ "來源": "從 等組擁有.組of-01 拆出(Pro 11-25 第二輪實測:持有與取得混淆)",
31
+ "作者": "Claude",
32
+ "建立": "2026-11-25"
33
+ }
hs/規則樹/葉子/等組比率/等組擁有.組of-01.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "等組擁有.組of-01",
3
+ "上層": "意思/等組擁有",
4
+ "種類": "敘述",
5
+ "優先層": 1,
6
+ "樣式": "<主體:人> {副}<動:有類動詞> <組數:組數> <容器:容器> (?:of|with|containing|holding) <量:量> {形}<物:物品>(?: each)?",
7
+ "說明": "A has/owns N 容器 of K 物 → A 擁有 乘 N K(持有=狀態)。取得類動詞(bought/received…)11-25 拆到 等組增加.組of-01。",
8
+ "正例": [
9
+ {
10
+ "句": "Sam has 4 boxes of 6 pencils",
11
+ "欄位": {
12
+ "主體": "sam",
13
+ "組數": "4",
14
+ "容器": "boxes",
15
+ "量": "6",
16
+ "物": "pencils"
17
+ }
18
+ }
19
+ ],
20
+ "反例": [
21
+ "Sam has 4 friends of 6 pencils",
22
+ "Sam has 4 boxes"
23
+ ],
24
+ "題例": [
25
+ {
26
+ "題": "Sam has 4 boxes of 6 pencils. How many pencils does Sam have?",
27
+ "答": "24"
28
+ }
29
+ ],
30
+ "來源": "nl2en_story_291 group_of 改寫成詞類槽",
31
+ "作者": "Claude 子代理(規則樹框架)",
32
+ "建立": "2026-11-24"
33
+ }
hs/規則樹/葉子/變化/增加.得到-01.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "增加.得到-01",
3
+ "上層": "意思/增加",
4
+ "種類": "敘述",
5
+ "優先層": 3,
6
+ "樣式": "<主體:人> {副}<動:得類動詞> <量:量>(?: more)?(?: {形}<物:物品>)?{尾}",
7
+ "說明": "A 自己多了 N 個(買、撿、贏、做…,動詞從詞庫 得類動詞 來);沒有起始量就當起始量。帶 from 某人時,會被更具體的 轉移.收到-01(優先層 1)蓋過:這片只記『比對成功』不記『實際採用』。",
8
+ "正例": [
9
+ {"句": "Paco bought 37 more cookies", "欄位": {"主體": "paco", "量": "37", "物": "cookies"}},
10
+ {"句": "Then she picked up 8 shells at the beach"},
11
+ {"句": "He earned $25"}
12
+ ],
13
+ "反例": ["Paco bought some cookies", "Paco bought 3 boxes of 6 cookies"],
14
+ "題例": [{"題": "Paco had 40 cookies. Then he bought 37 more cookies. How many cookies did Paco have left?", "答": "77"}],
15
+ "來源": "nl2en_story_292 gain 改寫成詞類槽",
16
+ "作者": "Claude 子代理(規則樹框架)",
17
+ "建立": "2026-11-24"
18
+ }
hs/規則樹/葉子/變化/減少.減量-01.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "減少.減量-01",
3
+ "上層": "意思/減少",
4
+ "種類": "敘述",
5
+ "優先層": 3,
6
+ "樣式": "<主體:人> {副}<動:減量動詞> <量:量>(?: of (?:them|it)| {形}<物:物品>)?{尾}",
7
+ "說明": "合併 減少.失去-01、減少.給出-01(兩片只差動詞槽):A 自己少了 N 個。動詞從抽出來的詞類 減量動詞(=失類動詞∪給類動詞:賣、吃、用、丟、給出…)來;帶 to 某人時會被 轉移.給到-01(優先層 1)蓋過。",
8
+ "正例": [
9
+ {
10
+ "句": "He ate 2 of them",
11
+ "欄位": {
12
+ "主體": "he",
13
+ "量": "2"
14
+ }
15
+ },
16
+ {
17
+ "句": "Edward spent $10 on lunch"
18
+ },
19
+ {
20
+ "句": "Tom sold 12 apples"
21
+ },
22
+ {
23
+ "句": "Nora gave 5 apples",
24
+ "欄位": {
25
+ "主體": "nora",
26
+ "量": "5",
27
+ "物": "apples"
28
+ }
29
+ },
30
+ {
31
+ "句": "Nora gives 5 apples to Leo"
32
+ }
33
+ ],
34
+ "反例": [
35
+ "He ate some of them",
36
+ "Tom sold 25% of them",
37
+ "Nora gave some apples"
38
+ ],
39
+ "題例": [
40
+ {
41
+ "題": "Paco had 40 cookies. He ate 2 of them. How many cookies did Paco have left?",
42
+ "答": "38"
43
+ },
44
+ {
45
+ "題": "Nora had 17 apples. Nora gave 5 apples. How many apples does Nora have now?",
46
+ "答": "12"
47
+ }
48
+ ],
49
+ "來源": "nl2en_story_292 loss(含 gives/gave 部分)改寫成詞類槽;merge.py 自動併",
50
+ "作者": "Claude 子代理(語法合併)",
51
+ "建立": "2026-11-24",
52
+ "合併自": [
53
+ "減少.失去-01",
54
+ "減少.給出-01"
55
+ ]
56
+ }
hs/規則樹/葉子/轉移/轉移.收到-01.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "轉移.收到-01",
3
+ "上層": "意思/轉移",
4
+ "連結": [
5
+ {"意思": "意思/轉移", "條件": {"已知人物": ["給方", "收方"]}},
6
+ {"意思": "意思/增加", "條件": {"非已知人物": "給方"}, "改名": {"收方": "主體"}},
7
+ {"意思": "意思/減少", "條件": {"已知人物": "給方", "非已知人物": "收方"}, "改名": {"給方": "主體"}}
8
+ ],
9
+ "種類": "敘述",
10
+ "優先層": 1,
11
+ "樣式": "<收方:人> {副}<動:收類動詞> <量:量>(?: more)?(?: {形}<物:物品>)? from <給方:人>{尾}",
12
+ "說明": "B 從 A 收到 N 個。A、B 都出現過=轉移(A 減、B 加,跟 A gives B 同一組事實);A 是新人物(例:from the store)=只算 B 增加;只有 A 出現過=A 減少。",
13
+ "正例": [
14
+ {"句": "Leo receives 5 apples from Nora", "欄位": {"收方": "leo", "量": "5", "物": "apples", "給方": "nora"}},
15
+ {"句": "Ann got 3 more marbles from Tom"},
16
+ {"句": "Sam bought 6 eggs from the store"}
17
+ ],
18
+ "反例": ["Leo receives 5 apples", "Nora gives 5 apples to Leo"],
19
+ "題例": [
20
+ {"題": "Nora had 17 apples. Leo had 8 apples. Leo receives 5 apples from Nora. How many apples does Nora have now?", "答": "12"},
21
+ {"題": "Sam had 4 eggs. Sam bought 6 eggs from the store. How many eggs does Sam have now?", "答": "10"}
22
+ ],
23
+ "來源": "使用者 11-24/Codex 06:04 換說法範例:A gives B 3 apples / B receives 3 apples from A",
24
+ "作者": "Claude 子代理(規則樹框架)",
25
+ "建立": "2026-11-24"
26
+ }
hs/規則樹/葉子/轉移/轉移.給人-01.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "轉移.給人-01",
3
+ "上層": "意思/轉移",
4
+ "連結": [
5
+ {"意思": "意思/轉移", "條件": {"已知人物": ["給方", "收方"]}},
6
+ {"意思": "意思/增加", "條件": {"已知人物": "收方", "非已知人物": "給方"}, "改名": {"收方": "主體"}},
7
+ {"意思": "意思/減少", "條件": {"非已知人物": "收方"}, "改名": {"給方": "主體"}}
8
+ ],
9
+ "種類": "敘述",
10
+ "優先層": 1,
11
+ "樣式": "<給方:人> {副}<動:給類動詞> <收方:人> <量:量>(?: more)?(?: {形}<物:物品>)?{尾}",
12
+ "說明": "A 給 B N 個(雙受詞)。A、B 都出現過=轉移;只有 B 出現過(例:Jack gave him 20 marbles)=B 增加;B 是新人物=A 減少。",
13
+ "正例": [
14
+ {"句": "Nora gives Leo 5 apples", "欄位": {"給方": "nora", "收方": "leo", "量": "5", "物": "apples"}},
15
+ {"句": "Then Mom gave her 4 more stickers"}
16
+ ],
17
+ "反例": ["Nora gave away 5 apples", "Nora gives 5 apples to Leo", "Nora gives 5 apples"],
18
+ "題例": [
19
+ {"題": "Nora had 17 apples. Leo had 8 apples. Nora gives Leo 5 apples. How many apples does Leo have now?", "答": "13"},
20
+ {"題": "Josh had 22 marbles in his collection. Jack gave him 20 marbles. How many marbles does Josh have now?", "答": "42"}
21
+ ],
22
+ "來源": "nl2en_story_292 gain_to 改寫成詞類槽",
23
+ "作者": "Claude 子代理(規則樹框架)",
24
+ "建立": "2026-11-24"
25
+ }
hs/規則樹/葉子/轉移/轉移.給到-01.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "轉移.給到-01",
3
+ "上層": "意思/轉移",
4
+ "連結": [
5
+ {"意思": "意思/轉移", "條件": {"已知人物": ["給方", "收方"]}},
6
+ {"意思": "意思/增加", "條件": {"已知人物": "收方", "非已知人物": "給方"}, "改名": {"收方": "主體"}},
7
+ {"意思": "意思/減少", "條件": {"非已知人物": "收方"}, "改名": {"給方": "主體"}}
8
+ ],
9
+ "種類": "敘述",
10
+ "優先層": 1,
11
+ "樣式": "<給方:人> {副}<動:給類動詞> <量:量>(?: of (?:them|it)| {形}<物:物品>)? to <收方:人>{尾}",
12
+ "說明": "A 給 B(to B)。一個說法三種意思,用連結+判別條件:A、B 都已在題目出現=轉移(A 減、B 加);只有 B 出現過=B 增加;B 是新人物=只算 A 減少(B 的起始量不知道)。挑不出唯一一個就拒答。",
13
+ "正例": [
14
+ {"句": "Nora gives 5 apples to Leo", "欄位": {"給方": "nora", "量": "5", "物": "apples", "收方": "leo"}},
15
+ {"句": "She gave 3 of them to Ann"},
16
+ {"句": "Then Tom handed 2 red marbles to Ann at school"}
17
+ ],
18
+ "反例": [
19
+ "Nora gives Leo 5 apples",
20
+ "Nora gave away 5 apples",
21
+ "Leo receives 5 apples from Nora",
22
+ "Nora gives 5 apples"
23
+ ],
24
+ "題例": [
25
+ {"題": "Nora had 17 apples. Leo had 8 apples. Nora gives 5 apples to Leo. How many apples does Leo have now?", "答": "13"},
26
+ {"題": "Nora had 17 apples. Nora gives 5 apples to Leo. How many apples does Nora have now?", "答": "12"},
27
+ {"題": "Nora had 17 apples. Nora gives 5 apples to Leo. How many apples does Leo have now?", "答": null}
28
+ ],
29
+ "來源": "nl2en_story_292 give_to(Claude #292 候選 規則候選_claude.py)改寫成詞類槽",
30
+ "作者": "Claude 子代理(規則樹框架)",
31
+ "建立": "2026-11-24"
32
+ }
hs/規則樹/葉子/量測/累計.移動-01.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "累計.移動-01",
3
+ "上層": "意思/累計量測",
4
+ "種類": "敘述",
5
+ "優先層": 2,
6
+ "樣式": "<主體:人> {副}<動:移動動詞> <量:量> <物:單位>{尾}",
7
+ "說明": "A ran/walked/swam N 單位。單位從詞庫 單位 子樹來(長度、時間…),新增單位不用改這片;不同單位相加時引擎插 換單位,交給左腦換算零件。",
8
+ "正例": [
9
+ {"句": "Tom ran 3 kilometers", "欄位": {"主體": "tom", "量": "3", "物": "kilometers"}},
10
+ {"句": "Then he swam 500 meters in the pool"},
11
+ {"句": "Ann walked 2 miles"}
12
+ ],
13
+ "反例": ["Tom ran 3 apples", "Tom ran fast"],
14
+ "題例": [{"題": "Tom ran 3 kilometers. Then he ran 500 meters. How many meters did Tom run in all?", "答": "3500"}],
15
+ "來源": "使用者 11-24 06:3x 詞類槽設計示範(單位)",
16
+ "作者": "Claude 子代理(規則樹框架)",
17
+ "建立": "2026-11-24"
18
+ }
hs/規則樹/詞庫.json ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "說明": "詞類樹(#306,使用者 11-24 06:3x):葉子的比對樣式只寫詞類槽 <槽名:詞類>,具體的詞都放這裡。新增一個詞=在這裡加一筆,所有用到該詞類(或它的上層詞類)的葉子自動適用。每個詞:形=會出現的寫法(含單複數、時態),其他欄位是屬性(係數=以該維度基本單位計、可切=能不能分成非整數份、代碼=幣別)。開放詞類有『樣式』:不在清單的詞也收,但拿不到屬性。",
3
+ "版本": "v0 2026-11-24 Claude 子代理(規則樹框架)",
4
+ "類": {
5
+ "人": {"上層": null, "說明": "題中的人或擁有者;開放詞類,排除虛詞", "樣式": "(?:(?:the|a|an) )?(?!(?:away|some|more|all|each|every|back|up|out|off|total|there|it|its|them|then|now|also|in|on|at|to|from|of|for|with|and|than)\\b)[a-z][a-z'-]*"},
6
+ "地點": {"上層": null, "說明": "放東西的地方(擁有者是地點);開放詞類", "樣式": "[a-z]+(?:-[a-z]+)*"},
7
+ "物品": {"上層": null, "說明": "所有可以數量化的東西的總類"},
8
+ "可數物品": {"上層": "物品", "說明": "整個的東西;開放詞類(不在清單也收),清單內的附屬性", "樣式": "[a-z]+(?:-[a-z]+)*",
9
+ "詞": {
10
+ "apple": {"形": ["apple", "apples"], "可切": false},
11
+ "orange": {"形": ["orange", "oranges"], "可切": false},
12
+ "pencil": {"形": ["pencil", "pencils"], "可切": false},
13
+ "marble": {"形": ["marble", "marbles"], "可切": false},
14
+ "cookie": {"形": ["cookie", "cookies"], "可切": false},
15
+ "book": {"形": ["book", "books"], "可切": false},
16
+ "sticker": {"形": ["sticker", "stickers"], "可切": false},
17
+ "egg": {"形": ["egg", "eggs"], "可切": false},
18
+ "child": {"形": ["child", "children"], "可切": false},
19
+ "person": {"形": ["person", "people"], "可切": false}
20
+ }},
21
+ "可切物質": {"上層": "物品", "說明": "可以分成非整數份的東西",
22
+ "詞": {
23
+ "juice": {"形": ["juice"], "可切": true},
24
+ "water": {"形": ["water"], "可切": true},
25
+ "milk": {"形": ["milk"], "可切": true},
26
+ "flour": {"形": ["flour"], "可切": true},
27
+ "pizza": {"形": ["pizza", "pizzas"], "可切": true},
28
+ "cake": {"形": ["cake", "cakes"], "可切": true}
29
+ }},
30
+ "容器": {"上層": null, "說明": "等組題的『組』:每個容器裝一樣多",
31
+ "詞": {
32
+ "box": {"形": ["box", "boxes"]}, "bag": {"形": ["bag", "bags"]}, "basket": {"形": ["basket", "baskets"]},
33
+ "pack": {"形": ["pack", "packs"]}, "packet": {"形": ["packet", "packets"]}, "carton": {"形": ["carton", "cartons"]},
34
+ "crate": {"形": ["crate", "crates"]}, "jar": {"形": ["jar", "jars"]}, "bucket": {"形":["bucket", "buckets"]},
35
+ "tray": {"形": ["tray", "trays"]}, "shelf": {"形": ["shelf", "shelves"]}, "row": {"形": ["row", "rows"]},
36
+ "plate": {"形": ["plate", "plates"]}, "bowl": {"形": ["bowl", "bowls"]}, "case": {"形": ["case", "cases"]},
37
+ "container": {"形": ["container", "containers"]}, "bundle": {"形": ["bundle", "bundles"]},
38
+ "page": {"形": ["page", "pages"]}, "table": {"形": ["table", "tables"]}, "team": {"形": ["team", "teams"]},
39
+ "group": {"形": ["group", "groups"]}, "dozen": {"形": ["dozen", "dozens"]}
40
+ }},
41
+ "單位": {"上層": null, "說明": "量的單位;換算交給左腦第二級①換算零件,規則裡不算"},
42
+ "長度單位": {"上層": "單位", "基本": "meter",
43
+ "詞": {
44
+ "meter": {"形": ["meter", "meters", "metre", "metres"], "係數": "1"},
45
+ "kilometer": {"形": ["kilometer", "kilometers", "kilometre", "kilometres", "km"], "係數": "1000"},
46
+ "centimeter": {"形": ["centimeter", "centimeters", "centimetre", "centimetres", "cm"], "係數": "1/100"},
47
+ "millimeter": {"形": ["millimeter", "millimeters", "mm"], "係數": "1/1000"},
48
+ "foot": {"形": ["foot", "feet"], "係數": "3048/10000"},
49
+ "inch": {"形": ["inch", "inches"], "係數": "254/10000"},
50
+ "yard": {"形": ["yard", "yards"], "係數": "9144/10000"},
51
+ "mile": {"形": ["mile", "miles"], "係數": "1609344/1000"}
52
+ }},
53
+ "時間單位": {"上層": "單位", "基本": "second",
54
+ "詞": {
55
+ "second": {"形": ["second", "seconds"], "係數": "1"},
56
+ "minute": {"形": ["minute", "minutes"], "係數": "60"},
57
+ "hour": {"形": ["hour", "hours"], "係數": "3600"},
58
+ "day": {"形": ["day", "days"], "係數": "86400"},
59
+ "week": {"形": ["week", "weeks"], "係數": "604800"}
60
+ }},
61
+ "重量單位": {"上層": "單位", "基本": "gram",
62
+ "詞": {
63
+ "gram": {"形": ["gram", "grams", "g"], "係數": "1"},
64
+ "kilogram": {"形": ["kilogram", "kilograms", "kg"], "係數": "1000"},
65
+ "pound": {"形": ["pound", "pounds", "lb", "lbs"], "係數": "45359237/100000"},
66
+ "ounce": {"形": ["ounce", "ounces", "oz"], "係數": "45359237/1600000"}
67
+ }},
68
+ "容量單位": {"上層": "單位", "基本": "liter",
69
+ "詞": {
70
+ "liter": {"形": ["liter", "liters", "litre", "litres"], "係數": "1"},
71
+ "milliliter": {"形": ["milliliter", "milliliters", "ml"], "係數": "1/1000"},
72
+ "gallon": {"形": ["gallon", "gallons"], "係數": "3785411784/1000000000"}
73
+ }},
74
+ "貨幣": {"上層": null, "說明": "金額;$N 由正規化處理,這裡收寫成字的幣別",
75
+ "詞": {
76
+ "dollar": {"形": ["dollar", "dollars"], "代碼": "USD", "係數": "1"},
77
+ "cent": {"形": ["cent", "cents"], "代碼": "USD", "係數": "1/100"}
78
+ }},
79
+ "動詞": {"上層": null, "說明": "動作詞總類"},
80
+ "有類動詞": {"上層": "動詞", "說明": "表示擁有(起始量)",
81
+ "詞": {
82
+ "have": {"形": ["has", "have", "had"]},
83
+ "own": {"形": ["owns", "own", "owned"]},
84
+ "start with": {"形": ["starts with", "started with", "start with", "began with", "begins with"]}
85
+ }},
86
+ "得類動詞": {"上層": "動詞", "說明": "主體的量增加(沒說從誰來)",
87
+ "詞": {
88
+ "buy": {"形": ["buys", "buy", "bought"]}, "get": {"形": ["gets", "get", "got"]},
89
+ "receive": {"形": ["receives", "receive", "received"]}, "find": {"形": ["finds", "find", "found"]},
90
+ "pick": {"形": ["picks", "picked", "pick", "picks up", "picked up"]}, "collect": {"形": ["collects", "collected", "collect"]},
91
+ "win": {"形": ["wins", "won", "win"]}, "earn": {"形": ["earns", "earned", "earn"]},
92
+ "make": {"形": ["makes", "made", "make"]}, "bake": {"形": ["bakes", "baked", "bake"]},
93
+ "catch": {"形": ["catches", "caught", "catch"]}, "save": {"形": ["saves", "saved", "save"]},
94
+ "borrow": {"形": ["borrows", "borrowed", "borrow"]}
95
+ }},
96
+ "失類動詞": {"上層": "動詞", "說明": "主體的量減少(沒說給誰)",
97
+ "詞": {
98
+ "give away": {"形": ["gives away", "gave away", "give away"]}, "sell": {"形": ["sells", "sold", "sell"]},
99
+ "use": {"形": ["uses", "used", "use"]}, "lose": {"形": ["loses", "lost", "lose"]},
100
+ "eat": {"形": ["eats", "ate", "eat"]}, "spend": {"形": ["spends", "spent", "spend"]},
101
+ "donate": {"形": ["donates", "donated", "donate"]}, "break": {"形": ["breaks", "broke", "break"]},
102
+ "throw away": {"形": ["throws away", "threw away"]}, "drink": {"形": ["drinks", "drank", "drink"]},
103
+ "pay": {"形": ["pays", "paid", "pay"]}, "return": {"形": ["returns", "returned"]}
104
+ }},
105
+ "給類動詞": {"上層": "動詞", "說明": "轉移:主詞給出、受詞(to 某人)收到",
106
+ "詞": {
107
+ "give": {"形": ["gives", "gave", "give"]}, "hand": {"形": ["hands", "handed", "hand"]},
108
+ "pass": {"形": ["passes", "passed", "pass"]}, "send": {"形": ["sends", "sent", "send"]},
109
+ "lend": {"形": ["lends", "lent", "lend"]}
110
+ }},
111
+ "收類動詞": {"上層": "動詞", "說明": "轉移:主詞收到、from 某人給出",
112
+ "詞": {
113
+ "receive": {"形": ["receives", "received", "receive"]}, "get": {"形": ["gets", "got", "get"]},
114
+ "take": {"形": ["takes", "took", "take"]}, "borrow": {"形": ["borrows", "borrowed", "borrow"]},
115
+ "buy": {"形": ["buys", "bought", "buy"]}
116
+ }},
117
+ "分類動詞": {"上層": "動詞", "說明": "均分",
118
+ "詞": {
119
+ "share": {"形": ["shares", "shared", "share"]}, "divide": {"形": ["divides", "divided", "divide"]},
120
+ "split": {"形": ["splits", "split"]}, "distribute": {"形": ["distributes", "distributed", "distribute"]},
121
+ "hand out": {"形": ["hands out", "handed out", "hand out"]}
122
+ }},
123
+ "裝類動詞": {"上層": "動詞", "說明": "容器裝了多少(等組比率)",
124
+ "詞": {
125
+ "contain": {"形": ["contains", "contained", "contain"]}, "hold": {"形": ["holds", "held", "hold"]},
126
+ "have": {"形": ["has", "have", "had"]}
127
+ }},
128
+ "移動動詞": {"上層": "動詞", "說明": "主體移動一段距離/時間",
129
+ "詞": {
130
+ "run": {"形": ["runs", "ran", "run"]}, "walk": {"形": ["walks", "walked", "walk"]},
131
+ "swim": {"形": ["swims", "swam", "swim"]}, "drive": {"形": ["drives", "drove", "drive"]},
132
+ "ride": {"形": ["rides", "rode", "ride"]}, "jog": {"形": ["jogs", "jogged", "jog"]},
133
+ "cycle": {"形": ["cycles", "cycled"]}
134
+ }},
135
+ "減量動詞": {"上層": null, "包含": ["失類動詞", "給類動詞"], "說明": "抽出來的概念:失類動詞∪給類動詞(合併 減少.失去-01、減少.給出-01 時建)"}
136
+ }
137
+ }
hs/語法模組/api.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """語法模組總入口:外部(電腦Codex 的 pipeline、規則樹、#315 三層)只 import 這一支。
2
+
3
+ import importlib.util; spec = importlib.util.spec_from_file_location("語法模組", r"H:\\Agent共用\\專案\\手搓算術\\語法模組\\api.py")
4
+ gm = importlib.util.module_from_spec(spec); spec.loader.exec_module(gm)
5
+ ctx = gm.units.UnitContext()
6
+ gm.units.convert(2, "dollars", "cents", ctx)["prefix"] # "乘 2 100"
7
+ gm.fmt.render(Fraction(9, 4)) # "2.25"
8
+ gm.comparison.relate("add", {"target": 13, "quantity": 5}, "source")
9
+ # {"value": Fraction(8), "prefix": "減 13 5", "status": "ok", ...}
10
+
11
+ 各模組檔名都叫 模組.py,這裡用路徑分開載入,避免同名互蓋。
12
+ """
13
+ import importlib.util
14
+ from pathlib import Path
15
+ import sys
16
+
17
+ HERE = Path(__file__).resolve().parent
18
+ sys.path.insert(0, str(HERE))
19
+ import 核心 # noqa: E402,F401
20
+ from 核心 import INCONSISTENT, INSUFFICIENT, UNSUPPORTED, Refusal # noqa: E402,F401
21
+
22
+
23
+ def _load(name, path):
24
+ if name in sys.modules:
25
+ return sys.modules[name]
26
+ spec = importlib.util.spec_from_file_location(name, path)
27
+ mod = importlib.util.module_from_spec(spec)
28
+ sys.modules[name] = mod
29
+ spec.loader.exec_module(mod)
30
+ return mod
31
+
32
+
33
+ units = _load("語法模組_單位", HERE / "單位" / "模組.py")
34
+ fmt = _load("語法模組_輸出格式", HERE / "輸出格式" / "模組.py")
35
+ comparison = _load("語法模組_比較", HERE / "比較" / "模組.py")
36
+ transfer = _load("語法模組_移轉", HERE / "移轉" / "模組.py").create(comparison.solve)
37
+ partwhole = _load("語法模組_部分與整體", HERE / "部分與整體" / "模組.py").create(comparison.solve)
38
+ rates = _load("語法模組_速率", HERE / "速率" / "模組.py").create(units, comparison)
39
+ VERSION = "v0-20261125+comparison-v1+transfer-v1+partwhole-v1+linear-v1+rate-udg-v2"
hs/語法模組/單位/換算策略/10_題內定義.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """換算策略:題目暫時單位(盒、袋、桶)照題內定義展開;題文優先於固定表。
2
+
3
+ 一條邊=「1 個 甲 = 倍率 個 乙」。這條策略給兩個方向:
4
+ 正向 bucket → liter(Each bucket contains 2 liters → 1 bucket = 2 liters)
5
+ 反向 liter → bucket(倍率 1/2;問『裝滿幾桶』時用)
6
+ """
7
+ from fractions import Fraction
8
+
9
+ NAME = "題內定義"
10
+ PRIORITY = 10
11
+
12
+
13
+ def edges(node, ctx):
14
+ out = []
15
+ if node.startswith("題:"):
16
+ d = ctx.problem.get(node[2:])
17
+ if d is not None:
18
+ out.append((ctx.node_of(d.unit), d.amount, f"problem definition: {d.evidence or '1 ' + node[2:] + ' = ' + str(d.amount) + ' ' + d.unit}"))
19
+ for name, d in ctx.problem.defs.items():
20
+ if ctx.node_of(d.unit) == node:
21
+ out.append(("題:" + name, Fraction(1) / d.amount, f"problem definition (reverse): {d.evidence or name}"))
22
+ return out
23
+
24
+
25
+ # 自帶正反例:在一個只有「1 bucket = 2 liter」的題裡,從 node 出發看得到哪些邊
26
+ EXAMPLES = [
27
+ {"名": "正向展開", "定義": [["bucket", 2, "liters", "Each bucket contains 2 liters."]],
28
+ "節點": "題:bucket", "預期": [["公升", "2"]]},
29
+ {"名": "反向", "定義": [["bucket", 2, "liters", ""]], "節點": "公升", "預期": [["題:bucket", "1/2"]]},
30
+ {"名": "沒定義就沒邊", "定義": [], "節點": "題:box", "預期": []},
31
+ ]
hs/語法模組/單位/換算策略/20_固定表同維度.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """換算策略:固定單位表裡同一維度的單位互換(dollar ↔ cent、liter ↔ milliliter、hour ↔ minute)。
2
+
3
+ 倍率=來源單位對最小單位的倍率 ÷ 目標單位的倍率,用 Fraction 保持精確。
4
+ 不同維度之間不給邊(公升換不成公斤:沒有密度就拒答)。
5
+ """
6
+
7
+ NAME = "固定表同維度"
8
+ PRIORITY = 20
9
+
10
+
11
+ def edges(node, ctx):
12
+ if node.startswith("題:"):
13
+ return []
14
+ src = ctx.table.by_canon.get(node)
15
+ if src is None:
16
+ return []
17
+ return [(u.canon, src.factor / u.factor, f"fixed table ({src.dim}): 1 {src.english[0]} = {src.factor / u.factor} {u.english[1]}")
18
+ for u in ctx.table.dim_units(src.dim) if u.canon != node]
19
+
20
+
21
+ EXAMPLES = [
22
+ {"名": "美元到美分", "定義": [], "節點": "美元", "含": ["美分", "100"]},
23
+ {"名": "公升到毫升", "定義": [], "節點": "公升", "含": ["毫升", "1000"]},
24
+ {"名": "分到時是分數", "定義": [], "節點": "分", "含": ["時", "1/60"]},
25
+ {"名": "公升不連公斤", "定義": [], "節點": "公升", "不含": "公斤"},
26
+ ]
hs/語法模組/單位/模組.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """單位模組 API(Claude 子代理(語法模組化)2026-11-25)。
2
+
3
+ ctx = UnitContext() # 一題一個;固定表共用、暫時單位只活在這題
4
+ ctx.problem.define("bucket", 2, "liters", evidence="Each bucket contains 2 liters.")
5
+ target, how = choose_target(["buckets"], asked="milliliters", ctx=ctx)
6
+ r = convert(4, "buckets", target, ctx)
7
+ r == {"value": Fraction(8000), "unit": "毫升", "unit_en": "milliliters",
8
+ "steps": [...每一步從誰到誰、乘多少、依據哪句...], "prefix": "乘 乘 4 2 1000"}
9
+
10
+ 吃:數值+原單位+目標單位(或問句要的單位);吐:精確值+單位+怎麼換的(步驟與螺旋語前綴式)。
11
+ 失敗一律 raise Refusal(status=insufficient/inconsistent/unsupported)。
12
+ 換算策略在 換算策略\、選單位策略在 選單位策略\,一條一個檔,加新檔不改這支。
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from collections import deque
17
+ from fractions import Fraction
18
+ from pathlib import Path
19
+ import sys
20
+
21
+ HERE = Path(__file__).resolve().parent
22
+ sys.path.insert(0, str(HERE.parent))
23
+ sys.path.insert(0, str(HERE))
24
+ from 核心 import INSUFFICIENT, UNSUPPORTED, Refusal, load_strategies, need # noqa: E402
25
+ from 表 import ProblemUnits, fixed_table, singular # noqa: E402
26
+
27
+ CONVERTERS = HERE / "換算策略"
28
+ CHOOSERS = HERE / "選單位策略"
29
+ MAX_STEPS = 4
30
+
31
+
32
+ class UnitContext:
33
+ def __init__(self, problem: ProblemUnits | None = None, table=None):
34
+ self.table = table or fixed_table()
35
+ self.problem = problem or ProblemUnits()
36
+
37
+ def node_of(self, word: str) -> str:
38
+ """英文單位字 → 圖上的節點。題內定義優先(題文覆寫固定表)。"""
39
+ need(bool(word), "missing_unit", "quantity has no unit", INSUFFICIENT)
40
+ if self.problem.get(word) is not None:
41
+ return "題:" + singular(word)
42
+ u = self.table.lookup(word)
43
+ if u is not None:
44
+ return u.canon
45
+ # 不在任何表、也沒題內定義:資料不足(可能是暫時單位但題目沒給它多大)
46
+ raise Refusal("unknown_unit", word, INSUFFICIENT)
47
+
48
+ def english(self, node: str, plural=True) -> str:
49
+ if node.startswith("題:"):
50
+ return node[2:] + ("s" if plural else "")
51
+ eng = self.table.by_canon[node].english
52
+ return eng[1] if plural else eng[0]
53
+
54
+
55
+ def _path(src: str, dst: str, ctx: UnitContext):
56
+ """在所有換算策略給的邊上找最短路徑;同長度時先到的策略(PRIORITY 小)勝。"""
57
+ if src == dst:
58
+ return []
59
+ strategies = load_strategies(CONVERTERS)
60
+ seen = {src: None}
61
+ queue = deque([src])
62
+ while queue:
63
+ node = queue.popleft()
64
+ depth = 0
65
+ back = node
66
+ while seen[back] is not None:
67
+ back = seen[back][0]
68
+ depth += 1
69
+ if depth >= MAX_STEPS:
70
+ continue
71
+ for strat in strategies:
72
+ for nxt, factor, why in strat.edges(node, ctx):
73
+ if nxt in seen:
74
+ continue
75
+ seen[nxt] = (node, Fraction(factor), why, strat.NAME)
76
+ if nxt == dst:
77
+ steps = []
78
+ cur = dst
79
+ while seen[cur] is not None:
80
+ prev, f, w, name = seen[cur]
81
+ steps.append({"from": ctx.english(prev), "to": ctx.english(cur), "times": str(f),
82
+ "strategy": name, "by": w})
83
+ cur = prev
84
+ return steps[::-1]
85
+ queue.append(nxt)
86
+ return None
87
+
88
+
89
+ def _num(x: Fraction) -> str:
90
+ return str(x.numerator) if x.denominator == 1 else f"{x.numerator}/{x.denominator}"
91
+
92
+
93
+ def prefix_step(inner: str, factor: Fraction) -> str:
94
+ """把一步換算包成螺旋語前綴式:乘 X k、除 X k、或 除 乘 X p q。"""
95
+ p, q = factor.numerator, factor.denominator
96
+ if p == q:
97
+ return inner
98
+ if q == 1:
99
+ return f"乘 {inner} {p}"
100
+ if p == 1:
101
+ return f"除 {inner} {q}"
102
+ return f"除 乘 {inner} {p} {q}"
103
+
104
+
105
+ def convert(value, unit: str, target: str, ctx: UnitContext, inner: str | None = None):
106
+ """value unit → target。inner 是 value 已有的前綴式(預設就是數字本身)。"""
107
+ value = Fraction(value)
108
+ src, dst = ctx.node_of(unit), (target if target in ctx.table.by_canon or target.startswith("題:") else ctx.node_of(target))
109
+ steps = _path(src, dst, ctx)
110
+ if steps is None:
111
+ a, b = ctx.table.by_canon.get(src), ctx.table.by_canon.get(dst)
112
+ if a is not None and b is not None and a.dim != b.dim:
113
+ raise Refusal("dimension_mismatch", f"{unit} ({a.dim}) -> {ctx.english(dst)} ({b.dim})", UNSUPPORTED)
114
+ raise Refusal("no_conversion_path", f"{unit} -> {ctx.english(dst)}", INSUFFICIENT)
115
+ expr = inner if inner is not None else _num(value)
116
+ for s in steps:
117
+ f = Fraction(s["times"])
118
+ value *= f
119
+ expr = prefix_step(expr, f)
120
+ return {"value": value, "unit": dst, "unit_en": ctx.english(dst), "steps": steps, "prefix": expr}
121
+
122
+
123
+ def convert_ratio(value, unit: str, target: str, ctx: UnitContext, inner: str | None = None):
124
+ """比率單位 a/b → c/d(視窗GPT 11-26,Claude子代理合併):分子分母各走原單位圖,分母倍率取倒數。
125
+ 只做等價表示;不把速率當時段、不猜一月幾週(題內明示定義才用)。"""
126
+ from 比率單位 import convert_rate
127
+ return convert_rate(value, unit, target, ctx, load_strategies(CONVERTERS), prefix_step, MAX_STEPS, inner)
128
+
129
+
130
+ def choose_target(sources: list, asked: str | None, ctx: UnitContext):
131
+ """決定答案用的單位。回 (節點, 用了哪條策略)。全部策略都不接 → 拒答。"""
132
+ for strat in load_strategies(CHOOSERS):
133
+ got = strat.choose(sources, asked, ctx)
134
+ if got is not None:
135
+ return got, strat.NAME
136
+ raise Refusal("no_target_unit", f"sources={sources} asked={asked}", INSUFFICIENT)
137
+
138
+
139
+ def to_target(quantities, asked, ctx):
140
+ """問題層常用:一串 (值, 單位[, 前綴式]) 換到同一個單位。回 (目標, 換好的清單, 選單位策略)。"""
141
+ target, how = choose_target([q[1] for q in quantities], asked, ctx)
142
+ out = [convert(q[0], q[1], target, ctx, q[2] if len(q) > 2 else None) for q in quantities]
143
+ return target, out, how
hs/語法模組/單位/比率單位.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """比率單位(a/b → c/d)換算。來源:視窗GPT 20261126「GEM比率換算加權清單與豁免反例」patch/比率單位.py,
2
+ Claude子代理(合併視窗GPT成果)11-26 原樣移入(只加這段說明);入口 模組.convert_ratio,程式腦 ratio_convert 用。
3
+
4
+ Explicit numerator/denominator conversion, using existing scalar graph edges.
5
+ Do not infer wages, elapsed/calendar equivalences or a common item from words.
6
+ Optional compound conversion only: no change to scalar conversions.
7
+ """
8
+ from collections import deque
9
+ from fractions import Fraction as F
10
+ import copy
11
+ from 核心 import Refusal, INSUFFICIENT, INCONSISTENT, UNSUPPORTED, need
12
+
13
+
14
+ def parts(s):
15
+ need(isinstance(s,str) and s.count('/') == 1, 'compound_unit_required', str(s))
16
+ a,b=(x.strip() for x in s.split('/'))
17
+ need(bool(a and b) and all(len(x)<=80 and not any(c in x for c in '*^()[]') for x in (a,b)), 'unsupported_compound_unit', str(s))
18
+ return a,b
19
+
20
+
21
+ def scoped_context(ctx, units):
22
+ # The existing UnitContext is per question, but item-specific capacities are not
23
+ # globally interchangeable. The raw convert API has no item binding, so don't use them.
24
+ c=copy.copy(ctx);c.problem=copy.copy(ctx.problem);c.problem.defs={}
25
+ for name,d in ctx.problem.defs.items():
26
+ if d.item is None and d.evidence and d.evidence.strip() not in ('無','none','—','-'):
27
+ # A unit whose name already denotes a fixed physical unit must not shadow it.
28
+ if ctx.table.lookup(name) is not None:
29
+ continue
30
+ c.problem.defs[name]=d
31
+ for u in units:
32
+ if ctx.problem.get(u) is not None and c.problem.get(u) is None:
33
+ raise Refusal('unverified_or_scoped_unit',u,INSUFFICIENT)
34
+ return c
35
+
36
+
37
+ def key(u,ctx):
38
+ return u if u in ctx.table.by_canon else ctx.node_of(u)
39
+
40
+
41
+ def axis(src,dst,ctx,strategies,max_steps):
42
+ a,b=key(src,ctx),key(dst,ctx)
43
+ # Reuse existing scalar edges, audit consistency over the reached component.
44
+ # The first traversal is BFS; retain shortest path, reject conflicting routes.
45
+ values={a:F(1)};prev={a:None};depth={a:0};q=deque([a]);edges_seen=0
46
+ while q:
47
+ u=q.popleft()
48
+ for st in strategies:
49
+ for v,f,why in st.edges(u,ctx):
50
+ edges_seen+=1;need(edges_seen<=8192,'unit_graph_budget')
51
+ f=F(f);need(f>0,'nonpositive_conversion',str(f),INCONSISTENT)
52
+ z=values[u]*f
53
+ if v in values:
54
+ need(values[v]==z,'conflicting_conversion_paths',f'{src}: {ctx.english(v)}',INCONSISTENT)
55
+ continue
56
+ need(len(values)<256,'unit_graph_budget')
57
+ values[v]=z;prev[v]=(u,f,why,st.NAME);depth[v]=depth[u]+1;q.append(v)
58
+ if b not in values:
59
+ x,y=ctx.table.by_canon.get(a),ctx.table.by_canon.get(b)
60
+ if x and y and x.dim!=y.dim:
61
+ raise Refusal('dimension_mismatch',f'{src} -> {dst}',UNSUPPORTED)
62
+ raise Refusal('no_conversion_path',f'{src} -> {dst}',INSUFFICIENT)
63
+ need(depth[b]<=max_steps,'conversion_path_budget',f'{src} -> {dst}',INSUFFICIENT)
64
+ steps=[];v=b
65
+ while prev[v] is not None:
66
+ u,f,why,name=prev[v]
67
+ steps.append({'from':ctx.english(u),'to':ctx.english(v),'times':str(f),'strategy':name,'by':why});v=u
68
+ return values[b],steps[::-1],b
69
+
70
+
71
+ def convert_rate(value,unit,target,ctx,strategies,prefix_step,max_steps,inner=None):
72
+ n,d=parts(unit);N,D=parts(target);ctx=scoped_context(ctx,(n,d,N,D))
73
+ fn,ns,Nkey=axis(n,N,ctx,strategies,max_steps)
74
+ fd,ds,Dkey=axis(d,D,ctx,strategies,max_steps)
75
+ x=F(value);z=x
76
+ if inner is None:
77
+ p,q=abs(x.numerator),x.denominator
78
+ inner=str(p) if q==1 else f'除 {p} {q}'
79
+ if x<0:inner='負號 '+inner
80
+ steps=[]
81
+ for role,ss in [('numerator',ns),('denominator',ds)]:
82
+ for s in ss:
83
+ f=F(s['times']);applied=f if role=='numerator' else 1/f
84
+ steps.append(dict(s,axis=role,applied_times=str(applied)))
85
+ z*=applied;inner=prefix_step(inner,applied)
86
+ need(z==x*fn/fd,'conversion_reconstruction_failed',status=INCONSISTENT)
87
+ # Return target spelling for chaining. Canonical pair is provided separately.
88
+ return {'value':z,'unit':target,'unit_en':ctx.english(Nkey)+'/'+ctx.english(Dkey),
89
+ 'canonical_pair':[Nkey,Dkey],'steps':steps,'prefix':inner,
90
+ 'factor':str(fn/fd),'numerator_factor':str(fn),'denominator_factor':str(fd)}
hs/語法模組/單位/表.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """單位模組的兩張表:固定單位表(全隊共用、只讀)+題目暫時單位(只活在一題)。
2
+
3
+ Claude 子代理(語法模組化)2026-11-25。
4
+ 固定表唯一來源=轉換庫\\轉換表.json 的「單位」「單位英文」;本資料夾 補充表.json 只補它還沒有的維度(貨幣)。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from dataclasses import dataclass, field
10
+ from fractions import Fraction
11
+ from pathlib import Path
12
+
13
+ import sys
14
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
15
+ from 核心 import INCONSISTENT, Refusal, need # noqa: E402
16
+
17
+ HERE = Path(__file__).resolve().parent
18
+ SHARED_TABLE = HERE.parent.parent / "轉換庫" / "轉換表.json"
19
+ EXTRA_TABLE = HERE / "補充表.json"
20
+
21
+ # 只當名詞、不當單位的字(共用表把 eggs 收成「個」,這裡不跟)
22
+ NOT_UNITS = {"eggs", "m", "l", "g"} # 單字母縮寫太容易撞(m=公尺/分,l=公升/磅),交讀題器帶語境再傳全名
23
+
24
+ IRREGULAR = {"feet": "foot", "inches": "inch", "loaves": "loaf", "knives": "knife", "shelves": "shelf",
25
+ "leaves": "leaf", "people": "person", "children": "child", "teeth": "tooth", "geese": "goose",
26
+ "mice": "mouse", "men": "man", "women": "woman", "dozen": "dozen", "series": "series", "glasses": "glass",
27
+ "boxes": "box", "dishes": "dish", "batches": "batch", "benches": "bench", "buses": "bus"}
28
+
29
+
30
+ def singular(word: str) -> str:
31
+ w = word.strip().lower()
32
+ if w in IRREGULAR:
33
+ return IRREGULAR[w]
34
+ if w.endswith("ies") and len(w) > 4:
35
+ return w[:-3] + "y"
36
+ if w.endswith(("ches", "shes", "sses", "xes", "zes")):
37
+ return w[:-2]
38
+ if w.endswith("s") and not w.endswith("ss") and len(w) > 3:
39
+ return w[:-1]
40
+ return w
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Unit:
45
+ canon: str # 正名(中文,固定表)或 題:bucket(暫時單位)
46
+ dim: str # 維度名;暫時單位="題內"
47
+ factor: Fraction # 對該維度最小單位的倍率;暫時單位=1
48
+ english: tuple # (單數, 複數)
49
+
50
+
51
+ class FixedTable:
52
+ """固定單位表:英文字 → Unit。只讀。"""
53
+
54
+ def __init__(self, shared=SHARED_TABLE, extra=EXTRA_TABLE):
55
+ dims, words, show = {}, {}, {}
56
+ for path in (shared, extra):
57
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
58
+ for dim, units in data["單位"].items():
59
+ dims.setdefault(dim, {}).update(units)
60
+ words.update(data["單位英文"])
61
+ show.update(data.get("顯示英文", {}))
62
+ self.by_canon = {}
63
+ for dim, units in dims.items():
64
+ for canon, f in units.items():
65
+ need(canon not in self.by_canon, "table_conflict", f"{canon} 在兩個維度")
66
+ eng = tuple(show.get(canon, [canon, canon]))
67
+ self.by_canon[canon] = Unit(canon, dim, Fraction(f), eng)
68
+ self.by_word = {}
69
+ for w, canon in words.items():
70
+ if w in NOT_UNITS:
71
+ continue
72
+ need(canon in self.by_canon, "table_conflict", f"{w}→{canon} 沒有倍率")
73
+ self.by_word[w.lower()] = self.by_canon[canon]
74
+ self.sources = [str(shared), str(extra)]
75
+
76
+ def lookup(self, word: str):
77
+ w = word.strip().lower()
78
+ return self.by_word.get(w) or self.by_word.get(singular(w))
79
+
80
+ def dim_units(self, dim):
81
+ return [u for u in self.by_canon.values() if u.dim == dim]
82
+
83
+
84
+ @dataclass
85
+ class Definition:
86
+ amount: Fraction
87
+ unit: str # 定義用的單位(英文原字)
88
+ evidence: str # 原句
89
+ item: str | None = None
90
+
91
+
92
+ @dataclass
93
+ class ProblemUnits:
94
+ """題目暫時單位:盒、袋、桶……只存在這一題的狀態表裡。"""
95
+
96
+ defs: dict = field(default_factory=dict)
97
+
98
+ def define(self, name: str, amount, unit: str, evidence: str = "", item: str | None = None):
99
+ key = singular(name)
100
+ amount = Fraction(amount)
101
+ need(amount > 0, "nonpositive_definition", f"1 {key} = {amount} {unit}", INCONSISTENT)
102
+ new = Definition(amount, unit, evidence, item)
103
+ old = self.defs.get(key)
104
+ if old is not None and (old.amount, singular(old.unit)) != (amount, singular(unit)):
105
+ raise Refusal("conflicting_problem_unit", f"{key}: {old.amount} {old.unit} vs {amount} {unit}", INCONSISTENT)
106
+ self.defs[key] = new
107
+ return new
108
+
109
+ def get(self, name: str):
110
+ return self.defs.get(singular(name))
111
+
112
+ def as_state(self):
113
+ """寫進 #315 狀態表用的樣子(英文短句層+原句)。"""
114
+ return [{"unit": k, "equals": str(d.amount), "of": d.unit, "item": d.item, "evidence": d.evidence}
115
+ for k, d in self.defs.items()]
116
+
117
+
118
+ _TABLE = None
119
+
120
+
121
+ def fixed_table() -> FixedTable:
122
+ global _TABLE
123
+ if _TABLE is None:
124
+ _TABLE = FixedTable()
125
+ return _TABLE
hs/語法模組/單位/補充表.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "說明": "Claude 子代理(語法模組化)2026-11-25。共用轉換表(H:\\Agent共用\\專案\\手搓算術\\轉換庫\\轉換表.json)還沒有貨幣維度,先補在這裡;合併時建議搬進轉換表的「單位」「單位英文」兩欄,這份就刪掉。quarter 不收(會跟『四分之一』『一刻鐘』撞),要收得先有題內語境策略。",
3
+ "單位": {
4
+ "美元貨幣": {"美分": 1, "五分鎳幣": 5, "一角硬幣": 10, "美元": 100}
5
+ },
6
+ "單位英文": {
7
+ "cent": "美分", "cents": "美分", "penny": "美分", "pennies": "美分",
8
+ "nickel": "五分鎳幣", "nickels": "五分鎳幣",
9
+ "dime": "一角硬幣", "dimes": "一角硬幣",
10
+ "dollar": "美元", "dollars": "美元", "usd": "美元",
11
+ "kg": "公斤", "kgs": "公斤", "ml": "毫升", "cm": "公分",
12
+ "metre": "公尺", "metres": "公尺", "centimetre": "公分", "centimetres": "公分",
13
+ "litre": "公升", "litres": "公升", "millilitre": "毫升", "millilitres": "毫升"
14
+ },
15
+ "顯示英文": {
16
+ "美分": ["cent", "cents"], "五分鎳幣": ["nickel", "nickels"], "一角硬幣": ["dime", "dimes"], "美元": ["dollar", "dollars"],
17
+ "公釐": ["millimeter", "millimeters"], "公分": ["centimeter", "centimeters"], "公尺": ["meter", "meters"], "公里": ["kilometer", "kilometers"],
18
+ "英寸": ["inch", "inches"], "英尺": ["foot", "feet"], "碼": ["yard", "yards"], "英里": ["mile", "miles"],
19
+ "克": ["gram", "grams"], "公斤": ["kilogram", "kilograms"], "盎司": ["ounce", "ounces"], "磅": ["pound", "pounds"],
20
+ "毫升": ["milliliter", "milliliters"], "公升": ["liter", "liters"], "杯": ["cup", "cups"], "品脫": ["pint", "pints"], "夸脫": ["quart", "quarts"], "加侖": ["gallon", "gallons"],
21
+ "秒": ["second", "seconds"], "分": ["minute", "minutes"], "時": ["hour", "hours"], "天": ["day", "days"], "週": ["week", "weeks"],
22
+ "個": ["item", "items"], "雙": ["pair", "pairs"], "打": ["dozen", "dozen"]
23
+ }
24
+ }
hs/語法模組/單位/選單位策略/10_問句指定.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """選單位策略:問句指定了單位(How many cents ...)就照它。使用者 11-25 01:38:先讀問句要的單位。"""
2
+
3
+ NAME = "問句指定"
4
+ PRIORITY = 10
5
+
6
+
7
+ def choose(sources, asked, ctx):
8
+ if not asked:
9
+ return None
10
+ return ctx.node_of(asked)
11
+
12
+
13
+ EXAMPLES = [
14
+ {"名": "問美分", "來源": ["dollars", "cents"], "問": "cents", "預期": "美分"},
15
+ {"名": "問句沒單位就跳過", "來源": ["dollars"], "問": None, "預期": None},
16
+ ]
hs/語法模組/單位/選單位策略/20_全同單位.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """選單位策略:問句沒指定、來源全是同一個單位 → 就用它(不換)。"""
2
+
3
+ NAME = "全同單位"
4
+ PRIORITY = 20
5
+
6
+
7
+ def choose(sources, asked, ctx):
8
+ nodes = {ctx.node_of(s) for s in sources}
9
+ return nodes.pop() if len(nodes) == 1 else None
10
+
11
+
12
+ EXAMPLES = [
13
+ {"名": "都是美元", "來源": ["dollars", "dollar"], "問": None, "預期": "美元"},
14
+ {"名": "混用就跳過", "來源": ["dollars", "cents"], "問": None, "預期": None},
15
+ ]
hs/語法模組/單位/選單位策略/30_最小單位.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """選單位策略:問句沒指定、來源混用同維度單位 → 取題目裡出現的最小單位,數字盡量保持整數。
2
+
3
+ 使用者 11-25 01:38 例:2 小時 30 分 → 150 分。跨維度或含暫時單位不歸這條管(回 None,讓後面的策略或拒答接手)。
4
+ """
5
+
6
+ NAME = "最小單位"
7
+ PRIORITY = 30
8
+
9
+
10
+ def choose(sources, asked, ctx):
11
+ units = []
12
+ for s in sources:
13
+ node = ctx.node_of(s)
14
+ u = ctx.table.by_canon.get(node)
15
+ if u is None:
16
+ return None
17
+ units.append(u)
18
+ if len({u.dim for u in units}) != 1:
19
+ return None
20
+ return min(units, key=lambda u: u.factor).canon
21
+
22
+
23
+ EXAMPLES = [
24
+ {"名": "時與分取分", "來源": ["hours", "minutes"], "問": None, "預期": "分"},
25
+ {"名": "美元與美分取美分", "來源": ["dollars", "cents"], "問": None, "預期": "美分"},
26
+ {"名": "跨維度不管", "來源": ["liters", "kilograms"], "問": None, "預期": None},
27
+ ]
hs/語法模組/核心.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """語法模組核心:拒答例外、策略載入(一條策略一個檔)、正反例執行。
2
+
3
+ Claude 子代理(語法模組化)2026-11-25 建。設計見同資料夾 設計.md。
4
+ 只用標準函式庫;策略檔不 import 任何東西,需要的資料由呼叫端放進 ctx 傳入。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import importlib.util
9
+ from pathlib import Path
10
+
11
+ HERE = Path(__file__).resolve().parent
12
+
13
+
14
+ # 拒答三種狀態(Pro 11-25 MathWorld 比較實驗:原版全回「未知」,分不出來)
15
+ INSUFFICIENT = "insufficient" # 資料不足:條件不夠決定答案(缺定義、缺初值、欠定)
16
+ INCONSISTENT = "inconsistent" # 條件矛盾:題目給的條件互相衝突(同一盒子兩種容量、s×0=5)
17
+ UNSUPPORTED = "unsupported" # 超出本模組能力:數學上可能有解,但目前策略/後端沒做(聯立方程、跨維度)
18
+ STATUSES = (INSUFFICIENT, INCONSISTENT, UNSUPPORTED)
19
+
20
+
21
+ class Refusal(ValueError):
22
+ """模組拒答:reason 是固定的機器碼(英文短句層看得懂),status 是三種狀態之一,detail 給人看。"""
23
+
24
+ def __init__(self, reason: str, detail: str = "", status: str = UNSUPPORTED):
25
+ assert status in STATUSES, status
26
+ super().__init__(f"[{status}] {reason}: {detail}" if detail else f"[{status}] {reason}")
27
+ self.reason = reason
28
+ self.detail = detail
29
+ self.status = status
30
+
31
+ def as_dict(self):
32
+ return {"status": self.status, "reason": self.reason, "detail": self.detail}
33
+
34
+
35
+ def need(cond, reason, detail="", status=UNSUPPORTED):
36
+ if not cond:
37
+ raise Refusal(reason, detail, status)
38
+
39
+
40
+ _CACHE: dict[str, list] = {}
41
+
42
+
43
+ def load_strategies(folder: Path) -> list:
44
+ """載入資料夾內每個 *.py 策略檔,依 PRIORITY(小的先)排序。
45
+
46
+ 每個策略檔至少要有 NAME(字串)、PRIORITY(整數);其餘函式依模組種類而定。
47
+ 檔名以 _ 開頭的不載入(草稿/停用)。
48
+ """
49
+ key = str(folder)
50
+ if key in _CACHE:
51
+ return _CACHE[key]
52
+ found = []
53
+ for path in sorted(folder.glob("*.py")):
54
+ if path.name.startswith("_"):
55
+ continue
56
+ spec = importlib.util.spec_from_file_location(f"語法模組策略_{folder.name}_{path.stem}", path)
57
+ mod = importlib.util.module_from_spec(spec)
58
+ spec.loader.exec_module(mod)
59
+ for attr in ("NAME", "PRIORITY"):
60
+ if not hasattr(mod, attr):
61
+ raise TypeError(f"策略檔 {path} 缺 {attr}")
62
+ mod.PATH = path
63
+ found.append(mod)
64
+ names = [m.NAME for m in found]
65
+ if len(names) != len(set(names)):
66
+ raise TypeError(f"{folder} 有重名策略:{names}")
67
+ found.sort(key=lambda m: (m.PRIORITY, m.NAME))
68
+ _CACHE[key] = found
69
+ return found
70
+
71
+
72
+ def run_examples(cases, call):
73
+ """cases:[{"名": , "輸入": {...}, "預期": 值 或 {"拒答": 原因碼}}];call(**輸入) → 值。
74
+
75
+ 回傳 (通過數, 失敗清單)。拒答例只看原因碼,不看 detail。
76
+ """
77
+ ok, bad = 0, []
78
+ for case in cases:
79
+ want = case["預期"]
80
+ try:
81
+ got = call(**case["輸入"])
82
+ except Refusal as exc:
83
+ got = {"拒答": exc.reason}
84
+ if isinstance(want, dict) and "狀態" in want:
85
+ got["狀態"] = exc.status
86
+ if got == want:
87
+ ok += 1
88
+ else:
89
+ bad.append({"名": case.get("名"), "預期": want, "得到": got})
90
+ return ok, bad
hs/語法模組/比較/solver/10_單一未知.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-occurrence, single-unknown propagation; dependencies arrive in ctx."""
2
+ NAME = "single_unknown"
3
+ PRIORITY = 10
4
+ EXAMPLES = [
5
+ {"名": "倒推", "輸入": {"equations": [{"left": "t", "right": ["add", "s", 5]}], "known": {"t": 13}, "query": "s"}, "預期": {"status": "ok", "value": "8", "prefix": "減 13 5"}},
6
+ {"名": "零乘矛盾", "輸入": {"equations": [{"left": 5, "right": ["mul", "s", 0]}], "known": {}, "query": "s"}, "預期": {"status": "inconsistent", "reason": "contradictory_equation"}}
7
+ ]
8
+
9
+
10
+ def solve(equations, known, query, ctx):
11
+ F, Refusal = ctx["Fraction"], ctx["Refusal"]
12
+ free, calc, prefix = ctx["free"], ctx["calc"], ctx["prefix"]
13
+ values, steps = dict(known), []
14
+
15
+ def sub(expr):
16
+ if isinstance(expr, str):
17
+ return values.get(expr, expr)
18
+ if isinstance(expr, F):
19
+ return expr
20
+ op, a, b = expr
21
+ a, b = sub(a), sub(b)
22
+ if op == "mul" and ((not free(a) and calc(a) == 0) or
23
+ (not free(b) and calc(b) == 0)):
24
+ return F(0)
25
+ return (op, a, b)
26
+
27
+ def count(expr, variable):
28
+ if isinstance(expr, str):
29
+ return int(expr == variable)
30
+ if isinstance(expr, F):
31
+ return 0
32
+ return count(expr[1], variable) + count(expr[2], variable)
33
+
34
+ def isolate(left, right, variable):
35
+ if variable not in free(left):
36
+ left, right = right, left
37
+ if isinstance(left, str):
38
+ return right
39
+ op, a, b = left
40
+ in_a = variable in free(a)
41
+ if op == "add":
42
+ expression = ("sub", right, b if in_a else a)
43
+ elif op == "sub":
44
+ expression = ("add", right, b) if in_a else ("sub", a, right)
45
+ elif op == "mul":
46
+ divisor = b if in_a else a
47
+ if calc(divisor) == 0:
48
+ raise Refusal("underdetermined", status=ctx["insufficient"])
49
+ expression = ("div", right, divisor)
50
+ else:
51
+ # Input equations exclude division; numeric prefix subtrees contain
52
+ # no variables, so isolation never needs to enter such a subtree.
53
+ return None
54
+ return isolate(a if in_a else b, expression, variable)
55
+
56
+ while True:
57
+ progress = False
58
+ for index, (left, right) in enumerate(equations):
59
+ a, b = sub(left), sub(right)
60
+ variables = free(a) | free(b)
61
+ if not variables:
62
+ if calc(a) != calc(b):
63
+ raise Refusal("contradictory_equation", str(index), ctx["inconsistent"])
64
+ continue
65
+ if len(variables) != 1:
66
+ continue
67
+ variable = next(iter(variables))
68
+ if count(a, variable) + count(b, variable) != 1:
69
+ continue
70
+ expression = isolate(a, b, variable)
71
+ if expression is None:
72
+ continue
73
+ calc(expression)
74
+ values[variable] = expression
75
+ steps.append({"variable": variable, "equation": index,
76
+ "prefix": prefix(expression), "value": calc(expression),
77
+ "backend": NAME})
78
+ progress = True
79
+ if not progress:
80
+ break
81
+
82
+ remaining = [(sub(a), sub(b)) for a, b in equations]
83
+ pending = [(a, b) for a, b in remaining if free(a) or free(b)]
84
+ result = sub(query)
85
+ if pending:
86
+ # A single equation with at least two distinct, once-occurring unknowns
87
+ # cannot fix a queried individual variable in this add/sub/mul grammar.
88
+ # Do not use this shortcut for a known query or for coupled constraints.
89
+ if len(equations) == 1 and isinstance(result, str):
90
+ a, b = pending[0]
91
+ variables = free(a) | free(b)
92
+ if len(variables) >= 2 and all(count(a, v) + count(b, v) == 1 for v in variables):
93
+ raise Refusal("underdetermined", status=ctx["insufficient"])
94
+ return None
95
+ if free(result):
96
+ raise Refusal("underdetermined", status=ctx["insufficient"])
97
+ return {"status": "ok", "value": calc(result), "prefix": prefix(result),
98
+ "steps": steps, "backend": NAME}
hs/語法模組/比較/solver/50_精確線性.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exact linear systems; imports and shared arithmetic arrive through ctx."""
2
+ NAME = "exact_linear"
3
+ PRIORITY = 50
4
+ EXAMPLES = [
5
+ {"名": "二元唯一解", "輸入": {"equations": [
6
+ {"left": ["add", "x", "y"], "right": 10},
7
+ {"left": ["sub", "x", "y"], "right": 2}], "known": {}, "query": "x"},
8
+ "預期": {"status": "ok", "value": "6", "prefix": "加 乘 除 1 2 10 乘 除 1 2 2"}},
9
+ {"名": "重複線性變數", "輸入": {"equations": [
10
+ {"left": ["add", "x", "x"], "right": 6}], "known": {}, "query": "x"},
11
+ "預期": {"status": "ok", "value": "3", "prefix": "乘 除 1 2 6"}}
12
+ ]
13
+
14
+
15
+ def solve(equations, known, query, ctx):
16
+ F, Refusal = ctx["Fraction"], ctx["Refusal"]
17
+ free, calc, prefix = ctx["free"], ctx["calc"], ctx["prefix"]
18
+ zero, one = F(0), F(1)
19
+
20
+ def refuse(reason, detail="", status=None):
21
+ raise Refusal(reason, detail, status or ctx["unsupported"])
22
+
23
+ def substitute(expr, values):
24
+ if isinstance(expr, F):
25
+ return expr
26
+ if isinstance(expr, str):
27
+ return values.get(expr, expr)
28
+ return (expr[0], substitute(expr[1], values), substitute(expr[2], values))
29
+
30
+ def constant(op, a, b):
31
+ # Preserve source ASTs; only literal zero/one identities are removed.
32
+ if op == "add":
33
+ if a == zero:
34
+ return b
35
+ if b == zero:
36
+ return a
37
+ elif op == "sub":
38
+ if b == zero:
39
+ return a
40
+ elif op == "mul":
41
+ if a == zero or b == zero:
42
+ return zero
43
+ if a == one:
44
+ return b
45
+ if b == one:
46
+ return a
47
+ return (op, a, b)
48
+
49
+ def merge(left, right, scale):
50
+ coefficients = dict(left)
51
+ for variable, value in right.items():
52
+ updated = coefficients.get(variable, zero) + scale * value
53
+ if updated:
54
+ coefficients[variable] = updated
55
+ else:
56
+ coefficients.pop(variable, None)
57
+ return coefficients
58
+
59
+ def affine(expr):
60
+ if not free(expr):
61
+ return {}, expr
62
+ if isinstance(expr, str):
63
+ return {expr: one}, zero
64
+ op, a, b = expr
65
+ left, right = affine(a), affine(b)
66
+ if left is None or right is None:
67
+ return None
68
+ left_coeff, left_const = left
69
+ right_coeff, right_const = right
70
+ if op in ("add", "sub"):
71
+ scale = one if op == "add" else -one
72
+ return merge(left_coeff, right_coeff, scale), constant(op, left_const, right_const)
73
+ if op == "mul":
74
+ if left_coeff and right_coeff:
75
+ return None
76
+ if left_coeff:
77
+ scale = calc(right_const)
78
+ coefficients = {key: value * scale for key, value in left_coeff.items() if value * scale}
79
+ else:
80
+ scale = calc(left_const)
81
+ coefficients = {key: value * scale for key, value in right_coeff.items() if value * scale}
82
+ return coefficients, constant("mul", left_const, right_const)
83
+ # Variable division cannot occur in parsed input; numeric known-prefix
84
+ # divisions were handled above by the no-free-variables branch.
85
+ return None
86
+
87
+ substituted = [(substitute(left, known), substitute(right, known)) for left, right in equations]
88
+ variables = sorted(set().union(*(free(left) | free(right) for left, right in substituted)))
89
+ source_equations, rows, rhs_asts = [], [], []
90
+ for index, (left, right) in enumerate(substituted):
91
+ left_affine, right_affine = affine(left), affine(right)
92
+ if left_affine is None or right_affine is None:
93
+ return None
94
+ a_left, c_left = left_affine
95
+ a_right, c_right = right_affine
96
+ coefficients = merge(a_left, a_right, -one)
97
+ # A*x=b, where b retains RIGHT constant minus LEFT constant.
98
+ rhs = constant("sub", c_right, c_left)
99
+ row = [coefficients.get(variable, zero) for variable in variables]
100
+ rhs_value = calc(rhs)
101
+ rows.append({"equation": index, "coefficients": row,
102
+ "rhs_value": rhs_value, "rhs_prefix": prefix(rhs)})
103
+ rhs_asts.append(rhs)
104
+ source_equations.append({"index": index, "left": left, "right": right,
105
+ "left_prefix": prefix(left), "right_prefix": prefix(right)})
106
+
107
+ # Sparse original-row weights avoid an unnecessary dense m*m identity.
108
+ matrix = [row["coefficients"][:] + [row["rhs_value"]] for row in rows]
109
+ weights = [{index: one} for index in range(len(rows))]
110
+ pivots, pivot_row = [], 0
111
+ for column in range(len(variables)):
112
+ selected = next((row for row in range(pivot_row, len(matrix)) if matrix[row][column]), None)
113
+ if selected is None:
114
+ continue
115
+ matrix[pivot_row], matrix[selected] = matrix[selected], matrix[pivot_row]
116
+ weights[pivot_row], weights[selected] = weights[selected], weights[pivot_row]
117
+ divisor = matrix[pivot_row][column]
118
+ matrix[pivot_row] = [value / divisor for value in matrix[pivot_row]]
119
+ weights[pivot_row] = {index: value / divisor for index, value in weights[pivot_row].items()}
120
+ for row in range(len(matrix)):
121
+ if row == pivot_row:
122
+ continue
123
+ factor = matrix[row][column]
124
+ if not factor:
125
+ continue
126
+ matrix[row] = [value - factor * pivot
127
+ for value, pivot in zip(matrix[row], matrix[pivot_row])]
128
+ for index, value in weights[pivot_row].items():
129
+ updated = weights[row].get(index, zero) - factor * value
130
+ if updated:
131
+ weights[row][index] = updated
132
+ else:
133
+ weights[row].pop(index, None)
134
+ pivots.append(column)
135
+ pivot_row += 1
136
+ if pivot_row == len(matrix):
137
+ break
138
+
139
+ for index, row in enumerate(matrix):
140
+ if not any(row[:-1]) and row[-1]:
141
+ refuse("contradictory_equation", f"eliminated row {index}", ctx["inconsistent"])
142
+ if len(pivots) < len(variables):
143
+ refuse("underdetermined", "The full linear system has no unique assignment", ctx["insufficient"])
144
+
145
+ def balanced_sum(terms):
146
+ if not terms:
147
+ return zero
148
+ def build(start, end):
149
+ if end - start == 1:
150
+ return terms[start]
151
+ middle = (start + end) // 2
152
+ return ("add", build(start, middle), build(middle, end))
153
+ return build(0, len(terms))
154
+
155
+ expressions, solution_values, solutions, steps = {}, {}, {}, []
156
+ for row, column in enumerate(pivots):
157
+ variable = variables[column]
158
+ row_weights = [{"equation": index, "weight": weight}
159
+ for index, weight in sorted(weights[row].items())]
160
+ terms = [constant("mul", item["weight"], rhs_asts[item["equation"]])
161
+ for item in row_weights]
162
+ expression = balanced_sum([term for term in terms if term != zero])
163
+ value = matrix[row][-1]
164
+ if calc(expression) != value:
165
+ refuse("linear_verification_failed", "Weighted RHS does not match the eliminated solution")
166
+ expressions[variable], solution_values[variable] = expression, value
167
+ certificate = {"value": value, "prefix": prefix(expression), "row_weights": row_weights}
168
+ solutions[variable] = certificate
169
+ steps.append({"variable": variable, **certificate, "backend": NAME})
170
+
171
+ # Verify ALL original equations, not just pivot rows or the queried value.
172
+ numeric_values = {**known, **solution_values}
173
+ for index, (left, right) in enumerate(equations):
174
+ a, b = substitute(left, numeric_values), substitute(right, numeric_values)
175
+ if free(a) or free(b) or calc(a) != calc(b):
176
+ refuse("linear_verification_failed", f"Original equation {index} failed substitution")
177
+ answer = substitute(query, {**known, **expressions})
178
+ if free(answer):
179
+ refuse("underdetermined", "Query contains an unbound variable", ctx["insufficient"])
180
+ proof = {"variables": variables, "source_equations": source_equations,
181
+ "known_inputs": {variable: {"value": calc(value), "prefix": prefix(value)}
182
+ for variable, value in known.items()},
183
+ "linear_rows": rows, "solutions": solutions, "rank": len(pivots),
184
+ "original_equations_verified": True}
185
+ return {"status": "ok", "value": calc(answer), "prefix": prefix(answer),
186
+ "steps": steps, "backend": NAME, "proof": proof}
hs/語法模組/比較/solver/90_聯立預留.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fallback for constraints unresolved by the available backends."""
2
+ NAME = "coupled_reserved"
3
+ PRIORITY = 90
4
+ EXAMPLES = [
5
+ {"名": "真正非線性平方仍未支援", "輸入": {"equations": [
6
+ {"left": ["mul", "x", "x"], "right": 4}], "known": {}, "query": "x"},
7
+ "預期": {"status": "unsupported", "reason": "unresolved_by_single_unknown_solver"}}
8
+ ]
9
+
10
+
11
+ def solve(equations, known, query, ctx):
12
+ # Keep the established machine-readable reason for compatibility.
13
+ raise ctx["Refusal"]("unresolved_by_single_unknown_solver",
14
+ "Remaining constraints need a different backend",
15
+ ctx["unsupported"])
hs/語法模組/比較/模組.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Comparison contracts for the shared grammar-module API.
2
+
3
+ relate(card, known, query, *, prefixes=None) uses add/mul role cards.
4
+ solve(equations, known, query, *, prefixes=None) accepts pre-bound equations.
5
+ Values are exact rational numbers; unit normalization and event/entity binding
6
+ belong to the caller. Exact linear systems have an ordered fallback backend;
7
+ this is not an NLP parser, inventory validator, or nonlinear-system solver.
8
+ Refusal uses the shared core's three statuses.
9
+ """
10
+ from fractions import Fraction
11
+ import json
12
+ from pathlib import Path
13
+
14
+ from 核心 import Refusal, INSUFFICIENT, INCONSISTENT, UNSUPPORTED, load_strategies
15
+
16
+ HERE = Path(__file__).resolve().parent
17
+ CARDS = json.loads((HERE / "關係卡.json").read_text(encoding="utf-8"))["cards"]
18
+ OPS = {"add": "加", "sub": "減", "mul": "乘", "div": "除"}
19
+ ROLES = frozenset(("source", "target", "quantity"))
20
+ BACKENDS = load_strategies(HERE / "solver")
21
+
22
+
23
+ def _fail(reason, detail="", status=UNSUPPORTED):
24
+ raise Refusal(reason, detail, status)
25
+
26
+
27
+ def _number(value):
28
+ if isinstance(value, bool) or not isinstance(value, (int, Fraction, str)):
29
+ _fail("invalid_numeric_type", "Use int, Fraction or an exact numeric string")
30
+ try:
31
+ return Fraction(value)
32
+ except (ValueError, ZeroDivisionError, TypeError):
33
+ _fail("invalid_numeric_value", str(value))
34
+
35
+
36
+ def _expr(value):
37
+ if isinstance(value, str) and value.isidentifier():
38
+ return value
39
+ if isinstance(value, (list, tuple)):
40
+ if len(value) != 3 or value[0] not in ("add", "sub", "mul"):
41
+ _fail("unsupported_expression", "Input equations support binary add/sub/mul")
42
+ return (value[0], _expr(value[1]), _expr(value[2]))
43
+ return _number(value)
44
+
45
+
46
+ def _free(expr):
47
+ if isinstance(expr, Fraction):
48
+ return set()
49
+ if isinstance(expr, str):
50
+ return {expr}
51
+ return _free(expr[1]) | _free(expr[2])
52
+
53
+
54
+ def _calc(expr):
55
+ if isinstance(expr, Fraction):
56
+ return expr
57
+ op, left, right = expr
58
+ a, b = _calc(left), _calc(right)
59
+ if op == "add":
60
+ return a + b
61
+ if op == "sub":
62
+ return a - b
63
+ if op == "mul":
64
+ return a * b
65
+ if b == 0:
66
+ _fail("division_by_zero", status=INCONSISTENT)
67
+ return a / b
68
+
69
+
70
+ def _prefix(expr):
71
+ if isinstance(expr, Fraction):
72
+ if expr.denominator == 1:
73
+ return str(expr.numerator)
74
+ return f"除 {expr.numerator} {expr.denominator}"
75
+ if isinstance(expr, str):
76
+ return expr
77
+ return f"{OPS[expr[0]]} {_prefix(expr[1])} {_prefix(expr[2])}"
78
+
79
+
80
+ def _read_prefix(text):
81
+ if not isinstance(text, str) or not text.strip():
82
+ _fail("invalid_prefix", "Expected a nonempty arithmetic prefix string")
83
+ tokens, position = text.split(), 0
84
+ operators = {v: k for k, v in OPS.items()}
85
+
86
+ def read():
87
+ nonlocal position
88
+ if position == len(tokens):
89
+ _fail("invalid_prefix", "Incomplete expression")
90
+ token = tokens[position]
91
+ position += 1
92
+ if token in operators:
93
+ return (operators[token], read(), read())
94
+ return _number(token)
95
+
96
+ result = read()
97
+ if position != len(tokens):
98
+ _fail("invalid_prefix", "Unconsumed tokens")
99
+ return result
100
+
101
+
102
+ def solve(equations, known, query, *, prefixes=None):
103
+ """Solve pre-bound add/sub/mul constraints through ordered backend files.
104
+
105
+ Equations are [{"left": expr, "right": expr}]. Expr is a variable name,
106
+ exact number, or [operator, expr, expr]. The query may be an expression.
107
+ The single-unknown backend preserves known-value conversion prefixes.
108
+ The exact-linear backend returns an equivalent evaluation prefix after
109
+ coefficient normalization; complete normalized input provenance and row
110
+ combination certificates are retained in its proof, not necessarily in
111
+ the final prefix. Its success requires a unique full-system solution.
112
+ Every remaining constraint must be resolved before an 'ok' is returned.
113
+ """
114
+ if not isinstance(equations, (list, tuple)) or not equations:
115
+ _fail("invalid_equations", "A nonempty equation list is required")
116
+ parsed = []
117
+ for row in equations:
118
+ if not isinstance(row, dict) or set(row) != {"left", "right"}:
119
+ _fail("invalid_equation_fields", "Use exactly left and right")
120
+ parsed.append((_expr(row["left"]), _expr(row["right"])))
121
+ requested = _expr(query)
122
+ variables = set().union(*(_free(a) | _free(b) for a, b in parsed))
123
+ if not isinstance(known, dict):
124
+ _fail("invalid_known", "Expected a mapping")
125
+ if any(not isinstance(k, str) or not k.isidentifier() for k in known):
126
+ _fail("invalid_known_variable")
127
+ if set(known) - variables:
128
+ _fail("unknown_known_variable", ",".join(sorted(set(known) - variables)))
129
+ values = {key: _number(value) for key, value in known.items()}
130
+ if prefixes is not None:
131
+ if not isinstance(prefixes, dict) or set(prefixes) - set(values):
132
+ _fail("invalid_prefix_roles", "Prefixes must refer to known quantities")
133
+ for key, text in prefixes.items():
134
+ expression = _read_prefix(text)
135
+ if _calc(expression) != values[key]:
136
+ _fail("prefix_value_mismatch", key, INCONSISTENT)
137
+ values[key] = expression
138
+ ctx = {"Fraction": Fraction, "Refusal": Refusal,
139
+ "insufficient": INSUFFICIENT, "inconsistent": INCONSISTENT,
140
+ "unsupported": UNSUPPORTED, "free": _free, "calc": _calc,
141
+ "prefix": _prefix}
142
+ for backend in BACKENDS:
143
+ result = backend.solve(parsed, values, requested, ctx)
144
+ if result is not None:
145
+ return result
146
+ _fail("unresolved_by_single_unknown_solver")
147
+
148
+
149
+ def relate(card, known, query, *, prefixes=None):
150
+ """Apply one comparison card; source/target labels in a card are metadata.
151
+
152
+ known has source/target/quantity numeric roles. query is one of those roles.
153
+ Labels never substitute for known quantities. Units must first be normalized
154
+ through the shared unit module; unsupported extra fields are not discarded.
155
+ """
156
+ if isinstance(card, str):
157
+ kind = card
158
+ elif isinstance(card, dict):
159
+ if "relation" not in card or set(card) - {"relation", "source", "target"}:
160
+ _fail("invalid_relation_card_fields")
161
+ if any(not isinstance(card[k], str) or not card[k].strip()
162
+ for k in ("source", "target") if k in card):
163
+ _fail("invalid_relation_labels")
164
+ kind = card["relation"]
165
+ else:
166
+ _fail("invalid_relation_card")
167
+ if not isinstance(kind, str) or kind not in CARDS:
168
+ _fail("unsupported_relation")
169
+ if not isinstance(known, dict) or set(known) - ROLES:
170
+ _fail("invalid_comparison_roles")
171
+ if not isinstance(query, str) or query not in ROLES:
172
+ _fail("invalid_query_role")
173
+ result = solve([CARDS[kind]], known, query, prefixes=prefixes)
174
+ return {**result, "relation": kind, "query": query}
hs/語法模組/比較/關係卡.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "comparison-cards-v1",
3
+ "origin": {
4
+ "concept": "MathWorld Comparison, section 3.2.3",
5
+ "paper": "https://aclanthology.org/2023.findings-acl.579/",
6
+ "upstream_commit": "345ba75ba83e00ddedfa6cc1bc1048fc5a030ccd",
7
+ "implementation": "視窗ChatGPT 2026-11-25; independently authored adapter"
8
+ },
9
+ "cards": {
10
+ "add": {"left": "target", "right": ["add", "source", "quantity"]},
11
+ "mul": {"left": "target", "right": ["mul", "source", "quantity"]}
12
+ }
13
+ }
hs/語法模組/知識庫/基礎詞.json ADDED
The diff for this file is too large to render. See raw diff
 
hs/語法模組/知識庫/換算.json ADDED
The diff for this file is too large to render. See raw diff
 
hs/語法模組/知識庫/規則登記.json ADDED
The diff for this file is too large to render. See raw diff
 
hs/語法模組/移轉/模組.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Completed, single-owner stock transfers; exact arithmetic is injected.
2
+
3
+ create(comparison.solve).relate(card, known, query, *, prefixes=None)
4
+ validates one before/after frame, selects a data card, and delegates every
5
+ numeric role to the existing solver. It does not parse language, classify
6
+ event phase, replay events, infer unit conversions, or validate another owner.
7
+ """
8
+ import json
9
+ from pathlib import Path
10
+
11
+ from 核心 import Refusal, INSUFFICIENT, INCONSISTENT, UNSUPPORTED, load_strategies
12
+
13
+ HERE = Path(__file__).resolve().parent
14
+ CARDS = json.loads((HERE / "關係卡.json").read_text(encoding="utf-8"))["cards"]
15
+ STRATEGIES = load_strategies(HERE / "策略")
16
+ ROLES = ("before", "after", "quantity")
17
+ ROOT_FIELDS = frozenset(("before", "after", "sender", "recipient", "phase", "evidence"))
18
+ STATE_FIELDS = frozenset(("id", "owner", "entity", "attribute", "unit", "time"))
19
+ STRUCTURE_FIELDS = ("owner", "entity", "attribute", "unit")
20
+
21
+
22
+ def _fail(reason, detail="", status=UNSUPPORTED):
23
+ raise Refusal(reason, detail, status)
24
+
25
+
26
+ def _label(value):
27
+ return isinstance(value, str) and bool(value.strip())
28
+
29
+
30
+ def _validate_card(card):
31
+ if not isinstance(card, dict):
32
+ _fail("invalid_transfer_card")
33
+ if set(card) - ROOT_FIELDS:
34
+ _fail("invalid_transfer_card_fields")
35
+ if "phase" not in card:
36
+ _fail("missing_event_phase", status=INSUFFICIENT)
37
+ if card["phase"] != "completed":
38
+ _fail("unsupported_event_phase", "Caller must supply phase='completed'")
39
+ if "evidence" in card and not isinstance(card["evidence"], str):
40
+ _fail("invalid_evidence", "Evidence must be a string")
41
+
42
+ for role in ("before", "after"):
43
+ state = card.get(role)
44
+ if not isinstance(state, dict):
45
+ _fail("invalid_container", role)
46
+ if set(state) - STATE_FIELDS or not {"id", "owner", "entity"} <= set(state):
47
+ _fail("invalid_container_fields", role)
48
+ if any(not _label(state[key]) for key in ("id", "owner", "entity")):
49
+ _fail("invalid_container_label", role)
50
+ for key in ("attribute", "unit"):
51
+ if state.get(key) is not None and not _label(state[key]):
52
+ _fail("invalid_container_label", f"{role}.{key}")
53
+ if "time" not in state:
54
+ _fail("missing_state_time", role, INSUFFICIENT)
55
+ if isinstance(state["time"], bool) or not isinstance(state["time"], int):
56
+ _fail("invalid_state_time", role)
57
+
58
+ before, after = card["before"], card["after"]
59
+ if before["id"] == after["id"]:
60
+ _fail("same_state_id")
61
+ if before["time"] >= after["time"]:
62
+ _fail("invalid_time_order", "Require before.time < after.time")
63
+ if any(before.get(key) != after.get(key) for key in STRUCTURE_FIELDS):
64
+ _fail("container_structure_mismatch")
65
+
66
+ sender, recipient = card.get("sender"), card.get("recipient")
67
+ if any(value is not None and not _label(value) for value in (sender, recipient)):
68
+ _fail("invalid_transfer_participant")
69
+ if sender is None and recipient is None:
70
+ _fail("missing_transfer_participant")
71
+ if sender is not None and sender == recipient:
72
+ _fail("self_transfer_unsupported")
73
+ if before["owner"] not in (sender, recipient):
74
+ _fail("owner_not_participant")
75
+
76
+
77
+ class _TransferAPI:
78
+ def __init__(self, solve):
79
+ self._solve = solve
80
+
81
+ def relate(self, card, known, query, *, prefixes=None):
82
+ """Validate one completed, nonnegative stock transfer.
83
+
84
+ known/query use before, after, quantity. At least two numeric roles
85
+ must be supplied. All values already use the card's common unit.
86
+ prefixes are delegated unchanged to comparison.solve for full parsing
87
+ and exact value checking. A success validates only this owner's frame.
88
+ """
89
+ _validate_card(card)
90
+ if not isinstance(known, dict) or set(known) - set(ROLES):
91
+ _fail("invalid_transfer_roles")
92
+ if not isinstance(query, str) or query not in ROLES:
93
+ _fail("invalid_query_role")
94
+ if len(known) < 2:
95
+ _fail("insufficient_transfer_values", "Supply at least two roles", INSUFFICIENT)
96
+
97
+ selected = None
98
+ ctx = {"cards": CARDS}
99
+ for strategy in STRATEGIES:
100
+ selected = strategy.build(card, ctx)
101
+ if selected is not None:
102
+ break
103
+ if selected is None:
104
+ _fail("unsupported_transfer_direction")
105
+
106
+ # Reuse the public solver for every role. This avoids duplicating its
107
+ # numeric/prefix parser and catches negative hidden values even when
108
+ # the requested role was already known and nonnegative.
109
+ resolved = {}
110
+ for role in ROLES:
111
+ result = self._solve([selected["equation"]], known, role, prefixes=prefixes)
112
+ if result["value"] < 0:
113
+ reason = "negative_transfer_quantity" if role == "quantity" else "negative_stock"
114
+ _fail(reason, role, INCONSISTENT)
115
+ resolved[role] = result
116
+ answer = {**resolved[query], "relation": "transfer",
117
+ "direction": selected["direction"], "query": query}
118
+ if "evidence" in card:
119
+ answer["evidence"] = card["evidence"]
120
+ return answer
121
+
122
+
123
+ def create(solve):
124
+ """Return an isolated API object bound to an existing comparison.solve."""
125
+ if not callable(solve):
126
+ _fail("invalid_solver_dependency")
127
+ return _TransferAPI(solve)