-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patheval_screenspot_pro.py
More file actions
555 lines (468 loc) · 21 KB
/
Copy patheval_screenspot_pro.py
File metadata and controls
555 lines (468 loc) · 21 KB
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# -----------------------------------------------------------------------------
# Copyright 2025 vivo Mobile Communication Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------------------
import copy
import itertools
import torch
import json
import re
import argparse
import os
from PIL import Image
import logging
from tqdm import tqdm
logging.basicConfig(level=logging.INFO)
torch.manual_seed(114514)
GT_TYPES = ['positive', 'negative']
INSTRUCTION_STYLES = ['instruction', 'action', 'description']
LANGUAGES = ['en', 'cn']
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model_type', type=str, required=True)
parser.add_argument('--model_name_or_path', type=str, required=False)
parser.add_argument('--screenspot_imgs', type=str, required=True)
parser.add_argument('--screenspot_test', type=str, required=True)
parser.add_argument('--task', type=str, required=True)
parser.add_argument('--inst_style', type=str, required=True, choices=INSTRUCTION_STYLES + ['all'], help="Instruction style to use.")
parser.add_argument('--language', type=str, required=True, choices=LANGUAGES + ['all'], default='en', help="Language to use.")
parser.add_argument('--gt_type', type=str, required=True, choices=GT_TYPES + ['all'], help="Ground truth type: 'positive' or 'negative'.")
parser.add_argument('--log_path', type=str, required=True)
parser.add_argument('--max_iter', type=int, default=5, help="Maximum number of iterations for iterative grounding.")
parser.add_argument('--threshold', type=float, default=0.05, help="Threshold for stopping in iterative grounding.")
args = parser.parse_args()
return args
def build_model(args):
model_type = args.model_type
model_name_or_path = args.model_name_or_path
if model_type == "ugroundv1":
from models.ugroundv1 import UGroundV1Model
model = UGroundV1Model()
model.load_model()
elif model_type == "osatlas-7b":
from models.osatlas7b import OSAtlas7BModel, OSAtlas7BVLLMModel
model = OSAtlas7BModel()
model.load_model()
# planner = PlannerAgent(executor)
elif model_type == "qwen2_5vl":
from models.qwen2_5vl import Qwen2_5VLModel
model = Qwen2_5VLModel()
if model_name_or_path:
model.load_model(model_name_or_path=model_name_or_path)
else:
model.load_model()
# elif model_type == "qwen1vl":
# from models.qwen1vl import Qwen1VLModel
# model = Qwen1VLModel()
# model.load_model()
# elif model_type == "qwen2vl":
# from models.qwen2vl import Qwen2VLModel
# model = Qwen2VLModel()
# if args.model_name_or_path:
# model.load_model(model_name_or_path=model_name_or_path)
# else:
# model.load_model()
# elif model_type == "qwen2_5vl":
# from models.qwen2_5vl import Qwen2_5VLModel
# model = Qwen2_5VLModel()
# model.load_model()
# elif model_type in ["gpt4o", "gpt4v"]:
# from models.gpt4x import GPT4XModel
# model = GPT4XModel()
elif model_type == "osatlas-4b":
from models.osatlas4b import OSAtlas4BModel
model = OSAtlas4BModel()
model.load_model()
# elif model_type == "osatlas-7b":
# from models.osatlas7b import OSAtlas7BModel, OSAtlas7BVLLMModel
# model = OSAtlas7BModel()
# model.load_model()
# elif model_type == "osatlas-omniv2":
# from models.osatlas_omniv2 import OSATLAS
# model = OSATLAS()
# # model = OSAtlas7BVLLMModel()
# model.load_model()
# elif model_type == "osatlas-iterative-omni":
# from models.osatlas_iterative_omni import OSAtlas7BModel
# model = OSAtlas7BModel()
# # model = OSAtlas7BVLLMModel()
# model.load_model()
# elif model_type == "osatlas-planner":
# from models.osatlas7b import OSAtlas7BModel
# from models.planner import PlannerAgent
# executor = OSAtlas7BModel()
# executor.load_model()
# planner = PlannerAgent(executor)
elif model_type == "uground":
from models.uground import UGroundModel
model = UGroundModel()
model.load_model()
else:
raise ValueError(f"Unsupported model type {model_type}.")
# executor.set_generation_config(temperature=0, max_new_tokens=256)
# planner.set_generation_config(temperature=0, max_new_tokens=256)
# return executor, planner
model.set_generation_config(temperature=0, max_new_tokens=256)
return model
def collect_results_to_eval(results, platform=None, group=None, application=None, language=None, gt_type=None, instruction_style=None, ui_type=None):
"""
Filters the results based on provided values. None means include all (ignore filtering this attribute).
Parameters:
results (list): A list of dictionaries containing sample results.
Returns:
list: A filtered list of dictionaries based on the given criteria.
"""
filtered_results = []
for sample in results:
# Check each filter condition; if None, consider it as passed
if (platform is None or sample.get("platform") == platform) and \
(group is None or sample.get("group") == group) and \
(application is None or sample.get("application") == application) and \
(language is None or sample.get("language") == language) and \
(gt_type is None or sample.get("gt_type") == gt_type) and \
(instruction_style is None or sample.get("instruction_style") == instruction_style) and \
(ui_type is None or sample.get("ui_type") == ui_type):
filtered_results.append(sample)
return filtered_results
def make_combinations(results, platform=False, group=None, application=False, language=False, gt_type=False, instruction_style=False, ui_type=False):
"""
Returns a list of combinations of values for attributes where the corresponding parameter is set to True.
"""
# Initialize a dictionary to store unique values for each attribute
unique_values = {
"platform": set(),
"group": set(),
"application": set(),
"language": set(),
"gt_type": set(),
"instruction_style": set(),
"ui_type": set(),
}
# Collect unique values from the results
for sample in results:
if platform:
unique_values["platform"].add(sample.get("platform"))
if group:
unique_values["group"].add(sample.get("group"))
if application:
unique_values["application"].add(sample.get("application"))
if language:
unique_values["language"].add(sample.get("language"))
if gt_type:
unique_values["gt_type"].add(sample.get("gt_type"))
if instruction_style:
unique_values["instruction_style"].add(sample.get("instruction_style"))
if ui_type:
unique_values["ui_type"].add(sample.get("ui_type"))
# Filter out the attributes that are set to False (no need for combinations)
filtered_values = {key: list(value) for key, value in unique_values.items() if value}
if not filtered_values:
return []
# Generate all combinations of the selected attributes using itertools.product
attribute_combinations = list(itertools.product(*filtered_values.values()))
# Convert combinations into dictionaries with corresponding attribute names
combinations = []
for combination in attribute_combinations:
combinations.append(dict(zip(filtered_values.keys(), combination)))
return combinations
def calc_metric_for_result_list(results):
"""Calculates the metrics for a simple result list."""
num_total = len(results)
correct_num = sum(1 for res in results if res["correctness"] == "correct")
wrong_format_num = sum(1 for res in results if res["correctness"] == "wrong_format")
# Calculate text and icon specific metrics using collect_results_to_eval
text_results = collect_results_to_eval(results, ui_type="text")
icon_results = collect_results_to_eval(results, ui_type="icon")
text_correct = sum(1 for res in text_results if res["correctness"] == "correct")
text_total = len(text_results)
icon_correct = sum(1 for res in icon_results if res["correctness"] == "correct")
icon_total = len(icon_results)
metrics = {
"num_correct_action": correct_num,
"num_total": num_total,
"wrong_format_num": wrong_format_num,
"action_acc": correct_num / num_total if num_total > 0 else 0,
"text_acc": text_correct / text_total if text_total > 0 else 0,
"icon_acc": icon_correct / icon_total if icon_total > 0 else 0
}
return metrics
def eval_sample_positive_gt(sample, response):
bbox = sample["bbox"]
bbox = [bbox[0], bbox[1], bbox[2], bbox[3]] # x1, y1, x2, y2
# bbox = [bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]] # x1, y1, w, h
img_size = sample["img_size"]
print("img_size:", img_size)
bbox = [bbox[0] / img_size[0], bbox[1] / img_size[1], bbox[2] / img_size[0], bbox[3] / img_size[1]]
click_point = response["point"] # may be none
print(click_point)
if click_point is None:
return "wrong_format"
# Check if the predicted point falls in the ground truth box
if (bbox[0] <= click_point[0] <= bbox[2]) and (bbox[1] <= click_point[1] <= bbox[3]):
return "correct"
else:
return "wrong"
def eval_sample_negative_gt(sample, response):
if response["result"] == "negative":
return "correct"
elif response["result"] == "positive":
return "wrong"
else: ## response["result"] == wrong_format
return "wrong_format"
def evaluate_fine_grained(results):
# Generate all combinations of platform, instruction_style, and gt_type
combinations = make_combinations(
results,
platform=True,
application=True,
instruction_style=True,
gt_type=True
)
evaluation_result = {}
# Iterate through each combination
for combo in combinations:
platform = combo.get("platform")
application = combo.get("application")
inst_style = combo.get("instruction_style")
gt_type = combo.get("gt_type")
# Filter results for the current combination
filtered_results = collect_results_to_eval(
results=results,
platform=platform,
application=application,
instruction_style=inst_style,
gt_type=gt_type
)
# Calculate metrics using the calc_metric_for_result_list function
metrics = calc_metric_for_result_list(filtered_results)
if metrics['num_total'] == 0:
continue
# Construct a unique key based on the combination
key = f"plat:{platform} app:{application} inst_style:{inst_style} gt_type:{gt_type}"
evaluation_result[key] = metrics
return evaluation_result
def evaluate_seeclick_paper_style(results):
# Generate all combinations of platform, instruction_style, and gt_type
combinations = make_combinations(
results,
platform=True,
instruction_style=True,
gt_type=True
)
evaluation_result = {}
# Iterate through each combination
for combo in combinations:
platform = combo.get("platform")
inst_style = combo.get("instruction_style")
gt_type = combo.get("gt_type")
# Filter results for the current combination
filtered_results = collect_results_to_eval(
results=results,
platform=platform,
instruction_style=inst_style,
gt_type=gt_type
)
# Calculate metrics using the calc_metric_for_result_list function
metrics = calc_metric_for_result_list(filtered_results)
if metrics['num_total'] == 0:
continue
# Construct a unique key based on the combination
key = f"plat:{platform} inst_style:{inst_style} gt_type:{gt_type}"
evaluation_result[key] = metrics
return evaluation_result
def evaluate_leaderboard_detailed_style(results):
# Generate all combinations of platform, instruction_style, and gt_type
combinations = make_combinations(
results,
application=True,
)
evaluation_result = {}
# Iterate through each combination
for combo in combinations:
application = combo.get("application")
# Filter results for the current combination
filtered_results = collect_results_to_eval(
results=results,
application=application,
)
# Calculate metrics using the calc_metric_for_result_list function
metrics = calc_metric_for_result_list(filtered_results)
if metrics['num_total'] == 0:
continue
# Construct a unique key based on the combination
key = f"app:{application}"
evaluation_result[key] = metrics
return evaluation_result
def evaluate_leaderboard_simple_style(results):
# Generate all combinations of platform, instruction_style, and gt_type
combinations = make_combinations(
results,
group=True,
)
evaluation_result = {}
# Iterate through each combination
for combo in combinations:
group = combo.get("group")
# Filter results for the current combination
filtered_results = collect_results_to_eval(
results=results,
group=group,
)
# Calculate metrics using the calc_metric_for_result_list function
metrics = calc_metric_for_result_list(filtered_results)
if metrics['num_total'] == 0:
continue
# Construct a unique key based on the combination
key = f"group:{group}"
evaluation_result[key] = metrics
return evaluation_result
def evaluate_overall(results):
"""
Evaluates the overall metrics for all results without any filtering.
Parameters:
results (list): A list of dictionaries containing sample results.
Returns:
dict: A dictionary containing the overall metrics.
"""
# Calculate metrics for the entire result set
metrics = calc_metric_for_result_list(results)
print(f"Overall metrics: {metrics}")
return metrics
def evaluate(results):
"""Collect results and calculate metrics. You can comment out function calls or add new ones based on your need.
"""
result_report = {
"details": [], # Store detailed information for each sample
"metrics": {}
}
# TODO: comment out function calls based on your need
result_report["metrics"]["fine_grained"] = evaluate_fine_grained(results)
result_report["metrics"]["seeclick_style"] = evaluate_seeclick_paper_style(results)
result_report["metrics"]["leaderboard_simple_style"] = evaluate_leaderboard_simple_style(results)
result_report["metrics"]["leaderboard_detailed_style"] = evaluate_leaderboard_detailed_style(results)
result_report["metrics"]["overall"] = evaluate_overall(results)
# Save detailed results
result_report["details"] = results
return result_report
def main(args):
# model, planner = build_model(args)
model = build_model(args)
print("Load model success")
if args.task == "all":
task_filenames = [
os.path.splitext(f)[0]
for f in os.listdir(args.screenspot_test)
if f.endswith(".json")
]
else:
task_filenames = args.task.split(",")
if args.inst_style == "all":
inst_styles = INSTRUCTION_STYLES
else:
inst_styles = args.inst_style.split(",")
if args.language == "all":
languages = LANGUAGES
else:
languages = args.language.split(",")
if args.gt_type == "all":
gt_types = GT_TYPES
else:
gt_types = args.gt_type.split(",")
tasks_to_run = []
for task_filename in task_filenames:
dataset = task_filename + ".json"
with open(os.path.join(args.screenspot_test, dataset), 'r') as f:
task_data = json.load(f)
# Create the list of tasks to run, one item as an instance. Tasks may be reused.
for inst_style in inst_styles: # Expand tasks based on user configurations
for gt_type in gt_types:
for lang in languages:
for task_instance in task_data:
task_instance = copy.deepcopy(task_instance)
task_instance["task_filename"] = task_filename
task_instance["gt_type"] = gt_type
task_instance["instruction_style"] = inst_style
task_instance["language"] = lang
if lang == "cn":
if inst_style!= 'instruction' or gt_type != 'positive':
# TODO: Translate the data
raise AttributeError("Only positive samples and 'instruction' style are supported for Chinese instructions.")
task_instance["prompt_to_evaluate"] = task_instance["instruction_cn"]
elif lang == "en":
task_instance["prompt_to_evaluate"] = task_instance["instruction"]
tasks_to_run.append(task_instance)
print(f"Num of sample in {task_filename}: {len(task_data)} * {len(inst_styles)} * {len(gt_types)} * {len(languages)} = {len(task_data) * len(inst_styles) * len(gt_types) * len(languages)}")
print(f"Total tasks: {len(tasks_to_run)}")
max_iter = args.max_iter
threshold = args.threshold
results = []
for sample in tqdm(tasks_to_run):
filename = sample["img_filename"]
subset = filename.split('/')[0]
img_path = os.path.join(args.screenspot_imgs, filename)
if task_instance["gt_type"] == "positive":
response = model.ground_only_positive(instruction=sample["prompt_to_evaluate"], image=img_path)
# response = model.ground_only_positive_iterative(instruction=sample["prompt_to_evaluate"], subset=subset, image=img_path)
# response = model.ground_only_positive_iterative_conquer(instruction=sample["prompt_to_evaluate"], subset=subset, image=img_path, max_iter=max_iter, threshold=threshold)
elif task_instance["gt_type"] == "negative":
response = model.ground_allow_negative(instruction=sample["prompt_to_evaluate"], image=img_path)
# print(response)
# 从response中获得归一化坐标
point = response["point"]
iterations = response["iterations"]
print("point:", point)
# 将归一化的坐标恢复到实际像素坐标
if point and 0 <= point[0] <= 1 and 0 <= point[1] <= 1:
img_size = sample["img_size"]
print(f"img_size: {img_size}")
point = [point[0] * img_size[0], point[1] * img_size[1]]
sample_result = {
"img_path": img_path,
"group": sample["group"] if "group" in sample else None,
"platform": sample["platform"],
"application": sample["application"],
"lang": sample["language"],
"instruction_style": sample["instruction_style"],
"prompt_to_evaluate": sample["prompt_to_evaluate"],
"gt_type": sample["gt_type"],
"ui_type": sample["ui_type"],
"task_filename": sample["task_filename"],
"image_size": sample["img_size"],
"pred": point,
"raw_response": response["raw_response"],
"iterations": iterations,
}
if sample["gt_type"] == "positive":
correctness = eval_sample_positive_gt(sample, response)
sample_result.update({
"bbox": sample["bbox"],
})
elif sample["gt_type"] == "negative":
correctness = eval_sample_negative_gt(sample, response)
else:
raise ValueError("Wrong instruction type")
print("correctness:", correctness)
sample_result.update({
"correctness": correctness,
})
results.append(sample_result)
result_report = evaluate(results)
# Save to file
os.makedirs(os.path.dirname(args.log_path), exist_ok=True)
with open(args.log_path, 'w') as f:
json.dump(result_report, f, indent=4)
print(f"Results saved to {args.log_path}")
logging.info("Evaluation of ScreenSpot finished.")
if __name__ == "__main__":
main(parse_args())