The recorded TODO 3.0 decision: generated, not downloaded. No image licensing question, no binary blobs in git, and it can produce the volume a virtualised grid actually has to be tested against, which no set of real photos on hand would. Frames are written to disk for real, and thumbnails with them. A gallery whose rows point at files that do not exist tests nothing about the delivery path, which is the half most likely to be wrong. --no-thumbnails leaves thumb_path NULL instead, which is how to exercise the queue at volume. The data imitates what the firmware sends rather than being uniformly random: bursts of frames around one radar trigger, the first one or two out of the PSRAM pre-trigger ring, timestamps weighted toward daylight because birds are diurnal and a gallery grouped by day looks wrong otherwise. Frames within a burst land milliseconds apart on purpose - that is the received_at collision the gallery cursor has to survive, and a seed that spread a burst over minutes would never reproduce the paging bug it causes. --clear is scoped by device_uid prefix, and that is the whole reason the prefix exists. This command holds a DELETE over the same tables a real camera writes to, so the property worth having is not that it removes seeded rows but that it removes nothing else. The test for that is the one to keep: it puts a non-seed device with a capture alongside the seeded ones and asserts both survive. That test was mutation-checked against a scratch database rather than the dev one, deliberately - a widened clear() would have taken the six real captures with it, and verifying a safety property is not worth risking the thing it protects. Against the scratch database, removing the scoping failed exactly that test and nothing else. The seed device is issued no token. It is a row for the gallery to point at, not a camera, and giving it a working credential would be creating a real way in for the sake of test data. One flaky test found and fixed rather than re-run. test_every_burst_has_ pre_trigger_frames failed about one run in fifteen, because a count that is not a multiple of the burst size left a truncated final burst - sometimes of one frame, which is necessarily all pre-trigger, so "not all frames are pre-trigger" did not hold. Both sides were wrong: a one-frame burst with burst_count=1 is not something a camera sends, so the generator now absorbs a short tail into the previous burst (bursts are 3-7 rather than 3-5), and the test states its precondition instead of assuming it. Verified by running the randomised tests fifteen times with the fix (0 failures) and fifteen times without it (1 failure), rather than by one green run. Tests: 293 -> 308. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
258 lines
9.6 KiB
Python
258 lines
9.6 KiB
Python
"""Synthetic captures for developing the gallery (TODO 3.0).
|
|
|
|
Generated, not downloaded. Three reasons, from the recorded decision:
|
|
|
|
* no image licensing question at all, and no binary blobs in git;
|
|
* it can produce the *volume* a virtualised grid has to be tested against,
|
|
which no set of real photos on hand would; and
|
|
* a real photo proves nothing about a gallery that a generated one does not.
|
|
|
|
**Seeded data is confined to its own device**, whose ``device_uid`` starts with
|
|
``SEED_UID_PREFIX``. That is what makes ``--clear`` safe: it deletes captures
|
|
belonging to seed devices and nothing else, so a real camera's frames are never
|
|
in scope. Without that boundary a convenience command sits next to real data
|
|
holding a delete, which is not a risk worth carrying for test rows.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import random
|
|
import secrets
|
|
import uuid
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
from sqlalchemy import delete, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from .config import get_settings
|
|
from .images import (
|
|
make_thumbnail,
|
|
relative_image_path,
|
|
relative_thumb_path,
|
|
write_atomically,
|
|
)
|
|
from .models import Capture, Device, Job
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
# Deliberately hex-looking, so it is a plausible device_uid, while still being
|
|
# unmistakable in a listing. "5eed".
|
|
SEED_UID_PREFIX = "5eed"
|
|
|
|
# A burst is what the firmware actually sends: a handful of frames around one
|
|
# radar trigger, the first of them pulled from the PSRAM pre-trigger ring.
|
|
BURST_MIN, BURST_MAX = 3, 5
|
|
|
|
# Realistic per API.md/SPEC: UXGA frames of a few hundred KB.
|
|
FRAME_WIDTH, FRAME_HEIGHT = 1600, 1200
|
|
|
|
# Birds are diurnal, and a gallery grouped by day looks wrong if captures are
|
|
# spread evenly around the clock. Weight toward daylight.
|
|
_DAY_HOURS = list(range(5, 21))
|
|
|
|
|
|
def _synthetic_jpeg(width: int, height: int, seed: int) -> bytes:
|
|
"""A distinct, cheap JPEG per capture.
|
|
|
|
Distinct matters more than pretty: identical tiles make it impossible to
|
|
see whether the grid is actually scrolling, and a flat colour compresses to
|
|
a few hundred bytes, which would not exercise the thumbnail path at a
|
|
realistic size. A coarse gradient plus noise blocks gives both.
|
|
"""
|
|
import io
|
|
|
|
from PIL import Image, ImageDraw
|
|
|
|
rng = random.Random(seed)
|
|
image = Image.new("RGB", (width, height))
|
|
draw = ImageDraw.Draw(image)
|
|
|
|
base = (rng.randint(40, 140), rng.randint(70, 170), rng.randint(40, 120))
|
|
# Coarse bands rather than per-pixel work: 500 frames at 1600x1200 is
|
|
# enough to notice, and the point is bytes on disk, not art.
|
|
band = max(8, height // 48)
|
|
for y in range(0, height, band):
|
|
shade = y / height
|
|
draw.rectangle(
|
|
[0, y, width, y + band],
|
|
fill=(
|
|
min(255, int(base[0] * (0.6 + shade))),
|
|
min(255, int(base[1] * (0.6 + shade))),
|
|
min(255, int(base[2] * (0.6 + shade))),
|
|
),
|
|
)
|
|
|
|
for _ in range(60):
|
|
x, y = rng.randint(0, width), rng.randint(0, height)
|
|
size = rng.randint(20, 90)
|
|
draw.ellipse(
|
|
[x, y, x + size, y + size],
|
|
fill=(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)),
|
|
)
|
|
|
|
buffer = io.BytesIO()
|
|
image.save(buffer, format="JPEG", quality=78)
|
|
return buffer.getvalue()
|
|
|
|
|
|
def seed_device(db: Session, name: str) -> Device:
|
|
"""The device seeded captures hang off. Reused if it already exists."""
|
|
device = db.scalar(
|
|
select(Device).where(Device.name == name, Device.device_uid.startswith(SEED_UID_PREFIX))
|
|
)
|
|
if device is not None:
|
|
return device
|
|
|
|
device = Device(
|
|
device_uid=f"{SEED_UID_PREFIX}{secrets.token_hex(6)}",
|
|
name=name,
|
|
# No token. A seed device is a row for the gallery to point at, not a
|
|
# camera that can authenticate -- issuing it a working credential
|
|
# would be creating a real way in for the sake of test data.
|
|
token_hash=None,
|
|
enabled=True,
|
|
battery_valid=False,
|
|
)
|
|
db.add(device)
|
|
db.commit()
|
|
db.refresh(device)
|
|
return device
|
|
|
|
|
|
def generate(
|
|
db: Session,
|
|
*,
|
|
count: int,
|
|
days: int,
|
|
device_name: str,
|
|
thumbnails: bool,
|
|
progress: bool = True,
|
|
) -> int:
|
|
"""Create ``count`` captures spread over the last ``days``. Returns how many.
|
|
|
|
Frames are written to disk for real, because a gallery whose rows point at
|
|
files that do not exist tests nothing about the delivery path -- which is
|
|
the half most likely to be wrong.
|
|
"""
|
|
settings = get_settings()
|
|
device = seed_device(db, device_name)
|
|
rng = random.Random()
|
|
|
|
made = 0
|
|
while made < count:
|
|
remaining = count - made
|
|
burst_size = min(rng.randint(BURST_MIN, BURST_MAX), remaining)
|
|
# Absorb a tail too short to be a burst. Plain truncation leaves a
|
|
# final burst of one or two frames with burst_count=1, which no camera
|
|
# sends -- and a one-frame burst is entirely pre-trigger, so it also
|
|
# makes that flag meaningless. Bursts here are 3-7 rather than 3-5,
|
|
# which is a better trade than inventing data the firmware cannot
|
|
# produce. (This was a flaky test before it was a comment: whether it
|
|
# happened depended on the random sizes.)
|
|
if 0 < remaining - burst_size < BURST_MIN:
|
|
burst_size = remaining
|
|
burst_id = str(uuid.uuid4())
|
|
|
|
# One trigger event, somewhere in the window, at a plausible hour.
|
|
moment = datetime.now(UTC) - timedelta(
|
|
days=rng.uniform(0, days),
|
|
)
|
|
moment = moment.replace(hour=rng.choice(_DAY_HOURS), minute=rng.randint(0, 59))
|
|
|
|
for index in range(burst_size):
|
|
capture_id = uuid.uuid4()
|
|
# Frames within a burst are milliseconds apart, which is exactly
|
|
# the received_at tie the gallery cursor has to survive.
|
|
captured = moment + timedelta(milliseconds=index * 120)
|
|
received = captured + timedelta(milliseconds=rng.randint(200, 1500))
|
|
|
|
data = _synthetic_jpeg(FRAME_WIDTH, FRAME_HEIGHT, seed=capture_id.int % (2**31))
|
|
relative = relative_image_path(capture_id, received)
|
|
write_atomically(settings.image_root / relative, data)
|
|
|
|
capture = Capture(
|
|
id=capture_id,
|
|
device_id=device.id,
|
|
path=relative,
|
|
sha256=secrets.token_hex(32),
|
|
width=FRAME_WIDTH,
|
|
height=FRAME_HEIGHT,
|
|
bytes=len(data),
|
|
captured_at_device=captured,
|
|
received_at=received,
|
|
trigger="radar" if rng.random() < 0.9 else "manual",
|
|
burst_id=burst_id,
|
|
burst_index=index,
|
|
burst_count=burst_size,
|
|
# The first frame or two come out of the pre-trigger ring, and
|
|
# are usually the good ones -- the bird is still arriving.
|
|
pre_trigger=index < (1 if burst_size < 4 else 2),
|
|
frame_seq=made + index,
|
|
radar_state=rng.choice([1, 2, 3]),
|
|
radar_distance_cm=rng.randint(60, 320),
|
|
radar_energy=rng.randint(20, 100),
|
|
battery_mv=None,
|
|
rssi=rng.randint(-82, -45),
|
|
temp_c=round(rng.uniform(2.0, 26.0), 1),
|
|
reviewed=rng.random() < 0.2,
|
|
kept=rng.random() > 0.1,
|
|
)
|
|
|
|
if thumbnails:
|
|
thumb_relative = relative_thumb_path(capture_id)
|
|
thumb_bytes, _ = make_thumbnail(settings.image_root / relative)
|
|
write_atomically(settings.thumb_root / thumb_relative, thumb_bytes)
|
|
capture.thumb_path = thumb_relative
|
|
|
|
db.add(capture)
|
|
|
|
made += burst_size
|
|
# Commit per burst, so interrupting a long run leaves whole bursts
|
|
# rather than a half-written one, and so 500 rows are not one
|
|
# transaction held open across 500 image encodes.
|
|
db.commit()
|
|
if progress and made % 50 < burst_size:
|
|
print(f" {made}/{count}")
|
|
|
|
return made
|
|
|
|
|
|
def clear(db: Session) -> tuple[int, int]:
|
|
"""Delete every seeded capture and device. Returns (captures, devices).
|
|
|
|
Scoped to seed devices by ``device_uid`` prefix, which is the whole reason
|
|
that prefix exists. A real camera's captures are never in scope, and this
|
|
command therefore cannot be the thing that loses them.
|
|
"""
|
|
devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all()
|
|
if not devices:
|
|
return 0, 0
|
|
|
|
settings = get_settings()
|
|
device_ids = [d.id for d in devices]
|
|
captures = db.scalars(select(Capture).where(Capture.device_id.in_(device_ids))).all()
|
|
|
|
for capture in captures:
|
|
(settings.image_root / capture.path).unlink(missing_ok=True)
|
|
if capture.thumb_path:
|
|
(settings.thumb_root / capture.thumb_path).unlink(missing_ok=True)
|
|
|
|
# Thumbnail jobs reference captures that are about to stop existing. The
|
|
# handler already tolerates a missing capture -- retention will do this
|
|
# routinely in Phase 5 -- but leaving them means the worker waking up to do
|
|
# pointless work and logging about it, which looks like a fault later.
|
|
capture_ids = [str(c.id) for c in captures]
|
|
if capture_ids:
|
|
db.execute(
|
|
delete(Job).where(
|
|
Job.kind == "thumbnail",
|
|
Job.payload["capture_id"].astext.in_(capture_ids),
|
|
)
|
|
)
|
|
|
|
db.execute(delete(Capture).where(Capture.device_id.in_(device_ids)))
|
|
db.execute(delete(Device).where(Device.id.in_(device_ids)))
|
|
db.commit()
|
|
return len(captures), len(devices)
|