Spaces:
Running on Zero
Running on Zero
Two layers: rule-tree reader first (no model), Qwen3-8B + #350 reading repair second
Browse files- app.py +38 -8
- data/rule_layer_coverage.json +23 -0
- hs/規則樹/資訊句輸出.py +657 -0
- hs/語法模組/資訊句/讀法修補.py +830 -0
- pipeline.py +149 -34
- tools/accept_layers.py +52 -0
- tools/build_bundle.py +4 -2
- tools/measure_rule_layer.py +44 -0
- tools/test_replay.py +3 -2
app.py
CHANGED
|
@@ -62,6 +62,9 @@ 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):
|
|
@@ -83,8 +86,24 @@ def _vars(rows):
|
|
| 83 |
return out
|
| 84 |
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
def trace_md(r, ref):
|
| 87 |
-
s = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
+ [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 []),
|
|
@@ -111,7 +130,7 @@ def answer_text(r, ref):
|
|
| 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']})")
|
|
@@ -142,7 +161,8 @@ _MARK = {"✓": "✓", "✗": "✗", "拒答": "拒", None: "-"}
|
|
| 142 |
|
| 143 |
|
| 144 |
def _short(r):
|
| 145 |
-
|
|
|
|
| 146 |
|
| 147 |
|
| 148 |
def solve_vary(question):
|
|
@@ -162,7 +182,7 @@ def solve_vary(question):
|
|
| 162 |
if ref:
|
| 163 |
head = f"原題 {_MARK[r1['verdict']]}|換數字 {_MARK[r2['verdict']]}"
|
| 164 |
if r1["verdict"] == "✓" and r2["verdict"] == "✓":
|
| 165 |
-
head += " → 會讀(非背題)"
|
| 166 |
elif r1["verdict"] == "✓":
|
| 167 |
head += " → 原題對、換數字沒對:可能背過題"
|
| 168 |
lines = [head, f"原題:{_short(r1)}(標答 {ref['gold']})",
|
|
@@ -179,14 +199,24 @@ def solve_vary(question):
|
|
| 179 |
|
| 180 |
# ---------------------------------------------------------------- page
|
| 181 |
INTRO = ("# 英文應用題讀題 Word-problem reader\n"
|
| 182 |
-
"**Qwen3-8B**
|
| 183 |
-
"讀不懂就拒答並指出卡在哪一句,不猜。
|
| 184 |
-
"
|
|
|
|
| 185 |
|
| 186 |
NOTES = f"""
|
| 187 |
---
|
| 188 |
## 說明 About
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
**誠實數字 Honest numbers.** Qwen3-8B 零樣本 v7 讀法,在 168 題 GSM8K train 開發題對照:**對 10、錯 7、拒 151**;
|
| 191 |
同題 DeepSeek v7 單讀 **19/5/144**。所以這裡大多數題目會拒答,這是預期的。團隊主讀題器用 DeepSeek(付費 API,不在這個 Space)。
|
| 192 |
數字是團隊自己量的,未經第三方驗證。On 168 GSM8K-train development questions Qwen3-8B (zero-shot, v7 prompt) got 10 right,
|
|
@@ -207,7 +237,7 @@ The model may have seen GSM8K train; a reading only counts if it still works wit
|
|
| 207 |
4. 守門:資訊句裡的字面數沒用到、資訊句沒用到(抽掉測試)、非整數答案、語意守門、v7 守門 → 拒答。解析器遇到畸形輸出無限遞迴也算拒答。
|
| 208 |
5. 前綴逐步交給手搓左腦([Bigbearbo/handwired-left-brain-1](https://huggingface.co/Bigbearbo/handwired-left-brain-1) v0.4)算整數加減乘除;左腦不收的(非整數、單位換算)標「Python 分數計算」。每一步也跟 Python 對照。
|
| 209 |
|
| 210 |
-
**限制 Limits.** 只讀一次(不做第二讀/
|
| 211 |
|
| 212 |
**授權 License.** 本 Space 程式與資料 cc-by-nc-4.0;Qwen3-8B 是 Apache-2.0(Qwen team);GSM8K 是 MIT(OpenAI)。
|
| 213 |
"""
|
|
|
|
| 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 |
+
_RULE = json.load(open(os.path.join(os.path.dirname(__file__), "data", "rule_layer_coverage.json"), encoding="utf-8"))
|
| 66 |
+
RULE_N = _RULE["讀出"]
|
| 67 |
+
RULE_DETAIL = f"對 {_RULE['對']}、錯 {_RULE['錯']};實跑 read/solve 統計,{_RULE['日期']}"
|
| 68 |
|
| 69 |
|
| 70 |
def random_question(kind):
|
|
|
|
| 86 |
return out
|
| 87 |
|
| 88 |
|
| 89 |
+
def layer_md(r):
|
| 90 |
+
if r["layer"] == "程式":
|
| 91 |
+
return ("**走哪一層:第一層 程式讀題**(規則樹讀題,沒有呼叫 Qwen,不會背題)。Layer 1, rule-tree reader: no model call.")
|
| 92 |
+
if r["layer"] == "模型":
|
| 93 |
+
return f"**走哪一層:第二層 {r['layer_label']}**。程式層拒因 rule-layer refusal:{r['rule_why'] or '-'}"
|
| 94 |
+
return "**走哪一層:-**"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
def trace_md(r, ref):
|
| 98 |
+
s = [layer_md(r)]
|
| 99 |
+
if r["layer"] == "模型" and r["rule_lines"]:
|
| 100 |
+
s += ["程式層讀到的資訊句(沒讀完,拒答)rule-layer sentences:", _code(r["rule_lines"])]
|
| 101 |
+
if r.get("repair"):
|
| 102 |
+
rp = r["repair"]
|
| 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)]),
|
| 109 |
"### 2. 讀題器原始回覆 Reader reply (Qwen3-8B, v7 prompt, greedy, thinking off)", _code([r["reply"]] if r["reply"] else []),
|
|
|
|
| 130 |
head = f"答案 Answer: {r['answer']}"
|
| 131 |
else:
|
| 132 |
head = "拒答 Refused(不猜)"
|
| 133 |
+
lines = [head, f"讀題層 layer: {r['layer_label'] or '-'}"]
|
| 134 |
if ref is not None:
|
| 135 |
mark = {"✓": "✓ 對 correct", "✗": "✗ 錯 wrong", "拒答": "拒答 refused"}[r["verdict"]]
|
| 136 |
lines.append(f"判分 {mark} (標答 reference: {ref['gold']})")
|
|
|
|
| 161 |
|
| 162 |
|
| 163 |
def _short(r):
|
| 164 |
+
a = f"答 {r['answer']}" if r["answer"] is not None else "拒答(" + (r["refusal"] or r["status"])[:80] + ")"
|
| 165 |
+
return f"[{r['layer_label'] or '-'}] {a}"
|
| 166 |
|
| 167 |
|
| 168 |
def solve_vary(question):
|
|
|
|
| 182 |
if ref:
|
| 183 |
head = f"原題 {_MARK[r1['verdict']]}|換數字 {_MARK[r2['verdict']]}"
|
| 184 |
if r1["verdict"] == "✓" and r2["verdict"] == "✓":
|
| 185 |
+
head += " → 會讀(非背題)" + ("(兩次都是程式讀題)" if r1["layer"] == r2["layer"] == "程式" else "")
|
| 186 |
elif r1["verdict"] == "✓":
|
| 187 |
head += " → 原題對、換數字沒對:可能背過題"
|
| 188 |
lines = [head, f"原題:{_short(r1)}(標答 {ref['gold']})",
|
|
|
|
| 199 |
|
| 200 |
# ---------------------------------------------------------------- page
|
| 201 |
INTRO = ("# 英文應用題讀題 Word-problem reader\n"
|
| 202 |
+
"兩層讀題:先用**程式讀題**(規則樹,不會背題);程式讀不出才交 **Qwen3-8B** 寫螺旋語資訊句(再過讀法修補)→ "
|
| 203 |
+
"**程式腦**(Python)列式求解 → **手搓左腦**(手填權重的門檻網路)算前綴;讀不懂就拒答並指出卡在哪一句,不猜。"
|
| 204 |
+
"Rule-tree reader first, Qwen3-8B only when it cannot read; the program brain solves, the hand-wired left brain "
|
| 205 |
+
"does the arithmetic; it refuses instead of guessing.")
|
| 206 |
|
| 207 |
NOTES = f"""
|
| 208 |
---
|
| 209 |
## 說明 About
|
| 210 |
|
| 211 |
+
**兩層 Two layers.**
|
| 212 |
+
- **第一層 程式讀題**:`規則樹/資訊句輸出.py`(規則樹選葉子寫資訊句,沒有模型)。程式讀的題不會背題,換數字照樣讀。
|
| 213 |
+
但涵蓋目前**很小**:GSM8K train 開發題(範圍守門過濾後)**7,066 題只讀出 {RULE_N} 題**({RULE_DETAIL});每加一條規則就會變多。
|
| 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 |
+
|
| 220 |
**誠實數字 Honest numbers.** Qwen3-8B 零樣本 v7 讀法,在 168 題 GSM8K train 開發題對照:**對 10、錯 7、拒 151**;
|
| 221 |
同題 DeepSeek v7 單讀 **19/5/144**。所以這裡大多數題目會拒答,這是預期的。團隊主讀題器用 DeepSeek(付費 API,不在這個 Space)。
|
| 222 |
數字是團隊自己量的,未經第三方驗證。On 168 GSM8K-train development questions Qwen3-8B (zero-shot, v7 prompt) got 10 right,
|
|
|
|
| 237 |
4. 守門:資訊句裡的字面數沒用到、資訊句沒用到(抽掉測試)、非整數答案、語意守門、v7 守門 → 拒答。解析器遇到畸形輸出無限遞迴也算拒答。
|
| 238 |
5. 前綴逐步交給手搓左腦([Bigbearbo/handwired-left-brain-1](https://huggingface.co/Bigbearbo/handwired-left-brain-1) v0.4)算整數加減乘除;左腦不收的(非整數、單位換算)標「Python 分數計算」。每一步也跟 Python 對照。
|
| 239 |
|
| 240 |
+
**限制 Limits.** 模型層只讀一次(不做第二讀);上面 10/7/151 是沒有程式層、沒有讀法修補時量的;一次只服務一位使用者;ZeroGPU 有每日 GPU 配額,排隊時會比較慢。程式腦是團隊共用區 2026-11-27 的版本複本(`hs/`),之後主線更新不會自動同步。
|
| 241 |
|
| 242 |
**授權 License.** 本 Space 程式與資料 cc-by-nc-4.0;Qwen3-8B 是 Apache-2.0(Qwen team);GSM8K 是 MIT(OpenAI)。
|
| 243 |
"""
|
data/rule_layer_coverage.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"題數": 7066,
|
| 3 |
+
"讀出": 2,
|
| 4 |
+
"對": 2,
|
| 5 |
+
"錯": 0,
|
| 6 |
+
"拒": 7064,
|
| 7 |
+
"日期": "2026-11-27",
|
| 8 |
+
"來源": "規則樹/資訊句輸出.solve(共用主線 1c3372ab),GSM8K train 開發題 real_set_audit.rows → 範圍守門.過濾",
|
| 9 |
+
"讀出題": [
|
| 10 |
+
{
|
| 11 |
+
"id": "train-5201",
|
| 12 |
+
"value": "270",
|
| 13 |
+
"gold": "270",
|
| 14 |
+
"判": "對"
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"id": "train-5492",
|
| 18 |
+
"value": "21",
|
| 19 |
+
"gold": "21",
|
| 20 |
+
"判": "對"
|
| 21 |
+
}
|
| 22 |
+
]
|
| 23 |
+
}
|
hs/規則樹/資訊句輸出.py
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
r"""規則樹葉子 → 螺旋語資訊句(#332 第 3 步 A 線支援;寫:Claude子代理(樹葉遷移資訊句)2026-11-25)。
|
| 3 |
+
|
| 4 |
+
依據:電腦Codex 12:06「請先按 持有、得到、減量 遷移已驗證單句欄位,再逐題驗收所求相依」;
|
| 5 |
+
基本概念表 v0/v1(語法模組\資訊句\基本概念表.md);吃掉模式(讀不懂的子句不放棄整題)。
|
| 6 |
+
|
| 7 |
+
做法(只讀 engine.py,不改;不改 解析.py/程式腦.py,只呼叫):
|
| 8 |
+
題目 → engine.normalize/split_clauses(跟 trace 同一套切法)
|
| 9 |
+
每個敘述子句 → 規則樹選葉子(同一套優先層與衝突規則)→ 意思節點的 op
|
| 10 |
+
→ 本檔 InfoStory 的 op 把它寫成英文式資訊句(每句附原文與子句編號)
|
| 11 |
+
讀不懂(沒有葉子、同層衝突、代名詞沒先行詞…)→ unread("原句", 理由).
|
| 12 |
+
問句 → ask(…)
|
| 13 |
+
全部資訊句 → 解析.parse(英文式)→ 程式腦.solve → 值、前綴
|
| 14 |
+
|
| 15 |
+
op → 資訊句(英文式;中文式見 基本概念表):
|
| 16 |
+
擁有 → have(主體, 物, 值, start).
|
| 17 |
+
變化(加) → change(主體, 物, +值). 之前沒有存量 → have(主體, 物, 值, start).(意思/增加「之前沒有就當起始量」)
|
| 18 |
+
變化(減) → change(主體, 物, -值). 之前沒有存量也照寫,起點未知交程式腦判斷相依
|
| 19 |
+
轉移(兩個變化)→ transfer(給方, 收方, 物, 值).
|
| 20 |
+
每組 → pergroup(容器, 物, 值).
|
| 21 |
+
均分 → split(整體, 份數, 物). (程式腦 v0 尚無 c_均分,這類題目前拒答)
|
| 22 |
+
百分比減 → change(主體, 物, neg(share(now, ?, 分數))).
|
| 23 |
+
問擁有 → ask(have(主體, 物, ?, now)). 問的單位跟存量不同 → ask(convert(have(…), 存量單位, 問的單位)).
|
| 24 |
+
問總和 → ask(partof(?, [甲, 乙], 物)). they → ask(partof(?, all, 物)).
|
| 25 |
+
問每份 → ask(div(整體, 份數)).
|
| 26 |
+
值:整數照寫;小數寫 1.5;dozen 寫 mul(3, 12);不同單位的變化寫 convert(值, 原單位, 存量單位)。
|
| 27 |
+
|
| 28 |
+
python -B 資訊句輸出.py "題目" # 單題:列每句資訊句、前綴、值
|
| 29 |
+
python -B 資訊句輸出.py 量 # 四庫量測(GSM8K train 走 real_set_audit.rows,排除盲測等保留題)
|
| 30 |
+
"""
|
| 31 |
+
import copy
|
| 32 |
+
import json
|
| 33 |
+
import re
|
| 34 |
+
import sys
|
| 35 |
+
from fractions import Fraction
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
|
| 38 |
+
HERE = Path(__file__).resolve().parent
|
| 39 |
+
sys.path.insert(0, str(HERE))
|
| 40 |
+
import engine as E
|
| 41 |
+
|
| 42 |
+
INFO_DIR = HERE.parent / '語法模組' / '資訊句'
|
| 43 |
+
sys.path.insert(0, str(INFO_DIR))
|
| 44 |
+
import 解析 as P # noqa: E402
|
| 45 |
+
import 程式腦 as B # noqa: E402
|
| 46 |
+
|
| 47 |
+
MAX_FACTS = 12
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# ---------------------------------------------------------------- 值
|
| 51 |
+
def V(expr):
|
| 52 |
+
"""engine 的量式子 → 資訊句參數(字串或巢狀概念 dict)。"""
|
| 53 |
+
if isinstance(expr, str):
|
| 54 |
+
if expr.startswith('小 '):
|
| 55 |
+
_, a, s = expr.split()
|
| 56 |
+
s = int(s)
|
| 57 |
+
v = Fraction(int(a), 10 ** s)
|
| 58 |
+
return str(v.numerator) if v.denominator == 1 else f'{int(a) / 10 ** s:.{s}f}'.rstrip('0').rstrip('.')
|
| 59 |
+
return expr
|
| 60 |
+
op = expr[0]
|
| 61 |
+
if op == '換單位':
|
| 62 |
+
return {'概念': '換算', '參數': [V(expr[1]), expr[2], expr[3]]}
|
| 63 |
+
return {'概念': op, '參數': [V(x) for x in expr[1:]]}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def neg(v):
|
| 67 |
+
if isinstance(v, str) and B.num(v) is not None:
|
| 68 |
+
return v[1:] if v.startswith('-') else '-' + v
|
| 69 |
+
return {'概念': '負', '參數': [v]}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def C(name, *args):
|
| 73 |
+
return {'概念': name, '參數': list(args)}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ---------------------------------------------------------------- 讀題狀態(只記讀題需要的:先行詞、存量單位、誰有起始量)
|
| 77 |
+
class InfoStory(E.Story):
|
| 78 |
+
def __init__(self, tree):
|
| 79 |
+
super().__init__(tree)
|
| 80 |
+
self.buf = [] # 這個子句產生的資訊句
|
| 81 |
+
self.out = [] # 全部資訊句
|
| 82 |
+
self.notes = []
|
| 83 |
+
self.mods = {} # 帳 → 第一次出現時的修飾詞(red ticket 的 red)
|
| 84 |
+
self.scope = {} # 帳 → 擁有句寫的容器範圍(in a drawer)
|
| 85 |
+
self._mods, self._scope, self._text = (), None, ''
|
| 86 |
+
|
| 87 |
+
def name(self, key):
|
| 88 |
+
"""帳的物名:錢 → dollar;量測 → 存量單位;一般物品 → 修飾詞+lemma(電腦Codex 12:46 ②:red ticket ≠ ticket ≠ blue ticket)。"""
|
| 89 |
+
who, item = key
|
| 90 |
+
if item == 'USD':
|
| 91 |
+
return 'dollar'
|
| 92 |
+
unit = self.units.get(key)
|
| 93 |
+
return unit or ' '.join(self.mods.get(key, ()) + (item,))
|
| 94 |
+
|
| 95 |
+
def register(self, key, scope=False):
|
| 96 |
+
"""新帳:記下這句的修飾詞(和擁有句的容器範圍)。"""
|
| 97 |
+
if key[1] != 'USD' and not self.units.get(key):
|
| 98 |
+
self.mods[key] = tuple(self._mods)
|
| 99 |
+
if scope and self._scope and self._scope != key[0]:
|
| 100 |
+
self.scope[key] = self._scope
|
| 101 |
+
|
| 102 |
+
def mention(self, key):
|
| 103 |
+
"""已有的帳再被提到:這句的修飾詞必須是帳的修飾詞的子集合(可以省略,不能多出或換掉)。"""
|
| 104 |
+
if key[1] == 'USD' or self.units.get(key):
|
| 105 |
+
return
|
| 106 |
+
extra = set(self._mods) - set(self.mods.get(key, ()))
|
| 107 |
+
if extra:
|
| 108 |
+
raise E.Refuse(f'修飾詞不符:{key[0]} 的 {self.name(key)} 不是 {" ".join(self._mods)} {key[1]}')
|
| 109 |
+
|
| 110 |
+
def emit(self, s):
|
| 111 |
+
self.buf.append(s)
|
| 112 |
+
|
| 113 |
+
# ---- 敘述
|
| 114 |
+
def op_擁有(self, s):
|
| 115 |
+
who = self.who(s['主體'])
|
| 116 |
+
item, unit = self.what(s['物'], s.get('量'))
|
| 117 |
+
key = (who, item)
|
| 118 |
+
if key in self.items:
|
| 119 |
+
raise E.Refuse('同一個量第二次給起始值')
|
| 120 |
+
n = self.amount(s['量'])
|
| 121 |
+
self.items[key], self.units[key] = n, unit
|
| 122 |
+
self.register(key, scope=True)
|
| 123 |
+
self.emit(C('擁有', who, self.name(key), V(n), '起'))
|
| 124 |
+
|
| 125 |
+
def op_變化(self, s):
|
| 126 |
+
who = self.who(s['主體'])
|
| 127 |
+
item, unit = self.what(s['物'], s.get('量'))
|
| 128 |
+
key = (who, item)
|
| 129 |
+
n = self.amount(s['量'])
|
| 130 |
+
if key not in self.items:
|
| 131 |
+
if any(it == item for it, _ in self.rates.values()):
|
| 132 |
+
raise E.Refuse('存量要從每組推導(程式腦 v0 的每組不接主體)')
|
| 133 |
+
if s.get('缺起點', '拒答') == '當起點' and s['方向'] == '加':
|
| 134 |
+
self.items[key], self.units[key] = n, unit
|
| 135 |
+
self.register(key)
|
| 136 |
+
self.emit(C('擁有', who, self.name(key), V(n), '起'))
|
| 137 |
+
self.notes.append(f'意思/增加 之前沒有存量 → 當起始量:{who}/{item}')
|
| 138 |
+
return
|
| 139 |
+
self.items[key], self.units[key] = None, unit # 起點未知:照寫變化,交程式腦
|
| 140 |
+
self.register(key)
|
| 141 |
+
else:
|
| 142 |
+
self.mention(key)
|
| 143 |
+
n = self.convert(n, unit, self.units.get(key))
|
| 144 |
+
self.items[key] = None
|
| 145 |
+
v = V(n)
|
| 146 |
+
self.emit(C('變化', who, self.name(key), v if s['方向'] == '加' else neg(v)))
|
| 147 |
+
|
| 148 |
+
def op_每組(self, s):
|
| 149 |
+
box = self.what(s['容器'], hint=['容器'])[0]
|
| 150 |
+
item, unit = self.what(s['物'], s.get('量'))
|
| 151 |
+
if box in self.rates:
|
| 152 |
+
raise E.Refuse('同一種容器第二個比率')
|
| 153 |
+
n = self.amount(s['量'])
|
| 154 |
+
self.rates[box] = (item, n)
|
| 155 |
+
self.emit(C('每組', box, 'dollar' if item == 'USD' else (unit or item), V(n)))
|
| 156 |
+
|
| 157 |
+
def op_均分(self, s):
|
| 158 |
+
who = self.who(s['主體'])
|
| 159 |
+
item, _ = self.what(s.get('物'), s.get('量'))
|
| 160 |
+
if self.share:
|
| 161 |
+
raise E.Refuse('第二次均分')
|
| 162 |
+
if s.get('量'):
|
| 163 |
+
total = V(self.amount(s['量']))
|
| 164 |
+
nm = 'dollar' if item == 'USD' else ' '.join(tuple(self._mods) + (item,))
|
| 165 |
+
else:
|
| 166 |
+
if (who, item) not in self.items:
|
| 167 |
+
raise E.Refuse('均分全部,但沒有存量')
|
| 168 |
+
self.mention((who, item))
|
| 169 |
+
nm = self.name((who, item))
|
| 170 |
+
total = C('擁有', who, nm, '—', '現在')
|
| 171 |
+
count = E.quantity(s['份數'])
|
| 172 |
+
if count == '1':
|
| 173 |
+
raise E.Refuse('一份不是均分')
|
| 174 |
+
recv = E.singular(s['受者'].split()[-1])
|
| 175 |
+
self.share = (who, item, total, count, recv)
|
| 176 |
+
self.emit(dict(C('均分', total, V(count), nm), _受者=recv))
|
| 177 |
+
|
| 178 |
+
def op_百分比減(self, s):
|
| 179 |
+
item = self.what(s['物'])[0] if s.get('物') else (self.last_item[0] if self.last_item else None)
|
| 180 |
+
if s.get('主體'):
|
| 181 |
+
key = (self.who(s['主體']), item)
|
| 182 |
+
else:
|
| 183 |
+
keys = self.holders(item)
|
| 184 |
+
if len(keys) != 1:
|
| 185 |
+
raise E.Refuse('百分比找不到唯一持有者')
|
| 186 |
+
key = keys[0]
|
| 187 |
+
if key not in self.items:
|
| 188 |
+
raise E.Refuse('百分比沒有已知存量')
|
| 189 |
+
self.mention(key)
|
| 190 |
+
self.items[key] = None
|
| 191 |
+
self.emit(C('變化', key[0], self.name(key), neg(C('比例份', '現在', '?', V(E.percent(s['百分']))))))
|
| 192 |
+
|
| 193 |
+
def holders(self, item):
|
| 194 |
+
return [k for k in self.items if k[1] == item]
|
| 195 |
+
|
| 196 |
+
# ---- 問句(只讀意思,不算值;算值交程式腦)
|
| 197 |
+
def op_問擁有(self, s):
|
| 198 |
+
item, unit = self.what(s['物'], hint=['物品', '單位'])
|
| 199 |
+
if s.get('主體'):
|
| 200 |
+
key = (self.who(s['主體']), item)
|
| 201 |
+
subj = key[0]
|
| 202 |
+
else:
|
| 203 |
+
keys = self.holders(item)
|
| 204 |
+
if len(keys) != 1:
|
| 205 |
+
raise E.Refuse('沒指明主體,持有者不唯一')
|
| 206 |
+
key, subj = keys[0], '—'
|
| 207 |
+
if key[0] not in self.people + self.places:
|
| 208 |
+
raise E.Refuse('問的主體沒在題目出現')
|
| 209 |
+
if key not in self.items:
|
| 210 |
+
raise E.Refuse(f'問的量找不到:{key[0]} 的 {key[1]}')
|
| 211 |
+
self.mention(key)
|
| 212 |
+
if key in self.scope and not re.search(rf"\b{re.escape(self.scope[key])}", self._text):
|
| 213 |
+
# 電腦Codex 12:46 ③:「40 tickets in a drawer」只說抽屜裡的,問「Mina 總共有幾張」不能當全部
|
| 214 |
+
raise E.Refuse(f'容器範圍:{key[0]} 的 {self.name(key)} 只寫了 {self.scope[key]} 裡的')
|
| 215 |
+
q = C('擁有', subj, self.name(key), '?', '現在')
|
| 216 |
+
have = self.units.get(key)
|
| 217 |
+
if unit and have and unit != have:
|
| 218 |
+
q = C('換算', q, have, unit)
|
| 219 |
+
self.emit(C('問題', q))
|
| 220 |
+
return True
|
| 221 |
+
|
| 222 |
+
def op_問總和(self, s):
|
| 223 |
+
item, _ = self.what(s['物'])
|
| 224 |
+
names = [self.who(x) for x in s['主體們'] if x]
|
| 225 |
+
if names and len(set(names)) != len(names):
|
| 226 |
+
raise E.Refuse('總和重複主體')
|
| 227 |
+
keys = [(n, item) for n in names] if names else self.holders(item)
|
| 228 |
+
for k in keys:
|
| 229 |
+
if k not in self.items:
|
| 230 |
+
raise E.Refuse(f'問的量找不到:{k[0]} 的 {k[1]}')
|
| 231 |
+
self.mention(k)
|
| 232 |
+
if k in self.scope:
|
| 233 |
+
raise E.Refuse(f'容器範圍:{k[0]} 的 {self.name(k)} 只寫了 {self.scope[k]} 裡的')
|
| 234 |
+
shown = {self.name(k) for k in keys}
|
| 235 |
+
if len(shown) != 1:
|
| 236 |
+
raise E.Refuse(f'總和的物名不一致:{sorted(shown)}')
|
| 237 |
+
nm = shown.pop()
|
| 238 |
+
self.emit(C('問題', C('部分整體', '?', names if names else '全部', nm)))
|
| 239 |
+
return True
|
| 240 |
+
|
| 241 |
+
def op_問每份(self, s):
|
| 242 |
+
if not self.share:
|
| 243 |
+
raise E.Refuse('問每份但沒有均分')
|
| 244 |
+
who, item, total, count, recv = self.share
|
| 245 |
+
if s.get('物') and self.what(s['物'])[0] != item:
|
| 246 |
+
raise E.Refuse('問的物品跟均分的不同')
|
| 247 |
+
if E.singular(s['受者'].split()[-1]) != recv:
|
| 248 |
+
raise E.Refuse('問的受者跟均分的不同')
|
| 249 |
+
self.emit(dict(C('問題', C('除', total, V(count))), _每份=recv))
|
| 250 |
+
return True
|
| 251 |
+
|
| 252 |
+
# ---- 一個子句
|
| 253 |
+
def clause(self, kind, text, stats, used):
|
| 254 |
+
picked = self.t.choose(kind, text, stats)
|
| 255 |
+
if picked is None:
|
| 256 |
+
return None
|
| 257 |
+
leaf, g, hits = picked
|
| 258 |
+
# 電腦Codex 12:46 ④:代名詞只有唯一候選才可解。連結條件把「非唯一的 him」當成非已知人物,
|
| 259 |
+
# 會把 Frances gave him 4 more 讀成 Frances 減少;任何槽是代名詞而候選不唯一就不讀。
|
| 260 |
+
for k, v in g.items():
|
| 261 |
+
if isinstance(v, str) and re.sub(r'^(?:the|a|an) ', '', v) in E.PRONOUNS and len(self.people) != 1:
|
| 262 |
+
raise E.Refuse(f'代名詞「{v}」候選不唯一({len(self.people)} 人)')
|
| 263 |
+
m = leaf['_rx'].fullmatch(text)
|
| 264 |
+
self._text, self._mods, self._scope = text, (), None
|
| 265 |
+
if m is not None and m.groupdict().get('物'):
|
| 266 |
+
if TIME_WORD.fullmatch(m['物'].split()[-1]):
|
| 267 |
+
raise E.Refuse(f'物品槽吃到時間詞「{m["物"]}」')
|
| 268 |
+
before = text[:m.start('物')].split()[-2:]
|
| 269 |
+
mods = []
|
| 270 |
+
for w in reversed(before):
|
| 271 |
+
if w in MOD_STOP or re.match(r'^\$?\d', w) or w in E.SMALL or w in E.PRONOUNS or self.t.lex.lookup(w):
|
| 272 |
+
break
|
| 273 |
+
mods.insert(0, w)
|
| 274 |
+
self._mods = tuple(mods)
|
| 275 |
+
sc = SCOPE_RX.match(text[m.end('物'):])
|
| 276 |
+
if sc and sc[1] not in SCOPE_OK:
|
| 277 |
+
self._scope = E.singular(sc[1])
|
| 278 |
+
meaning, g = self.resolve(leaf, g)
|
| 279 |
+
node = self.t.nodes[meaning]
|
| 280 |
+
used.append({'子句': text, '葉子': leaf['id'], '意思': meaning, '同句命中': hits})
|
| 281 |
+
n0 = len(self.buf)
|
| 282 |
+
for op in node['輸出']:
|
| 283 |
+
spec = {k: self.val(v, g) for k, v in op.items()}
|
| 284 |
+
getattr(self, 'op_' + op['op'])(spec)
|
| 285 |
+
new = self.buf[n0:]
|
| 286 |
+
if meaning == '意思/轉移' and len(new) == 2 and all(x['概念'] in ('變化', '擁有') for x in new):
|
| 287 |
+
# 給方減、收方加 → 一句 移轉(收方原本沒有起始量也照寫,程式腦會建未知起點)
|
| 288 |
+
give, take = new
|
| 289 |
+
if give['概念'] != '變化':
|
| 290 |
+
raise E.Refuse('轉移的給方沒有起始量')
|
| 291 |
+
amount = take['參數'][2]
|
| 292 |
+
if take['概念'] == '擁有':
|
| 293 |
+
raise E.Refuse('轉移收方被當成起始量')
|
| 294 |
+
del self.buf[n0:]
|
| 295 |
+
self.emit(C('移轉', give['參數'][0], take['參數'][0], give['參數'][1], amount))
|
| 296 |
+
for x in self.buf[n0:]:
|
| 297 |
+
x['_葉子'] = leaf['id']
|
| 298 |
+
return True
|
| 299 |
+
|
| 300 |
+
def snapshot(self):
|
| 301 |
+
return copy.deepcopy({k: getattr(self, k) for k in
|
| 302 |
+
('items', 'units', 'attrs', 'rates', 'share', 'people', 'places', 'last_item',
|
| 303 |
+
'mods', 'scope')})
|
| 304 |
+
|
| 305 |
+
def restore(self, snap):
|
| 306 |
+
for k, v in snap.items():
|
| 307 |
+
setattr(self, k, v)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
MOD_STOP = {'of', 'the', 'a', 'an', 'his', 'her', 'their', 'its', 'my', 'our', 'your', 'more', 'many', 'much', 'how',
|
| 311 |
+
'some', 'all', 'and', 'than', 'each', 'every', 'those', 'these', 'that', 'this', 'other', 'extra', 'total',
|
| 312 |
+
'number', 'dozen', 'away', 'them', 'it', 'another', 'with', 'to', 'from', 'in', 'on', 'at', 'for', 'into'}
|
| 313 |
+
TIME_WORD = re.compile(r'yesterday|today|tomorrow|tonight|morning|afternoon|evening|night|day|week|month|year|'
|
| 314 |
+
r'monday|tuesday|wednesday|thursday|friday|saturday|sunday|weekend|ago|earlier|before|later')
|
| 315 |
+
TIME_RX = re.compile(r'\b(?:yesterday|today|tomorrow|tonight|ago|earlier|previously|before|last (?:week|month|year|night|'
|
| 316 |
+
r'time|weekend|monday|tuesday|wednesday|thursday|friday|saturday|sunday)|next \w+|this (?:morning|'
|
| 317 |
+
r'afternoon|evening|week|month|year)|in the (?:morning|afternoon|evening)|on (?:monday|tuesday|'
|
| 318 |
+
r'wednesday|thursday|friday|saturday|sunday))\b')
|
| 319 |
+
PRESENT_RX = re.compile(r'\b(?:has|have|owns|own|is|are|holds|keeps|contains)\b')
|
| 320 |
+
SCOPE_RX = re.compile(r' (?:in|inside|on|at|into) (?:a|an|the|his|her|their|its|my|our|each) ([a-z]+)')
|
| 321 |
+
SCOPE_OK = {'all', 'total', 'collection', 'beginning', 'start', 'end', 'morning', 'afternoon', 'evening', 'first'}
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def time_guard(sents):
|
| 325 |
+
"""電腦Codex 12:46 ①:題目有現在式的擁有(Mina has 40)又有帶日期的事件(lost 3 yesterday)時,
|
| 326 |
+
不知道事件在觀察之前還是之後 → 帶日期的事件句改成未讀(帶數字,G1 會讓整題拒答)。"""
|
| 327 |
+
present = any(s['概念'] == '擁有' and PRESENT_RX.search(s['原文']) and not TIME_RX.search(s['原文'])
|
| 328 |
+
for s in sents)
|
| 329 |
+
if not present:
|
| 330 |
+
return sents
|
| 331 |
+
out, done = [], set()
|
| 332 |
+
for s in sents:
|
| 333 |
+
if s['概念'] in ('變化', '移轉', '擁有', '比例份', '均分') and TIME_RX.search(s['原文']) and not \
|
| 334 |
+
(s['概念'] == '擁有' and PRESENT_RX.search(s['原文'])):
|
| 335 |
+
if s['句號'] not in done:
|
| 336 |
+
done.add(s['句號'])
|
| 337 |
+
why = f'時間邊界:現在式擁有+帶日期的事件「{TIME_RX.search(s["原文"])[0]}」'
|
| 338 |
+
out.append(dict(unread(s['原文'], why), 原文=s['原文'], 句號=s['句號'], 出處='逐字'))
|
| 339 |
+
continue
|
| 340 |
+
out.append(s)
|
| 341 |
+
return out
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def unread(text, why):
|
| 345 |
+
return C('未讀', text, why)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# 題目明確給出三站、兩段等距車程和中站停留時,三個時間分開保留。
|
| 349 |
+
_STATION_VALUE = r'(?P<value>[0-9]+(?:\.[0-9]+)?)'
|
| 350 |
+
_STATION_UNIT = r'(?P<unit>hours?|minutes?)'
|
| 351 |
+
_STATION_SPACING = re.compile(
|
| 352 |
+
rf'(?:three|3) train stations are {_STATION_VALUE} {_STATION_UNIT} apart(?: from (?:one another|each other))?'
|
| 353 |
+
)
|
| 354 |
+
_STATION_TRIP = re.compile(
|
| 355 |
+
r'(?P<actor>[a-z]+(?: [a-z]+)*) travels? from the first station to the third(?: station)?,? '
|
| 356 |
+
rf'taking (?:a )?{_STATION_VALUE}[ -]{_STATION_UNIT} (?:break|rest) at the second station'
|
| 357 |
+
)
|
| 358 |
+
_STATION_QUESTION = re.compile(
|
| 359 |
+
r"what(?:'s| is) the total time,? in minutes,? that (?P<actor>[a-z]+(?: [a-z]+)*) "
|
| 360 |
+
r'takes? to travel between the first(?: station)? and (?:the )?third station\?'
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _station_reading(facts, question):
|
| 365 |
+
if len(facts) != 2 or 'train stations' not in facts[0]:
|
| 366 |
+
return None
|
| 367 |
+
spacing = _STATION_SPACING.fullmatch(facts[0])
|
| 368 |
+
trip = _STATION_TRIP.fullmatch(facts[1])
|
| 369 |
+
query = _STATION_QUESTION.fullmatch(question)
|
| 370 |
+
if not (spacing and trip and query and trip['actor'] == query['actor']):
|
| 371 |
+
return None
|
| 372 |
+
legs = ('first-second', 'second-third')
|
| 373 |
+
unit = spacing['unit'].rstrip('s')
|
| 374 |
+
rest_unit = trip['unit'].rstrip('s')
|
| 375 |
+
actor = trip['actor']
|
| 376 |
+
|
| 377 |
+
def sourced(row, index, text):
|
| 378 |
+
return dict(row, 原文=text, 句號=index, 出處='逐字')
|
| 379 |
+
|
| 380 |
+
def minutes(owner, source_unit):
|
| 381 |
+
amount = C('擁有', owner, source_unit, '?', '—')
|
| 382 |
+
return amount if source_unit == 'minute' else C('換算', amount, source_unit, 'minute')
|
| 383 |
+
|
| 384 |
+
rows = [
|
| 385 |
+
sourced(C('擁有', leg, unit, spacing['value'], '—'), 1, facts[0])
|
| 386 |
+
for leg in legs
|
| 387 |
+
]
|
| 388 |
+
rows.append(sourced(C('擁有', actor, rest_unit, trip['value'], '—'), 2, facts[1]))
|
| 389 |
+
total = C('加', *(minutes(leg, unit) for leg in legs), minutes(actor, rest_unit))
|
| 390 |
+
rows.append(sourced(C('問題', total), 3, question))
|
| 391 |
+
return rows
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def read(question, tree=None):
|
| 395 |
+
"""題目 → {'資訊句': [物件…], '英文式': [字串…], '子句': n, '讀懂': n, '拒答': 理由或 None}。"""
|
| 396 |
+
tree = tree or E.default_tree()
|
| 397 |
+
out = {'題目': question, '資訊句': [], '英文式': [], '子句': 0, '讀懂': 0, '走過': [], '拒答': None}
|
| 398 |
+
text = E.normalize(question)
|
| 399 |
+
if len(text) > 2000 or text.count('?') != 1 or not text.endswith('?'):
|
| 400 |
+
out['拒答'] = '不是一個問句結尾的應用題'
|
| 401 |
+
return out
|
| 402 |
+
*facts, final = E.split_clauses(text)
|
| 403 |
+
if not 1 <= len(facts) <= MAX_FACTS:
|
| 404 |
+
out['拒答'] = f'敘述句數不在 1~{MAX_FACTS}'
|
| 405 |
+
return out
|
| 406 |
+
station_rows = _station_reading(facts, final)
|
| 407 |
+
if station_rows is not None:
|
| 408 |
+
return dict(out, 資訊句=station_rows, 英文式=P.render(station_rows, '英'),
|
| 409 |
+
子句=len(facts), 讀懂=len(facts), 走過=['車站區間'], 備註=[])
|
| 410 |
+
st = InfoStory(tree)
|
| 411 |
+
sents = []
|
| 412 |
+
for i, f in enumerate(facts, 1):
|
| 413 |
+
f = tree.lead.sub('', f).strip(' ,')
|
| 414 |
+
out['子句'] += 1
|
| 415 |
+
snap, used = st.snapshot(), []
|
| 416 |
+
st.buf = []
|
| 417 |
+
why = None
|
| 418 |
+
try:
|
| 419 |
+
if st.clause('敘述', f, None, used) is None:
|
| 420 |
+
pieces = re.split(r',? and ', f)
|
| 421 |
+
if len(pieces) != 2:
|
| 422 |
+
why = '沒有葉子認得'
|
| 423 |
+
else:
|
| 424 |
+
st.buf = []
|
| 425 |
+
for x in pieces:
|
| 426 |
+
if st.clause('敘述', x, None, used) is None:
|
| 427 |
+
why = '沒有葉子認得(and 拆兩半也不行)'
|
| 428 |
+
break
|
| 429 |
+
except (E.Refuse, KeyError, ValueError, TypeError) as e:
|
| 430 |
+
why = str(e) if isinstance(e, E.Refuse) else f'內部錯誤:{type(e).__name__} {e}'
|
| 431 |
+
if not why:
|
| 432 |
+
why = numbers_eaten(f, st.buf)
|
| 433 |
+
if why:
|
| 434 |
+
st.restore(snap)
|
| 435 |
+
sents.append(dict(unread(f, why), 原文=f, 句號=i, 出處='逐字'))
|
| 436 |
+
else:
|
| 437 |
+
out['讀懂'] += 1
|
| 438 |
+
out['走過'] += used
|
| 439 |
+
sents += [dict(x, 原文=f, 句號=i, 出處='逐字') for x in st.buf]
|
| 440 |
+
q = tree.lead.sub('', final.rstrip('?')).strip(' ,')
|
| 441 |
+
st.buf = []
|
| 442 |
+
used = []
|
| 443 |
+
try:
|
| 444 |
+
if st.clause('問句', q, None, used) is None:
|
| 445 |
+
out['拒答'] = f'沒有問句葉子認得:「{q}」'
|
| 446 |
+
except (E.Refuse, KeyError, ValueError, TypeError) as e:
|
| 447 |
+
out['拒答'] = '問句:' + (str(e) if isinstance(e, E.Refuse) else f'內部錯誤 {type(e).__name__} {e}')
|
| 448 |
+
if out['拒答'] is None:
|
| 449 |
+
out['走過'] += used
|
| 450 |
+
sents += [dict(x, 原文=q + '?', 句號=len(facts) + 1, 出處='逐字') for x in st.buf]
|
| 451 |
+
sents = time_guard(sents)
|
| 452 |
+
out['資訊句'] = sents
|
| 453 |
+
out['英文式'] = P.render([{k: v for k, v in s.items() if not k.startswith('_')} for s in sents], '英')
|
| 454 |
+
out['備註'] = st.notes
|
| 455 |
+
return out
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
# ---------------------------------------------------------------- 守門(量測後加;不改程式腦,只在交程式腦之前多擋)
|
| 459 |
+
NUMWORD = sorted({k for k in list(B.WORDNUM) + list(B.ORDINAL) if k not in ('a', 'an', 'single')}, key=len, reverse=True)
|
| 460 |
+
QTYWORD = ('half', 'twice', 'double', 'triple', 'some', 'several', 'few', 'many', 'all', 'none', 'another', 'extra',
|
| 461 |
+
'more', 'less', 'fewer', 'rest', 'remaining', 'left', 'each', 'every', 'per')
|
| 462 |
+
NUM_RX = re.compile(r'\$?\d[\d,]*(?:\.\d+)?\s*(?:%|percent)?|\b(?:' + '|'.join(NUMWORD) + r')\b')
|
| 463 |
+
QTY_RX = re.compile(r'\b(?:' + '|'.join(QTYWORD) + r')\b')
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def unread_guard(sents):
|
| 467 |
+
"""G1(ASDiv nluds-2136「made nine extra」):程式腦 _mentions 只看阿拉伯數字;數詞(nine)、量詞(extra、more…)
|
| 468 |
+
的未讀句也可能改所求 → 一律算有關,拒答。"""
|
| 469 |
+
for s in sents:
|
| 470 |
+
if s['概念'] == '未讀':
|
| 471 |
+
t = s['原文']
|
| 472 |
+
m = NUM_RX.search(t) or QTY_RX.search(t)
|
| 473 |
+
if m:
|
| 474 |
+
return f'未讀句帶數量「{m[0].strip()}」:「{t}」'
|
| 475 |
+
return None
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def clause_numbers(text):
|
| 479 |
+
out = []
|
| 480 |
+
for m in NUM_RX.finditer(text):
|
| 481 |
+
w = m[0].strip()
|
| 482 |
+
if re.match(r'^\$?\d', w):
|
| 483 |
+
pct = w.endswith(('%', 'percent'))
|
| 484 |
+
n = Fraction(re.sub(r'[^\d.]', '', w.replace('percent', '')))
|
| 485 |
+
out.append(n / 100 if pct else n)
|
| 486 |
+
elif w in B.ORDINAL:
|
| 487 |
+
out.append(Fraction(1, B.ORDINAL[w]))
|
| 488 |
+
elif w in B.WORDNUM:
|
| 489 |
+
out.append(Fraction(B.WORDNUM[w]))
|
| 490 |
+
return out
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def numbers_eaten(text, sents):
|
| 494 |
+
"""G2(ASDiv nluds-2145「walked nine miles on monday and nine more on tuesday」:句尾片段 {尾} 把第二個量吞掉):
|
| 495 |
+
子句裡每個數(含數詞、百分比)都要對到這個子句資訊句裡的一個字面值(多重集合),否則整句當未讀。"""
|
| 496 |
+
vals = []
|
| 497 |
+
|
| 498 |
+
def lits(p): # 自己收字面數(不靠程式腦 literal_values:它會把 mul(3, 12) 收成 36、換算收成一對)
|
| 499 |
+
if isinstance(p, dict):
|
| 500 |
+
for x in p.get('參數', []):
|
| 501 |
+
lits(x)
|
| 502 |
+
elif isinstance(p, list):
|
| 503 |
+
for x in p:
|
| 504 |
+
lits(x)
|
| 505 |
+
elif isinstance(p, str) and B.num(p) is not None:
|
| 506 |
+
vals.append(abs(B.num(p)))
|
| 507 |
+
for s in sents:
|
| 508 |
+
lits(s)
|
| 509 |
+
for n in clause_numbers(text):
|
| 510 |
+
hit = next((i for i, v in enumerate(vals) if v == n), None)
|
| 511 |
+
if hit is None:
|
| 512 |
+
return f'子句的數 {n} 沒有讀進資訊句'
|
| 513 |
+
vals.pop(hit)
|
| 514 |
+
return None
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def lower(sents):
|
| 518 |
+
"""交程式腦前的展開(程式腦 v0 沒有 c_均分):均分(整體,份數,物)→ 比例份(整體,受者,1/份數);
|
| 519 |
+
問每份 → 問題(擁有(受者,—,?,現在))。展開只換成表裡已有的概念,不新增名字。"""
|
| 520 |
+
out = []
|
| 521 |
+
for s in sents:
|
| 522 |
+
if s['概念'] == '均分':
|
| 523 |
+
whole, count, item = s['參數']
|
| 524 |
+
out.append(dict(s, 概念='比例份', 參數=[whole, s['_受者'], f'1/{count}']))
|
| 525 |
+
elif s['概念'] == '問題' and s.get('_每份'):
|
| 526 |
+
out.append(dict(s, 參數=[C('擁有', s['_每份'], '—', '?', '現在')]))
|
| 527 |
+
else:
|
| 528 |
+
out.append(s)
|
| 529 |
+
return out
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def solve(question, tree=None):
|
| 533 |
+
"""讀題 → 英文式資訊句 → 解析.parse → 程式腦.solve。回 read() 的結果加 'brain'、'prefix'、'value'。"""
|
| 534 |
+
r = read(question, tree)
|
| 535 |
+
r['prefix'] = r['value'] = None
|
| 536 |
+
if r['拒答']:
|
| 537 |
+
return r
|
| 538 |
+
why = unread_guard(r['資訊句'])
|
| 539 |
+
if why:
|
| 540 |
+
r['拒答'] = '守門 G1:' + why
|
| 541 |
+
return r
|
| 542 |
+
r['交程式腦'] = P.render([{k: v for k, v in s.items() if not k.startswith('_')} for s in lower(r['資訊句'])], '英')
|
| 543 |
+
parsed = P.parse(r['交程式腦'])
|
| 544 |
+
bad = [p for p in parsed if p['概念'] == '未讀' and str(p['參數'][1]).startswith('未讀:格式')]
|
| 545 |
+
if bad:
|
| 546 |
+
r['拒答'] = f'資訊句格式錯:{bad[0]["參數"]}'
|
| 547 |
+
return r
|
| 548 |
+
try:
|
| 549 |
+
b = B.solve(parsed)
|
| 550 |
+
except Exception as e: # 程式腦內部錯誤一律當拒答
|
| 551 |
+
r['拒答'] = f'程式腦內部錯誤:{type(e).__name__} {e}'
|
| 552 |
+
return r
|
| 553 |
+
r['brain'] = {k: b.get(k) for k in ('status', 'value', 'prefix', '拒答原因', '方程', '走法')}
|
| 554 |
+
if b['status'] == 'ok':
|
| 555 |
+
r['prefix'], r['value'] = b['prefix'], b['value']
|
| 556 |
+
else:
|
| 557 |
+
r['拒答'] = '程式腦:' + str(b['拒答原因'])
|
| 558 |
+
return r
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
# ---------------------------------------------------------------- 量測
|
| 562 |
+
def same(v, gold):
|
| 563 |
+
try:
|
| 564 |
+
return v not in (None, 'invalid') and Fraction(str(v)) == Fraction(str(gold).replace(',', ''))
|
| 565 |
+
except (ValueError, ZeroDivisionError):
|
| 566 |
+
return False
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def measure(limit=None):
|
| 570 |
+
sys.dont_write_bytecode = True
|
| 571 |
+
sys.path.insert(0, r"H:\Codex用\work\gsm8k-g1m3-wave68-20261125")
|
| 572 |
+
import real_set_audit as R
|
| 573 |
+
import evaluate as EV
|
| 574 |
+
bank = HERE.parent / '題集'
|
| 575 |
+
src = {"GSM8K-train": EV.TRAIN, "SVAMP": bank / "SVAMP/SVAMP.json", "ASDiv": bank / "ASDiv/ASDiv.xml",
|
| 576 |
+
"MAWPS": bank / "MAWPS/calc-mawps_original-splits.jsonl"}
|
| 577 |
+
tree = E.default_tree()
|
| 578 |
+
report, ex = {}, {'一致': [], '救回': [], '新錯': [], '原對值不同': [], '原對拒答': []}
|
| 579 |
+
concept_count, refuse_why = {}, {}
|
| 580 |
+
for name, path in src.items():
|
| 581 |
+
r = dict.fromkeys(['題數', '原對', '原錯', '原拒', '原對_資訊同', '原對_資訊不同', '原對_資訊拒',
|
| 582 |
+
'原錯_資訊同錯', '原錯_資訊對', '原錯_資訊拒', '原錯_資訊另錯',
|
| 583 |
+
'原拒_救回', '原拒_新錯', '原拒_資訊拒', '子句', '子句讀懂', '問句讀懂'], 0)
|
| 584 |
+
for k, (rid, q, gold) in enumerate(R.rows(name, path)):
|
| 585 |
+
if limit and k >= limit:
|
| 586 |
+
break
|
| 587 |
+
r['題數'] += 1
|
| 588 |
+
a = E.trace(q, tree)
|
| 589 |
+
av = E.value(a['en'], tree.lex) if a['en'] else None
|
| 590 |
+
b = solve(q, tree)
|
| 591 |
+
r['子句'] += b['子句']
|
| 592 |
+
r['子句讀懂'] += b['讀懂']
|
| 593 |
+
r['問句讀懂'] += any(s['概念'] == '問題' for s in b['資訊句'])
|
| 594 |
+
for s in b['資訊句']:
|
| 595 |
+
concept_count[s['概念']] = concept_count.get(s['概念'], 0) + 1
|
| 596 |
+
bo = b['value'] is not None
|
| 597 |
+
bok = bo and same(b['value'], gold)
|
| 598 |
+
rec = {'庫': name, 'id': rid, '題目': q, '原前綴': a['en'], '原值': None if av is None else str(av),
|
| 599 |
+
'資訊句': b['英文式'], '前綴': b['prefix'], '值': b['value'], '標答': str(gold), '拒答': b['拒答']}
|
| 600 |
+
if a['en'] is not None and same(av, gold):
|
| 601 |
+
r['原對'] += 1
|
| 602 |
+
if bo and same(b['value'], av):
|
| 603 |
+
r['原對_資訊同'] += 1
|
| 604 |
+
if len(ex['一致']) < 40:
|
| 605 |
+
ex['一致'].append(rec)
|
| 606 |
+
elif bo:
|
| 607 |
+
r['原對_資訊不同'] += 1
|
| 608 |
+
ex['原對值不同'].append(rec)
|
| 609 |
+
else:
|
| 610 |
+
r['原對_資訊拒'] += 1
|
| 611 |
+
why = re.sub(r'[::].*', '', b['拒答'] or '')[:40]
|
| 612 |
+
refuse_why[why] = refuse_why.get(why, 0) + 1
|
| 613 |
+
if len(ex['原對拒答']) < 60:
|
| 614 |
+
ex['原對拒答'].append(rec)
|
| 615 |
+
elif a['en'] is not None:
|
| 616 |
+
r['原錯'] += 1
|
| 617 |
+
if not bo:
|
| 618 |
+
r['原錯_資訊拒'] += 1
|
| 619 |
+
elif bok:
|
| 620 |
+
r['原錯_資訊對'] += 1
|
| 621 |
+
ex['救回'].append(rec)
|
| 622 |
+
elif same(b['value'], av):
|
| 623 |
+
r['原錯_資訊同錯'] += 1
|
| 624 |
+
ex['新錯'].append(dict(rec, 類='原錯同錯'))
|
| 625 |
+
else:
|
| 626 |
+
r['原錯_資訊另錯'] += 1
|
| 627 |
+
ex['新錯'].append(dict(rec, 類='原錯另錯'))
|
| 628 |
+
else:
|
| 629 |
+
r['原拒'] += 1
|
| 630 |
+
if not bo:
|
| 631 |
+
r['原拒_資訊拒'] += 1
|
| 632 |
+
elif bok:
|
| 633 |
+
r['原拒_救回'] += 1
|
| 634 |
+
ex['救回'].append(rec)
|
| 635 |
+
else:
|
| 636 |
+
r['原拒_新錯'] += 1
|
| 637 |
+
ex['新錯'].append(dict(rec, 類='原拒新錯'))
|
| 638 |
+
report[name] = r
|
| 639 |
+
print(name, json.dumps(r, ensure_ascii=False), flush=True)
|
| 640 |
+
res = {'說明': '原 engine.trace vs 資訊句路(規則樹葉子→英文式資訊句→解析.parse→程式腦.solve);'
|
| 641 |
+
'GSM8K train 走 real_set_audit.rows(排除盲測等保留題)', '結果': report,
|
| 642 |
+
'資訊句概念次數': concept_count, '原對但資訊句拒答的理由': refuse_why, '例子': ex}
|
| 643 |
+
(HERE / '報告' / '資訊句輸出-四庫-20261125.json').write_text(
|
| 644 |
+
json.dumps(res, ensure_ascii=False, indent=1), encoding='utf-8')
|
| 645 |
+
return res
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
if __name__ == '__main__':
|
| 649 |
+
if len(sys.argv) > 1 and sys.argv[1] == '量':
|
| 650 |
+
measure(int(sys.argv[2]) if len(sys.argv) > 2 else None)
|
| 651 |
+
elif len(sys.argv) > 1:
|
| 652 |
+
r = solve(sys.argv[1])
|
| 653 |
+
for s in r['英文式']:
|
| 654 |
+
print(' ', s)
|
| 655 |
+
print('前綴', r['prefix'], '值', r['value'], '拒答', r['拒答'])
|
| 656 |
+
if r.get('brain'):
|
| 657 |
+
print('方程', r['brain'].get('方程'))
|
hs/語法模組/資訊句/讀法修補.py
ADDED
|
@@ -0,0 +1,830 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""讀法修補 v0(#350,Claude子代理(#350 讀法修補器)2026-11-27)。
|
| 2 |
+
|
| 3 |
+
使用者 11-27 06:53:「程式多一個功能,幫忙把錯一點的ai嘗試改對,這樣解題力應該強很多」;06:49:「變數字還能讀才算」。
|
| 4 |
+
位置:模型寫的資訊句 → 【這裡】 → 解析+程式腦+全部既有守門。只在一讀「被擋下」(status≠ok)時才試;
|
| 5 |
+
產生候選修補讀法,各自重跑 build(數字出處/角色/格式守門)→ 程式腦 → 答案層守門(缺一塊全掃.evaluate:
|
| 6 |
+
字面數沒用到、非整數、語意守門、v7 守門)。不改 讀題_LLM.py/解析.py/程式腦.py。
|
| 7 |
+
|
| 8 |
+
修補動作(開關 _REPAIR_FORCE[id]=0 關掉):
|
| 9 |
+
R1 缺單位補位(照電腦Codex 06:58 隔離區 時段引用省略單位 的條件,不放寬):ask 裡的 時段 引用單位是「?」
|
| 10 |
+
(或三參數 duration(主體, 活動, ?) 被解析成 duration(主體, —, 活動, ?))→ 同主體+同活動恰好一筆有出處的時段、
|
| 11 |
+
單位是時間單位 → 沿用;整個算式(加減/convert 串)換算後單位一致,且問句恰好問一個時間單位、跟它相同才收。
|
| 12 |
+
R2 自算數字還原:那句資訊句的數字不在原文(數字無出處),但=同一句原文某數 ×(單位模組換算因子,原文緊跟該數的單位
|
| 13 |
+
→ 該值所在槽的單位)→ 改回原文數並包 convert(原數, 原單位, 目標單位)。
|
| 14 |
+
R3 引用對齊:ask 引用(擁有/時段/數量/成本/目標)跟事實句對不上(謂詞不同 have↔duration、槽位錯),題內找
|
| 15 |
+
同主詞+描述槽重疊最大且「唯一」的事實,照那條事實的謂詞與參數順序改寫引用(值槽 ?)。速率不改(分子分母反過來是倒數)。
|
| 16 |
+
R4 時點補齊:擁有 的時點是「—」或與原文時間詞矛盾 → 照原文 originally/initially/at first…→ start、
|
| 17 |
+
now/left/remaining/still…→ now(基本概念表 指代:原本→第一版、now/rest/remaining→目前版);兩組詞都出現 → 不動。
|
| 18 |
+
放行規矩:每個開著的動作子集(固定順序 R2→R4→R1→R3 疊加)都算一個候選;所有成功候選答案相同才放行,否則拒「修補多義」。
|
| 19 |
+
每個修補記證據(原文哪個詞/數、依據哪條事實)。修補後新出現的數必須在該句原文允許數內、新出現的詞必須是原讀法已有的詞
|
| 20 |
+
(R2 的單位詞要在原文)——不新增原文沒有的數字或角色。
|
| 21 |
+
|
| 22 |
+
import 讀法修補 as M; M.setup()
|
| 23 |
+
M.修補(sents, [(1, "duration(kira, break, 30, minute)."), (2, "ask(...).")]) → {"status", "value", "修補", "候選", ...}
|
| 24 |
+
|
| 25 |
+
量測(0 元、只用已存讀法):python -B -X utf8 讀法修補.py 量 [--批 A B C]
|
| 26 |
+
"""
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import copy
|
| 30 |
+
import itertools
|
| 31 |
+
import json
|
| 32 |
+
import re
|
| 33 |
+
import sys
|
| 34 |
+
from fractions import Fraction
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
|
| 37 |
+
HERE = Path(__file__).resolve().parent
|
| 38 |
+
sys.path.insert(0, str(HERE))
|
| 39 |
+
|
| 40 |
+
# 預設照 11-27 量測(讀法修補\result.json,一打五:救 ≥5 且淨正才開):R3 救 16/新錯 3 → 開;R2 救 4/新錯 1 → 關(救不到 5);
|
| 41 |
+
# R4 救 0/新錯 2 → 關;R1 開發題 0 變化(電腦Codex 同口徑 5,997 題也 0 差異),只修 Kira 型缺單位,零成本 → 開。
|
| 42 |
+
_REPAIR_FORCE = {"R1": 1, "R2": 0, "R3": 1, "R4": 0}
|
| 43 |
+
順序 = ("R2", "R4", "R1", "R3")
|
| 44 |
+
分支上限 = 8
|
| 45 |
+
OUTD = HERE / "讀法修補"
|
| 46 |
+
WHO = "Claude子代理(#350 讀法修補器)"
|
| 47 |
+
|
| 48 |
+
S = R = B = None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def setup():
|
| 52 |
+
"""用 缺一塊全掃 的環境(HEAD 程式腦、v7 守門、語意守門、斷網)。"""
|
| 53 |
+
global S, R, B
|
| 54 |
+
import 缺一塊全掃 as _S
|
| 55 |
+
if _S.R is None:
|
| 56 |
+
_S.setup()
|
| 57 |
+
S, R, B = _S, _S.R, _S.B
|
| 58 |
+
return S
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ------------------------------------------------------------------ 讀寫一行
|
| 62 |
+
def 讀行(body):
|
| 63 |
+
"""模型寫的一行(英文式)→ 未補預設的結構(照模型寫的參數個數);壞掉回 None。"""
|
| 64 |
+
P = R.解析
|
| 65 |
+
b = (body or "").strip().strip("`").strip()
|
| 66 |
+
if not b:
|
| 67 |
+
return None
|
| 68 |
+
k = P._body_end(b)
|
| 69 |
+
try:
|
| 70 |
+
s, rest = P._expr(P._en_to_zh_punct(b[:k]), True)
|
| 71 |
+
except Exception:
|
| 72 |
+
return None
|
| 73 |
+
if rest.strip() or not isinstance(s, dict):
|
| 74 |
+
return None
|
| 75 |
+
return s
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def 寫行(s):
|
| 79 |
+
return R.解析._one(s, True) + "."
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def 完整(s):
|
| 83 |
+
t = copy.deepcopy(s)
|
| 84 |
+
try:
|
| 85 |
+
return None if R.解析.check(t) else t
|
| 86 |
+
except Exception:
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def W(x):
|
| 91 |
+
return B.word(x) if isinstance(x, str) and x not in B.NONE and x != "?" and B.num(x) is None else None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _atoms(x, out):
|
| 95 |
+
if isinstance(x, dict):
|
| 96 |
+
for y in x.get("參數", []):
|
| 97 |
+
_atoms(y, out)
|
| 98 |
+
elif isinstance(x, list):
|
| 99 |
+
for y in x:
|
| 100 |
+
_atoms(y, out)
|
| 101 |
+
elif isinstance(x, str):
|
| 102 |
+
w = W(x)
|
| 103 |
+
if w and x not in ("起", "現在", "全部"):
|
| 104 |
+
out.add(w)
|
| 105 |
+
return out
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _lits(x):
|
| 109 |
+
return R.literals(x)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ------------------------------------------------------------------ 評一個讀法
|
| 113 |
+
_評快取 = {}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def 評(sents, lines):
|
| 117 |
+
"""lines:[(句號, 行)] → build(全部守門)→ evaluate(程式腦+答案層守門)。"""
|
| 118 |
+
key = (tuple(sents), tuple(lines))
|
| 119 |
+
if key in _評快取:
|
| 120 |
+
return _評快取[key]
|
| 121 |
+
reply = "\n".join(f"#{n}: {b}" for n, b in lines)
|
| 122 |
+
try:
|
| 123 |
+
objs, rows = R.build(sents, reply)
|
| 124 |
+
e = S.evaluate(sents, objs)
|
| 125 |
+
except RecursionError:
|
| 126 |
+
e, rows = {"status": "refused", "value": None, "拒答原因": "例外:解析遞迴", "lines": [], "objs": []}, []
|
| 127 |
+
e = {"status": e["status"], "value": e.get("value"), "拒答原因": e.get("拒答原因"), "lines": e.get("lines") or []}
|
| 128 |
+
if len(_評快取) > 30000:
|
| 129 |
+
_評快取.clear()
|
| 130 |
+
_評快取[key] = e
|
| 131 |
+
return e
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
_過守門快取 = {}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def 過守門(sents, n, body):
|
| 138 |
+
"""這一行單獨 build 會不會被擋(數字出處/格式/角色)。"""
|
| 139 |
+
key = (tuple(sents), n, body)
|
| 140 |
+
if key not in _過守門快取:
|
| 141 |
+
try:
|
| 142 |
+
_, rows = R.build(sents, f"#{n}: {body}")
|
| 143 |
+
_過守門快取[key] = bool(rows) and not rows[0].get("守門")
|
| 144 |
+
except RecursionError:
|
| 145 |
+
_過守門快取[key] = False
|
| 146 |
+
return _過守門快取[key]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def 事實(sents, lines):
|
| 150 |
+
"""過了 build 守門的事實行(不含 ask/unread):[(i, 句號, 完整結構)]。"""
|
| 151 |
+
out = []
|
| 152 |
+
for i, (n, b) in enumerate(lines):
|
| 153 |
+
if not 1 <= n <= len(sents):
|
| 154 |
+
continue
|
| 155 |
+
s = 讀行(b)
|
| 156 |
+
if not s or s["概念"] in ("問題", "未讀"):
|
| 157 |
+
continue
|
| 158 |
+
f = 完整(s)
|
| 159 |
+
if f and 過守門(sents, n, b):
|
| 160 |
+
out.append((i, n, f))
|
| 161 |
+
return out
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _換(s, path, new):
|
| 165 |
+
"""回 s 的拷貝,path(參數索引序列)位置換成 new。"""
|
| 166 |
+
t = copy.deepcopy(s)
|
| 167 |
+
x = t
|
| 168 |
+
for k in path[:-1]:
|
| 169 |
+
x = x["參數"][k] if isinstance(x, dict) else x[k]
|
| 170 |
+
if isinstance(x, dict):
|
| 171 |
+
x["參數"][path[-1]] = new
|
| 172 |
+
else:
|
| 173 |
+
x[path[-1]] = new
|
| 174 |
+
return t
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _走(x, path=()):
|
| 178 |
+
"""(path, 節點) 走全部 dict 節點。"""
|
| 179 |
+
if isinstance(x, dict):
|
| 180 |
+
yield path, x
|
| 181 |
+
for k, y in enumerate(x.get("參數", [])):
|
| 182 |
+
yield from _走(y, path + (k,))
|
| 183 |
+
elif isinstance(x, list):
|
| 184 |
+
for k, y in enumerate(x):
|
| 185 |
+
yield from _走(y, path + (k,))
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------------ R1 缺單位補位(照電腦Codex restore_duration_units 條件)
|
| 189 |
+
def gen_R1(sents, lines):
|
| 190 |
+
facts = 事實(sents, lines)
|
| 191 |
+
durs = [(n, f) for _, n, f in facts if f["概念"] == "時段"]
|
| 192 |
+
out = []
|
| 193 |
+
for i, (n, b) in enumerate(lines):
|
| 194 |
+
if not 1 <= n <= len(sents):
|
| 195 |
+
continue
|
| 196 |
+
s = 讀行(b)
|
| 197 |
+
if not s or s["概念"] != "問題" or not s.get("參數"):
|
| 198 |
+
continue
|
| 199 |
+
q = 完整(s)
|
| 200 |
+
if not q:
|
| 201 |
+
continue
|
| 202 |
+
fixes = []
|
| 203 |
+
|
| 204 |
+
def inspect(node):
|
| 205 |
+
if not isinstance(node, dict):
|
| 206 |
+
return node, None
|
| 207 |
+
c, a = node["概念"], node.get("參數", [])
|
| 208 |
+
if c == "時段":
|
| 209 |
+
if len(a) != 4:
|
| 210 |
+
return node, None
|
| 211 |
+
who, act, length, unit = a
|
| 212 |
+
if unit == "?":
|
| 213 |
+
if node.get("變種") == 3 and act in B.NONE:
|
| 214 |
+
act, length = length, "?"
|
| 215 |
+
if length != "?" or not all(isinstance(x, str) and x not in B.NONE and B.num(x) is None
|
| 216 |
+
and not B.is_unknown(x) for x in (who, act)):
|
| 217 |
+
return node, None
|
| 218 |
+
hits = [(fn, f) for fn, f in durs if (B.word(f["參數"][0]), B.word(f["參數"][1])) == (B.word(who), B.word(act))]
|
| 219 |
+
if len(hits) != 1:
|
| 220 |
+
return node, None
|
| 221 |
+
fn, f = hits[0]
|
| 222 |
+
u = B.word(f["參數"][3]) if isinstance(f["參數"][3], str) else None
|
| 223 |
+
if u not in B.TIME_UNITS:
|
| 224 |
+
return node, None
|
| 225 |
+
fixes.append({"引用": f"duration({who}, …, ?)", "補單位": u, "依據事實": 寫行(f), "事實句號": fn,
|
| 226 |
+
"原文": sents[fn - 1]})
|
| 227 |
+
nn = {"概念": "時段", "參數": [who, act, "?", u]}
|
| 228 |
+
return nn, u
|
| 229 |
+
u = B.word(unit) if isinstance(unit, str) else None
|
| 230 |
+
return node, u if u in B.TIME_UNITS else None
|
| 231 |
+
if c == "換算" and len(a) == 3:
|
| 232 |
+
child, u = inspect(a[0])
|
| 233 |
+
frm, dest = a[1:]
|
| 234 |
+
if u and isinstance(frm, str) and isinstance(dest, str) and B.same_unit(u, frm) and B.word(dest) in B.TIME_UNITS:
|
| 235 |
+
return dict(node, 參數=[child, frm, dest]), B.word(dest)
|
| 236 |
+
return dict(node, 參數=[child, frm, dest]), None
|
| 237 |
+
if c in ("加", "減") and len(a) >= 2:
|
| 238 |
+
children, units = zip(*(inspect(t) for t in a))
|
| 239 |
+
if units[0] and all(x and B.same_unit(x, units[0]) for x in units):
|
| 240 |
+
return dict(node, 參數=list(children)), units[0]
|
| 241 |
+
return dict(node, 參數=list(children)), None
|
| 242 |
+
return node, None
|
| 243 |
+
|
| 244 |
+
fixed, unit = inspect(q["參數"][0])
|
| 245 |
+
if not fixes or not unit:
|
| 246 |
+
continue
|
| 247 |
+
text = (sents[n - 1] or "").lower()
|
| 248 |
+
asked = {B.word(m) for m in re.findall(r"\b(?:how many|in)\s+([a-z]+)\b", text) if B.word(m) in B.TIME_UNITS}
|
| 249 |
+
if len(asked) != 1 or not B.same_unit(unit, next(iter(asked))):
|
| 250 |
+
continue
|
| 251 |
+
new = {"概念": "問題", "參數": [fixed]}
|
| 252 |
+
L = list(lines)
|
| 253 |
+
L[i] = (n, 寫行(new))
|
| 254 |
+
out.append((L, {"動作": "R1", "句號": n, "原行": b, "新行": L[i][1], "證據": fixes,
|
| 255 |
+
"問句單位": next(iter(asked))}))
|
| 256 |
+
return out
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# ------------------------------------------------------------------ R2 自算數字還原
|
| 260 |
+
_NUMW = {k: v for k, v in {"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7,
|
| 261 |
+
"eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "half": Fraction(1, 2)}.items()}
|
| 262 |
+
_PAIR = re.compile(r"(\$?)(\d[\d,]*(?:\.\d+)?|\b(?:a|an|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|half)\b)"
|
| 263 |
+
r"[\s-]*(?:and a half\s+)?([A-Za-z]+)", re.I)
|
| 264 |
+
_FILL = {"of", "more", "less", "fewer", "times", "and", "to", "in", "on", "at", "for", "per", "each", "the", "a", "an", "than"}
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def 原文數單位(src):
|
| 268 |
+
"""原句的(數, 緊跟的單位詞, 原字);$5 → (5, dollar)。"""
|
| 269 |
+
out = []
|
| 270 |
+
for m in _PAIR.finditer(src):
|
| 271 |
+
g = m.group(2)
|
| 272 |
+
try:
|
| 273 |
+
v = Fraction(g.replace(",", "")) if g[0].isdigit() else Fraction(_NUMW[g.lower()])
|
| 274 |
+
except Exception:
|
| 275 |
+
continue
|
| 276 |
+
noun = "dollar" if m.group(1) else m.group(3).lower()
|
| 277 |
+
if noun in _FILL:
|
| 278 |
+
continue
|
| 279 |
+
out.append((v, B.word(noun), m.group(0)))
|
| 280 |
+
return out
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def _因子(frm, to):
|
| 284 |
+
try:
|
| 285 |
+
f = Fraction(B.gm.units.convert(1, frm, to, B._uctx())["value"])
|
| 286 |
+
return f if f not in (0, 1) else None
|
| 287 |
+
except Exception:
|
| 288 |
+
return None
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def _槽單位(node, k):
|
| 292 |
+
"""node 的第 k 參數是值時,它的單位詞(讀題_LLM.VALUE_UNIT 同一張表)。"""
|
| 293 |
+
for vi, ui in R.VALUE_UNIT.get(node["概念"], []):
|
| 294 |
+
if vi == k:
|
| 295 |
+
if ui == "$":
|
| 296 |
+
return "dollar"
|
| 297 |
+
a = node.get("參數", [])
|
| 298 |
+
return a[ui] if ui < len(a) and isinstance(a[ui], str) else None
|
| 299 |
+
return None
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def gen_R2(sents, lines):
|
| 303 |
+
out_alts = []
|
| 304 |
+
for i, (n, b) in enumerate(lines):
|
| 305 |
+
if not 1 <= n <= len(sents):
|
| 306 |
+
continue
|
| 307 |
+
if 過守門(sents, n, b):
|
| 308 |
+
continue
|
| 309 |
+
s = 讀行(b)
|
| 310 |
+
if not s or s["概念"] in ("未讀",):
|
| 311 |
+
continue
|
| 312 |
+
f = 完整(s)
|
| 313 |
+
if not f:
|
| 314 |
+
continue
|
| 315 |
+
src = sents[n - 1]
|
| 316 |
+
allow = R.allowed_numbers(src)
|
| 317 |
+
pairs = 原文數單位(src)
|
| 318 |
+
bad = [] # (path, x, 該槽單位)
|
| 319 |
+
for path, node in _走(f):
|
| 320 |
+
for k, y in enumerate(node.get("參數", [])):
|
| 321 |
+
if isinstance(y, str) and B.num(y) is not None and B.num(y) not in allow:
|
| 322 |
+
bad.append((path + (k,), B.num(y), _槽單位(node, k)))
|
| 323 |
+
if not bad:
|
| 324 |
+
continue
|
| 325 |
+
per = []
|
| 326 |
+
for path, x, su in bad:
|
| 327 |
+
alts = set()
|
| 328 |
+
# 目標單位只用「該值所在槽」的單位(11-27 量測:拿行內任意單位會湊出巧合,train-2798 every other day 的 1/2
|
| 329 |
+
# 被當成 12 hour→day;ask 裡無槽的 24 也不還原)
|
| 330 |
+
tos = [B.word(su)] if su and W(su) else []
|
| 331 |
+
for y, frm, raw in pairs:
|
| 332 |
+
if not frm or y not in allow:
|
| 333 |
+
continue
|
| 334 |
+
for to in dict.fromkeys(tos):
|
| 335 |
+
if not to or B.same_unit(frm, to):
|
| 336 |
+
continue
|
| 337 |
+
fac = _因子(frm, to)
|
| 338 |
+
if fac is not None and y * fac == x:
|
| 339 |
+
alts.add((str(y), frm, to, raw.strip()))
|
| 340 |
+
if not alts:
|
| 341 |
+
per = None
|
| 342 |
+
break
|
| 343 |
+
per.append([(path, x, a) for a in sorted(alts)])
|
| 344 |
+
if not per:
|
| 345 |
+
continue
|
| 346 |
+
for combo in itertools.islice(itertools.product(*per), 分支上限):
|
| 347 |
+
t = f
|
| 348 |
+
ev = []
|
| 349 |
+
for path, x, (y, frm, to, raw) in combo:
|
| 350 |
+
t = _換(t, path, {"概念": "換算", "參數": [y, frm, to]})
|
| 351 |
+
ev.append({"數": str(x), "還原": f"convert({y}, {frm}, {to})", "原文詞": raw, "因子": str(_因子(frm, to))})
|
| 352 |
+
L = list(lines)
|
| 353 |
+
L[i] = (n, 寫行(t))
|
| 354 |
+
out_alts.append((i, L[i], {"動作": "R2", "句號": n, "原行": b, "新行": L[i][1], "證據": ev, "原文": src}))
|
| 355 |
+
if not out_alts:
|
| 356 |
+
return []
|
| 357 |
+
# 每行各自的候選;多行時取各行第一候選疊加 + 每行單獨(分支)
|
| 358 |
+
by_line = {}
|
| 359 |
+
for i, ln, ev in out_alts:
|
| 360 |
+
by_line.setdefault(i, []).append((ln, ev))
|
| 361 |
+
res = []
|
| 362 |
+
keys = sorted(by_line)
|
| 363 |
+
for combo in itertools.islice(itertools.product(*[by_line[k] for k in keys]), 分支上限):
|
| 364 |
+
L = list(lines)
|
| 365 |
+
evs = []
|
| 366 |
+
for k, (ln, ev) in zip(keys, combo):
|
| 367 |
+
L[k] = ln
|
| 368 |
+
evs.append(ev)
|
| 369 |
+
res.append((L, {"動作": "R2", "行": evs}))
|
| 370 |
+
return res
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# ------------------------------------------------------------------ R3 引用對齊
|
| 374 |
+
槽 = { # 概念: (主體位, 描述位, 值位)
|
| 375 |
+
"擁有": (0, (1,), 2), "時段": (0, (1, 3), 2), "成本": (0, (1,), 2), "目標": (0, (1,), 2), "進度": (0, (1,), 2),
|
| 376 |
+
"數量": (None, (1, 2), 0),
|
| 377 |
+
}
|
| 378 |
+
_帳概念 = {"擁有": [(0, 1)], "變化": [(0, 1)], "移轉": [(0, 2), (1, 2)], "購買": [(0, 1)], "賣出": [(0, 1)],
|
| 379 |
+
"遺失": [(0, 1)], "目標": [(0, 1)], "進度": [(0, 1)]}
|
| 380 |
+
_標準時點 = ("起", "現在", "—", "-", None, "")
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _描述詞(f):
|
| 384 |
+
c = f["概念"]
|
| 385 |
+
sp, ds, vp = 槽[c]
|
| 386 |
+
a = f["參數"]
|
| 387 |
+
w = {W(a[k]) for k in ds if k < len(a)}
|
| 388 |
+
if c == "擁有" and len(a) > 3 and a[3] not in _標準時點:
|
| 389 |
+
w.add(W(a[3])) # 模型把活動塞在時點槽(have(kira, minute, 30, break))
|
| 390 |
+
return {x for x in w if x}
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _對得上(node, facts):
|
| 394 |
+
c, a = node["概念"], node["參數"]
|
| 395 |
+
if c == "擁有":
|
| 396 |
+
who, it = W(a[0]), W(a[1])
|
| 397 |
+
for _, _, f in facts:
|
| 398 |
+
for p, q in _帳概念.get(f["概念"], []):
|
| 399 |
+
fa = f["參數"]
|
| 400 |
+
if (who is None or W(fa[p]) == who) and (it is None or W(fa[q]) == it):
|
| 401 |
+
return True
|
| 402 |
+
return False
|
| 403 |
+
sp, ds, vp = 槽[c]
|
| 404 |
+
for _, _, f in facts:
|
| 405 |
+
if f["概念"] != c:
|
| 406 |
+
continue
|
| 407 |
+
fa = f["參數"]
|
| 408 |
+
if sp is not None and W(a[sp]) and W(fa[sp]) != W(a[sp]):
|
| 409 |
+
continue
|
| 410 |
+
if all(W(a[k]) is None or W(a[k]) == W(fa[k]) for k in ds if c != "時段" or k == 1):
|
| 411 |
+
return True
|
| 412 |
+
return False
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def gen_R3(sents, lines):
|
| 416 |
+
facts = 事實(sents, lines)
|
| 417 |
+
cands = [(n, f) for _, n, f in facts if f["概念"] in 槽]
|
| 418 |
+
res = []
|
| 419 |
+
for i, (n, b) in enumerate(lines):
|
| 420 |
+
if not 1 <= n <= len(sents):
|
| 421 |
+
continue
|
| 422 |
+
s = 讀行(b)
|
| 423 |
+
if not s or s["概念"] != "問題":
|
| 424 |
+
continue
|
| 425 |
+
q = 完整(s)
|
| 426 |
+
if not q:
|
| 427 |
+
continue
|
| 428 |
+
cur = q
|
| 429 |
+
evs = []
|
| 430 |
+
for path, node in list(_走(q)):
|
| 431 |
+
if node is q or node["概念"] not in 槽:
|
| 432 |
+
continue
|
| 433 |
+
c, a = node["概念"], node["參數"]
|
| 434 |
+
sp, ds, vp = 槽[c]
|
| 435 |
+
if vp >= len(a) or a[vp] != "?" or _對得上(node, facts):
|
| 436 |
+
continue
|
| 437 |
+
who = W(a[sp]) if sp is not None else None
|
| 438 |
+
if sp is not None and not who:
|
| 439 |
+
continue
|
| 440 |
+
nw = {W(a[k]) for k in ds if k < len(a)} | ({W(a[3])} if c == "擁有" and len(a) > 3 and a[3] not in _標準時點 else set())
|
| 441 |
+
nw = {x for x in nw if x and x != who}
|
| 442 |
+
if not nw:
|
| 443 |
+
continue
|
| 444 |
+
best, picks = 0, []
|
| 445 |
+
for fn, f in cands:
|
| 446 |
+
fa = f["參數"]
|
| 447 |
+
fsp = 槽[f["概念"]][0]
|
| 448 |
+
if sp is not None and (fsp is None or W(fa[fsp]) != who):
|
| 449 |
+
continue
|
| 450 |
+
if sp is None and fsp is not None:
|
| 451 |
+
continue
|
| 452 |
+
sc = len(nw & _描述詞(f))
|
| 453 |
+
if sc and sc > best:
|
| 454 |
+
best, picks = sc, [(fn, f)]
|
| 455 |
+
elif sc and sc == best:
|
| 456 |
+
picks.append((fn, f))
|
| 457 |
+
if not picks:
|
| 458 |
+
continue
|
| 459 |
+
news = {}
|
| 460 |
+
for fn, f in picks:
|
| 461 |
+
fa = list(f["參數"])
|
| 462 |
+
fvp = 槽[f["概念"]][2]
|
| 463 |
+
fa[fvp] = "?"
|
| 464 |
+
if f["概念"] == "擁有":
|
| 465 |
+
fa[3] = a[3] if c == "擁有" and a[3] in _標準時點 else "—"
|
| 466 |
+
nn = {"概念": f["概念"], "參數": fa}
|
| 467 |
+
news.setdefault(寫行(nn), (nn, fn, f))
|
| 468 |
+
if len(news) != 1:
|
| 469 |
+
continue # 多條同分事實 → 不猜
|
| 470 |
+
(txt, (nn, fn, f)), = news.items()
|
| 471 |
+
if txt == 寫行({"概念": c, "參數": a}):
|
| 472 |
+
continue
|
| 473 |
+
cur = _換(cur, path, nn)
|
| 474 |
+
evs.append({"引用": 寫行({"概念": c, "參數": a})[:-1], "改成": txt[:-1], "依據事實": 寫行(f)[:-1],
|
| 475 |
+
"事實句號": fn, "重疊詞": sorted(nw & _描述詞(f)), "原文": sents[fn - 1]})
|
| 476 |
+
if evs:
|
| 477 |
+
L = list(lines)
|
| 478 |
+
L[i] = (n, 寫行(cur))
|
| 479 |
+
res.append((L, {"動作": "R3", "句號": n, "原行": b, "新行": L[i][1], "證據": evs}))
|
| 480 |
+
if len(res) > 1: # 多個 ask 行各自改:疊在一起當一個候選
|
| 481 |
+
L = list(lines)
|
| 482 |
+
for Lx, ev in res:
|
| 483 |
+
k = next(j for j, (x, y) in enumerate(lines) if y == ev["原行"])
|
| 484 |
+
L[k] = Lx[k]
|
| 485 |
+
return [(L, {"動作": "R3", "行": [ev for _, ev in res]})]
|
| 486 |
+
return res
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
# ------------------------------------------------------------------ R4 時點補齊
|
| 490 |
+
_起 = re.compile(r"\b(originally|initially|at first|at the (?:start|beginning)|to begin with|in the beginning|"
|
| 491 |
+
r"started (?:out )?with|starts (?:out )?with|began with|begins with)\b", re.I)
|
| 492 |
+
# left 只收「剩下」用法(has/have/are… left、left over);「left early」=離開(11-27 量測新錯 train-1031)
|
| 493 |
+
_今 = re.compile(r"\b(now|(?:has|have|had|is|are|was|were|be) (?:\w+ )?left|left over|leftover|remaining|remain|remains|still|"
|
| 494 |
+
r"currently|in the end)\b", re.I)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def 時點線索(src):
|
| 498 |
+
a, b = bool(_起.search(src or "")), bool(_今.search(src or ""))
|
| 499 |
+
if a == b:
|
| 500 |
+
return None, None
|
| 501 |
+
m = (_起 if a else _今).search(src)
|
| 502 |
+
return ("起" if a else "現在"), m.group(0)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def gen_R4(sents, lines):
|
| 506 |
+
L = list(lines)
|
| 507 |
+
evs = []
|
| 508 |
+
for i, (n, b) in enumerate(lines):
|
| 509 |
+
if not 1 <= n <= len(sents):
|
| 510 |
+
continue
|
| 511 |
+
s = 讀行(b)
|
| 512 |
+
if not s:
|
| 513 |
+
continue
|
| 514 |
+
f = 完整(s)
|
| 515 |
+
if not f or f["概念"] == "未讀":
|
| 516 |
+
continue
|
| 517 |
+
want, cue = 時點線索(sents[n - 1])
|
| 518 |
+
if not want:
|
| 519 |
+
continue
|
| 520 |
+
cur, ch = f, []
|
| 521 |
+
targets = [((), f)] if f["概念"] == "擁有" else \
|
| 522 |
+
[(p, x) for p, x in _走(f) if x["概念"] == "擁有" and f["概念"] == "問題" and x is not f]
|
| 523 |
+
for p, x in targets:
|
| 524 |
+
t = x["參數"][3] if len(x["參數"]) > 3 else "—"
|
| 525 |
+
if t in ("—", "-") or (t == "起" and want == "現在") or (t == "現在" and want == "起"):
|
| 526 |
+
if t == want:
|
| 527 |
+
continue
|
| 528 |
+
nx = dict(x, 參數=list(x["參數"][:3]) + [want])
|
| 529 |
+
cur = nx if p == () else _換(cur, p, nx)
|
| 530 |
+
ch.append({"引用": 寫行(x)[:-1], "時點": f"{t} → {'start' if want == '起' else 'now'}", "原文詞": cue})
|
| 531 |
+
if ch:
|
| 532 |
+
L[i] = (n, 寫行(cur))
|
| 533 |
+
evs.append({"句號": n, "原行": b, "新行": L[i][1], "證據": ch, "原文": sents[n - 1]})
|
| 534 |
+
return [(L, {"動作": "R4", "行": evs})] if evs else []
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
GEN = {"R1": gen_R1, "R2": gen_R2, "R3": gen_R3, "R4": gen_R4}
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
# ------------------------------------------------------------------ 新增檢查:不新增原文沒有的數字或角色
|
| 541 |
+
def 沒新增(sents, old, new):
|
| 542 |
+
oldset = set(old)
|
| 543 |
+
old_atoms = set()
|
| 544 |
+
for _, b in old:
|
| 545 |
+
s = 讀行(b)
|
| 546 |
+
if s:
|
| 547 |
+
_atoms(s, old_atoms)
|
| 548 |
+
text = " ".join(sents).lower()
|
| 549 |
+
for n, b in new:
|
| 550 |
+
if (n, b) in oldset:
|
| 551 |
+
continue
|
| 552 |
+
s = 讀行(b)
|
| 553 |
+
if not s:
|
| 554 |
+
return "新行讀不懂"
|
| 555 |
+
allow = R.allowed_numbers(sents[n - 1])
|
| 556 |
+
bad = [x for x in _lits(s) if x not in allow]
|
| 557 |
+
if bad:
|
| 558 |
+
return f"新增原文沒有的數:{bad[0]}"
|
| 559 |
+
for w in _atoms(s, set()) - old_atoms:
|
| 560 |
+
if not re.search(rf"\b{re.escape(w)}", text):
|
| 561 |
+
return f"新增原文沒有的詞:{w}"
|
| 562 |
+
return None
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
# ------------------------------------------------------------------ 主入口
|
| 566 |
+
def 修補(sents, lines, 開=None, base=None):
|
| 567 |
+
"""sents:原文斷句;lines:[(句號, 模型寫的行)];開:{R1..R4: 0/1}(None=_REPAIR_FORCE)。
|
| 568 |
+
回 {"status": ok/refused/未修, "value", "拒答原因", "修補": 採用的候選證據, "候選": [...]}。"""
|
| 569 |
+
sw = dict(_REPAIR_FORCE, **(開 or {}))
|
| 570 |
+
on = [k for k in 順序 if sw.get(k)]
|
| 571 |
+
lines = [(int(n), b) for n, b in lines if b]
|
| 572 |
+
base = base or 評(sents, lines)
|
| 573 |
+
if base["status"] == "ok":
|
| 574 |
+
return {"status": "未修", "value": base["value"], "拒答原因": None, "修補": None, "候選": [], "基準": base}
|
| 575 |
+
seen, cands = {tuple(lines)}, []
|
| 576 |
+
for r in range(1, len(on) + 1):
|
| 577 |
+
for sub in itertools.combinations(on, r):
|
| 578 |
+
frontier = [(lines, [])]
|
| 579 |
+
for act in sub:
|
| 580 |
+
nxt = []
|
| 581 |
+
for L, ev in frontier:
|
| 582 |
+
for L2, e2 in GEN[act](sents, L):
|
| 583 |
+
if L2 != L:
|
| 584 |
+
nxt.append((L2, ev + [e2]))
|
| 585 |
+
frontier = nxt[:分支上限]
|
| 586 |
+
if not frontier:
|
| 587 |
+
break
|
| 588 |
+
for L, ev in frontier:
|
| 589 |
+
if tuple(L) in seen:
|
| 590 |
+
continue
|
| 591 |
+
seen.add(tuple(L))
|
| 592 |
+
cands.append({"動作": list(sub), "lines": L, "證據": ev})
|
| 593 |
+
out = []
|
| 594 |
+
for c in cands:
|
| 595 |
+
why = 沒新增(sents, lines, c["lines"])
|
| 596 |
+
if why:
|
| 597 |
+
c.update(status="refused", value=None, 拒答原因=why)
|
| 598 |
+
else:
|
| 599 |
+
e = 評(sents, c["lines"])
|
| 600 |
+
c.update(status=e["status"], value=e.get("value"), 拒答原因=e.get("拒答原因"), 資訊句=e.get("lines"))
|
| 601 |
+
out.append(c)
|
| 602 |
+
ok = [c for c in out if c["status"] == "ok"]
|
| 603 |
+
if not ok:
|
| 604 |
+
return {"status": "refused", "value": None, "拒答原因": base.get("拒答原因"), "修補": None, "候選": out,
|
| 605 |
+
"基準": base}
|
| 606 |
+
vals = {Fraction(str(c["value"])) for c in ok}
|
| 607 |
+
if len(vals) > 1:
|
| 608 |
+
return {"status": "refused", "value": None, "拒答原因": "修補多義:" + "/".join(sorted(str(v) for v in vals)),
|
| 609 |
+
"修補": None, "候選": out, "基準": base}
|
| 610 |
+
use = min(ok, key=lambda c: len(c["動作"]))
|
| 611 |
+
return {"status": "ok", "value": str(vals.pop()), "拒答原因": None, "修補": use, "候選": out, "基準": base}
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def 從rows(rows):
|
| 615 |
+
return [(r["n"], r["行"]) for r in rows or [] if r.get("行")]
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
# ------------------------------------------------------------------ 量測
|
| 619 |
+
模式 = {"全關": {k: 0 for k in 順序}, **{k: {j: int(j == k) for j in 順序} for k in 順序}, "全開": {k: 1 for k in 順序}}
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def _分類(jo, jn):
|
| 623 |
+
return {("拒", "對"): "救", ("拒", "錯"): "新錯", ("對", "錯"): "變錯", ("對", "拒"): "變拒",
|
| 624 |
+
("錯", "對"): "錯→對", ("錯", "拒"): "擋下舊錯", ("錯", "錯"): "錯→錯"}.get((jo, jn))
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def _修一讀(sents, x):
|
| 628 |
+
"""一讀 → {模式: (status, value, 修補證據)};ok 的讀不動。"""
|
| 629 |
+
lines = 從rows(x.get("rows"))
|
| 630 |
+
if x["status"] == "ok":
|
| 631 |
+
return {m: ("ok", x["value"], None) for m in 模式}
|
| 632 |
+
base = 評(sents, lines)
|
| 633 |
+
res = {}
|
| 634 |
+
for m, sw in 模式.items():
|
| 635 |
+
if m == "全關":
|
| 636 |
+
res[m] = (base["status"], base.get("value"), None)
|
| 637 |
+
continue
|
| 638 |
+
r = 修補(sents, lines, sw, base)
|
| 639 |
+
st = "ok" if r["status"] in ("ok", "未修") else "refused"
|
| 640 |
+
res[m] = (st, r["value"] if st == "ok" else None, r if r["status"] == "ok" else
|
| 641 |
+
({"多義": r["拒答原因"]} if str(r["拒答原因"] or "").startswith("修補多義") else None))
|
| 642 |
+
return res
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def _例(pid, q, x, r, gold):
|
| 646 |
+
u = r["修補"]
|
| 647 |
+
return {"題號": pid, "原文": q, "模型資訊句": [b for _, b in 從rows(x.get("rows"))], "拒因": r["基準"].get("拒答原因"),
|
| 648 |
+
"修補動作": u["動作"], "證據": u["證據"], "修補後資訊句": [b for _, b in u["lines"]], "程式腦答": r["value"],
|
| 649 |
+
"標答": gold, "判": S.judge(r["value"], gold)}
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def 量A():
|
| 653 |
+
import pickle
|
| 654 |
+
import 範圍守門
|
| 655 |
+
PR = pickle.loads(S.PKL.read_bytes())
|
| 656 |
+
ids = [p for p, P in PR.items() if 範圍守門.可用(p, P["q"])]
|
| 657 |
+
target = {p for p in ids if PR[p]["基準"]["寬"]["status"] != "ok"}
|
| 658 |
+
final = {} # pid -> {模式: (status, value)}
|
| 659 |
+
ev = {}
|
| 660 |
+
for k, p in enumerate(sorted(ids, key=lambda s: int(s.split("-")[-1])), 1):
|
| 661 |
+
P = PR[p]
|
| 662 |
+
reads = {}
|
| 663 |
+
for src, s in P["源"].items():
|
| 664 |
+
for v in ("A", "B"):
|
| 665 |
+
x = s.get(v)
|
| 666 |
+
if x is not None and S.real(x):
|
| 667 |
+
reads[(src, v)] = _修一讀(P["句"], x)
|
| 668 |
+
per = {}
|
| 669 |
+
for m in 模式:
|
| 670 |
+
P2 = {"源": {}}
|
| 671 |
+
for src, s in P["源"].items():
|
| 672 |
+
d = {}
|
| 673 |
+
for v in ("A", "B"):
|
| 674 |
+
x = s.get(v)
|
| 675 |
+
if x is None:
|
| 676 |
+
d[v] = None
|
| 677 |
+
elif (src, v) in reads:
|
| 678 |
+
st, val, _ = reads[(src, v)][m]
|
| 679 |
+
d[v] = dict(x, status=st, value=val, 拒答原因=x.get("拒答原因") if st != "ok" else None)
|
| 680 |
+
else:
|
| 681 |
+
d[v] = x
|
| 682 |
+
P2["源"][src] = d
|
| 683 |
+
f = S.problem_final(P2, "寬")
|
| 684 |
+
per[m] = (f["status"], f.get("value"))
|
| 685 |
+
final[p] = per
|
| 686 |
+
ev[p] = {kk: vv for kk, vv in reads.items()}
|
| 687 |
+
if k % 1000 == 0:
|
| 688 |
+
print(f"A {k}/{len(ids)}", flush=True)
|
| 689 |
+
return final, ev, target, {p: PR[p]["q"] for p in ids}, {p: PR[p] for p in ids}
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def 量B():
|
| 693 |
+
import pickle
|
| 694 |
+
import ZeroGPU讀題對照 as Z
|
| 695 |
+
import shutil
|
| 696 |
+
import tempfile
|
| 697 |
+
R0 = Z.setup()
|
| 698 |
+
tmp = Path(tempfile.mkdtemp(prefix="讀法修補_qwen_")) / "快取.jsonl"
|
| 699 |
+
src_cache = HERE / "ZeroGPU讀題對照_快取.jsonl"
|
| 700 |
+
if src_cache.exists():
|
| 701 |
+
shutil.copy(src_cache, tmp)
|
| 702 |
+
R0.CACHE, R0._cache = tmp, None # 不寫別人的快取檔
|
| 703 |
+
PR = pickle.loads(S.PKL.read_bytes())
|
| 704 |
+
ids = Z.pick(R0, PR, 600)
|
| 705 |
+
Z.load_replies()
|
| 706 |
+
out = {}
|
| 707 |
+
for p in ids:
|
| 708 |
+
P = PR[p]
|
| 709 |
+
if Z.prompt_of(R0, P) not in Z.REPLIES:
|
| 710 |
+
continue
|
| 711 |
+
try:
|
| 712 |
+
x = S.slim(R0.read_once_ext(p, "A", P["句"]))
|
| 713 |
+
except RecursionError:
|
| 714 |
+
continue
|
| 715 |
+
out[p] = (P["句"], x, P["q"])
|
| 716 |
+
return out
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
_數詞 = re.compile(r"\b(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|twenty|thirty|forty|fifty|hundred|"
|
| 720 |
+
r"dozen|twice|double|triple|thrice|half|third|quarter|fourth|fifth)\b", re.I)
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def 量C():
|
| 724 |
+
F = HERE / "變形題"
|
| 725 |
+
rows = {json.loads(l)["id"]: json.loads(l) for l in (F / "變形題.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()}
|
| 726 |
+
done = json.loads((F / "ds讀結果.json").read_text(encoding="utf-8"))
|
| 727 |
+
out, drop = {}, []
|
| 728 |
+
for i, d in done.items():
|
| 729 |
+
r = rows[i]
|
| 730 |
+
if d.get("err"):
|
| 731 |
+
continue
|
| 732 |
+
if r["型"] == "a" and [m.lower() for m in _數詞.findall(r["q"])] != [m.lower() for m in _數詞.findall(r["原q"])]:
|
| 733 |
+
drop.append(i)
|
| 734 |
+
continue
|
| 735 |
+
out[i] = (R.sentences(r["q"]), d, r["q"], r["答"], r["型"])
|
| 736 |
+
return out, drop
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def _單讀表(items, gold_of):
|
| 740 |
+
"""items:{id: (sents, x, ...)} → 每模式計數與題號,外加例子。"""
|
| 741 |
+
cnt = {m: {} for m in 模式}
|
| 742 |
+
exs = []
|
| 743 |
+
for pid, it in items.items():
|
| 744 |
+
sents, x = it[0], it[1]
|
| 745 |
+
res = _修一讀(sents, x)
|
| 746 |
+
g = gold_of(pid)
|
| 747 |
+
jo = S.judge(res["全關"][1], g) if res["全關"][0] == "ok" else "拒"
|
| 748 |
+
for m in 模式:
|
| 749 |
+
if m == "全關":
|
| 750 |
+
continue
|
| 751 |
+
st, val, ev = res[m]
|
| 752 |
+
jn = S.judge(val, g) if st == "ok" else "拒"
|
| 753 |
+
k = _分類(jo, jn)
|
| 754 |
+
if k and (jo != jn or (jo == "錯" and val != res["全關"][1])):
|
| 755 |
+
cnt[m].setdefault(k, []).append(pid)
|
| 756 |
+
if m == "全開" and ev and "動作" in (ev.get("修補") or {}) and jo == "拒":
|
| 757 |
+
exs.append(_例(pid, it[2], x, ev, g))
|
| 758 |
+
cnt["全關"].setdefault("基準" + jo, []).append(pid)
|
| 759 |
+
return cnt, exs
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def cmd_量(a):
|
| 763 |
+
setup()
|
| 764 |
+
OUTD.mkdir(exist_ok=True)
|
| 765 |
+
result = {"作者": WHO, "日期": "2026-11-27", "說明": "每批:修補全關 vs 逐條開 vs 全開;救=拒→對、新錯=拒→錯、變錯=對→錯、"
|
| 766 |
+
"變拒=對→拒(題號列在各格)。A 用 寬 放行合兩讀(v5/v7/視窗 DeepSeek),B、C 單讀。", "批": {}}
|
| 767 |
+
exs = {}
|
| 768 |
+
if "A" in a.批:
|
| 769 |
+
final, ev, target, qs, PRs = 量A()
|
| 770 |
+
gold = S.X.load_gold() # 全部修完才讀答案
|
| 771 |
+
tab = {m: {} for m in 模式}
|
| 772 |
+
allreg = {m: {} for m in 模式}
|
| 773 |
+
exA = []
|
| 774 |
+
for p, per in final.items():
|
| 775 |
+
jo = S.judge(per["全關"][1], gold[p]) if per["全關"][0] == "ok" else "拒"
|
| 776 |
+
tab["全關"].setdefault("基準" + jo, []).append(p) if p in target else None
|
| 777 |
+
for m in 模式:
|
| 778 |
+
if m == "全關":
|
| 779 |
+
continue
|
| 780 |
+
st, val = per[m]
|
| 781 |
+
jn = S.judge(val, gold[p]) if st == "ok" else "拒"
|
| 782 |
+
k = _分類(jo, jn)
|
| 783 |
+
if k and (jo != jn or (jo == "錯" and str(val) != str(per["全關"][1]))):
|
| 784 |
+
(tab if p in target else allreg)[m].setdefault(k, []).append(p)
|
| 785 |
+
if m == "全開" and jo == "拒" and jn in ("對", "錯") and len(exA) < 12:
|
| 786 |
+
for key, rr in ev[p].items():
|
| 787 |
+
e = rr["全開"][2]
|
| 788 |
+
if e and "動作" in (e.get("修補") or {}):
|
| 789 |
+
x = PRs[p]["源"][key[0]][key[1]]
|
| 790 |
+
exA.append(dict(_例(p, qs[p], x, e, gold[p]), 來源=f"{key[0]}/{key[1]}"))
|
| 791 |
+
break
|
| 792 |
+
result["批"]["A_寬仍拒開發題"] = {"題數": len(target), "表": _計(tab),
|
| 793 |
+
"其餘題回歸(寬已答的 %d 題)" % (len(final) - len(target)): _計(allreg)}
|
| 794 |
+
exs["A"] = exA
|
| 795 |
+
if "B" in a.批:
|
| 796 |
+
items = 量B()
|
| 797 |
+
gold = S.X.load_gold()
|
| 798 |
+
cnt, ex = _單讀表(items, lambda p: gold[p])
|
| 799 |
+
result["批"]["B_Qwen3-8B_168題"] = {"題數": len(items), "表": _計(cnt)}
|
| 800 |
+
exs["B"] = ex[:8]
|
| 801 |
+
if "C" in a.批:
|
| 802 |
+
items, drop = 量C()
|
| 803 |
+
cnt, ex = _單讀表(items, lambda i: items[i][3])
|
| 804 |
+
result["批"]["C_變形題"] = {"題數": len(items), "扣掉a型數字詞被改": len(drop), "扣掉題號": drop, "表": _計(cnt),
|
| 805 |
+
"依型": {t: _計(_單讀表({k: v for k, v in items.items() if v[4] == t},
|
| 806 |
+
lambda i: items[i][3])[0]) for t in "ab"}}
|
| 807 |
+
exs["C"] = ex[:8]
|
| 808 |
+
result["例"] = exs
|
| 809 |
+
p = OUTD / ("result.json" if set(a.批) == {"A", "B", "C"} else f"result_{''.join(a.批)}.json")
|
| 810 |
+
p.write_text(json.dumps(result, ensure_ascii=False, indent=1, default=str), encoding="utf-8")
|
| 811 |
+
for b, v in result["批"].items():
|
| 812 |
+
print(b, v["題數"])
|
| 813 |
+
for m, t in v["表"].items():
|
| 814 |
+
print(" ", m, {k: x["數"] for k, x in t.items()})
|
| 815 |
+
print("寫", p)
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def _計(tab):
|
| 819 |
+
return {m: {k: {"數": len(v), "題號": sorted(v)} for k, v in t.items()} for m, t in tab.items()}
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
if __name__ == "__main__":
|
| 823 |
+
import argparse
|
| 824 |
+
sys.stdout.reconfigure(encoding="utf-8")
|
| 825 |
+
ap = argparse.ArgumentParser()
|
| 826 |
+
sp = ap.add_subparsers(dest="cmd", required=True)
|
| 827 |
+
q = sp.add_parser("量")
|
| 828 |
+
q.add_argument("--批", nargs="+", default=["A", "B", "C"])
|
| 829 |
+
a = ap.parse_args()
|
| 830 |
+
cmd_量(a)
|
pipeline.py
CHANGED
|
@@ -86,6 +86,43 @@ def init():
|
|
| 86 |
_S["lex"] = sys.modules["規則樹_engine"].default_tree().lex
|
| 87 |
except Exception: # noqa: BLE001
|
| 88 |
_S["lex"] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
return _S
|
| 90 |
|
| 91 |
|
|
@@ -344,14 +381,65 @@ def _stuck(objs, brain, why):
|
|
| 344 |
return uniq
|
| 345 |
|
| 346 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
def solve(question, gen, lb_solve=None, gold=None, pid="user"):
|
| 348 |
-
"""English word problem -> dict (never raises).
|
| 349 |
-
|
|
|
|
|
|
|
| 350 |
t_all = time.time()
|
| 351 |
q = " ".join((question or "").split())
|
| 352 |
res = dict(question=q, sentences=[], reply="", lines=[], parsed="", brain_status="", prefix="", brain_value=None,
|
| 353 |
equations=[], variables=[], teaching=[], lb_steps=[], answer=None, status="", verdict=None,
|
| 354 |
-
stuck=[], refusal="", notes=[], seconds={}
|
|
|
|
| 355 |
if not q:
|
| 356 |
res["status"] = "拒答 Refused: 題目是空的 empty input."
|
| 357 |
return res
|
|
@@ -362,6 +450,26 @@ def solve(question, gen, lb_solve=None, gold=None, pid="user"):
|
|
| 362 |
R, B = S["R"], S["B"]
|
| 363 |
sents = R.sentences(q)
|
| 364 |
res["sentences"] = sents
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
S["gen"], S["reply"], S["llm_seconds"] = gen, "", None
|
| 366 |
t0 = time.time()
|
| 367 |
try:
|
|
@@ -377,22 +485,47 @@ def solve(question, gen, lb_solve=None, gold=None, pid="user"):
|
|
| 377 |
res["reply"] = S.get("reply") or ""
|
| 378 |
objs = r.get("objs") or []
|
| 379 |
res["lines"] = r.get("lines") or []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
try:
|
| 381 |
res["parsed"] = S["P"].render(objs, "中") if objs else ""
|
| 382 |
except Exception: # noqa: BLE001
|
| 383 |
res["parsed"] = ""
|
| 384 |
-
brain =
|
| 385 |
-
if objs:
|
| 386 |
-
try:
|
| 387 |
-
brain = B.solve(objs) # again, for the display fields (變數表/方程/教學/缺口)
|
| 388 |
-
except Exception: # noqa: BLE001
|
| 389 |
-
brain = None
|
| 390 |
-
if brain:
|
| 391 |
-
res["equations"] = list(brain.get("方程_代號") or brain.get("方程") or [])
|
| 392 |
-
res["variables"] = list(brain.get("變數表") or [])
|
| 393 |
-
res["teaching"] = [str(x) for x in brain.get("教學") or []]
|
| 394 |
-
res["brain_status"] = brain.get("status") or ""
|
| 395 |
-
res["notes"] = list(r.get("註記") or [])
|
| 396 |
if r["status"] != "ok":
|
| 397 |
why = str(r.get("拒答原因") or "no answer")
|
| 398 |
res["refusal"] = why
|
|
@@ -401,22 +534,4 @@ def solve(question, gen, lb_solve=None, gold=None, pid="user"):
|
|
| 401 |
res["verdict"] = "拒答" if gold is not None else None
|
| 402 |
res["seconds"]["合計 total"] = round(time.time() - t_all, 1)
|
| 403 |
return res
|
| 404 |
-
res
|
| 405 |
-
res["brain_value"] = str(r.get("value"))
|
| 406 |
-
t1 = time.time()
|
| 407 |
-
e = left_brain_eval(res["prefix"], lb_solve, S["lex"])
|
| 408 |
-
res["seconds"]["左腦 left brain"] = round(time.time() - t1, 2)
|
| 409 |
-
res["lb_steps"] = e["steps"]
|
| 410 |
-
if e["value"] is None:
|
| 411 |
-
res["answer"] = res["brain_value"]
|
| 412 |
-
res["status"] = f"答 Answered by the program brain (left-brain evaluation failed: {e['error']})"
|
| 413 |
-
else:
|
| 414 |
-
res["answer"] = _show(e["value"])
|
| 415 |
-
c = e["cnt"]
|
| 416 |
-
agree = _same(r.get("value"), e["value"])
|
| 417 |
-
res["status"] = (f"答 Answered. 左腦算 {c['lb']} 步、Python 分數計算 {c['py']} 步;"
|
| 418 |
-
+ ("與程式腦精確值一致。" if agree else "與程式腦精確值不一致(照實顯示)。"))
|
| 419 |
-
if gold is not None:
|
| 420 |
-
res["verdict"] = "✓" if _same(res["answer"], gold) else "✗"
|
| 421 |
-
res["seconds"]["合計 total"] = round(time.time() - t_all, 1)
|
| 422 |
-
return res
|
|
|
|
| 86 |
_S["lex"] = sys.modules["規則樹_engine"].default_tree().lex
|
| 87 |
except Exception: # noqa: BLE001
|
| 88 |
_S["lex"] = None
|
| 89 |
+
|
| 90 |
+
# program layer: the rule-tree reader (規則樹/資訊句輸出.py, no LLM)
|
| 91 |
+
tree_dir = str(HERE / "hs" / "規則樹")
|
| 92 |
+
if tree_dir not in sys.path:
|
| 93 |
+
sys.path.insert(0, tree_dir)
|
| 94 |
+
import 資訊句輸出 as T
|
| 95 |
+
_S["T"] = T
|
| 96 |
+
|
| 97 |
+
# model-layer repair (#350 讀法修補.py) expects the 缺一塊全掃 environment; here a small stand-in module
|
| 98 |
+
# carries the same objects and the same evaluate() (copied from 缺一塊全掃.evaluate, unchanged logic).
|
| 99 |
+
shim = types.ModuleType("缺一塊全掃")
|
| 100 |
+
shim.R, shim.B, shim.X, shim.V7G = R, B, X, V7G
|
| 101 |
+
|
| 102 |
+
def evaluate(sents, objs, variant="A"):
|
| 103 |
+
try:
|
| 104 |
+
r = B.solve(objs)
|
| 105 |
+
except Exception as e: # noqa: BLE001
|
| 106 |
+
r = {"status": "refused", "value": None, "prefix": None, "拒答原因": f"例外:{type(e).__name__}: {e}"}
|
| 107 |
+
lines = R.解析.render(objs, "英")
|
| 108 |
+
if r["status"] == "ok":
|
| 109 |
+
miss = R.unused_literals(sents, objs, r["prefix"])
|
| 110 |
+
if miss:
|
| 111 |
+
r = dict(r, status="refused", value=None, 拒答原因=f"有字面數沒用到:{', '.join(map(str, miss[:3]))}")
|
| 112 |
+
elif Fraction(r["value"]).denominator != 1:
|
| 113 |
+
r = dict(r, status="refused", value=None, 拒答原因=f"非整數答案:{r['value']}")
|
| 114 |
+
else:
|
| 115 |
+
g = X.語意守門(sents, objs) + V7G.守門(sents, lines)
|
| 116 |
+
if g:
|
| 117 |
+
r = dict(r, status="refused", value=None, 拒答原因=g[0])
|
| 118 |
+
return {"variant": variant, "status": r["status"], "value": r.get("value"), "prefix": r.get("prefix"),
|
| 119 |
+
"拒答原因": r.get("拒答原因"), "lines": lines, "objs": objs}
|
| 120 |
+
shim.evaluate = evaluate
|
| 121 |
+
shim.setup = lambda *a, **k: None
|
| 122 |
+
sys.modules["缺一塊全掃"] = shim
|
| 123 |
+
import 讀法修補 as M
|
| 124 |
+
M.setup()
|
| 125 |
+
_S["M"] = M
|
| 126 |
return _S
|
| 127 |
|
| 128 |
|
|
|
|
| 381 |
return uniq
|
| 382 |
|
| 383 |
|
| 384 |
+
def _brain_display(res, objs, B):
|
| 385 |
+
brain = None
|
| 386 |
+
if objs:
|
| 387 |
+
try:
|
| 388 |
+
brain = B.solve(objs) # again, for the display fields (變數表/方程/教學/缺口)
|
| 389 |
+
except Exception: # noqa: BLE001
|
| 390 |
+
brain = None
|
| 391 |
+
if brain:
|
| 392 |
+
res["equations"] = list(brain.get("方程_代號") or brain.get("方程") or [])
|
| 393 |
+
res["variables"] = list(brain.get("變數表") or [])
|
| 394 |
+
res["teaching"] = [str(x) for x in brain.get("教學") or []]
|
| 395 |
+
res["brain_status"] = brain.get("status") or ""
|
| 396 |
+
return brain
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _finish(res, value, prefix, lb_solve, gold, S, t_all):
|
| 400 |
+
res["prefix"] = prefix or ""
|
| 401 |
+
res["brain_value"] = str(value)
|
| 402 |
+
t1 = time.time()
|
| 403 |
+
e = left_brain_eval(res["prefix"], lb_solve, S["lex"])
|
| 404 |
+
res["seconds"]["左腦 left brain"] = round(time.time() - t1, 2)
|
| 405 |
+
res["lb_steps"] = e["steps"]
|
| 406 |
+
if e["value"] is None:
|
| 407 |
+
res["answer"] = res["brain_value"]
|
| 408 |
+
res["status"] = f"答 Answered by the program brain (left-brain evaluation failed: {e['error']})"
|
| 409 |
+
else:
|
| 410 |
+
res["answer"] = _show(e["value"])
|
| 411 |
+
c = e["cnt"]
|
| 412 |
+
agree = _same(value, e["value"])
|
| 413 |
+
res["status"] = (f"答 Answered. 左腦算 {c['lb']} 步、Python 分數計算 {c['py']} 步;"
|
| 414 |
+
+ ("與程式腦精確值一致。" if agree else "與程式腦精確值不一致(照實顯示)。"))
|
| 415 |
+
if gold is not None:
|
| 416 |
+
res["verdict"] = "✓" if _same(res["answer"], gold) else "✗"
|
| 417 |
+
res["seconds"]["合計 total"] = round(time.time() - t_all, 1)
|
| 418 |
+
return res
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def rule_layer(q, S):
|
| 422 |
+
"""Program layer: 規則樹/資訊句輸出.solve. Returns (result dict or None on exception, refusal reason or None)."""
|
| 423 |
+
try:
|
| 424 |
+
r = S["T"].solve(q)
|
| 425 |
+
except Exception as e: # noqa: BLE001
|
| 426 |
+
return None, f"程式讀題內部錯誤 {type(e).__name__}: {e}"[:200]
|
| 427 |
+
if r.get("拒答") or r.get("value") is None:
|
| 428 |
+
return r, str(r.get("拒答") or "沒有答案")
|
| 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
|
|
|
|
| 450 |
R, B = S["R"], S["B"]
|
| 451 |
sents = R.sentences(q)
|
| 452 |
res["sentences"] = sents
|
| 453 |
+
|
| 454 |
+
# ---- 1. program layer
|
| 455 |
+
t0 = time.time()
|
| 456 |
+
rr, why = rule_layer(q, S)
|
| 457 |
+
res["seconds"]["程式讀題 rule-tree reader"] = round(time.time() - t0, 2)
|
| 458 |
+
res["rule_lines"] = list((rr or {}).get("英文式") or [])
|
| 459 |
+
if why is None:
|
| 460 |
+
res["layer"], res["layer_label"] = "程式", "程式讀題(不會背題)"
|
| 461 |
+
res["lines"] = res["rule_lines"]
|
| 462 |
+
try:
|
| 463 |
+
objs = S["P"].parse(rr.get("交程式腦") or rr["英文式"])
|
| 464 |
+
res["parsed"] = S["P"].render(objs, "中")
|
| 465 |
+
except Exception: # noqa: BLE001
|
| 466 |
+
objs = []
|
| 467 |
+
_brain_display(res, objs, B)
|
| 468 |
+
return _finish(res, rr["value"], rr["prefix"], lb_solve, gold, S, t_all)
|
| 469 |
+
res["rule_why"] = why
|
| 470 |
+
|
| 471 |
+
# ---- 2. model layer
|
| 472 |
+
res["layer"] = "模型"
|
| 473 |
S["gen"], S["reply"], S["llm_seconds"] = gen, "", None
|
| 474 |
t0 = time.time()
|
| 475 |
try:
|
|
|
|
| 485 |
res["reply"] = S.get("reply") or ""
|
| 486 |
objs = r.get("objs") or []
|
| 487 |
res["lines"] = r.get("lines") or []
|
| 488 |
+
res["notes"] = list(r.get("註記") or [])
|
| 489 |
+
res["layer_label"] = "模型讀題(未修補)"
|
| 490 |
+
# #350 reading repair: only when the read was refused (not when the model call itself failed)
|
| 491 |
+
if r["status"] != "ok" and r.get("rows") and not str(r.get("拒答原因") or "").startswith("LLM 失敗"):
|
| 492 |
+
t2 = time.time()
|
| 493 |
+
try:
|
| 494 |
+
M = S["M"]
|
| 495 |
+
rp = M.修補(sents, M.從rows(r["rows"]))
|
| 496 |
+
except RecursionError:
|
| 497 |
+
rp = {"status": "refused"}
|
| 498 |
+
except Exception as e: # noqa: BLE001
|
| 499 |
+
rp = {"status": "refused", "錯誤": f"{type(e).__name__}: {e}"[:200]}
|
| 500 |
+
res["seconds"]["讀法修補 repair (#350)"] = round(time.time() - t2, 2)
|
| 501 |
+
if rp.get("status") == "ok":
|
| 502 |
+
use = rp["修補"]
|
| 503 |
+
try:
|
| 504 |
+
reply = "\n".join(f"#{n}: {b}" for n, b in use["lines"])
|
| 505 |
+
objs2, _ = R.build(sents, reply)
|
| 506 |
+
b2 = B.solve(objs2)
|
| 507 |
+
except Exception: # noqa: BLE001
|
| 508 |
+
b2 = {"status": "refused"}
|
| 509 |
+
if b2.get("status") == "ok" and _same(b2["value"], rp["value"]):
|
| 510 |
+
acts = "、".join(use["動作"])
|
| 511 |
+
res["layer_label"] = f"模型讀題(已修補 {acts})"
|
| 512 |
+
res["repair"] = {"動作": use["動作"], "證據": [str(x) for x in use["證據"]],
|
| 513 |
+
"修補前拒因": r.get("拒答原因"), "修補後資訊句": use.get("資訊句") or []}
|
| 514 |
+
res["lines_before_repair"] = res["lines"]
|
| 515 |
+
res["lines"] = use.get("資訊句") or R.解析.render(objs2, "英")
|
| 516 |
+
try:
|
| 517 |
+
res["parsed"] = S["P"].render(objs2, "中")
|
| 518 |
+
except Exception: # noqa: BLE001
|
| 519 |
+
res["parsed"] = ""
|
| 520 |
+
_brain_display(res, objs2, B)
|
| 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
|
| 527 |
res["parsed"] = ""
|
| 528 |
+
brain = _brain_display(res, objs, B)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 529 |
if r["status"] != "ok":
|
| 530 |
why = str(r.get("拒答原因") or "no answer")
|
| 531 |
res["refusal"] = why
|
|
|
|
| 534 |
res["verdict"] = "拒答" if gold is not None else None
|
| 535 |
res["seconds"]["合計 total"] = round(time.time() - t_all, 1)
|
| 536 |
return res
|
| 537 |
+
return _finish(res, r.get("value"), r.get("prefix"), lb_solve, gold, S, t_all)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/accept_layers.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Acceptance for the two-layer Space: Kira 1/2/3 hours (/solve, expect program layer 150/270/390), Kira 2 hours with
|
| 3 |
+
/vary (program layer on both), 2 random dataset questions (/vary) and 1 typed question (/vary).
|
| 4 |
+
python -B tools/accept_layers.py out.json"""
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
from gradio_client import Client
|
| 11 |
+
from huggingface_hub import get_token
|
| 12 |
+
|
| 13 |
+
c = Client("Bigbearbo/word-problem-reader", hf_token=get_token(), verbose=False)
|
| 14 |
+
KIRA = ("Three train stations are {h} apart from one another. Kira travels from the first station to the third, "
|
| 15 |
+
"taking a 30 minutes break at the second station. What's the total time, in minutes, that Kira takes to travel "
|
| 16 |
+
"between the first and third station?")
|
| 17 |
+
TYPED = ("Maria has 3 boxes of pencils with 12 pencils in each box. She gives 9 pencils to her friend. "
|
| 18 |
+
"How many pencils does Maria have left?")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def info_lines(md):
|
| 22 |
+
if not md or "### 3." not in md:
|
| 23 |
+
return []
|
| 24 |
+
return [x for x in md.split("### 3.")[1].split("```")[1].strip().split("\n") if x.strip()]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def layer(md):
|
| 28 |
+
m = re.search(r"\*\*走哪一層:(.*?)\*\*(.*)", md or "")
|
| 29 |
+
return (m.group(1) + m.group(2)).strip() if m else ""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def run(q, info, api):
|
| 33 |
+
t0 = time.time()
|
| 34 |
+
ans, t1, t2 = c.predict(q, api_name=api)
|
| 35 |
+
r = {"抽題": info, "api": api, "題目": q, "回答框": ans, "層": layer(t1), "資訊句": info_lines(t1),
|
| 36 |
+
"換數字層": layer(t2), "換數字資訊句": info_lines(t2), "耗秒_含網路": round(time.time() - t0, 1)}
|
| 37 |
+
print(json.dumps(r, ensure_ascii=False, indent=1), flush=True)
|
| 38 |
+
return r
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
runs = [run(KIRA.format(h=h), f"Kira {h}", "/solve") for h in ("1 hour", "2 hours", "3 hours")]
|
| 42 |
+
runs.append(run(KIRA.format(h="2 hours"), "Kira 2 hours 換數字", "/vary"))
|
| 43 |
+
got = 0
|
| 44 |
+
for _ in range(6):
|
| 45 |
+
if got == 2:
|
| 46 |
+
break
|
| 47 |
+
q, info, _ = c.predict("隨機抽題型 Random type", api_name="/random")
|
| 48 |
+
r = run(q, info, "/vary")
|
| 49 |
+
runs.append(r)
|
| 50 |
+
got += not r["回答框"].startswith("換數字失敗")
|
| 51 |
+
runs.append(run(TYPED, "typed", "/vary"))
|
| 52 |
+
json.dump(runs, open(sys.argv[1], "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
tools/build_bundle.py
CHANGED
|
@@ -8,7 +8,9 @@ from pathlib import Path
|
|
| 8 |
|
| 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 |
SUB = ["單位", "比較", "移轉", "輸出格式", "速率", "部分與整體"] # 語法模組 sub-modules: *.py (no tests) + 關係卡/補充表
|
| 13 |
KB = ["基礎詞.json", "換算.json", "規則登記.json"]
|
| 14 |
|
|
@@ -38,7 +40,7 @@ def main():
|
|
| 38 |
n += cp(p.relative_to(SRC))
|
| 39 |
for f in KB:
|
| 40 |
n += cp(Path("語法模組/知識庫") / f)
|
| 41 |
-
for f in
|
| 42 |
n += cp(Path("規則樹") / f)
|
| 43 |
for p in (SRC / "規則樹" / "葉子").rglob("*.json"):
|
| 44 |
n += cp(p.relative_to(SRC))
|
|
|
|
| 8 |
|
| 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"]
|
| 16 |
|
|
|
|
| 40 |
n += cp(p.relative_to(SRC))
|
| 41 |
for f in KB:
|
| 42 |
n += cp(Path("語法模組/知識庫") / f)
|
| 43 |
+
for f in TREE:
|
| 44 |
n += cp(Path("規則樹") / f)
|
| 45 |
for p in (SRC / "規則樹" / "葉子").rglob("*.json"):
|
| 46 |
n += cp(p.relative_to(SRC))
|
tools/measure_rule_layer.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Rule-layer coverage: 規則樹/資訊句輸出.solve on every GSM8K-train development question (real_set_audit.rows,
|
| 3 |
+
the same loader 資訊句輸出.measure uses, then 範圍守門.過濾 → 7,066). Run against a source tree (mainline or the
|
| 4 |
+
Space copy hs/) to compare. GSM8K test is never read.
|
| 5 |
+
python -B tools/measure_rule_layer.py <手搓算術 root> out.json"""
|
| 6 |
+
import json
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
from collections import Counter
|
| 10 |
+
from fractions import Fraction
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
sys.dont_write_bytecode = True
|
| 14 |
+
root = Path(sys.argv[1])
|
| 15 |
+
sys.path.insert(0, r"H:\Codex用\work\gsm8k-g1m3-wave68-20261125")
|
| 16 |
+
import real_set_audit as RS # noqa: E402
|
| 17 |
+
import evaluate as EV # noqa: E402
|
| 18 |
+
sys.path.insert(0, r"H:\Agent共用\專案\手搓算術\語法模組\資訊句")
|
| 19 |
+
import 範圍守門 # noqa: E402
|
| 20 |
+
rows = list(RS.rows("GSM8K-train", EV.TRAIN))
|
| 21 |
+
gold = {a: str(c) for a, b, c in rows}
|
| 22 |
+
qs = 範圍守門.過濾([(a, b) for a, b, c in rows])
|
| 23 |
+
sys.path.remove(r"H:\Agent共用\專案\手搓算術\語法模組\資訊句")
|
| 24 |
+
sys.path.insert(0, str(root / "規則樹"))
|
| 25 |
+
import 資訊句輸出 as T # noqa: E402
|
| 26 |
+
t0 = time.time()
|
| 27 |
+
cnt, out, ex = Counter(), {}, []
|
| 28 |
+
for pid, q in qs:
|
| 29 |
+
try:
|
| 30 |
+
r = T.solve(q)
|
| 31 |
+
v = r["value"] if not r["拒答"] else None
|
| 32 |
+
except Exception: # noqa: BLE001
|
| 33 |
+
v = None
|
| 34 |
+
cnt["例外"] += 1
|
| 35 |
+
cnt["n"] += 1
|
| 36 |
+
if v is None:
|
| 37 |
+
cnt["拒"] += 1
|
| 38 |
+
else:
|
| 39 |
+
ok = Fraction(str(v)) == Fraction(gold[pid].replace(",", ""))
|
| 40 |
+
cnt["對" if ok else "錯"] += 1
|
| 41 |
+
ex.append({"id": pid, "q": q, "value": str(v), "gold": gold[pid], "判": "對" if ok else "錯"})
|
| 42 |
+
out[pid] = None if v is None else str(v)
|
| 43 |
+
print(dict(cnt), round(time.time() - t0, 1), "s", T.__file__)
|
| 44 |
+
json.dump({"統計": dict(cnt), "讀出": ex, "值": out}, open(sys.argv[2], "w", encoding="utf-8"), ensure_ascii=False)
|
tools/test_replay.py
CHANGED
|
@@ -25,12 +25,13 @@ for t in fx:
|
|
| 25 |
seen["p"] = prompt
|
| 26 |
return t["reply"]
|
| 27 |
r = pipeline.solve(t["q"], gen, lb, gold=t["gold"], pid=t["id"])
|
| 28 |
-
if seen.get("p") != t["prompt"]:
|
| 29 |
cnt["提示不同"] += 1
|
| 30 |
v = {"✓": "對", "✗": "錯", "拒答": "拒"}[r["verdict"]]
|
| 31 |
cnt[v] += 1
|
|
|
|
| 32 |
if v != t["verdict"]:
|
| 33 |
-
diff.append((t["id"], t["verdict"], v, r["status"][:
|
| 34 |
if v == "對" and "ex" not in cnt:
|
| 35 |
cnt["ex"] = 0
|
| 36 |
print(json.dumps({k: r[k] for k in ("question", "lines", "prefix", "lb_steps", "answer", "verdict", "seconds")},
|
|
|
|
| 25 |
seen["p"] = prompt
|
| 26 |
return t["reply"]
|
| 27 |
r = pipeline.solve(t["q"], gen, lb, gold=t["gold"], pid=t["id"])
|
| 28 |
+
if r["layer"] == "模型" and seen.get("p") != t["prompt"]:
|
| 29 |
cnt["提示不同"] += 1
|
| 30 |
v = {"✓": "對", "✗": "錯", "拒答": "拒"}[r["verdict"]]
|
| 31 |
cnt[v] += 1
|
| 32 |
+
cnt[f"{r['layer_label']}:{v}"] += 1
|
| 33 |
if v != t["verdict"]:
|
| 34 |
+
diff.append((t["id"], t["verdict"], v, r["layer_label"], r["status"][:80]))
|
| 35 |
if v == "對" and "ex" not in cnt:
|
| 36 |
cnt["ex"] = 0
|
| 37 |
print(json.dumps({k: r[k] for k in ("question", "lines", "prefix", "lb_steps", "answer", "verdict", "seconds")},
|