Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,13 +4,28 @@ import torch.nn as nn
|
|
| 4 |
import torchvision.transforms as T
|
| 5 |
import torchvision.models as models
|
| 6 |
from PIL import Image
|
| 7 |
-
import json
|
| 8 |
import os
|
| 9 |
|
| 10 |
# -----------------------------
|
| 11 |
-
#
|
| 12 |
# -----------------------------
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
checkpoint = torch.load(model_path, map_location="cpu")
|
| 16 |
class_names = checkpoint["class_names"]
|
|
@@ -42,7 +57,6 @@ def predict(img):
|
|
| 42 |
outputs = model(img)
|
| 43 |
probs = torch.softmax(outputs[0], dim=0)
|
| 44 |
|
| 45 |
-
# Return top 3 predictions
|
| 46 |
top3_probs, top3_idxs = torch.topk(probs, 3)
|
| 47 |
result = {class_names[i]: float(top3_probs[idx])
|
| 48 |
for idx, i in enumerate(top3_idxs)}
|
|
|
|
| 4 |
import torchvision.transforms as T
|
| 5 |
import torchvision.models as models
|
| 6 |
from PIL import Image
|
|
|
|
| 7 |
import os
|
| 8 |
|
| 9 |
# -----------------------------
|
| 10 |
+
# Safe model loading
|
| 11 |
# -----------------------------
|
| 12 |
+
possible_paths = [
|
| 13 |
+
"model/model.pth",
|
| 14 |
+
"model.pth",
|
| 15 |
+
"/app/model/model.pth",
|
| 16 |
+
"/app/model.pth"
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
model_path = None
|
| 20 |
+
for p in possible_paths:
|
| 21 |
+
if os.path.exists(p):
|
| 22 |
+
model_path = p
|
| 23 |
+
break
|
| 24 |
+
|
| 25 |
+
if model_path is None:
|
| 26 |
+
raise FileNotFoundError(
|
| 27 |
+
"❌ model.pth not found. Upload it to /model/model.pth or root folder."
|
| 28 |
+
)
|
| 29 |
|
| 30 |
checkpoint = torch.load(model_path, map_location="cpu")
|
| 31 |
class_names = checkpoint["class_names"]
|
|
|
|
| 57 |
outputs = model(img)
|
| 58 |
probs = torch.softmax(outputs[0], dim=0)
|
| 59 |
|
|
|
|
| 60 |
top3_probs, top3_idxs = torch.topk(probs, 3)
|
| 61 |
result = {class_names[i]: float(top3_probs[idx])
|
| 62 |
for idx, i in enumerate(top3_idxs)}
|