-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnn_project.py
397 lines (331 loc) · 12.1 KB
/
nn_project.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import streamlit as st
# base
import torch
import torchvision
import torch.nn as nn
from torchvision import transforms as T
import requests
from PIL import Image
import requests
from io import BytesIO
import torchvision
from PIL import Image
import time
trnsfrms2 = T.Compose([
T.Resize((299, 299)),
T.ToTensor()
]
)
st.sidebar.title("Model Selection")
model_options = ["Model 1", "Model 2"]
selected_model = st.sidebar.radio("Select Model", model_options)
if selected_model == "Model 1":
class_names=['dew', 'fogsmog', 'frost', 'glaze', 'hail', 'lightning', 'rain', 'rainbow', 'rime', 'sandstorm', 'snow']
model = torchvision.models.resnet18(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 11)
model.load_state_dict(torch.load('weather_classification_resnet18.pth', map_location=torch.device('cpu')))
st.title("This App recognizes weather based on image provided")
url = st.text_input("Enter image url")
def get_prediction(path: str) -> str:
response = requests.get(path)
image = Image.open(BytesIO(response.content)).convert('RGB')
input_tensor = trnsfrms2(image)
input_batch = input_tensor.unsqueeze(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
input_batch = input_batch.to(device)
model.eval()
with torch.no_grad():
output = model(input_batch)
start_time = time.time()
predicted_class_index = model(input_batch.to(device)).softmax(dim=1).argmax().item()
end_time = time.time()
response_time = round(end_time - start_time,4)
#img=input_tensor[i].permute(1, 2, 0).numpy() if isinstance(input_tensor, torch.Tensor) else img[i]
st.image(image.resize((400, 400)))
st.write(f'Pred class: {class_names[predicted_class_index]}')
st.write("Response Time:", response_time, "seconds")
def get_prediction2(uploaded_file: str) -> str:
image = Image.open(uploaded_file).convert('RGB')
input_tensor = trnsfrms2(image)
input_batch = input_tensor.unsqueeze(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
input_batch = input_batch.to(device)
model.eval()
with torch.no_grad():
output = model(input_batch)
start_time = time.time()
predicted_class_index = model(input_batch.to(device)).softmax(dim=1).argmax().item()
end_time = time.time()
response_time = round(end_time - start_time,4)
#img=input_tensor[i].permute(1, 2, 0).numpy() if isinstance(input_tensor, torch.Tensor) else img[i]
st.image(image.resize((400, 400)))
st.write(f'Pred class: {class_names[predicted_class_index]}')
st.write("Response Time:", response_time, "seconds")
st.title("Multiple Image Uploader")
# Allow multiple file uploads
uploaded_files = st.file_uploader("Upload multiple images", accept_multiple_files=True, type=["jpg", "jpeg", "png"])
if uploaded_files is not None:
for uploaded_file in uploaded_files:
#st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
get_prediction2(uploaded_file)
if url: # Check if URL is not empty
try:
get_prediction(url)
# Process the response further if needed
except requests.exceptions.MissingSchema:
st.warning("Invalid URL format. Make sure to include 'http://' or 'https://'")
elif selected_model == "Model 2":
class_names2=[
'Black_footed_Albatross',
'Laysan_Albatross',
'Sooty_Albatross',
'Groove_billed_Ani',
'Crested_Auklet',
'Least_Auklet',
'Parakeet_Auklet',
'Rhinoceros_Auklet',
'Brewer_Blackbird',
'Red_winged_Blackbird',
'Rusty_Blackbird',
'Yellow_headed_Blackbird',
'Bobolink',
'Indigo_Bunting',
'Lazuli_Bunting',
'Painted_Bunting',
'Cardinal',
'Spotted_Catbird',
'Gray_Catbird',
'Yellow_breasted_Chat',
'Eastern_Towhee',
'Chuck_will_Widow',
'Brandt_Cormorant',
'Red_faced_Cormorant',
'Pelagic_Cormorant',
'Bronzed_Cowbird',
'Shiny_Cowbird',
'Brown_Creeper',
'American_Crow',
'Fish_Crow',
'Black_billed_Cuckoo',
'Mangrove_Cuckoo',
'Yellow_billed_Cuckoo',
'Gray_crowned_Rosy_Finch',
'Purple_Finch',
'Northern_Flicker',
'Acadian_Flycatcher',
'Great_Crested_Flycatcher',
'Least_Flycatcher',
'Olive_sided_Flycatcher',
'Scissor_tailed_Flycatcher',
'Vermilion_Flycatcher',
'Yellow_bellied_Flycatcher',
'Frigatebird',
'Northern_Fulmar',
'Gadwall',
'American_Goldfinch',
'European_Goldfinch',
'Boat_tailed_Grackle',
'Eared_Grebe',
'Horned_Grebe',
'Pied_billed_Grebe',
'Western_Grebe',
'Blue_Grosbeak',
'Evening_Grosbeak',
'Pine_Grosbeak',
'Rose_breasted_Grosbeak',
'Pigeon_Guillemot',
'California_Gull',
'Glaucous_winged_Gull',
'Heermann_Gull',
'Herring_Gull',
'Ivory_Gull',
'Ring_billed_Gull',
'Slaty_backed_Gull',
'Western_Gull',
'Anna_Hummingbird',
'Ruby_throated_Hummingbird',
'Rufous_Hummingbird',
'Green_Violetear',
'Long_tailed_Jaeger',
'Pomarine_Jaeger',
'Blue_Jay',
'Florida_Jay',
'Green_Jay',
'Dark_eyed_Junco',
'Tropical_Kingbird',
'Gray_Kingbird',
'Belted_Kingfisher',
'Green_Kingfisher',
'Pied_Kingfisher',
'Ringed_Kingfisher',
'White_breasted_Kingfisher',
'Red_legged_Kittiwake',
'Horned_Lark',
'Pacific_Loon',
'Mallard',
'Western_Meadowlark',
'Hooded_Merganser',
'Red_breasted_Merganser',
'Mockingbird',
'Nighthawk',
'Clark_Nutcracker',
'White_breasted_Nuthatch',
'Baltimore_Oriole',
'Hooded_Oriole',
'Orchard_Oriole',
'Scott_Oriole',
'Ovenbird',
'Brown_Pelican',
'White_Pelican',
'Western_Wood_Pewee',
'Sayornis',
'American_Pipit',
'Whip_poor_Will',
'Horned_Puffin',
'Common_Raven',
'White_necked_Raven',
'American_Redstart',
'Geococcyx',
'Loggerhead_Shrike',
'Great_Grey_Shrike',
'Baird_Sparrow',
'Black_throated_Sparrow',
'Brewer_Sparrow',
'Chipping_Sparrow',
'Clay_colored_Sparrow',
'House_Sparrow',
'Field_Sparrow',
'Fox_Sparrow',
'Grasshopper_Sparrow',
'Harris_Sparrow',
'Henslow_Sparrow',
'Le_Conte_Sparrow',
'Lincoln_Sparrow',
'Nelson_Sharp_tailed_Sparrow',
'Savannah_Sparrow',
'Seaside_Sparrow',
'Song_Sparrow',
'Tree_Sparrow',
'Vesper_Sparrow',
'White_crowned_Sparrow',
'White_throated_Sparrow',
'Cape_Glossy_Starling',
'Bank_Swallow',
'Barn_Swallow',
'Cliff_Swallow',
'Tree_Swallow',
'Scarlet_Tanager',
'Summer_Tanager',
'Artic_Tern',
'Black_Tern',
'Caspian_Tern',
'Common_Tern',
'Elegant_Tern',
'Forsters_Tern',
'Least_Tern',
'Green_tailed_Towhee',
'Brown_Thrasher',
'Sage_Thrasher',
'Black_capped_Vireo',
'Blue_headed_Vireo',
'Philadelphia_Vireo',
'Red_eyed_Vireo',
'Warbling_Vireo',
'White_eyed_Vireo',
'Yellow_throated_Vireo',
'Bay_breasted_Warbler',
'Black_and_white_Warbler',
'Black_throated_Blue_Warbler',
'Blue_winged_Warbler',
'Canada_Warbler',
'Cape_May_Warbler',
'Cerulean_Warbler',
'Chestnut_sided_Warbler',
'Golden_winged_Warbler',
'Hooded_Warbler',
'Kentucky_Warbler',
'Magnolia_Warbler',
'Mourning_Warbler',
'Myrtle_Warbler',
'Nashville_Warbler',
'Orange_crowned_Warbler',
'Palm_Warbler',
'Pine_Warbler',
'Prairie_Warbler',
'Prothonotary_Warbler',
'Swainson_Warbler',
'Tennessee_Warbler',
'Wilson_Warbler',
'Worm_eating_Warbler',
'Yellow_Warbler',
'Northern_Waterthrush',
'Louisiana_Waterthrush',
'Bohemian_Waxwing',
'Cedar_Waxwing',
'American_Three_toed_Woodpecker',
'Pileated_Woodpecker',
'Red_bellied_Woodpecker',
'Red_cockaded_Woodpecker',
'Red_headed_Woodpecker',
'Downy_Woodpecker',
'Bewick_Wren',
'Cactus_Wren',
'Carolina_Wren',
'House_Wren',
'Marsh_Wren',
'Rock_Wren',
'Winter_Wren',
'Common_Yellowthroat']
model2 = torchvision.models.resnet18(pretrained=True)
num_ftrs2 = model2.fc.in_features
model2.fc = nn.Linear(num_ftrs2, 200)
model2.load_state_dict(torch.load('birds_classifications_weights.pt', map_location=torch.device('cpu')))
st.title("This App recognizes 200 bird species")
url2 = st.text_input("Enter image url")
def get_prediction21(path: str) -> str:
response = requests.get(path)
image = Image.open(BytesIO(response.content)).convert('RGB')
input_tensor = trnsfrms2(image)
input_batch = input_tensor.unsqueeze(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
input_batch = input_batch.to(device)
model2.eval()
with torch.no_grad():
output = model2(input_batch)
start_time = time.time()
predicted_class_index = model2(input_batch.to(device)).softmax(dim=1).argmax().item()
end_time = time.time()
response_time = round(end_time - start_time,4)
#img=input_tensor[i].permute(1, 2, 0).numpy() if isinstance(input_tensor, torch.Tensor) else img[i]
st.image(image.resize((400, 400)))
st.write(f'Pred class: {class_names2[predicted_class_index]}')
st.write("Response Time:", response_time, "seconds")
def get_prediction22(uploaded_file: str) -> str:
image = Image.open(uploaded_file).convert('RGB')
input_tensor = trnsfrms2(image)
input_batch = input_tensor.unsqueeze(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
input_batch = input_batch.to(device)
model2.eval()
start_time = time.time()
predicted_class_index = model2(input_batch.to(device)).softmax(dim=1).argmax().item()
end_time = time.time()
response_time2 = round(end_time - start_time,4)
#img=input_tensor[i].permute(1, 2, 0).numpy() if isinstance(input_tensor, torch.Tensor) else img[i]
st.image(image.resize((400, 400)))
st.write(f'Pred class: {class_names2[predicted_class_index]}')
st.write("Response Time:", response_time2, "seconds")
st.title("Multiple Image Uploader")
# Allow multiple file uploads
uploaded_files2 = st.file_uploader("Upload multiple images", accept_multiple_files=True, type=["jpg", "jpeg", "png"])
if uploaded_files2 is not None:
for uploaded_file in uploaded_files2:
#st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
get_prediction22(uploaded_file)
if url2: # Check if URL is not empty
try:
get_prediction21(url2)
# Process the response further if needed
except requests.exceptions.MissingSchema:
st.warning("Invalid URL format. Make sure to include 'http://' or 'https://'")