Spaces:
Running on Zero

Bigbearbo commited on
Commit
2acc5b8
·
verified ·
1 Parent(s): f78a0d0

Add 回饋修正 switch (#350 v1, default off): program points out bad lines, the same Qwen3-8B rewrites them (1 round)

Browse files
app.py CHANGED
@@ -103,6 +103,19 @@ def trace_md(r, ref):
103
  s += [f"### 讀法修補 Reading repair (#350): {'、'.join(rp['動作'])}",
104
  f"修補前拒因 before: {rp['修補前拒因']}", "修補前資訊句 before:", _code(r.get("lines_before_repair") or []),
105
  "證據 evidence:", _code(rp["證據"])]
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  s += ["### 耗時 Seconds", "\n".join(["| 階段 stage | 秒 s |", "|---|---|"]
107
  + [f"| {k} | {v} |" for k, v in r["seconds"].items()])]
108
  s += ["### 1. 斷句 Sentences", _code([f"#{i} {x}" for i, x in enumerate(r["sentences"], 1)]),
@@ -146,12 +159,16 @@ def answer_text(r, ref):
146
  return "\n".join(lines)
147
 
148
 
149
- def solve(question):
 
 
 
150
  q = " ".join((question or "").split())
151
  hit = BY_Q.get(q)
152
  ref = hit[0] if hit else None
153
  _lb_ready.wait(timeout=90)
154
- r = pipeline.solve(q, generate, _LB["fn"], gold=ref["gold"] if ref else None, pid=ref["id"] if ref else "user")
 
155
  if _LB["fn"] is None and r["lb_steps"]:
156
  r["lb_steps"] = r["lb_steps"] + [f"(左腦沒載入:{_LB['err'] or 'still loading'};以上都由 Python 分數計算)"]
157
  return answer_text(r, ref), trace_md(r, ref), ""
@@ -165,19 +182,21 @@ def _short(r):
165
  return f"[{r['layer_label'] or '-'}] {a}"
166
 
167
 
168
- def solve_vary(question):
169
  """🔀 換數字再讀: read the question as is, then a copy with new Arabic integers (word numbers unchanged)."""
170
  q = " ".join((question or "").split())
171
  hit = BY_Q.get(q)
172
  ref = hit[0] if hit else None
173
  v = pipeline.variant(q, ref["deepseek_v7_lines"] if ref else None, random.Random())
174
  _lb_ready.wait(timeout=90)
175
- r1 = pipeline.solve(q, generate, _LB["fn"], gold=ref["gold"] if ref else None, pid=ref["id"] if ref else "user")
 
176
  if not v["question"]:
177
  msg = (f"換數字失敗(試 {v['tries']} 次):{v['why']}\n只讀了原題 {_short(r1)}"
178
  + (f",判分 {_MARK[r1['verdict']]}(標答 {ref['gold']})" if ref else ""))
179
  return msg, trace_md(r1, ref), ""
180
- r2 = pipeline.solve(v["question"], generate, _LB["fn"], gold=v["gold"], pid=(ref["id"] + "-a") if ref else "user-a")
 
181
  mp = "、".join(f"{pipeline._fs(a)}→{pipeline._fs(b)}" for a, b in v["map"].items())
182
  if ref:
183
  head = f"原題 {_MARK[r1['verdict']]}|換數字 {_MARK[r2['verdict']]}"
@@ -214,6 +233,9 @@ NOTES = f"""
214
  - **第二層 模型讀題**:程式讀不出才交 Qwen3-8B;一讀被擋下時再試 #350 讀法修補器(預設開 R1 缺單位補位、R3 引用對齊;R2、R4 關),
215
  所有成功的修補候選答案相同才放行,不新增原文沒有的數字或角色。回答框標「模型讀題(已修補 R?)」或「(未修補)」。
216
  **模型層要換數字還對才算**(模型可能看過 GSM8K train)。
 
 
 
217
  - Layer 1 rule-tree reader covers only {RULE_N} of 7,066 GSM8K-train dev questions today and grows with each rule; layer 2
218
  (Qwen3-8B + #350 repair) only counts if it still reads correctly with new numbers.
219
 
@@ -254,6 +276,7 @@ with gr.Blocks(title="Word-problem reader") as demo:
254
  dice = gr.Button("🎲 隨機出題 Random question", scale=1)
255
  go = gr.Button("送出 Solve", variant="primary", scale=1)
256
  vary = gr.Button("🔀 換數字再讀 New numbers", scale=1)
 
257
  picked = gr.Markdown("")
258
  with gr.Accordion("跑的過程 Pipeline trace", open=True):
259
  with gr.Row():
@@ -262,8 +285,8 @@ with gr.Blocks(title="Word-problem reader") as demo:
262
  gr.Markdown(NOTES)
263
 
264
  dice.click(random_question, inputs=kind, outputs=[question, picked, answer], api_name="random")
265
- go.click(solve, inputs=question, outputs=[answer, trace, trace2], api_name="solve")
266
- vary.click(solve_vary, inputs=question, outputs=[answer, trace, trace2], api_name="vary")
267
- question.submit(solve, inputs=question, outputs=[answer, trace, trace2], api_name=False)
268
 
269
  demo.queue(default_concurrency_limit=1).launch(show_error=True)
 
103
  s += [f"### 讀法修補 Reading repair (#350): {'、'.join(rp['動作'])}",
104
  f"修補前拒因 before: {rp['修補前拒因']}", "修補前資訊句 before:", _code(r.get("lines_before_repair") or []),
105
  "證據 evidence:", _code(rp["證據"])]
106
+ fb = r.get("feedback")
107
+ if fb:
108
+ s += ["### 🔧 回饋修正 Feedback correction (#350 v1, same Qwen3-8B)" + ("(成功)" if fb["status"] == "ok" else "(仍拒答)")]
109
+ if fb.get("錯誤"):
110
+ s += [f"錯誤 error: {fb['錯誤']}"]
111
+ if not fb["rounds"]:
112
+ s += ["(沒有進行:程式產生不出指正,或一讀前的修補已通過)"]
113
+ for h in fb["rounds"]:
114
+ s += [f"第 {h['回合']} 回合 round {h['回合']} 程式指正原文 program's feedback:", _code(h["指正"].split("\n")),
115
+ "模型改後的行 model's rewritten lines:", _code((h["模型改後"] or "(empty)").split("\n")),
116
+ f"→ {'答 ' + str(h['value']) if h['status'] == 'ok' else '拒答:' + str(h['拒答原因'])}"
117
+ + (f"(另經修補 {'、'.join(h['修補'])})" if h.get("修補") else "")
118
+ + (f";丟掉沒被指出的句號的行:{h['越界行']}" if h.get("越界行") else "")]
119
  s += ["### 耗時 Seconds", "\n".join(["| 階段 stage | 秒 s |", "|---|---|"]
120
  + [f"| {k} | {v} |" for k, v in r["seconds"].items()])]
121
  s += ["### 1. 斷句 Sentences", _code([f"#{i} {x}" for i, x in enumerate(r["sentences"], 1)]),
 
159
  return "\n".join(lines)
160
 
161
 
162
+ FEEDBACK_ROUNDS = 1
163
+
164
+
165
+ def solve(question, feedback=False):
166
  q = " ".join((question or "").split())
167
  hit = BY_Q.get(q)
168
  ref = hit[0] if hit else None
169
  _lb_ready.wait(timeout=90)
170
+ r = pipeline.solve(q, generate, _LB["fn"], gold=ref["gold"] if ref else None, pid=ref["id"] if ref else "user",
171
+ feedback=bool(feedback), rounds=FEEDBACK_ROUNDS)
172
  if _LB["fn"] is None and r["lb_steps"]:
173
  r["lb_steps"] = r["lb_steps"] + [f"(左腦沒載入:{_LB['err'] or 'still loading'};以上都由 Python 分數計算)"]
174
  return answer_text(r, ref), trace_md(r, ref), ""
 
182
  return f"[{r['layer_label'] or '-'}] {a}"
183
 
184
 
185
+ def solve_vary(question, feedback=False):
186
  """🔀 換數字再讀: read the question as is, then a copy with new Arabic integers (word numbers unchanged)."""
187
  q = " ".join((question or "").split())
188
  hit = BY_Q.get(q)
189
  ref = hit[0] if hit else None
190
  v = pipeline.variant(q, ref["deepseek_v7_lines"] if ref else None, random.Random())
191
  _lb_ready.wait(timeout=90)
192
+ fbk = dict(feedback=bool(feedback), rounds=FEEDBACK_ROUNDS)
193
+ r1 = pipeline.solve(q, generate, _LB["fn"], gold=ref["gold"] if ref else None, pid=ref["id"] if ref else "user", **fbk)
194
  if not v["question"]:
195
  msg = (f"換數字失敗(試 {v['tries']} 次):{v['why']}\n只讀了原題 {_short(r1)}"
196
  + (f",判分 {_MARK[r1['verdict']]}(標答 {ref['gold']})" if ref else ""))
197
  return msg, trace_md(r1, ref), ""
198
+ r2 = pipeline.solve(v["question"], generate, _LB["fn"], gold=v["gold"], pid=(ref["id"] + "-a") if ref else "user-a",
199
+ **fbk)
200
  mp = "、".join(f"{pipeline._fs(a)}→{pipeline._fs(b)}" for a, b in v["map"].items())
201
  if ref:
202
  head = f"原題 {_MARK[r1['verdict']]}|換數字 {_MARK[r2['verdict']]}"
 
233
  - **第二層 模型讀題**:程式讀不出才交 Qwen3-8B;一讀被擋下時再試 #350 讀法修補器(預設開 R1 缺單位補位、R3 引用對齊;R2、R4 關),
234
  所有成功的修補候選答案相同才放行,不新增原文沒有的數字或角色。回答框標「模型讀題(已修補 R?)」或「(未修補)」。
235
  **模型層要換數字還對才算**(模型可能看過 GSM8K train)。
236
+ - **🔧 回饋修正(#350 v1,開關,預設關)**:修補後仍拒答時,程式指出哪幾句有問題(句號+原文+那句的行+問題+該詞格式),
237
+ 請**同一個 Qwen3-8B** 只重寫那幾句(來回 1 次);改完重跑全部守門,其他句號的行一律丟掉。團隊量測(修正模型是另一個免費模型 GLM-5.3-flash,不是這裡的 Qwen):
238
+ 救 16/新錯 5,換數字 41 件 對 13/錯 0;Qwen 當修正模型的開/關對照還沒量,量完淨正才會改成預設開。開了會多一次 GPU 呼叫。
239
  - Layer 1 rule-tree reader covers only {RULE_N} of 7,066 GSM8K-train dev questions today and grows with each rule; layer 2
240
  (Qwen3-8B + #350 repair) only counts if it still reads correctly with new numbers.
241
 
 
276
  dice = gr.Button("🎲 隨機出題 Random question", scale=1)
277
  go = gr.Button("送出 Solve", variant="primary", scale=1)
278
  vary = gr.Button("🔀 換數字再讀 New numbers", scale=1)
279
+ fbk = gr.Checkbox(value=False, label="🔧 程式指正後讓模型再改一次 Let the model fix the lines the program points out (1 round)")
280
  picked = gr.Markdown("")
281
  with gr.Accordion("跑的過程 Pipeline trace", open=True):
282
  with gr.Row():
 
285
  gr.Markdown(NOTES)
286
 
287
  dice.click(random_question, inputs=kind, outputs=[question, picked, answer], api_name="random")
288
+ go.click(solve, inputs=[question, fbk], outputs=[answer, trace, trace2], api_name="solve")
289
+ vary.click(solve_vary, inputs=[question, fbk], outputs=[answer, trace, trace2], api_name="vary")
290
+ question.submit(solve, inputs=[question, fbk], outputs=[answer, trace, trace2], api_name=False)
291
 
292
  demo.queue(default_concurrency_limit=1).launch(show_error=True)
hs/語法模組/資訊句/回饋修正.py ADDED
@@ -0,0 +1,655 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""回饋修正 v0(#350 v1,Claude子代理(#350 讀法修補器)2026-11-27)。
2
+
3
+ 使用者 11-27 08:35:「先補一個簡單功能,程式對可能填錯的部分指出來,請小模型修正,可以設定來回次數」。
4
+ 流程:模型讀法 → build(全部守門)+程式腦+答案層守門 →(讀法修補 R1、R3 先修,照 _REPAIR_FORCE 預設)→ 仍拒 →
5
+ 程式產生「具體指正」:哪一句(#n+原文)、那句寫了哪些資訊句、什麼問題(拒因翻成英文白話)、基本概念表該詞的正確格式
6
+ (讀題提示 v7 的概念行)。只送有問題的那幾句給小模型,請它只重寫那幾句;改完重跑全部守門;最多 來回次數 回合。
7
+ 守門不放鬆:模型回的行只收被指出的句號(其他句號的行丟掉並記錄);改後的數字照 build 守門必須在該句原文;
8
+ 一回合通過(ok)就停,記每回合答案。不改 讀題_LLM.py/解析.py/程式腦.py/讀法修補.py。
9
+
10
+ import 回饋修正 as F; F.setup()
11
+ F.回饋修正(sents, [(句號, 行)], 來回次數=None, 模型=None) # 來回次數 None=團隊參數「回饋修正來回次數」(預設 2)
12
+ 模型:"nvidia:z-ai/glm-5.3-flash"(預設,免費池 NIM)/"groq"/"google"/"zerogpu",或傳一個 函式(prompt)->str
13
+
14
+ 量測:python -B -X utf8 回饋修正.py 量 [--A題 300] [--上限 1200] [--並行 6]
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import concurrent.futures as cf
19
+ import json
20
+ import random
21
+ import re
22
+ import sys
23
+ import threading
24
+ import time
25
+ from collections import Counter
26
+ from fractions import Fraction
27
+ from pathlib import Path
28
+
29
+ HERE = Path(__file__).resolve().parent
30
+ sys.path.insert(0, str(HERE))
31
+ sys.path.insert(0, r"H:\Agent共用\專案\團隊系統")
32
+ import 讀法修補 as M # noqa: E402
33
+
34
+ WHO = "Claude子代理(#350 回饋修正)"
35
+ OUTD = HERE / "讀法修補" / "回饋修正"
36
+ 預設模型 = "nvidia:z-ai/glm-5.3-flash"
37
+ S = R = B = None
38
+ _lk = threading.Lock()
39
+ 呼叫 = {"次": 0, "上限": None, "失敗": 0, "依模型": Counter()}
40
+
41
+
42
+ def setup():
43
+ global S, R, B
44
+ M.setup()
45
+ S, R, B = M.S, M.R, M.B
46
+ R.use_prompt("v7")
47
+ return S
48
+
49
+
50
+ def 來回次數預設():
51
+ try:
52
+ import 團隊參數
53
+ return int(團隊參數.get("回饋修正來回次數", 2))
54
+ except Exception:
55
+ return 2
56
+
57
+
58
+ # ------------------------------------------------------------------ 模型
59
+ class 超過上限(RuntimeError):
60
+ pass
61
+
62
+
63
+ def 叫模型(prompt, 模型=None, max_tokens=1600):
64
+ 模型 = 模型 or 預設模型
65
+ if callable(模型):
66
+ return 模型(prompt)
67
+ with _lk:
68
+ if 呼叫["上限"] is not None and 呼叫["次"] >= 呼叫["上限"]:
69
+ raise 超過上限("呼叫數到上限")
70
+ 呼叫["次"] += 1
71
+ 呼叫["依模型"][模型] += 1
72
+ try:
73
+ if 模型 == "zerogpu":
74
+ sys.path.insert(0, r"H:\Agent共用\專案\團隊系統\ZeroGPU")
75
+ import zerogpu
76
+ outs, _ = zerogpu.ask_batch([prompt], max_tokens)
77
+ t = outs[0] or ""
78
+ else:
79
+ sys.path.insert(0, r"H:\Agent共用\ai-call")
80
+ import 免費AI池 as pool
81
+ name, _, model = 模型.partition(":")
82
+ t = ""
83
+ for k in range(2):
84
+ try:
85
+ t = pool.ask(name, prompt, model=model or None, max_tokens=max_tokens, timeout=150)
86
+ break
87
+ except Exception as e:
88
+ if k == 1 or getattr(e, "code", None) not in (429, 500, 502, 503, None):
89
+ raise
90
+ time.sleep(8)
91
+ except 超過上限:
92
+ raise
93
+ except Exception:
94
+ with _lk:
95
+ 呼叫["失敗"] += 1
96
+ return ""
97
+ return re.sub(r"<think>.*?</think>", "", t or "", flags=re.S).strip()
98
+
99
+
100
+ # ------------------------------------------------------------------ 指正
101
+ 概念英 = R_EN = None
102
+
103
+
104
+ def _概念詞(body):
105
+ return re.findall(r"\b([a-z]+)\(", body or "")
106
+
107
+
108
+ def _格式(bodies):
109
+ out = []
110
+ for w in dict.fromkeys(w for b in bodies for w in _概念詞(b)):
111
+ h = R._concept_hint(w)
112
+ if h:
113
+ out.append(h)
114
+ return out
115
+
116
+
117
+ def _ascii(t):
118
+ """拒因裡的中文對英文層模型沒用:只留 ASCII(名字、數字、單位)。"""
119
+ return re.sub(r"\s+", " ", re.sub(r"[^\x00-\x7f]+", " ", t or "")).strip()
120
+
121
+
122
+ def 指正(sents, lines, e, rows):
123
+ """回 [{n, 原文, 行, 問題}]:每句一筆(同句多問題合併)。e=評的結果(含拒答原因),rows=build 的逐行紀錄。"""
124
+ items = {}
125
+
126
+ def add(n, why):
127
+ if not isinstance(n, int) or not 1 <= n <= len(sents):
128
+ return
129
+ d = items.setdefault(n, {"n": n, "原文": sents[n - 1], "行": [b for m, b in lines if m == n], "問題": []})
130
+ if why not in d["問題"]:
131
+ d["問題"].append(why)
132
+ ask_n = next((n for n, b in reversed(lines) if b.lstrip().startswith("ask(")), len(sents))
133
+ for r in rows or []:
134
+ g = str(r.get("守門") or "")
135
+ n = r.get("n")
136
+ if not g:
137
+ continue
138
+ if g.startswith("數字無出處"):
139
+ add(n, f"the number(s) {g.split(':', 1)[-1]} in your line do not appear in this sentence. Use only numbers written in "
140
+ f"the sentence; if a unit change is needed, keep the sentence's number and unit (e.g. 1 hour stays "
141
+ f"duration(x, act, 1, hour)) and let the program convert, or write convert(1, hour, minute)")
142
+ elif g.startswith("格式"):
143
+ add(n, f"the line could not be parsed ({g.split(':', 1)[-1][:120]}); check the number of arguments against the format below")
144
+ elif g.startswith("純字面運算"):
145
+ add(n, "do not do arithmetic on the sentence's numbers yourself (e.g. mul(2, 3)); write each fact with its own number")
146
+ elif g.startswith("數字與單位不符"):
147
+ add(n, f"a number is bound to the wrong unit ({g.split(':', 1)[-1]}); keep each number with the word next to it")
148
+ elif g.startswith(("角色無出處", "引用的角色無出處")):
149
+ add(n, "the owner/name in your line is not mentioned in this sentence or earlier; use the name from the text")
150
+ elif g.startswith("skip"):
151
+ add(n, "you wrote skip but the sentence has a number; write the fact")
152
+ elif g.startswith("漏寫"):
153
+ add(n, "this sentence has a number but you wrote no line for it")
154
+ why = str(e.get("拒答原因") or "")
155
+ if items: # 先修被守門擋下的行:程式腦的拒因(指代找不到、未讀跟所求有關…)多半是它們的連帶結果
156
+ why = ""
157
+ bad_rows = {(r.get("n"), r.get("行")) for r in rows or [] if r.get("守門")}
158
+ if why.startswith("有字面數沒用到"):
159
+ nums = re.findall(r"-?\d+(?:/\d+)?", why.split(":", 1)[-1])
160
+ for x in nums[:3]:
161
+ hit = [n for n, b in lines if re.search(rf"(?<![\d/]){re.escape(x.lstrip('-'))}(?![\d/])", b)]
162
+ for n in hit[:2]:
163
+ add(n, f"the number {x.lstrip('-')} is written here but the question's ask does not use it; check whether this "
164
+ f"fact is linked to the asked amount (same owner/item names as in the ask)")
165
+ add(ask_n, f"the ask does not use {', '.join(n.lstrip('-') for n in nums[:3])}; make the ask refer to the facts that hold them")
166
+ elif why.startswith("未讀跟所求有關"):
167
+ t = why.split(":", 1)[-1].strip()
168
+ hit = [k for k, s in enumerate(sents, 1) if s.strip() == t or (t and t[:40] in s)]
169
+ for n in hit[:1]:
170
+ add(n, "this sentence was not read into a usable fact, but the question needs its amount; write it as a fact")
171
+ elif why.startswith("沒有問題句"):
172
+ add(ask_n if ask_n <= len(sents) else len(sents),
173
+ "there is no valid ask line for the question; write ask(...) for what is asked, using only numbers in that sentence "
174
+ "(usually none: refer to the facts with ? instead)")
175
+ elif why.startswith(("指代找不到", "指代不唯一", "找不到量", "換算單位不符", "單位不符", "資料不足", "缺值")):
176
+ facts = [b for n, b in lines if not b.lstrip().startswith(("ask(", "unread(")) and (n, b.strip().strip("`")) not in bad_rows]
177
+ msg = {"指代找不到": "the ask refers to an amount that no fact line has",
178
+ "指代不唯一": "the ask refers to an amount that matches more than one fact line",
179
+ "找不到量": "the ask needs an amount (owner/item) that no fact gives",
180
+ "換算單位不符": "convert(...) is applied to an amount whose unit is not the from-unit",
181
+ "單位不符": "the units in the ask do not match",
182
+ "資料不足": "the asked amount is not connected to any fact",
183
+ "缺值": "a referenced fact has no value"}
184
+ k = next(x for x in msg if why.startswith(x))
185
+ det = _ascii(why.split(":", 1)[-1])[:120]
186
+ add(ask_n, f"{msg[k]} ({det}). Refer to facts exactly as written: same predicate "
187
+ f"(e.g. duration(...) for a duration fact, have(...) for a have fact), same owner and item, with ?. "
188
+ f"Fact lines now: {' | '.join(facts)[:600]}")
189
+ elif why.startswith("解題器"):
190
+ det = _ascii(why)[:80]
191
+ add(ask_n, f"the facts are not enough or contradict each other ({det}); check each sentence's amount is written "
192
+ f"once, with the right owner/item and time (start/now), and that the ask uses those names")
193
+ elif why and not items:
194
+ add(ask_n, f"the program could not compute the ask ({_ascii(why)[:160]}); check that the ask refers to the facts by "
195
+ f"the same predicate, owner and item")
196
+ return [items[k] for k in sorted(items)]
197
+
198
+
199
+ def _概念表():
200
+ p = R.PROMPTS["A"]
201
+ i = p.find("Concepts (")
202
+ j = p.find("\n\n", i + 20)
203
+ return p[i:j if j > 0 else i + 4000]
204
+
205
+
206
+ def 指正文字(sents, lines, items):
207
+ ctx = "\n".join(f"#{k}: {s}" for k, s in enumerate(sents, 1))
208
+ cur = "\n".join(f"#{n}: {b}" for n, b in lines)
209
+ fl = []
210
+ for d in items:
211
+ fmt = _格式(d["行"])
212
+ fl.append(f"Sentence #{d['n']}: \"{d['原文']}\"\n your line(s): " + (" | ".join(d["行"]) or "(none)") +
213
+ "\n problem: " + " ; ".join(d["問題"]) + ("\n formats: " + " ; ".join(fmt) if fmt else ""))
214
+ ns = ", ".join(f"#{d['n']}" for d in items)
215
+ return (f"You wrote info sentences (a small predicate language) for a math word problem. A program checked them and "
216
+ f"found problems in {ns}. Rewrite ONLY the lines of {ns}. Keep every other line as it is (do not output them).\n\n"
217
+ f"{_概念表()}\n\nProblem sentences:\n{ctx}\n\nAll your current lines:\n{cur}\n\nProblems found:\n" + "\n".join(fl) +
218
+ f"\n\nRules: use only numbers written in that sentence; do not compute anything yourself; refer to other facts "
219
+ f"with ?. Output only the corrected lines, one per line, as #n: line (n in {ns}). No explanations.")
220
+
221
+
222
+ _LINE = re.compile(r"^\s*#\s*(\d+)\s*[::]\s*(.+?)\s*$")
223
+
224
+
225
+ def 套回(lines, reply, ns):
226
+ """模型回覆 → 新 lines:被指出的句號換成模型的行;其他句號的行丟掉(記在 越界)。"""
227
+ got, extra = {}, []
228
+ for x in (reply or "").splitlines():
229
+ m = _LINE.match(x.strip().strip("`"))
230
+ if not m:
231
+ continue
232
+ n, b = int(m.group(1)), m.group(2).strip().strip("`")
233
+ if n in ns:
234
+ got.setdefault(n, []).append(b if b.endswith(".") else b + ".")
235
+ else:
236
+ extra.append(f"#{n}: {b}")
237
+ if not got:
238
+ return None, extra
239
+ out, done = [], set()
240
+ for n, b in lines:
241
+ if n in got:
242
+ if n not in done:
243
+ out += [(n, x) for x in got[n]]
244
+ done.add(n)
245
+ else:
246
+ out.append((n, b))
247
+ for n in sorted(set(got) - done): # 原本沒寫過行的句子:插在句號順序位置
248
+ k = next((i for i, (m, _) in enumerate(out) if m > n), len(out))
249
+ out[k:k] = [(n, x) for x in got[n]]
250
+ return out, extra
251
+
252
+
253
+ def _評全(sents, lines):
254
+ """build 全部守門 → evaluate;被擋下再走讀法修補(R1/R3 預設)。回 (結果, rows, 修補證據)。"""
255
+ reply = "\n".join(f"#{n}: {b}" for n, b in lines)
256
+ try:
257
+ objs, rows = R.build(sents, reply)
258
+ e = S.evaluate(sents, objs)
259
+ except RecursionError:
260
+ return {"status": "refused", "value": None, "拒答原因": "例外:解析遞迴", "lines": []}, [], None
261
+ fix = None
262
+ if e["status"] != "ok":
263
+ r = M.修補(sents, lines)
264
+ if r["status"] == "ok":
265
+ fix = r["修補"]
266
+ e = {"status": "ok", "value": r["value"], "拒答原因": None, "lines": fix.get("資訊句") or [], "objs": []}
267
+ return e, rows, fix
268
+
269
+
270
+ def 回饋修正(sents, lines, 來回次數=None, 模型=None):
271
+ N = 來回次數預設() if 來回次數 is None else 來回次數
272
+ lines = [(int(n), b) for n, b in lines if b]
273
+ e, rows, fix = _評全(sents, lines)
274
+ hist = [{"回合": 0, "status": e["status"], "value": e.get("value"), "拒答原因": e.get("拒答原因"), "修補": fix,
275
+ "lines": lines}]
276
+ cur = lines
277
+ for k in range(1, N + 1):
278
+ if e["status"] == "ok":
279
+ break
280
+ items = 指正(sents, cur, e, rows)
281
+ if not items:
282
+ hist.append({"回合": k, "status": "refused", "拒答原因": "產生不出指正", "停": True})
283
+ break
284
+ prompt = 指正文字(sents, cur, items)
285
+ reply = 叫模型(prompt, 模型)
286
+ if not (reply or "").strip() and not callable(模型): # 空回覆(思考吃光 token 等):同回合重叫一次
287
+ reply = 叫模型(prompt, 模型)
288
+ new, extra = 套回(cur, reply, {d["n"] for d in items})
289
+ h = {"回合": k, "指正": items, "提示字數": len(prompt), "回覆": reply, "越界行": extra}
290
+ if new is None:
291
+ h.update(status="refused", value=None, 拒答原因="模型沒回可用的行(" + (e.get("拒答原因") or "") + ")", lines=cur)
292
+ hist.append(h)
293
+ continue
294
+ cur = new
295
+ e, rows, fix = _評全(sents, cur)
296
+ h.update(status=e["status"], value=e.get("value"), 拒答原因=e.get("拒答原因"), 修補=fix, lines=cur)
297
+ hist.append(h)
298
+ last_ok = next((h for h in reversed(hist) if h.get("status") == "ok"), None)
299
+ vals = {str(h["value"]) for h in hist if h.get("status") == "ok"}
300
+ return {"status": "ok" if last_ok else "refused", "value": last_ok["value"] if last_ok else None,
301
+ "回合": hist, "用到回合": last_ok["回合"] if last_ok else None, "答值不一致": len(vals) > 1}
302
+
303
+
304
+ def 第k回合(res, k):
305
+ """回饋修正結果截在 N=k:最後一個 回合≤k 的狀態。"""
306
+ hs = [h for h in res["回合"] if h["回合"] <= k]
307
+ h = hs[-1]
308
+ return (h.get("status"), h.get("value")) if h.get("status") == "ok" else ("refused", None)
309
+
310
+
311
+ # ------------------------------------------------------------------ 換數字(變形題 a 型的程式版:只換阿拉伯整數,照參考讀法重算標答)
312
+ _NUM = re.compile(r"\d+\s*/\s*\d+|\d[\d,]*(?:\.\d+)?")
313
+ _INT = re.compile(r"(?<![\w.:/,-])(?:\d{1,3}(?:,\d{3})+|\d+)(?!(?:st|nd|rd|th)\b|[\d:/]|[.,]\d)")
314
+
315
+
316
+ def _fs(n):
317
+ return str(n.numerator) if n.denominator == 1 else f"{n.numerator}/{n.denominator}"
318
+
319
+
320
+ def 換數字(q, rng):
321
+ allnums = set()
322
+ for m in _NUM.findall(q):
323
+ try:
324
+ allnums.add(Fraction(m.replace(",", "").replace(" ", "").rstrip(".")))
325
+ except (ValueError, ZeroDivisionError):
326
+ pass
327
+ mp = {}
328
+ for m in _INT.finditer(q):
329
+ v = Fraction(m.group(0).replace(",", ""))
330
+ if v in mp:
331
+ continue
332
+ pct = bool(re.match(r"\s*(%|percent)", q[m.end():m.end() + 9], re.I)) and v < 100
333
+ n = int(v)
334
+ for _ in range(50):
335
+ if pct:
336
+ x = rng.choice([y for y in range(5, 100, 5) if y != n])
337
+ elif n <= 10:
338
+ x = rng.randint(2, 12)
339
+ else:
340
+ x = rng.randint(max(2, int(n * 0.5)), int(n * 1.5) + 2)
341
+ if x != n and Fraction(x) not in allnums | set(mp.values()):
342
+ break
343
+ mp[v] = Fraction(x)
344
+ return _INT.sub(lambda m: _fs(mp[Fraction(m.group(0).replace(",", ""))]), q), mp
345
+
346
+
347
+ def 變形(q, ref_lines, rng, tries=5):
348
+ """參考讀法(救回那題最後答對的資訊句,英文式含原文)照同一對位換數 → 程式腦重算新標答。"""
349
+ """失敗回 {"失敗": 原因}。讀法沒用到的原文數(干擾數、讀法寫成別的形式):第一輪全換,換不進讀法就改成「只換讀法用到的數」
350
+ (沒用到的數留原值,不影響標答),記 部分換。"""
351
+ sys.path.insert(0, str(HERE / "變形題"))
352
+ import 變形題工廠 as FAC
353
+ why = Counter()
354
+ for k in range(tries * 2):
355
+ nq, mp = 換數字(q, rng)
356
+ if not mp:
357
+ return {"失敗": "題目沒有可換的阿拉伯整數"}
358
+ part = False
359
+ try:
360
+ objs0 = R.解析.parse(ref_lines)
361
+ objs, used = FAC.sub_objs(objs0, mp)
362
+ if not set(mp) <= used:
363
+ if k < tries:
364
+ why["有數換不進讀法"] += 1
365
+ continue
366
+ keep = {x: y for x, y in mp.items() if x in used}
367
+ if not keep:
368
+ why["讀法沒用到任何可換的數"] += 1
369
+ continue
370
+ mp, part = keep, True
371
+ nq = _INT.sub(lambda m: _fs(mp.get(Fraction(m.group(0).replace(",", "")), Fraction(m.group(0).replace(",", "")))), q)
372
+ objs, used = FAC.sub_objs(objs0, mp)
373
+ r = B.solve(objs)
374
+ except Exception as e:
375
+ why[f"例外 {type(e).__name__}"] += 1
376
+ continue
377
+ if r["status"] != "ok":
378
+ why["程式腦算不出新題"] += 1
379
+ continue
380
+ v = Fraction(r["value"])
381
+ if v.denominator == 1 and v > 0:
382
+ return {"q": nq, "map": {str(x): str(y) for x, y in mp.items()}, "標答": str(v), "部分換": part}
383
+ why["新答案不是正整數"] += 1
384
+ return {"失敗": ";".join(f"{x}×{n}" for x, n in why.most_common())}
385
+
386
+
387
+ def 模型讀題(sents, 模型=None):
388
+ """變形題從零讀(v7 提示+同一個免費模型)。"""
389
+ prompt = R.PROMPTS["A"] + "\n\n" + R.user_msg(sents)
390
+ t = 叫模型(prompt, 模型, max_tokens=1500)
391
+ rows = R.last_attempt(t)
392
+ out = []
393
+ for x in rows:
394
+ m = R.LINE_RE.match(x)
395
+ if m:
396
+ out.append((int(m.group(1)), m.group(2).strip().strip("`")))
397
+ return out, t
398
+
399
+
400
+ # ------------------------------------------------------------------ 量測
401
+ def _載B():
402
+ items = M.量B()
403
+ return {p: (sents, M.從rows(x["rows"]), q) for p, (sents, x, q) in items.items()}
404
+
405
+
406
+ def _載A(n, seed=20261127):
407
+ import pickle
408
+ import 範圍守門
409
+ PR = pickle.loads(S.PKL.read_bytes())
410
+ ids = sorted((p for p, P in PR.items() if 範圍守門.可用(p, P["q"]) and P["基準"]["寬"]["status"] != "ok"),
411
+ key=lambda s: int(s.split("-")[-1]))
412
+ random.Random(seed).shuffle(ids)
413
+ out = {}
414
+ for p in ids:
415
+ P = PR[p]
416
+ for src in ("v7", "v5", "視窗DeepSeek"):
417
+ x = (P["源"].get(src) or {}).get("A")
418
+ if x is not None and S.real(x):
419
+ out[p] = (P["句"], M.從rows(x["rows"]), P["q"], src)
420
+ break
421
+ if len(out) >= n:
422
+ break
423
+ return out
424
+
425
+
426
+ def cmd_量(a):
427
+ setup()
428
+ OUTD.mkdir(parents=True, exist_ok=True)
429
+ 呼叫["上限"] = a.上限
430
+ N = 3
431
+ batches = {"B": _載B(), "A": _載A(a.A題)}
432
+ res = {b: {} for b in batches}
433
+ # 廣度優先:先每題第 0 回合(不叫模型),再���回合全部題目各叫一次,額度留給變形題
434
+ state = {}
435
+ for b, items in batches.items():
436
+ for p, it in items.items():
437
+ sents, lines = it[0], it[1]
438
+ e, rows, fix = _評全(sents, lines)
439
+ state[(b, p)] = {"sents": sents, "cur": lines, "e": e, "rows": rows,
440
+ "hist": [{"回合": 0, "status": e["status"], "value": e.get("value"), "拒答原因": e.get("拒答原因"),
441
+ "修補": fix, "lines": lines}]}
442
+ 保留 = a.變形保留
443
+ # 11-27 修:主量測的硬上限=上限−保留(之前只用題數截 todo,空回重叫一題吃 2 次,第 2 回合吃光保留額度)
444
+ 呼叫["上限"] = a.上限 - 保留
445
+
446
+ def one_round(key, k):
447
+ st = state[key]
448
+ if st["e"]["status"] == "ok" or st.get("停"):
449
+ return
450
+ items = 指正(st["sents"], st["cur"], st["e"], st["rows"])
451
+ if not items:
452
+ st["停"] = True
453
+ st["hist"].append({"回合": k, "status": "refused", "拒答原因": "產生不出指正"})
454
+ return
455
+ prompt = 指正文字(st["sents"], st["cur"], items)
456
+ reply = 叫模型(prompt)
457
+ if not (reply or "").strip():
458
+ reply = 叫模型(prompt)
459
+ new, extra = 套回(st["cur"], reply, {d["n"] for d in items})
460
+ h = {"回合": k, "指正": items, "提示字數": len(prompt), "回覆": reply, "越界行": extra}
461
+ if new is None:
462
+ h.update(status="refused", value=None, 拒答原因="模型沒回可用的行")
463
+ else:
464
+ st["cur"] = new
465
+ st["e"], st["rows"], fix = _評全(st["sents"], new)
466
+ h.update(status=st["e"]["status"], value=st["e"].get("value"), 拒答原因=st["e"].get("拒答原因"), 修補=fix, lines=new)
467
+ st["hist"].append(h)
468
+
469
+ calls_at = {0: 0}
470
+ for k in range(1, N + 1):
471
+ todo = [key for key, st in state.items() if st["e"]["status"] != "ok" and not st.get("停")]
472
+ room = (a.上限 - 保留 - 呼叫["次"]) // 2 # 每題預留 2 次(空回重叫)
473
+ todo = todo[:max(0, room)]
474
+ print(f"回合 {k}:{len(todo)} 題", flush=True)
475
+ with cf.ThreadPoolExecutor(a.並行) as ex:
476
+ list(ex.map(lambda key: _safe(one_round, key, k), todo))
477
+ calls_at[k] = 呼叫["次"]
478
+ print(f" 累計呼叫 {呼叫['次']}(失敗 {呼叫['失敗']})", flush=True)
479
+ # 判分(全部讀完才讀答案)
480
+ gold = S.X.load_gold()
481
+ out = {"作者": WHO, "日期": "2026-11-27", "模型": 預設模型, "批": {}, "累計呼叫": calls_at}
482
+ rescued = []
483
+ for b in batches:
484
+ tab = {}
485
+ for k in range(N + 1):
486
+ c = Counter()
487
+ for (bb, p), st in state.items():
488
+ if bb != b:
489
+ continue
490
+ hs = [h for h in st["hist"] if h["回合"] <= k]
491
+ h = next((x for x in reversed(hs) if x.get("status") == "ok"), None)
492
+ c["對" if h and S.judge(h["value"], gold[p]) == "對" else "錯" if h else "拒"] += 1
493
+ tab[f"N={k}"] = dict(c)
494
+ ids = {}
495
+ for (bb, p), st in state.items():
496
+ if bb != b:
497
+ continue
498
+ j0 = st["hist"][0]
499
+ j0 = S.judge(j0["value"], gold[p]) if j0["status"] == "ok" else "拒"
500
+ h = next((x for x in reversed(st["hist"]) if x.get("status") == "ok"), None)
501
+ jn = S.judge(h["value"], gold[p]) if h else "拒"
502
+ if j0 != jn:
503
+ ids.setdefault(f"{j0}→{jn}", []).append(p)
504
+ if j0 == "拒" and jn == "對" and h["回合"] > 0:
505
+ rescued.append((b, p, h))
506
+ vals = {str(x["value"]) for x in st["hist"] if x.get("status") == "ok"}
507
+ if len(vals) > 1:
508
+ ids.setdefault("回合間答值不一致", []).append(p)
509
+ out["批"][b] = {"題數": len(batches[b]), "每回合": tab, "變化題號": {k: sorted(v) for k, v in ids.items()}}
510
+ # 救回的題:換數字整套重跑(模型重讀+回饋)
511
+ rng = random.Random(20261127)
512
+ var = []
513
+ 呼叫["上限"] = a.上限
514
+ for b, p, h in rescued:
515
+ it = batches[b][p]
516
+ q = it[2]
517
+ ref = _評全(state[(b, p)]["sents"], h["lines"])[0].get("lines") or [] if h.get("lines") else []
518
+ v = 變形(q, ref, rng) if ref else {"失敗": "沒有參考讀法"}
519
+ if "失敗" in v:
520
+ var.append({"批": b, "題號": p, "判": "換不出", "原因": v["失敗"]})
521
+ continue
522
+ try:
523
+ sents2 = R.sentences(v["q"])
524
+ lines2, raw = 模型讀題(sents2)
525
+ r2 = 回饋修正(sents2, lines2, 來回次數=N)
526
+ except 超過上限:
527
+ var.append({"批": b, "題號": p, "判": "額度用完"})
528
+ continue
529
+ j = S.judge(r2["value"], v["標答"]) if r2["status"] == "ok" else "拒"
530
+ var.append({"批": b, "題號": p, "換數字題": v["q"], "對位": v["map"], "��標答": v["標答"], "新答": r2["value"],
531
+ "用到回合": r2["用到回合"], "判": j})
532
+ vc = Counter(x["判"] for x in var)
533
+ out["換數字重跑"] = {"救回題數": len(rescued), "統計": dict(vc),
534
+ "換數字還對比例": f"{vc['對']}/{len(var)}" if var else None, "題": var}
535
+ out["總呼叫"] = 呼叫["次"]
536
+ out["呼叫失敗"] = 呼叫["失敗"]
537
+ # 例子:救回的第一題
538
+ exs = []
539
+ for b, p, h in rescued[:6]:
540
+ st = state[(b, p)]
541
+ fb = next(x for x in st["hist"] if x["回合"] == h["回合"])
542
+ exs.append({"批": b, "題號": p, "原文": batches[b][p][2], "原讀法": [x for _, x in batches[b][p][1]],
543
+ "第0回合拒因": st["hist"][0]["拒答原因"], "程式指正": fb.get("指正"), "模型改後": fb.get("回覆"),
544
+ "程式腦答": h["value"], "標答": gold[p], "判": S.judge(h["value"], gold[p]), "回合": h["回合"]})
545
+ out["例"] = exs
546
+ detail = {f"{b}|{p}": st["hist"] for (b, p), st in state.items() if len(st["hist"]) > 1}
547
+ (OUTD / "逐題.json").write_text(json.dumps(detail, ensure_ascii=False, default=str), encoding="utf-8")
548
+ (OUTD / "result.json").write_text(json.dumps(out, ensure_ascii=False, indent=1, default=str), encoding="utf-8")
549
+ print(json.dumps({k: out[k] for k in ("批", "累計呼叫", "總呼叫")}, ensure_ascii=False, default=str)[:3000])
550
+ print("換數字", out["換數字重跑"]["統計"], out["換數字重跑"]["換數字還對比例"])
551
+
552
+
553
+ def cmd_換數字(a):
554
+ """只做換數字:讀現有 result.json+逐題.json 的救回題,不重跑主量測。每題 a.份 個變形+1 個原題對照,
555
+ 都由同一個模型從零讀(v7 提示)再回饋修正(來回次數=團隊參數)。"""
556
+ import pickle
557
+ setup()
558
+ 呼叫["上限"] = a.上限
559
+ res = json.loads((OUTD / "result.json").read_text(encoding="utf-8"))
560
+ det = json.loads((OUTD / "逐題.json").read_text(encoding="utf-8"))
561
+ PR = pickle.loads(S.PKL.read_bytes())
562
+ N = 來回次數預設()
563
+ rescued = []
564
+ for b, v in res["批"].items():
565
+ for p in v["變化題號"].get("拒→對", []):
566
+ hist = det.get(f"{b}|{p}") or []
567
+ h = next((x for x in reversed(hist) if x.get("status") == "ok"), None)
568
+ if h and h["回合"] > 0:
569
+ rescued.append((b, p, h))
570
+ rng = random.Random(a.種子)
571
+ jobs = []
572
+ for b, p, h in rescued:
573
+ P = PR[p]
574
+ lines = [(int(n), x) for n, x in h["lines"]]
575
+ ref = _評全(P["句"], lines)[0].get("lines") or []
576
+ jobs.append({"批": b, "題號": p, "型": "原題對照", "q": P["q"], "標答": None})
577
+ for i in range(a.份):
578
+ v = 變形(P["q"], ref, rng) if ref else {"失敗": "沒有參考讀法"}
579
+ if "失敗" in v:
580
+ jobs.append({"批": b, "題號": p, "型": f"變形{i + 1}", "判": "換不出", "原因": v["失敗"]})
581
+ if v["失敗"].startswith("題目沒有"):
582
+ break
583
+ continue
584
+ jobs.append({"批": b, "題號": p, "型": f"變形{i + 1}", "q": v["q"], "標答": v["標答"], "對位": v["map"],
585
+ "部分換": v["部分換"]})
586
+ gold = S.X.load_gold()
587
+
588
+ def run(j):
589
+ if "q" not in j:
590
+ return j
591
+ try:
592
+ sents = R.sentences(j["q"])
593
+ lines, raw = 模型讀題(sents)
594
+ r = 回饋修正(sents, lines, 來回次數=N)
595
+ except 超過上限:
596
+ return dict(j, 判="額度用完")
597
+ g = j["標答"] or gold[j["題號"]]
598
+ per = {}
599
+ for k in range(N + 1):
600
+ st, val = 第k回合(r, k)
601
+ per[f"N={k}"] = S.judge(val, g) if st == "ok" else "拒"
602
+ return dict(j, 標答=g, 新答=r["value"], 用到回合=r["用到回合"], 每回合=per, 判=per[f"N={N}"],
603
+ 讀法=[x for _, x in lines], 回合=[{kk: h.get(kk) for kk in ("回合", "status", "value", "拒答原因", "回覆")}
604
+ for h in r["回合"]])
605
+ with cf.ThreadPoolExecutor(a.並行) as ex:
606
+ done = list(ex.map(run, jobs))
607
+ stat = {}
608
+ for t in ("原題對照", "變形"):
609
+ xs = [x for x in done if x["型"].startswith(t)]
610
+ c = Counter(x["判"] for x in xs)
611
+ per = {f"N={k}": dict(Counter(x["每回合"][f"N={k}"] for x in xs if "每回合" in x)) for k in range(N + 1)}
612
+ stat[t] = {"件數": len(xs), "統計": dict(c), "每回合": per}
613
+ v_ok = [x for x in done if x["型"].startswith("變形") and "每回合" in x]
614
+ by_p = {}
615
+ for x in v_ok:
616
+ by_p.setdefault(x["題號"], []).append(x["判"] == "對")
617
+ res["換數字重跑"] = {
618
+ "說明": f"救回 {len(rescued)} 題,每題 {a.份} 個程式換數字變形(a 型:只換阿拉伯整數;標答=救回那題最後答對的資訊句照同一對位換數、"
619
+ f"程式腦重算;讀法沒用到的���第二輪起不換=部分換)+1 個原題對照,全部由 {預設模型} 從零讀 v7 提示再回饋修正(來回 {N})。"
620
+ "原讀題模型(Qwen/DeepSeek)沒用:ZeroGPU 今日已超 1,500 秒、DeepSeek 付費。",
621
+ "救回題數": len(rescued), "統計": stat,
622
+ "換數字還對比例(變形件)": f"{sum(x['判'] == '對' for x in v_ok)}/{len(v_ok)}",
623
+ "至少一個變形對的題": f"{sum(any(v) for v in by_p.values())}/{len(by_p)}",
624
+ "換不出": [{k: x[k] for k in ("批", "題號", "型", "原因")} for x in done if x.get("判") == "換不出"],
625
+ "題": done, "呼叫": 呼叫["次"], "呼叫失敗": 呼叫["失敗"]}
626
+ (OUTD / "result.json").write_text(json.dumps(res, ensure_ascii=False, indent=1, default=str), encoding="utf-8")
627
+ print(json.dumps({k: v for k, v in res["換數字重跑"].items() if k not in ("題",)}, ensure_ascii=False, default=str)[:4000])
628
+
629
+
630
+ def _safe(fn, *a):
631
+ try:
632
+ return fn(*a)
633
+ except 超過上限:
634
+ return None
635
+ except Exception as e: # 單題例外不停整批
636
+ print("例外", a[0], type(e).__name__, str(e)[:200], flush=True)
637
+
638
+
639
+ if __name__ == "__main__":
640
+ import argparse
641
+ sys.stdout.reconfigure(encoding="utf-8")
642
+ ap = argparse.ArgumentParser()
643
+ sp = ap.add_subparsers(dest="cmd", required=True)
644
+ q = sp.add_parser("量")
645
+ q.add_argument("--A題", type=int, default=300)
646
+ q.add_argument("--上限", type=int, default=1200)
647
+ q.add_argument("--變形保留", type=int, default=150)
648
+ q.add_argument("--並行", type=int, default=6)
649
+ w = sp.add_parser("換數字")
650
+ w.add_argument("--上限", type=int, default=400)
651
+ w.add_argument("--份", type=int, default=3)
652
+ w.add_argument("--種子", type=int, default=20261127)
653
+ w.add_argument("--並行", type=int, default=6)
654
+ a = ap.parse_args()
655
+ (cmd_量 if a.cmd == "量" else cmd_換數字)(a)
pipeline.py CHANGED
@@ -123,6 +123,9 @@ def init():
123
  import 讀法修補 as M
124
  M.setup()
125
  _S["M"] = M
 
 
 
126
  return _S
127
 
128
 
@@ -429,17 +432,72 @@ def rule_layer(q, S):
429
  return r, None
430
 
431
 
432
- def solve(question, gen, lb_solve=None, gold=None, pid="user"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
  """English word problem -> dict (never raises). Two layers:
434
  1. 程式讀題 program layer (rule tree, no LLM) — if it reads the question, the model is not called;
435
- 2. 模型讀題 model layer: gen(prompt)->str (Qwen3-8B), then the #350 reading repair when the read is refused.
 
436
  lb_solve(q)->dict is the left brain (None = Python fractions only); gold = reference answer (dev questions)."""
437
  t_all = time.time()
438
  q = " ".join((question or "").split())
439
  res = dict(question=q, sentences=[], reply="", lines=[], parsed="", brain_status="", prefix="", brain_value=None,
440
  equations=[], variables=[], teaching=[], lb_steps=[], answer=None, status="", verdict=None,
441
  stuck=[], refusal="", notes=[], seconds={}, layer="", layer_label="", rule_why="", rule_lines=[],
442
- repair=None)
443
  if not q:
444
  res["status"] = "拒答 Refused: 題目是空的 empty input."
445
  return res
@@ -521,6 +579,11 @@ def solve(question, gen, lb_solve=None, gold=None, pid="user"):
521
  return _finish(res, b2["value"], b2["prefix"], lb_solve, gold, S, t_all)
522
  elif str(rp.get("拒答原因") or "").startswith("修補多義"):
523
  res["notes"].append("讀法修補:" + rp["拒答原因"])
 
 
 
 
 
524
  try:
525
  res["parsed"] = S["P"].render(objs, "中") if objs else ""
526
  except Exception: # noqa: BLE001
 
123
  import 讀法修補 as M
124
  M.setup()
125
  _S["M"] = M
126
+ import 回饋修正 as FB # #350 v1: program points out the bad lines, the model rewrites only those
127
+ FB.setup()
128
+ _S["FB"] = FB
129
  return _S
130
 
131
 
 
432
  return r, None
433
 
434
 
435
+ def _feedback(res, sents, r, gen, rounds, lb_solve, gold, S, t_all):
436
+ """回饋修正.回饋修正 with the Space's own model as the correcting model. Returns the finished res, or None (refused;
437
+ the rounds are still recorded in res['feedback'] for the trace)."""
438
+ R, B, M, FB = S["R"], S["B"], S["M"], S["FB"]
439
+ t0 = time.time()
440
+ secs = []
441
+
442
+ def model(prompt):
443
+ t1 = time.time()
444
+ try:
445
+ return gen(prompt) or ""
446
+ finally:
447
+ secs.append(round(time.time() - t1, 1))
448
+ try:
449
+ fr = FB.回饋修正(sents, M.從rows(r["rows"]), 來回次數=rounds, 模型=model)
450
+ except RecursionError:
451
+ fr = {"status": "refused", "回合": [], "錯誤": "RecursionError"}
452
+ except Exception as e: # noqa: BLE001
453
+ fr = {"status": "refused", "回合": [], "錯誤": f"{type(e).__name__}: {e}"[:200]}
454
+ res["seconds"]["回饋修正 feedback (model calls: " + "+".join(map(str, secs)) + " s)"] = round(time.time() - t0, 1)
455
+ rounds_out = []
456
+ for h in fr.get("回合") or []:
457
+ if h["回合"] == 0:
458
+ continue
459
+ pts = [f"#{d['n']} \"{d['原文']}\"\n your line(s): {' | '.join(d['行']) or '(none)'}\n problem: {' ; '.join(d['問題'])}"
460
+ for d in h.get("指正") or []]
461
+ rounds_out.append({"回合": h["回合"], "指正": "\n".join(pts), "模型改後": h.get("回覆") or "",
462
+ "越界行": h.get("越界行") or [], "status": h.get("status"), "value": h.get("value"),
463
+ "拒答原因": h.get("拒答原因"), "修補": (h.get("修補") or {}).get("動作")})
464
+ res["feedback"] = {"rounds": rounds_out, "status": fr.get("status"), "錯誤": fr.get("錯誤")}
465
+ if fr.get("status") != "ok":
466
+ return None
467
+ h = next(x for x in reversed(fr["回合"]) if x.get("status") == "ok")
468
+ lines = (h.get("修補") or {}).get("lines") or h["lines"]
469
+ try:
470
+ objs2, _ = R.build(sents, "\n".join(f"#{n}: {b}" for n, b in lines))
471
+ b2 = B.solve(objs2)
472
+ except Exception: # noqa: BLE001
473
+ return None
474
+ if b2.get("status") != "ok" or not _same(b2["value"], fr["value"]):
475
+ res["notes"].append("回饋修正:重算前綴時答值對不上,不採用")
476
+ return None
477
+ fix = f"+修補 {'、'.join(h['修補']['動作'])}" if h.get("修補") else ""
478
+ res["layer_label"] = f"模型讀題(回饋修正 第 {h['回合']} 回合{fix})"
479
+ res["lines_before_repair"] = res["lines"]
480
+ res["lines"] = R.解析.render(objs2, "英")
481
+ try:
482
+ res["parsed"] = S["P"].render(objs2, "中")
483
+ except Exception: # noqa: BLE001
484
+ res["parsed"] = ""
485
+ _brain_display(res, objs2, B)
486
+ return _finish(res, b2["value"], b2["prefix"], lb_solve, gold, S, t_all)
487
+
488
+
489
+ def solve(question, gen, lb_solve=None, gold=None, pid="user", feedback=False, rounds=1):
490
  """English word problem -> dict (never raises). Two layers:
491
  1. 程式讀題 program layer (rule tree, no LLM) — if it reads the question, the model is not called;
492
+ 2. 模型讀題 model layer: gen(prompt)->str (Qwen3-8B), then the #350 reading repair when the read is refused;
493
+ feedback=True: then #350 v1 回饋修正 (program points out bad lines, the same model rewrites them; `rounds`).
494
  lb_solve(q)->dict is the left brain (None = Python fractions only); gold = reference answer (dev questions)."""
495
  t_all = time.time()
496
  q = " ".join((question or "").split())
497
  res = dict(question=q, sentences=[], reply="", lines=[], parsed="", brain_status="", prefix="", brain_value=None,
498
  equations=[], variables=[], teaching=[], lb_steps=[], answer=None, status="", verdict=None,
499
  stuck=[], refusal="", notes=[], seconds={}, layer="", layer_label="", rule_why="", rule_lines=[],
500
+ repair=None, feedback=None)
501
  if not q:
502
  res["status"] = "拒答 Refused: 題目是空的 empty input."
503
  return res
 
579
  return _finish(res, b2["value"], b2["prefix"], lb_solve, gold, S, t_all)
580
  elif str(rp.get("拒答原因") or "").startswith("修補多義"):
581
  res["notes"].append("讀法修補:" + rp["拒答原因"])
582
+ # #350 v1 回饋修正 (switch, default off): the program points out the bad lines, the same model rewrites them
583
+ if feedback:
584
+ done = _feedback(res, sents, r, gen, rounds, lb_solve, gold, S, t_all)
585
+ if done is not None:
586
+ return done
587
  try:
588
  res["parsed"] = S["P"].render(objs, "中") if objs else ""
589
  except Exception: # noqa: BLE001
tools/build_bundle.py CHANGED
@@ -9,7 +9,7 @@ from pathlib import Path
9
  SRC = Path(r"H:\Agent共用\專案\手搓算術")
10
  DST = Path(__file__).resolve().parent.parent / "hs"
11
  INFO = ["程式腦.py", "解析.py", "讀題_LLM.py", "讀題_提示v7.py", "v7守門.py", "探索模式.py",
12
- "讀法修補.py"] # #350 reading repair (model layer)
13
  TREE = ["engine.py", "樹.json", "詞庫.json", "資訊句輸出.py"] # 資訊句輸出.py = rule-tree reader (program layer)
14
  SUB = ["單位", "比較", "移轉", "輸出格式", "速率", "部分與整體"] # 語法模組 sub-modules: *.py (no tests) + 關係卡/補充表
15
  KB = ["基礎詞.json", "換算.json", "規則登記.json"]
 
9
  SRC = Path(r"H:\Agent共用\專案\手搓算術")
10
  DST = Path(__file__).resolve().parent.parent / "hs"
11
  INFO = ["程式腦.py", "解析.py", "讀題_LLM.py", "讀題_提示v7.py", "v7守門.py", "探索模式.py",
12
+ "讀法修補.py", "回饋修正.py"] # #350 reading repair + v1 feedback correction
13
  TREE = ["engine.py", "樹.json", "詞庫.json", "資訊句輸出.py"] # 資訊句輸出.py = rule-tree reader (program layer)
14
  SUB = ["單位", "比較", "移轉", "輸出格式", "速率", "部分與整體"] # 語法模組 sub-modules: *.py (no tests) + 關係卡/補充表
15
  KB = ["基礎詞.json", "換算.json", "規則登記.json"]
tools/measure_feedback.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """🔧 回饋修正 開/關 對照(Qwen3-8B 當修正模型)。**要用 ZeroGPU:等每日額度換日後(08:00)再跑。**
3
+ 168 題 Qwen 已存的 v7 一讀(fixture.json)走 Space 管線兩次:關(現在的預設)vs 開(來回 1 次)。
4
+ 1. 收集:開的那一次先用「只記提示、回空字串」的假修正模型跑,收齊每題的指正提示(來回 1 次 → 提示只由一讀決定);
5
+ 2. 叫模型:提示交 團隊系統\\ZeroGPU\\zerogpu.ask_batch(Bigbearbo/free-reader,同一個 Qwen3-8B、貪婪、thinking off),
6
+ 回覆存快取 jsonl(重跑不重叫);
7
+ 3. 判分:開=用快取回覆重跑;關=不開。輸出 對/錯/拒、逐題變化(救=拒→對、新錯=拒→錯、對→錯、對→拒)與淨正判定
8
+ (救 ≥ 新錯+對→錯,且 錯 不增)。淨正才建議把 app.py 的 Checkbox 預設改成開——本腳本不改 app.py。
9
+ python -B tools/measure_feedback.py fixture.json out.json [--只收集] [--批 8]
10
+ """
11
+ import json
12
+ import sys
13
+ import time
14
+ from collections import Counter
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parent.parent
18
+ sys.path.insert(0, str(ROOT))
19
+ import pipeline # noqa: E402
20
+
21
+ CACHE = ROOT / "tools" / "measure_feedback_快取.jsonl"
22
+ V = {"✓": "對", "✗": "錯", "拒答": "拒"}
23
+
24
+
25
+ def load_cache():
26
+ out = {}
27
+ if CACHE.exists():
28
+ for x in CACHE.read_text(encoding="utf-8").splitlines():
29
+ if x.strip():
30
+ r = json.loads(x)
31
+ out[r["prompt"]] = r["reply"]
32
+ return out
33
+
34
+
35
+ def run(fx, fixer, on):
36
+ res = {}
37
+ for t in fx:
38
+ def gen(p, t=t):
39
+ return fixer(p) if "A program checked them" in p else t["reply"]
40
+ r = pipeline.solve(t["q"], gen, None, gold=t["gold"], pid=t["id"], feedback=on, rounds=1)
41
+ res[t["id"]] = (V[r["verdict"]], r["answer"], r["layer_label"])
42
+ return res
43
+
44
+
45
+ def main():
46
+ fx = json.load(open(sys.argv[1], encoding="utf-8"))
47
+ batch = int(sys.argv[sys.argv.index("--批") + 1]) if "--批" in sys.argv else 8
48
+ t0 = time.time()
49
+ prompts = []
50
+ run(fx, lambda p: prompts.append(p) or "", True)
51
+ cache = load_cache()
52
+ todo = [p for p in dict.fromkeys(prompts) if p not in cache]
53
+ print(f"指正提示 {len(prompts)}(待叫模型 {len(todo)})", flush=True)
54
+ if "--只收集" in sys.argv:
55
+ return
56
+ if todo:
57
+ sys.path.insert(0, r"H:\Agent共用\專案\團隊系統\ZeroGPU")
58
+ import zerogpu
59
+ for s in range(0, len(todo), batch):
60
+ part = todo[s:s + batch]
61
+ outs, skipped = zerogpu.ask_batch(part, pipeline.MAX_NEW_TOKENS, chunk=batch, privacy=False)
62
+ with open(CACHE, "a", encoding="utf-8") as f:
63
+ for p, o in zip(part, outs):
64
+ if o is not None:
65
+ cache[p] = o
66
+ f.write(json.dumps({"prompt": p, "reply": o}, ensure_ascii=False) + "\n")
67
+ print(f"{s + len(part)}/{len(todo)} {time.time() - t0:.0f}s 有回覆 {sum(o is not None for o in outs)}", flush=True)
68
+ miss = [p for p in prompts if p not in cache]
69
+ off = run(fx, lambda p: "", False)
70
+ on = run(fx, lambda p: cache.get(p, ""), True)
71
+ cnt, trans, rows = Counter(), Counter(), []
72
+ for t in fx:
73
+ a, b = off[t["id"]], on[t["id"]]
74
+ cnt["關:" + a[0]] += 1
75
+ cnt["開:" + b[0]] += 1
76
+ if a[0] != b[0] or a[1] != b[1]:
77
+ trans[f"{a[0]}→{b[0]}"] += 1
78
+ rows.append({"id": t["id"], "關": a, "開": b})
79
+ rescue = trans["拒→對"]
80
+ harm = trans["拒→錯"] + trans["對→錯"]
81
+ net = rescue >= harm and cnt["開:錯"] <= cnt["關:錯"]
82
+ out = {"統計": dict(cnt), "變化": dict(trans), "救": rescue, "新錯": harm, "對→拒": trans["對→拒"],
83
+ "淨正(建議預設開)": net, "沒拿到模型回覆的提示": len(miss), "變的題": rows, "秒": round(time.time() - t0)}
84
+ json.dump(out, open(sys.argv[2], "w", encoding="utf-8"), ensure_ascii=False, indent=1)
85
+ print(json.dumps({k: v for k, v in out.items() if k != "變的題"}, ensure_ascii=False))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
tools/mix_replies.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """逐句混合 phase 1 (team-folder environment): for each saved Qwen reply, every fact sentence whose atomic clauses are
3
+ ALL read by the construction reader (構式讀題, 門檻 0.7, 名字對齊 on) with a construction in the 21-entry allow list
4
+ (構式\\逐句混合\\result.json 放行表) gets its Qwen lines replaced by the program reading; other sentences (incl. the
5
+ question) keep Qwen's lines. Same per-sentence rule as 構式逐句混合.py's 251-variant section.
6
+ python -B tools/mix_replies.py fixture.json mixed.json
7
+ Writes, per question: mixed reply text (#n: line), which sentences were replaced, construction keys. No API calls."""
8
+ import json
9
+ import re
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+
14
+ sys.dont_write_bytecode = True
15
+ SYN = Path(r"H:\Agent共用\專案\手搓算術\語法模組\句法讀題")
16
+ sys.path.insert(0, str(SYN))
17
+ import 構式讀題 as K # noqa: E402
18
+ import 構式逐句混合 as X # noqa: E402
19
+
20
+ A, Z = K.A, K.Z
21
+ LINE = re.compile(r"^\s*#(\d+)\s*:\s*(.+?)\s*$")
22
+ NONEMPTY = "--非空" in sys.argv # variant: an empty program reading does not replace lines the model wrote
23
+
24
+
25
+ def build_reader():
26
+ t0 = time.time()
27
+ A.US = A.unitset()
28
+ K.MIN_PREC = 0.7
29
+ Z.省略開 = False
30
+ X.對齊開 = True # 構式名字對齊.py chose 「只名字對齊」
31
+ D = K.load()
32
+ DS = K.load(K.OUTD / "資料_標準.json")
33
+ ids = sorted(D, key=lambda s: int(s.split("-")[1]))
34
+ tr, te = K.split_ids(ids)
35
+ lab = {p: DS[p]["行"] for p in ids}
36
+ F = {p: K.features_problem(D[p], lab[p]) for p in ids}
37
+ R = K.train_reader(D, tr, lab, F)
38
+ allow = set(json.loads((K.OUTD / "逐句混合" / "result.json").read_text(encoding="utf-8"))
39
+ ["放行表(學習集定、驗收集量)"]["構式"])
40
+ print("reader", len(R.rules), "rules; allow", len(allow), f"{time.time() - t0:.0f}s", flush=True)
41
+ return R, allow, set(tr)
42
+
43
+
44
+ def parse_reply(reply):
45
+ """Qwen reply → {句號: [raw line, …]} (keeps Qwen's exact text)."""
46
+ by = {}
47
+ for ln in (reply or "").splitlines():
48
+ m = LINE.match(ln)
49
+ if m:
50
+ by.setdefault(int(m.group(1)), []).append(m.group(2))
51
+ return by
52
+
53
+
54
+ def mix(q, reply, R, allow):
55
+ sents = K.sentences(q)
56
+ raw = parse_reply(reply)
57
+ by_tok = {}
58
+ for n, L in raw.items():
59
+ for b in L:
60
+ if 1 <= n <= len(sents):
61
+ by_tok.setdefault(n, [])
62
+ body = b.rstrip(".").strip()
63
+ if body.startswith(("skip", "unread(")):
64
+ continue
65
+ try:
66
+ by_tok[n].append(A.pieces(body))
67
+ except Exception: # noqa: BLE001
68
+ pass
69
+ qns = [n for n, L in raw.items() if any(b.lstrip().startswith("ask(") for b in L)]
70
+ qn = qns[0] if qns else K.qn_of({"句": sents})
71
+ names = A.problem_names(sents)
72
+ atoms_by = {}
73
+ for n, s in enumerate(sents, 1):
74
+ if n == qn or K.is_q(s):
75
+ atoms_by[n] = [s]
76
+ else:
77
+ try:
78
+ atoms_by[n] = [a["text"] for a in Z.解壓(s)]
79
+ except Exception: # noqa: BLE001
80
+ atoms_by[n] = [s]
81
+ K.docs([a for n in sorted(atoms_by) for a in atoms_by[n]])
82
+ ctx = K.Ctx(frozenset(names))
83
+ out, per = dict(raw), []
84
+ for n, s in enumerate(sents, 1):
85
+ if n == qn:
86
+ per.append({"句號": n, "來源": "模型", "構式": None})
87
+ continue
88
+ gots, keys = [], []
89
+ for a in atoms_by[n]:
90
+ f = K.特徵(a, ctx)
91
+ g, _ = R.read(f)
92
+ if g is not None:
93
+ g, _ = X.align(g, a, X.vocab_of(by_tok, n), names)
94
+ ctx.see(f, g or [])
95
+ gots.append(g if (g is not None and f["鍵"]["類"] in allow) else None)
96
+ keys.append(f["鍵"]["類"])
97
+ if NONEMPTY and gots and all(g is not None for g in gots) and not any(gots) and raw.get(n):
98
+ per.append({"句號": n, "來源": "模型", "構式": keys, "備註": "程式讀成空、模型有寫 → 不取代(--非空)"})
99
+ elif gots and all(g is not None for g in gots):
100
+ out[n] = [A.render(ps) + "." for g in gots for ps in g]
101
+ per.append({"句號": n, "來源": "程式", "構式": keys, "程式讀": out[n], "模型讀": raw.get(n, [])})
102
+ else:
103
+ per.append({"句號": n, "來源": "模型", "構式": keys})
104
+ text = "\n".join(f"#{n}: {b}" for n in sorted(out) for b in out[n])
105
+ return text, per
106
+
107
+
108
+ def main():
109
+ R, allow, trs = build_reader()
110
+ fx = json.load(open(sys.argv[1], encoding="utf-8"))
111
+ res = []
112
+ for t in fx:
113
+ try:
114
+ text, per = mix(t["q"], t["reply"], R, allow)
115
+ except Exception as e: # noqa: BLE001
116
+ text, per = t["reply"], [{"錯誤": f"{type(e).__name__}: {e}"[:200]}]
117
+ res.append({"id": t["id"], "mixed_reply": text, "逐句": per, "在構式學習集": t["id"] in trs,
118
+ "換句數": sum(1 for p in per if p.get("來源") == "程式")})
119
+ json.dump(res, open(sys.argv[2], "w", encoding="utf-8"), ensure_ascii=False, indent=1)
120
+ print("題", len(res), "有換句的題", sum(r["換句數"] > 0 for r in res), "換句", sum(r["換句數"] for r in res),
121
+ "在學習集", sum(r["在構式學習集"] for r in res))
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
tools/test_feedback_offline.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Offline check of the 🔧 回饋修正 switch with a FAKE model (no ZeroGPU): Kira N=1 where the "model" reads the two legs
3
+ as 60 minutes (數字無出處:60), the program points at sentence #1, the fake model rewrites #1 as 1 hour (and also sends
4
+ a #3 line, which must be dropped). The rule layer reads Kira itself, so it is switched off here to reach the model layer.
5
+ Also: the switch off → refused; a bad fixer that repeats 60 → still refused.
6
+ python -B tools/test_feedback_offline.py [out.json]"""
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ ROOT = Path(__file__).resolve().parent.parent
12
+ sys.path.insert(0, str(ROOT))
13
+ import pipeline # noqa: E402
14
+
15
+ Q = ("Three train stations are 1 hours apart from one another. Kira travels from the first station to the third, taking "
16
+ "a 30 minutes break at the second station. What's the total time, in minutes, that Kira takes to travel between the "
17
+ "first and third station?")
18
+ READ = ("#1: duration(station 1, travel to station 2, 60, minute).\n#1: duration(station 2, travel to station 3, 60, minute).\n"
19
+ "#2: duration(kira, break, 30, minute).\n"
20
+ "#3: ask(add(duration(station 1, travel to station 2, ?, minute), duration(station 2, travel to station 3, ?, minute), "
21
+ "duration(kira, break, ?, minute))).")
22
+ GOOD = ("#1: duration(station 1, travel to station 2, 1, hour).\n#1: duration(station 2, travel to station 3, 1, hour).\n"
23
+ "#3: ask(add(duration(kira, break, ?, minute), 999)).")
24
+ BAD = "#1: duration(station 1, travel to station 2, 60, minute).\n#1: duration(station 2, travel to station 3, 60, minute)."
25
+
26
+
27
+ def fake(fix):
28
+ calls = []
29
+
30
+ def gen(prompt):
31
+ calls.append(prompt)
32
+ return fix if "A program checked them" in prompt else READ
33
+ return gen, calls
34
+
35
+
36
+ pipeline.init()
37
+ pipeline.rule_layer = lambda q, S: ({"英文式": []}, "(測試:略過程式層,直接走模型層)")
38
+ out = {}
39
+ for name, fix, on in (("開+好修正", GOOD, True), ("關", GOOD, False), ("開+壞修正", BAD, True)):
40
+ gen, calls = fake(fix)
41
+ r = pipeline.solve(Q, gen, None, gold="150", feedback=on, rounds=1)
42
+ fb = r.get("feedback") or {}
43
+ out[name] = {"模型呼叫": len(calls), "層": r["layer_label"], "答": r["answer"], "判": r["verdict"], "拒因": r["refusal"],
44
+ "回合": fb.get("rounds"), "資訊句": r["lines"], "前綴": r["prefix"], "左腦": r["lb_steps"]}
45
+ ok = (out["開+好修正"]["判"] == "✓" and out["開+好修正"]["模型呼叫"] == 2 and out["開+好修正"]["回合"][0]["越界行"]
46
+ and out["關"]["判"] == "拒答" and out["關"]["模型呼叫"] == 1 and out["開+壞修正"]["判"] == "拒答")
47
+ print(json.dumps(out, ensure_ascii=False, indent=1))
48
+ print("通過" if ok else "失敗")
49
+ if len(sys.argv) > 1:
50
+ json.dump(out, open(sys.argv[1], "w", encoding="utf-8"), ensure_ascii=False, indent=1)
51
+ sys.exit(0 if ok else 1)
tools/test_mix_replay.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """逐句混合 phase 2: replay the 168 saved Qwen replies through the Space pipeline (two layers + #350 repair) twice —
3
+ pure Qwen reply vs the mixed reply from tools/mix_replies.py — and compare 對/錯/拒 per question.
4
+ python -B tools/test_mix_replay.py fixture.json mixed.json out.json"""
5
+ import json
6
+ import sys
7
+ from collections import Counter
8
+ from pathlib import Path
9
+
10
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
11
+ import pipeline # noqa: E402
12
+
13
+ fx = json.load(open(sys.argv[1], encoding="utf-8"))
14
+ mx = {m["id"]: m for m in json.load(open(sys.argv[2], encoding="utf-8"))}
15
+ V = {"✓": "對", "✗": "錯", "拒答": "拒"}
16
+ cnt, trans, rows = Counter(), Counter(), []
17
+ for t in fx:
18
+ m = mx[t["id"]]
19
+ ra = pipeline.solve(t["q"], lambda p, t=t: t["reply"], None, gold=t["gold"], pid=t["id"])
20
+ rb = pipeline.solve(t["q"], lambda p, m=m: m["mixed_reply"], None, gold=t["gold"], pid=t["id"])
21
+ a, b = V[ra["verdict"]], V[rb["verdict"]]
22
+ cnt["純:" + a] += 1
23
+ cnt["混:" + b] += 1
24
+ if a != b:
25
+ trans[f"{a}→{b}"] += 1
26
+ rows.append({"id": t["id"], "q": t["q"], "gold": t["gold"], "純": [a, ra["answer"], ra["layer_label"], ra["refusal"]],
27
+ "混": [b, rb["answer"], rb["layer_label"], rb["refusal"]], "逐句": m["逐句"],
28
+ "在構式學習集": m["在構式學習集"]})
29
+ cnt["有換句的題"] += m["換句數"] > 0
30
+ out = {"統計": dict(cnt), "變化": dict(trans), "變的題": rows}
31
+ json.dump(out, open(sys.argv[3], "w", encoding="utf-8"), ensure_ascii=False, indent=1)
32
+ print(json.dumps({"統計": dict(cnt), "變化": dict(trans)}, ensure_ascii=False))
33
+ for r in rows:
34
+ print(r["id"], r["純"][:3], "→", r["混"][:3], "學習集" if r["在構式學習集"] else "")
逐句混合量測.json ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "日期": "2026-11-27",
3
+ "作者": "Claude子代理(讀題 Space)",
4
+ "題": "168 題 Qwen3-8B 已存 v7 回覆(ZeroGPU讀題對照,範圍守門後)",
5
+ "做法": "構式讀題器(門檻 0.7、名字對齊開、21 構式放行表)逐原子句讀;一句的原子句全部讀出且構式都在放行表才整句換成程式讀法(同 構式逐句混合.py 251 變形題口徑);問句與其他句留 Qwen;兩邊都走 Space 管線(程式層→模型層→#350 修補 R1R3)。",
6
+ "純Qwen+修補": {
7
+ "對": 11,
8
+ "錯": 7,
9
+ "拒": 150
10
+ },
11
+ "逐句混合+修補": {
12
+ "對": 10,
13
+ "錯": 9,
14
+ "拒": 149,
15
+ "有換句的題": 49,
16
+ "換句": 55,
17
+ "變化": {
18
+ "拒→錯": 2,
19
+ "對→拒": 1
20
+ },
21
+ "變的題": [
22
+ {
23
+ "id": "train-2325",
24
+ "q": "George was selling some of his old toys on the internet. He managed to sell 3 little cars and a set of Legos. In total, he earned $45. How much did the Legos set cost, if one little car was sold for $5?",
25
+ "gold": "30",
26
+ "純": [
27
+ "拒",
28
+ null,
29
+ "模型讀題(未修補)",
30
+ "未讀跟所求有關:George was selling some of his old toys on the internet."
31
+ ],
32
+ "混": [
33
+ "錯",
34
+ "45",
35
+ "模型讀題(未修補)",
36
+ ""
37
+ ],
38
+ "逐句": [
39
+ {
40
+ "句號": 1,
41
+ "來源": "程式",
42
+ "構式": [
43
+ "失||人:0"
44
+ ],
45
+ "程式讀": [],
46
+ "模型讀": [
47
+ "sell(george, little car, 3, 5)."
48
+ ]
49
+ },
50
+ {
51
+ "句號": 2,
52
+ "來源": "模型",
53
+ "構式": [
54
+ "他||人:n"
55
+ ]
56
+ },
57
+ {
58
+ "句號": 3,
59
+ "來源": "模型",
60
+ "構式": [
61
+ "得|$合|人:$"
62
+ ]
63
+ },
64
+ {
65
+ "句號": 4,
66
+ "來源": "模型",
67
+ "構式": null
68
+ }
69
+ ],
70
+ "在構式學習集": false
71
+ },
72
+ {
73
+ "id": "train-6021",
74
+ "q": "Harry is traveling home on the bus. He has already been sat on the bus for 15 minutes, and he knows the rest of the journey will take another 25 minutes. The walk from the bus stop to his house will take half the amount of time the bus journey took. In total, how many minutes will Harry have spent traveling?",
75
+ "gold": "60",
76
+ "純": [
77
+ "拒",
78
+ null,
79
+ "模型讀題(未修補)",
80
+ "未讀跟所求有關:Harry is traveling home on the bus."
81
+ ],
82
+ "混": [
83
+ "錯",
84
+ "50",
85
+ "模型讀題(未修補)",
86
+ ""
87
+ ],
88
+ "逐句": [
89
+ {
90
+ "句號": 1,
91
+ "來源": "程式",
92
+ "構式": [
93
+ "動||人:0"
94
+ ],
95
+ "程式讀": [],
96
+ "模型讀": [
97
+ "have(harry, minute, 15, start)."
98
+ ]
99
+ },
100
+ {
101
+ "句號": 2,
102
+ "來源": "模型",
103
+ "構式": [
104
+ "他||人:n",
105
+ "他|再剩|人:n"
106
+ ]
107
+ },
108
+ {
109
+ "句號": 3,
110
+ "來源": "模型",
111
+ "構式": [
112
+ "得|給|物:分",
113
+ "得||物:0"
114
+ ]
115
+ },
116
+ {
117
+ "句號": 4,
118
+ "來源": "模型",
119
+ "構式": null
120
+ }
121
+ ],
122
+ "在構式學習集": false
123
+ },
124
+ {
125
+ "id": "train-6179",
126
+ "q": "Diane shows Sarah a game that deciphers at what age she will marry based on her name and current age. Sarah is 9 years old. The game consists of adding the number of letters in the player's name plus twice the player's age. According to the game, at what age will Sarah get married?",
127
+ "gold": "23",
128
+ "純": [
129
+ "對",
130
+ "23",
131
+ "模型讀題(未修補)",
132
+ ""
133
+ ],
134
+ "混": [
135
+ "拒",
136
+ null,
137
+ "模型讀題(未修補)",
138
+ "解題器:insufficient/underdetermined"
139
+ ],
140
+ "逐句": [
141
+ {
142
+ "句號": 1,
143
+ "來源": "程式",
144
+ "構式": [
145
+ "他||物:0",
146
+ "他||物:0",
147
+ "他||人:0"
148
+ ],
149
+ "程式讀": [],
150
+ "模型讀": [
151
+ "have(sarah, letter, letters(\"Sarah\"))."
152
+ ]
153
+ },
154
+ {
155
+ "句號": 2,
156
+ "來源": "模型",
157
+ "構式": [
158
+ "是||人:n"
159
+ ]
160
+ },
161
+ {
162
+ "句號": 3,
163
+ "來源": "模型",
164
+ "構式": null
165
+ },
166
+ {
167
+ "句號": 4,
168
+ "來源": "程式",
169
+ "構式": [
170
+ "他|續|人:0"
171
+ ],
172
+ "程式讀": [],
173
+ "模型讀": []
174
+ }
175
+ ],
176
+ "在構式學習集": false
177
+ }
178
+ ]
179
+ },
180
+ "變體_程式讀成空不取代": {
181
+ "對": 11,
182
+ "錯": 7,
183
+ "拒": 150,
184
+ "有換句的題": 4,
185
+ "變化": {}
186
+ },
187
+ "結論": "不淨正(救 0、錯 +2、對→拒 1)→ 不上線,Space 不動。變的 3 題都是「:0 構式(無數字句)程式讀成空」取代了 Qwen 錯編號到 #1 的事實行;空讀取代拿掉了原本擋下的未讀,變成錯答。變體(空讀不取代)只剩 4 句取代、0 變化,也不淨正。",
188
+ "學習集重疊": "168 題��� 15 題在構式讀題器學習集"
189
+ }