# -*- coding: utf-8 -*- """qa_v2_pack.py —— QA v2 打包库:短系统提示 + ≤2,000 token 装箱(9B 分词 + chat 模板)。 用户消息 = 头段(【问题】+ 本简自带段)+【材料片段】(保留原 [#k] 编号)+ 尾段(【本简释文】【机器逐字比对】)。 装箱阶梯(只在超限时往下走):L0 不动块 → L1 未引用块截 300/150 字 → L2 逐条删未引用块(大者先)→ L3 已引用块截到 600/450/300/200/120 字(保留答案里引自该块的「引语」所在位置的窗口)→ L4 头段收紧(CV/释文 ≤200 字)。 """ import re, json BLOCK_HEAD_RE = re.compile(r"^\[#(\d+)\]\s*(.*)$") STOP = ("【任务】", "【本简释文", "【机器逐字比对", "【输出格式】") CITE_RE = re.compile(r"\[#(\d+)\]") QUOTE_RE = re.compile(r"[「『“\"]([^」』”\"]{1,200})[」』”\"]") def split_user(u): """→ head_paras(list[str]), blocks(list[{k,head,body}]), tail_paras(list[str]);块区规则同 k27_common.parse_blocks_from_user。""" lines = u.split("\n") st = next((i for i, l in enumerate(lines) if l.strip().startswith("【材料片段】")), None) if st is None: return None head = "\n".join(lines[:st]).strip("\n") blocks, cur, j = [], None, st + 1 while j < len(lines): l = lines[j]; s = l.strip() if any(s.startswith(x) for x in STOP): break m = BLOCK_HEAD_RE.match(s) if m: if cur: blocks.append(cur) cur = {"k": int(m.group(1)), "head": s, "body": []} elif cur is not None: cur["body"].append(l) j += 1 if cur: blocks.append(cur) for b in blocks: b["body"] = "\n".join(b["body"]).strip("\n") tail = "\n".join(lines[j:]).strip("\n") return head, blocks, tail def paras(s): return [p for p in re.split(r"\n\s*\n", s) if p.strip()] if s else [] def cited_quotes(ans): """{k: [引语...]}:答案中每条引自 [#k] 的行里的引语。""" out = {} for ln in ans.split("\n"): ks = [int(x) for x in CITE_RE.findall(ln)] if not ks: continue qs = QUOTE_RE.findall(ln) for k in ks: out.setdefault(k, []).extend(qs) return out def cut_body(body, cap, quotes, margin=30): if len(body) <= cap: return body spans = [] for q in quotes: q = q.strip() if len(q) < 2: continue i = body.find(q) if i < 0 and len(q) > 4: i = body.find(q[:4]) if i >= 0: spans.append((max(0, i - margin), min(len(body), i + len(q) + margin))) if not spans: return body[:cap] + "……" spans.sort(); merged = [] for s, e in spans: if merged and s <= merged[-1][1] + 10: merged[-1] = (merged[-1][0], max(merged[-1][1], e)) else: merged.append((s, e)) need = sum(e - s for s, e in merged) if need >= cap: return "……".join(body[s:e] for s, e in merged) + "……" # 先放开头,再放各引语窗口 budget = cap - need; pieces = []; pos = 0 head_end = min(budget, merged[0][0]) if head_end > 0: pieces.append(body[:head_end]); pos = head_end for s, e in merged: if s > pos: pieces.append("……") pieces.append(body[max(s, pos):e]); pos = max(pos, e) if pos < len(body): pieces.append("……") return "".join(pieces) CJK = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\U00020000-\U0002ffff]") STOPBG = set("之也而以其于者所为是不有曰此与则乃亦若矣焉") def claim_bigrams(lines): bg = set() for ln in lines: t = CITE_RE.sub("", ln) t = "".join(ch if CJK.match(ch) else " " for ch in t) for run in t.split(): for j in range(len(run) - 1): g = run[j:j + 2] if not (g[0] in STOPBG and g[1] in STOPBG): bg.add(g) return bg def cited_lines(ans): out = {} for ln in ans.split("\n"): for k in set(int(x) for x in CITE_RE.findall(ln)): out.setdefault(k, []).append(ln) return out _T2S = [None] def t2s(x): if _T2S[0] is None: import opencc _T2S[0] = opencc.OpenCC("t2s").convert y = _T2S[0](x) return y if len(y) == len(x) else x NAME_RE = re.compile(r"^[-\s]*([\u4e00-\u9fff〈〉《》·]{2,10}?)(?:等人|等)?(?:认为|指出|主张|以为|提出|怀疑|推测|释为|读为|读作|断为|据|引|谓|云|说|曰|疑)") def line_keys(lines): """引自某块的结论行里须保留可见的关键串:「引语」+ 行首学者/书名主语(简体)。""" ks = [] for ln in lines: ks += [q.strip() for q in QUOTE_RE.findall(ln) if len(q.strip()) >= 2] m = NAME_RE.match(ln.strip()) if m: ks.append(m.group(1).strip("《》〈〉·")) return ks def cut_body_g(body, cap, quotes, lines, margin=8, win=64): """已引用块截断(繁简不敏感):必留 = 引语、行首学者/书名主语所在处;其余按引自该块的结论行双字组密度贪心取 ≥win 字的大窗口,总长 ≤cap。""" if len(body) <= cap: return body sb = t2s(body); n = len(body) must = [] for q in line_keys(lines): qq = t2s(q) i = sb.find(qq) if i < 0 and len(qq) > 4: i = sb.find(qq[:4]) if i >= 0: must.append((max(0, i - margin), min(n, i + len(qq) + margin))) bg = claim_bigrams([t2s(l) for l in lines]) w = [0] * n for i in range(n - 1): if sb[i:i + 2] in bg: w[i] = 1 chosen = []; used = 0 for s0, e0 in sorted(must): if chosen and s0 <= chosen[-1][1]: chosen[-1] = (chosen[-1][0], max(chosen[-1][1], e0)) else: chosen.append((s0, e0)) used = sum(e - s for s, e in chosen) covered = [False] * n for s0, e0 in chosen: for i in range(s0, e0): covered[i] = True ww = max(16, min(win, cap // 2)) while used + ww <= cap: pre = [0] for i in range(n): pre.append(pre[-1] + (w[i] if not covered[i] else 0)) best, bi = 0, -1 for i in range(0, n - ww + 1): v = pre[i + ww] - pre[i] if v > best: best, bi = v, i if bi < 0 or best < 2: break chosen.append((bi, bi + ww)); used += ww for i in range(bi, bi + ww): covered[i] = True if not chosen: return body[:cap] + "……" chosen.sort(); merged = [] for s0, e0 in chosen: if merged and s0 <= merged[-1][1] + 6: merged[-1] = (merged[-1][0], max(merged[-1][1], e0)) else: merged.append((s0, e0)) if merged[0][0] < 12: merged[0] = (0, merged[0][1]) return ("……" if merged[0][0] > 0 else "") + "……".join(body[a:b] for a, b in merged) + ("……" if merged[-1][1] < n else "") def name_visible(user_blocks, ans): """行首学者/书名主语在所引块可见正文(转简)中出现的行数 / 有主语的行数。""" tot = ok = 0 for ln in ans.split("\n"): ks = [int(x) for x in CITE_RE.findall(ln)] m = NAME_RE.match(ln.strip()) if not ks or not m: continue nm = m.group(1).strip("《》〈〉·"); tot += 1 pool = t2s("\n".join(user_blocks.get(k, "") for k in ks)) ok += nm in pool return ok, tot def grounded_ratio(user_blocks, ans): """结论行词面落地率:引自 [#k] 的结论行,其双字组(去停用)在所引块可见正文中命中 ≥2 个的比例。""" tot = ok = 0 for ln in ans.split("\n"): ks = [int(x) for x in CITE_RE.findall(ln)] if not ks or not ln.strip().startswith("-"): continue pool = t2s("\n".join(user_blocks.get(k, "") for k in ks)) bg = claim_bigrams([t2s(ln)]); tot += 1 ok += sum(1 for g in bg if g in pool) >= 2 return ok, tot def render(head, blocks, tail, partial): hdr = "【材料片段】共 %d 条%s:" % (len(blocks), "(节选,保留原编号)" if partial else "") body = "\n\n".join(b["head"] + ("\n" + b["text"] if b["text"] else "") for b in blocks) return (head + "\n\n" if head else "") + hdr + "\n\n" + body + ("\n\n" + tail if tail else "") def fit(ntok, sys_prompt, head, blocks, tail, ans, limit=2000, head_shrink=None): """返回 (user, n_tok, level, info);level ∈ L0..L4;放不下返回 (None, n, 'FAIL', info)。""" cq = cited_quotes(ans); cited = set(cq) bl = [dict(b, text=b["body"]) for b in blocks] def count(bs, h=head, t=tail, partial=False): u = render(h, bs, t, partial) return u, ntok([{"role": "system", "content": sys_prompt}, {"role": "user", "content": u}, {"role": "assistant", "content": ans}]) u, n = count(bl) if n <= limit: return u, n, "L0", {"dropped": [], "cut": [], "vis": {b["k"]: b["text"] for b in bl}} info = {"dropped": [], "cut": []} for cap in (300, 150): bl = [dict(b, text=cut_body(b["body"], cap, [])) if b["k"] not in cited else b for b in bl] u, n = count(bl, partial=True) if n <= limit: info["cut"] = [b["k"] for b in bl if b["k"] not in cited]; info["vis"] = {b["k"]: b["text"] for b in bl}; return u, n, "L1", info unc = sorted([b for b in bl if b["k"] not in cited], key=lambda b: -len(b["text"])) for b in unc: bl = [x for x in bl if x["k"] != b["k"]]; info["dropped"].append(b["k"]) u, n = count(bl, partial=True) if n <= limit: info["vis"] = {b["k"]: b["text"] for b in bl}; return u, n, "L2", info cls = cited_lines(ans) for cap in (600, 450, 300, 200, 120): bl = [dict(b, text=cut_body_g(b["body"], cap, cq.get(b["k"], []), cls.get(b["k"], []))) for b in bl] u, n = count(bl, partial=True) if n <= limit: info["cut"] = [b["k"] for b in bl]; info["cited_cap"] = cap; info["vis"] = {b["k"]: b["text"] for b in bl}; return u, n, "L3", info if head_shrink: h2, t2 = head_shrink(head, tail) for cap, mg in ((120, 6), (80, 4), (60, 2), (40, 1)): bl = [dict(b, text=cut_body_g(b["body"], cap, cq.get(b["k"], []), cls.get(b["k"], []), mg)) for b in bl] u, n = count(bl, h2, t2, partial=True) if n <= limit: info["cut"] = [b["k"] for b in bl]; info["cited_cap"] = cap; info["head_shrunk"] = True; info["vis"] = {b["k"]: b["text"] for b in bl}; return u, n, "L4", info return None, n, "FAIL", info