Food_recipe_app / app.py
GS123's picture
Update app.py
1ce82da verified
Raw
History Blame Contribute Delete
2.71 kB
import tensorflow as tf
import cv2
import numpy as np
import sqlite3
import gradio as gr
# ============================
# Load Model
# ============================
model = tf.keras.models.load_model("efficient_model.keras")
# ============================
# Load Database
# ============================
conn = sqlite3.connect("food_recipes.db", check_same_thread=False)
cursor = conn.cursor()
# ============================
# Classes
# ============================
class_names = [
"chocolate_cake",
"cup_cakes",
"donuts",
"dumplings",
"french_fries",
"fried_rice",
"garlic_bread",
"pizza",
"samosa",
"waffles",
]
# ============================
# Image Preprocessing
# ============================
def sq_img(img):
h, w = img.shape[:2]
if h >= w:
diff = h - w
left = diff // 2
right = diff - left
top = bottom = 0
else:
diff = w - h
top = diff // 2
bottom = diff - top
left = right = 0
return cv2.copyMakeBorder(
img,
top,
bottom,
left,
right,
cv2.BORDER_CONSTANT,
value=0,
)
# ============================
# Prediction Function
# ============================
def predict(image):
if image is None:
return "Please upload an image.", ""
img = sq_img(image)
img = cv2.resize(img, (224, 224))
img = np.expand_dims(img, axis=0)
probs = model.predict(img, verbose=0)
pred = np.argmax(probs, axis=1)[0]
confidence = float(np.max(probs)) * 100
if confidence < 80:
return (
f"Prediction Confidence: {confidence:.2f}%\n\nPlease upload another image.",
"",
)
food_name = class_names[pred]
cursor.execute(
"SELECT food_recipe FROM recipe WHERE name=?",
(food_name,),
)
result = cursor.fetchone()
recipe = result[0] if result else "Recipe not found."
prediction = f"### ๐Ÿฝ๏ธ {food_name.replace('_',' ').title()}\nConfidence : **{confidence:.2f}%**"
return prediction, recipe
# ============================
# Gradio Interface
# ============================
demo = gr.Interface(
fn=predict,
inputs=gr.Image(type="numpy", label="Upload Food Image"),
outputs=[
gr.Markdown(label="Prediction"),
gr.Markdown(label="Recipe"),
],
title="๐Ÿž Food Recipe Search",
description="Upload a food image to identify it and get its recipe.",
)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860
)