warfbro commited on
Commit
fa655ab
·
verified ·
1 Parent(s): 91e2986

Upload ensemble_extract.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. ensemble_extract.py +199 -0
ensemble_extract.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 双模型集成人名提取
3
+ - 模型A (finetune_best.pt) + 模型B (frozen_best.pt) 分别提取
4
+ - 一致 → 直接输出
5
+ - 不一致 → LLM 裁定
6
+ 用法: python ensemble_extract.py <input.xlsx> [output.xlsx]
7
+ """
8
+ import sys
9
+ import torch
10
+ import openpyxl
11
+ import re
12
+
13
+ from config import BIO_ID2LABEL, BIO_LABELS
14
+ from model import ErnieCRF, ErnieCRF2
15
+ from config import ERNIE_LOCAL, CHECKPOINT, CHECKPOINT_FROZEN
16
+
17
+
18
+ def clean_names(names: list) -> list:
19
+ cleaned = []
20
+ for n in names:
21
+ n = re.sub(r"等\d*人?$", "", n)
22
+ if n.strip():
23
+ cleaned.append(n.strip())
24
+ return cleaned
25
+
26
+
27
+ def expand_bracket_names(names: list, title: str) -> list:
28
+ expanded = []
29
+ for name in names:
30
+ idx = title.find(name)
31
+ if idx == -1:
32
+ expanded.append(name)
33
+ continue
34
+ found = False
35
+ # 英文(中文)
36
+ if idx > 0 and title[idx - 1] == "(":
37
+ right = idx + len(name)
38
+ if right < len(title) and title[right] == ")":
39
+ left = idx - 2
40
+ if left >= 0 and re.match(r"[A-Za-z]", title[left]):
41
+ start = left
42
+ while start > 0 and re.match(r"[A-Za-z]", title[start - 1]):
43
+ start -= 1
44
+ found = True
45
+ expanded.append(title[start:right + 1])
46
+ # 中文(英文)
47
+ if not found:
48
+ right = idx + len(name)
49
+ if right < len(title) and title[right] == "(":
50
+ close = title.find(")", right)
51
+ if close != -1 and re.match(r"[A-Za-z]", title[right + 1:close]):
52
+ found = True
53
+ expanded.append(title[idx:close + 1])
54
+ if not found:
55
+ expanded.append(name)
56
+ # 去子串
57
+ deduped = []
58
+ for n in expanded:
59
+ if not any(n != other and n in other for other in expanded):
60
+ deduped.append(n)
61
+ return deduped
62
+
63
+
64
+ def postprocess(names, title):
65
+ names = clean_names(names)
66
+ names = expand_bracket_names(names, title)
67
+ names = [n for n in names if n in title]
68
+ return names
69
+
70
+
71
+ def model_extract(title, model, tokenizer, device):
72
+ chars = list(title)
73
+ ids = [tokenizer.cls_token_id]
74
+ for c in chars:
75
+ ids.extend(tokenizer.encode(c, add_special_tokens=False))
76
+ ids.append(tokenizer.sep_token_id)
77
+
78
+ input_ids = torch.tensor([ids], device=device)
79
+ mask = torch.ones_like(input_ids)
80
+ with torch.no_grad():
81
+ preds = model(input_ids, mask)[0]
82
+ preds = preds[1:1 + len(chars)]
83
+
84
+ names, cur = [], []
85
+ for char, lid in zip(title, preds):
86
+ tag = BIO_ID2LABEL.get(lid, "O")
87
+ if tag == "B-PER":
88
+ if cur:
89
+ names.append("".join(cur))
90
+ cur = [char]
91
+ elif tag == "I-PER" and cur:
92
+ cur.append(char)
93
+ else:
94
+ if cur:
95
+ names.append("".join(cur))
96
+ cur = []
97
+ if cur:
98
+ names.append("".join(cur))
99
+ return names
100
+
101
+
102
+ def load_models(device):
103
+ from transformers import AutoTokenizer
104
+ tokenizer = AutoTokenizer.from_pretrained(ERNIE_LOCAL)
105
+
106
+ model_a = ErnieCRF(ERNIE_LOCAL, len(BIO_LABELS)).to(device)
107
+ model_a.load_state_dict(torch.load(CHECKPOINT, map_location=device, weights_only=True))
108
+ model_a.eval()
109
+
110
+ model_b = ErnieCRF(ERNIE_LOCAL, len(BIO_LABELS)).to(device)
111
+ model_b.load_state_dict(torch.load(CHECKPOINT_FROZEN, map_location=device, weights_only=True))
112
+ model_b.eval()
113
+
114
+ return tokenizer, model_a, model_b
115
+
116
+
117
+ def main():
118
+ if len(sys.argv) < 2:
119
+ print("用法: python ensemble_extract.py <input.xlsx> [output.xlsx]")
120
+ sys.exit(1)
121
+
122
+ input_xlsx = sys.argv[1]
123
+ output_xlsx = sys.argv[2] if len(sys.argv) > 2 else "提取结果_集成.xlsx"
124
+
125
+ device = "cuda" if torch.cuda.is_available() else "cpu"
126
+ print(f"加载双模型 ({device})...")
127
+ tokenizer, model_a, model_b = load_models(device)
128
+
129
+ print(f"读取: {input_xlsx}")
130
+ wb = openpyxl.load_workbook(input_xlsx)
131
+ ws = wb.active
132
+
133
+ out_wb = openpyxl.Workbook()
134
+ out_ws = out_wb.active
135
+ out_ws.append(["A列:原数据", "B列:提取人名", "C列:方法", "D列:姓名字数"])
136
+
137
+ stats = {"一致": 0, "LLM裁定": 0, "未检出": 0}
138
+ disagreements = [] # (row_idx, title, names_a, names_b)
139
+ results_cache = {} # title → final_names
140
+
141
+ for row_idx, row in enumerate(ws.iter_rows(min_row=2, min_col=1, max_col=12, values_only=True)):
142
+ title = str(row[0]) if row[0] else ""
143
+ org = str(row[11]) if len(row) > 11 and row[11] else ""
144
+
145
+ if not title:
146
+ continue
147
+
148
+ clean_title = title
149
+ if org and org in title:
150
+ clean_title = title.replace(org, "").replace(" ", " ").strip()
151
+
152
+ # 双��型分别提取
153
+ raw_a = model_extract(clean_title, model_a, tokenizer, device)
154
+ raw_b = model_extract(clean_title, model_b, tokenizer, device)
155
+ names_a = postprocess(raw_a, title)
156
+ names_b = postprocess(raw_b, title)
157
+
158
+ name_str_a = "、".join(names_a) if names_a else ""
159
+ name_str_b = "、".join(names_b) if names_b else ""
160
+
161
+ if name_str_a == name_str_b:
162
+ # 一致,直接输出
163
+ stats["一致"] += 1
164
+ if not name_str_a:
165
+ stats["未检出"] += 1
166
+ name_len = "、".join(str(len(n)) for n in names_a) if names_a else "0"
167
+ out_ws.append([title, name_str_a, "一致", name_len])
168
+ else:
169
+ # 不一致,缓存等 LLM
170
+ disagreements.append((title, name_str_a, name_str_b))
171
+
172
+ print(f"一致: {stats['一致']} 条 (含未检出)")
173
+ print(f"不一致需LLM裁定: {len(disagreements)} 条")
174
+
175
+ if disagreements:
176
+ from llm_resolver import resolve_batch
177
+ print(f"\n开始LLM裁定...")
178
+ final_names = resolve_batch(disagreements)
179
+
180
+ for (title, na, nb), final in zip(disagreements, final_names):
181
+ stats["LLM裁定"] += 1
182
+ names = [n.strip() for n in final.split("、") if n.strip()] if final else []
183
+ # 后处理
184
+ names = [n for n in names if n in title]
185
+ name_str = "、".join(names) if names else ""
186
+ name_len = "、".join(str(len(n)) for n in names) if names else "0"
187
+ out_ws.append([title, name_str, "LLM裁定", name_len])
188
+
189
+ out_wb.save(output_xlsx)
190
+
191
+ print(f"\n=== 统计 ===")
192
+ print(f"一致: {stats['一致']} 条")
193
+ print(f"LLM裁定: {stats['LLM裁定']} 条")
194
+ print(f"未检出: {stats['未检出']} 条")
195
+ print(f"已保存: {output_xlsx}")
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()