File size: 2,089 Bytes
4e2dcc3
 
38ca780
4e2dcc3
38ca780
4e2dcc3
 
b0e0299
4e2dcc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0e0299
4e2dcc3
 
 
 
 
 
 
 
 
 
38ca780
 
4e2dcc3
 
 
 
 
 
 
 
 
 
 
 
38ca780
4e2dcc3
 
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
from pathlib import Path

import gradio as gr
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
import spaces

def conv_block(c_in, c_out):
    return nn.Sequential(
        nn.Conv2d(c_in, c_out, 3, padding=1),
        nn.BatchNorm2d(c_out),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(2),
    )


class SimpleCNN(nn.Module):
    def __init__(self, n_classes):
        super().__init__()
        self.features = nn.Sequential(
            conv_block(3, 32),
            conv_block(32, 64),
            conv_block(64, 128),
            conv_block(128, 256),
        )
        self.pool = nn.AdaptiveAvgPool2d(1)
        self.head = nn.Sequential(nn.Flatten(), nn.Dropout(0.4), nn.Linear(256, n_classes))

    def forward(self, x):
        return self.head(self.pool(self.features(x)))


MODEL_PATH = Path(__file__).parent / "cv01_model_full.pt"
ckpt = torch.load(MODEL_PATH, map_location="cpu")
CLASSES = ckpt["classes"]
IMG_SIZE = ckpt["img_size"]
model = SimpleCNN(len(CLASSES))
model.load_state_dict(ckpt["model_state"])
model.eval()

@spaces.GPU
def classify(img):
    if img is None:
        return None
    img = Image.fromarray(img) if isinstance(img, np.ndarray) else img
    img = img.convert("RGB").resize((IMG_SIZE, IMG_SIZE))
    x = torch.from_numpy(np.array(img)).permute(2, 0, 1).float() / 255.0
    x = ((x - 0.5) / 0.5).unsqueeze(0)
    with torch.no_grad():
        probs = torch.softmax(model(x), dim=1)[0].numpy()
    return {c: float(p) for c, p in zip(CLASSES, probs)}


demo = gr.Interface(
    fn=classify,
    inputs=gr.Image(type="pil", label="Single blood cell image"),
    outputs=gr.Label(num_top_classes=8, label="Prediction"),
    title="Blood Cell Classifier",
    description=(
        "A CNN trained on the PBC dataset (8 normal peripheral blood cell types). "
        "Works on single, centred cell images like the dataset; whole-field images or "
        "other stains give unreliable results. Research prototype, not a diagnostic tool."
    ),
    flagging_mode="never",
)

if __name__ == "__main__":
    demo.launch()