Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090)

This commit is contained in:
Thomas Karner committed 2026-09-20 23:49:40 +02:00
1 parent 3694cdf207
commit 8a51e3d95e
38 files changed
+2442 -21

No files matched your search

+190
View File
@@ -0,0 +1,190 @@
"""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,
DateTime,
Float,
ForeignKey,
Index,
Integer,
String,
Table,
Text,
Column,
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),
)