fohy24 commited on
Commit
49a7401
·
1 Parent(s): 3f810f2

added app.py with predict function

Browse files
Files changed (1) hide show
  1. app.py +88 -0
app.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+ import torch
7
+ # from torch.utils.data import Dataset, DataLoader, Subset
8
+ from torch import nn
9
+ from torchvision import models
10
+ import torch.nn.functional as F
11
+ from torchvision.transforms import v2
12
+
13
+ from PIL import Image
14
+
15
+ # from PIL import ImageFile
16
+ # ImageFile.LOAD_TRUNCATED_IMAGES = True
17
+
18
+ labels = ['Pastel',
19
+ 'Yellow Belly',
20
+ 'Enchi',
21
+ 'Clown',
22
+ 'Leopard',
23
+ 'Piebald',
24
+ 'Orange Dream',
25
+ 'Fire',
26
+ 'Mojave',
27
+ 'Pinstripe',
28
+ 'Banana',
29
+ 'Normal',
30
+ 'Black Pastel',
31
+ 'Lesser',
32
+ 'Spotnose',
33
+ 'Cinnamon',
34
+ 'GHI',
35
+ 'Hypo',
36
+ 'Spider',
37
+ 'Super Pastel']
38
+ num_labels = len(labels)
39
+
40
+ def predict(img):
41
+
42
+ new_layers = nn.Sequential(
43
+ nn.Linear(1920, 1000), # Reduce dimension from 1024 to 500
44
+ nn.BatchNorm1d(1000), # Normalize the activations from the previous layer
45
+ nn.ReLU(), # Non-linear activation function
46
+ nn.Dropout(0.5), # Dropout for regularization (50% probability)
47
+ nn.Linear(1000, num_labels) # Final layer for class predictions
48
+ )
49
+
50
+ IMAGE_SIZE = 512
51
+ transform = v2.Compose([
52
+ v2.ToImage(),
53
+ v2.Resize((IMAGE_SIZE, IMAGE_SIZE)),
54
+ v2.ToDtype(torch.float32, scale=True),
55
+ v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
56
+ ])
57
+
58
+
59
+ densenet = models.densenet201(weights='DenseNet201_Weights.DEFAULT')
60
+ densenet.classifier = new_layers
61
+
62
+ # If using GPU
63
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
64
+
65
+ checkpoint = torch.load(f'model/model_v8_epoch9.pt', map_location=device)
66
+ densenet.load_state_dict(checkpoint['model_state_dict'])
67
+
68
+ densenet.eval()
69
+
70
+ input_img = transform(img)
71
+ input_img = input_img.unsqueeze(0)
72
+
73
+
74
+ with torch.no_grad():
75
+ output = densenet(input_img)
76
+
77
+ predicted_probs = torch.sigmoid(output).to('cpu')
78
+ prediction = pd.DataFrame(predicted_probs, index=['predictions'],
79
+ columns=labels).T.sort_values(by=['predictions'], ascending=False)
80
+
81
+
82
+ prediction_probs = prediction.query('predictions > 0.5').reset_index(names='morphs')['morphs'].to_list()
83
+ prediction_confidence = prediction.query('predictions > 0.5')['predictions'].to_list()
84
+
85
+ return prediction_probs, prediction_confidence
86
+
87
+
88
+