Captures now get a WebP thumbnail: 400px on the long edge, written to
thumbs/<uuid>_400.webp (SPEC 3.3). /ingest enqueues the job in the same
transaction as the capture row, so the worker never sees a job for a capture
that was rolled back, and decoding stays off the request path - it is the one
genuinely expensive part of a capture, and the device is waiting with a burst
still to upload.
api/images.py moves up to poorbird/images.py. Both sides use it now, and a
worker importing from api would be the wrong way round. The split by cost
stays: everything the ingest path touches still reads nine bytes of JPEG
header, and Pillow appears only in the thumbnail half.
Handler behaviour is about which failures are worth retrying:
- An undecodable frame returns rather than raises. The handler contract
makes a raise mean "retry", and a frame that will never decode should not
spend three attempts proving it. Logged, thumb_path left NULL.
- A missing source file raises, because it should be there and a mount that
has not come back yet is worth retrying for.
- A capture deleted between enqueue and run is not an error. Retention will
do that routinely in Phase 5.
- A malformed payload is validated with a Pydantic model and recorded, not
retried (SEC-003 applied to a job payload).
- Never upscales: blowing a 100px frame up to 400px produces a blurry lie.
- Fills in width/height when the ingest header parse could not. This is the
first full decode, so it is the chance to fix that.
Verified end to end against a real device row, a real HTTP ingest and the
real worker dispatch path - claim, _run_one, complete - not just the handler
called directly: 1600x1200 JPEG in, WEBP 400x300 on disk, job marked done.
That run is what caught the rest of this commit.
Tests were leaking jobs into the shared queue, which broke test_queue.py once
/ingest started enqueuing. Three separate causes, all the same shape as the
teardown bug fixed in 269a6ea:
- test_ingest cleaned captures but not their thumbnail jobs, and one test
hand-rolled teardown for a second device and forgot half of it. Devices
now come from a fixture that cleans frames, captures and jobs for every
device a test makes.
- test_queue claimed jobs without checking they were its own, so a leftover
thumbnail job could be failed on its behalf, and one test claimed a
second job to prove the first did not recur and then stranded it in
'running' forever. It now enqueues at a priority that wins, asserts every
claim is its own, and releases anything else it touches.
The suite now runs twice in a row leaving zero jobs behind, which is the
assertion that actually matters here.
Tests: 175 -> 193.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
187 lines
7.7 KiB
Python
187 lines
7.7 KiB
Python
"""Captures, observations, taxonomy and tags.
|
|
|
|
Two structural decisions from SPEC 3, both load-bearing:
|
|
|
|
1. ``captures`` 1--n ``observations``. One photo can hold two species, and can
|
|
legitimately hold none (a false trigger, an empty frame). A single
|
|
``species`` column on the image would have to be undone later.
|
|
2. Human labels and model predictions share one table, separated by
|
|
``source``. The edit UI is therefore already the training-data pipeline for
|
|
any future detection model, with no migration when that day comes.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import uuid
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import (
|
|
BigInteger,
|
|
Boolean,
|
|
CheckConstraint,
|
|
Column,
|
|
DateTime,
|
|
Float,
|
|
ForeignKey,
|
|
Index,
|
|
Integer,
|
|
String,
|
|
Table,
|
|
Text,
|
|
Uuid,
|
|
func,
|
|
)
|
|
from sqlalchemy.dialects.postgresql import JSONB
|
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
|
|
from .base import Base
|
|
|
|
# API.md sends 'radar'; SPEC 3 predates the LD2410 decision and says 'pir'.
|
|
TRIGGERS = ("radar", "manual", "timer", "stream_grab")
|
|
|
|
|
|
class Capture(Base):
|
|
__tablename__ = "captures"
|
|
__table_args__ = (
|
|
CheckConstraint("trigger IN " + str(TRIGGERS), name="trigger_valid"),
|
|
Index("ix_captures_device_received", "device_id", "received_at"),
|
|
Index("ix_captures_burst", "burst_id", "burst_index"),
|
|
Index("ix_captures_triage", "kept", "reviewed", "received_at"),
|
|
)
|
|
|
|
# UUID rather than a serial, because it is also the filename:
|
|
# /srv/poorbird/images/2026/09/08/<uuid>.jpg (SPEC 3.3).
|
|
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
|
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
|
|
|
|
path: Mapped[str] = mapped_column(Text)
|
|
thumb_path: Mapped[str | None] = mapped_column(Text)
|
|
sha256: Mapped[str] = mapped_column(String(64), index=True)
|
|
width: Mapped[int | None] = mapped_column(Integer)
|
|
height: Mapped[int | None] = mapped_column(Integer)
|
|
bytes: Mapped[int] = mapped_column(BigInteger)
|
|
|
|
# NULL when the device clock was unsynced. X-Captured-At: 0 means unsynced,
|
|
# NOT 1970 -- never store an epoch date for it (API.md).
|
|
captured_at_device: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
# SPEC C7: authoritative, always.
|
|
received_at: Mapped[datetime] = mapped_column(
|
|
DateTime(timezone=True), server_default=func.now()
|
|
)
|
|
|
|
trigger: Mapped[str] = mapped_column(String(16))
|
|
burst_id: Mapped[str | None] = mapped_column(String(64))
|
|
burst_index: Mapped[int | None] = mapped_column(Integer)
|
|
burst_count: Mapped[int | None] = mapped_column(Integer)
|
|
# SPEC 0 / API.md: this frame was captured BEFORE the trigger fired, out of
|
|
# the PSRAM ring. Usually the good ones -- the bird is still arriving.
|
|
pre_trigger: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
|
|
frame_seq: Mapped[int | None] = mapped_column(Integer)
|
|
|
|
radar_state: Mapped[int | None] = mapped_column(Integer) # 0 none 1 moving 2 stationary 3 both
|
|
radar_distance_cm: Mapped[int | None] = mapped_column(Integer)
|
|
radar_energy: Mapped[int | None] = mapped_column(Integer)
|
|
|
|
battery_mv: Mapped[int | None] = mapped_column(Integer)
|
|
rssi: Mapped[int | None] = mapped_column(Integer)
|
|
temp_c: Mapped[float | None] = mapped_column(Float)
|
|
|
|
reviewed: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
|
|
# Soft reject. Drives retention -- see TODO Phase 5 and open question 8.
|
|
kept: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
|
|
|
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
|
|
observations: Mapped[list[Observation]] = relationship(
|
|
back_populates="capture", cascade="all, delete-orphan"
|
|
)
|
|
tags: Mapped[list[Tag]] = relationship(secondary="capture_tags", back_populates="captures")
|
|
|
|
|
|
class Observation(Base):
|
|
__tablename__ = "observations"
|
|
__table_args__ = (
|
|
CheckConstraint("age IN ('adult', 'juvenile', 'unknown')", name="age_valid"),
|
|
CheckConstraint("sex IN ('male', 'female', 'unknown')", name="sex_valid"),
|
|
CheckConstraint(
|
|
"behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')",
|
|
name="behaviour_valid",
|
|
),
|
|
CheckConstraint(
|
|
"certainty IN ('certain', 'probable', 'uncertain')", name="certainty_valid"
|
|
),
|
|
CheckConstraint("source IN ('human', 'model')", name="source_valid"),
|
|
)
|
|
|
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
capture_id: Mapped[uuid.UUID] = mapped_column(
|
|
ForeignKey("captures.id", ondelete="CASCADE"), index=True
|
|
)
|
|
taxon_id: Mapped[int | None] = mapped_column(ForeignKey("taxa.id", ondelete="RESTRICT"))
|
|
|
|
individuals: Mapped[int] = mapped_column(Integer, default=1, server_default="1")
|
|
age: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'")
|
|
sex: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'")
|
|
behaviour: Mapped[str | None] = mapped_column(String(16))
|
|
certainty: Mapped[str] = mapped_column(
|
|
String(16), default="certain", server_default="'certain'"
|
|
)
|
|
notes: Mapped[str | None] = mapped_column(Text)
|
|
|
|
source: Mapped[str] = mapped_column(String(8), default="human", server_default="'human'")
|
|
# Populated only when source = 'model'. Schema is ready; the pipeline is
|
|
# explicitly not built (SPEC Option C).
|
|
model_version: Mapped[str | None] = mapped_column(String(64))
|
|
confidence: Mapped[float | None] = mapped_column(Float)
|
|
bbox: Mapped[dict | None] = mapped_column(JSONB)
|
|
|
|
created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
|
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
updated_at: Mapped[datetime] = mapped_column(
|
|
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
|
)
|
|
|
|
capture: Mapped[Capture] = relationship(back_populates="observations")
|
|
taxon: Mapped[Taxon | None] = relationship()
|
|
|
|
|
|
class Taxon(Base):
|
|
"""Seeded, never free text.
|
|
|
|
This is what makes "species, biologically" real rather than a string
|
|
column that accumulates Kohlmeise, kohlmeise, Parus major and Kohlmeise?
|
|
as four distinct species (SPEC 3.2).
|
|
"""
|
|
|
|
__tablename__ = "taxa"
|
|
|
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
gbif_key: Mapped[int | None] = mapped_column(BigInteger, unique=True)
|
|
scientific_name: Mapped[str] = mapped_column(String(128), unique=True)
|
|
name_de: Mapped[str | None] = mapped_column(String(128), index=True)
|
|
name_en: Mapped[str | None] = mapped_column(String(128), index=True)
|
|
family: Mapped[str | None] = mapped_column(String(64))
|
|
# "order" is reserved in SQL; SQLAlchemy quotes it.
|
|
order: Mapped[str | None] = mapped_column("order", String(64))
|
|
iucn_status: Mapped[str | None] = mapped_column(String(8))
|
|
# Ranks the autocomplete. The local garden list comes first.
|
|
is_local_common: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
|
|
|
|
|
|
class Tag(Base):
|
|
__tablename__ = "tags"
|
|
|
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
label: Mapped[str] = mapped_column(String(64), unique=True)
|
|
colour: Mapped[str | None] = mapped_column(String(16))
|
|
|
|
captures: Mapped[list[Capture]] = relationship(secondary="capture_tags", back_populates="tags")
|
|
|
|
|
|
capture_tags = Table(
|
|
"capture_tags",
|
|
Base.metadata,
|
|
Column("capture_id", ForeignKey("captures.id", ondelete="CASCADE"), primary_key=True),
|
|
Column("tag_id", ForeignKey("tags.id", ondelete="CASCADE"), primary_key=True),
|
|
)
|