TransBench / transferability_gui_benchmark.py
luyuheng's picture
Upload 2 files (#1)
5fbc91c verified
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
# TODO: Address all TODOs and remove all explanatory comments
"""TODO: Add a description here."""
import base64
import csv
import io
import json
import os
from uu import encode
import openpyxl
import datasets
from PIL import Image
_CITATION = """\
@InProceedings{huggingface:dataset,
title = {TransBench: Breaking Barriers for Transferable Graphical User Interface Agents in Dynamic Digital Environments},
author={Lu, Yuheng and Yu, Qian and Wang, Hongru and Liu, Zeming and Su, Wei and Liu, Yanping and Guo, Yuhang and Liang, Maocheng and Wang, Yunhong and Wang, Haifeng},
booktitle={Findings of the Association for Computational Linguistics: ACL 2025},
year={2025}
}
"""
_DESCRIPTION = """\
This dataset is the supplementary dataset for the paper, generated by an automated pipeline with additional manual quality control.
"""
# TODO: Add a link to an official homepage for the dataset here
_HOMEPAGE = "https://github.com/BUAA-IRIP-LLM/TransBench"
# TODO: Add the licence for the dataset here if you can find it
_LICENSE = ""
# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLS = {
"first_domain": "https://huggingface.co/great-new-dataset-first_domain.zip",
"second_domain": "https://huggingface.co/great-new-dataset-second_domain.zip",
}
# TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
class TransferabilityGuiBenchmark(datasets.GeneratorBasedBuilder):
"""This dataset is the supplementary dataset for the paper, generated by an automated pipeline with additional manual quality control.
It is worth noting that due to the use of an automated annotation pipeline to generate tasks, there may be a few errors. Direct use for training that is sensitive to data quality may lead to abnormal phenomena.
"""
VERSION = datasets.Version("1.0.0")
# This is an example of a dataset with multiple configurations.
# If you don't want/need to define several sub-sets in your dataset,
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
# If you need to make complex sub-parts in the datasets with configurable options
# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
# BUILDER_CONFIG_CLASS = MyBuilderConfig
# You will be able to load one or the other configurations in the following list with
# data = datasets.load_dataset('my_dataset', 'first_domain')
# data = datasets.load_dataset('my_dataset', 'second_domain')
BUILDER_CONFIGS = [
datasets.BuilderConfig(name="all", version=VERSION, description="all datapoint of this dataset"),
datasets.BuilderConfig(name="android_low", version=VERSION,
description="use android_low_version to train model"),
datasets.BuilderConfig(name="ios", version=VERSION,
description="use ios to train model"),
datasets.BuilderConfig(name="web", version=VERSION,
description="use ios to train model"),
datasets.BuilderConfig(name="normal", version=VERSION,
description="use ramdom 5000 data split to train model"),
datasets.BuilderConfig(name="app", version=VERSION,
description="use 2/5 apps in top7 app-type to train model"),
]
DEFAULT_CONFIG_NAME = "all" # It's not mandatory to have a default configuration. Just use one if it make sense.
def _info(self):
# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
# "grounding_instruction", "target_bbox", "screenshot_filename", "platform_type", "app_name", "page_name", "app_version", "app_type"
# if self.config.name == "all": # This is the name of the configuration selected in BUILDER_CONFIGS above
# features = datasets.Features(
# {
# "grounding_instruction": datasets.Value("string"),
# "target_bbox": datasets.Array2D(shape=(1, 4), dtype="float32"),
# "app_type": datasets.Value("string"),
# "screenshot_png_base64": datasets.Value("string"),
# "screenshot_path": datasets.Value("string"),
# "platform_type": datasets.Value("string"),
# "app_name": datasets.Value("string"),
# "page_name": datasets.Value("string"),
# "app_version": datasets.Value("string")
# # These are the features of your dataset like images, labels ...
# }
# )
# else: # This is an example to show how to have different features for "first_domain" and "second_domain"
# features = datasets.Features(
# {
# "sentence": datasets.Value("string"),
# "option2": datasets.Value("string"),
# "second_domain_answer": datasets.Value("string")
# # These are the features of your dataset like images, labels ...
# }
# )
features = datasets.Features(
{
"grounding_instruction": datasets.Value("string"),
"target_bbox": datasets.Array2D(shape=(1, 4), dtype="float32"),
"app_type": datasets.Value("string"),
"screenshot_png_base64": datasets.Value("string"),
"screenshot_path": datasets.Value("string"),
"platform_type": datasets.Value("string"),
"app_name": datasets.Value("string"),
"page_name": datasets.Value("string"),
"app_version": datasets.Value("string"),
"app_version_type" : datasets.Value("string"),
# These are the features of your dataset like images, labels ...
}
)
return datasets.DatasetInfo(
# This is the description that will appear on the datasets page.
description=_DESCRIPTION,
# This defines the different columns of the dataset and their types
features=features, # Here we define them above because they are different between the two configurations
# If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
# specify them. They'll be used if as_supervised=True in builder.as_dataset.
# supervised_keys=("sentence", "label"),
# Homepage of the dataset for documentation
homepage=_HOMEPAGE,
# License for the dataset if available
license=_LICENSE,
# Citation for the dataset
citation=_CITATION,
)
def __check_all_screenshots_exists(self, rootpath: str):
with open(os.path.join(rootpath, "processed_grounding_data.json"), 'r', encoding='utf-8') as f:
data = json.load(f)
for case in data:
if not os.path.exists(
os.path.join(rootpath,
os.path.join("screenshots",
os.path.join(str(case['platform_type']),
case['screenshot_filename'])
)
)
):
raise Exception(f"{case['screenshot_filename']} is not exist")
def _split_generators(self, dl_manager):
# TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
# dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
# It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
# By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
# urls = _URLS[self.config.name]
# data_dir = dl_manager.download_and_extract(urls)
url = "TGB.zip"
data_dir = dl_manager.download_and_extract(url)
self.__check_all_screenshots_exists(data_dir)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={
'data_dir': data_dir,
"screenshots_path": os.path.join(data_dir, "screenshots"),
"json_path": os.path.join(data_dir, "processed_grounding_data.json"),
"split": "train",
"appinfo": os.path.join(data_dir, "appinfo.xlsx")
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
# These kwargs will be passed to _generate_examples
gen_kwargs={
'data_dir': data_dir,
"screenshots_path": os.path.join(data_dir, "screenshots"),
"json_path": os.path.join(data_dir, "processed_grounding_data.json"),
"split": "valid",
"appinfo": os.path.join(data_dir, "appinfo.xlsx")
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
# These kwargs will be passed to _generate_examples
gen_kwargs={
'data_dir': data_dir,
"screenshots_path": os.path.join(data_dir, "screenshots"),
"json_path": os.path.join(data_dir, "processed_grounding_data.json"),
"split": "test",
"appinfo": os.path.join(data_dir, "appinfo.xlsx")
},
),
]
def get_app_version_dict(self, datas):
app_to_versions = {}
for case in datas:
appname = case['app_name']
if appname not in app_to_versions:
app_to_versions[appname] = set([])
app_to_versions[appname].add(case['app_version'])
return app_to_versions
def get_lowest_version_set(self, app_to_versions):
app_version_set = set([])
for app in app_to_versions:
_versions = list(app_to_versions[app])
_versions.sort()
if len(_versions) < 2:
continue
app_version_set.add((app, _versions[0]))
return app_version_set
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
def _generate_examples(self, screenshots_path: str, split, json_path, appinfo, data_dir):
# TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
# The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
split_file_map = {"all": "",
"android_low": "split_by_android_low_version.json",
"ios": "split_by_ios.json",
"web": "split_by_web.json",
"normal": "split_normal.json",
"app": "split_app.json"}
split_file = split_file_map[self.config.name]
split_data = {}
if split_file:
with open(os.path.join(data_dir, split_file), encoding="utf-8") as f:
split_data = json.load(f)
book = openpyxl.load_workbook(appinfo)
sheet = book["Sheet2"]
row_idx = 1
prefix_to_apptype = {}
while sheet.cell(row=row_idx, column=1).value:
row_data = []
col_idx = 1
while sheet.cell(row=row_idx, column=col_idx).value:
row_data.append(sheet.cell(row=row_idx, column=col_idx).value)
col_idx += 1
prefix_to_apptype[row_data[0]] = row_data[1]
row_idx += 1
with open(json_path, encoding="utf-8") as f:
datas = json.load(f)
_datas = [t for t in datas if t['platform_type'] == "android"]
_app_version_dict = self.get_app_version_dict(_datas)
app_version_set = self.get_lowest_version_set(_app_version_dict)
for data in datas:
if data['platform_type'] == "android" and (data['app_name'], data['app_version']) in app_version_set:
data['version_type'] = 'low'
else:
data['version_type'] = 'high'
if self.config.name == "all":
# with open(json_path, encoding="utf-8") as f:
key = 0
# datas = json.load(f)
for data in datas:
# Yields examples as (key, example) tuples\
img_path = os.path.join(
os.path.join(screenshots_path, data['platform_type']), str(data['screenshot_filename'])
)
# img = Image.open(
# img_path
# )
# image_data = io.BytesIO()
# img.save(image_data, format='PNG')
# image_data_bytes = image_data.getvalue()
# encoded_png_image = base64.b64encode(image_data_bytes).decode('utf-8')
encoded_image = ""
yield key, {
"grounding_instruction": data["grounding_instruction"],
"target_bbox": [[float(x) for x in data['target_bbox']]],
"app_type": prefix_to_apptype[int(data['screenshot_filename'].split('-')[0])],
"screenshot_png_base64": encoded_image,
"screenshot_path": img_path,
"platform_type": data["platform_type"],
"app_name": data["app_name"],
"page_name": data["page_name"],
"app_version": data["app_version"],
"app_version_type": data["version_type"]
# These are the features of your dataset like images, labels ...
}
key += 1
else:
split_idxs = split_data[split]
split_idxs_set = set(split_idxs)
# assert same len
assert len(split_idxs) == len(split_idxs_set)
# with open(json_path, encoding="utf-8") as f:
key = 0
for current_idx in range(len(datas)):
data = datas[current_idx]
if current_idx not in split_idxs_set:
continue
img_path = os.path.join(
os.path.join(screenshots_path, data['platform_type']), str(data['screenshot_filename'])
)
encoded_image = ""
yield key, {
"grounding_instruction": data["grounding_instruction"],
"target_bbox": [[float(x) for x in data['target_bbox']]],
"app_type": prefix_to_apptype[int(data['screenshot_filename'].split('-')[0])],
"screenshot_png_base64": encoded_image,
"screenshot_path": img_path,
"platform_type": data["platform_type"],
"app_name": data["app_name"],
"page_name": data["page_name"],
"app_version": data["app_version"],
"app_version_type": data["version_type"]
# These are the features of your dataset like images, labels ...
}
key += 1