Cotton code
441 lines · 20.1 KB · PythonRaw
#!/usr/bin/env python3"""A synthetic photo library for Cotton Albums, with its truth beside it.    python3 scripts/albums-library.py --out <dir> [--photos 5000] [--videos 30] [--faces <hyperface dir>] [--seed 7]    python3 scripts/albums-library.py --load <dir> --sim <udid>     # into a simulator's Photos, 200 at a timeNothing here is anyone's photo (assets/design/albums/DECISIONS.md "Test plan": synthetic only). Every picture is drawnfrom a seed: a scene of shapes and texture per moment, and each shot of a moment the same scene a little moved, litand grained, so a moment's shots look nearly the same and two moments do not. Into it go:  - moments of one shot, and bursts of 2 to 25 shots one or two seconds apart (the "keep these 5" case);  - blurred shots (15%) and dark shots (6%) inside moments, so the best shot is not always the first;  - people: synthetic faces from HyperFace (Zenodo 15087238, CC BY-SA 4.0: 10,000 made-up identities, 64 pictures    each, none a real person), each person drawn on a power law so a few appear often, at 24 to 360 px across,    one picture of the identity per shot;  - screenshots (PNG at an iPhone's screen size, EXIF UserComment "Screenshot"), receipts and documents (a page    of text in perspective on a table), WhatsApp copies of camera shots (1600 px, re-encoded, no EXIF, WhatsApp's    file names), and videos made by ffmpeg, a few long;  - dates over ten years with EXIF DateTimeOriginal, and places on three continents in EXIF GPS.`truth.jsonl` says, per file, what it is: its moment and shot, blurred or dark, the people in it with their boxes,the original of a WhatsApp copy. The Mac scores the phone's export (`albums-export.jsonl`) against it."""import argparseimport jsonimport mathimport osimport randomimport subprocessimport sysfrom datetime import datetime, timedelta, timezonefrom multiprocessing import Poolfrom pathlib import Pathimport numpy as npfrom PIL import Image, ImageDraw, ImageFilter, ImageFontROOT = Path(__file__).resolve().parent.parentFONT = ROOT / "assets/fonts/look/InstrumentSans.ttf"PLACES = [  # name, lat, lon, weight, seconds east of UTC: home first    ("Bandra", 19.0596, 72.8295, 0.55, 19800), ("Goa", 15.4909, 73.8278, 0.1, 19800),    ("Lisbon", 38.7223, -9.1393, 0.08, 0), ("Tokyo", 35.6762, 139.6503, 0.07, 32400),    ("Nairobi", -1.2921, 36.8219, 0.05, 10800), ("Pune", 18.5204, 73.8567, 0.1, 19800),    ("Kochi", 9.9312, 76.2673, 0.05, 19800),]HOME = PLACES[0]TRIP_PLACES = [p for p in PLACES if p[0] not in ("Bandra", "Pune")]PUNE = PLACES[5]def timeline(start, end, rng):    """Where he is, as spans (from, to, place, trip): home in Bandra; about one weekend in six at his parents' in Pune    (a Place: many photos on many days); about three trips a year of 3–12 days. Truth names each trip."""    spans = []    t = start    trip = 0    while t < end:        gap = timedelta(days=rng.uniform(70, 150))        t += gap        if t >= end:            break        days = rng.randint(3, 12)        place = rng.choice(TRIP_PLACES)        trip += 1        spans.append((t, t + timedelta(days=days), place, f"trip-{trip}"))        t += timedelta(days=days)    # Weekends in Pune (Saturday morning to Sunday evening), never inside a trip.    day = start    while day < end:        if day.weekday() == 5 and rng.random() < 1 / 6:            a, b = day.replace(hour=4), day.replace(hour=4) + timedelta(hours=38)            if not any(x < b and a < y for x, y, _, _ in spans):                spans.append((a, b, PUNE, None))        day += timedelta(days=1)    spans.sort(key=lambda s: s[0])    return spansdef where(spans, t):    for a, b, place, trip in spans:        if a <= t < b:            return place, trip    return HOME, NoneCAMERA = (2016, 1512)LARGE = (4032, 3024)SCREEN = (1179, 2556)def font(size):    try:        return ImageFont.truetype(str(FONT), size)    except OSError:        return ImageFont.load_default()# ---------------------------------------------------------------- the plandef plan(photos, seed, identities):    """The library as a list of jobs, one per file, oldest first, each with its truth."""    rng = random.Random(seed)    start = datetime(2016, 11, 1, tzinfo=timezone.utc)    span = (datetime(2026, 11, 20, tzinfo=timezone.utc) - start).total_seconds()    # People on a power law: a few appear in many photos.    weights = [1 / (i + 1) ** 1.1 for i in range(len(identities))]    jobs = []    moment = 0    end = start + timedelta(seconds=span)    spans = timeline(start, end, rng)    # Away, he takes more photos: a quarter of the moments fall on trips and weekends away.    away = [(a, b) for a, b, _, _ in spans]    away_seconds = sum((b - a).total_seconds() for a, b in away)    times = []    for _ in range(photos):        if away and rng.random() < 0.25:            x = rng.random() * away_seconds            for a, b in away:                d = (b - a).total_seconds()                if x < d:                    times.append((a - start).total_seconds() + x)                    break                x -= d        else:            times.append(rng.random() * span)    times.sort()    i = 0    while len(jobs) < photos:        # A moment's time follows how full the library is, not how many moments came before: a burst spends many        # photos on one time, and indexing by moment ran the ten years out half way (the library ended in 2020).        i = max(i + 1, int(len(jobs) / photos * len(times)))        t = start + timedelta(seconds=times[min(i, len(times) - 1)])        here, trip = where(spans, t)        place = (*here[:3], here[4], trip)        r = rng.random()        moment += 1        if r < 0.07:            jobs.append(dict(kind="screenshot", moment=moment, shot=0, when=t.isoformat(), seed=rng.randrange(1 << 30)))            continue        if r < 0.1:            jobs.append(dict(kind="document", moment=moment, shot=0, when=t.isoformat(), seed=rng.randrange(1 << 30),                             place=place))            continue        shots = 1 if rng.random() < 0.6 else min(25, max(2, int(rng.paretovariate(1.2) * 2)))        people = []        if identities and rng.random() < 0.35:            people = rng.choices(range(len(identities)), weights=weights, k=rng.choice([1, 1, 1, 2, 2, 3, 4, 5]))            people = sorted(set(people))        scene = rng.randrange(1 << 30)        large = rng.random() < 0.12        for shot in range(shots):            when = t + timedelta(seconds=shot * rng.choice([1, 1, 2]))            jobs.append(dict(                kind="camera", moment=moment, shot=shot, when=when.isoformat(), scene=scene, seed=rng.randrange(1 << 30),                blurred=rng.random() < 0.15, dark=rng.random() < 0.06, large=large, place=place,                people=[dict(identity=identities[p], picture=rng.randrange(64)) for p in people]))            if len(jobs) >= photos:                break    # WhatsApp copies of 3% of camera shots, saved a few days later.    camera = [j for j in jobs if j["kind"] == "camera"]    for original in rng.sample(camera, k=max(1, len(camera) * 3 // 100)):        when = datetime.fromisoformat(original["when"]) + timedelta(days=rng.randrange(1, 20), seconds=rng.randrange(86400))        jobs.append(dict(original, kind="whatsapp", when=when.isoformat(), copy_of=None))    jobs.sort(key=lambda j: j["when"])    for n, j in enumerate(jobs):        stamp = datetime.fromisoformat(j["when"]).strftime("%Y%m%d_%H%M%S")        if j["kind"] == "screenshot":            j["file"] = f"Screenshot_{stamp}_{n:05d}.png"        elif j["kind"] == "whatsapp":            j["file"] = f"IMG-{stamp[:8]}-WA{n % 10000:04d}.jpg"        else:            j["file"] = f"IMG_{stamp}_{n:05d}.jpg"    for j in jobs:        if j["kind"] == "whatsapp":            j["copy_of"] = next(o["file"] for o in jobs if o["kind"] == "camera" and o["moment"] == j["moment"] and o["shot"] == j["shot"])    return jobs# ---------------------------------------------------------------- drawingdef scene_picture(scene, size, shot_seed, shift):    """The moment's scene: a sky and ground gradient, shapes and texture, all from `scene`; then moved and grained    by the shot."""    rng = np.random.default_rng(scene)    w, h = 800, 600    sky = rng.integers(40, 230, 3)    ground = rng.integers(20, 200, 3)    horizon = rng.uniform(0.3, 0.7)    y = np.linspace(0, 1, h)[:, None]    mix = np.clip((y - horizon) * 6 + 0.5, 0, 1)    base = (sky[None, None, :] * (1 - mix[..., None]) + ground[None, None, :] * mix[..., None]) * np.ones((h, w, 1))    # Texture: low-frequency noise, the same for every shot of the moment.    tex = rng.normal(0, 1, (h // 20 + 1, w // 20 + 1, 3))    tex = np.array(Image.fromarray(((tex - tex.min()) / (np.ptp(tex) + 1e-6) * 255).astype(np.uint8)).resize((w, h), Image.BICUBIC), float)    base = np.clip(base * 0.75 + tex * 0.25, 0, 255).astype(np.uint8)    img = Image.fromarray(base)    d = ImageDraw.Draw(img)    for _ in range(int(rng.integers(6, 18))):        c = tuple(int(v) for v in rng.integers(0, 255, 3))        x0, y0 = int(rng.integers(-100, w)), int(rng.integers(-100, h))        x1, y1 = x0 + int(rng.integers(30, 400)), y0 + int(rng.integers(30, 300))        kind = int(rng.integers(0, 3))        if kind == 0:            d.ellipse([x0, y0, x1, y1], fill=c)        elif kind == 1:            d.rectangle([x0, y0, x1, y1], fill=c)        else:            d.polygon([(x0, y1), ((x0 + x1) // 2, y0), (x1, y1)], fill=c)    # The shot: a little moved and zoomed, then sized.    srng = np.random.default_rng(shot_seed)    dx, dy = srng.uniform(-shift, shift, 2) * np.array([w, h])    z = 1 + srng.uniform(0, shift)    box = (w * (1 - 1 / z) / 2 + dx, h * (1 - 1 / z) / 2 + dy, w - w * (1 - 1 / z) / 2 + dx, h - h * (1 - 1 / z) / 2 + dy)    return img.transform(size, Image.EXTENT, box, Image.BICUBIC)def paste_face(img, face_path, cx, cy, side, rng):    face = Image.open(face_path).convert("RGB").resize((side, side), Image.BICUBIC)    # A torso under the face, then the face in a soft oval.    d = ImageDraw.Draw(img)    torso = tuple(int(v) for v in rng.integers(20, 230, 3))    d.ellipse([cx - side, cy + side * 0.45, cx + side, cy + side * 2.6], fill=torso)    mask = Image.new("L", (side, side), 0)    ImageDraw.Draw(mask).ellipse([side * 0.04, 0, side * 0.96, side], fill=255)    mask = mask.filter(ImageFilter.GaussianBlur(max(1, side // 24)))    img.paste(face, (int(cx - side / 2), int(cy - side / 2)), mask)    return [int(cx - side / 2), int(cy - side / 2), side, side]def draw_camera(job, faces_dir):    size = LARGE if job.get("large") else CAMERA    img = scene_picture(job["scene"], size, job["seed"], 0.03)    rng = np.random.default_rng(job["seed"])    boxes = []    people = job.get("people") or []    if people:        # Faces of one moment keep their places; each shot moves them a little.        prng = np.random.default_rng(job["scene"] + 1)        sides = [int(np.clip(prng.lognormal(math.log(110), 0.7), 24, 360)) for _ in people]        for n, (person, side) in enumerate(zip(people, sides)):            scale = size[0] / CAMERA[0]            side = int(side * scale)            cx = (n + 1) / (len(people) + 1) * size[0] + rng.uniform(-0.01, 0.01) * size[0]            cy = size[1] * prng.uniform(0.3, 0.55) + rng.uniform(-0.01, 0.01) * size[1]            path = Path(faces_dir) / person["identity"] / f"{person['picture']}.png"            if not path.exists():                candidates = sorted((Path(faces_dir) / person["identity"]).glob("*"))                path = candidates[person["picture"] % len(candidates)]            box = paste_face(img, path, cx, cy, side, rng)            boxes.append(dict(identity=person["identity"], box=box, side=side))    # Grain, then blur or dark.    arr = np.asarray(img, float)    arr += rng.normal(0, 4, arr.shape)    exposure = rng.uniform(0.9, 1.1)    if job.get("dark"):        exposure *= rng.uniform(0.12, 0.28)    img = Image.fromarray(np.clip(arr * exposure, 0, 255).astype(np.uint8))    if job.get("blurred"):        img = img.filter(ImageFilter.GaussianBlur(rng.uniform(4, 12) * size[0] / CAMERA[0]))    return img, boxesdef draw_screenshot(job):    rng = random.Random(job["seed"])    img = Image.new("RGB", SCREEN, rng.choice([(250, 250, 250), (20, 20, 22), (242, 242, 247)]))    d = ImageDraw.Draw(img)    dark = img.getpixel((0, 0))[0] < 100    ink = (235, 235, 235) if dark else (20, 20, 20)    d.text((60, 30), "9:41", fill=ink, font=font(44))    y = 200    words = ["Order", "Delivered", "Meeting", "Tomorrow", "Payment", "Received", "Flight", "Gate", "Boarding", "Reply"]    while y < SCREEN[1] - 200:        if rng.random() < 0.2:            c = tuple(rng.randrange(40, 220) for _ in range(3))            d.rounded_rectangle([60, y, SCREEN[0] - 60, y + 360], 28, fill=c)            y += 400        else:            d.text((60, y), " ".join(rng.choice(words) for _ in range(rng.randrange(2, 6))), fill=ink, font=font(48))            y += 90    return imgdef draw_document(job):    rng = random.Random(job["seed"])    table = Image.new("RGB", CAMERA, tuple(rng.randrange(60, 160) for _ in range(3)))    page = Image.new("RGB", (900, 1300), (248, 246, 240))    d = ImageDraw.Draw(page)    d.text((60, 50), rng.choice(["TAX INVOICE", "RECEIPT", "Bill of supply", "Rental agreement"]), fill=(20, 20, 20), font=font(56))    y = 160    while y < 1200:        d.text((60, y), f"{rng.choice(['Item', 'Tea', 'Paper', 'Rice', 'Service', 'GST'])} {rng.randrange(1, 99)}", fill=(30, 30, 30), font=font(36))        d.text((640, y), f"{rng.randrange(10, 9999)}.{rng.randrange(0, 99):02d}", fill=(30, 30, 30), font=font(36))        y += 60    # The page in perspective on the table.    w, h = CAMERA    q = [rng.uniform(0.15, 0.3) * w, rng.uniform(0.05, 0.15) * h]    quad = (q[0], q[1], q[0] - rng.uniform(0, 0.05) * w, h * rng.uniform(0.85, 0.95),            w - q[0] + rng.uniform(0, 0.05) * w, h * rng.uniform(0.85, 0.95), w - q[0], q[1] + rng.uniform(-0.03, 0.03) * h)    coeffs = find_coeffs([(quad[0], quad[1]), (quad[2], quad[3]), (quad[4], quad[5]), (quad[6], quad[7])],                         [(0, 0), (0, 1300), (900, 1300), (900, 0)])    warped = page.transform(CAMERA, Image.PERSPECTIVE, coeffs, Image.BICUBIC)    mask = Image.new("L", (900, 1300), 255).transform(CAMERA, Image.PERSPECTIVE, coeffs, Image.BICUBIC)    table.paste(warped, (0, 0), mask)    return tabledef find_coeffs(output, page):    """PIL's perspective coefficients: for each pixel (x, y) of the output, the page's (u, v)."""    matrix, b = [], []    for (x, y), (u, v) in zip(output, page):        matrix.append([x, y, 1, 0, 0, 0, -u * x, -u * y])        matrix.append([0, 0, 0, x, y, 1, -v * x, -v * y])        b += [u, v]    return np.linalg.solve(np.array(matrix, float), np.array(b, float)).tolist()def exif(job, camera=True):    e = Image.Exif()    when = datetime.fromisoformat(job["when"])    place = job.get("place")    offset = place[3] if place else 19800    local = when + timedelta(seconds=offset)    if camera:        e[0x010F] = "Apple"        e[0x0110] = "iPhone 15 Pro"    ifd = e.get_ifd(0x8769)    ifd[0x9003] = local.strftime("%Y:%m:%d %H:%M:%S")  # DateTimeOriginal    ifd[0x9004] = local.strftime("%Y:%m:%d %H:%M:%S")    ifd[0x9011] = f"{'+' if offset >= 0 else '-'}{abs(offset) // 3600:02d}:{abs(offset) % 3600 // 60:02d}"    if job["kind"] == "screenshot":        ifd[0x9286] = b"ASCII\x00\x00\x00Screenshot"    if place:        rng = random.Random(job.get("scene", job["seed"]))        lat, lon = place[1] + rng.uniform(-0.02, 0.02), place[2] + rng.uniform(-0.02, 0.02)        g = e.get_ifd(0x8825)        g[1] = "N" if lat >= 0 else "S"        g[2] = dms(abs(lat))        g[3] = "E" if lon >= 0 else "W"        g[4] = dms(abs(lon))    return edef dms(v):    d = int(v)    m = int((v - d) * 60)    s = (v - d - m / 60) * 3600    return (d, m, round(s, 4))def make(args):    job, out, faces_dir, long_edge = args    path = Path(out) / job["file"]    truth = {k: job[k] for k in ("file", "kind", "moment", "shot", "when") if k in job}    if path.exists():        return None    if job["kind"] == "camera":        img, boxes = draw_camera(job, faces_dir)        img.save(path, "JPEG", quality=88, exif=exif(job))        truth.update(blurred=job["blurred"], dark=job["dark"], people=boxes, place=job["place"][0], trip=job["place"][4],                     offset=job["place"][3], size=img.size)    elif job["kind"] == "whatsapp":        img, boxes = draw_camera(job, faces_dir)        img.thumbnail((1600, 1600), Image.BICUBIC)        img.save(path, "JPEG", quality=70)        truth.update(copy_of=job["copy_of"], people=boxes, size=img.size)    elif job["kind"] == "screenshot":        img = draw_screenshot(job)        img.save(path, "PNG", exif=exif(job, camera=False))        truth.update(size=img.size)    else:        img = draw_document(job)        img.save(path, "JPEG", quality=88, exif=exif(job))        truth.update(size=img.size, place=job["place"][0], trip=job["place"][4])    if long_edge and max(img.size) > long_edge:        # A big library for memory and speed at scale (--long-edge): the same picture, smaller on disk. Face boxes in the        # truth stay in the drawn size's pixels, so `size` keeps the drawn size too.        small = Image.open(path)        small.thumbnail((long_edge, long_edge), Image.BICUBIC)        small.save(path, small.format or "JPEG", **({"quality": 85} if path.suffix.lower() == ".jpg" else {}), exif=small.info.get("exif", b""))    return truthdef videos(out, count, seed):    rng = random.Random(seed)    made = []    for n in range(count):        long = n < max(1, count // 7)        seconds = rng.randrange(150, 300) if long else rng.randrange(6, 40)        when = datetime(2017, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=rng.randrange(0, 9 * 365 * 86400))        name = f"IMG_{when.strftime('%Y%m%d_%H%M%S')}_v{n:03d}.MOV"        path = Path(out) / name        if not path.exists():            subprocess.run([                "ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i",                f"testsrc2=size=1920x1080:rate=30,hue=h={rng.randrange(360)}", "-t", str(seconds),                "-c:v", "libx264", "-preset", "veryfast", "-b:v", "10M" if long else "6M", "-pix_fmt", "yuv420p",                "-metadata", f"creation_time={when.strftime('%Y-%m-%dT%H:%M:%SZ')}", str(path)], check=True)        made.append(dict(file=name, kind="video", seconds=seconds, when=when.isoformat(), long=long))    return madedef load(folder, sim, chunk=200):    files = sorted(p for p in Path(folder).iterdir() if p.suffix.lower() in (".jpg", ".png", ".mov"))    for i in range(0, len(files), chunk):        subprocess.run(["xcrun", "simctl", "addmedia", sim, *map(str, files[i:i + chunk])], check=True)        print(f"loaded {min(len(files), i + chunk)} of {len(files)}", flush=True)def main():    ap = argparse.ArgumentParser()    ap.add_argument("--out")    ap.add_argument("--photos", type=int, default=5000)    ap.add_argument("--videos", type=int, default=30)    ap.add_argument("--faces", help="HyperFace's folder: one folder per identity")    ap.add_argument("--seed", type=int, default=7)    ap.add_argument("--long-edge", type=int, default=0, help="shrink every picture to this long edge (a big library that fits a disk)")    ap.add_argument("--load")    ap.add_argument("--sim")    ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 2))    a = ap.parse_args()    if a.load:        load(a.load, a.sim)        return    out = Path(a.out)    out.mkdir(parents=True, exist_ok=True)    identities = []    if a.faces:        identities = sorted(p.name for p in Path(a.faces).iterdir() if p.is_dir() and len(list(p.iterdir())) >= 64)    jobs = plan(a.photos, a.seed, identities)    with Pool(a.workers) as pool:        truths = [t for t in pool.imap(make, [(j, str(out), a.faces, a.long_edge) for j in jobs], chunksize=8) if t]    truths += videos(out, a.videos, a.seed)    with open(out / "truth.jsonl", "a") as f:        for t in truths:            f.write(json.dumps(t) + "\n")    print(f"{len(jobs)} pictures, {a.videos} videos, {len(identities)} identities -> {out}")if __name__ == "__main__":    sys.exit(main())