asr / evaluate_model.py
xkpl's picture
Add files using upload-large-folder tool
6b0c1de verified
Raw
History Blame Contribute Delete
63.5 kB
#!/usr/bin/env python3
"""
ASR 诗词纠错模型评估脚本
使用真实 ASR 测试集评估模型效果
"""
import os
import sys
import json
import argparse
import re
import random
import unicodedata
from collections import defaultdict, Counter
from pathlib import Path
from tqdm import tqdm
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
try:
from pypinyin import lazy_pinyin
PYPINYIN_AVAILABLE = True
except ImportError:
PYPINYIN_AVAILABLE = False
try:
from opencc import OpenCC
OPENCC = OpenCC("t2s")
OPENCC_AVAILABLE = True
except Exception:
OPENCC = None
OPENCC_AVAILABLE = False
# 添加项目路径
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(script_dir, 'ChineseErrorCorrector'))
def load_model(base_model_path, lora_path=None, device="auto"):
"""加载模型"""
print(f"加载基础模型: {base_model_path}")
if device == "auto":
runtime_device = "cuda" if torch.cuda.is_available() else "cpu"
elif device == "cuda" and not torch.cuda.is_available():
print("WARNING: 未检测到可用 CUDA,自动切换到 CPU")
runtime_device = "cpu"
else:
runtime_device = device
print(f"推理设备: {runtime_device}")
tokenizer = AutoTokenizer.from_pretrained(base_model_path, trust_remote_code=True)
if runtime_device == "cpu":
model = AutoModelForCausalLM.from_pretrained(
base_model_path,
torch_dtype=torch.float32,
device_map=None,
trust_remote_code=True
)
model = model.to("cpu")
else:
model = AutoModelForCausalLM.from_pretrained(
base_model_path,
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True
)
if lora_path and os.path.exists(lora_path):
print(f"加载 LoRA 权重: {lora_path}")
model = PeftModel.from_pretrained(model, lora_path)
model = model.merge_and_unload() # 合并 LoRA 权重
if runtime_device == "cpu":
model = model.to("cpu")
model.eval()
return model, tokenizer
def get_model_device(model):
try:
return model.device
except Exception:
return next(model.parameters()).device
def predict(model, tokenizer, text, max_length=256, num_beams=1):
"""单条预测,支持 beam search"""
messages = [
{"role": "user", "content": text}
]
input_text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
device = get_model_device(model)
inputs = tokenizer(input_text, return_tensors="pt").to(device)
gen_kwargs = dict(
max_new_tokens=max_length,
do_sample=False,
pad_token_id=tokenizer.eos_token_id,
)
if num_beams > 1:
gen_kwargs["num_beams"] = num_beams
gen_kwargs["early_stopping"] = True
with torch.no_grad():
outputs = model.generate(**inputs, **gen_kwargs)
response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
return response.strip()
def resolve_path(path):
if os.path.isabs(path):
return path
return os.path.join(script_dir, path)
def extract_query_text(raw_input_text):
"""从 prompt+输入中提取真正的 ASR 句子。"""
if ":" in raw_input_text:
return raw_input_text.rsplit(":", 1)[-1].strip()
return raw_input_text.strip()
def extract_candidate_text(record):
"""从 JSON 记录里提取候选正确句。"""
if not isinstance(record, dict):
return ""
conversations = record.get("conversations")
if isinstance(conversations, list) and len(conversations) >= 2:
assistant = conversations[1]
if isinstance(assistant, dict):
text = str(assistant.get("value", "")).strip()
if text:
return text
for key in ("target", "reference", "text", "value"):
if key in record:
text = str(record.get(key, "")).strip()
if text:
return text
return ""
def normalize_candidate_text(text):
text = str(text).strip()
text = re.sub(r"\s+", "", text)
return text
RETRIEVAL_PUNCT_RE = re.compile(
r"[,。!?;:、,.!?;:·…“”\"'‘’`~\-—_()()【】\[\]《》<>「」『』\s]+"
)
KEEP_QUOTES_PUNCT_RE = re.compile(
r"[,。!?;:、,.!?;:·…\"'`~\-—_()()【】\[\]《》<>\s]+"
)
STRONG_PUNCT_SPLIT_RE = re.compile(
r"[。!?;;\n]+|(?<=[”’」』])(?=[\u4e00-\u9fffA-Za-z0-9])"
)
CLAUSE_PUNCT_SPLIT_RE = re.compile(
r"[,。!?;:、,.!?;:\n]+|(?<=[”’」』])(?=[\u4e00-\u9fffA-Za-z0-9])"
)
SOURCE_IGNORE_PARTS = {".git", "__pycache__", "vendor"}
def normalize_retrieval_text(text):
"""
检索规范化:
1) Unicode 归一化
2) 可选繁转简(如果 opencc 可用)
3) 去标点/空白
"""
text = str(text).strip()
if not text:
return ""
text = unicodedata.normalize("NFKC", text)
if OPENCC_AVAILABLE and OPENCC is not None:
try:
text = OPENCC.convert(text)
except Exception:
pass
text = RETRIEVAL_PUNCT_RE.sub("", text)
return text
def normalize_runtime_base_text(text):
text = str(text).strip()
if not text:
return ""
text = unicodedata.normalize("NFKC", text)
if OPENCC_AVAILABLE and OPENCC is not None:
try:
text = OPENCC.convert(text)
except Exception:
pass
text = re.sub(r"\s+", "", text)
return text
def normalize_text_keep_quotes(text):
text = normalize_runtime_base_text(text)
if not text:
return ""
return KEEP_QUOTES_PUNCT_RE.sub("", text)
def build_candidate_text_variants(text, min_len=2, max_len=64):
base = normalize_runtime_base_text(text)
if not base:
return []
variants = []
seen = set()
for candidate in (
normalize_retrieval_text(base),
normalize_text_keep_quotes(base),
):
candidate = str(candidate).strip()
candidate_norm = normalize_retrieval_text(candidate)
if not candidate_norm:
continue
if not (min_len <= len(candidate_norm) <= max_len):
continue
if candidate in seen:
continue
seen.add(candidate)
variants.append(candidate)
return variants
def normalize_retrieval_output_text(text):
normalized = normalize_runtime_base_text(text)
if normalized:
return normalized
return str(text).strip()
def split_nonempty_parts(text, pattern):
parts = []
for part in pattern.split(str(text)):
part = str(part).strip()
if part:
parts.append(part)
return parts
def build_clause_windows(units, min_len=2, max_len=64, max_windows=96):
windows = []
seen = set()
for start in range(len(units)):
current = []
for end in range(start, len(units)):
current.append(units[end])
merged = "".join(current).strip()
merged_norm = normalize_retrieval_text(merged)
if len(merged_norm) > max_len:
break
if len(merged_norm) < min_len:
continue
if merged in seen:
continue
seen.add(merged)
windows.append(merged)
if len(windows) >= max_windows:
return windows
return windows
def build_normalized_projection(text):
norm_chars = []
norm_to_raw = []
for raw_idx, raw_char in enumerate(str(text)):
piece = unicodedata.normalize("NFKC", raw_char)
if OPENCC_AVAILABLE and OPENCC is not None:
try:
piece = OPENCC.convert(piece)
except Exception:
pass
for ch in piece:
if RETRIEVAL_PUNCT_RE.fullmatch(ch):
continue
norm_chars.append(ch)
norm_to_raw.append(raw_idx)
return "".join(norm_chars), norm_to_raw
def slice_raw_span_by_projection(text, norm_to_raw, start, end):
if start < 0 or end <= start or end > len(norm_to_raw):
return ""
raw_start = norm_to_raw[start]
raw_end = norm_to_raw[end - 1]
return str(text)[raw_start:raw_end + 1].strip()
def build_char_window_spans(text, query_norm, min_len=2, max_len=64, max_windows=128):
projected_norm, norm_to_raw = build_normalized_projection(text)
if not projected_norm or not norm_to_raw:
return []
q_len = len(query_norm)
size_candidates = sorted({
max(min_len, min(max_len, q_len - 6)),
max(min_len, min(max_len, q_len - 2)),
max(min_len, min(max_len, q_len)),
max(min_len, min(max_len, q_len + 4)),
max(min_len, min(max_len, q_len + 8)),
max(min_len, min(max_len, q_len + 12)),
})
step = max(1, min(8, max(q_len // 3, 1)))
spans = []
seen = set()
for size in size_candidates:
if size <= 0 or size > len(projected_norm):
continue
starts = list(range(0, len(projected_norm) - size + 1, step))
last_start = len(projected_norm) - size
if not starts:
starts = [0]
elif starts[-1] != last_start:
starts.append(last_start)
for start in starts:
raw_span = slice_raw_span_by_projection(text, norm_to_raw, start, start + size)
if not raw_span or raw_span in seen:
continue
seen.add(raw_span)
spans.append(raw_span)
if len(spans) >= max_windows:
return spans
return spans
def score_retrieval_text_match(query_norm, candidate_norm, query_char=None, query_pinyin=None):
if not query_norm or not candidate_norm:
return None
query_char = query_char or char_ngrams(query_norm, n=2)
candidate_char = char_ngrams(candidate_norm, n=2)
if not query_char or not candidate_char:
return None
char_overlap = len(query_char & candidate_char)
if char_overlap <= 0:
return None
char_coverage = char_overlap / len(query_char)
char_precision = char_overlap / len(candidate_char)
char_score = 0.75 * char_coverage + 0.25 * char_precision
score = char_score
pinyin_coverage = 0.0
if query_pinyin:
candidate_pinyin = pinyin_ngrams(candidate_norm, n=2)
if candidate_pinyin:
pinyin_overlap = len(query_pinyin & candidate_pinyin)
pinyin_coverage = pinyin_overlap / len(query_pinyin) if query_pinyin else 0.0
pinyin_precision = pinyin_overlap / len(candidate_pinyin)
pinyin_score = 0.75 * pinyin_coverage + 0.25 * pinyin_precision
score = 0.7 * char_score + 0.3 * pinyin_score
length_gap = abs(len(candidate_norm) - len(query_norm)) / max(len(query_norm), 1)
score -= 0.08 * min(length_gap, 2.0)
if candidate_norm == query_norm:
score += 0.25
elif query_norm in candidate_norm or candidate_norm in query_norm:
score += 0.10
return {
"score": score,
"char_coverage": char_coverage,
"char_precision": char_precision,
"pinyin_coverage": pinyin_coverage,
}
def patch_query_with_candidate_span(
query_text,
candidate_text,
patch_min_len_ratio=0.40,
patch_max_window_delta=6,
patch_max_local_edit_ratio=0.45,
patch_min_align_score=0.45,
):
query_norm, query_norm_to_raw = build_normalized_projection(query_text)
candidate_norm = normalize_retrieval_text(candidate_text)
if not query_norm or not query_norm_to_raw or not candidate_norm:
return None
q_len = len(query_norm)
c_len = len(candidate_norm)
min_patch_len = max(2, int(round(q_len * patch_min_len_ratio)))
if c_len < min_patch_len or c_len >= q_len:
return None
candidate_char = char_ngrams(candidate_norm, n=2)
candidate_pinyin = pinyin_ngrams(candidate_norm, n=2)
if not candidate_char:
return None
max_window_delta = max(1, patch_max_window_delta)
min_window_len = max(1, c_len - max_window_delta)
max_window_len = min(q_len, c_len + max_window_delta)
best = None
for window_len in range(min_window_len, max_window_len + 1):
for start in range(0, q_len - window_len + 1):
window_norm = query_norm[start:start + window_len]
metrics = score_retrieval_text_match(
candidate_norm,
window_norm,
query_char=candidate_char,
query_pinyin=candidate_pinyin,
)
if not metrics:
continue
local_edit_ratio = levenshtein_distance(candidate_norm, window_norm) / max(max(c_len, window_len), 1)
if local_edit_ratio > patch_max_local_edit_ratio:
continue
length_gap = abs(window_len - c_len) / max(c_len, 1)
alignment_score = (
0.45 * metrics["char_coverage"]
+ 0.20 * metrics["pinyin_coverage"]
+ 0.35 * (1.0 - local_edit_ratio)
- 0.08 * min(length_gap, 2.0)
)
if window_norm == candidate_norm:
alignment_score += 0.10
elif candidate_norm in window_norm or window_norm in candidate_norm:
alignment_score += 0.05
item = {
"start": start,
"end": start + window_len,
"window_norm": window_norm,
"alignment_score": alignment_score,
"local_edit_ratio": local_edit_ratio,
"length_gap": length_gap,
}
if best is None or (
item["alignment_score"],
-item["local_edit_ratio"],
-item["length_gap"],
) > (
best["alignment_score"],
-best["local_edit_ratio"],
-best["length_gap"],
):
best = item
if best is None or best["alignment_score"] < patch_min_align_score:
return None
raw_start = query_norm_to_raw[best["start"]]
raw_end = query_norm_to_raw[best["end"] - 1]
candidate_insert_text = normalize_retrieval_text(candidate_text)
if not candidate_insert_text:
return None
patched_text = (
str(query_text)[:raw_start]
+ candidate_insert_text
+ str(query_text)[raw_end + 1:]
)
patched_text = normalize_candidate_text(patched_text)
patched_norm = normalize_retrieval_text(patched_text)
if not patched_text or not patched_norm:
return None
length_delta_ratio = abs(len(patched_norm) - q_len) / max(q_len, 1)
if length_delta_ratio > 0.20:
return None
if patched_text == normalize_candidate_text(query_text):
return None
return {
"patched_text": patched_text,
"patched_norm": patched_norm,
"alignment_score": best["alignment_score"],
"local_edit_ratio": best["local_edit_ratio"],
"matched_window_norm": best["window_norm"],
}
def extract_local_span_candidates(
doc_text,
query_text,
min_len=2,
max_len=64,
local_top_k=12,
enable_patch=False,
min_full_span_ratio=0.80,
prefer_full_candidate_min_score=0.45,
patch_min_len_ratio=0.40,
patch_max_window_delta=6,
patch_max_local_edit_ratio=0.45,
patch_min_align_score=0.45,
):
query_norm = normalize_retrieval_text(query_text)
if not query_norm:
return []
raw_spans = []
seen_raw_spans = set()
def add_raw_span(raw_span):
raw_span = str(raw_span).strip()
if not raw_span or raw_span in seen_raw_spans:
return
seen_raw_spans.add(raw_span)
raw_spans.append(raw_span)
doc_norm = normalize_retrieval_text(doc_text)
if min_len <= len(doc_norm) <= max_len:
add_raw_span(doc_text)
projected_norm, norm_to_raw = build_normalized_projection(doc_text)
if projected_norm and norm_to_raw:
search_start = 0
hit_count = 0
while hit_count < 8:
pos = projected_norm.find(query_norm, search_start)
if pos < 0:
break
add_raw_span(
slice_raw_span_by_projection(
doc_text,
norm_to_raw,
pos,
pos + len(query_norm),
)
)
for extra in (2, 4, 8):
add_raw_span(
slice_raw_span_by_projection(
doc_text,
norm_to_raw,
max(0, pos - extra),
min(len(projected_norm), pos + len(query_norm) + extra),
)
)
search_start = pos + 1
hit_count += 1
clause_units = split_nonempty_parts(doc_text, CLAUSE_PUNCT_SPLIT_RE)
for window in build_clause_windows(
clause_units,
min_len=min_len,
max_len=max_len,
max_windows=max(local_top_k * 8, 32),
):
add_raw_span(window)
for span in build_char_window_spans(
doc_text,
query_norm,
min_len=min_len,
max_len=max_len,
max_windows=max(local_top_k * 10, 48),
):
add_raw_span(span)
query_char = char_ngrams(query_norm, n=2)
query_pinyin = pinyin_ngrams(query_norm, n=2)
candidates_by_text = {}
for raw_span in raw_spans:
for candidate_text in build_candidate_text_variants(
raw_span,
min_len=min_len,
max_len=max_len,
):
candidate_norm = normalize_retrieval_text(candidate_text)
if not candidate_norm:
continue
replace_mode = "full"
patch_info = None
final_text = candidate_text
final_norm = candidate_norm
min_full_span_len = max(min_len, int(round(len(query_norm) * min_full_span_ratio)))
if len(candidate_norm) < min_full_span_len:
if not enable_patch:
continue
patch_info = patch_query_with_candidate_span(
query_text=query_text,
candidate_text=candidate_text,
patch_min_len_ratio=patch_min_len_ratio,
patch_max_window_delta=patch_max_window_delta,
patch_max_local_edit_ratio=patch_max_local_edit_ratio,
patch_min_align_score=patch_min_align_score,
)
if not patch_info:
continue
replace_mode = "patch"
final_text = patch_info["patched_text"]
final_norm = patch_info["patched_norm"]
metrics = score_retrieval_text_match(
query_norm,
final_norm,
query_char=query_char,
query_pinyin=query_pinyin,
)
if not metrics:
continue
local_match_score = metrics["score"]
if patch_info is not None:
local_match_score = 0.75 * metrics["score"] + 0.25 * patch_info["alignment_score"]
item = {
"text": final_text,
"norm_text": final_norm,
"local_match_score": local_match_score,
"char_coverage": metrics["char_coverage"],
"char_precision": metrics["char_precision"],
"pinyin_coverage": metrics["pinyin_coverage"],
"replace_mode": replace_mode,
"source_span_text": candidate_text,
"source_span_norm": candidate_norm,
"patch_alignment_score": patch_info["alignment_score"] if patch_info else None,
"patch_local_edit_ratio": patch_info["local_edit_ratio"] if patch_info else None,
}
prev = candidates_by_text.get(final_text)
if prev is None or item["local_match_score"] > prev["local_match_score"]:
candidates_by_text[final_text] = item
candidate_values = list(candidates_by_text.values())
has_good_full_candidate = any(
item.get("replace_mode") == "full"
and item.get("local_match_score", 0.0) >= prefer_full_candidate_min_score
for item in candidate_values
)
if has_good_full_candidate:
candidate_values = [item for item in candidate_values if item.get("replace_mode") == "full"]
candidates = sorted(
candidate_values,
key=lambda x: (
x["local_match_score"],
x["char_coverage"],
-abs(len(x["norm_text"]) - len(query_norm)),
),
reverse=True,
)
return candidates[:local_top_k]
def split_text_to_candidates(text, min_len=2, max_len=64):
"""
把长文本切分为可检索片段:
- 短句直接保留
- 长句按常见中文标点切分
"""
text = normalize_candidate_text(text)
if not text:
return []
if min_len <= len(text) <= max_len:
return [text]
pieces = re.split(r"[,。!?;:、,.!?;:]", text)
out = []
for p in pieces:
p = normalize_candidate_text(p)
if min_len <= len(p) <= max_len:
out.append(p)
return out
def is_chinese_poetry_source(source_name):
source = str(source_name).replace("\\", "/").lower()
return "chinese-poetry" in source
def iter_text_fields_from_json(obj):
"""递归提取 JSON 中潜在的正文文本字段。"""
if isinstance(obj, dict):
for k, v in obj.items():
if k in {"paragraphs", "content", "contents", "text", "value", "sentence"}:
if isinstance(v, str):
yield v
elif isinstance(v, list):
for item in v:
if isinstance(item, str):
yield item
# 继续深入递归,兼容不同数据结构
if isinstance(v, (dict, list)):
yield from iter_text_fields_from_json(v)
elif isinstance(obj, list):
for item in obj:
yield from iter_text_fields_from_json(item)
def char_ngrams(text, n=2):
if not text:
return set()
if len(text) < n:
return {text}
return {text[i:i + n] for i in range(len(text) - n + 1)}
def pinyin_ngrams(text, n=2):
if not PYPINYIN_AVAILABLE or not text:
return set()
tokens = lazy_pinyin(text, errors=lambda x: list(x))
tokens = [t for t in tokens if t]
if not tokens:
return set()
if len(tokens) < n:
return {"_".join(tokens)}
return {"_".join(tokens[i:i + n]) for i in range(len(tokens) - n + 1)}
def jaccard(a, b):
if not a or not b:
return 0.0
inter = len(a & b)
if inter == 0:
return 0.0
return inter / len(a | b)
def levenshtein_distance(a, b):
if a == b:
return 0
if not a:
return len(b)
if not b:
return len(a)
if len(a) < len(b):
a, b = b, a
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i]
for j, cb in enumerate(b, 1):
cost = 0 if ca == cb else 1
cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost))
prev = cur
return prev[-1]
def load_retrieval_texts(
corpus_file="",
source_files="",
min_len=2,
max_len=64,
max_candidates=80000,
match_mode="doc_span",
doc_max_len=512,
):
"""
加载检索候选语料。
优先使用 corpus_file;否则按 source_files 读取训练 JSONL。
"""
text_list = []
text_key_to_text = {}
source_stats = Counter()
used_sources = []
text_source_labels = defaultdict(set)
rng = random.Random(42)
def add_candidate(text, source_name):
if len(text_list) >= max_candidates:
return
raw_text = str(text).strip()
if not raw_text:
return
source_label = "poetry" if is_chinese_poetry_source(source_name) else "non_poetry"
if match_mode == "doc_span":
dedup_key = normalize_retrieval_text(raw_text)
stored_text = raw_text
if not (min_len <= len(dedup_key) <= doc_max_len):
return
else:
stored_text = normalize_candidate_text(raw_text)
dedup_key = stored_text
if not (min_len <= len(stored_text) <= max_len):
return
existing_text = text_key_to_text.get(dedup_key)
if existing_text is not None:
text_source_labels[existing_text].add(source_label)
return
text_key_to_text[dedup_key] = stored_text
text_list.append(stored_text)
source_stats[source_name] += 1
text_source_labels[stored_text].add(source_label)
def add_from_raw_text(text, source_name):
if match_mode == "doc_span":
add_candidate(text, source_name)
return
for cand in split_text_to_candidates(text, min_len=min_len, max_len=max_len):
add_candidate(cand, source_name)
def load_one_jsonl_file(path, source_name=None):
if not os.path.exists(path):
return 0
source_name = source_name or path
count = 0
with open(path, "r", encoding="utf-8") as f:
for line in f:
if len(text_list) >= max_candidates:
break
line = line.strip()
if not line:
continue
text = ""
try:
obj = json.loads(line)
# 训练样本优先走固定字段抽取
text = extract_candidate_text(obj)
if text:
add_from_raw_text(text, source_name=source_name)
count += 1
continue
# 兜底:递归抽取文本字段
for t in iter_text_fields_from_json(obj):
add_from_raw_text(t, source_name=source_name)
except json.JSONDecodeError:
add_from_raw_text(line, source_name=source_name)
count += 1
return count
def load_one_json_file(path, source_name=None):
if not os.path.exists(path):
return 0
source_name = source_name or path
count = 0
try:
with open(path, "r", encoding="utf-8") as f:
obj = json.load(f)
except Exception:
return 0
for t in iter_text_fields_from_json(obj):
if len(text_list) >= max_candidates:
break
before = len(text_list)
add_from_raw_text(t, source_name=source_name)
if len(text_list) > before:
count += 1
return count
def load_one_source(path):
if not os.path.exists(path):
return 0
p = Path(path)
total = 0
if p.is_file():
suffix = p.suffix.lower()
if suffix == ".jsonl":
total += load_one_jsonl_file(path, source_name=path)
elif suffix == ".json":
total += load_one_json_file(path, source_name=path)
else:
# 纯文本一行一条
with open(path, "r", encoding="utf-8") as f:
for line in f:
if len(text_list) >= max_candidates:
break
before = len(text_list)
add_from_raw_text(line.strip(), source_name=path)
if len(text_list) > before:
total += 1
used_sources.append(path)
return total
# 目录:递归读取 json/jsonl
json_files = [
fp for fp in p.rglob("*.json")
if not any(part in SOURCE_IGNORE_PARTS for part in fp.parts)
]
jsonl_files = [
fp for fp in p.rglob("*.jsonl")
if not any(part in SOURCE_IGNORE_PARTS for part in fp.parts)
]
txt_files = [
fp for fp in p.rglob("*.txt")
if not any(part in SOURCE_IGNORE_PARTS for part in fp.parts)
]
rng.shuffle(json_files)
rng.shuffle(jsonl_files)
rng.shuffle(txt_files)
for fp in jsonl_files:
if len(text_list) >= max_candidates:
break
total += load_one_jsonl_file(str(fp), source_name=path)
for fp in json_files:
if len(text_list) >= max_candidates:
break
total += load_one_json_file(str(fp), source_name=path)
for fp in txt_files:
if len(text_list) >= max_candidates:
break
with open(fp, "r", encoding="utf-8") as f:
for line in f:
if len(text_list) >= max_candidates:
break
before = len(text_list)
add_from_raw_text(line.strip(), source_name=path)
if len(text_list) > before:
total += 1
used_sources.append(path)
return total
if corpus_file:
corpus_path = resolve_path(corpus_file)
load_one_source(corpus_path)
if not text_list:
if not source_files:
source_files = (
"retrieval_extra/liezi.jsonl,"
"retrieval_extra/textbook_prose_manual.jsonl,"
"retrieval_extra/textbook_poetry_manual.jsonl,"
"retrieval_extra/yuefu_history_manual.jsonl,"
"retrieval_extra/yuanqu_dialogue_manual.jsonl,"
"retrieval_extra/classical_modern_originals.jsonl,"
"chinese-poetry"
)
for part in source_files.split(","):
if len(text_list) >= max_candidates:
break
part = part.strip()
if not part:
continue
load_one_source(resolve_path(part))
return text_list, used_sources, dict(source_stats), dict(text_source_labels)
def filter_eval_targets_from_retrieval(retrieval_texts, text_source_labels, eval_references):
"""
从检索库中剔除评测集 target,但保留 chinese-poetry 来源的同名句子。
"""
eval_targets = set()
for ref in eval_references:
ref_norm = normalize_candidate_text(ref)
if ref_norm:
eval_targets.add(ref_norm)
if not eval_targets:
return retrieval_texts, 0, 0, 0
filtered_texts = []
removed_non_poetry = 0
kept_poetry_overlap = 0
for text in retrieval_texts:
if text not in eval_targets:
filtered_texts.append(text)
continue
labels = set(text_source_labels.get(text, []))
if "poetry" in labels:
# 用户要求 chinese-poetry 部分不动
filtered_texts.append(text)
kept_poetry_overlap += 1
else:
removed_non_poetry += 1
return filtered_texts, removed_non_poetry, kept_poetry_overlap, len(eval_targets)
class RetrievalIndex:
"""轻量检索索引:字符 n-gram 倒排 + 可选拼音重评分。"""
def __init__(self, texts, match_mode="doc_span"):
# 使用规范化文本建索引(去标点 + 可选繁转简),但保留原始文本用于模型重排
self.match_mode = match_mode
self.texts = []
self.norm_texts = []
seen_norm = set()
for text in texts:
norm = normalize_retrieval_text(text)
if len(norm) < 2:
continue
if norm in seen_norm:
continue
seen_norm.add(norm)
self.texts.append(text)
self.norm_texts.append(norm)
self.lengths = [len(t) for t in self.norm_texts]
self.char_gram_sizes = []
self.inverted = defaultdict(list)
for idx, norm_text in enumerate(self.norm_texts):
grams = char_ngrams(norm_text, n=2)
self.char_gram_sizes.append(max(len(grams), 1))
for gram in grams:
self.inverted[gram].append(idx)
self.pinyin_cache = {}
def get_pinyin_grams(self, idx):
if idx not in self.pinyin_cache:
self.pinyin_cache[idx] = pinyin_ngrams(self.norm_texts[idx], n=2)
return self.pinyin_cache[idx]
def retrieve(
self,
query,
top_k=30,
prefilter_k=600,
length_window=8,
):
query_norm = normalize_retrieval_text(query)
if not query_norm:
return []
q_char = char_ngrams(query_norm, n=2)
if not q_char:
return []
q_len = len(query_norm)
overlap_counter = defaultdict(int)
for gram in q_char:
for idx in self.inverted.get(gram, []):
if self.match_mode == "doc_span":
if self.lengths[idx] + length_window < q_len:
continue
else:
if abs(self.lengths[idx] - q_len) > length_window:
continue
overlap_counter[idx] += 1
if not overlap_counter:
return []
ranked_by_overlap = sorted(
overlap_counter.items(),
key=lambda x: x[1],
reverse=True
)[:max(prefilter_k, top_k)]
q_pinyin = pinyin_ngrams(query_norm, n=2)
candidates = []
for idx, overlap in ranked_by_overlap:
char_coverage = overlap / len(q_char)
char_precision = overlap / self.char_gram_sizes[idx]
char_score = 0.75 * char_coverage + 0.25 * char_precision
if q_pinyin:
doc_pinyin = self.get_pinyin_grams(idx)
py_overlap = len(q_pinyin & doc_pinyin)
py_cov = py_overlap / len(q_pinyin) if q_pinyin else 0.0
py_prec = py_overlap / max(len(doc_pinyin), 1)
py_score = 0.75 * py_cov + 0.25 * py_prec
score = 0.7 * char_score + 0.3 * py_score
else:
py_cov = 0.0
score = char_score
if query_norm == self.norm_texts[idx]:
score += 0.15
elif query_norm in self.norm_texts[idx]:
score += 0.08
if self.match_mode == "doc_span":
extra_len = max(self.lengths[idx] - q_len, 0) / max(q_len, 1)
score -= 0.02 * min(extra_len, 5.0)
else:
length_gap = abs(self.lengths[idx] - q_len) / max(q_len, 1)
score -= 0.05 * min(length_gap, 2.0)
candidates.append({
"text": self.texts[idx],
"norm_text": self.norm_texts[idx],
"retrieval_score": score,
"char_coverage": char_coverage,
"char_precision": char_precision,
"pinyin_coverage": py_cov,
})
candidates.sort(key=lambda x: x["retrieval_score"], reverse=True)
return candidates[:top_k]
def build_doc_span_candidates(query_text, doc_hits, args):
merged = {}
for doc_item in doc_hits[:max(args.retrieval_doc_top_k, 1)]:
local_candidates = extract_local_span_candidates(
doc_item["text"],
query_text,
min_len=args.retrieval_min_len,
max_len=args.retrieval_max_len,
local_top_k=args.retrieval_local_candidate_k,
enable_patch=args.retrieval_enable_patch,
min_full_span_ratio=args.retrieval_min_full_span_ratio,
prefer_full_candidate_min_score=args.retrieval_prefer_full_candidate_min_score,
patch_min_len_ratio=args.retrieval_patch_min_len_ratio,
patch_max_window_delta=args.retrieval_patch_max_window_delta,
patch_max_local_edit_ratio=args.retrieval_patch_max_local_edit_ratio,
patch_min_align_score=args.retrieval_patch_min_align_score,
)
for candidate in local_candidates:
combined_score = 0.35 * doc_item["retrieval_score"] + 0.65 * candidate["local_match_score"]
output_text = normalize_retrieval_output_text(candidate["text"])
output_norm = normalize_retrieval_text(output_text) or candidate["norm_text"]
item = {
"text": output_text,
"raw_text": candidate["text"],
"norm_text": output_norm,
"retrieval_score": combined_score,
"doc_retrieval_score": doc_item["retrieval_score"],
"local_match_score": candidate["local_match_score"],
"char_coverage": candidate["char_coverage"],
"char_precision": candidate["char_precision"],
"pinyin_coverage": candidate["pinyin_coverage"],
"doc_text": doc_item["text"],
"replace_mode": candidate.get("replace_mode"),
"source_span_text": candidate.get("source_span_text"),
"patch_alignment_score": candidate.get("patch_alignment_score"),
"patch_local_edit_ratio": candidate.get("patch_local_edit_ratio"),
}
prev = merged.get(output_text)
if prev is None or item["retrieval_score"] > prev["retrieval_score"]:
merged[output_text] = item
return sorted(
merged.values(),
key=lambda x: (
x["retrieval_score"],
x["local_match_score"],
x["char_coverage"],
),
reverse=True,
)[:args.retrieval_top_k]
def should_accept_doc_span_candidate(best_item, query_norm, edit_ratio, rerank_margin, args):
span_norm = normalize_retrieval_text(best_item.get("source_span_text") or best_item.get("text", ""))
span_len_ratio = None
if query_norm and span_norm:
span_len_ratio = len(span_norm) / max(len(query_norm), 1)
replace_mode = best_item.get("replace_mode") or "full"
if replace_mode == "patch":
if not args.retrieval_enable_patch:
return False, span_len_ratio, "patch_disabled"
if best_item["retrieval_score"] < args.retrieval_patch_min_score:
return False, span_len_ratio, "patch_low_score"
if (best_item.get("patch_alignment_score") or 0.0) < args.retrieval_patch_use_align_score:
return False, span_len_ratio, "patch_low_align"
if rerank_margin < args.retrieval_patch_margin:
return False, span_len_ratio, "patch_low_margin"
if edit_ratio > args.retrieval_patch_max_edit_ratio:
return False, span_len_ratio, "patch_high_edit"
return True, span_len_ratio, "patch_ok"
if span_len_ratio is not None:
if span_len_ratio < args.retrieval_full_min_span_ratio:
return False, span_len_ratio, "full_too_short"
if span_len_ratio > args.retrieval_full_max_span_ratio:
return False, span_len_ratio, "full_too_long"
if query_norm and len(query_norm) <= args.retrieval_short_query_max_len:
if best_item.get("local_match_score", 0.0) < args.retrieval_short_query_min_local_score:
return False, span_len_ratio, "full_short_query_low_local"
return True, span_len_ratio, "full_ok"
def score_candidate_with_model(model, tokenizer, raw_input_text, candidate_text, prompt_cache):
"""
计算候选句在条件 p(candidate|input) 下的平均 token log-prob。
分值越大越好(越不负)。
"""
if raw_input_text in prompt_cache:
prompt_text, prompt_ids = prompt_cache[raw_input_text]
else:
device = get_model_device(model)
messages = [{"role": "user", "content": raw_input_text}]
prompt_text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
prompt_ids = tokenizer(prompt_text, return_tensors="pt")["input_ids"].to(device)
prompt_cache[raw_input_text] = (prompt_text, prompt_ids)
device = get_model_device(model)
full_text = prompt_text + candidate_text
full_ids = tokenizer(full_text, return_tensors="pt")["input_ids"].to(device)
prompt_len = prompt_ids.shape[1]
if full_ids.shape[1] <= prompt_len:
return -1e9
with torch.no_grad():
logits = model(full_ids).logits
shifted_logits = logits[:, :-1, :]
shifted_labels = full_ids[:, 1:]
log_probs = torch.log_softmax(shifted_logits, dim=-1)
token_log_probs = log_probs.gather(-1, shifted_labels.unsqueeze(-1)).squeeze(-1)
# candidate token 对应到 shifted 后的起始位置
start_idx = max(prompt_len - 1, 0)
candidate_log_probs = token_log_probs[:, start_idx:]
return candidate_log_probs.mean().item()
def predict_with_retrieval(
model,
tokenizer,
raw_input_text,
query_text,
args,
retrieval_index,
prompt_cache,
):
"""检索候选 -> 模型重排 -> 不稳则回退生成。"""
if retrieval_index is None:
prediction = predict(model, tokenizer, raw_input_text, num_beams=args.num_beams)
return prediction, {"strategy": "generate_only"}
doc_hits = retrieval_index.retrieve(
query=query_text,
top_k=args.retrieval_top_k,
prefilter_k=args.retrieval_prefilter_k,
length_window=args.retrieval_length_window,
)
if not doc_hits:
prediction = predict(model, tokenizer, raw_input_text, num_beams=args.num_beams)
if args.retrieval_force_replace:
return prediction, {"strategy": "replace_no_candidate_generate"}
return prediction, {"strategy": "generate_no_candidate"}
if args.retrieval_match_mode == "doc_span":
retrieved = build_doc_span_candidates(query_text, doc_hits, args)
else:
retrieved = doc_hits
if not retrieved:
prediction = predict(model, tokenizer, raw_input_text, num_beams=args.num_beams)
if args.retrieval_force_replace:
return prediction, {"strategy": "replace_no_local_span_generate"}
return prediction, {"strategy": "generate_no_local_span"}
rerank_pool = retrieved[:min(args.retrieval_rerank_k, len(retrieved))]
reranked = []
for item in rerank_pool:
item = dict(item)
item["text"] = normalize_retrieval_output_text(item["text"])
item["norm_text"] = normalize_retrieval_text(item["text"]) or item.get("norm_text", "")
lm_score = score_candidate_with_model(
model,
tokenizer,
raw_input_text,
item["text"],
prompt_cache,
)
reranked.append((lm_score, item))
reranked.sort(key=lambda x: x[0], reverse=True)
best_lm, best_item = reranked[0]
second_lm = reranked[1][0] if len(reranked) > 1 else -1e9
rerank_margin = best_lm - second_lm if len(reranked) > 1 else float("inf")
query_norm = normalize_retrieval_text(query_text)
best_norm = best_item.get("norm_text", "")
if query_norm and best_norm:
edit_ratio = levenshtein_distance(query_norm, best_norm) / max(len(query_norm), 1)
else:
edit_ratio = levenshtein_distance(query_text, best_item["text"]) / max(len(query_text), 1)
accept_reason = None
span_len_ratio = None
if args.retrieval_force_replace:
return best_item["text"], {
"strategy": "retrieval_force_replace",
"retrieval_score": best_item["retrieval_score"],
"doc_retrieval_score": best_item.get("doc_retrieval_score"),
"local_match_score": best_item.get("local_match_score"),
"replace_mode": best_item.get("replace_mode"),
"patch_alignment_score": best_item.get("patch_alignment_score"),
"source_span_len_ratio": span_len_ratio,
"retrieval_accept_reason": "force_replace",
"rerank_margin": rerank_margin,
"edit_ratio": edit_ratio,
}
use_retrieval = (
best_item["retrieval_score"] >= args.retrieval_min_score
and rerank_margin >= args.retrieval_margin
and edit_ratio <= args.retrieval_max_edit_ratio
)
if use_retrieval and args.retrieval_match_mode == "doc_span":
use_retrieval, span_len_ratio, accept_reason = should_accept_doc_span_candidate(
best_item,
query_norm,
edit_ratio,
rerank_margin,
args,
)
else:
accept_reason = "base_threshold_failed" if not use_retrieval else "candidate_mode"
if use_retrieval:
return best_item["text"], {
"strategy": "retrieval_rerank",
"retrieval_score": best_item["retrieval_score"],
"doc_retrieval_score": best_item.get("doc_retrieval_score"),
"local_match_score": best_item.get("local_match_score"),
"replace_mode": best_item.get("replace_mode"),
"patch_alignment_score": best_item.get("patch_alignment_score"),
"source_span_len_ratio": span_len_ratio,
"retrieval_accept_reason": accept_reason,
"rerank_margin": rerank_margin,
"edit_ratio": edit_ratio,
}
prediction = predict(model, tokenizer, raw_input_text, num_beams=args.num_beams)
return prediction, {
"strategy": "fallback_generate",
"retrieval_score": best_item["retrieval_score"],
"doc_retrieval_score": best_item.get("doc_retrieval_score"),
"local_match_score": best_item.get("local_match_score"),
"replace_mode": best_item.get("replace_mode"),
"patch_alignment_score": best_item.get("patch_alignment_score"),
"source_span_len_ratio": span_len_ratio,
"retrieval_accept_reason": accept_reason,
"rerank_margin": rerank_margin,
"edit_ratio": edit_ratio,
}
def calculate_metrics(predictions, references):
"""
计算评估指标
- 字符级准确率
- 句子级准确率
"""
total_chars = 0
correct_chars = 0
total_sentences = len(predictions)
correct_sentences = 0
for pred, ref in zip(predictions, references):
# 句子级
if pred == ref:
correct_sentences += 1
# 字符级
for p, r in zip(pred, ref):
total_chars += 1
if p == r:
correct_chars += 1
char_acc = correct_chars / total_chars if total_chars > 0 else 0
sent_acc = correct_sentences / total_sentences if total_sentences > 0 else 0
return {
'char_accuracy': char_acc,
'sentence_accuracy': sent_acc,
'total_sentences': total_sentences,
'correct_sentences': correct_sentences
}
def main():
parser = argparse.ArgumentParser(description='ASR 诗词纠错模型评估')
parser.add_argument('--base_model',
default='ChineseErrorCorrector3-4B',
type=str, help='基础模型路径')
parser.add_argument('--lora_path',
default='output/asr_poetry_lora',
type=str, help='LoRA 权重路径 (可选)')
parser.add_argument('--test_file',
default='train_data_v3/test_real_asr.jsonl',
type=str, help='测试数据路径')
parser.add_argument('--output_file',
default='evaluation_results.jsonl',
type=str, help='评估结果输出')
parser.add_argument('--max_samples',
default=-1,
type=int, help='最大评估样本数 (-1 表示全部)')
parser.add_argument('--num_beams',
default=1,
type=int, help='Beam search 宽度 (1=greedy, 4=beam search)')
parser.add_argument('--device',
default='auto',
choices=['auto', 'cpu', 'cuda'],
type=str, help='推理设备:auto/cpu/cuda')
# 轻量检索重排(默认关闭,保证兼容旧流程)
parser.add_argument('--enable_retrieval',
action='store_true',
help='启用 检索候选+模型重排+回退生成')
parser.add_argument('--retrieval_match_mode',
default='doc_span',
choices=['doc_span', 'candidate'],
type=str,
help='检索模式:doc_span=原文文档召回后局部抽 span;candidate=旧的短句候选模式')
parser.add_argument('--retrieval_force_replace',
action='store_true',
help='直接采用重排第一候选(有候选时不回退生成)')
parser.add_argument('--retrieval_corpus',
default='',
type=str,
help='检索语料路径(jsonl 或 纯文本,一行一条)')
parser.add_argument('--retrieval_source_files',
default='retrieval_extra/liezi.jsonl,retrieval_extra/textbook_prose_manual.jsonl,retrieval_extra/textbook_poetry_manual.jsonl,retrieval_extra/yuefu_history_manual.jsonl,retrieval_extra/yuanqu_dialogue_manual.jsonl,retrieval_extra/classical_modern_originals.jsonl,chinese-poetry',
type=str,
help='当 retrieval_corpus 为空时,按逗号读取文件/目录(可含 chinese-poetry)')
parser.add_argument('--retrieval_min_len',
default=2,
type=int,
help='候选最短长度')
parser.add_argument('--retrieval_max_len',
default=64,
type=int,
help='最终替换候选/局部 span 的最长长度')
parser.add_argument('--retrieval_doc_max_len',
default=512,
type=int,
help='doc_span 模式下单条原文文档的最大规范化长度')
parser.add_argument('--retrieval_max_candidates',
default=1000000,
type=int,
help='检索库最大条数(防止内存过高)')
parser.add_argument('--retrieval_top_k',
default=30,
type=int,
help='检索阶段返回 topK 候选')
parser.add_argument('--retrieval_doc_top_k',
default=8,
type=int,
help='doc_span 模式进入局部 span 抽取的文档数')
parser.add_argument('--retrieval_local_candidate_k',
default=12,
type=int,
help='doc_span 模式每篇文档保留的局部候选数')
parser.add_argument('--retrieval_enable_patch',
action='store_true',
help='doc_span 模式允许短 span 走局部 patch;默认关闭以避免误 patch')
parser.add_argument('--retrieval_min_full_span_ratio',
default=0.90,
type=float,
help='doc_span 模式下候选长度达到输入多少比例时才允许整句替换')
parser.add_argument('--retrieval_prefer_full_candidate_min_score',
default=0.45,
type=float,
help='doc_span 模式中若存在达到该分数的 full 候选,则优先只保留 full 候选')
parser.add_argument('--retrieval_full_min_span_ratio',
default=0.90,
type=float,
help='doc_span 模式最终接管时,full 候选最短长度占输入比例')
parser.add_argument('--retrieval_full_max_span_ratio',
default=1.25,
type=float,
help='doc_span 模式最终接管时,full 候选最长长度占输入比例')
parser.add_argument('--retrieval_short_query_max_len',
default=8,
type=int,
help='doc_span 模式最终接管时,按短句处理的最大长度')
parser.add_argument('--retrieval_short_query_min_local_score',
default=0.52,
type=float,
help='doc_span 模式最终接管时,短句 full 候选的最低局部匹配分')
parser.add_argument('--retrieval_patch_min_len_ratio',
default=0.40,
type=float,
help='doc_span 模式下短 span 至少达到输入多少比例才允许做局部 patch')
parser.add_argument('--retrieval_patch_max_window_delta',
default=6,
type=int,
help='doc_span 局部 patch 时,对齐窗口长度允许偏移的字符数')
parser.add_argument('--retrieval_patch_max_local_edit_ratio',
default=0.45,
type=float,
help='doc_span 局部 patch 时候选与输入局部窗口的最大编辑距离比例')
parser.add_argument('--retrieval_patch_min_align_score',
default=0.45,
type=float,
help='doc_span 局部 patch 时最小局部对齐分数')
parser.add_argument('--retrieval_patch_min_score',
default=0.65,
type=float,
help='doc_span 模式最终接管时,patch 候选最低分数')
parser.add_argument('--retrieval_patch_use_align_score',
default=0.80,
type=float,
help='doc_span 模式最终接管时,patch 候选最低对齐分数')
parser.add_argument('--retrieval_patch_margin',
default=1.00,
type=float,
help='doc_span 模式最终接管时,patch 候选的重排分差阈值')
parser.add_argument('--retrieval_patch_max_edit_ratio',
default=0.20,
type=float,
help='doc_span 模式最终接管时,patch 候选允许的最大编辑距离比例')
parser.add_argument('--retrieval_rerank_k',
default=5,
type=int,
help='进入模型重排的候选数')
parser.add_argument('--retrieval_prefilter_k',
default=600,
type=int,
help='倒排召回后预筛候选数')
parser.add_argument('--retrieval_length_window',
default=8,
type=int,
help='检索长度窗口(与输入长度差)')
parser.add_argument('--retrieval_min_score',
default=0.45,
type=float,
help='检索分数最低阈值')
parser.add_argument('--retrieval_margin',
default=0.10,
type=float,
help='重排最佳与次佳分差阈值')
parser.add_argument('--retrieval_max_edit_ratio',
default=0.50,
type=float,
help='候选与输入编辑距离比例上限')
parser.add_argument('--exclude_eval_targets_from_retrieval',
action='store_true',
help='从非 chinese-poetry 候选中剔除评测集 target(poetry 部分保持不变)')
args = parser.parse_args()
print("=" * 70)
print("ASR 诗词纠错模型评估")
print("=" * 70)
# 加载模型
model, tokenizer = load_model(args.base_model, args.lora_path, device=args.device)
# 加载测试数据
print(f"\n加载测试数据: {args.test_file}")
test_data = []
with open(args.test_file, 'r', encoding='utf-8') as f:
for line in f:
test_data.append(json.loads(line))
if args.max_samples > 0:
test_data = test_data[:args.max_samples]
print(f"测试样本数: {len(test_data)}")
# 构建检索索引
retrieval_index = None
prompt_cache = {}
if args.enable_retrieval:
retrieval_texts, used_sources, source_stats, text_source_labels = load_retrieval_texts(
corpus_file=args.retrieval_corpus,
source_files=args.retrieval_source_files,
min_len=args.retrieval_min_len,
max_len=args.retrieval_max_len,
max_candidates=args.retrieval_max_candidates,
match_mode=args.retrieval_match_mode,
doc_max_len=args.retrieval_doc_max_len,
)
if args.exclude_eval_targets_from_retrieval:
eval_references = []
for item in test_data:
try:
ref = str(item['conversations'][1]['value']).strip()
except Exception:
ref = ""
if ref:
eval_references.append(ref)
before_count = len(retrieval_texts)
retrieval_texts, removed_non_poetry, kept_poetry_overlap, eval_target_count = filter_eval_targets_from_retrieval(
retrieval_texts,
text_source_labels,
eval_references,
)
print("评测集 target 过滤: ON (chinese-poetry 保留)")
print(f" - 评测 target 去重数: {eval_target_count}")
print(f" - 从非 poetry 候选移除: {removed_non_poetry}")
print(f" - 因 poetry 来源保留: {kept_poetry_overlap}")
print(f" - 过滤前/后: {before_count}/{len(retrieval_texts)}")
print("\n检索模块: ON")
print(f"检索模式: {args.retrieval_match_mode}")
print(f"检索规范化: ON (opencc={'yes' if OPENCC_AVAILABLE else 'no'})")
if args.retrieval_match_mode == "doc_span":
print(
"局部 span 参数: "
f"doc_top_k={args.retrieval_doc_top_k}, "
f"local_k={args.retrieval_local_candidate_k}, "
f"doc_max_len={args.retrieval_doc_max_len}, "
f"patch={'on' if args.retrieval_enable_patch else 'off'}, "
f"full_ratio={args.retrieval_min_full_span_ratio:.2f}, "
f"full_keep={args.retrieval_full_min_span_ratio:.2f}-{args.retrieval_full_max_span_ratio:.2f}, "
f"short_q={args.retrieval_short_query_max_len}/{args.retrieval_short_query_min_local_score:.2f}, "
f"prefer_full={args.retrieval_prefer_full_candidate_min_score:.2f}, "
f"patch_min_ratio={args.retrieval_patch_min_len_ratio:.2f}, "
f"patch_edit={args.retrieval_patch_max_local_edit_ratio:.2f}, "
f"patch_align={args.retrieval_patch_min_align_score:.2f}, "
f"patch_use_score={args.retrieval_patch_min_score:.2f}, "
f"patch_use_align={args.retrieval_patch_use_align_score:.2f}"
)
if used_sources:
print("检索语料来源:")
for p in used_sources:
print(f" - {p}")
print(f"检索库去重后条数: {len(retrieval_texts)}")
if source_stats:
print("候选来源分布(Top5):")
for k, v in sorted(source_stats.items(), key=lambda x: x[1], reverse=True)[:5]:
print(f" - {k}: {v}")
if retrieval_texts:
retrieval_index = RetrievalIndex(retrieval_texts, match_mode=args.retrieval_match_mode)
else:
print("WARNING: 检索候选为空,自动回退为纯生成评估")
# 预测
print("\n开始评估...")
predictions = []
references = []
results = []
strategy_counter = Counter()
for item in tqdm(test_data, desc="评估"):
input_text = item['conversations'][0]['value']
query_text = extract_query_text(input_text)
reference = item['conversations'][1]['value']
prediction, debug = predict_with_retrieval(
model=model,
tokenizer=tokenizer,
raw_input_text=input_text,
query_text=query_text,
args=args,
retrieval_index=retrieval_index,
prompt_cache=prompt_cache,
)
predictions.append(prediction)
references.append(reference)
record = {
'input': query_text,
'prediction': prediction,
'reference': reference,
'correct': prediction == reference
}
if args.enable_retrieval:
record.update({
'strategy': debug.get('strategy', 'unknown'),
'retrieval_mode': args.retrieval_match_mode,
'retrieval_score': debug.get('retrieval_score'),
'doc_retrieval_score': debug.get('doc_retrieval_score'),
'local_match_score': debug.get('local_match_score'),
'replace_mode': debug.get('replace_mode'),
'patch_alignment_score': debug.get('patch_alignment_score'),
'source_span_len_ratio': debug.get('source_span_len_ratio'),
'retrieval_accept_reason': debug.get('retrieval_accept_reason'),
'rerank_margin': debug.get('rerank_margin'),
'edit_ratio': debug.get('edit_ratio'),
})
strategy_counter[record['strategy']] += 1
results.append(record)
# 计算指标
metrics = calculate_metrics(predictions, references)
# 打印结果
print("\n" + "=" * 70)
print("评估结果")
print("=" * 70)
print(f"字符级准确率: {metrics['char_accuracy']*100:.2f}%")
print(f"句子级准确率: {metrics['sentence_accuracy']*100:.2f}%")
print(f"正确句子数: {metrics['correct_sentences']}/{metrics['total_sentences']}")
if args.enable_retrieval and strategy_counter:
print("\n策略分布:")
for k, v in strategy_counter.items():
print(f" - {k}: {v}")
# 保存详细结果
with open(args.output_file, 'w', encoding='utf-8') as f:
# 先写入汇总指标
f.write(json.dumps({'metrics': metrics}, ensure_ascii=False) + '\n')
# 再写入详细结果
for result in results:
f.write(json.dumps(result, ensure_ascii=False) + '\n')
print(f"\n详细结果保存到: {args.output_file}")
# 显示一些错误案例
print("\n" + "-" * 70)
print("错误案例(前5个):")
error_count = 0
for result in results:
if not result['correct']:
error_count += 1
print(f"\n[{error_count}]")
print(f" 输入: {result['input']}")
print(f" 预测: {result['prediction']}")
print(f" 正确: {result['reference']}")
if error_count >= 5:
break
if __name__ == '__main__':
main()