File size: 12,554 Bytes
89995d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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