Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,124 +0,0 @@
|
|
| 1 |
-
### 1. Imports and class names setup ###
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import os
|
| 4 |
-
import torch
|
| 5 |
-
|
| 6 |
-
from model import create_effnetb2_model
|
| 7 |
-
from timeit import default_timer as timer
|
| 8 |
-
from typing import Tuple, Dict, Union
|
| 9 |
-
|
| 10 |
-
# Setup class names
|
| 11 |
-
with open("class_names.txt", "r") as f: # reading them in from class_names.txt
|
| 12 |
-
class_names = [food_name.strip() for food_name in f.readlines()]
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
# Define a function to check if an image is likely to be food
|
| 17 |
-
def is_food_image(img) -> bool:
|
| 18 |
-
"""
|
| 19 |
-
Simple heuristic to check if an image might be food.
|
| 20 |
-
This function uses the model's confidence to determine if the image is food.
|
| 21 |
-
|
| 22 |
-
Args:
|
| 23 |
-
img: PIL Image to check
|
| 24 |
-
|
| 25 |
-
Returns:
|
| 26 |
-
bool: True if the image is likely food, False otherwise
|
| 27 |
-
"""
|
| 28 |
-
# Transform the image
|
| 29 |
-
img_tensor = effnetb2_transforms(img).unsqueeze(0)
|
| 30 |
-
|
| 31 |
-
# Get model prediction
|
| 32 |
-
effnetb2.eval()
|
| 33 |
-
with torch.inference_mode():
|
| 34 |
-
pred_logits = effnetb2(img_tensor)
|
| 35 |
-
pred_probs = torch.softmax(pred_logits, dim=1)
|
| 36 |
-
|
| 37 |
-
# Check if the highest confidence is above threshold
|
| 38 |
-
top_prob = torch.max(pred_probs).item()
|
| 39 |
-
# Also check if the top predictions are reasonably distributed
|
| 40 |
-
top5_probs = torch.topk(pred_probs, 5).values.squeeze().tolist()
|
| 41 |
-
|
| 42 |
-
# Heuristic: If the model is very confident (>0.7) or if the top 5
|
| 43 |
-
# classes have good distribution (top one >0.4 and sum of top 5 >0.9)
|
| 44 |
-
is_food = (top_prob > 0.7) or (top_prob > 0.4 and sum(top5_probs) > 0.9)
|
| 45 |
-
|
| 46 |
-
return is_food
|
| 47 |
-
|
| 48 |
-
### 2. Model and transforms preparation ###
|
| 49 |
-
|
| 50 |
-
# Create model
|
| 51 |
-
effnetb2, effnetb2_transforms = create_effnetb2_model(
|
| 52 |
-
num_classes=101, # could also use len(class_names)
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
# Load saved weights
|
| 56 |
-
effnetb2.load_state_dict(
|
| 57 |
-
torch.load(
|
| 58 |
-
f="09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth",
|
| 59 |
-
map_location=torch.device("cpu"), # load to CPU
|
| 60 |
-
)
|
| 61 |
-
)
|
| 62 |
-
|
| 63 |
-
### 3. Predict function ###
|
| 64 |
-
|
| 65 |
-
# Create predict function
|
| 66 |
-
def predict(img) -> Tuple[Dict, float]:
|
| 67 |
-
"""
|
| 68 |
-
Transforms and performs a prediction on img and returns prediction and time taken.
|
| 69 |
-
If the image doesn't appear to be food, returns a message in a format compatible with gr.Label.
|
| 70 |
-
"""
|
| 71 |
-
# Start the timer
|
| 72 |
-
start_time = timer()
|
| 73 |
-
|
| 74 |
-
# Check if the image is likely food
|
| 75 |
-
if not is_food_image(img):
|
| 76 |
-
# If not food, return a dictionary with a message that works with gr.Label
|
| 77 |
-
pred_time = round(timer() - start_time, 5)
|
| 78 |
-
return {"Please upload a food image": 1.0}, pred_time
|
| 79 |
-
|
| 80 |
-
# Transform the target image and add a batch dimension
|
| 81 |
-
img_tensor = effnetb2_transforms(img).unsqueeze(0)
|
| 82 |
-
|
| 83 |
-
# Put model into evaluation mode and turn on inference mode
|
| 84 |
-
effnetb2.eval()
|
| 85 |
-
with torch.inference_mode():
|
| 86 |
-
# Pass the transformed image through the model and turn the prediction logits into prediction probabilities
|
| 87 |
-
pred_probs = torch.softmax(effnetb2(img_tensor), dim=1)
|
| 88 |
-
|
| 89 |
-
# Create a prediction label and probability dictionary for each prediction class
|
| 90 |
-
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
|
| 91 |
-
|
| 92 |
-
# Calculate the prediction time
|
| 93 |
-
pred_time = round(timer() - start_time, 5)
|
| 94 |
-
|
| 95 |
-
# Return the prediction dictionary and prediction time
|
| 96 |
-
return pred_labels_and_probs, pred_time
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
### 4. Gradio app ###
|
| 100 |
-
|
| 101 |
-
# Create title, description and article strings
|
| 102 |
-
title = "FoodVision Big ๐๐"
|
| 103 |
-
description = "An EfficientNetB2 feature extractor computer vision model to classify images of food into [101 different classes]"
|
| 104 |
-
article = "Created by ZC."
|
| 105 |
-
|
| 106 |
-
# Create examples list from "examples/" directory
|
| 107 |
-
example_list = [["examples/" + example] for example in os.listdir("examples")]
|
| 108 |
-
|
| 109 |
-
# Create Gradio interface
|
| 110 |
-
demo = gr.Interface(
|
| 111 |
-
fn=predict,
|
| 112 |
-
inputs=gr.Image(type="pil"),
|
| 113 |
-
outputs=[
|
| 114 |
-
gr.Label(num_top_classes=5, label="Predictions"),
|
| 115 |
-
gr.Number(label="Prediction time (s)"),
|
| 116 |
-
],
|
| 117 |
-
examples=example_list,
|
| 118 |
-
title=title,
|
| 119 |
-
description=description,
|
| 120 |
-
article=article
|
| 121 |
-
)
|
| 122 |
-
|
| 123 |
-
# Launch the app with settings to address the NumPy compatibility issue
|
| 124 |
-
demo.launch(server_name="0.0.0.0", share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|