jarad2's picture
Add Android Bench sample: tasks and runs (part 14)
89995d3 verified
Raw History Blame Contribute Delete
12.6 kB
# This file is used for whole app migration tasks during their validation phase.
# In order to use it, your dockerfile must contain pip install opencv-python-headless Pillow numpy google-genai pydantic
import os
import sys
import subprocess
import time
import xml.etree.ElementTree as ET
from PIL import Image
import numpy as np
import re
from pydantic import BaseModel, Field
from google import genai
from google.genai import types
import logging
logging.getLogger("google_genai").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
MSE_TOLERANCE = 500
SCREENSHOT_OUT_PATH = "/logs/artifacts/screenshots/"
def run_cmd(cmd):
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode != 0:
print(f"Command failed: {cmd}")
print(f"Stdout: {result.stdout}")
print(f"Stderr: {result.stderr}")
sys.exit(1)
return result.stdout.strip()
def get_aapt2():
android_home = os.environ.get("ANDROID_HOME", "/opt/android-sdk")
res = subprocess.run(
f"find {android_home}/build-tools/ -name aapt2",
shell=True,
capture_output=True,
text=True,
)
if res.returncode == 0 and res.stdout:
return res.stdout.strip().split("\n")[0]
return "aapt2"
def get_apk_launch_info(apk):
aapt = get_aapt2()
dump = run_cmd(f"{aapt} dump badging {apk}")
pkg, act = "", ""
for line in dump.split("\n"):
if "package: name=" in line:
pkg = re.search(r"name='([^']+)'", line).group(1)
if "launchable-activity: name=" in line:
act = re.search(r"name='([^']+)'", line).group(1)
return pkg, act
def get_android_package(root_module="app"):
paths = [
f"/workspace/testbed/{root_module}/build.gradle.kts",
f"/workspace/testbed/{root_module}/build.gradle",
]
for p in paths:
if os.path.exists(p):
with open(p, "r") as f:
content = f.read()
m = re.search(
r'(?:applicationId|namespace)\s*(?:=)?\s*["\']([^"\']+)["\']',
content,
)
if m:
return m.group(1)
return None
def find_node(text=None, clickable=False, top_right=False, exact=False, dump_file=None):
if dump_file and os.path.exists(dump_file):
root = ET.parse(dump_file).getroot()
else:
dump_path = os.path.join(os.getcwd(), "dump.xml")
if os.path.exists(dump_path):
os.remove(dump_path)
subprocess.run(
"adb shell uiautomator dump /data/local/tmp/dump.xml",
shell=True,
capture_output=True,
)
subprocess.run(
f"adb pull /data/local/tmp/dump.xml {dump_path}",
shell=True,
capture_output=True,
)
if not os.path.exists(dump_path):
return None
root = ET.parse(dump_path).getroot()
matches = []
for node in root.iter("node"):
nt = node.get("text", "")
cd = node.get("content-desc", "")
rid = node.get("resource-id", "")
clickable_val = node.get("clickable") == "true"
bounds = node.get("bounds", "")
m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", bounds)
if not m:
continue
left, top, right, bottom = map(int, m.groups())
cx, cy = (left + right) // 2, (top + bottom) // 2
if text:
if exact:
match = (
text.lower() == nt.lower()
or text.lower() == cd.lower()
or text.lower() == rid.lower()
)
else:
match = (
text.lower() in nt.lower()
or text.lower() in cd.lower()
or text.lower() in rid.lower()
)
if match:
if clickable and not clickable_val:
continue
matches.append((cx, cy, right - top))
elif clickable and clickable_val and not text:
matches.append((cx, cy, right - top))
if top_right and matches:
matches.sort(key=lambda x: x[2], reverse=True)
return matches[0][0], matches[0][1]
if matches:
return matches[0][0], matches[0][1]
return None
def click(x, y):
run_cmd(f"adb shell input tap {x} {y}")
time.sleep(2)
def type_text(text):
t = text.replace(" ", "%s")
run_cmd(f"adb shell input text {t}")
time.sleep(1)
def compare_images(img1_path, img2_path):
if not os.path.exists(img1_path) or not os.path.exists(img2_path):
print(f"Missing screenshot to compare: {img1_path} or {img2_path}")
return 99999, False
i1 = Image.open(img1_path)
i2 = Image.open(img2_path)
if i1.size != i2.size:
i2 = i2.resize(i1.size)
diff = np.abs(np.array(i1).astype(int) - np.array(i2).astype(int))
mse = np.mean(diff**2)
print(f"MSE {img1_path} vs {img2_path}: {mse}")
return mse, mse < MSE_TOLERANCE
def calculate_partial_score_on_mse(mean_mse: float, max_mse: float = 3500.0) -> float:
"""Calculates a partial score between 0 and 1 based on mean MSE.
A mean_mse <= MSE_TOLERANCE results in a score of 1.0.
A mean_mse >= max_mse results in a score of 0.0.
"""
if max_mse <= MSE_TOLERANCE:
return 1.0 if mean_mse <= MSE_TOLERANCE else 0.0
return max(0.0, min(1.0, (max_mse - mean_mse) / (max_mse - MSE_TOLERANCE)))
def count_text_nodes(xml_path):
if not os.path.exists(xml_path):
print(f"XML dump missing: {xml_path}")
return 0
try:
root = ET.parse(xml_path).getroot()
count = 0
for node in root.iter("node"):
text = node.get("text", "")
cd = node.get("content-desc", "")
if text.strip() or cd.strip():
count += 1
return count
except Exception as e:
print(f"Error parsing XML {xml_path}: {e}")
return 0
def wait_for_app_launch(pkg, act=None, timeout=30):
print(f"Waiting for app {pkg} to be in foreground...")
start_time = time.time()
while time.time() - start_time < timeout:
pid_res = subprocess.run(
f"adb shell pidof {pkg}", shell=True, capture_output=True, text=True
)
if pid_res.returncode == 0 and pid_res.stdout.strip():
focus_res = subprocess.run(
"adb shell dumpsys window windows",
shell=True,
capture_output=True,
text=True,
)
current_focus = False
for line in focus_res.stdout.split("\n"):
if any(
k in line
for k in [
"mCurrentFocus",
"mFocusedWindow",
"mFocusedApp",
"imeLayeringTarget",
"imeInputTarget",
]
):
if pkg in line:
current_focus = True
break
if not current_focus:
act_res = subprocess.run(
"adb shell dumpsys activity activities | grep mResumedActivity",
shell=True,
capture_output=True,
text=True,
)
if pkg in act_res.stdout:
current_focus = True
if current_focus:
print(f"App {pkg} is seen in foreground.")
time.sleep(2)
return True
time.sleep(1)
print(f"Timed out waiting for app {pkg} to be in foreground.")
return False
def ensure_screenshots(
screenshot_out_path, original_screenshots_dir="/workspace/original_screenshots"
):
import os
import shutil
if (
not os.path.exists(original_screenshots_dir)
or len(os.listdir(original_screenshots_dir)) == 0
):
for fallback in [
"/tests/open/screenshots",
"/workspace/validate/screenshots",
"/workspace/tests/open/screenshots",
]:
if os.path.exists(fallback) and len(os.listdir(fallback)) > 0:
original_screenshots_dir = fallback
break
has_artifacts = (
len(os.listdir(screenshot_out_path)) > 0
if os.path.exists(screenshot_out_path)
else False
)
has_original = (
len(os.listdir(original_screenshots_dir)) > 0
if os.path.exists(original_screenshots_dir)
else False
)
if not has_artifacts:
if has_original:
print(
f"Copying screenshots from {original_screenshots_dir} to {screenshot_out_path}"
)
for f in os.listdir(original_screenshots_dir):
shutil.copy(
os.path.join(original_screenshots_dir, f), screenshot_out_path
)
return False
else:
print("Neither artifacts nor original screenshots exist.")
return True
return False
class ScreenEvaluation(BaseModel):
reasoning: str = Field(
description="Reasoning for whether the Android app screenshot matches the original app screenshot semantically and visually."
)
matches: bool = Field(
description="True if the Android screenshot successfully implements the required UI and matches the original screenshot. False otherwise."
)
def run_llm_judge(
screens,
screenshot_dir,
prefix="original",
model_name="models/gemini-3-flash-preview",
):
gemini_api_key = os.environ.get("GEMINI_API_KEY")
if not gemini_api_key:
print("GEMINI_API_KEY not set. Cannot run LLM judge.")
return 0.0, 99999.0 * len(screens), ["GEMINI_API_KEY not set."]
client = genai.Client(api_key=gemini_api_key)
llm_passes = 0
total_screens = len(screens)
reasoning = []
total_mse_sum = 0.0
for screen in screens:
o_path = os.path.join(screenshot_dir, f"{prefix}_{screen}.png")
a_path = os.path.join(screenshot_dir, f"android_{screen}.png")
mse, _ = compare_images(o_path, a_path)
total_mse_sum += mse
if os.path.exists(o_path) and os.path.exists(a_path):
try:
original_image = Image.open(o_path)
android_image = Image.open(a_path)
except Exception as e:
print(
f" Error opening images for {screen}: {e}. Skipping LLM check for this screen."
)
continue
prompt = f"Compare the original app screenshot (Image 1) and Android app screenshot (Image 2) for the '{screen}' screen. Does the Android app match the original app functionally and semantically? The images don't need to be pixel perfect, but the structural UI elements, text, colors, and general layout should match."
try:
response = client.models.generate_content(
model=model_name,
contents=[original_image, android_image, prompt],
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=ScreenEvaluation,
temperature=0.0,
),
)
eval_res = response.parsed
if eval_res and eval_res.matches:
llm_passes += 1
else:
print(
f"Screen {screen} failed LLM check. Reasoning: {eval_res.reasoning if eval_res else 'None'}"
)
reasoning.append(
f"Screen {screen} failed LLM check: {eval_res.reasoning if eval_res else 'None'}"
)
except Exception as e:
print(f"Error evaluating screen {screen} with LLM: {e}")
reasoning.append(f"Error evaluating screen {screen}: {e}")
else:
print(
f"Missing images for screen {screen}. Skipping LLM check for this screen."
)
reasoning.append(f"Missing images for screen {screen}.")
llm_judge_score = llm_passes / total_screens if total_screens > 0 else 0.0
return llm_judge_score, total_mse_sum, reasoning