File size: 15,847 Bytes
dbbc4fe
 
02116bc
dbbc4fe
9174245
026ebc5
d75bb73
 
2c474c5
37deff4
026ebc5
 
37deff4
2c474c5
dad1232
c723914
 
 
 
d75bb73
851126c
d75bb73
851126c
d75bb73
 
851126c
d75bb73
 
 
 
02116bc
d75bb73
 
 
9174245
d75bb73
 
 
 
 
aa9caf1
d75bb73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac14a76
d75bb73
 
 
 
 
 
 
 
 
 
02116bc
d75bb73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02116bc
9174245
d75bb73
5aa1d82
 
d75bb73
aa9caf1
d75bb73
 
 
 
 
 
 
02116bc
d75bb73
 
 
 
 
 
ac14a76
d75bb73
02116bc
d75bb73
 
 
 
02116bc
d75bb73
ac14a76
02116bc
9174245
851126c
ee502f6
02116bc
 
 
ee502f6
02116bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee502f6
 
 
 
 
 
02116bc
851126c
02116bc
 
 
ee502f6
851126c
ee502f6
 
 
02116bc
ee502f6
 
 
 
 
8915be6
02116bc
ee502f6
893dd33
 
 
 
279530a
 
d75bb73
279530a
 
d75bb73
02116bc
279530a
d75bb73
 
851126c
ba59c03
 
 
 
ad608c7
ba59c03
 
851126c
 
d75bb73
ad608c7
15a8307
 
d75bb73
 
 
 
9174245
d75bb73
 
87cea30
17011cd
d75bb73
9174245
 
 
 
 
 
c7730e8
 
9174245
 
 
 
17011cd
d75bb73
9174245
17011cd
9174245
 
17011cd
9174245
02116bc
851126c
893dd33
 
5aa1d82
f929629
893dd33
 
17011cd
02116bc
851126c
ee502f6
851126c
d75bb73
ee502f6
 
 
9174245
 
 
5aa1d82
f929629
17011cd
 
 
 
9174245
851126c
 
02116bc
 
66d85d7
 
 
02116bc
851126c
 
 
44ce1ea
c723914
 
89927ac
ac14a76
44ce1ea
17011cd
02116bc
 
ac14a76
aa9caf1
9af7d46
 
 
 
02116bc
d211fb0
9af7d46
 
 
02116bc
17011cd
 
 
 
 
d4d7138
 
 
9af7d46
 
 
ae0274c
 
9af7d46
ae0274c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9af7d46
d4d7138
ae0274c
d4d7138
ee502f6
17011cd
 
 
893dd33
 
02116bc
 
17011cd
 
02116bc
17011cd
 
d75bb73
ee502f6
17011cd
 
 
 
 
 
 
 
 
 
 
 
 
851126c
2b6d901
47a091e
2b6d901
 
 
 
 
 
 
 
 
 
47a091e
 
 
aa9caf1
dbbc4fe
851126c
 
dbbc4fe
 
851126c
8e0b90f
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import gradio as gr
import pandas as pd
import os, json, datetime
from apscheduler.schedulers.background import BackgroundScheduler
from sklearn.metrics import mean_absolute_error
from huggingface_hub import login, hf_hub_download
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
import base64

# Log in programmatically using token from secrets.
login(token=os.getenv("HF_TOKEN"))

# ---------- Load Image for Description ----------
with open("assets/image.png", "rb") as f:
    image_data = f.read()
encoded_image = base64.b64encode(image_data).decode("utf-8")


# ---------- CSV to COCO Conversion Functions ----------

def convert_gt_csv_to_coco(gt_df):
    """
    Convert ground truth DataFrame to COCO-style dictionary.
    Expected columns in gt_df: image_name, class_id, xmin, ymin, xmax, ymax, weight.
    """
    images = []
    annotations = []
    # Create a mapping for image names to unique IDs.
    image_names = gt_df["image_name"].unique()
    image_id_map = {name: idx + 1 for idx, name in enumerate(image_names)}
    
    # Create a list of categories from the unique class_ids.
    category_ids = sorted(gt_df["class_id"].unique())
    categories = [{"id": int(cat), "name": f"class_{int(cat)}"} for cat in category_ids]
    
    ann_id = 1
    for idx, row in gt_df.iterrows():
        img_name = row["image_name"]
        image_id = image_id_map[img_name]
        # Add image information if not already added.
        if image_id not in [img["id"] for img in images]:
            images.append({"id": image_id, "file_name": img_name})
        x = row["xmin"]
        y = row["ymin"]
        width = row["xmax"] - row["xmin"]
        height = row["ymax"] - row["ymin"]
        ann = {
            "id": ann_id,
            "image_id": image_id,
            "category_id": int(row["class_id"]),
            "bbox": [x, y, width, height],
            "area": width * height,
            "iscrowd": 0
        }
        annotations.append(ann)
        ann_id += 1
    coco_dict = {
        "images": images,
        "annotations": annotations,
        "categories": categories
    }
    return coco_dict, image_id_map

def convert_pred_csv_to_coco(pred_df, image_id_map):
    """
    Convert predictions DataFrame to COCO-style list of predictions.
    Expected columns in pred_df: image_name, class_id, xmin, ymin, xmax, ymax, weight, conf.
    """
    preds = []
    for idx, row in pred_df.iterrows():
        img_name = row["image_name"]
        image_id = image_id_map.get(img_name)
        if image_id is None:
            continue  # Skip predictions for images not in the ground truth.
        x = row["xmin"]
        y = row["ymin"]
        width = row["xmax"] - row["xmin"]
        height = row["ymax"] - row["ymin"]
        pred = {
            "image_id": image_id,
            "category_id": int(row["class_id"]),
            "bbox": [x, y, width, height],
            "score": row["conf"]
        }
        preds.append(pred)
    return preds

def compute_map50(gt_df, pred_df):
    """
    Convert CSV DataFrames to COCO format and compute mAP50 using pycocotools.
    Returns the mAP50 value.
    """
    coco_gt_dict, image_id_map = convert_gt_csv_to_coco(gt_df)
    coco_preds = convert_pred_csv_to_coco(pred_df, image_id_map)
    
    # Save temporary JSON files.
    gt_json_path = "temp_gt_coco.json"
    pred_json_path = "temp_pred_coco.json"
    with open(gt_json_path, "w") as f:
        json.dump(coco_gt_dict, f)
    with open(pred_json_path, "w") as f:
        json.dump(coco_preds, f)
        
    # Load ground truth and predictions with the COCO API.
    cocoGt = COCO(gt_json_path)
    try:
        cocoDt = cocoGt.loadRes(pred_json_path)
    except Exception as e:
        print("Error loading predictions into COCO:", e)
        return None

    cocoEval = COCOeval(cocoGt, cocoDt, iouType="bbox")
    # Set evaluation to only consider an IoU threshold of 0.50.
    cocoEval.params.iouThrs = [0.5]
    cocoEval.evaluate()
    cocoEval.accumulate()
    cocoEval.summarize()
    # stats[0] is typically the [email protected].
    return cocoEval.stats[0]


# ---------- Evaluation Functions (Combined Metrics) ----------

# Update leaderboard columns (here we remove explicit user and submission date fields).
LEADERBOARD_FILE = "evaluation_results.csv"
LEADERBOARD_COLUMNS = [
    "Name", "Model", "mAP@50", "weight_MAE (g)",
    "Paper", "Source Code", "Model Type", "Hub License"
]

def save_submission_result(result):
    if os.path.exists(LEADERBOARD_FILE):
        df = pd.read_csv(LEADERBOARD_FILE)
        df = pd.concat([df, pd.DataFrame([result])], ignore_index=True)
    else:
        df = pd.DataFrame([result], columns=LEADERBOARD_COLUMNS)
    df.to_csv(LEADERBOARD_FILE, index=False)

def load_leaderboard():
    if os.path.exists(LEADERBOARD_FILE):
        df = pd.read_csv(LEADERBOARD_FILE)
        # Sort by mAP@50 (higher is better)
        df = df.sort_values(by="mAP@50", ascending=False)
        return df
    else:
        return pd.DataFrame(columns=LEADERBOARD_COLUMNS)

# --- Rate Limiting by IP ---
# A global dictionary that will map client IPs to the timestamp of their last submission.
submissions_by_ip = {}
# Set the allowed interval between submissions in seconds. Here, 86400 seconds = 1 day.
SUBMISSION_INTERVAL_SECONDS = 86400

def evaluate_submission(file, submission_name, model_description, link_paper, link_code, model_type, hub_license, req: gr.Request):
    """
    Evaluate the submitted CSV by computing:
    - mAP@50 (using COCO evaluation) for bounding boxes.
    - Weight MAE for the food weight predictions.
    Also implements a simple rate limiting per IP address to help avoid spam.
    """
    # Get the client IP from the Gradio request.
    client_ip = req.client.host if req.client and req.client.host else "unknown"
    now = datetime.datetime.now()
    
    # Check if this IP has submitted recently.
    if client_ip in submissions_by_ip:
        last_sub_time = submissions_by_ip[client_ip]
        delta = (now - last_sub_time).total_seconds()
        if delta < SUBMISSION_INTERVAL_SECONDS:
            return f"โŒ Only one submission per day is allowed. Please try again later."
    
    # Validate required fields.
    if not submission_name.strip():
        return "โŒ Name field is required."
    if not model_description.strip():
        return "โŒ Model field is required."
    if file is None:
        return "โŒ Please upload a file."
    
    print("File received:", file)
    try:
        pred_df = pd.read_csv(file.name)
        print("Prediction CSV columns:", pred_df.columns.tolist())
    except Exception as e:
        return f"โŒ Prediction CSV read failed: {e}"
    
    try:
        gt_path = hf_hub_download(
            repo_id="issai/ground-truth-food-eval",
            filename="ground_truth.csv",
            repo_type="dataset",
            token=True
        )
        gt_df = pd.read_csv(gt_path)
    except Exception as e:
        return "Error loading ground truth file: " + str(e)
    
    print("Ground truth shape:", gt_df.shape)
    print("Ground truth sample:")
    print(gt_df.head())
    print("Predictions shape:", pred_df.shape)
    print("Predictions sample:")
    print(pred_df.head())
    
    # --- Compute mAP50 ---
    ap50 = compute_map50(gt_df, pred_df)
    if ap50 is None:
        return "Error computing mAP@50."
    print("Computed mAP50:", ap50)
    
    # --- Compute Weight MAE ---
    try:
        df = pd.merge(gt_df, pred_df, on=["image_name", "class_id"], suffixes=("_gt", "_pred"))
    except Exception as e:
        return f"โŒ Error during merge for MAE: {e}"
    
    df["weight_gt"] = pd.to_numeric(df["weight_gt"], errors="coerce")
    df["weight_pred"] = pd.to_numeric(df["weight_pred"], errors="coerce")
    
    before_filter = df.shape[0]
    df = df[(df["weight_gt"] != -1) & (df["weight_pred"] != -1)]
    filtered_out = before_filter - df.shape[0]
    print(f"Filtered out {filtered_out} rows for MAE due to weight == -1")
    
    if df.empty:
        weight_mae = 0.0
    else:
        weight_mae = mean_absolute_error(df["weight_gt"], df["weight_pred"])
    print("Computed Weight MAE:", weight_mae)
    
    # --- Save Submission Result ---
    result = {
        "Name": submission_name,
        "Model": model_description,
        "mAP@50": f"{ap50:.3f}",
        "weight_MAE (g)": f"{weight_mae:.3f}",
        "Paper": link_paper,
        "Source Code": link_code,
        "Model Type": model_type,
        "Hub License": hub_license,
    }
    
    save_submission_result(result)
    
    # Update the last submission time for this IP.
    submissions_by_ip[client_ip] = now
    
    result_text = (
        f"**Evaluation Results for '{submission_name}'**\n\n"
        f"- Model: {model_description}\n"
        f"- mAP@50: {ap50:.3f}\n"
        f"- Weight MAE: {weight_mae:.3f} grams\n"
        f"- Link to Paper: {link_paper}\n"
        f"- Link to Source Code: {link_code}\n"
        f"- Model Type: {model_type}\n"
        f"- Hub License: {hub_license}\n"
    )
    return result_text

def evaluate_and_refresh(file, submission_name, model_description, link_paper, link_code, model_type, hub_license, req: gr.Request):
    result_text = evaluate_submission(file, submission_name, model_description, link_paper, link_code, model_type, hub_license, req)
    updated_leaderboard = load_leaderboard()
    return result_text, updated_leaderboard


# ---------- Gradio Interface ----------

with gr.Blocks() as demo:
    gr.Markdown("# Benchmark Leaderboard: Food Object Detection & Food Weight Estimation")
    
    gr.HTML(f'<img src="data:image/png;base64,{encoded_image}" alt="Description" style="max-width:100%;height:auto;">')

    gr.Markdown(
        "This leaderboard evaluates submissions for the [Food Portion Benchmark dataset](https://huggingface.co/datasets/issai/Food_Portion_Benchmark) using **mAP@50** for bounding boxes "
        "and **Mean Absolute Error (MAE)** for food weight predictions. \n\n"
        "Submissions are expected in CSV format with the columns: `image_name, class_id, xmin, ymin, xmax, ymax, weight, conf`.\n\n"
        "The ground truth CSV (kept privately) has the columns: `image_name, class_id, xmin, ymin, xmax, ymax, weight`.\n\n"
    )

    gr.Markdown(
        """
        ### Sample Submission Template

        Download a sample CSV file to see the required format:
        [Download Sample Submission CSV](https://huggingface.co/spaces/issai/Food-Weight-Benchmark/resolve/main/sample_submission.csv)
        """
    )

    # --- Leaderboard Tab (Public) ---
    with gr.TabItem("๐Ÿ… Leaderboard"):
        leaderboard_output = gr.Dataframe(label="Leaderboard")
        demo.load(load_leaderboard, outputs=leaderboard_output)
        refresh_button = gr.Button("Refresh Leaderboard")
        refresh_button.click(fn=load_leaderboard, outputs=leaderboard_output)

    with gr.TabItem("๐Ÿ“ˆ Metrics"):
        gr.Markdown(
            """
            ### Evaluation Metrics

            - **mAP@50 (Mean Average Precision at IoU 0.50):**  
            This metric evaluates how well the predicted bounding boxes match the ground truth. In mAP@50, a prediction is considered a true positive if the Intersection over Union (IoU) between the predicted box and the ground truth box is at least 0.50. The final score is averaged across all classes and images, yielding a single value between 0 and 1, where a higher value indicates better localization performance.

            - **Weight MAE (Mean Absolute Error):**  
            This metric calculates the average absolute difference (in grams) between the predicted food weight and the actual weight provided in the ground truth. A lower MAE signifies more accurate weight predictions.

            ### Benchmark Dataset

            The **Food Portion Benchmark dataset** is a comprehensive dataset for evaluating object detection and food weight estimation models. Here are some key details:

            - **Dataset Composition:**  
            It contains 14,083 RGB images of food items spanning 133 distinct classes. For each food item, the dataset includes manually annotated bounding boxes and precise weight measurements.

            - **Portion Sizes:**  
            Each food item is represented with annotations for three different portion sizes (big, average, small), reflecting the real-world variation in food serving sizes.

            - **Annotations:**  
            The ground truth annotations include the food itemโ€™s image name, class, bounding box coordinates in YOLO format, and weight in grams. 

            - **Reference and Access:**  
            You can explore and download the dataset on Hugging Face at the following link:  
            [Food Portion Benchmark Dataset](https://huggingface.co/datasets/issai/Food_Portion_Benchmark)

            ### Additional Notes

            - **Submission Requirements:**  
            Prediction CSV files must contain: image_name, class_id, xmin, ymin, xmax, ymax, weight, conf  
        
            - **Evaluation Process:**  
                - **mAP@50** is computed via the COCO evaluation API using pycocotools library, which compares the predicted bounding boxes (along with their confidence scores) to the ground truth annotations.
                - **Weight MAE** is computed using sklearnโ€™s mean absolute error function.

            - **Contact Information:**  
            For any questions regarding the dataset or evaluation methodology, please refer to the dataset documentation on Hugging Face or contact our support team.
            """
        )
                

    # --- Submission Tab ---
    with gr.TabItem("๐Ÿš€ Submit CSV"):
        gr.Markdown("**Submit your prediction CSV file and model metadata.**")
        submission_file = gr.File(label="Upload Prediction CSV", file_types=[".csv"])
        submission_name_textbox = gr.Textbox(label="Name *", placeholder="Enter your name", interactive=True)
        model_description_textbox = gr.Textbox(label="Model *", placeholder="Enter model name", interactive=True)
        link_paper_textbox = gr.Textbox(label="Link to Paper (URL)", placeholder="https://...", interactive=True)
        link_code_textbox = gr.Textbox(label="Link to Source Code (URL)", placeholder="https://...", interactive=True)
        model_type_dropdown = gr.Dropdown(label="Model Type", choices=["Open Source", "Private"], value="Open Source")
        hub_license_dropdown = gr.Dropdown(label="Hub License", choices=["", "MIT", "Apache-2.0", "CC-BY", "CC-BY-NC-4.0", "Other"], value="")

        submit_button = gr.Button("Evaluate Submission")
        evaluation_output = gr.Markdown()
        
        # No explicit username; rate limiting is done via client IP.
        submit_button.click(
            evaluate_and_refresh,
            inputs=[
                submission_file, 
                submission_name_textbox, 
                model_description_textbox,
                link_paper_textbox, 
                link_code_textbox,
                model_type_dropdown,
                hub_license_dropdown
            ],
            outputs=[evaluation_output, leaderboard_output]
        )

    gr.Markdown(
        """
        ### ๐Ÿ“™ Citation
        If you use the Food Portion Benchmark dataset in your research, please cite our work as follows:
        ```bibtex
        @misc{foodportionbenchmark2025,
        title={Paper Title},
        author={Authors},
        year={2025},
        note={Under Review}
        }
        ```
        """
    )

# ---------- Scheduler (Optional) ----------
scheduler = BackgroundScheduler()
def restart_space():
    pass
scheduler.add_job(restart_space, "interval", seconds=1800)
scheduler.start()

demo.queue(default_concurrency_limit=40).launch(show_api=False)