anonymous-eatbench-2026 commited on
Commit
9cad8a4
·
verified ·
1 Parent(s): cea4b31

Upload folder using huggingface_hub

Browse files
codes/Evaluation/evaluate.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ import argparse
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Tuple
6
+
7
+ from scipy.optimize import linear_sum_assignment
8
+
9
+ CLASSES = ["Contacting Food", "Food Approaching Mouth", "Food in Mouth"]
10
+
11
+ # Map prediction keys (snake_case) to canonical class names
12
+ PRED_LABEL_MAP = {
13
+ "contacting_food": "Contacting Food",
14
+ "food_approaching_mouth": "Food Approaching Mouth",
15
+ "food_in_mouth": "Food in Mouth",
16
+ }
17
+
18
+
19
+ def parse_args():
20
+ parser = argparse.ArgumentParser(
21
+ description="Evaluate temporal action localization on EatBench-2.7K."
22
+ )
23
+ parser.add_argument("--annotation_json", type=str, required=True,
24
+ help="Path to eatbench_annotation_full.json (ground truth).")
25
+ parser.add_argument("--pred_json", type=str, required=True,
26
+ help="Path to model prediction JSON.")
27
+ parser.add_argument("--output_json", type=str, default=None,
28
+ help="Optional path to save evaluation results.")
29
+ parser.add_argument("--thresholds", type=float, nargs="+", default=[0.1, 0.3, 0.5],
30
+ help="tIoU thresholds to evaluate at (default: 0.1 0.3 0.5).")
31
+ return parser.parse_args()
32
+
33
+
34
+ # ================== UTILS ==================
35
+
36
+ def tiou(a: Tuple[float, float], b: Tuple[float, float]) -> float:
37
+ """Temporal Intersection over Union."""
38
+ inter = max(0.0, min(a[1], b[1]) - max(a[0], b[0]))
39
+ union = (a[1] - a[0]) + (b[1] - b[0]) - inter
40
+ return inter / union if union > 1e-9 else 0.0
41
+
42
+
43
+ def safe_float(x, default=0.0) -> float:
44
+ try:
45
+ v = float(x)
46
+ return default if (math.isnan(v) or math.isinf(v)) else v
47
+ except Exception:
48
+ return default
49
+
50
+
51
+ # ================== LOADERS ==================
52
+
53
+ def load_gt(gt_path: str) -> Dict[str, Dict[str, List[Tuple[float, float]]]]:
54
+ """Load ground-truth annotations from eatbench_annotation_full.json."""
55
+ raw = json.loads(Path(gt_path).read_text())
56
+ out = {}
57
+ for entry in raw:
58
+ vid = entry.get("Video Name")
59
+ if not vid:
60
+ continue
61
+ per = {c: [] for c in CLASSES}
62
+ for act in entry.get("Actions", []):
63
+ cls = act.get("Label")
64
+ if cls not in CLASSES:
65
+ continue
66
+ s, e = safe_float(act.get("Start")), safe_float(act.get("End"))
67
+ if s > e:
68
+ s, e = e, s
69
+ if e - s > 1e-9:
70
+ per[cls].append((s, e))
71
+ out[vid] = per
72
+ return out
73
+
74
+
75
+ def load_pred(pred_path: str) -> Dict[str, Dict[str, List[Tuple[float, float]]]]:
76
+ """
77
+ Load model predictions. Supports two formats:
78
+ - {vid: {snake_key: [[s, e], ...], ...}}
79
+ - {vid: {"prediction": {snake_key: [{"segment": [s, e]}, ...]}}}
80
+ Scores are ignored (score-free evaluation).
81
+ """
82
+ raw = json.loads(Path(pred_path).read_text())
83
+ out = {}
84
+ for vid, item in raw.items():
85
+ block = item.get("prediction", item)
86
+ per = {c: [] for c in CLASSES}
87
+ if not isinstance(block, dict):
88
+ out[vid] = per
89
+ continue
90
+ for pred_lbl, segs in block.items():
91
+ cls = PRED_LABEL_MAP.get(pred_lbl)
92
+ if cls is None or not isinstance(segs, list):
93
+ continue
94
+ for it in segs:
95
+ seg = it.get("segment") if isinstance(it, dict) else it
96
+ if not (isinstance(seg, (list, tuple)) and len(seg) == 2):
97
+ continue
98
+ s, e = safe_float(seg[0]), safe_float(seg[1])
99
+ if s > e:
100
+ s, e = e, s
101
+ if e - s > 1e-9:
102
+ per[cls].append((s, e))
103
+ out[vid] = per
104
+ return out
105
+
106
+
107
+ # ================== MATCHING ==================
108
+
109
+ def hungarian_match(
110
+ pred: List[Tuple[float, float]],
111
+ gt: List[Tuple[float, float]],
112
+ thr: float,
113
+ ) -> List[Tuple[int, int, float]]:
114
+ """
115
+ One-to-one Hungarian matching maximizing total tIoU (Eq. 1 in paper).
116
+ Returns matched pairs (pred_i, gt_j, iou) with iou >= thr.
117
+ """
118
+ if not pred or not gt:
119
+ return []
120
+
121
+ BIG = 1e6
122
+ iou_mat = [[tiou(p, g) for g in gt] for p in pred]
123
+ cost = [[BIG if iou_mat[i][j] < thr else 1.0 - iou_mat[i][j]
124
+ for j in range(len(gt))]
125
+ for i in range(len(pred))]
126
+
127
+ row_ind, col_ind = linear_sum_assignment(cost)
128
+ return [
129
+ (i, j, iou_mat[i][j])
130
+ for i, j in zip(row_ind.tolist(), col_ind.tolist())
131
+ if iou_mat[i][j] >= thr and cost[i][j] < BIG
132
+ ]
133
+
134
+
135
+ # ================== EVALUATION ==================
136
+
137
+ def evaluate(
138
+ gt_path: str,
139
+ pred_path: str,
140
+ thresholds: Tuple[float, ...] = (0.1, 0.3, 0.5),
141
+ ) -> Dict[str, Any]:
142
+ """
143
+ Evaluate predictions against ground truth using Hungarian matching.
144
+ Reports per-class Precision, Recall, F1, matched mIoU, and Macro-F1
145
+ at each tIoU threshold (Section 3.6 in paper).
146
+ """
147
+ gt = load_gt(gt_path)
148
+ pred = load_pred(pred_path)
149
+ videos = sorted(set(gt.keys()) & set(pred.keys()))
150
+
151
+ results: Dict[str, Any] = {
152
+ "summary": {
153
+ "num_videos": len(videos),
154
+ "thresholds": list(thresholds),
155
+ },
156
+ "per_threshold": {},
157
+ }
158
+
159
+ for thr in thresholds:
160
+ per_class = {}
161
+ for cls in CLASSES:
162
+ TP = FP = FN = 0
163
+ iou_sum = 0.0
164
+ iou_cnt = 0
165
+ gt_total = pred_total = 0
166
+
167
+ for v in videos:
168
+ G = gt[v].get(cls, [])
169
+ P = pred[v].get(cls, [])
170
+ gt_total += len(G)
171
+ pred_total += len(P)
172
+
173
+ matches = hungarian_match(P, G, thr)
174
+ tp = len(matches)
175
+ TP += tp
176
+ FP += len(P) - tp
177
+ FN += len(G) - tp
178
+ for _, _, iou in matches:
179
+ iou_sum += iou
180
+ iou_cnt += 1
181
+
182
+ prec = TP / (TP + FP) if TP + FP > 0 else 0.0
183
+ rec = TP / (TP + FN) if TP + FN > 0 else 0.0
184
+ f1 = 2 * prec * rec / (prec + rec) if prec + rec > 0 else 0.0
185
+ miou = iou_sum / iou_cnt if iou_cnt > 0 else 0.0
186
+
187
+ per_class[cls] = {
188
+ "Precision": round(prec, 4),
189
+ "Recall": round(rec, 4),
190
+ "F1": round(f1, 4),
191
+ "mIoU": round(miou, 4),
192
+ "TP": TP, "FP": FP, "FN": FN,
193
+ "GT": gt_total, "Pred": pred_total,
194
+ }
195
+
196
+ macro_f1 = sum(per_class[c]["F1"] for c in CLASSES) / len(CLASSES)
197
+ results["per_threshold"][f"tIoU@{thr}"] = {
198
+ "per_class": per_class,
199
+ "Macro_F1": round(macro_f1, 4),
200
+ }
201
+
202
+ return results
203
+
204
+
205
+ def print_results(results: Dict[str, Any]):
206
+ print(f"\nVideos evaluated: {results['summary']['num_videos']}")
207
+ for thr_key, data in results["per_threshold"].items():
208
+ print(f"\n{'='*50}")
209
+ print(f" {thr_key} Macro-F1: {data['Macro_F1']:.4f}")
210
+ print(f"{'='*50}")
211
+ print(f" {'Class':<28} {'P':>6} {'R':>6} {'F1':>6} {'mIoU':>6}")
212
+ print(f" {'-'*54}")
213
+ for cls, m in data["per_class"].items():
214
+ print(f" {cls:<28} {m['Precision']:>6.4f} {m['Recall']:>6.4f} {m['F1']:>6.4f} {m['mIoU']:>6.4f}")
215
+
216
+
217
+ # ================== MAIN ==================
218
+
219
+ if __name__ == "__main__":
220
+ args = parse_args()
221
+
222
+ results = evaluate(
223
+ gt_path=args.annotation_json,
224
+ pred_path=args.pred_json,
225
+ thresholds=tuple(args.thresholds),
226
+ )
227
+
228
+ print_results(results)
229
+
230
+ if args.output_json:
231
+ Path(args.output_json).parent.mkdir(parents=True, exist_ok=True)
232
+ Path(args.output_json).write_text(json.dumps(results, indent=2))
233
+ print(f"\nResults saved to: {args.output_json}")
codes/README.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EatBench-2.7K: Evaluation Code
2
+
3
+ This directory contains the evaluation code for EatBench-2.7K, including the SAFR frame selection strategy, the OneThinker inference pipeline, and the evaluation script.
4
+
5
+ ## Overview
6
+
7
+ The full pipeline runs in three steps:
8
+
9
+ 1. **`run_SAFR.py`** — Extract frames from each video using uniform sampling or SAFR (Semantic-Anchored Frame Relocation). Saves frames to disk and produces a manifest JSON with frame paths and timestamps.
10
+ 2. **`run_OneThinker.py`** — Run OneThinker inference using the cached frames from the manifest, and save predicted action segments to a results JSON.
11
+ 3. **`Evaluation/evaluate.py`** — Evaluate predictions against ground truth using Hungarian matching and report per-class Precision, Recall, F1, mIoU, and Macro-F1.
12
+
13
+ ## Requirements
14
+
15
+ ```bash
16
+ pip install torch transformers opencv-python numpy tqdm vllm qwen-vl-utils
17
+ ```
18
+
19
+ CLIP model (`openai/clip-vit-base-patch32`) and OneThinker checkpoint (`OneThink/OneThinker-8B`) will be downloaded automatically from HuggingFace on first run.
20
+
21
+ ## Step 1: Frame Extraction
22
+
23
+ ### Uniform Sampling (baseline)
24
+
25
+ ```bash
26
+ python run_SAFR.py \
27
+ --mode uniform \
28
+ --annotation_json /path/to/eatbench_annotation_full.json \
29
+ --video_dir /path/to/videos/ \
30
+ --output_dir /path/to/frames/
31
+ ```
32
+
33
+ ### SAFR (Semantic-Anchored Frame Relocation)
34
+
35
+ ```bash
36
+ python run_SAFR.py \
37
+ --mode safr \
38
+ --smooth_w 3 \
39
+ --annotation_json /path/to/eatbench_annotation_full.json \
40
+ --video_dir /path/to/videos/ \
41
+ --output_dir /path/to/frames/
42
+ ```
43
+
44
+ **Arguments:**
45
+
46
+ | Argument | Default | Description |
47
+ |---|---|---|
48
+ | `--mode` | `safr` | Frame selection mode: `uniform` or `safr` |
49
+ | `--smooth_w` | `3` | Temporal smoothing window size for CLIP similarity (SAFR only) |
50
+ | `--annotation_json` | required | Path to `eatbench_annotation_full.json` |
51
+ | `--video_dir` | required | Directory containing video `.mp4` files |
52
+ | `--output_dir` | required | Root directory for cached frames and manifest |
53
+
54
+ **Output:** A subdirectory is created under `--output_dir` containing:
55
+ - Extracted frame images (`*.jpg`) organized per video
56
+ - `manifest_with_time.json` — maps each video to its selected frame paths and timestamps
57
+
58
+ ## Step 2: OneThinker Inference
59
+
60
+ ```bash
61
+ python run_OneThinker.py \
62
+ --annotation_json /path/to/eatbench_annotation_full.json \
63
+ --video_dir /path/to/videos/ \
64
+ --manifest_json /path/to/frames/safr_safr_fps2.0_max16_smooth3/manifest_with_time.json \
65
+ --output_json /path/to/results/onethinker_safr.json
66
+ ```
67
+
68
+ **Arguments:**
69
+
70
+ | Argument | Default | Description |
71
+ |---|---|---|
72
+ | `--checkpoint` | `OneThink/OneThinker-8B` | Model checkpoint path or HuggingFace model ID |
73
+ | `--annotation_json` | required | Path to `eatbench_annotation_full.json` |
74
+ | `--video_dir` | required | Directory containing video `.mp4` files |
75
+ | `--manifest_json` | required | Path to `manifest_with_time.json` from Step 1 |
76
+ | `--output_json` | required | Path to save prediction results |
77
+
78
+ **Output:** A JSON file mapping each video name to predicted action segments:
79
+
80
+ ```json
81
+ {
82
+ "video_name.mp4": {
83
+ "contacting_food": [[0.0, 1.2], [8.3, 9.1]],
84
+ "food_approaching_mouth": [[1.2, 2.0], [9.1, 9.8]],
85
+ "food_in_mouth": [[2.0, 5.5], [9.8, 12.3]]
86
+ },
87
+ ...
88
+ }
89
+ ```
90
+
91
+ ## Full Pipeline Example
92
+
93
+ ```bash
94
+ # Step 1: extract frames with SAFR
95
+ python run_SAFR.py \
96
+ --mode safr \
97
+ --annotation_json eatbench_annotation_full.json \
98
+ --video_dir videos/ \
99
+ --output_dir frames/
100
+
101
+ # Step 2: run OneThinker inference
102
+ python run_OneThinker.py \
103
+ --annotation_json eatbench_annotation_full.json \
104
+ --video_dir videos/ \
105
+ --manifest_json frames/safr_safr_fps2.0_max16_smooth3/manifest_with_time.json \
106
+ --output_json results/onethinker_safr.json
107
+
108
+ # Step 3: evaluate
109
+ python Evaluation/evaluate.py \
110
+ --annotation_json eatbench_annotation_full.json \
111
+ --pred_json results/onethinker_safr.json \
112
+ --output_json results/onethinker_safr_metrics.json
113
+ ```
114
+
115
+ ## Step 3: Evaluation
116
+
117
+ ```bash
118
+ python Evaluation/evaluate.py \
119
+ --annotation_json /path/to/eatbench_annotation_full.json \
120
+ --pred_json /path/to/results/onethinker_safr.json \
121
+ --output_json /path/to/results/onethinker_safr_metrics.json
122
+ ```
123
+
124
+ **Arguments:**
125
+
126
+ | Argument | Default | Description |
127
+ |---|---|---|
128
+ | `--annotation_json` | required | Path to `eatbench_annotation_full.json` (ground truth) |
129
+ | `--pred_json` | required | Path to model prediction JSON from Step 2 |
130
+ | `--output_json` | `None` | Optional path to save evaluation results as JSON |
131
+ | `--thresholds` | `0.1 0.3 0.5` | tIoU thresholds to evaluate at |
132
+
133
+ **Console output:**
134
+ ```
135
+ Videos evaluated: 525
136
+
137
+ ==================================================
138
+ tIoU@0.1 Macro-F1: 0.3330
139
+ ==================================================
140
+ Class P R F1 mIoU
141
+ ------------------------------------------------------
142
+ Contacting Food 0.2880 0.3460 0.3150 0.1892
143
+ Food Approaching Mouth 0.3620 0.1830 0.2430 0.1421
144
+ Foodin Mouth 0.7330 0.3150 0.4410 0.2105
145
+ ```
146
+
147
+ **Output JSON format:**
148
+ ```json
149
+ {
150
+ "summary": {"num_videos": 525, "thresholds": [0.1, 0.3, 0.5]},
151
+ "per_threshold": {
152
+ "tIoU@0.1": {
153
+ "Macro_F1": 0.333,
154
+ "per_class": {
155
+ "Contacting Food": {"Precision": 0.288, "Recall": 0.346, "F1": 0.315, "mIoU": 0.189, ...},
156
+ "Food Approaching Mouth": {"Precision": 0.362, "Recall": 0.183, "F1": 0.243, "mIoU": 0.142, ...},
157
+ "Food in Mouth": {"Precision": 0.733, "Recall": 0.315, "F1": 0.441, "mIoU": 0.211, ...}
158
+ }
159
+ }
160
+ }
161
+ }
162
+ ```
163
+
164
+ The evaluator accepts predictions in two formats:
165
+ - `{video_name: {snake_key: [[s, e], ...], ...}}` — output of `run_OneThinker.py`
166
+ - `{video_name: {"prediction": {snake_key: [{"segment": [s, e], "score": ...}, ...]}}}` — score-based format (scores ignored)
167
+
168
+ ## SAFR Algorithm
169
+
170
+ SAFR partitions the video timeline into K equal windows around uniform anchors and relocates each anchor to the frame with the highest semantic similarity to the eating-action prompts (Algorithm 1 in the paper).
171
+
172
+ Given T video frames and frame budget K:
173
+ 1. Compute per-frame, per-action CLIP similarity scores s_a(t)
174
+ 2. Smooth each s_a(t) with a temporal window, then aggregate: S(t) = max_a s̃_a(t)
175
+ 3. Place uniform anchors at u_i = floor((T/K)(i − 0.5))
176
+ 4. For each window W_i around u_i, select y_i = argmax_{t ∈ W_i} S(t)
177
+
178
+ SAFR adds O(T) overhead over uniform sampling and requires no training or model modification.
codes/requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core
2
+ torch>=2.1.0
3
+ torchvision>=0.16.0
4
+ numpy>=1.24.0
5
+ Pillow>=10.0.0
6
+
7
+ # Video processing
8
+ opencv-python>=4.8.0
9
+
10
+ # CLIP (for SAFR frame selection)
11
+ transformers>=4.45.0
12
+
13
+ # OneThinker / Qwen2.5-VL inference
14
+ vllm>=0.6.3
15
+ qwen-vl-utils>=0.0.8
16
+ accelerate>=0.26.0
17
+
18
+ # Utilities
19
+ tqdm>=4.65.0
20
+ scipy>=1.11.0
codes/run_OneThinker.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import ast
4
+ import re
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ import cv2
9
+ from tqdm import tqdm
10
+ from transformers import AutoProcessor
11
+ from vllm import LLM, SamplingParams
12
+ from qwen_vl_utils import process_vision_info
13
+
14
+ os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
15
+
16
+
17
+ # ================== TASK DEFINITION ==================
18
+ FINE_DEFS = (
19
+ "Identify fine-grained eating micro-actions in the video. "
20
+ "Categories:\n"
21
+ "1) contacting_food — direct contact with food using hand/utensil (pick/grab/cut/scoop/pour/stir/serve).\n"
22
+ "2) food_approaching_mouth — transporting/aligning food toward the lips/teeth/tongue.\n"
23
+ "3) food_in_mouth — from first contact with lips until food crosses the lip line."
24
+ )
25
+
26
+ FORMAT_INSTRUCTION = (
27
+ "Please provide only the action localization results as a JSON dictionary within the <answer>...</answer> tags. "
28
+ "Example:\n<answer>{{\"contacting_food\": [[0.0, 1.2]], \"food_approaching_mouth\": [[2.3, 3.1]], \"food_in_mouth\": [[3.2, 5.0]]}}</answer>"
29
+ )
30
+
31
+ QUESTION_TEMPLATE = (
32
+ "{Question}\n"
33
+ "Provide your thinking process between the <think> and </think> tags, and then give your final answer between the <answer> and </answer> tags.\n"
34
+ + FORMAT_INSTRUCTION
35
+ )
36
+
37
+
38
+ def parse_args():
39
+ parser = argparse.ArgumentParser(description="Run OneThinker on EatBench-2.7K.")
40
+ parser.add_argument("--checkpoint", type=str, default="OneThink/OneThinker-8B",
41
+ help="Model checkpoint path or HuggingFace model ID.")
42
+ parser.add_argument("--annotation_json", type=str, required=True,
43
+ help="Path to EatBench annotation JSON.")
44
+ parser.add_argument("--video_dir", type=str, required=True,
45
+ help="Directory containing video files.")
46
+ parser.add_argument("--manifest_json", type=str, required=True,
47
+ help="Path to frame manifest produced by run_SAFR.py.")
48
+ parser.add_argument("--output_json", type=str, required=True,
49
+ help="Path to save prediction results.")
50
+ return parser.parse_args()
51
+
52
+
53
+ # ================== UTILS ==================
54
+
55
+ def get_video_meta(path):
56
+ cap = cv2.VideoCapture(path)
57
+ if not cap.isOpened():
58
+ return 0.0, 0, 30.0
59
+ frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
60
+ fps = float(cap.get(cv2.CAP_PROP_FPS)) or 30.0
61
+ duration = frames / fps if fps > 0 else 0.0
62
+ cap.release()
63
+ return duration, frames, fps
64
+
65
+
66
+ def try_parse_answer(text):
67
+ match = re.search(r'<answer>(.*?)</answer>', text, re.DOTALL)
68
+ if match:
69
+ content = match.group(1).strip()
70
+ try:
71
+ return ast.literal_eval(content)
72
+ except Exception:
73
+ clean = re.sub(r'```json|```', '', content).strip()
74
+ try:
75
+ return json.loads(clean)
76
+ except Exception:
77
+ pass
78
+ return {}
79
+
80
+
81
+ def normalize(obj):
82
+ keys = ["contacting_food", "food_approaching_mouth", "food_in_mouth"]
83
+ out = {k: [] for k in keys}
84
+ if not isinstance(obj, dict):
85
+ return out
86
+ for k in keys:
87
+ for it in obj.get(k, []):
88
+ if isinstance(it, (list, tuple)) and len(it) == 2:
89
+ out[k].append([round(float(it[0]), 1), round(float(it[1]), 1)])
90
+ return out
91
+
92
+
93
+ def build_timeline_header(frames_list):
94
+ """Build a compact frame timestamp header to prepend to the prompt."""
95
+ frames_list = sorted(frames_list, key=lambda x: int(x.get("idx", 0)))
96
+ lines = ["Selected frames (time in seconds):"]
97
+ for fr in frames_list:
98
+ lines.append(f"#{int(fr.get('k', 0))} t={float(fr.get('t', 0.0)):.2f}s")
99
+ return "\n".join(lines)
100
+
101
+
102
+ def prepare_inputs_for_vllm(messages, processor):
103
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
104
+ image_inputs, video_inputs, video_kwargs = process_vision_info(
105
+ messages,
106
+ image_patch_size=processor.image_processor.patch_size,
107
+ return_video_kwargs=True,
108
+ return_video_metadata=True,
109
+ )
110
+ mm_data = {}
111
+ if image_inputs is not None:
112
+ mm_data["image"] = image_inputs
113
+ if video_inputs is not None:
114
+ mm_data["video"] = video_inputs
115
+ if video_kwargs is not None and "video_grid_thw" in video_kwargs:
116
+ mm_data["video_metadata"] = {"video_grid_thw": video_kwargs["video_grid_thw"]}
117
+ return {
118
+ "prompt": text,
119
+ "multi_modal_data": mm_data,
120
+ "mm_processor_kwargs": video_kwargs,
121
+ }
122
+
123
+
124
+ # ================== MAIN ==================
125
+
126
+ def main():
127
+ args = parse_args()
128
+
129
+ with open(args.manifest_json) as f:
130
+ manifest = json.load(f)
131
+
132
+ processor = AutoProcessor.from_pretrained(args.checkpoint)
133
+ llm = LLM(
134
+ model=args.checkpoint,
135
+ mm_encoder_tp_mode="data",
136
+ tensor_parallel_size=1,
137
+ max_model_len=24576,
138
+ gpu_memory_utilization=0.5,
139
+ )
140
+ sampling_params = SamplingParams(temperature=0.0, max_tokens=4096)
141
+
142
+ with open(args.annotation_json) as f:
143
+ test_list = json.load(f)
144
+
145
+ all_inputs = []
146
+ video_names = []
147
+
148
+ print("Pre-processing video inputs...")
149
+ for entry in tqdm(test_list):
150
+ videoname = entry.get("Video Name")
151
+ if not videoname:
152
+ continue
153
+ video_path = os.path.join(args.video_dir, videoname)
154
+ if not os.path.exists(video_path):
155
+ continue
156
+
157
+ info = manifest.get(videoname)
158
+ if info and isinstance(info.get("frames"), list) and info["frames"]:
159
+ frames_list = sorted(info["frames"], key=lambda x: int(x.get("idx", 0)))
160
+ frame_paths = [fr["path"] for fr in frames_list if os.path.exists(fr.get("path", ""))]
161
+ video_field = frame_paths if frame_paths else video_path
162
+ else:
163
+ frames_list = None
164
+ video_field = video_path
165
+
166
+ duration, _, _ = get_video_meta(video_path)
167
+
168
+ if frames_list and isinstance(video_field, list):
169
+ timeline = build_timeline_header(frames_list)
170
+ question_text = f"{timeline}\nThe video lasts {duration:.1f}s. {FINE_DEFS}"
171
+ else:
172
+ question_text = f"The video lasts {duration:.1f}s. {FINE_DEFS}"
173
+
174
+ full_text = QUESTION_TEMPLATE.format(Question=question_text)
175
+ messages = [
176
+ {
177
+ "role": "user",
178
+ "content": [
179
+ {"type": "video", "video": video_field, "max_pixels": 256 * 32 * 32},
180
+ {"type": "text", "text": full_text},
181
+ ],
182
+ }
183
+ ]
184
+
185
+ all_inputs.append(prepare_inputs_for_vllm(messages, processor))
186
+ video_names.append(videoname)
187
+
188
+ print(f"Running inference on {len(all_inputs)} videos...")
189
+ outputs = llm.generate(all_inputs, sampling_params=sampling_params)
190
+
191
+ results = {}
192
+ for videoname, output in zip(video_names, outputs):
193
+ parsed = try_parse_answer(output.outputs[0].text)
194
+ results[videoname] = normalize(parsed)
195
+
196
+ os.makedirs(str(Path(args.output_json).parent), exist_ok=True)
197
+ with open(args.output_json, "w") as f:
198
+ json.dump(results, f, indent=2)
199
+
200
+ print(f"Results saved to {args.output_json}")
201
+
202
+
203
+ if __name__ == "__main__":
204
+ main()
codes/run_SAFR.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+ from pathlib import Path
5
+
6
+ import cv2
7
+ import numpy as np
8
+ from tqdm import tqdm
9
+
10
+
11
+ # ================== CONFIG ==================
12
+ CLIP_MODEL_ID = "openai/clip-vit-base-patch32"
13
+ BATCH_SIZE = 32
14
+ ACTION_TEXTS = [
15
+ "contacting food with hand or utensil (pick/grab/cut/scoop/pour/stir/serve)",
16
+ "food approaching mouth (transporting food toward lips/teeth/tongue)",
17
+ "food in mouth (food crosses the lip line, chewing or inside mouth)",
18
+ ]
19
+ FPS_SAMPLE = 2.0
20
+ MAX_FRAMES = 16
21
+ # ============================================
22
+
23
+
24
+ def parse_args():
25
+ parser = argparse.ArgumentParser(
26
+ description="Extract frames with uniform sampling or SAFR (Semantic-Anchored Frame Relocation)."
27
+ )
28
+ parser.add_argument("--mode", type=str, default="safr", choices=["uniform", "safr"],
29
+ help="Frame selection mode: 'uniform' or 'safr'.")
30
+ parser.add_argument("--smooth_w", type=int, default=3,
31
+ help="Temporal smoothing window size for CLIP similarity scores (paper default: 3).")
32
+ parser.add_argument("--annotation_json", type=str, required=True,
33
+ help="Path to EatBench annotation JSON.")
34
+ parser.add_argument("--video_dir", type=str, required=True,
35
+ help="Directory containing video files.")
36
+ parser.add_argument("--output_dir", type=str, required=True,
37
+ help="Root output directory for cached frames and manifest.")
38
+ return parser.parse_args()
39
+
40
+
41
+ # ================== VIDEO UTILS ==================
42
+
43
+ def get_video_meta(path: str):
44
+ cap = cv2.VideoCapture(path)
45
+ if not cap.isOpened():
46
+ return 0.0, 0, 30.0
47
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
48
+ fps = float(cap.get(cv2.CAP_PROP_FPS)) or 30.0
49
+ duration = total_frames / fps if fps > 0 else 0.0
50
+ cap.release()
51
+ return duration, total_frames, fps
52
+
53
+
54
+ def desired_num_frames(duration_s: float) -> int:
55
+ """Compute frame budget: duration * FPS_SAMPLE, capped at MAX_FRAMES."""
56
+ n = int(round(duration_s * FPS_SAMPLE))
57
+ return max(1, min(n, MAX_FRAMES))
58
+
59
+
60
+ def uniform_sample_frames(total_frames: int, num_frames: int):
61
+ """Tick/center uniform sampling. Returns frame indices in [0, total_frames-1]."""
62
+ if num_frames <= 0 or total_frames <= 0:
63
+ return []
64
+ if num_frames >= total_frames:
65
+ return list(range(total_frames))
66
+ tick = total_frames / num_frames
67
+ idx = [int(tick / 2.0 + tick * x) for x in range(num_frames)]
68
+ idx = [min(max(i, 0), total_frames - 1) for i in idx]
69
+ out, last = [], None
70
+ for i in idx:
71
+ if last is None or i != last:
72
+ out.append(i)
73
+ last = i
74
+ return out
75
+
76
+
77
+ def extract_frames_by_indices(video_path: str, out_dir: Path, indices, skip_if_exists=True):
78
+ """Extract frames at given indices and save as JPEG. Returns list of (k, idx, path)."""
79
+ out_dir.mkdir(parents=True, exist_ok=True)
80
+ expected = [out_dir / f"f_{k:03d}_idx{idx:06d}.jpg" for k, idx in enumerate(indices)]
81
+ if skip_if_exists and expected and all(p.exists() for p in expected):
82
+ return [(k, indices[k], str(expected[k])) for k in range(len(indices))]
83
+
84
+ cap = cv2.VideoCapture(video_path)
85
+ if not cap.isOpened():
86
+ return []
87
+ total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
88
+ saved = []
89
+ for k, idx in enumerate(indices):
90
+ idx = int(min(max(idx, 0), total - 1))
91
+ save_path = out_dir / f"f_{k:03d}_idx{idx:06d}.jpg"
92
+ if skip_if_exists and save_path.exists():
93
+ saved.append((k, idx, str(save_path)))
94
+ continue
95
+ cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
96
+ ok, frame = cap.read()
97
+ if not ok:
98
+ continue
99
+ cv2.imwrite(str(save_path), frame)
100
+ saved.append((k, idx, str(save_path)))
101
+ cap.release()
102
+ return saved
103
+
104
+
105
+ # ================== SAFR ==================
106
+
107
+ def moving_average(x: np.ndarray, w: int) -> np.ndarray:
108
+ """Symmetric moving average with reflect padding."""
109
+ if w <= 1:
110
+ return x.astype(np.float64)
111
+ if w % 2 == 0:
112
+ w += 1
113
+ pad = w // 2
114
+ xp = np.pad(x.astype(np.float64), (pad, pad), mode="reflect")
115
+ kernel = np.ones(w, dtype=np.float64) / float(w)
116
+ return np.convolve(xp, kernel, mode="valid")
117
+
118
+
119
+ def build_windows(total_frames: int, anchors: list):
120
+ """
121
+ Build K disjoint windows W_i = [L_i, R_i] around uniform anchors,
122
+ bounded by midpoints between adjacent anchors (Algorithm 1, SAFR).
123
+ """
124
+ n = len(anchors)
125
+ if n == 0:
126
+ return []
127
+ a = [int(x) for x in anchors]
128
+ bounds = [0]
129
+ for i in range(n - 1):
130
+ bounds.append((a[i] + a[i + 1]) // 2)
131
+ bounds.append(total_frames - 1)
132
+
133
+ segs = []
134
+ for i in range(n):
135
+ L = bounds[i]
136
+ R = bounds[i + 1]
137
+ if i > 0:
138
+ L = max(L, segs[-1][1] + 1)
139
+ segs.append((L, max(L, R)))
140
+ segs[-1] = (segs[-1][0], total_frames - 1)
141
+ return segs
142
+
143
+
144
+ def select_indices_safr(s_mat: np.ndarray, anchors: list, smooth_w: int) -> list:
145
+ """
146
+ SAFR frame selection (Algorithm 1 in the paper).
147
+
148
+ Args:
149
+ s_mat: (A, T) array of per-action CLIP similarity scores.
150
+ anchors: K uniform anchor frame indices.
151
+ smooth_w: Temporal smoothing window size.
152
+
153
+ Returns:
154
+ List of K selected frame indices, one per window.
155
+ """
156
+ T = s_mat.shape[1]
157
+
158
+ # Smooth each action's similarity sequence independently, then aggregate (Eq. 4)
159
+ s_mat_sm = np.stack([moving_average(s_mat[a], smooth_w) for a in range(s_mat.shape[0])])
160
+ S = s_mat_sm.max(axis=0) # S(t) = max_a s̃_a(t)
161
+
162
+ # Select argmax within each local window (Eq. 5)
163
+ windows = build_windows(T, anchors)
164
+ chosen = []
165
+ for (L, R) in windows:
166
+ sub = S[L:R + 1]
167
+ t = L if sub.size == 0 else int(L + np.argmax(sub))
168
+ chosen.append(t)
169
+
170
+ # Enforce strictly increasing indices
171
+ out, last = [], -1
172
+ for t in chosen:
173
+ if t <= last:
174
+ t = min(last + 1, T - 1)
175
+ out.append(t)
176
+ last = t
177
+ return out[:len(anchors)]
178
+
179
+
180
+ # ================== CLIP SCORING ==================
181
+
182
+ def clip_scores_all_frames(video_path: str, total_frames: int, model, processor, text_emb, device):
183
+ """
184
+ Compute per-action CLIP similarity for every frame in the video.
185
+ Returns s_mat of shape (A, total_frames).
186
+ """
187
+ from PIL import Image
188
+ import torch
189
+
190
+ cap = cv2.VideoCapture(video_path)
191
+ if not cap.isOpened():
192
+ return None
193
+
194
+ A = text_emb.shape[0]
195
+ s_mat = np.zeros((A, total_frames), dtype=np.float32)
196
+ imgs, idxs = [], []
197
+ t = 0
198
+
199
+ def flush(imgs, idxs):
200
+ with torch.no_grad():
201
+ inputs = processor(images=imgs, return_tensors="pt").to(device)
202
+ img_emb = model.get_image_features(**inputs)
203
+ img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True)
204
+ sim = (text_emb @ img_emb.T).float().cpu().numpy()
205
+ for b, fr_idx in enumerate(idxs):
206
+ s_mat[:, fr_idx] = sim[:, b]
207
+
208
+ while True:
209
+ ok, frame = cap.read()
210
+ if not ok:
211
+ break
212
+ imgs.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
213
+ idxs.append(t)
214
+ t += 1
215
+ if len(imgs) >= BATCH_SIZE:
216
+ flush(imgs, idxs)
217
+ imgs, idxs = [], []
218
+
219
+ if imgs:
220
+ flush(imgs, idxs)
221
+ cap.release()
222
+ return s_mat
223
+
224
+
225
+ # ================== MAIN ==================
226
+
227
+ def main():
228
+ args = parse_args()
229
+
230
+ output_dir = Path(args.output_dir) / f"safr_{args.mode}_fps{FPS_SAMPLE}_max{MAX_FRAMES}"
231
+ if args.mode == "safr":
232
+ output_dir = Path(str(output_dir) + f"_smooth{args.smooth_w}")
233
+ output_dir.mkdir(parents=True, exist_ok=True)
234
+ manifest_path = output_dir / "manifest_with_time.json"
235
+
236
+ with open(args.annotation_json, "r") as f:
237
+ test_list = json.load(f)
238
+
239
+ # Load CLIP only when needed
240
+ if args.mode == "safr":
241
+ import torch
242
+ from transformers import CLIPProcessor, CLIPModel
243
+ device = "cuda" if torch.cuda.is_available() else "cpu"
244
+ clip_model = CLIPModel.from_pretrained(CLIP_MODEL_ID).to(device).eval()
245
+ clip_proc = CLIPProcessor.from_pretrained(CLIP_MODEL_ID)
246
+ with torch.no_grad():
247
+ text_inputs = clip_proc(text=ACTION_TEXTS, return_tensors="pt", padding=True).to(device)
248
+ text_emb = clip_model.get_text_features(**text_inputs)
249
+ text_emb = text_emb / text_emb.norm(dim=-1, keepdim=True)
250
+ else:
251
+ clip_model = clip_proc = text_emb = device = None
252
+
253
+ manifest = {}
254
+ missing = 0
255
+
256
+ for entry in tqdm(test_list, desc=f"Frame extraction [{args.mode}]"):
257
+ videoname = entry.get("Video Name")
258
+ if not videoname:
259
+ continue
260
+ video_path = os.path.join(args.video_dir, videoname)
261
+ if not os.path.exists(video_path):
262
+ missing += 1
263
+ continue
264
+
265
+ duration, total_frames, fps = get_video_meta(video_path)
266
+ if total_frames <= 0 or fps <= 0:
267
+ continue
268
+
269
+ n = desired_num_frames(duration)
270
+ anchors = uniform_sample_frames(total_frames, n)
271
+
272
+ if args.mode == "uniform":
273
+ indices = anchors
274
+ else:
275
+ s_mat = clip_scores_all_frames(video_path, total_frames, clip_model, clip_proc, text_emb, device)
276
+ if s_mat is None:
277
+ continue
278
+ indices = select_indices_safr(s_mat, anchors, smooth_w=args.smooth_w)
279
+
280
+ saved = extract_frames_by_indices(video_path, output_dir / videoname, indices)
281
+ if not saved:
282
+ continue
283
+
284
+ frames = [{"k": k, "idx": idx, "t": round(idx / fps, 3), "path": p} for k, idx, p in saved]
285
+ manifest[videoname] = {
286
+ "video_path": video_path,
287
+ "duration": round(duration, 3),
288
+ "fps": round(fps, 6),
289
+ "total_frames": int(total_frames),
290
+ "nframes": len(frames),
291
+ "frames": frames,
292
+ "mode": args.mode,
293
+ "smooth_w": args.smooth_w if args.mode == "safr" else None,
294
+ "clip_model": CLIP_MODEL_ID if args.mode == "safr" else None,
295
+ }
296
+
297
+ with open(manifest_path, "w") as f:
298
+ json.dump(manifest, f, indent=2)
299
+
300
+ print(f"Processed: {len(manifest)} videos")
301
+ if missing:
302
+ print(f"Missing video files: {missing}")
303
+ print(f"Manifest saved to: {manifest_path}")
304
+
305
+
306
+ if __name__ == "__main__":
307
+ main()