brxerq commited on
Commit
6c5251e
Β·
verified Β·
1 Parent(s): cc98060

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -9
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 (Must match original model)
14
  def create_model():
15
- model = resnet50(pretrained=False) # Change if your model used a different architecture
16
- model[1] = torch.nn.Linear(model[1].in_features, len(categories)) # Adjust output layer
 
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 classification function
28
  def classify_image(img):
29
  preds, idx, probs = learn.predict(img)
30
  return dict(zip(categories, map(float, probs)))
31
 
32
- # βœ… Gradio components
33
  image = gr.Image()
34
  label = gr.Label(num_top_classes=3)
35
 
36
- # βœ… Create and launch the interface
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)