Spaces:
Running on Zero

Bigbearbo's picture
Model layer: #348 per-sentence mix (取代守門 keep, 31 allowed constructions, spaCy en_core_web_sm)
eef10ae verified
Raw History Blame Contribute Delete
4.72 kB
# -*- coding: utf-8 -*-
"""逐句混合 for the Space's model layer (no Gradio import). After Qwen3-8B writes its reply, every fact sentence whose
atomic clauses are ALL read by the construction reader (#348 構式讀題, trained offline, pickled in
data/construction_reader.pkl) with a construction in the 31-entry allow list gets the program reading; with the
取代守門 'keep' mode the model lines that do not belong to that sentence (number not in it, owner/item not in it) are
kept. The question sentence and every other sentence keep Qwen's lines. 名字對齊 on, 速率構式 off.
The function `mix` is the same as tools/mix_replies.py's (measured: 168 Qwen questions 11/7/150 unchanged).
Code under hs/語法模組/句法讀題 and hs/語法模組/吸收讀題 is an unchanged copy of the team's files.
Written by: Claude subagent (讀題 Space), 2026-11-27."""
import pickle
import re
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
SYN = HERE / "hs" / "語法模組" / "句法讀題"
LINE = re.compile(r"^\s*#(\d+)\s*:\s*(.+?)\s*$")
_S = {}
def init():
if _S:
return _S
if str(SYN) not in sys.path:
sys.path.insert(0, str(SYN))
import 構式讀題 as K
import 構式逐句混合 as X
import 取代守門 as G4
d = pickle.loads((HERE / "data" / "construction_reader.pkl").read_bytes())
m = d["meta"]
K.A.US = K.A.unitset()
K.MIN_PREC = m["MIN_PREC"]
K.Z.省略開 = m["省略開"]
X.對齊開 = m["對齊開"]
G4.模式 = m["取代守門"]
K.開關["速率"] = m["速率"]
_S.update(K=K, X=X, G4=G4, A=K.A, Z=K.Z, R=d["R"], allow=set(m["allow"]), meta=m)
return _S
def parse_reply(reply):
by = {}
for ln in (reply or "").splitlines():
m = LINE.match(ln)
if m:
by.setdefault(int(m.group(1)), []).append(m.group(2))
return by
def mix(q, reply):
"""Returns (mixed reply text, per-sentence list [{句號, 來源 程式/模型, 構式, 程式讀?, 模型讀?, 守門留下?, 備註?}])."""
S = init()
K, X, G4, A, Z, R, allow = S["K"], S["X"], S["G4"], S["A"], S["Z"], S["R"], S["allow"]
sents = K.sentences(q)
raw = parse_reply(reply)
by_tok, by_raw = {}, {}
for n, L in raw.items():
for b in L:
if 1 <= n <= len(sents):
by_tok.setdefault(n, [])
body = b.rstrip(".").strip()
if body.startswith(("skip", "unread(")):
continue
try:
by_tok[n].append(A.pieces(body))
by_raw.setdefault(n, []).append(b)
except Exception: # noqa: BLE001
pass
qns = [n for n, L in raw.items() if any(b.lstrip().startswith("ask(") for b in L)]
qn = qns[0] if qns else K.qn_of({"句": sents})
names = A.problem_names(sents)
atoms_by = {}
for n, s in enumerate(sents, 1):
if n == qn or K.is_q(s):
atoms_by[n] = [s]
else:
try:
atoms_by[n] = [a["text"] for a in Z.解壓(s)]
except Exception: # noqa: BLE001
atoms_by[n] = [s]
K.docs([a for n in sorted(atoms_by) for a in atoms_by[n]])
ctx = K.Ctx(frozenset(names))
out, per = dict(raw), []
for n, s in enumerate(sents, 1):
if n == qn:
per.append({"句號": n, "來源": "模型", "構式": None, "備註": "問句留模型"})
continue
gots, keys = [], []
for a in atoms_by[n]:
f = K.特徵(a, ctx)
g, _ = R.read(f)
if g is not None:
g, _ = X.align(g, a, X.vocab_of(by_tok, n), names)
ctx.see(f, g or [])
gots.append(g if (g is not None and f["鍵"]["類"] in allow) else None)
keys.append(f["鍵"]["類"])
if gots and all(g is not None for g in gots):
prog = [ps for g in gots for ps in g]
merged, keep = G4.合併(prog, by_tok.get(n, []), s, names)
if merged is None:
per.append({"句號": n, "來源": "模型", "構式": keys, "備註": "取代守門:有模型行不屬於這句 → 整句不換"})
continue
kept = [by_raw[n][i] for i in keep]
out[n] = [A.render(ps) + "." for ps in prog] + kept
per.append({"句號": n, "來源": "程式", "構式": keys, "程式讀": out[n], "模型讀": raw.get(n, []),
**({"守門留下": kept} if kept else {})})
else:
per.append({"句號": n, "來源": "模型", "構式": keys})
text = "\n".join(f"#{n}: {b}" for n in sorted(out) for b in out[n])
return text, per