Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ jobs:
run: pip install -r tests/requirements.txt

- name: launch tests
run: pytest tests/*
run: pytest tests --ignore=tests/e2e

- name: Capture logs
if: always()
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ data/images/
data/models/
# Written by init_script at the end of a successful run
data/.init_done
# Touched by the engine container (./data is mounted)
data/heartbeat
# Written by make e2e
e2e-artifacts/
*.pem
# Byte-compiled / optimized / DLL files
__pycache__/
Expand Down
33 changes: 29 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ help:
@echo " build Build local images in this repo"
@echo " build-external Build images in sibling repos"
@echo " build-all Build local and external images"
@echo " build-e2e Build only the local images the e2e needs (no notebooks)"
@echo " fetch-scenario Download scenario images (SCENARIO=smoke-then-clear)"
@echo " run-backend Start base services only"
@echo " run-camera Start only the fake cameras, to work on pyro-engine"
Expand All @@ -21,7 +22,8 @@ help:
@echo " stop Stop and remove all services and volumes"
@echo " ps Show compose status"
@echo " logs Follow logs"
@echo " test Run pytest"
@echo " test Run the unit tests"
@echo " e2e Fresh stack, then the end-to-end tests (SCENARIO=smoke-then-clear), artifacts in e2e-artifacts/"

# -------------------------------------------------------------------
# Init
Expand All @@ -40,6 +42,11 @@ build: fetch-scenario
docker build -f containers/notebooks/Dockerfile -t pyronear/notebooks:latest containers/notebooks/
docker build --build-context scenarios=data/scenarios -f containers/fake_camera/Dockerfile -t pyronear/fake-camera:latest containers/fake_camera/

# Same images as `build` minus notebooks, which the e2e does not run.
build-e2e: fetch-scenario
docker build -f containers/init_script/Dockerfile -t pyronear/pyro-api-init:latest containers/init_script/
docker build --build-context scenarios=data/scenarios -f containers/fake_camera/Dockerfile -t pyronear/fake-camera:latest containers/fake_camera/

# -------------------------------------------------------------------
# Build images from sibling repositories
# -------------------------------------------------------------------
Expand All @@ -62,11 +69,12 @@ run-backend:
# Fake camera scenarios: definitions are in data/scenarios/<name>/scenario.json,
# images come from the "scenarios" GitHub release.
SCENARIO ?= smoke-then-clear
SCENARIOS_URL = https://github.com/pyronear/pyro-envdev/releases/download/scenarios
export SCENARIO
SCENARIOS_URL ?= https://github.com/pyronear/pyro-envdev/releases/download/scenarios
# Downloads unless every camera of scenario.json already has frames.
fetch-scenario:
@python3 -c "import glob, json, sys; d = 'data/scenarios/$(SCENARIO)'; \
sys.exit(any(not glob.glob(f'{d}/{c}/*.jpg') for c in json.load(open(f'{d}/scenario.json'))['cameras']))" || \
sys.exit(any(not glob.glob(f'{d}/{c}/**/*.jpg', recursive=True) for c in json.load(open(f'{d}/scenario.json'))['cameras']))" || \
(curl -fsSL $(SCENARIOS_URL)/$(SCENARIO).zip -o /tmp/$(SCENARIO).zip && \
unzip -oq /tmp/$(SCENARIO).zip -x '*/scenario.json' -d data/scenarios && rm /tmp/$(SCENARIO).zip)

Expand Down Expand Up @@ -122,4 +130,21 @@ logs:
# -------------------------------------------------------------------

test:
pytest -s tests/*
pytest -s tests --ignore=tests/e2e -m "not integration"

# End-to-end: fresh stack (data/ is a bind mount, so the init marker survives `down -v`),
# then the tests. Whatever fails, ps and the logs are dumped to e2e-artifacts/ and make
# exits with the failing step's code. The stack is left up for debugging, `make stop` cleans.
e2e:
$(MAKE) stop
rm -f data/.init_done
$(MAKE) init build-e2e
rm -rf e2e-artifacts && mkdir -p e2e-artifacts
@rc=0; \
docker compose --profile front --profile engine up -d --wait || rc=$$?; \
if [ $$rc -eq 0 ]; then \
uv run --python 3.12 --with-requirements tests/requirements.txt pytest tests/e2e --junitxml=e2e-artifacts/junit.xml -ra --tb=short || rc=$$?; \
fi; \
docker compose ps -a > e2e-artifacts/ps.txt 2>&1; \
docker compose --profile front --profile engine logs --no-color > e2e-artifacts/compose.log 2>&1; \
exit $$rc
28 changes: 23 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ make run

```bash
make build
make run-all
make run
make run-engine
```

This launches everything, including the engine and the fake cameras playing the
Expand Down Expand Up @@ -88,6 +89,14 @@ docker compose logs -f engine

---

## 🧪 End-to-end tests

`make e2e SCENARIO=<name>` tears the stack down, brings up a fresh one (two fake cameras playing the scenario, the real camera API, engine, pyro-api and the frontend) and runs the pytest suite in `tests/e2e/` against it. It needs Docker and [`uv`](https://docs.astral.sh/uv/), and leaves the stack running afterwards for debugging (`make stop` cleans it).

Whatever the outcome, `e2e-artifacts/` holds `junit.xml` (which assertion failed, open it first), `compose.log` (engine, camera API and fake camera logs) and `ps.txt` (container states). A run rewrites the tracked `data/credentials.json`, since init writes the camera tokens into it: do not commit that change. Scenarios need a fresh stack, because the API groups detections of the same pose for 2 hours, which is why `make e2e` always starts from `make stop`.

---

## 🔑 Access

* **API**: [http://localhost:5050/docs](http://localhost:5050/docs)
Expand Down Expand Up @@ -120,8 +129,8 @@ certificate, so the real `pyro_camera_api` and `engine` run against them unchang
images shown one after the other, the last image being held forever. Each preset moves to
its next image on its next visit by the patrol (the first `Snap` after a `ToPos`), so the
engine sees every image once per preset, in order, whatever its timing; snaps taken in place,
like the autofocus ones, see the same image. Every preset of a camera serves the same images
for now.
like the autofocus ones, see the same image. A preset can have its own images (see
Scenario format), otherwise it plays the camera's.

```bash
make run-engine # engine + camera API + fake cameras
Expand All @@ -133,11 +142,15 @@ Scenarios:

* `smoke-then-clear` (default): real wildfire seen by both cameras, 40 frames of smoke then a clear view
* `never-smoke`: both cameras hold a clear view
* `smoke-one-camera`: smoke on preset 3 of `croix-augas-01` only, every other pose clear (one alert expected)
* `false-positive`: false positives from the pyro-dataset val set, YOLO fires but the temporal model rejects them (no alert expected with temporal validation)

`make fetch-scenario` downloads from the `scenarios` release by default, `SCENARIOS_URL=<url>` points it at another release.

`GET https://localhost:8443/scenario` (8444 for `fakecam-2`) reports the camera state:
current preset and azimuth, its frame index and `finished` once every visited preset shows the
last frame.
current preset and azimuth, its frame index and `finished` once every preset declared in
`poses` shows its last frame (a preset never visited is not finished). A `presets` block gives the
visits, frame and frames of each preset.

The image embeds `smoke-then-clear`, so it also runs alone, without the `data/scenarios`
volume (used by pi-manager-template on a test station).
Expand All @@ -157,8 +170,13 @@ data/scenarios/smoke-then-clear/
scenario.json # {"cameras": {"<name>": {"poses": {"<preset>": <azimuth>}}}}
croix-augas-01/ # frames of fakecam-1, in order: 000.jpg, 001.jpg, ...
nemours-02/ # frames of fakecam-2
croix-augas-01/3/ # optional: frames of preset 3 only (key of "poses"), 000.jpg, ...
```

A preset without a folder plays the camera-level frames; a preset with neither makes the
fake camera refuse to start. `--preset 3` of `make_scenario.py` writes into `<camera>/3/` the
sequence seen on the pose whose `patrol_id` is 3 in the alert.

Camera names and presets match `data/csv/API_DATA_DEV - cameras.csv` / `poses.csv`, so
the init script gives each fake camera its token and the engine finds its poses.

Expand Down
81 changes: 63 additions & 18 deletions containers/fake_camera/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@
Answers the Reolink HTTP API (``/cgi-bin/api.cgi?cmd=...``) the way the real
``pyro_camera_api`` Reolink adapter expects, serving the frames of a scenario.
One process is one camera: ``SCENARIO`` and ``CAMERA`` select
``<SCENARIOS_DIR>/<SCENARIO>/<CAMERA>/*.jpg`` (sorted, last frame held).
Each preset moves to its next frame on its next visit: the first Snap after a
ToPos, so snaps taken in place (autofocus) see the same frame. A camera never
positioned (static) moves on every Snap.
``<SCENARIOS_DIR>/<SCENARIO>/<CAMERA>/``. A preset (a key of ``poses`` in
``scenario.json``) plays the frames of ``<CAMERA>/<preset>/*.jpg`` (sorted, last
frame held), or else the camera-level ``<CAMERA>/*.jpg``, so a scenario can put
smoke on one pose only. Each preset keeps its own position: it moves to its next
frame on its next visit, the first Snap after a ToPos, so snaps taken in place
(autofocus) see the same frame. A camera never positioned (static) plays the
camera-level frames and moves on every Snap.

``GET /scenario`` is not part of the Reolink API: it reports the camera state
(preset, azimuth, frame, finished) so tests know where the scenario is.
(scenario, preset, azimuth, frame and frames of the current preset, finished,
and visits, frame and frames of every declared preset) so tests know where the
scenario is. ``finished`` means every declared preset is on its last frame, a
preset never visited counting as not finished.
"""

import json
Expand Down Expand Up @@ -44,48 +50,86 @@ def reply(cmd, value=None, error=None):


class Camera:
def __init__(self, scenario_dir, name):
def __init__(self, scenario_dir, name, scenario=None):
meta = json.loads((scenario_dir / "scenario.json").read_text())
self.name = name
self.scenario = scenario # reported by /scenario
# preset id -> real-world azimuth, informational only (see /scenario)
self.azimuths = {
int(k): float(v) for k, v in meta["cameras"][name]["poses"].items()
}
# ponytail: every preset serves the same frames; per-preset folders if needed
self.frames = sorted((scenario_dir / name).glob("*.jpg"))
if not self.frames:
camera_dir = scenario_dir / name
# Camera-level frames: the fallback of a preset without a folder, and what a
# Snap sees before any ToPos (a static camera).
self.frames = sorted(camera_dir.glob("*.jpg"))
# preset id -> its own frames, or the camera-level ones
self.preset_frames = {}
for preset in self.azimuths:
own = sorted((camera_dir / str(preset)).glob("*.jpg"))
if not (own or self.frames):
raise SystemExit(
f"no frames for scenario {scenario or scenario_dir.name}, "
f"camera {name}, preset {preset}: expected "
f"{camera_dir / str(preset)}/*.jpg or {camera_dir}/*.jpg, "
"run `make fetch-scenario` first"
)
self.preset_frames[preset] = own or self.frames
if not self.preset_frames and not self.frames:
raise SystemExit(
f"no frames in {scenario_dir / name}, run `make fetch-scenario` first"
f"no frames in {camera_dir}, run `make fetch-scenario` first"
)
if not self.frames:
# A Snap before any ToPos has no camera-level frames: use the first preset's
self.frames = self.preset_frames[min(self.preset_frames)]
self.lock = threading.Lock()
self.preset = None # unknown until a ToPos; stays None on a static camera
self.visits = {} # preset -> visits that took a Snap
self.arrived = True # the next Snap is the first at the current position
self.enabled = set(self.azimuths)
self.zoom, self.focus, self.autofocus_disabled = 0, 720, 0

def _frames(self, preset):
return self.preset_frames.get(preset, self.frames)

def _frame(self, preset):
return frame_index(self.visits.get(preset, 0), len(self.frames))
return frame_index(self.visits.get(preset, 0), len(self._frames(preset)))

def _on_last_frame(self, preset):
return self.visits.get(preset, 0) >= len(self._frames(preset))

def snap(self):
with self.lock:
if self.arrived or self.preset is None:
self.visits[self.preset] = self.visits.get(self.preset, 0) + 1
self.arrived = False
return self.frames[self._frame(self.preset)].read_bytes()
return self._frames(self.preset)[self._frame(self.preset)].read_bytes()

def status(self):
with self.lock:
return {
"scenario": self.scenario,
"camera": self.name,
"preset": self.preset,
"azimuth": self.azimuths.get(self.preset),
"frame": self._frame(self.preset),
"frames": len(self.frames),
"finished": bool(self.visits)
and all(self._frame(p) == len(self.frames) - 1 for p in self.visits),
"frames": len(self._frames(self.preset)),
"finished": self._finished(),
"presets": {
str(p): {
"visits": self.visits.get(p, 0),
"frame": self._frame(p),
"frames": len(self._frames(p)),
}
for p in sorted(self.preset_frames)
},
}

def _finished(self):
if self.preset_frames:
# Snaps before any ToPos (preset None) neither block nor trigger this
return all(self._on_last_frame(p) for p in self.preset_frames)
return bool(self.visits) and all(self._on_last_frame(p) for p in self.visits)

def command(self, cmd, param):
with self.lock:
if cmd == "PtzCtrl":
Expand Down Expand Up @@ -207,6 +251,7 @@ def main():
camera = Camera(
Path(os.environ.get("SCENARIOS_DIR", "/scenarios")) / scenario,
os.environ["CAMERA"],
scenario,
)
port = int(os.environ.get("PORT", "443"))
here = Path(__file__).parent
Expand All @@ -219,11 +264,11 @@ def main():
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
logging.info(
"fake camera %s plays scenario %s: "
"%d frames, one per preset visit, presets %s, port %d",
"one frame per preset visit, frames per preset %s, port %d",
camera.name,
scenario,
len(camera.frames),
sorted(camera.enabled),
{p: len(f) for p, f in sorted(camera.preset_frames.items())}
or len(camera.frames),
port,
)
httpd.serve_forever()
Expand Down
5 changes: 5 additions & 0 deletions data/scenarios/never-smoke/scenario.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@
"cameras": {
"croix-augas-01": {"poses": {"1": 326.5, "2": 13.2, "3": 59.8}},
"nemours-02": {"poses": {"0": 245.9, "1": 292.4, "2": 339.4, "3": 25.4}}
},
"expected": {
"alerts": 0,
"sequences": [],
"timeout_s": 600
}
}
13 changes: 13 additions & 0 deletions data/scenarios/smoke-one-camera/scenario.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"description": "Smoke on preset 3 of croix-augas-01 only (18 frames of prod alert 49767, then a clear view held forever), every other pose of both cameras holds a clear view. Expected: exactly one alert, from one sequence on that pose.",
"cameras": {
"croix-augas-01": {"poses": {"1": 326.5, "2": 13.2, "3": 59.8}},
"nemours-02": {"poses": {"0": 245.9, "1": 292.4, "2": 339.4, "3": 25.4}}
},
"expected": {
"alerts": 1,
"sequences": [{"camera": "croix-augas-01", "preset": "3", "min_detections": 7}],
"location": null,
"timeout_s": 900
}
}
13 changes: 13 additions & 0 deletions data/scenarios/smoke-then-clear/scenario.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,18 @@
"cameras": {
"croix-augas-01": {"poses": {"1": 326.5, "2": 13.2, "3": 59.8}},
"nemours-02": {"poses": {"0": 245.9, "1": 292.4, "2": 339.4, "3": 25.4}}
},
"expected": {
"alerts": 5,
"sequences": [
{"camera": "croix-augas-01", "preset": "1", "min_detections": 15},
{"camera": "croix-augas-01", "preset": "2", "min_detections": 15},
{"camera": "croix-augas-01", "preset": "3", "min_detections": 15},
{"camera": "nemours-02", "preset": "0", "min_detections": 15},
{"camera": "nemours-02", "preset": "1", "min_detections": 15},
{"camera": "nemours-02", "preset": "2", "min_detections": 15},
{"camera": "nemours-02", "preset": "3", "min_detections": 15}
],
"timeout_s": 2400
}
}
6 changes: 6 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ services:
pyro_api:
container_name: api
image: pyronear/alert-api:latest
# No arm64 manifest on Docker Hub (Apple Silicon runs it emulated)
platform: linux/amd64
command: "sh -c 'alembic upgrade head && python app/db.py && uvicorn app.main:app --reload --host 0.0.0.0 --port 5050 --proxy-headers'"
ports:
- 5050:5050
Expand Down Expand Up @@ -164,6 +166,8 @@ services:
temporal_model_api:
container_name: temporal_model_api
image: pyronear/temporal-model-api:latest
# No arm64 manifest on Docker Hub (Apple Silicon runs it emulated)
platform: linux/amd64
profiles:
- temporal
ports:
Expand Down Expand Up @@ -213,6 +217,8 @@ services:
condition: service_healthy
frontend:
image: pyronear/pyro-platform-react:latest
# Image is amd64 only (Apple Silicon runs it emulated)
platform: linux/amd64
profiles:
- front
ports:
Expand Down
7 changes: 7 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[pytest]
testpaths = tests
pythonpath = .
addopts = --strict-markers
markers =
e2e: needs the whole compose stack (make e2e)
integration: needs a running service such as the fake camera or the database
Loading