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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from model import PredicateAwareSRL
|
| 2 |
+
import torch, json
|
| 3 |
+
from transformers import AutoTokenizer
|
| 4 |
+
import spacy
|
| 5 |
+
from spacy import cli as spacy_cli
|
| 6 |
+
|
| 7 |
+
_CACHE = {
|
| 8 |
+
"ckpt_path": None,
|
| 9 |
+
"bert_name": None,
|
| 10 |
+
"spacy_model": None,
|
| 11 |
+
"device": None,
|
| 12 |
+
"model": None,
|
| 13 |
+
"tokenizer": None,
|
| 14 |
+
"label2id": None,
|
| 15 |
+
"id2label": None,
|
| 16 |
+
"hparams": None,
|
| 17 |
+
"nlp": None,
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
_CACHE = {
|
| 21 |
+
"model": None, "tokenizer": None, "id2label": None, "nlp": None, "device": None,
|
| 22 |
+
"ckpt_path": None, "bert_name": None, "spacy_model": None,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
def srl_init(model_path, bert_name="bert-base-cased", spacy_model="en_core_web_md"):
|
| 26 |
+
"""
|
| 27 |
+
Call ONCE per session to load and cache model/tokenizer/spaCy.
|
| 28 |
+
After this, you can call: prediction("your sentence here")
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 32 |
+
ckpt = torch.load(model_path, map_location=device)
|
| 33 |
+
hp = ckpt.get("hparams", ckpt.get("hyper_parameters", {}))
|
| 34 |
+
if "bert_name" not in hp:
|
| 35 |
+
hp["bert_name"] = bert_name
|
| 36 |
+
if "num_labels" not in hp:
|
| 37 |
+
label2id = ckpt.get("label2id") or {v:k for k,v in ckpt["id2label"].items()}
|
| 38 |
+
hp["num_labels"] = len(label2id)
|
| 39 |
+
|
| 40 |
+
model = PredicateAwareSRL(**hp).to(device).eval()
|
| 41 |
+
state = ckpt.get("model_state") or ckpt.get("state_dict") or ckpt
|
| 42 |
+
model.load_state_dict(state)
|
| 43 |
+
|
| 44 |
+
tokenizer = AutoTokenizer.from_pretrained(hp.get("bert_name", bert_name), use_fast=True)
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
nlp = spacy.load(spacy_model, disable=["parser","ner","lemmatizer"])
|
| 48 |
+
except OSError:
|
| 49 |
+
spacy_cli.download(spacy_model)
|
| 50 |
+
nlp = spacy.load(spacy_model, disable=["parser","ner","lemmatizer"])
|
| 51 |
+
|
| 52 |
+
label2id = ckpt.get("label2id") or {v:k for k,v in ckpt["id2label"].items()}
|
| 53 |
+
id2label = {int(v): k for k, v in label2id.items()}
|
| 54 |
+
|
| 55 |
+
_CACHE.update({
|
| 56 |
+
"model": model, "tokenizer": tokenizer, "id2label": id2label,
|
| 57 |
+
"nlp": nlp, "device": device, "ckpt_path": model_path,
|
| 58 |
+
"bert_name": hp.get("bert_name", bert_name), "spacy_model": spacy_model,
|
| 59 |
+
})
|
| 60 |
+
torch.set_grad_enabled(False)
|
| 61 |
+
|
| 62 |
+
def normalize_whitespace(s: str) -> str:
|
| 63 |
+
if s is None: return ""
|
| 64 |
+
return s.replace("\u00A0", " ").replace("\u2009", " ").strip()
|
| 65 |
+
|
| 66 |
+
def spacy_verb_indices(nlp, sentence: str):
|
| 67 |
+
doc = nlp(sentence)
|
| 68 |
+
return [i for i, t in enumerate(doc) if t.pos_ in ("VERB","AUX") or t.tag_.startswith("VB")]
|
| 69 |
+
|
| 70 |
+
def words_and_spans_spacy(sentence: str, nlp):
|
| 71 |
+
doc = nlp(sentence)
|
| 72 |
+
words = [t.text for t in doc]
|
| 73 |
+
spans = [(t.idx, t.idx + len(t.text)) for t in doc]
|
| 74 |
+
return words, spans
|
| 75 |
+
|
| 76 |
+
def bio_to_spans(tags):
|
| 77 |
+
spans = []; i = 0
|
| 78 |
+
while i < len(tags):
|
| 79 |
+
t = tags[i]
|
| 80 |
+
if t == "O" or t.endswith("-V"):
|
| 81 |
+
i += 1; continue
|
| 82 |
+
if t.startswith("B-"):
|
| 83 |
+
role = t[2:]; j = i+1
|
| 84 |
+
while j < len(tags) and tags[j] == f"I-{role}": j += 1
|
| 85 |
+
spans.append((role, i, j-1)); i = j
|
| 86 |
+
else:
|
| 87 |
+
i += 1
|
| 88 |
+
return spans
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _predict_cached(sentence):
|
| 92 |
+
"""Internal: uses cached objects set by srl_init()."""
|
| 93 |
+
if _CACHE["model"] is None:
|
| 94 |
+
raise RuntimeError("Model not loaded. Call srl_init(ckpt_path, bert_name) once first.")
|
| 95 |
+
model = _CACHE["model"]
|
| 96 |
+
tokenizer = _CACHE["tokenizer"]
|
| 97 |
+
id2label = _CACHE["id2label"]
|
| 98 |
+
nlp = _CACHE["nlp"]
|
| 99 |
+
device = "cuda" if (_CACHE["device"].type == "cuda") else "cpu"
|
| 100 |
+
|
| 101 |
+
sentence = normalize_whitespace(sentence)
|
| 102 |
+
|
| 103 |
+
return predict_srl_allennlp_like_spacy(
|
| 104 |
+
model, tokenizer, nlp, sentence, id2label,
|
| 105 |
+
device=device, prob_threshold=0.40, top_k=None, pick_best_if_none=True
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def _pick_device(dev=None):
|
| 109 |
+
if dev == "cpu":
|
| 110 |
+
return torch.device("cpu")
|
| 111 |
+
if dev and dev.startswith("cuda") and torch.cuda.is_available():
|
| 112 |
+
return torch.device(dev)
|
| 113 |
+
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 114 |
+
|
| 115 |
+
def _ensure_loaded(model_path, bert_name, spacy_model, model_cls): # NEW
|
| 116 |
+
"""Load model/tokenizer/spaCy once and reuse."""
|
| 117 |
+
must_reload = (
|
| 118 |
+
_CACHE["model"] is None
|
| 119 |
+
or _CACHE["ckpt_path"] != model_path
|
| 120 |
+
or _CACHE["bert_name"] != bert_name
|
| 121 |
+
or _CACHE["spacy_model"] != spacy_model
|
| 122 |
+
)
|
| 123 |
+
if not must_reload:
|
| 124 |
+
return # already warm
|
| 125 |
+
|
| 126 |
+
device = _pick_device()
|
| 127 |
+
ckpt = torch.load(model_path, map_location=device)
|
| 128 |
+
h = ckpt.get("hparams", ckpt.get("hyper_parameters", {}))
|
| 129 |
+
|
| 130 |
+
# defaults if not present in ckpt
|
| 131 |
+
if "bert_name" not in h: h["bert_name"] = bert_name
|
| 132 |
+
if "num_labels" not in h:
|
| 133 |
+
label2id = ckpt.get("label2id")
|
| 134 |
+
if label2id is None and "id2label" in ckpt:
|
| 135 |
+
label2id = {v:k for k,v in ckpt["id2label"].items()}
|
| 136 |
+
h["num_labels"] = len(label2id) if label2id else 0
|
| 137 |
+
|
| 138 |
+
model = model_cls(**h).to(device).eval()
|
| 139 |
+
state = ckpt.get("model_state") or ckpt.get("state_dict") or ckpt
|
| 140 |
+
model.load_state_dict(state)
|
| 141 |
+
|
| 142 |
+
tok = AutoTokenizer.from_pretrained(h.get("bert_name", bert_name), use_fast=True)
|
| 143 |
+
|
| 144 |
+
try:
|
| 145 |
+
nlp = spacy.load(spacy_model, disable=["parser","ner","lemmatizer"])
|
| 146 |
+
except OSError:
|
| 147 |
+
spacy_cli.download(spacy_model)
|
| 148 |
+
nlp = spacy.load(spacy_model, disable=["parser","ner","lemmatizer"])
|
| 149 |
+
|
| 150 |
+
label2id = ckpt.get("label2id")
|
| 151 |
+
if label2id is None and "id2label" in ckpt:
|
| 152 |
+
label2id = {v:k for k,v in ckpt["id2label"].items()}
|
| 153 |
+
id2label = {int(v): k for k, v in label2id.items()}
|
| 154 |
+
|
| 155 |
+
_CACHE.update({
|
| 156 |
+
"ckpt_path": model_path,
|
| 157 |
+
"bert_name": h.get("bert_name", bert_name),
|
| 158 |
+
"spacy_model": spacy_model,
|
| 159 |
+
"device": device,
|
| 160 |
+
"model": model,
|
| 161 |
+
"tokenizer": tok,
|
| 162 |
+
"label2id": label2id,
|
| 163 |
+
"id2label": id2label,
|
| 164 |
+
"hparams": h,
|
| 165 |
+
"nlp": nlp,
|
| 166 |
+
})
|
| 167 |
+
torch.set_grad_enabled(False)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@torch.no_grad()
|
| 171 |
+
def predict_srl_single(model, tokenizer, words, predicate_word_idx, id2label, device="cuda"):
|
| 172 |
+
model.eval()
|
| 173 |
+
sent_enc = tokenizer(
|
| 174 |
+
words,
|
| 175 |
+
is_split_into_words=True,
|
| 176 |
+
add_special_tokens=False,
|
| 177 |
+
truncation=True,
|
| 178 |
+
max_length=500,
|
| 179 |
+
return_attention_mask=False,
|
| 180 |
+
return_token_type_ids=False,
|
| 181 |
+
)
|
| 182 |
+
# word ids
|
| 183 |
+
try:
|
| 184 |
+
sent_word_ids = sent_enc.word_ids()
|
| 185 |
+
except Exception:
|
| 186 |
+
raise ValueError("Tokenizer must be fast (use_fast=True).")
|
| 187 |
+
|
| 188 |
+
sent_wp_ids = sent_enc["input_ids"]
|
| 189 |
+
if isinstance(sent_wp_ids[0], list):
|
| 190 |
+
sent_wp_ids = sent_wp_ids[0]
|
| 191 |
+
|
| 192 |
+
first_pos_by_wid = {}
|
| 193 |
+
for pos, wid in enumerate(sent_word_ids):
|
| 194 |
+
if wid is not None and wid not in first_pos_by_wid:
|
| 195 |
+
first_pos_by_wid[wid] = pos + 1
|
| 196 |
+
|
| 197 |
+
n_words = len(words)
|
| 198 |
+
word_first_wp_fullidx = torch.tensor(
|
| 199 |
+
[first_pos_by_wid[i] for i in range(n_words)], dtype=torch.long
|
| 200 |
+
).unsqueeze(0)
|
| 201 |
+
|
| 202 |
+
# pred_enc = tokenizer(
|
| 203 |
+
# [words[predicate_word_idx]], is_split_into_words=True, add_special_tokens=False,
|
| 204 |
+
# return_attention_mask=False, return_token_type_ids=False,
|
| 205 |
+
# )
|
| 206 |
+
|
| 207 |
+
pred_enc = tokenizer(
|
| 208 |
+
[words[predicate_word_idx]],
|
| 209 |
+
is_split_into_words=True,
|
| 210 |
+
add_special_tokens=False,
|
| 211 |
+
truncation=True,
|
| 212 |
+
max_length=10,
|
| 213 |
+
return_attention_mask=False,
|
| 214 |
+
return_token_type_ids=False,
|
| 215 |
+
)
|
| 216 |
+
pred_wp_ids = pred_enc["input_ids"]
|
| 217 |
+
if isinstance(pred_wp_ids[0], list):
|
| 218 |
+
pred_wp_ids = pred_wp_ids[0]
|
| 219 |
+
|
| 220 |
+
cls_id, sep_id = tokenizer.cls_token_id, tokenizer.sep_token_id
|
| 221 |
+
input_ids = [cls_id] + sent_wp_ids + [sep_id] + pred_wp_ids + [sep_id]
|
| 222 |
+
token_type_ids = [0] * (1 + len(sent_wp_ids) + 1) + [1] * (len(pred_wp_ids) + 1)
|
| 223 |
+
attention_mask = [1] * len(input_ids)
|
| 224 |
+
|
| 225 |
+
device = _pick_device(device)
|
| 226 |
+
input_ids = torch.tensor(input_ids).unsqueeze(0).to(device)
|
| 227 |
+
token_type_ids = torch.tensor(token_type_ids).unsqueeze(0).to(device)
|
| 228 |
+
attention_mask = torch.tensor(attention_mask).unsqueeze(0).to(device)
|
| 229 |
+
|
| 230 |
+
sent_len = torch.tensor([n_words], dtype=torch.long).to(device)
|
| 231 |
+
sentence_mask = torch.ones(1, n_words, dtype=torch.bool).to(device)
|
| 232 |
+
pred_word_idx = torch.tensor([predicate_word_idx], dtype=torch.long).to(device)
|
| 233 |
+
indicator = torch.zeros(1, n_words, dtype=torch.long).to(device)
|
| 234 |
+
indicator[0, predicate_word_idx] = 1
|
| 235 |
+
word_first_wp_fullidx = word_first_wp_fullidx.to(device)
|
| 236 |
+
|
| 237 |
+
logits, _ = model(
|
| 238 |
+
input_ids=input_ids,
|
| 239 |
+
token_type_ids=token_type_ids,
|
| 240 |
+
attention_mask=attention_mask,
|
| 241 |
+
word_first_wp_fullidx=word_first_wp_fullidx,
|
| 242 |
+
sentence_mask=sentence_mask,
|
| 243 |
+
sent_lens=sent_len,
|
| 244 |
+
pred_word_idx=pred_word_idx,
|
| 245 |
+
indicator=indicator,
|
| 246 |
+
labels=None,
|
| 247 |
+
)
|
| 248 |
+
pred_ids = logits.argmax(-1).squeeze(0).tolist()
|
| 249 |
+
tags = [id2label[i] for i in pred_ids]
|
| 250 |
+
return tags, logits.squeeze(0).cpu()
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _encode_sentence_once(words, tokenizer):
|
| 254 |
+
enc = tokenizer(
|
| 255 |
+
words,
|
| 256 |
+
is_split_into_words=True,
|
| 257 |
+
add_special_tokens=False,
|
| 258 |
+
truncation=True,
|
| 259 |
+
max_length=max_length,
|
| 260 |
+
return_attention_mask=False,
|
| 261 |
+
return_token_type_ids=False,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
sent_wp_ids = enc["input_ids"]
|
| 265 |
+
if isinstance(sent_wp_ids[0], list):
|
| 266 |
+
sent_wp_ids = sent_wp_ids[0]
|
| 267 |
+
wid = enc.word_ids()
|
| 268 |
+
first_pos = {}
|
| 269 |
+
for pos, w in enumerate(wid):
|
| 270 |
+
if w is not None and w not in first_pos:
|
| 271 |
+
first_pos[w] = pos + 1 # +1 for [CLS]
|
| 272 |
+
n_words = len(words)
|
| 273 |
+
word_first = torch.tensor([first_pos[i] for i in range(n_words)], dtype=torch.long)
|
| 274 |
+
return sent_wp_ids, word_first, n_words
|
| 275 |
+
|
| 276 |
+
@torch.no_grad()
|
| 277 |
+
def _batch_predict_verbs(model, tokenizer, words, verb_idxs, id2label, device):
|
| 278 |
+
"""One forward pass for all verbs in the sentence."""
|
| 279 |
+
device = _pick_device(device)
|
| 280 |
+
sent_wp_ids, word_first_1, n_words = _encode_sentence_once(words, tokenizer, max_length=500)
|
| 281 |
+
cls_id, sep_id = tokenizer.cls_token_id, tokenizer.sep_token_id
|
| 282 |
+
|
| 283 |
+
ids_list, tt_list, am_list = [], [], []
|
| 284 |
+
pred_idx_list, ind_list, wf_list = [], [], []
|
| 285 |
+
|
| 286 |
+
for p in verb_idxs:
|
| 287 |
+
if p >= n_words:
|
| 288 |
+
continue
|
| 289 |
+
|
| 290 |
+
pred_wp_ids = tokenizer(
|
| 291 |
+
[words[p]],
|
| 292 |
+
is_split_into_words=True,
|
| 293 |
+
add_special_tokens=False,
|
| 294 |
+
truncation=True,
|
| 295 |
+
max_length=10,
|
| 296 |
+
return_attention_mask=False,
|
| 297 |
+
return_token_type_ids=False,
|
| 298 |
+
)["input_ids"]
|
| 299 |
+
if isinstance(pred_wp_ids[0], list):
|
| 300 |
+
pred_wp_ids = pred_wp_ids[0]
|
| 301 |
+
|
| 302 |
+
ids = [cls_id] + sent_wp_ids + [sep_id] + pred_wp_ids + [sep_id]
|
| 303 |
+
tt = [0]*(1 + len(sent_wp_ids) + 1) + [1]*(len(pred_wp_ids) + 1)
|
| 304 |
+
am = [1]*len(ids)
|
| 305 |
+
|
| 306 |
+
ids_list.append(torch.tensor(ids, dtype=torch.long))
|
| 307 |
+
tt_list.append(torch.tensor(tt, dtype=torch.long))
|
| 308 |
+
am_list.append(torch.tensor(am, dtype=torch.long))
|
| 309 |
+
pred_idx_list.append(torch.tensor(p, dtype=torch.long))
|
| 310 |
+
ind = torch.zeros(n_words, dtype=torch.long); ind[p] = 1
|
| 311 |
+
ind_list.append(ind)
|
| 312 |
+
wf_list.append(word_first_1.clone())
|
| 313 |
+
|
| 314 |
+
# pad
|
| 315 |
+
def pad_1d(seq, pad_id=0):
|
| 316 |
+
L = max(x.numel() for x in seq)
|
| 317 |
+
out = torch.full((len(seq), L), pad_id, dtype=seq[0].dtype)
|
| 318 |
+
for i, x in enumerate(seq):
|
| 319 |
+
out[i, :x.numel()] = x
|
| 320 |
+
return out
|
| 321 |
+
|
| 322 |
+
pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
|
| 323 |
+
input_ids = pad_1d(ids_list, pad_id).to(device)
|
| 324 |
+
token_type_ids = pad_1d(tt_list, 0).to(device)
|
| 325 |
+
attention_mask = pad_1d(am_list, 0).to(device)
|
| 326 |
+
|
| 327 |
+
B = len(verb_idxs)
|
| 328 |
+
sent_lens = torch.full((B,), n_words, dtype=torch.long, device=device)
|
| 329 |
+
sentence_mask = torch.ones(B, n_words, dtype=torch.bool, device=device)
|
| 330 |
+
pred_word_idx = torch.stack(pred_idx_list).to(device)
|
| 331 |
+
indicator = torch.stack(ind_list).to(device)
|
| 332 |
+
word_first_wp_fullidx = torch.stack(wf_list).to(device)
|
| 333 |
+
|
| 334 |
+
logits, _ = model(
|
| 335 |
+
input_ids=input_ids,
|
| 336 |
+
token_type_ids=token_type_ids,
|
| 337 |
+
attention_mask=attention_mask,
|
| 338 |
+
word_first_wp_fullidx=word_first_wp_fullidx,
|
| 339 |
+
sentence_mask=sentence_mask,
|
| 340 |
+
sent_lens=sent_lens,
|
| 341 |
+
pred_word_idx=pred_word_idx,
|
| 342 |
+
indicator=indicator,
|
| 343 |
+
labels=None,
|
| 344 |
+
) # [B, n_words, C]
|
| 345 |
+
|
| 346 |
+
results = []
|
| 347 |
+
for row, p in enumerate(verb_idxs):
|
| 348 |
+
row_logits = logits[row]
|
| 349 |
+
tags = [id2label[i] for i in row_logits.argmax(-1).tolist()]
|
| 350 |
+
results.append((p, tags, row_logits))
|
| 351 |
+
return results
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@torch.no_grad()
|
| 355 |
+
def predict_srl_allennlp_like_spacy(
|
| 356 |
+
model, tokenizer, nlp, sentence, id2label,
|
| 357 |
+
device="cuda",
|
| 358 |
+
prob_threshold=0.50,
|
| 359 |
+
top_k=None,
|
| 360 |
+
pick_best_if_none=True
|
| 361 |
+
):
|
| 362 |
+
model.eval()
|
| 363 |
+
words, _ = words_and_spans_spacy(sentence, nlp)
|
| 364 |
+
if not words:
|
| 365 |
+
return [], []
|
| 366 |
+
|
| 367 |
+
verb_idxs = spacy_verb_indices(nlp, sentence)
|
| 368 |
+
if not verb_idxs:
|
| 369 |
+
return words, []
|
| 370 |
+
|
| 371 |
+
# one forward for all verbs (fast path)
|
| 372 |
+
batch_out = _batch_predict_verbs(model, tokenizer, words, verb_idxs, id2label, device)
|
| 373 |
+
b_v_id = next((i for i,t in id2label.items() if t in ("B-V","V")), None)
|
| 374 |
+
|
| 375 |
+
frames = []
|
| 376 |
+
for p, tags, row_logits in batch_out:
|
| 377 |
+
p_bv = float(torch.softmax(row_logits[p], dim=-1)[b_v_id].item()) if b_v_id is not None else 1.0
|
| 378 |
+
frames.append({
|
| 379 |
+
"predicate_index": p,
|
| 380 |
+
"predicate": words[p],
|
| 381 |
+
"p_bv": p_bv,
|
| 382 |
+
"tags": tags,
|
| 383 |
+
"spans": bio_to_spans(tags)
|
| 384 |
+
})
|
| 385 |
+
|
| 386 |
+
# optional thresholding / top-k
|
| 387 |
+
if prob_threshold is not None:
|
| 388 |
+
keep = [f for f in frames if f["p_bv"] >= prob_threshold]
|
| 389 |
+
if not keep and pick_best_if_none and frames:
|
| 390 |
+
keep = [max(frames, key=lambda r: r["p_bv"])]
|
| 391 |
+
frames = keep
|
| 392 |
+
if top_k is not None and len(frames) > top_k:
|
| 393 |
+
frames = sorted(frames, key=lambda r: r["p_bv"], reverse=True)[:top_k]
|
| 394 |
+
|
| 395 |
+
return words, frames
|
| 396 |
+
|
| 397 |
+
def main_predictor(model_path, bert_name, sentence, spacy_model="en_core_web_md"):
|
| 398 |
+
sentence = normalize_whitespace(sentence)
|
| 399 |
+
_ensure_loaded(model_path, bert_name, spacy_model, PredicateAwareSRL) # NEW: cache/warm
|
| 400 |
+
model = _CACHE["model"]
|
| 401 |
+
tokenizer = _CACHE["tokenizer"]
|
| 402 |
+
id2label = _CACHE["id2label"]
|
| 403 |
+
nlp = _CACHE["nlp"]
|
| 404 |
+
device = _CACHE["device"]
|
| 405 |
+
|
| 406 |
+
words, frames = predict_srl_allennlp_like_spacy(
|
| 407 |
+
model, tokenizer, nlp, sentence, id2label,
|
| 408 |
+
device=str(device), prob_threshold=0.40, top_k=None, pick_best_if_none=True
|
| 409 |
+
)
|
| 410 |
+
return words, frames
|
| 411 |
+
|
| 412 |
+
|