#!/usr/bin/env python3 """Outline maps for the wallpaper change (wallpaper/shaders/colonies.frag, mode 1). When a new wallpaper has a clear subject, the change draws the subject's outline, fills it in from that outline, and then grows the rest of the picture out of it. This helper finds the subject (BiRefNet, through onnxruntime) and bakes two RGB maps in the image's own space; the shader only reads them. field.png R depth inside the subject: 0 on its outline, 1 at its deepest G signed distance to the outline, +-SD_RANGE map px, 0.5 on it line.png R position along the outline (two pens from the top), 0 = no line G/B order in which the outside arrives, 16 bits, smooth Maps are cached per image (path, size and mtime). Commands, each printing one JSON object: choose IMG {"kind": "outline", "field", "line"} when cached maps exist, {"kind": "colonies", "pending": true} when IMG is not processed yet, {"kind": "colonies"} when it has no subject. Uses only the standard library, so it answers at once. status IMG... {IMG: "outline" | "colonies" | "pending"}; standard library only. warm IMG... processes every image not cached yet; one warm at a time. outline IMG [--force] Requires GLASSMXRPH_WALLFX_MODEL (BiRefNet ONNX) and numpy, opencv, pillow and onnxruntime in the interpreter running this file. """ import hashlib import json import os import sys CACHE = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "glassMxrph", "wallfx") MODEL = os.environ.get("GLASSMXRPH_WALLFX_MODEL", "") MAP_MAX = 1280 # long side of the maps; the shader interpolates them SD_RANGE = 16.0 # signed distance kept within +-16 map px of the outline EXTS = (".jpg", ".jpeg", ".png", ".webp", ".bmp") def key(img): st = os.stat(img) return hashlib.sha1(f"{os.path.realpath(img)}|{st.st_size}|{int(st.st_mtime)}".encode()).hexdigest()[:16] def cached(img): """(field, line) if IMG has cached maps, False if it has no subject, None if unprocessed.""" base = os.path.join(CACHE, key(img)) try: with open(base + ".json") as f: meta = json.load(f) except (OSError, ValueError): return None if not meta.get("ok"): return False field, line = base + "-field.png", base + "-line.png" return (field, line) if os.path.exists(field) and os.path.exists(line) else None # ───────────────────────────── subject mask ───────────────────────────── _session = None def mask_of(im): """BiRefNet's foreground probability for a PIL RGB image, as float32 0..1.""" global _session import numpy as np import onnxruntime as ort from PIL import Image if _session is None: opts = ort.SessionOptions() opts.intra_op_num_threads = max(1, (os.cpu_count() or 2) // 2) # leave the desktop room _session = ort.InferenceSession(MODEL, opts, providers=["CPUExecutionProvider"]) x = np.asarray(im.resize((1024, 1024), Image.Resampling.LANCZOS), np.float32) x /= max(float(x.max()), 1e-6) x = (x - np.array([0.485, 0.456, 0.406], np.float32)) / np.array([0.229, 0.224, 0.225], np.float32) x = x.transpose(2, 0, 1)[None].astype(np.float32) out = _session.run(None, {_session.get_inputs()[0].name: x})[0][0, 0] p = 1.0 / (1.0 + np.exp(-out)) p = (p - p.min()) / max(float(p.max() - p.min()), 1e-6) m = Image.fromarray((p * 255).astype(np.uint8)).resize(im.size, Image.Resampling.LANCZOS) return np.asarray(m, np.float32) / 255.0 # ───────────────────────────── maps ───────────────────────────── def value_noise(rng, w, h, scale): import numpy as np lat = rng.random((int(h / scale) + 3, int(w / scale) + 3)) xs, ys = np.arange(w) / scale, np.arange(h) / scale ix, iy = xs.astype(int), ys.astype(int) fx, fy = xs - ix, ys - iy fx, fy = fx * fx * (3 - 2 * fx), fy * fy * (3 - 2 * fy) top = lat[iy][:, ix] * (1 - fx) + lat[iy][:, ix + 1] * fx bot = lat[iy + 1][:, ix] * (1 - fx) + lat[iy + 1][:, ix + 1] * fx return top * (1 - fy)[:, None] + bot * fy[:, None] def write_png(path, rgb): """Atomic: the shell may be reading the previous maps while these are written. RGB without alpha, so Qt does not premultiply the numbers.""" from PIL import Image tmp = f"{path}.{os.getpid()}.tmp.png" Image.fromarray(rgb, "RGB").save(tmp) os.replace(tmp, path) def build(img, force=False): """Bake IMG's maps; returns (field, line) or None when it has no clear subject.""" import fcntl os.makedirs(CACHE, exist_ok=True) base = os.path.join(CACHE, key(img)) with open(base + ".lock", "w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) # one bake per image at a time if not force: hit = cached(img) if hit is not None: return hit or None import cv2 import numpy as np from PIL import Image im = Image.open(img).convert("RGB") im.thumbnail((MAP_MAX, MAP_MAX)) mask_path = base + "-mask.png" # the slow part; kept across --force if os.path.exists(mask_path): m = np.asarray(Image.open(mask_path).convert("L").resize(im.size), np.float32) / 255.0 else: m = mask_of(im) Image.fromarray((m * 255).astype(np.uint8)).save(mask_path) h, w = m.shape b = (m > 0.5).astype(np.uint8) # Specks of foreground would be outlined as dots all over the screen. n, lab, stats, _ = cv2.connectedComponentsWithStats(b, connectivity=8) keep = np.zeros(n, bool) keep[1:] = stats[1:, cv2.CC_STAT_AREA] >= 0.002 * w * h b = keep[lab].astype(np.uint8) cover = float(b.mean()) unsure = float(((m > 0.1) & (m < 0.9)).mean()) # A subject takes part of the picture, not nearly all of it nor a crumb, # and the model is sure where it ends. ok = 0.008 <= cover <= 0.72 and unsure <= 0.06 meta = {"img": img, "ok": ok, "cover": round(cover, 3), "unsure": round(unsure, 3)} if ok: din = cv2.distanceTransform(b, cv2.DIST_L2, 5) dout = cv2.distanceTransform(1 - b, cv2.DIST_L2, 5) sd = dout - din # > 0 outside inner = np.clip(din / max(float(np.percentile(din[b > 0], 99)), 1.0), 0, 1) # Outside order: distance from the subject, bent by noise so the front # is not a plain offset of the silhouette, then ranked by area. rng = np.random.default_rng(int(key(img)[:8], 16)) noise = 0.6 * value_noise(rng, w, h, w / 9.0) + 0.4 * value_noise(rng, w, h, w / 28.0) warped = dout * (0.75 + 0.5 * noise) + noise * 0.08 * max(w, h) outside = b == 0 order = np.zeros((h, w), np.float32) vals = warped[outside] rank = np.empty(vals.size) rank[np.argsort(vals, kind="stable")] = np.arange(vals.size) order[outside] = rank / max(vals.size - 1, 1) order = cv2.GaussianBlur(order, (0, 0), 4.0) # Along the outline: each contour starts at its top point, drawn by two # pens going round in opposite directions that meet on the far side. edge = np.zeros((h, w), np.uint8) param = np.zeros((h, w), np.float32) contours, _ = cv2.findContours(b, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) for c in contours: if len(c) < 40 or abs(cv2.contourArea(c)) < 0.0008 * w * h: continue # tiny holes get no line c = c[:, 0, :] seg = np.sqrt((np.diff(c, axis=0, append=c[:1]) ** 2).sum(1)) s = np.concatenate([[0], np.cumsum(seg)[:-1]]) total = s[-1] + seg[-1] s = (s - s[np.argmin(c[:, 1])]) % total p = np.minimum(s, total - s) / (total / 2) # Where the subject runs off the picture its contour follows the # border: that is not an outline. p[(c[:, 0] <= 1) | (c[:, 0] >= w - 2) | (c[:, 1] <= 1) | (c[:, 1] >= h - 2)] = -1 edge[c[:, 1], c[:, 0]] = 1 param[c[:, 1], c[:, 0]] = p line = np.zeros((h, w), np.uint8) if edge.any(): _, labels = cv2.distanceTransformWithLabels(1 - edge, cv2.DIST_L2, 5, labelType=cv2.DIST_LABEL_PIXEL) ys, xs = np.nonzero(edge) table = np.concatenate([[0], param[ys, xs]]) near = np.abs(sd) < SD_RANGE v = table[labels[near]] line[near] = np.where(v < 0, 0, np.clip(v * 255, 1, 255)).astype(np.uint8) field = np.zeros((h, w, 3), np.uint8) field[..., 0] = np.clip(inner * 255, 0, 255) field[..., 1] = np.clip((sd + SD_RANGE) / (2 * SD_RANGE) * 255, 0, 255) q = np.clip(order * 65535.0 + 0.5, 0, 65535).astype(np.uint16) lines = np.zeros((h, w, 3), np.uint8) lines[..., 0] = line lines[..., 1] = q >> 8 lines[..., 2] = q & 255 write_png(base + "-field.png", field) write_png(base + "-line.png", lines) tmp = f"{base}.json.{os.getpid()}.tmp" with open(tmp, "w") as f: json.dump(meta, f) os.replace(tmp, base + ".json") return (base + "-field.png", base + "-line.png") if ok else None def warm(paths): import fcntl os.makedirs(CACHE, exist_ok=True) with open(os.path.join(CACHE, ".warm.lock"), "w") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: return # another warm is already on it for path in paths: if not path.lower().endswith(EXTS) or not os.path.isfile(path): continue try: if cached(path) is None: r = build(path) print(("outline " if r else "colonies ") + path, file=sys.stderr, flush=True) except Exception as e: # one bad file must not stop the rest print(f"error {path}: {e}", file=sys.stderr, flush=True) def main(argv): if len(argv) < 2 or argv[0] not in ("choose", "status", "warm", "outline"): print(__doc__, file=sys.stderr) return 2 cmd, rest = argv[0], argv[1:] if cmd == "choose": try: hit = cached(rest[0]) except OSError: hit = False if hit: out = {"kind": "outline", "field": hit[0], "line": hit[1]} else: out = {"kind": "colonies", "pending": hit is None and bool(MODEL)} elif cmd == "status": out = {} for path in rest: try: hit = cached(path) except OSError: continue out[path] = "outline" if hit else ("pending" if hit is None else "colonies") elif not MODEL or not os.path.exists(MODEL): print("wallfx: GLASSMXRPH_WALLFX_MODEL is not set or missing", file=sys.stderr) return 1 elif cmd == "warm": warm(rest) return 0 else: r = build(rest[0], force="--force" in rest) out = {"kind": "outline", "field": r[0], "line": r[1]} if r else {"kind": "colonies"} print(json.dumps(out)) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))