EvoStream / evo2 /classifier.py
SitongGong's picture
Add files using upload-large-folder tool
197d46b verified
Raw History Blame Contribute Delete
4.36 kB
"""题型推断:由模型自己判断题目落在哪个 6×3 格子(不读任何 benchmark 标签)。
用户定稿 2026-08-21:题型识别本身是模型的活,不能外部告知。
输出全部落盘(cell_log.jsonl),将来可用于训练一个小分类器替换 LLM 调用。
消融档见 ablation.py:llm(默认)/ lexical(纯关键词规则,免费)/ none(不分类)。
"""
import json
import logging
import os
import re
from .qtype import SPACE, TIME, spec_for_prompt, is_valid
logger = logging.getLogger(__name__)
PROMPT = """给你一道视频问答题,判断它属于哪一类。
{spec}
题目:{question}
选项:{options}
只输出 JSON:{{"space": "<空间维度>", "time": "<时序维度>", "confidence": 0.0-1.0}}"""
# 纯词法兜底规则(也是 lexical 消融档的实现)
_LEX_SPACE = [
("COUNT", r"\bhow many\b|\bhow much\b|\bnumber of\b|\bcount\b|几个|多少"),
("TEXT", r"\bwritten\b|\btext\b|\blabel\b|\bsign\b|\bbrand\b|\bword[s]?\b|\bread[s]?\b|文字|写着"),
("ORDER", r"\border\b|\bsequence\b|\bfirst\b|\bthen\b|\bbefore\b|\bafter\b|\bnext\b|顺序|先|然后"),
("SPATIAL", r"\bwhere\b|\bleft\b|\bright\b|\babove\b|\bbelow\b|\bnext to\b|\bposition\b|位置|在哪"),
("STATE", r"\bcolor\b|\bcolour\b|\bopen\b|\bclosed\b|\bstate\b|\bstatus\b|\bhow many times\b|状态|颜色"),
("ACTION", r"\bdoing\b|\baction\b|\bactivity\b|\bperform\b|\btask\b|\bpurpose\b|\bgoal\b|做什么|动作"),
]
_LEX_TIME = [
("GLOBAL", r"\bthroughout\b|\boverall\b|\bprimary\b|\bentire\b|\bwhole video\b|\bin general\b|\bsummar\w*\b|\boverarching\b|\btaking into account\b|全局|整段|总体"),
# 过去时标记必须优先于 NOW 的 is/are:
# "Where did I put X" / "Where was the drill" 是回溯题,
# 但句中常同时含 is/are,若 NOW 在前会被抢走(v1 实测的 EPM/HLD 错分主因)。
("PAST", r"\bdid\b|\bwas\b|\bwere\b|\bearlier\b|\bbefore\b|\bpreviously\b|\blast time\b|\bhad\b|之前|过去|上一次"),
("NOW", r"\bnow\b|\bcurrent\w*\b|\bthis moment\b|\bam i\b|\bis (?:he|she|this|the) \w+ing\b|当前|正在"),
]
def classify_lexical(question: str, options=None) -> dict:
"""免费的词法分类(消融档 + LLM 失败兜底)。"""
q = (question or "").lower()
space = next((s for s, pat in _LEX_SPACE if re.search(pat, q)), "ACTION")
time = next((t for t, pat in _LEX_TIME if re.search(pat, q)), "PAST")
return {"space": space, "time": time, "confidence": 0.3, "method": "lexical"}
def classify_llm(question: str, options, llm) -> dict:
"""LLM 判定;解析失败或越界则回落词法。"""
opts = " | ".join(f"{chr(65+i)}. {o}" for i, o in enumerate(options or []))
try:
r = llm.chat_json(PROMPT.format(spec=spec_for_prompt(), question=question,
options=opts or "(无选项)"), max_tokens=200) or {}
except Exception as e:
logger.warning("题型分类调用失败: %s,回落词法", e)
r = {}
s, t = str(r.get("space", "")).upper(), str(r.get("time", "")).upper()
if not is_valid(s, t):
fb = classify_lexical(question, options)
fb["llm_raw"] = {k: r.get(k) for k in ("space", "time")}
return fb
return {"space": s, "time": t,
"confidence": float(r.get("confidence", 0.5) or 0.5), "method": "llm"}
class CellClassifier:
"""带落盘的题型推断器。mode: llm | lexical | none"""
def __init__(self, llm=None, mode: str = "llm", log_path: str = ""):
self.llm, self.mode, self.log_path = llm, mode, log_path
if log_path:
os.makedirs(os.path.dirname(log_path), exist_ok=True)
def classify(self, question: str, options=None, meta: dict = None) -> dict:
if self.mode == "none":
out = {"space": None, "time": None, "confidence": 0.0, "method": "none"}
elif self.mode == "lexical" or self.llm is None:
out = classify_lexical(question, options)
else:
out = classify_llm(question, options, self.llm)
if self.log_path:
with open(self.log_path, "a") as f:
f.write(json.dumps({**(meta or {}), "question": question,
**out}, ensure_ascii=False) + "\n")
return out