visual-product-matching / evaluation /ui_validation.py
Ypeng12's picture
Publish verified cache speedup, pixel-equivalence checks, UI results and Chinese evaluation
23cdd96 verified
Raw History Blame Contribute Delete
7.14 kB
"""Verify the deployed evaluated preset, original reset, and responsive output UI."""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
from urllib.parse import urlparse
from huggingface_hub import HfApi
from playwright.sync_api import sync_playwright
BASE = Path(__file__).resolve().parent
URL = 'https://ypeng12-visual-product-matching.hf.space'
REPO = 'Ypeng12/visual-product-matching'
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--expected-sha', required=True)
args = parser.parse_args()
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
output = BASE / 'ui_validation_results' / stamp
output.mkdir(parents=True, exist_ok=True)
report = {'target': URL, 'revision': HfApi().space_info(REPO).sha,
'started_utc': stamp, 'checks': [], 'screenshots': [], 'page_errors': [],
'compare_request_settings': [], 'passed': False}
def check(name, condition, evidence=None):
report['checks'].append({'name': name, 'passed': bool(condition), 'evidence': evidence})
if not condition:
raise AssertionError(f'{name}: {evidence}')
try:
check('expected_revision', report['revision'] == args.expected_sha, report['revision'])
with sync_playwright() as p:
chrome = Path('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
browser = p.chromium.launch(headless=True, executable_path=str(chrome) if chrome.exists() else None)
page = browser.new_page(viewport={'width': 1440, 'height': 1100}, device_scale_factor=1)
page.set_default_timeout(30000)
page.on('pageerror', lambda error: report['page_errors'].append(str(error)))
def record_request(request):
if request.method != 'POST' or '/gradio_api/' not in urlparse(request.url).path:
return
try:
data = request.post_data_json.get('data', [])
if len(data) == 9:
report['compare_request_settings'].append(data[2:])
except Exception:
pass
page.on('request', record_request)
page.goto(URL, wait_until='domcontentloaded', timeout=60000)
page.get_by_text('Five-dimensional algorithm profile', exact=True).wait_for(timeout=90000)
page.get_by_text('Tune the comparison', exact=True).click()
ranges = "Array.from(document.querySelectorAll('input[type=range]')).map(el=>Number(el.value))"
originals = [.75, 40, 75, .30, .30, .20, .20]
evaluated = [.75, 40, 30, .30, .50, .10, .10]
check('original_defaults', page.evaluate(ranges) == originals, page.evaluate(ranges))
page.get_by_role('button', name='Apply evaluated SOP settings', exact=True).click()
page.wait_for_function(f'expected => JSON.stringify({ranges}) === JSON.stringify(expected)', arg=evaluated)
check('evaluated_controls_threshold_weights', page.evaluate(ranges) == evaluated, page.evaluate(ranges))
page.get_by_role('button', name='Compare images →', exact=True).click()
page.wait_for_function("document.querySelector('.result-details')?.innerText.includes('Threshold 30')", timeout=90000)
page.locator('#algorithm-radar .main-svg').first.wait_for(state='visible', timeout=90000)
check('evaluated_result_uses_threshold_30', 'Threshold 30' in page.locator('.result-details').inner_text())
check('evaluated_api_settings', bool(report['compare_request_settings']) and report['compare_request_settings'][-1] == [.75, 30, 40, .30, .50, .10, .10], report['compare_request_settings'])
page.screenshot(path=str(output / 'desktop-evaluated-preset.png'), full_page=True)
report['screenshots'].append(str((output / 'desktop-evaluated-preset.png').relative_to(BASE)))
page.get_by_role('button', name='Reset original settings', exact=True).click()
page.wait_for_function(f'expected => JSON.stringify({ranges}) === JSON.stringify(expected)', arg=originals)
check('original_reset_threshold_weights', page.evaluate(ranges) == originals, page.evaluate(ranges))
page.get_by_role('button', name='Compare images →', exact=True).click()
page.wait_for_function("document.querySelector('.result-details')?.innerText.includes('Threshold 75')", timeout=90000)
check('reset_result_uses_threshold_75', 'Threshold 75' in page.locator('.result-details').inner_text())
check('reset_api_settings', report['compare_request_settings'][-1] == [.75, 75, 40, .30, .30, .20, .20], report['compare_request_settings'][-1])
colors = page.locator('#algorithm-radar .js-plotly-plot').evaluate('(plot) => ({line:plot.data[0].line.color,fill:plot.data[0].fillcolor})')
check('radar_colors_preserved', colors == {'line': '#0d9488', 'fill': 'rgba(13, 148, 136, 0.18)'}, colors)
check('heatmap_color_legend_preserved', page.get_by_text('Red = higher similarity · blue = lower similarity', exact=True).count() >= 1)
for width, name in [(1440, 'desktop-reset'), (390, 'mobile-390-reset'), (360, 'mobile-360-reset')]:
page.set_viewport_size({'width': width, 'height': 1100})
page.wait_for_timeout(300)
dimensions = page.evaluate('({client:document.documentElement.clientWidth,scroll:document.documentElement.scrollWidth})')
check(f'no_document_overflow_{width}', dimensions['scroll'] <= dimensions['client'], dimensions)
check(f'radar_visible_{width}', page.locator('#algorithm-radar .main-svg').first.is_visible())
if width == 1440:
left = page.get_by_text('SIFT keypoint matches', exact=True).bounding_box()
right = page.get_by_text('SSIM structural colormap', exact=True).bounding_box()
check('keypoint_heatmap_side_by_side', abs(left['y'] - right['y']) < 3, {'left': left, 'right': right})
page.screenshot(path=str(output / f'{name}.png'), full_page=True)
report['screenshots'].append(str((output / f'{name}.png').relative_to(BASE)))
check('no_javascript_exceptions', not report['page_errors'], report['page_errors'])
check('revision_unchanged', HfApi().space_info(REPO).sha == report['revision'])
report['passed'] = True
browser.close()
except Exception as exc:
report['error'] = f'{type(exc).__name__}: {exc}'
raise
finally:
report['finished_utc'] = datetime.now(timezone.utc).isoformat()
(output / 'report.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps({'output_relative_to_vision_evaluation': str(output.relative_to(BASE)), 'passed': report['passed'], 'checks': len(report['checks']), 'error': report.get('error')}), flush=True)
if __name__ == '__main__':
main()