KabeerAmjad commited on
Commit
d97b868
1 Parent(s): 5cf4eea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -10
app.py CHANGED
@@ -1,22 +1,35 @@
1
  import gradio as gr
2
- from transformers import AutoModelForImageClassification, AutoFeatureExtractor
3
- from PIL import Image
4
  import torch
 
 
 
5
 
6
- # Load the model directly from Hugging Face
7
- model_id = "KabeerAmjad/food_classification_model"
8
- model = AutoModelForImageClassification.from_pretrained(model_id)
9
- feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
 
 
 
 
 
 
 
 
 
10
 
11
  # Define the prediction function
12
  def classify_image(img):
13
- inputs = feature_extractor(images=img, return_tensors="pt")
 
 
 
14
  with torch.no_grad():
15
- outputs = model(**inputs)
16
- probs = torch.softmax(outputs.logits, dim=-1)
17
 
18
  # Get the label with the highest probability
19
- top_label = model.config.id2label[probs.argmax().item()]
20
  return top_label
21
 
22
  # Create the Gradio interface
 
1
  import gradio as gr
 
 
2
  import torch
3
+ from torch import nn
4
+ from torchvision import models, transforms
5
+ from PIL import Image
6
 
7
+ # Load the model architecture and weights
8
+ model_id = "KabeerAmjad/food_classification_model"
9
+ model = models.resnet50(pretrained=False) # Do not load the pretrained weights here
10
+ model.fc = nn.Linear(model.fc.in_features, 11) # Adjust the number of classes (replace 11 with your number of classes)
11
+ model.load_state_dict(torch.load(model_id)) # Load the model weights you uploaded
12
+ model.eval()
13
+
14
+ # Define the same preprocessing used during training
15
+ transform = transforms.Compose([
16
+ transforms.Resize((224, 224)),
17
+ transforms.ToTensor(),
18
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
19
+ ])
20
 
21
  # Define the prediction function
22
  def classify_image(img):
23
+ # Preprocess the image
24
+ img = transform(img).unsqueeze(0) # Add batch dimension
25
+
26
+ # Make prediction
27
  with torch.no_grad():
28
+ outputs = model(img)
29
+ probs = torch.softmax(outputs, dim=-1)
30
 
31
  # Get the label with the highest probability
32
+ top_label = model.config.id2label[probs.argmax().item()] # Map to label (use your custom label mapping if needed)
33
  return top_label
34
 
35
  # Create the Gradio interface