minus-ad-detectors / examples /make_composite.py
cebeuq's picture
Minus ad-detection models: tier 1 + minus-xs-v3, minus-s-v1, minus-m-v1 (minus-l-v1 configs)
76a6384 verified
Raw History Blame Contribute Delete
7.54 kB
"""Build the exact model inputs for one page element (Pillow only).
From a viewport screenshot, the element's box (CSS px) and the page URL or domain this writes:
- the composite (what minus-s / minus-m / minus-l read): a dark "CROP" header over the element crop
(fit into 896 x 640), then a dark "CONTEXT - page: <domain> - element outlined in magenta" header over
the page around the element (box grown by max(160, w/2) CSS px left/right and max(100, h/2) up/down,
clipped to the viewport, element outlined ~3 px #ff00ff, fit into 896 x 448). Grey background, 8 px margins.
- optionally the bare crop (what minus-xs reads): the box's pixels, longest side <= 1024.
The models then see the image scaled down to <= 200,000 px (`fit_pixels`, BICUBIC); score.py does that step,
or pass --fit to save the fitted image.
Pixels are byte-identical to the shipped engine with Pillow 13.0 (the header text uses Pillow's built-in font,
so other Pillow versions can differ by a few text pixels).
Usage:
python make_composite.py shot.jpg --box X Y W H --url https://www.example.com/page -o composite.png
python make_composite.py shot.jpg --box X Y W H --domain example.com --viewport 1280 900 \
-o composite.png --bare-out bare.png
"""
from __future__ import annotations
import argparse
from urllib.parse import urlsplit
from PIL import Image, ImageDraw, ImageFont
VIEW_W, VIEW_H = 1280, 900 # default viewport (CSS px); the screenshot may be at any device scale
CROP_MAX_SIDE = 1024 # bare crop: longest side
CROP_PANEL = (896, 640)
CTX_PANEL = (896, 448)
CTX_MIN_X, CTX_MIN_Y = 160, 100
MARGIN, HEADER = 8, 30
OUTLINE = (255, 0, 255)
BG, HEADER_BG, HEADER_FG = (128, 128, 128), (40, 40, 40), (255, 255, 255)
MAX_PIXELS = 200_000 # the models' image budget
def clip_box(x, y, w, h, view=(VIEW_W, VIEW_H)):
"""{x, y, w, h} CSS px -> clipped (x0, y0, x1, y1), or None when nothing is inside the viewport."""
c = (max(0.0, float(x)), max(0.0, float(y)), min(float(view[0]), float(x) + float(w)),
min(float(view[1]), float(y) + float(h)))
return c if c[2] - c[0] >= 1 and c[3] - c[1] >= 1 else None
def bare_crop(shot, c, view=(VIEW_W, VIEW_H)):
"""The element's pixels, longest side <= 1024."""
s = shot.width / view[0]
cr = shot.crop((round(c[0] * s), round(c[1] * s), round(c[2] * s), round(c[3] * s)))
f = min(1.0, CROP_MAX_SIDE / max(cr.size))
if f < 1:
cr = cr.resize((max(1, round(cr.width * f)), max(1, round(cr.height * f))), Image.Resampling.LANCZOS)
return cr
def _fit(im, box):
f = min(box[0] / im.width, box[1] / im.height, 1.0)
if f < 1:
im = im.resize((max(1, round(im.width * f)), max(1, round(im.height * f))), Image.Resampling.LANCZOS)
return im
def context_region(c, view=(VIEW_W, VIEW_H)):
"""(x0, y0, x1, y1) CSS px of the context panel around clipped box c."""
w, h = c[2] - c[0], c[3] - c[1]
mx, my = max(CTX_MIN_X, w / 2), max(CTX_MIN_Y, h / 2)
return (max(0, int(round(c[0] - mx))), max(0, int(round(c[1] - my))),
min(view[0], int(round(c[2] + mx))), min(view[1], int(round(c[3] + my))))
def context_strip(shot, c, view=(VIEW_W, VIEW_H)):
"""The page around the element with the element outlined in magenta, fit into 896 x 448."""
s = shot.width / view[0]
r = context_region(c, view)
im = shot.crop((round(r[0] * s), round(r[1] * s), round(r[2] * s), round(r[3] * s))).convert("RGB")
f = min(CTX_PANEL[0] / im.width, CTX_PANEL[1] / im.height, 1.0)
lw = max(2, round(3 / f))
d = ImageDraw.Draw(im)
bx = ((c[0] - r[0]) * s, (c[1] - r[1]) * s, (c[2] - r[0]) * s - 1, (c[3] - r[1]) * s - 1)
d.rectangle(bx, outline=OUTLINE, width=lw)
return _fit(im, CTX_PANEL), r
def composite(bare, ctx, domain):
"""Crop panel over context panel, with headers (the context header names the page domain)."""
crop = _fit(bare.convert("RGB"), CROP_PANEL)
W = max(crop.width, ctx.width, 420) + 2 * MARGIN
H = HEADER + crop.height + MARGIN + HEADER + ctx.height + MARGIN
canvas = Image.new("RGB", (W, H), BG)
d = ImageDraw.Draw(canvas)
font = ImageFont.load_default(size=18)
d.rectangle([0, 0, W - 1, HEADER - 1], fill=HEADER_BG)
d.text((MARGIN, 5), "CROP", fill=HEADER_FG, font=font)
canvas.paste(crop, (MARGIN, HEADER))
y = HEADER + crop.height + MARGIN
d.rectangle([0, y, W - 1, y + HEADER - 1], fill=HEADER_BG)
d.text((MARGIN, y + 5), f"CONTEXT - page: {domain[:60]} - element outlined in magenta", fill=HEADER_FG, font=font)
canvas.paste(ctx, (MARGIN, y + HEADER))
return canvas
def fit_pixels(image, max_pixels=MAX_PIXELS):
"""Downscale (aspect kept) so width * height <= max_pixels; never upscales."""
if not max_pixels:
return image
w, h = image.size
if w * h <= max_pixels:
return image
s = (max_pixels / float(w * h)) ** 0.5
return image.resize((max(1, int(w * s)), max(1, int(h * s))), Image.BICUBIC)
# Second-level labels under a two-letter country code that make a three-label registrable domain (co.uk, ...).
_SLD = frozenset(("ac co com edu gob gov go gv in ltd me mil ne net nhs nic nom or org plc res sch web").split())
def page_domain(url):
"""The registrable domain of the page URL as the composite prints it ("cnet.com", "bbc.co.uk")."""
try:
host = (urlsplit(str(url or "")).hostname or "").rstrip(".").lower()
except ValueError:
host = ""
if not host:
return "unknown"
if host.replace(".", "").isdigit() or ":" in host:
return host
labels = host.split(".")
if len(labels) >= 3 and len(labels[-1]) == 2 and labels[-2] in _SLD:
return ".".join(labels[-3:])
return ".".join(labels[-2:])
def build(shot, box, domain, view=(VIEW_W, VIEW_H)):
"""-> (composite, bare crop) for box = (x, y, w, h) CSS px on a screenshot of a `view` CSS-px viewport."""
c = clip_box(*box, view=view)
if c is None:
raise ValueError("box is outside the viewport")
bare = bare_crop(shot, c, view)
strip, _ = context_strip(shot, c, view)
return composite(bare, strip, domain), bare.convert("RGB")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("screenshot")
ap.add_argument("--box", nargs=4, type=float, required=True, metavar=("X", "Y", "W", "H"),
help="element box in CSS px, relative to the viewport")
g = ap.add_mutually_exclusive_group(required=True)
g.add_argument("--url", help="page URL (its registrable domain is printed in the composite)")
g.add_argument("--domain", help="page domain as printed, e.g. example.com")
ap.add_argument("--viewport", nargs=2, type=int, default=[VIEW_W, VIEW_H], metavar=("W", "H"),
help="viewport size in CSS px (default 1280 900)")
ap.add_argument("-o", "--out", required=True, help="composite PNG")
ap.add_argument("--bare-out", help="also save the bare crop (minus-xs input)")
ap.add_argument("--fit", action="store_true", help="save the images already fitted to <= 200k px")
a = ap.parse_args()
shot = Image.open(a.screenshot).convert("RGB")
comp, bare = build(shot, a.box, a.domain or page_domain(a.url), tuple(a.viewport))
(fit_pixels(comp) if a.fit else comp).save(a.out)
if a.bare_out:
(fit_pixels(bare) if a.fit else bare).save(a.bare_out)
if __name__ == "__main__":
main()