Thompson001 commited on
Commit
1bc9e9e
·
verified ·
1 Parent(s): eaea67f

Upload inference.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. inference.py +31 -0
inference.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from model import SimpleCNN
3
+ from PIL import Image
4
+ from torchvision import transforms
5
+
6
+ # Load model
7
+ device = "cuda" if torch.cuda.is_available() else "cpu"
8
+ model = SimpleCNN()
9
+ state = torch.load("pytorch_model.bin", map_location="cpu")
10
+ model.load_state_dict(state)
11
+ model.eval()
12
+
13
+ # Preprocessing
14
+ transform = transforms.Compose([
15
+ transforms.Resize((224, 224)),
16
+ transforms.ToTensor(),
17
+ ])
18
+
19
+ labels = ["no_crack", "crack"]
20
+
21
+ def predict(image: Image.Image):
22
+ img = transform(image).unsqueeze(0)
23
+ with torch.no_grad():
24
+ logits = model(img)
25
+ probs = torch.softmax(logits, dim=1)[0]
26
+ idx = probs.argmax().item()
27
+
28
+ return {
29
+ "label": labels[idx],
30
+ "score": float(probs[idx])
31
+ }