Download scripts/qa_cs/cs_sample.py from Raphael2099/llm-data-eval-20261030: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/Raphael2099/llm-data-eval-20261030/resolve/main/scripts/qa_cs/cs_sample.py
- Command line
-
hf download hf://datasets/Raphael2099/llm-data-eval-20261030/scripts/qa_cs/cs_sample.py
-
curl -L -o cs_sample.py https://huggingface.co/datasets/Raphael2099/llm-data-eval-20261030/resolve/main/scripts/qa_cs/cs_sample.py
10.4 kB
| #!/usr/bin/env python3 | |
| # cs_sample.py —— 传世考释问答 v1 · 抽样(CPU)。PLAN v4 §2「考释问答 v2 第二批:A2 篇章 ↔ C 库诸家说」。 | |
| # 源:lib A2 主快照 src=epub(传世典籍译注本,带今译 meta.trans);作品 = cite 首个《…》。 | |
| # 排除:B_dev_eval 14 族(睡虎地/黄帝四经/孙膑/鬼谷子/尉缭子/老子/中庸/孙子/吴子/公孙龙子/大学/司马法/孝经/竹书纪年;含礼记·中庸/大学篇); | |
| # dev_overlap / eval_overlap / demo_parallel 块;限先秦两汉典籍(与 v4 今译去汉以后同口径)。 | |
| # 「被 C 库引用/讨论」:C 库主快照(epub 注疏/译注、epubver 专著、nus02 论文/集释;qiuli 已让位 v2 不在主快照)norm 列 8-gram 索引, | |
| # 某 C 块与本段(汉字归一)共享 ≥3 个 8-gram(≈≥10 字连续引用)即算一条「锚」;无锚不入。C 块 eval/dev_overlap 不作锚。 | |
| # 闸门:leak_gate.Gate(gatesets_v1 全部 9 集 + 演示 76 简)对 原文 与 今译 检查,12-gram / 6-gram 覆盖≥0.3 / ≥6 字包含 任一 → 弃。 | |
| # 问法:F_ju「这句话怎么理解、各家怎么说」/ F_zi「『X』字在这里怎么训释」(X = 锚块里紧跟训释标记的、本段中的字;有 X 的段 50% 取 F_zi)。 | |
| # 输出:data/qa_cs/sample_cs_v1.jsonl + SAMPLE_STATS_cs_v1.json | |
| import json, re, sys, os, sqlite3, random, collections, time, lzma | |
| import numpy as np | |
| W = "/root/autodl-tmp/llm_rag_20261023"; IDX = "/root/autodl-tmp/llm_rag_20260919/index/snapshot_20260920/meta.sqlite" | |
| D = W + "/data/qa_cs"; N_TARGET = int(os.environ.get("N_TARGET", "8000")); SEED = "20261024" | |
| sys.path.insert(0, W + "/scripts") | |
| def log(m): print(time.strftime("%H:%M:%S"), m, flush=True) | |
| HAN = re.compile(r"[㐀-䶿一-鿿\U00020000-\U0002ffff]") | |
| def han(s): return "".join(HAN.findall(s or "")) | |
| EARLY = set("""论语 孟子 礼记 左传 春秋左传 春秋公羊传 春秋穀梁传 周易 诗经 诗 尚书 书 周礼 仪礼 庄子 管子 墨子 荀子 韩非子 列子 淮南子 淮南鸿烈 | |
| 吕氏春秋 国语 战国策 孔子家语 孔子集語 晏子春秋 尔雅 史记 汉书 后汉书 楚辞 屈原 山海经 六韬 商君书 尸子 尹文子 关尹子 盐铁论 黄石公三略 贾谊 司马相如 扬雄 班固 司马迁 | |
| 新序 说苑 列女传 大戴礼记 逸周书 穆天子传 新书 春秋繁露 法言 论衡 白虎通 风俗通义 韩诗外传 黄帝内经""".split()) | |
| EXCL_WORK = ("睡虎地", "黄帝四经", "黃帝四經", "孙膑", "孫臏", "鬼谷子", "尉缭子", "尉繚子", "老子", "道德经", "中庸", "孙子", "孫子", "吴子", "吳子", | |
| "公孙龙子", "公孫龍子", "大学", "大學", "司马法", "司馬法", "孝经", "孝經", "竹书纪年", "竹書紀年") | |
| def excluded(work, pian, cite): | |
| for k in EXCL_WORK: | |
| if work.startswith(k): return k | |
| if re.search(r"中庸|大学|大學|孝经|孝經", pian or ""): return "pian:" + (pian or "")[:8] | |
| return None | |
| N = 8; P = np.uint64(1000003) | |
| def hashes(arr): | |
| n = len(arr) - N + 1 | |
| if n <= 0: return np.zeros(0, np.uint64) | |
| h = np.zeros(n, np.uint64) | |
| with np.errstate(over="ignore"): | |
| for j in range(N): h = h * P + arr[j:j + n].astype(np.uint64) | |
| return h | |
| def main(): | |
| t0 = time.time(); st = collections.Counter() | |
| con = sqlite3.connect("file:%s?mode=ro" % IDX, uri=True) | |
| # ---- 1 A2 passages | |
| A = [] | |
| for cid, cite, text, meta, dev, ev, dp in con.execute("select cid,cite,text,meta,dev_overlap,eval_overlap,demo_parallel from chunks where lib='A2' and src='epub'"): | |
| st["a2_epub"] += 1 | |
| m = json.loads(meta) if meta else {} | |
| mm = re.search(r"《([^》]+)》", cite or ""); work = mm.group(1) if mm else "" | |
| if dev or ev or dp or m.get("eval_overlap") or m.get("eval_parallel"): st["drop_overlap_flag"] += 1; continue | |
| if work not in EARLY: st["drop_not_early"] += 1; continue | |
| ex = excluded(work, m.get("pian") or m.get("chapter") or "", cite) | |
| if ex: st["drop_bdev_family"] += 1; st["drop_bdev_family:" + ex] += 1; continue | |
| hz = han(text) | |
| if len(hz) < 12 or len(hz) > 200: st["drop_len"] += 1; continue | |
| A.append({"cid": cid, "cite": cite, "work": work, "pian": m.get("pian") or "", "chapter": m.get("chapter") or "", | |
| "text": text, "trans": (m.get("trans") or "").strip(), "hz": hz, "prev": m.get("prev"), "next": m.get("next")}) | |
| log("A2 candidates %d" % len(A)) | |
| # ---- 2 C norm 8-gram index | |
| cids, starts, buf = [], [], []; pos = 0 | |
| for cid, norm, ev, dev in con.execute("select cid,norm,eval_overlap,dev_overlap from chunks where lib='C' and src in ('epub','epubver','nus02')"): | |
| if ev or dev or not norm: st["c_skip"] += 1; continue | |
| cids.append(cid); starts.append(pos); buf.append(norm); pos += len(norm) + 1 | |
| big = "\x00".join(buf); del buf | |
| arr = np.frombuffer(big.encode("utf-32-le"), dtype=np.uint32); del big | |
| log("C chunks %d chars %d" % (len(cids), len(arr))) | |
| h = hashes(arr) | |
| sep = np.concatenate([[0], np.cumsum(arr == 0)]) | |
| ok = (sep[N:N + len(h)] - sep[:len(h)]) == 0 | |
| hp = np.nonzero(ok)[0].astype(np.int64); hv = h[ok]; del h, ok | |
| o = np.argsort(hv, kind="stable"); hv = hv[o]; hp = hp[o]; del o | |
| starts = np.array(starts, np.int64) | |
| log("C index built %d grams %.0fs" % (len(hv), time.time() - t0)) | |
| # ---- 3 anchors | |
| CAP = 60; pairs = collections.defaultdict(collections.Counter) | |
| for i, a in enumerate(A): | |
| pa = np.frombuffer(a["hz"].encode("utf-32-le"), dtype=np.uint32) | |
| q = hashes(pa) | |
| lo = np.searchsorted(hv, q, "left"); hi = np.searchsorted(hv, q, "right") | |
| cnt = collections.Counter() | |
| for w, (l, r) in enumerate(zip(lo, hi)): | |
| if r <= l or r - l > CAP: continue | |
| ch = np.searchsorted(starts, hp[l:r], "right") - 1 | |
| for c in set(ch.tolist()): cnt[c] += 1 | |
| nw = len(q); need = min(3, nw) | |
| anc = [(c, n) for c, n in cnt.most_common(12) if n >= need] | |
| if anc: a["anchors"] = [(cids[c], n) for c, n in anc[:6]]; a["n_anchor_chunks"] = sum(1 for c, n in cnt.items() if n >= need) | |
| if i % 10000 == 0: log("anchor %d/%d" % (i, len(A))) | |
| del hv, hp, arr, sep | |
| A = [a for a in A if a.get("anchors")] | |
| st["with_anchor"] = len(A) | |
| log("with anchors %d" % len(A)) | |
| # ---- 4 pre-select (caps) before the slow gate: per work ≤1500, per chapter ≤10, score = anchors | |
| rng = random.Random(SEED) | |
| for a in A: a["_r"] = rng.random() | |
| A.sort(key=lambda a: (-min(a["n_anchor_chunks"], 5), -bool(a["trans"]), a["_r"])) | |
| pw, pc, pre = collections.Counter(), collections.Counter(), [] | |
| for a in A: | |
| k = (a["work"], a["chapter"] or a["pian"]) | |
| if pw[a["work"]] >= 1500 or pc[k] >= 10: continue | |
| pw[a["work"]] += 1; pc[k] += 1; pre.append(a) | |
| if len(pre) >= int(N_TARGET * 1.6): break | |
| log("pre-selected %d for gate" % len(pre)) | |
| # ---- 5 gate (parallel) | |
| from multiprocessing import Pool | |
| global GATE | |
| from leak_gate import Gate | |
| GATE = Gate() | |
| with lzma.open(W + "/data/gatesets_v1.jsonl.xz", "rt", encoding="utf-8") as f: | |
| for l in f: | |
| r = json.loads(l); GATE.add(r["set"], r.get("id"), r.get("text") or "") | |
| for r in (json.loads(l) for l in open(W + "/vendor/release_demo_core_v1_2/data/slips.jsonl", encoding="utf-8") if l.strip()): | |
| for k in ("text_loose_punct", "text_strict_punct"): | |
| if r.get(k): GATE.add("demo76", r["slip_key"], r[k]) | |
| log("gate loaded %d rows" % len(GATE.rows)) | |
| with Pool(48) as pool: | |
| res = pool.map(_gate_one, [(a["text"], a["trans"]) for a in pre], chunksize=20) | |
| kept, gsets = [], collections.Counter() | |
| for a, (rej, sets) in zip(pre, res): | |
| if rej: st["drop_gate"] += 1; gsets.update(sets); continue | |
| kept.append(a) | |
| log("gate kept %d / %d" % (len(kept), len(pre))) | |
| kept = kept[:N_TARGET] | |
| # ---- 6 forms + X | |
| GL = re.compile(r"(?:读为|讀爲|读作|讀作|通作|假借为|借为|通|同|犹|猶|训为|訓爲|训|訓|谓|謂|义为|義爲|意为|意思是|指|即)") | |
| FUNC = set("之乎者也而以其于於为為则則所与與矣焉哉亦乃且若此是不无無有曰子人一二三四五") | |
| q = "select cid,text from chunks where cid in (%s)" | |
| allc = sorted({c for a in kept for c, _ in a["anchors"]}) | |
| ctext = {} | |
| for i in range(0, len(allc), 500): | |
| ch = allc[i:i + 500] | |
| for cid, t in con.execute(q % ",".join("?" * len(ch)), ch): ctext[cid] = t | |
| fc = collections.Counter() | |
| for a in kept: | |
| cand = collections.Counter() | |
| chars = set(a["hz"]) - FUNC | |
| for cid, _ in a["anchors"][:3]: | |
| t = ctext.get(cid) or "" | |
| for m in GL.finditer(t): | |
| s = t[max(0, m.start() - 3):m.start()] | |
| for ch in s: | |
| if ch in chars: cand[ch] += 1 | |
| r2 = random.Random(SEED + "|" + a["cid"]) | |
| if cand and r2.random() < 0.5: | |
| a["form"] = "F_zi"; a["x_char"] = cand.most_common(1)[0][0] | |
| else: | |
| a["form"] = "F_ju"; a["x_char"] = None | |
| fc[a["form"]] += 1 | |
| with open(D + "/sample_cs_v1.jsonl", "w", encoding="utf-8") as f: | |
| for a in kept: | |
| a.pop("_r", None) | |
| f.write(json.dumps(a, ensure_ascii=False) + "\n") | |
| stats = {"n": len(kept), "counts": dict(st), "gate_hit_sets": dict(gsets), "forms": dict(fc), | |
| "by_work": dict(collections.Counter(a["work"] for a in kept).most_common()), | |
| "anchor_rule": "C 主快照 epub/epubver/nus02 norm 8-gram;同块共享 ≥min(3,窗口数) 个 8-gram;每 8-gram 出现 >60 次不计", | |
| "excl_work": EXCL_WORK, "early_works": sorted(EARLY), "seed": SEED, "sec": round(time.time() - t0, 1)} | |
| json.dump(stats, open(D + "/SAMPLE_STATS_cs_v1.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) | |
| log("DONE n=%d forms=%s" % (len(kept), dict(fc))) | |
| GATE = None | |
| def _gate_one(x): | |
| sets = set(); rej_any = False | |
| for t in x: | |
| if not t: continue | |
| rej, info = GATE.check(t) | |
| if rej or info.get("hit12") or info.get("contain"): | |
| rej_any = True; sets |= set(info.get("sets") or []) | |
| return rej_any, sorted(sets) | |
| if __name__ == "__main__": | |
| main() | |