Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,33 +6,36 @@ __all__ = ['bird', 'learn', 'classify_image', 'categories', 'image', 'label', 'e
|
|
| 6 |
with open("labels.txt", "r") as file:
|
| 7 |
categories = [line.strip() for line in file.readlines()]
|
| 8 |
|
| 9 |
-
# Import FastAI and Gradio
|
| 10 |
from fastai.vision.all import *
|
| 11 |
import gradio as gr
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
# β
Define Model Architecture
|
| 14 |
def create_model():
|
| 15 |
-
model = resnet50(
|
| 16 |
-
|
|
|
|
| 17 |
return model
|
| 18 |
|
| 19 |
-
# β
Load Model Safely
|
| 20 |
model = create_model()
|
| 21 |
model.load_state_dict(torch.load("model_weights.pth", map_location="cpu"))
|
| 22 |
model.eval() # Set to evaluation mode
|
| 23 |
|
| 24 |
-
# Wrap in a FastAI Learner
|
| 25 |
learn = Learner(dls=None, model=model)
|
| 26 |
|
| 27 |
-
# β
Define the
|
| 28 |
def classify_image(img):
|
| 29 |
preds, idx, probs = learn.predict(img)
|
| 30 |
return dict(zip(categories, map(float, probs)))
|
| 31 |
|
| 32 |
-
# β
Gradio
|
| 33 |
image = gr.Image()
|
| 34 |
label = gr.Label(num_top_classes=3)
|
| 35 |
|
| 36 |
-
# β
Create and
|
| 37 |
intf = gr.Interface(fn=classify_image, inputs=image, outputs=label)
|
| 38 |
intf.launch(inline=False, share=True)
|
|
|
|
| 6 |
with open("labels.txt", "r") as file:
|
| 7 |
categories = [line.strip() for line in file.readlines()]
|
| 8 |
|
| 9 |
+
# Import FastAI, PyTorch, and Gradio
|
| 10 |
from fastai.vision.all import *
|
| 11 |
import gradio as gr
|
| 12 |
+
import torch
|
| 13 |
+
from torchvision.models import resnet50
|
| 14 |
|
| 15 |
+
# β
Define Model Architecture
|
| 16 |
def create_model():
|
| 17 |
+
model = resnet50(weights=None) # No pre-trained weights
|
| 18 |
+
num_features = model.fc.in_features # Get input features of the final layer
|
| 19 |
+
model.fc = torch.nn.Linear(num_features, len(categories)) # Replace final layer
|
| 20 |
return model
|
| 21 |
|
| 22 |
+
# β
Load Model Weights Safely
|
| 23 |
model = create_model()
|
| 24 |
model.load_state_dict(torch.load("model_weights.pth", map_location="cpu"))
|
| 25 |
model.eval() # Set to evaluation mode
|
| 26 |
|
| 27 |
+
# β
Wrap in a FastAI Learner (Even Without DataLoaders)
|
| 28 |
learn = Learner(dls=None, model=model)
|
| 29 |
|
| 30 |
+
# β
Define the Classification Function
|
| 31 |
def classify_image(img):
|
| 32 |
preds, idx, probs = learn.predict(img)
|
| 33 |
return dict(zip(categories, map(float, probs)))
|
| 34 |
|
| 35 |
+
# β
Gradio UI Components
|
| 36 |
image = gr.Image()
|
| 37 |
label = gr.Label(num_top_classes=3)
|
| 38 |
|
| 39 |
+
# β
Create and Launch Gradio Interface
|
| 40 |
intf = gr.Interface(fn=classify_image, inputs=image, outputs=label)
|
| 41 |
intf.launch(inline=False, share=True)
|