File size: 4,094 Bytes
cade23e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2cee83
c1b9ee7
0344c9f
cade23e
851add9
f2cee83
17eb8dc
f2cee83
5117f6f
0344c9f
f2cee83
555fd54
0344c9f
f2cee83
0344c9f
c1b9ee7
0344c9f
f2cee83
cade23e
 
 
 
 
 
 
 
f2cee83
17eb8dc
c1b9ee7
 
 
 
0344c9f
f2cee83
c1b9ee7
 
 
f2cee83
 
 
 
 
 
 
 
 
 
 
c1b9ee7
f2cee83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0344c9f
f2cee83
17eb8dc
f2cee83
17eb8dc
 
 
f2cee83
 
 
 
 
 
17eb8dc
 
851add9
553781d
11b476f
f2cee83
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# 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()