File size: 1,908 Bytes
71ec175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import torch
from PIL import Image
from huggingface_hub import hf_hub_download
from models.biohcl_sssm import BioHCLSSSM
from dataset import get_transforms

def load_pretrained_model(repo_id="unknownBrain/BioHCL-SSSM-Pediatric-Pneumonia", device="cpu"):
    """
    Downloads and instantiates the best BioHCL-SSSM model checkpoint from Hugging Face.
    """
    print(f"Downloading best model from {repo_id}...")
    ckpt_path = hf_hub_download(repo_id=repo_id, filename="checkpoints/best_student_cv.pt")
    
    model = BioHCLSSSM(num_classes=2, embed_dim=512, chain_mode="dual", num_sssm_blocks=3)
    state_dict = torch.load(ckpt_path, map_location=device)
    if "model_state_dict" in state_dict:
        state_dict = state_dict["model_state_dict"]
    model.load_state_dict(state_dict)
    model.to(device)
    model.eval()
    print("Model loaded successfully!")
    return model

def predict_chest_xray(model, image_path, device="cpu"):
    """
    Runs diagnostic prediction on a single chest X-ray image.
    """
    _, eval_transform = get_transforms(img_size=224)
    image = Image.open(image_path).convert("RGB")
    tensor = eval_transform(image=np.array(image))["image"].unsqueeze(0).to(device)
    
    with torch.no_grad():
        logits, _ = model(tensor)
        probs = torch.softmax(logits, dim=1)[0]
        pred_idx = torch.argmax(probs).item()
        
    classes = ["NORMAL", "PNEUMONIA"]
    return {
        "prediction": classes[pred_idx],
        "confidence": float(probs[pred_idx]),
        "probabilities": {"NORMAL": float(probs[0]), "PNEUMONIA": float(probs[1])}
    }

if __name__ == "__main__":
    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Running inference on {device}...")
    # model = load_pretrained_model(device=device)
    # result = predict_chest_xray(model, "sample_xray.jpeg", device=device)
    # print("Result:", result)