qiukingballball commited on
Commit
ff15a6c
·
verified ·
1 Parent(s): c32d135

Upload eval.py

Browse files
Files changed (1) hide show
  1. eval.py +174 -0
eval.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from datetime import datetime
4
+
5
+ import torch
6
+ from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
7
+
8
+ from qwen_vl_utils import process_vision_info
9
+
10
+ MODEL_PATH = os.environ.get("QWEN_VL_MODEL_PATH", "./qwen2_5_vl_model")
11
+ DEFAULT_INPUT_JSON = os.environ.get("EVAL_INPUT_JSON", "test.json")
12
+ DEFAULT_OUTPUT_JSON = os.environ.get("EVAL_OUTPUT_JSON", "results/qwen_sft_eval_results.json")
13
+
14
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
15
+ MODEL_PATH, torch_dtype="auto", device_map="auto"
16
+ )
17
+ processor = AutoProcessor.from_pretrained(MODEL_PATH)
18
+
19
+
20
+ def build_prompt(action):
21
+ return (
22
+ "Given a video and an action description, reply with one of the following options ONLY:\n"
23
+ "- 'yes' if the action is completed,\n"
24
+ "- 'no' if the action is not completed,\n"
25
+ "- 'Not exists' if the action in the video does not match the given action.\n\n"
26
+ f"Action: {action}"
27
+ )
28
+
29
+
30
+ def call_qwen_vl_with_video(prompt, video_path, max_pixels=151200, fps=0.5):
31
+ if not os.path.exists(video_path):
32
+ print(f"[error] Video not found: {video_path}")
33
+ return "Error: Video not found"
34
+ try:
35
+ messages = [
36
+ {
37
+ "role": "user",
38
+ "content": [
39
+ {
40
+ "type": "video",
41
+ "video": f"file://{video_path}",
42
+ "max_pixels": max_pixels,
43
+ "fps": fps,
44
+ },
45
+ {"type": "text", "text": prompt},
46
+ ],
47
+ }
48
+ ]
49
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
50
+ image_inputs, video_inputs = process_vision_info(messages)
51
+ inputs = processor(
52
+ text=[text],
53
+ images=image_inputs,
54
+ videos=video_inputs,
55
+ fps=fps,
56
+ padding=True,
57
+ return_tensors="pt",
58
+ ).to(model.device)
59
+ generated_ids = model.generate(**inputs, max_new_tokens=20)
60
+ generated_ids_trimmed = [
61
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
62
+ ]
63
+ output_text = processor.batch_decode(
64
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
65
+ )
66
+ return output_text[0].strip().lower()
67
+ except Exception as exc:
68
+ print(f"[error] Failed to process {video_path}: {exc}")
69
+ return "Error: Video processing failed"
70
+
71
+
72
+ def get_processed_videos(output_json_path):
73
+ if not os.path.exists(output_json_path):
74
+ return set()
75
+ try:
76
+ with open(output_json_path, "r", encoding="utf-8") as file:
77
+ data = json.load(file)
78
+ return {item["video"] for item in data}
79
+ except (json.JSONDecodeError, FileNotFoundError):
80
+ return set()
81
+
82
+
83
+ def save_result_json_list(output_path, result_entry):
84
+ result_entry["timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
85
+ if os.path.exists(output_path):
86
+ try:
87
+ with open(output_path, "r", encoding="utf-8") as file:
88
+ data = json.load(file)
89
+ except json.JSONDecodeError:
90
+ data = []
91
+ else:
92
+ data = []
93
+ data.append(result_entry)
94
+ with open(output_path, "w", encoding="utf-8") as file:
95
+ json.dump(data, file, indent=2, ensure_ascii=False)
96
+
97
+
98
+ def evaluate(json_path, output_json_path):
99
+ processed_videos = get_processed_videos(output_json_path)
100
+ print(f"[info] Previously processed videos: {len(processed_videos)}")
101
+ with open(json_path, "r", encoding="utf-8") as file:
102
+ data = json.load(file)
103
+ total = 0
104
+ correct = 0
105
+ skipped = 0
106
+ for idx, item in enumerate(data):
107
+ video_path = item["video"]
108
+ action = item["action"]
109
+ ground_truth = item["if_finish"].strip().lower()
110
+ if video_path in processed_videos:
111
+ print(
112
+ f"[{idx + 1}/{len(data)}] Skip {os.path.basename(video_path)} (already processed)"
113
+ )
114
+ skipped += 1
115
+ continue
116
+ print(f"[{idx + 1}/{len(data)}] Process {os.path.basename(video_path)}")
117
+ if not os.path.exists(video_path):
118
+ print(f"[warning] Missing file: {video_path}")
119
+ continue
120
+ prompt = build_prompt(action)
121
+ prediction = call_qwen_vl_with_video(prompt, video_path)
122
+ if prediction.startswith("Error:"):
123
+ print(f"[warning] Skipping {video_path}: {prediction}")
124
+ continue
125
+ if "not exists" in prediction:
126
+ predicted_label = "Not exists"
127
+ elif "yes" in prediction:
128
+ predicted_label = "yes"
129
+ elif "no" in prediction:
130
+ predicted_label = "no"
131
+ else:
132
+ print(f"[warning] Unrecognized output: {prediction}")
133
+ predicted_label = "Unknown"
134
+ is_correct = predicted_label.lower() == ground_truth.lower()
135
+ result_entry = {
136
+ "video": video_path,
137
+ "action": action,
138
+ "ground_truth": ground_truth,
139
+ "prediction": predicted_label,
140
+ "raw_output": prediction,
141
+ "correct": is_correct,
142
+ }
143
+ save_result_json_list(output_json_path, result_entry)
144
+ total += 1
145
+ if is_correct:
146
+ correct += 1
147
+ if total > 0:
148
+ current_accuracy = correct / total
149
+ print(f"[session] Accuracy: {current_accuracy * 100:.2f}% ({correct}/{total})")
150
+ else:
151
+ print("[session] No new videos processed.")
152
+ processed_entries = get_processed_videos(output_json_path)
153
+ all_total = len(processed_entries)
154
+ if all_total > 0:
155
+ with open(output_json_path, "r", encoding="utf-8") as file:
156
+ results_data = json.load(file)
157
+ all_correct = sum(1 for item in results_data if item.get("correct", False))
158
+ overall_accuracy = all_correct / all_total
159
+ print(f"[overall] Accuracy: {overall_accuracy * 100:.2f}% ({all_correct}/{all_total})")
160
+ print(f"[overall] Skipped videos: {skipped}")
161
+
162
+
163
+ def main():
164
+ json_path = DEFAULT_INPUT_JSON
165
+ output_json_path = DEFAULT_OUTPUT_JSON
166
+ output_dir = os.path.dirname(output_json_path)
167
+ if output_dir:
168
+ os.makedirs(output_dir, exist_ok=True)
169
+ print("Starting Qwen2.5-VL evaluation...")
170
+ evaluate(json_path, output_json_path)
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()