#!/usr/bin/env python3 """Screenshot every Ind* indicator widget with CSV data loaded. Takes each committed example in examples/.py, injects a ``widget.load_csv(...)`` call into its _build_widgets(), runs it under Xvfb, and screenshots the root window cropped to the example window size -- the same render path as the pythondoc sweep (drive.py run_one) and the visreg harness, so the shots are directly comparable to the template-data goldens in tools/visreg/goldens/. Usage (on hot_newyork, from the repo root): python3 tools/ind_csv_shots.py [--out-dir DIR] [--workers N] [--csv PATH] [Kind ...] Writes .png per widget into the out dir (default /opt/lightgui-docs/pythondoc/work/ind-csv-shots), plus report.json with the ImageMagick RMSE of each CSV shot against its template golden (large = the CSV data really is what is plotted). """ import argparse import json import os import re import signal import subprocess import sys import time REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, REPO) from lightgui.xframe import indicators as ind_mod # noqa: E402 KINDS = ind_mod.indicator_names() DEFAULT_OUT = "/opt/lightgui-docs/pythondoc/work/ind-csv-shots" DEFAULT_CSV = os.path.join(REPO, "tests", "data", "ohlcv_30.csv") def win_size(kind): from lightgui.xframe.palette import PALETTE entry = next(e for e in PALETTE if e.name == kind) return (max(entry.default_w + 32, 220), max(entry.default_h + 32, 120)) def patched_example(kind, csv_path, tmpdir): """Copy the committed example, inject load_csv, return path.""" slug = kind.lower() src = os.path.join(REPO, "examples", slug + ".py") with open(src, encoding="utf-8") as f: code = f.read() lines = [" widget.load_csv(%r)" % csv_path] anchor = " widget = create('%s', " % kind out_lines = [] injected = False for line in code.split("\n"): out_lines.append(line) if not injected and line.startswith(anchor): out_lines.extend(lines) injected = True if not injected: raise RuntimeError("create() line not found in %s" % src) path = os.path.join(tmpdir, slug + "_csv.py") with open(path, "w", encoding="utf-8") as f: f.write("\n".join(out_lines)) return path def wait_for_x(display, timeout=15): sock = "/tmp/.X11-unix/X%d" % display t0 = time.time() while time.time() - t0 < timeout: if os.path.exists(sock): return True time.sleep(0.2) return False def crop_to_window(path, kind): from PIL import Image w, h = win_size(kind) im = Image.open(path) im.crop((0, 0, min(w, im.width), min(h, im.height))).save(path) def rmse_pct(golden, shot): """Normalised RMSE % between two PNGs (ImageMagick compare).""" proc = subprocess.run( ["compare", "-metric", "RMSE", golden, shot, "null:"], capture_output=True, text=True, timeout=60) text = (proc.stderr or proc.stdout).strip() m = re.search(r"\(([\d.]+)\)", text) if not m: return None return round(float(m.group(1)) * 100, 2) def run_one(kind, display, csv_path, outdir, tmpdir): slug = kind.lower() result = {"kind": kind, "name": kind, "slug": slug, "ok": False, "reason": "", "shot": os.path.join(outdir, slug + ".png"), "rmse_vs_template_pct": None} try: ex = patched_example(kind, csv_path, tmpdir) except Exception as exc: # noqa: BLE001 result["reason"] = "patch failed: %r" % (exc,) return result chk = subprocess.run([sys.executable, "-m", "py_compile", ex], capture_output=True, text=True, timeout=60) if chk.returncode != 0: result["reason"] = "py_compile failed: " + chk.stderr.strip()[:300] return result env = dict(os.environ) env["DISPLAY"] = ":%d" % display env["PYTHONPATH"] = REPO + os.pathsep + env.get("PYTHONPATH", "") logp = os.path.join(tmpdir, slug + ".log") png = result["shot"] with open(logp, "w", encoding="utf-8") as logf: proc = subprocess.Popen( [sys.executable, ex], env=env, stdout=logf, stderr=subprocess.STDOUT, start_new_session=True) try: time.sleep(2.5) if proc.poll() is not None: result["reason"] = "exited early rc=%s; log: %s" % ( proc.returncode, open(logp, encoding="utf-8", errors="replace").read()[-400:]) return result shot = subprocess.run( ["import", "-window", "root", png], env=env, capture_output=True, text=True, timeout=30) if shot.returncode != 0 or not os.path.exists(png): result["reason"] = "screenshot failed: " + shot.stderr[:300] return result crop_to_window(png, kind) finally: try: os.killpg(proc.pid, signal.SIGTERM) except ProcessLookupError: pass golden = os.path.join(REPO, "tools", "visreg", "goldens", slug + ".png") if os.path.exists(golden): result["rmse_vs_template_pct"] = rmse_pct(golden, png) result["ok"] = True return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--out-dir", default=DEFAULT_OUT) parser.add_argument("--workers", type=int, default=6) parser.add_argument("--csv", default=DEFAULT_CSV) parser.add_argument("kinds", nargs="*", default=KINDS) args = parser.parse_args() kinds = [k for k in args.kinds if k in KINDS] if not kinds: print("no in-scope kinds requested") return 1 os.makedirs(args.out_dir, exist_ok=True) tmpdir = os.path.join(args.out_dir, ".tmp") os.makedirs(tmpdir, exist_ok=True) displays = [141 + i for i in range(args.workers)] procs = [] for d in displays: procs.append(subprocess.Popen( ["Xvfb", ":%d" % d, "-screen", "0", "1280x900x24"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) try: for d in displays: if not wait_for_x(d): print("Xvfb :%d did not come up" % d) return 1 # Round-robin the kinds over the displays, sequentially per # display (each run needs its own display; 2.5 s settle each). results = [] for i, kind in enumerate(kinds): display = displays[i % len(displays)] print("[%d/%d] %s on :%d" % (i + 1, len(kinds), kind, display), flush=True) results.append(run_one(kind, display, args.csv, args.out_dir, tmpdir)) finally: for p in procs: p.terminate() ok = [r for r in results if r["ok"]] print("shots: ok=%d fail=%d" % (len(ok), len(results) - len(ok))) for r in results: if r["ok"]: print(" OK %-28s RMSE vs template: %s%%" % ( r["kind"], r["rmse_vs_template_pct"] if r["rmse_vs_template_pct"] is not None else "?")) else: print(" FAIL %-28s %s" % (r["kind"], r["reason"])) with open(os.path.join(args.out_dir, "report.json"), "w", encoding="utf-8") as f: json.dump(results, f, indent=1) return 0 if len(ok) == len(results) else 1 if __name__ == "__main__": sys.exit(main())