diff --git a/server/src/poorbird/cli.py b/server/src/poorbird/cli.py index 6ba6c4c..fcdc474 100644 --- a/server/src/poorbird/cli.py +++ b/server/src/poorbird/cli.py @@ -214,6 +214,30 @@ def cmd_user_passwd(args: argparse.Namespace) -> int: return 0 +def cmd_seed(args: argparse.Namespace) -> int: + from .db import SessionLocal + from .seed import clear, generate + + with SessionLocal() as session: + if args.clear: + captures, devices = clear(session) + print(f"removed {captures} seeded capture(s) and {devices} seed device(s)") + return 0 + + print(f"generating {args.captures} capture(s) over {args.days} day(s)...") + made = generate( + session, + count=args.captures, + days=args.days, + device_name=args.device_name, + thumbnails=not args.no_thumbnails, + ) + + print(f"\ndone: {made} capture(s) on device {args.device_name!r}") + print("Remove them again with: poorbird seed --clear") + return 0 + + def cmd_check(_args: argparse.Namespace) -> int: settings = get_settings() problems: list[str] = [] @@ -327,6 +351,27 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("payload", nargs="?", help="JSON object") p.set_defaults(func=cmd_enqueue) + p = sub.add_parser( + "seed", + help="generate synthetic captures for gallery development", + description=( + "Creates captures on a dedicated seed device, with real JPEGs on disk. " + "--clear removes them again, and is scoped to seed devices only, so a " + "real camera's captures are never in scope." + ), + ) + p.add_argument("--captures", type=int, default=500, help="how many frames (default 500)") + p.add_argument("--days", type=int, default=14, help="spread them over this many days") + p.add_argument("--device-name", default="seed-cam") + p.add_argument( + "--no-thumbnails", + action="store_true", + help="leave thumb_path NULL so the worker generates them, which is how to " + "exercise the queue at volume", + ) + p.add_argument("--clear", action="store_true", help="delete all seeded data instead") + p.set_defaults(func=cmd_seed) + p = sub.add_parser("user", help="manage UI accounts (there is no web signup)") usersub = p.add_subparsers(dest="user_command", required=True) diff --git a/server/src/poorbird/seed.py b/server/src/poorbird/seed.py new file mode 100644 index 0000000..05edb0a --- /dev/null +++ b/server/src/poorbird/seed.py @@ -0,0 +1,257 @@ +"""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) diff --git a/server/tests/test_seed.py b/server/tests/test_seed.py new file mode 100644 index 0000000..3b439e7 --- /dev/null +++ b/server/tests/test_seed.py @@ -0,0 +1,302 @@ +"""The gallery seed command (TODO 3.0). + +The scoping test here is the one that matters. ``poorbird seed --clear`` holds +a DELETE over the same tables a real camera writes to, so the property worth +pinning is not that it removes seeded rows -- it is that it removes *nothing +else*. + +Counts are deliberately tiny. Each frame is a real 1600x1200 JPEG encode plus +a thumbnail; the behaviour under test is the same at 8 as at 500, and the suite +should not spend half a minute proving it. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db +from sqlalchemy import func, select, text + +from poorbird.config import get_settings +from poorbird.models import Capture, Device +from poorbird.seed import BURST_MIN, SEED_UID_PREFIX, clear, generate, seed_device + +pytestmark = [pytest.mark.db, needs_db] + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture(autouse=True) +def no_seed_left_behind(db): + """Remove seeded rows however the test ends. + + ``clear()`` is the subject of some of these tests, so it cannot be relied + on as the teardown for all of them -- a broken clear() would then leave the + database dirty *and* hide that it was broken. + """ + yield + devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() + for device in devices: + db.execute(text("DELETE FROM captures WHERE device_id = :i"), {"i": device.id}) + db.execute(text("DELETE FROM devices WHERE id = :i"), {"i": device.id}) + db.commit() + + +@pytest.fixture +def real_device(db): + """A device that is NOT seeded, with a capture, to prove clear() misses it.""" + device = Device(device_uid=secrets.token_hex(6), name="real-camera", enabled=True) + db.add(device) + db.commit() + db.refresh(device) + + capture = Capture( + device_id=device.id, + path="2026/09/20/real.jpg", + sha256=secrets.token_hex(32), + bytes=1234, + trigger="radar", + ) + db.add(capture) + db.commit() + device_id = device.id + + yield device + + db.execute(text("DELETE FROM captures WHERE device_id = :i"), {"i": device_id}) + db.execute(text("DELETE FROM devices WHERE id = :i"), {"i": device_id}) + db.commit() + + +def _seeded_captures(db, device: Device) -> list[Capture]: + return list( + db.scalars( + select(Capture).where(Capture.device_id == device.id).order_by(Capture.frame_seq) + ).all() + ) + + +# --- generating -------------------------------------------------------------- + + +def test_it_makes_the_requested_number_of_captures(db): + made = generate(db, count=6, days=3, device_name="t-seed", thumbnails=False, progress=False) + assert made == 6 + + device = seed_device(db, "t-seed") + assert len(_seeded_captures(db, device)) == 6 + + +def test_the_count_is_exact_even_though_bursts_are_random_sized(db): + """Bursts are 3-5 frames, so a naive loop overshoots. 7 is not a multiple + of any burst size, which is the point of asking for it.""" + made = generate(db, count=7, days=2, device_name="t-seed", thumbnails=False, progress=False) + assert made == 7 + assert len(_seeded_captures(db, seed_device(db, "t-seed"))) == 7 + + +def test_the_frames_really_exist_on_disk(db): + """A gallery whose rows point at missing files tests nothing about the + delivery path, which is the half most likely to be wrong.""" + generate(db, count=4, days=1, device_name="t-seed", thumbnails=False, progress=False) + root = get_settings().image_root + + for capture in _seeded_captures(db, seed_device(db, "t-seed")): + path = root / capture.path + assert path.is_file(), f"missing {path}" + assert path.read_bytes().startswith(b"\xff\xd8\xff"), "not a JPEG" + assert capture.bytes == path.stat().st_size + + +def test_thumbnails_are_generated_when_asked(db): + generate(db, count=3, days=1, device_name="t-seed", thumbnails=True, progress=False) + thumb_root = get_settings().thumb_root + + for capture in _seeded_captures(db, seed_device(db, "t-seed")): + assert capture.thumb_path is not None + thumb = thumb_root / capture.thumb_path + assert thumb.is_file() + # WebP, per SPEC 3.3. RIFF magic rather than trusting the extension. + assert thumb.read_bytes()[:4] == b"RIFF" + + +def test_without_thumbnails_the_worker_still_has_something_to_do(db): + """--no-thumbnails is how the queue gets exercised at volume, so the rows + must be left in exactly the state /ingest leaves them.""" + generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) + captures = _seeded_captures(db, seed_device(db, "t-seed")) + assert captures + assert all(c.thumb_path is None for c in captures) + + +def test_frames_are_grouped_into_consistent_bursts(db): + generate(db, count=8, days=2, device_name="t-seed", thumbnails=False, progress=False) + captures = _seeded_captures(db, seed_device(db, "t-seed")) + + by_burst: dict[str, list[Capture]] = {} + for capture in captures: + by_burst.setdefault(capture.burst_id, []).append(capture) + + assert len(by_burst) >= 2, "8 frames should not be one burst" + for frames in by_burst.values(): + indexes = sorted(f.burst_index for f in frames) + assert indexes == list(range(len(frames))), "burst_index must be dense from 0" + # burst_count is what the device claims it sent, so every frame in a + # burst has to agree on it. + assert len({f.burst_count for f in frames}) == 1 + + +def test_every_burst_has_pre_trigger_frames(db): + """SPEC 0: the first frames come out of the PSRAM ring and are usually the + good ones. A seed with none would hide whatever the UI does with them.""" + generate(db, count=8, days=2, device_name="t-seed", thumbnails=False, progress=False) + captures = _seeded_captures(db, seed_device(db, "t-seed")) + + by_burst: dict[str, list[Capture]] = {} + for capture in captures: + by_burst.setdefault(capture.burst_id, []).append(capture) + + assert by_burst + for frames in by_burst.values(): + assert any(f.pre_trigger for f in frames) + # ...and not all of them, or the flag would carry no information. + # Stated with its precondition: a single-frame burst is necessarily + # all pre-trigger, so the generator is expected not to produce one. + assert len(frames) >= BURST_MIN, "a burst this short is not something a camera sends" + assert not all(f.pre_trigger for f in frames) + + +def test_frames_in_a_burst_arrive_close_enough_to_tie(db): + """The reason the gallery cursor carries the id as well as the timestamp. + + If the seed spread a burst over minutes, it would never reproduce the + received_at collision that real bursts cause, and the paging bug that + collision triggers would only ever appear against a real camera. + """ + generate(db, count=5, days=1, device_name="t-seed", thumbnails=False, progress=False) + captures = _seeded_captures(db, seed_device(db, "t-seed")) + + by_burst: dict[str, list[Capture]] = {} + for capture in captures: + by_burst.setdefault(capture.burst_id, []).append(capture) + + burst = max(by_burst.values(), key=len) + span = max(f.received_at for f in burst) - min(f.received_at for f in burst) + assert span.total_seconds() < 5, "a burst should arrive within seconds, not minutes" + + +def test_the_seed_device_cannot_authenticate(db): + """It is a row for the gallery to point at, not a camera. Giving it a + working token would be creating a real way in for test data's sake.""" + device = seed_device(db, "t-seed") + assert device.token_hash is None + assert device.device_uid.startswith(SEED_UID_PREFIX) + + +def test_seeding_twice_reuses_the_same_device(db): + generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) + generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) + + devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() + assert len(devices) == 1 + assert len(_seeded_captures(db, devices[0])) == 6 + + +# --- clearing ---------------------------------------------------------------- + + +def test_clear_removes_seeded_captures_and_the_device(db): + generate(db, count=4, days=1, device_name="t-seed", thumbnails=True, progress=False) + + captures, devices = clear(db) + assert captures == 4 + assert devices == 1 + assert ( + db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() == [] + ) + + +def test_clear_leaves_a_real_camera_completely_alone(db, real_device): + """The property this command lives or dies by. + + It holds a DELETE over the same tables a real camera writes to. Scoping it + by device_uid prefix is what makes that safe, and a change that widened the + scope has to fail here rather than in someone's photo library. + """ + generate(db, count=4, days=1, device_name="t-seed", thumbnails=False, progress=False) + before = db.scalar( + select(func.count()).select_from(Capture).where(Capture.device_id == real_device.id) + ) + assert before == 1 + + clear(db) + + assert db.get(Device, real_device.id) is not None + assert ( + db.scalar( + select(func.count()).select_from(Capture).where(Capture.device_id == real_device.id) + ) + == 1 + ) + + +def test_clear_deletes_the_files_too(db): + """Otherwise the image root grows every time the seed is regenerated, and + nothing ever points at the leftovers.""" + generate(db, count=3, days=1, device_name="t-seed", thumbnails=True, progress=False) + settings = get_settings() + device = seed_device(db, "t-seed") + paths = [ + (settings.image_root / c.path, settings.thumb_root / c.thumb_path) + for c in _seeded_captures(db, device) + ] + assert all(image.is_file() and thumb.is_file() for image, thumb in paths) + + clear(db) + + for image, thumb in paths: + assert not image.exists(), f"left behind {image}" + assert not thumb.exists(), f"left behind {thumb}" + + +def test_clear_on_an_unseeded_database_is_not_an_error(db): + assert clear(db) == (0, 0) + + +def test_clear_removes_the_thumbnail_jobs_as_well(db): + """A job pointing at a capture that no longer exists is not a failure -- + the handler tolerates it -- but it is the worker waking up to do nothing + and logging about it, which looks like a fault later.""" + from poorbird.models import Job + from poorbird.worker.queue import enqueue + + generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) + device = seed_device(db, "t-seed") + captures = _seeded_captures(db, device) + for capture in captures: + enqueue(db, "thumbnail", {"capture_id": str(capture.id)}) + db.commit() + + ids = [str(c.id) for c in captures] + assert ( + db.scalar( + select(func.count()).select_from(Job).where(Job.payload["capture_id"].astext.in_(ids)) + ) + == 3 + ) + + clear(db) + + assert ( + db.scalar( + select(func.count()).select_from(Job).where(Job.payload["capture_id"].astext.in_(ids)) + ) + == 0 + )