Download scripts/qa/qa_sample.py from Raphael2099/llm-data-eval-20261030: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/datasets/Raphael2099/llm-data-eval-20261030/resolve/main/scripts/qa/qa_sample.py
- Command line
-
hf download hf://datasets/Raphael2099/llm-data-eval-20261030/scripts/qa/qa_sample.py
-
curl -L -o qa_sample.py https://huggingface.co/datasets/Raphael2099/llm-data-eval-20261030/resolve/main/scripts/qa/qa_sample.py
15.2 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """qa_sample.py —— 考释问答 v1 · 采样(PLAN v3 §2.2「考释问答」行)。CPU only。 | |
| 池:KB addon_slips_v1 的 lib A 出土简块(meta.split=="train", era==EXCAVATED),汉字 15–220。 | |
| 排除(按作品,先于一切):四篇(王家嘴孔子曰、枣纸简吴王夫差/齐桓公、安大仲尼曰、QYCF14)、演示 76 简(核心包 slips.jsonl)、 | |
| A_dev_clean 441 族(split=dev 诸族)、越公其事(holdout)、B_dev_eval 出土同族(睡虎地/马王堆老子+卷前后古佚书/孙膑/孙子/尉缭子/郭店老子)、 | |
| 9 月 k27 已训练的 3,119 支(按 sample_id;另以 12-gram/包含 挡其它版本的同文块)。 | |
| 泄漏门:W/scripts/leak_gate.py(gatesets_v1 全部 9 个门集 + 演示 76 简;12-gram / 6-gram 覆盖≥0.3 / ≥6 字包含,双向)。 | |
| 问题形式:每支简按 (seed 20261023, id) 独立随机;F2(「X」字)只在简内有通假/待考括注字时可选,否则在 F1/F3 中取。 | |
| 输出 W/data/qa/{slips_v1.jsonl, queries_v1.jsonl, SAMPLE_STATS.json} | |
| """ | |
| import collections, glob, hashlib, json, lzma, math, os, random, re, sqlite3, sys | |
| W = "/root/autodl-tmp/llm_rag_20261023" | |
| sys.path.insert(0, os.path.join(W, "scripts")) | |
| from leak_gate import Gate, norm1, norm2 # noqa: E402 | |
| I = "/root/autodl-tmp/llm_rag_20260919/index" | |
| SEED = 20261023 | |
| TARGET = int(os.environ.get("TARGET", "8000")) | |
| MIN_HAN, MAX_HAN = 15, 220 | |
| CAP_FRAC = 0.04 | |
| OUT = os.path.join(W, "data", "qa") | |
| DEMO_SLIPS = os.path.join(W, "vendor", "release_demo_core_v1_2", "data", "slips.jsonl") | |
| K27_DIR = "/root/autodl-tmp/_from_bjb1b/llm_sft_20260918/kaoshi27b/data" | |
| GATESETS = os.path.join(W, "data", "gatesets_v1.jsonl.xz") | |
| TITLE_PAT = ("孔子曰", "仲尼曰", "吴王夫差", "吳王夫差", "齐桓公", "齊桓公", "QYCF", "群玉", "越公其事", "yuegongqishi") | |
| FAMILY_EXCL = {"GD_六位", "SB_柬大王泊旱", "SB_陳公治兵", "SB_融師有成氏", "SB_相邦之道", "QH_摄命", "QH_攝命", | |
| "QH_保训", "QH_保訓", "GD_魯穆公問子思", "QH06_yuegongqishi"} | |
| BDEV_PAT = ("睡虎地", "古佚書", "古佚书", "孫臏", "孙膑", "老子", "孫子兵法", "孙子兵法", "尉繚子", "尉缭子") | |
| EXTRA_STORES = [ # 其余 KB lib A 出土简分片(无 split 字段:训练划分 = 按作品排除 dev/holdout 族);layer 优先序:带通假括注的层在前 | |
| ("addon_slips_qh15_v1", ("loose", "strict")), | |
| ("addon_slips_qhv3_gdll_v1", ("strict", "loose")), | |
| ("addon_slips_sbv4_v1", ("strict", "loose")), | |
| ("addon_kaoshi_shiwen6_v1", ("strict", "原简释文", "loose")), | |
| ("addon_slips_cd14_v1", ("釋文",)), | |
| ] | |
| PIAN_EXCL = ("六位", "六德", "柬大王泊旱", "陈公治兵", "融师有成氏", "相邦之道", "摄命", "保训", "鲁穆公问子思", "越公其事") | |
| def norm_text(t, store=""): | |
| t = t or "" | |
| t = re.sub(r"⟦(?:glyph|region):[^⟧]*⟧", "[?]", t) | |
| t = re.sub(r"⟦sym:(?:chongwen|hewen)[^⟧]*⟧", "=", t) | |
| t = re.sub(r"⟦[^⟧]*⟧", "", t) | |
| t = re.sub(r"〔[一二三四五六七八九十百〇零]+〕", "", t) | |
| t = re.sub(r"\s*\$\^\{\[\d+\]\}\$", "", t) | |
| t = re.sub(r"\s*\[\d+\]", "", t) | |
| t = re.sub(r"\(([^()]{1,6})\)", "(\\1)", t) | |
| t = re.sub(r"[ \t\u3000]+", "", t).strip() | |
| if store == "addon_slips_cd14_v1": | |
| t = re.sub(r"(\d+)$", "【\\1】", t) | |
| return t | |
| HAN = re.compile(r"[㐀-鿿\U00020000-\U0002ffff]") | |
| # 通假/待考括注:单字 X(Y);Y 1–4 字,可带 ? | |
| ANN = re.compile(r"([㐀-鿿\U00020000-\U0002ffff])(([^()]{1,6}))") | |
| COMMON = set("亓其又有才在女汝如母毋隹惟唯曰之而於于也者") # 极常见括注:F2 尽量不选 | |
| RE_SLIPNO = re.compile(r"【[^】]*】") | |
| RE_BRACE = re.compile(r"\{[^}]*\}") | |
| PUNCT = set(",。、;:?!「」『』“”‘’《》〈〉…—-·,.;:?!\"' \t\n") | |
| def hkey(*p): | |
| return hashlib.sha256(("%d|" % SEED + "|".join(str(x) for x in p)).encode()).hexdigest() | |
| def nhan(s): | |
| return len(HAN.findall(s or "")) | |
| def strip_punct(s): | |
| return "".join(c for c in (s or "") if c not in PUNCT) | |
| def make_query(text_nopunct): | |
| q = RE_SLIPNO.sub("", text_nopunct) | |
| q = RE_BRACE.sub("", q) | |
| q = re.sub(r"[((]([^()()]{1,4})[))]", "", q) # 宽式里偶见的括注:保留本字 | |
| q = q.replace("[?]", "").replace("○", "").replace("□", "").replace("〼", "").replace("■", "") | |
| q = re.sub(r"[〔〕\[\]]", "", q) | |
| return re.sub(r"\s+", "", q)[:120] | |
| def ann_chars(*texts): | |
| out = [] | |
| for t in texts: | |
| for m in ANN.finditer(t or ""): | |
| x, y = m.group(1), m.group(2) | |
| if not HAN.search(y) and "?" not in y and "?" not in y: | |
| continue | |
| if x == y: | |
| continue | |
| kind = "daikao" if ("?" in y or "?" in y) else "tongjia" | |
| out.append((x, y, kind)) | |
| seen, uniq = set(), [] | |
| for a in out: | |
| if a[0] not in seen: | |
| seen.add(a[0]); uniq.append(a) | |
| return uniq | |
| def main(): | |
| os.makedirs(OUT, exist_ok=True) | |
| drops = collections.Counter() | |
| for k in ("total", "not_train_split", "not_excavated", "han_out_of_range", "title_four_texts", | |
| "family_dev_holdout", "family_bdev_excavated", "k27_sample_id", "k27_text", "gate_eval", | |
| "dup_text"): | |
| drops[k] = 0 | |
| # ── 门集 | |
| gate = Gate() | |
| gs_n = collections.Counter() | |
| with lzma.open(GATESETS, "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 "") | |
| gs_n[r["set"]] += 1 | |
| for l in open(DEMO_SLIPS, encoding="utf-8"): | |
| r = json.loads(l) | |
| for k in ("text_loose_punct", "text_strict_punct"): | |
| if r.get(k): | |
| gate.add("demo76", r["slip_key"], r[k]) | |
| gs_n["demo76"] += 1 | |
| # ── k27(9 月已训练 3,119 支) | |
| k27_ids, k27_gate = set(), Gate() | |
| for l in open(os.path.join(K27_DIR, "prompts.jsonl"), encoding="utf-8"): | |
| k27_ids.add(json.loads(l)["id"]) | |
| for l in open(os.path.join(K27_DIR, "slips_sample.dedup.jsonl"), encoding="utf-8"): | |
| u = json.loads(l) | |
| if u["id"] in k27_ids: | |
| k27_gate.add("k27", u["id"], u.get("text_punct") or u.get("text_nopunct") or "") | |
| # ── 池 | |
| con = sqlite3.connect("file:%s/addon_slips_v1/meta.sqlite?mode=ro" % I, uri=True) | |
| cands, seen = [], {} | |
| gate_hits = collections.Counter() | |
| for cid, text, cite, tier, quotable, meta in con.execute( | |
| "select cid,text,cite,tier,quotable,meta from chunks where lib='A' order by rowid"): | |
| drops["total"] += 1 | |
| m = json.loads(meta) | |
| if m.get("split") != "train": | |
| drops["not_train_split"] += 1; continue | |
| if m.get("era") != "EXCAVATED": | |
| drops["not_excavated"] += 1; continue | |
| n = nhan(text) | |
| if not (MIN_HAN <= n <= MAX_HAN): | |
| drops["han_out_of_range"] += 1; continue | |
| fam = m.get("family_id") or "" | |
| title_blob = " ".join(str(m.get(k) or "") for k in ("pian", "pian_raw", "book", "corpus_name", "doc_key")) + " " + fam + " " + (cite or "") | |
| if any(p in title_blob for p in TITLE_PAT): | |
| drops["title_four_texts"] += 1; continue | |
| if fam in FAMILY_EXCL: | |
| drops["family_dev_holdout"] += 1; continue | |
| if any(p in title_blob for p in BDEV_PAT): | |
| drops["family_bdev_excavated"] += 1; continue | |
| if m.get("sample_id") and m["sample_id"] in k27_ids: | |
| drops["k27_sample_id"] += 1; continue | |
| strict = m.get("text_strict") or "" | |
| rej, _ = k27_gate.check(text) | |
| if rej: | |
| drops["k27_text"] += 1; continue | |
| rej, info = gate.check(text + "\n" + strict) if False else gate.check(text) | |
| if not rej and strict: | |
| rej, info = gate.check(strict) | |
| if rej: | |
| drops["gate_eval"] += 1 | |
| for s in info["sets"]: | |
| gate_hits[s] += 1 | |
| continue | |
| key = norm2(text) | |
| if key in seen: | |
| drops["dup_text"] += 1; continue | |
| seen[key] = cid | |
| cands.append((cid, text, cite, tier, quotable, m, strict, n)) | |
| # ── 其余 lib A 分片 | |
| from leak_gate import t2s as _t2s | |
| extra_ct = collections.Counter() | |
| for store, layers in EXTRA_STORES: | |
| con2 = sqlite3.connect("file:%s/%s/meta.sqlite?mode=ro" % (I, store), uri=True) | |
| rows2 = [] | |
| for cid, text, cite, tier, quotable, meta in con2.execute( | |
| "select cid,text,cite,tier,quotable,meta from chunks where lib='A' order by rowid"): | |
| m = json.loads(meta) | |
| layer = m.get("layer") or m.get("section_kind") or m.get("part") or "" | |
| if layer not in layers: | |
| continue | |
| rows2.append((layers.index(layer), cid, text, cite, tier, quotable, m, layer)) | |
| rows2.sort(key=lambda x: x[0]) | |
| seen_slip = set() | |
| for _, cid, text, cite, tier, quotable, m, layer in rows2: | |
| drops["total"] += 1; extra_ct[(store, "in")] += 1 | |
| t = norm_text(text, store) | |
| n = nhan(t) | |
| if not (MIN_HAN <= n <= MAX_HAN) or t.count("[?]") > 0.25 * max(n, 1): | |
| drops["han_out_of_range"] += 1; continue | |
| fam = m.get("doc_key") or "" | |
| blob = _t2s(" ".join(str(m.get(k) or "") for k in ("pian", "book", "doc_key", "corpus_name", "site")) + " " + (cite or "")) | |
| if any(p in blob for p in TITLE_PAT): | |
| drops["title_four_texts"] += 1; continue | |
| if any(p in blob for p in PIAN_EXCL): | |
| drops["family_dev_holdout"] += 1; continue | |
| if any(p in blob for p in BDEV_PAT) or any(_t2s(p) in blob for p in BDEV_PAT): | |
| drops["family_bdev_excavated"] += 1; continue | |
| sk = (fam, str(m.get("slip_no") or m.get("page") or cid)) | |
| if sk in seen_slip: | |
| drops["dup_text"] += 1; continue | |
| rej, _ = k27_gate.check(t) | |
| if rej: | |
| drops["k27_text"] += 1; continue | |
| rej, info = gate.check(t) | |
| if rej: | |
| drops["gate_eval"] += 1 | |
| for s_ in info["sets"]: | |
| gate_hits[s_] += 1 | |
| continue | |
| key = norm2(t) | |
| if key in seen: | |
| drops["dup_text"] += 1; continue | |
| seen[key] = cid; seen_slip.add(sk) | |
| m2 = dict(m, family_id=fam, corpus_name=m.get("corpus_name") or m.get("corpus"), split="(family-level)", layer=layer, store=store) | |
| cands.append((cid, t, cite, tier, quotable, m2, t, n)) | |
| extra_ct[(store, "kept")] += 1 | |
| print("EXTRA", {"%s:%s" % k: v for k, v in sorted(extra_ct.items())}, file=sys.stderr) | |
| # ── 按作品轮转 | |
| by_fam = collections.defaultdict(list) | |
| for c in cands: | |
| by_fam[c[5].get("family_id") or c[0]].append(c) | |
| for f in by_fam: | |
| by_fam[f].sort(key=lambda c: hkey("order", c[0])) | |
| fams = sorted(by_fam, key=lambda f: (hkey("fam", f), f)) | |
| cap = max(1, int(math.ceil(CAP_FRAC * TARGET))) | |
| picked, idx = [], {f: 0 for f in fams} | |
| while len(picked) < TARGET: | |
| prog = False | |
| for f in fams: | |
| if len(picked) >= TARGET: | |
| break | |
| i = idx[f] | |
| if i >= len(by_fam[f]) or i >= cap: | |
| continue | |
| picked.append(by_fam[f][i]); idx[f] = i + 1; prog = True | |
| if not prog: | |
| break | |
| # ── 落盘 | |
| units, queries = [], [] | |
| form_ct, form_elig = collections.Counter(), collections.Counter() | |
| for cid, text, cite, tier, quotable, m, strict, n in picked: | |
| if norm2(strict) == norm2(text) or strict == text: | |
| strict = "" # 其余分片单层:不重复给严式块 | |
| nopunct = strip_punct(text) | |
| strict_np = strip_punct(strict) | |
| use_strict_cv = bool(strict) and int(hkey("cv", cid)[:8], 16) % 1000 < 300 | |
| anns = ann_chars(strict, text) | |
| rng = random.Random("%d|%s" % (SEED, cid)) | |
| forms = ["F1_shidu", "F2_zi", "F3_duidu"] if anns else ["F1_shidu", "F3_duidu"] | |
| if anns: | |
| form_elig["F2_eligible"] += 1 | |
| form = rng.choice(forms) | |
| x = None | |
| if form == "F2_zi": | |
| pool = [a for a in anns if a[2] == "daikao"] or [a for a in anns if a[0] not in COMMON] or anns | |
| x = rng.choice(pool) | |
| form_ct[form] += 1 | |
| corpus_cn = m.get("corpus_name") or m.get("corpus") or "" | |
| u = {"id": cid, "store": m.get("store") or "addon_slips_v1", "layer": m.get("layer"), "corpus": m.get("corpus"), "corpus_cn": corpus_cn, "book": m.get("book"), | |
| "pian": m.get("pian"), "family_id": m.get("family_id"), "kb_tier": tier, "kb_quotable": quotable, | |
| "sample_id": m.get("sample_id"), "n_han": n, | |
| "text_punct": text, "text_nopunct": nopunct, | |
| "text_strict_punct": strict, "text_strict": strict_np, | |
| "cite": cite, "cv_text": strict_np if use_strict_cv else nopunct, | |
| "cv_source": "strict_nopunct" if use_strict_cv else "loose_nopunct", | |
| "verdict": "confirmed", "form": form, | |
| "x_char": x[0] if x else None, "x_read": x[1] if x else None, "x_kind": x[2] if x else None, | |
| "n_ann": len(anns)} | |
| units.append(u) | |
| queries.append({"id": cid, "query": make_query(nopunct) or nopunct[:120], "verdict": "confirmed", "batch": ""}) | |
| with open(os.path.join(OUT, "slips_v1.jsonl"), "w", encoding="utf-8") as f: | |
| for u in units: | |
| f.write(json.dumps(u, ensure_ascii=False) + "\n") | |
| with open(os.path.join(OUT, "queries_v1.jsonl"), "w", encoding="utf-8") as f: | |
| for q in queries: | |
| f.write(json.dumps(q, ensure_ascii=False) + "\n") | |
| per_fam = collections.Counter(u["family_id"] for u in units) | |
| stats = {"seed": SEED, "target": TARGET, "n_units": len(units), "n_candidates_after_guards": len(cands), | |
| "pool": "addon_slips_v1 lib A split=train era=EXCAVATED", "han_range": [MIN_HAN, MAX_HAN], | |
| "family_cap": cap, "dropped": dict(drops), "gate_hits_by_set": dict(gate_hits), | |
| "gatesets_rows": dict(gs_n), "k27_ids": len(k27_ids), | |
| "form_counts": dict(form_ct), "form_eligibility": dict(form_elig), | |
| "by_corpus": dict(collections.Counter(u["corpus_cn"] for u in units)), | |
| "by_book": dict(collections.Counter(u["book"] for u in units)), | |
| "by_tier": dict(collections.Counter(u["kb_tier"] for u in units)), | |
| "by_store": dict(collections.Counter(u["store"] for u in units)), | |
| "n_families": len(per_fam), "top_families": per_fam.most_common(15), | |
| "n_families_capped": sum(1 for f in by_fam if len(by_fam[f]) > cap)} | |
| json.dump(stats, open(os.path.join(OUT, "SAMPLE_STATS.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1) | |
| print(json.dumps(stats, ensure_ascii=False, indent=1)) | |
| if __name__ == "__main__": | |
| main() | |