File size: 10,170 Bytes
25f8367 d324d15 25f8367 d324d15 25f8367 d324d15 25f8367 d324d15 25f8367 d324d15 25f8367 d324d15 25f8367 d324d15 25f8367 d324d15 25f8367 d324d15 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | """
Model loading and inference utilities (SAFE VERSION)
β Handles torch failure (DLL issue)
β CPU fallback
β Streamlit-safe caching
β Works even if BERT/Longformer fail
"""
import numpy as np
import joblib
import streamlit as st
import contextlib
# ββ SAFE TORCH IMPORT βββββββββββββββββββββββββββββ
torch = None
try:
import torch as _torch
torch = _torch
except Exception:
torch = None
# ββ CONFIG IMPORTS ββββββββββββββββββββββββββββββββ
from utils.config import (
BILINGUAL_LOOKUP_PATH, SVM_PATH, MODEL_B2_PATH, MODEL_C_PATH, MODEL_D_PATH,
CLINICALBERT_NAME, LONGFORMER_NAME,
NUM_LABELS_FULL, NUM_LABELS_RERANKER,
MAX_LENGTH_BERT, MAX_LENGTH_LONG,
)
from utils.preprocessing import clean_clinical_text
from utils.retriever import HierarchicalTFIDFRetriever
# ββ DEVICE HANDLING βββββββββββββββββββββββββββββββ
def get_device():
if torch is not None and torch.cuda.is_available():
return torch.device("cuda")
return "cpu"
def get_gpu_info():
if torch is None:
return None
if torch.cuda.is_available():
return {
"name": torch.cuda.get_device_name(0),
"allocated_gb": round(torch.cuda.memory_allocated() / 1024**3, 2),
"reserved_gb": round(torch.cuda.memory_reserved() / 1024**3, 2),
"total_gb": round(torch.cuda.get_device_properties(0).total_memory / 1024**3, 2),
}
return None
# ββ LOOKUP ββββββββββββββββββββββββββββββββββββββββ
@st.cache_resource(show_spinner="Loading ICD-10 lookup...")
def load_bilingual_lookup():
return joblib.load(BILINGUAL_LOOKUP_PATH)
# ββ LABEL ENCODER ββββββββββββββββββββββββββββββββ
@st.cache_resource(show_spinner="Preparing labels...")
def load_label_encoder():
from sklearn.preprocessing import LabelEncoder
lookup = load_bilingual_lookup()
le = LabelEncoder()
le.fit(sorted(lookup.keys()))
return le
# ββ RETRIEVER βββββββββββββββββββββββββββββββββββββ
@st.cache_resource(show_spinner="Building TF-IDF retriever...")
def load_retriever():
lookup = load_bilingual_lookup()
retriever = HierarchicalTFIDFRetriever()
retriever.fit(lookup)
return retriever
# ββ SVM (MODEL A) βββββββββββββββββββββββββββββββββ
@st.cache_resource(show_spinner="Loading SVM model...")
def load_model_a():
"""Load the TF-IDF + LinearSVC pipeline."""
import os
if not os.path.exists(SVM_PATH):
return None
try:
return joblib.load(SVM_PATH)
except Exception as e:
print("SVM LOAD ERROR:", e)
return None
def predict_svm(text, top_k=10):
"""Run SVM prediction and return results in the standard format."""
from scipy.special import softmax
svm_pipeline = load_model_a()
if svm_pipeline is None:
return None
le = load_label_encoder()
lookup = load_bilingual_lookup()
try:
scores = svm_pipeline.decision_function([text])[0]
probs = softmax(scores)
top_idx = np.argsort(probs)[::-1][:top_k]
results = []
for rank, idx in enumerate(top_idx, 1):
icd_code = le.classes_[idx]
info = lookup.get(icd_code, {})
results.append({
"rank": rank,
"icd_code": icd_code,
"confidence": float(probs[idx]),
"english_description": info.get("english", "Unknown"),
"chinese_description": info.get("chinese", ""),
})
return results
except Exception as e:
print("SVM PREDICT ERROR:", e)
return None
# ββ MODEL LOADERS βββββββββββββββββββββββββββββββββ
@st.cache_resource
def load_model_b2():
if torch is None:
return None, None, "cpu"
try:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from peft import PeftModel
device = get_device()
tokenizer = AutoTokenizer.from_pretrained(MODEL_B2_PATH)
base = AutoModelForSequenceClassification.from_pretrained(
CLINICALBERT_NAME, num_labels=NUM_LABELS_FULL
)
model = PeftModel.from_pretrained(base, MODEL_B2_PATH)
if device != "cpu":
model = model.to(device)
model.eval()
return model, tokenizer, device
except Exception as e:
print("BERT LOAD ERROR:", e)
return None, None, "cpu"
@st.cache_resource
def load_model_c():
if torch is None:
return None, None, "cpu"
try:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from peft import PeftModel
device = get_device()
tokenizer = AutoTokenizer.from_pretrained(MODEL_C_PATH)
base = AutoModelForSequenceClassification.from_pretrained(
LONGFORMER_NAME, num_labels=NUM_LABELS_FULL
)
model = PeftModel.from_pretrained(base, MODEL_C_PATH)
if device != "cpu":
model = model.to(device)
model.eval()
return model, tokenizer, device
except Exception as e:
print("LONGFORMER LOAD ERROR:", e)
return None, None, "cpu"
@st.cache_resource
def load_model_d():
if torch is None:
return None, None, "cpu"
try:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from peft import PeftModel
device = get_device()
tokenizer = AutoTokenizer.from_pretrained(MODEL_D_PATH)
base = AutoModelForSequenceClassification.from_pretrained(
CLINICALBERT_NAME, num_labels=NUM_LABELS_RERANKER
)
model = PeftModel.from_pretrained(base, MODEL_D_PATH)
if device != "cpu":
model = model.to(device)
model.eval()
return model, tokenizer, device
except Exception as e:
print("RERANKER LOAD ERROR:", e)
return None, None, "cpu"
# ββ CORE INFERENCE ββββββββββββββββββββββββββββββββ
def predict_single_label(model, tokenizer, device, text, max_length, top_k=10):
if torch is None or model is None:
return []
enc = tokenizer(
text,
max_length=max_length,
padding="max_length",
truncation=True,
return_tensors="pt"
)
input_ids = enc["input_ids"]
attention_mask = enc["attention_mask"]
if device != "cpu":
input_ids = input_ids.to(device)
attention_mask = attention_mask.to(device)
with torch.no_grad():
logits = model(input_ids=input_ids, attention_mask=attention_mask).logits
probs = torch.softmax(logits, dim=-1).cpu().numpy().flatten()
top_idx = np.argsort(probs)[::-1][:top_k]
return [(int(i), float(probs[i])) for i in top_idx]
# ββ MODEL PREDICTIONS βββββββββββββββββββββββββββββ
def predict_b2(text, top_k=10):
model, tokenizer, device = load_model_b2()
if model is None:
return None
le = load_label_encoder()
lookup = load_bilingual_lookup()
results = predict_single_label(model, tokenizer, device, text, MAX_LENGTH_BERT, top_k)
return [
{
"rank": rank,
"icd_code": le.classes_[idx],
"confidence": prob,
"english_description": lookup.get(le.classes_[idx], {}).get("english", "Unknown"),
"chinese_description": lookup.get(le.classes_[idx], {}).get("chinese", ""),
}
for rank, (idx, prob) in enumerate(results, 1)
]
def predict_longformer(text, top_k=10):
model, tokenizer, device = load_model_c()
if model is None:
return None
le = load_label_encoder()
lookup = load_bilingual_lookup()
results = predict_single_label(model, tokenizer, device, text, MAX_LENGTH_LONG, top_k)
return [
{
"rank": rank,
"icd_code": le.classes_[idx],
"confidence": prob,
"english_description": lookup.get(le.classes_[idx], {}).get("english", "Unknown"),
"chinese_description": lookup.get(le.classes_[idx], {}).get("chinese", ""),
}
for rank, (idx, prob) in enumerate(results, 1)
]
def predict_reranker(text, top_k=10):
retriever = load_retriever()
model, tokenizer, device = load_model_d()
if model is None:
return None
lookup = load_bilingual_lookup()
candidates = retriever.retrieve(text, top_k=100)
results = []
for code, _ in candidates:
desc = lookup.get(code, {}).get("english", "")
enc = tokenizer(
text, desc,
max_length=MAX_LENGTH_BERT,
padding="max_length",
truncation=True,
return_tensors="pt"
)
input_ids = enc["input_ids"]
attention_mask = enc["attention_mask"]
if device != "cpu":
input_ids = input_ids.to(device)
attention_mask = attention_mask.to(device)
with torch.no_grad():
logits = model(input_ids=input_ids, attention_mask=attention_mask).logits
score = torch.sigmoid(logits).item()
results.append((code, score))
results.sort(key=lambda x: x[1], reverse=True)
final = []
for rank, (code, score) in enumerate(results[:top_k], 1):
info = lookup.get(code, {})
final.append({
"rank": rank,
"icd_code": code,
"confidence": score,
"english_description": info.get("english", "Unknown"),
"chinese_description": info.get("chinese", ""),
})
return final |