yolospace / app.py
AlaaElsayed's picture
Update app.py
f2cee83 verified
# from ultralytics import YOLO
# import pandas as pd
# from PIL import Image, ImageDraw
# import gradio as gr
# # تحميل الموديل
# model = YOLO("best.pt")
# # تحميل بيانات التغذية
# food_df = pd.read_csv("food_cleaned.csv")
# # جلب القيم الغذائية
# def get_nutrition(label):
# row = food_df[food_df["Food_Name"].str.lower() == label.lower()]
# if row.empty:
# return "No data"
# cals = row["Calories_per_100g"].values[0]
# fat = row["Fat_g"].values[0]
# protein = row["Protein_g"].values[0]
# carbs = row["Carbs_g"].values[0]
# return f"{label}: {cals} kcal, {fat}g fat, {protein}g protein, {carbs}g carbs"
# # دالة الكشف والرسم
# def detect(image):
# results = model.predict(image)
# result = results[0]
# boxes = result.boxes
# names = model.names
# img = Image.fromarray(result.plot()) # الصورة عليها البوكسات
# draw = ImageDraw.Draw(img)
# for box in boxes:
# cls_id = int(box.cls[0])
# label = names[cls_id]
# nutrition = get_nutrition(label)
# xy = box.xyxy[0].tolist()
# draw.text((xy[0], xy[1] - 10), nutrition, fill=(255, 0, 0))
# return img
# # Gradio app
# demo = gr.Interface(
# fn=detect,
# inputs=gr.Image(type="pil"),
# outputs=gr.Image(type="pil"),
# title="YOLOv8 Food Detector + Nutrition Info",
# description="Upload an image of food and see calories and nutrients!"
# )
# demo.launch()
from ultralytics import YOLO
import pandas as pd
from PIL import Image
import gradio as gr
from collections import Counter
# Load YOLO model
model = YOLO("best.pt")
# Load food nutrition data
food_df = pd.read_csv("food_cleaned.csv")
# Retrieve nutrition info for a given label
def get_nutrition(label):
row = food_df[food_df["Food_Name"].str.lower() == label.lower()]
if row.empty:
return {"label": label, "info": "No data found"}
return {
"label": label,
"calories": float(row["Calories_per_100g"].values[0]),
"fat": float(row["Fat_g"].values[0]),
"protein": float(row["Protein_g"].values[0]),
"carbs": float(row["Carbs_g"].values[0])
}
# Detection and nutrition calculation
def detect(image):
results = model.predict(image)
result = results[0]
boxes = result.boxes
names = model.names
detected_labels = []
for box in boxes:
cls_id = int(box.cls[0])
label = names[cls_id]
detected_labels.append(label)
label_counts = Counter(detected_labels)
total_calories = 0
total_fat = 0
total_protein = 0
total_carbs = 0
detailed_items = []
for label, count in label_counts.items():
nutrition = get_nutrition(label)
if "info" in nutrition:
continue
nutrition["count"] = count
nutrition["total_calories"] = round(nutrition["calories"] * count, 2)
nutrition["total_fat"] = round(nutrition["fat"] * count, 2)
nutrition["total_protein"] = round(nutrition["protein"] * count, 2)
nutrition["total_carbs"] = round(nutrition["carbs"] * count, 2)
total_calories += nutrition["total_calories"]
total_fat += nutrition["total_fat"]
total_protein += nutrition["total_protein"]
total_carbs += nutrition["total_carbs"]
detailed_items.append(nutrition)
overall_summary = {
"Total Calories": round(total_calories, 2),
"Total Fat": round(total_fat, 2),
"Total Protein": round(total_protein, 2),
"Total Carbs": round(total_carbs, 2)
}
return Image.fromarray(result.plot()), {"summary": overall_summary, "details": detailed_items}
# Gradio web app
demo = gr.Interface(
fn=detect,
inputs=gr.Image(type="pil"),
outputs=[
gr.Image(type="pil", label="Detected Image"),
gr.JSON(label="Nutrition Info")
],
title="Smart Food Detector - Nutrition Calculator",
description="Upload a food image to get total calories, fat, protein, and carbs."
)
demo.launch()