Spaces:
Build error
Build error
Upload model.py
Browse files
model.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import timm
|
2 |
+
import torch
|
3 |
+
from torch import nn
|
4 |
+
import albumentations
|
5 |
+
from PIL import Image
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
augmentations = albumentations.Compose(
|
9 |
+
[
|
10 |
+
albumentations.Normalize(
|
11 |
+
mean=[0.485, 0.456, 0.406],
|
12 |
+
std=[0.229, 0.224, 0.225],
|
13 |
+
max_pixel_value=255.0,
|
14 |
+
always_apply=True
|
15 |
+
)
|
16 |
+
]
|
17 |
+
)
|
18 |
+
|
19 |
+
target_map = {
|
20 |
+
0: 'Cranberry',
|
21 |
+
1: 'Musk melon',
|
22 |
+
2: 'Pineapple',
|
23 |
+
3: 'Watermelon',
|
24 |
+
4: 'Orange',
|
25 |
+
5: 'Dragon fruit',
|
26 |
+
6: 'Bananas',
|
27 |
+
7: 'Blue berries',
|
28 |
+
8: 'Jack fruit',
|
29 |
+
9: 'Avacados',
|
30 |
+
}
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
class ImageModelInfer(nn.Module):
|
35 |
+
def __init__(self, model_path, num_classes):
|
36 |
+
super().__init__()
|
37 |
+
model_path = model_path
|
38 |
+
self.model = timm.create_model(model_path, pretrained=False, num_classes=num_classes)
|
39 |
+
|
40 |
+
def forward(self, data):
|
41 |
+
logits = self.model(data)
|
42 |
+
return logits
|
43 |
+
|
44 |
+
|
45 |
+
def prepare_image(image):
|
46 |
+
# image = Image.open(image)
|
47 |
+
# image = image.convert("RGB")
|
48 |
+
# image = image.resize((256, 256), resample=Image.BILINEAR)
|
49 |
+
image = np.array(image)
|
50 |
+
augmented = augmentations(image=image)
|
51 |
+
image = augmented['image']
|
52 |
+
image = np.transpose(image, (2, 0, 1)).astype(np.float32)
|
53 |
+
return torch.tensor(image, dtype=torch.float)
|
54 |
+
|
55 |
+
|
56 |
+
def predict_fruit_type(img):
|
57 |
+
img = prepare_image(img)
|
58 |
+
prediction = model(img.unsqueeze(0))[0].detach().numpy()
|
59 |
+
class_ = np.argmax(prediction)
|
60 |
+
return target_map[class_]
|
61 |
+
|
62 |
+
|
63 |
+
model = ImageModelInfer('vgg16', num_classes=10)
|
64 |
+
model.load_state_dict(torch.load('best_loss_0.ckpt', map_location=torch.device('cpu'))['state_dict']);
|