gabrielkasmi commited on
Commit
1be92b1
·
verified ·
1 Parent(s): c07bf50

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +72 -0
model.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ model.py — helpers to load BDAPPV baseline models from HuggingFace Hub.
3
+
4
+ Usage:
5
+ from huggingface_hub import hf_hub_download
6
+ import importlib.util, sys
7
+
8
+ path = hf_hub_download("gabrielkasmi/bdappv-models", "model.py")
9
+ spec = importlib.util.spec_from_file_location("bdappv_model", path)
10
+ mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
11
+
12
+ seg = mod.load_segmentation_model("google") # or "ign"
13
+ clf = mod.load_classification_model("google") # or "ign"
14
+ """
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ from huggingface_hub import hf_hub_download
19
+ from torchvision.models.segmentation import deeplabv3_resnet101
20
+ from torchvision.models import inception_v3
21
+
22
+ REPO = "gabrielkasmi/bdappv-models"
23
+
24
+
25
+ def load_segmentation_model(provider: str = "google", device: str = "cpu"):
26
+ """
27
+ Load the DeepLabV3-ResNet101 segmentation model.
28
+
29
+ Args:
30
+ provider : "google" or "ign"
31
+ device : "cpu", "cuda", or "mps"
32
+
33
+ Returns:
34
+ model in eval mode
35
+ """
36
+ assert provider in ("google", "ign"), "provider must be 'google' or 'ign'"
37
+
38
+ path = hf_hub_download(REPO, f"deeplab_{provider}_best.pth")
39
+ model = deeplabv3_resnet101(weights=None, aux_loss=False)
40
+ model.classifier[-1] = nn.Conv2d(256, 1, kernel_size=1)
41
+
42
+ state = torch.load(path, map_location=device, weights_only=False)
43
+ model_dict = model.state_dict()
44
+ compatible = {k: v for k, v in state.items()
45
+ if k in model_dict and v.shape == model_dict[k].shape}
46
+ model_dict.update(compatible)
47
+ model.load_state_dict(model_dict)
48
+
49
+ return model.eval().to(device)
50
+
51
+
52
+ def load_classification_model(provider: str = "google", device: str = "cpu"):
53
+ """
54
+ Load the InceptionV3 classification model (panel / no panel).
55
+
56
+ Args:
57
+ provider : "google" or "ign"
58
+ device : "cpu", "cuda", or "mps"
59
+
60
+ Returns:
61
+ model in eval mode
62
+ """
63
+ assert provider in ("google", "ign"), "provider must be 'google' or 'ign'"
64
+
65
+ path = hf_hub_download(REPO, f"inception_{provider}_best.pth")
66
+ model = inception_v3(weights=None, aux_logits=False)
67
+ model.fc = nn.Linear(model.fc.in_features, 1)
68
+
69
+ state = torch.load(path, map_location=device, weights_only=False)
70
+ model.load_state_dict(state)
71
+
72
+ return model.eval().to(device)