diff --git a/src/cpp/.dockerignore b/src/cpp/.dockerignore index 536dd3f..b7fd387 100644 --- a/src/cpp/.dockerignore +++ b/src/cpp/.dockerignore @@ -6,6 +6,7 @@ __pycache__ **/*.pyc **/*.so build +demo media .local *.log diff --git a/src/cpp/Dockerfile b/src/cpp/Dockerfile index a55e50a..60e4746 100644 --- a/src/cpp/Dockerfile +++ b/src/cpp/Dockerfile @@ -45,14 +45,3 @@ EXPOSE 8000 HEALTHCHECK --interval=30s --timeout=3s --start-period=60s \ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)" || exit 1 CMD ["uvicorn", "rkapi.app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--limit-concurrency", "16"] - -# The catalog selects weights and adapter; no Dockerfile edit per new model. -FROM build AS package -COPY rkapi /source/rkapi -COPY tools/models.py /source/tools/models.py -COPY models /source/models -ARG MODEL_ID -RUN python3 tools/models.py prepare --model "$MODEL_ID" --output /model-package - -FROM runtime AS model -COPY --from=package /model-package/ /opt/model/ diff --git a/src/cpp/Dockerfile.video b/src/cpp/Dockerfile.video new file mode 100644 index 0000000..d93ca78 --- /dev/null +++ b/src/cpp/Dockerfile.video @@ -0,0 +1,3 @@ +ARG RUNTIME_IMAGE=rockchip-cv-runtime:local +FROM ${RUNTIME_IMAGE} +ADD --link video.tar / diff --git a/src/cpp/README.md b/src/cpp/README.md index c4ae712..83c1462 100644 --- a/src/cpp/README.md +++ b/src/cpp/README.md @@ -107,12 +107,12 @@ if metadata["model"]["task"] == "detection": ## Models YOLO26 ships in sizes `n`, `s`, and `m` for RK3576 and RK3588, with -INT8 and FP16 builds for all seven tasks. Each image serves one model. +INT8 and FP16 builds for all seven tasks. Each image serves one model and includes a short demo video. The catalog contains 84 variants across 21 image names. All images built from the same code revision share the same ARM64 operating -system, dependencies, C++ engine, HTTP API, and browser code. Only the final -filesystem layer contains model-specific files. The common entrypoint loads +system, dependencies, C++ engine, HTTP API, and browser code. The final filesystem layer contains model-specific files. A separate layer contains +the selected demo video and its attribution. The common entrypoint loads the model manifest bundled at `/opt/model/package.json`. Image names below use the prefix `ghcr.io/seeed-projects/recomputer-rk-cv/`. @@ -208,9 +208,9 @@ the client to include transport and response delivery. | Environment variable | Default | Purpose | | --- | --- | --- | | `RK_NMS` | Model setting | Enable or disable server NMS with `on` or `off` | -| `RK_SOURCE` | Unset | RTSP URL, mounted video file, or H.264 V4L2 device | -| `RK_LOOP_VIDEO` | `0` | Set to `1` for the browser-rendered local MP4 detection demo | -| `RK_WORKERS` | `0` | Automatic live worker count, or `1` for a single context | +| `RK_SOURCE` | Bundled demo video | Override with an RTSP URL, mounted video file, or H.264 V4L2 device. Set to an empty string to disable live preview. | +| `RK_LOOP_VIDEO` | `1` for the bundled demo, otherwise `0` | Set to `1` for looping, browser-rendered playback of a local MP4 | +| `RK_WORKERS` | `0` | Use all NPU cores with dedicated workers, two on RK3576 and three on RK3588. Set to `1` for one context. | | `RK_MAX_UPLOAD_MB` | `128` | Maximum upload size in MB | | `RK_CLASSES` | Packaged labels | Override labels with one class per line | | `RK_PACKAGE` | `/opt/model/package.json` | Model package manifest path | @@ -224,22 +224,24 @@ provide a usable frame. ## Video -For continuous prediction, add `-e RK_SOURCE=rtsp://192.168.1.10/live` to -the Docker run command. For a local video, pass -`-v "$PWD/media:/media:ro" -e RK_SOURCE=/media/input.mp4`. -An H.264 V4L2 camera can use `-e RK_SOURCE=/dev/video0`. - -Continuous H.264/H.265 sources use MPP hardware decoding. Once a frame is -ready, open `http://:8000` to watch the annotated feed and -adjust confidence and NMS IoU. Threshold changes also update the container's -API defaults. Use a detection image such as `yolo26n:rk3576-int8` for the live preview. - -For smooth playback of a mounted H.264 MP4 with an object detection model, -also pass `-e RK_LOOP_VIDEO=1`. The board loops the file and publishes -timestamped detection results. The browser plays the original MP4 and draws -boxes on a canvas, so playback can run at the video's frame rate even when -inference produces fewer results. The MP4 should use landscape or portrait -dimensions encoded directly, without a rotation tag. +Open `http://:8000` to play the bundled clip and view the model's +output. The first live-stream subscriber starts the decoder and NPU workers. +The last disconnect stops them. Reading the page or checking `/health` does +not start inference. Image or video-frame uploads still run on demand. +`/health` reports whether the pipeline is active, the subscriber count, and +the worker count and core masks when running. + +| Tasks | Bundled clip | +| --- | --- | +| Detection, classification, instance segmentation, semantic segmentation, depth | Street traffic with moving vehicles and foreground/background separation | +| Pose | A full-body squat demonstration | +| Oriented boxes | Aerial footage of boats at different angles | + +The browser plays the H.264 MP4 and draws model results on a canvas. For a +custom clip, pass `-v "$PWD/input.mp4:/media/input.mp4:ro"` with +`-e RK_SOURCE=/media/input.mp4 -e RK_LOOP_VIDEO=1`. Use a browser-compatible +MP4 without a rotation tag. RTSP and H.264 V4L2 sources still use the MJPEG +preview with the source selected through `RK_SOURCE`. With a YOLO26 split scores-and-boxes model, the browser applies confidence filtering and per-class NMS locally. The board sends every valid decoded @@ -255,37 +257,27 @@ six `float32` values per proposal in the order `x1, y1, x2, y2, confidence, class_id`. Box coordinates are in source-image pixels. Use the label list from `GET /api/metadata`. -Call `curl -fsS -X POST "$API/api/predict"` for the latest result or use -`/api/video_feed` directly for the 10 FPS MJPEG preview. Local files follow -media timestamps from container startup and retain the last result at EOF -when looping is disabled. +Call `curl -fsS -X POST "$API/api/predict"` for the latest result while a +preview stream is subscribed. `/api/video_feed` serves the 10 FPS MJPEG +preview and holds a live-source subscription. ## Build and publish ### Build locally Run these commands in `src/cpp` on an ARM64 Docker host. Inference requires -the matching Rockchip board. +the matching Rockchip board. Leave out `--model` to build the full catalog. ```sh python3 tools/models.py list - -docker build --platform linux/arm64 --target model \ - --build-arg MODEL_ID=yolo26n-rk3588-int8 \ - -t yolo26n:rk3588-int8 . -``` - -Set `IMAGE=yolo26n:rk3588-int8` in the quick-start command to run the local -image. To build several model images from exactly the same local runtime, use -the same packaging script as CI. Leave out `--model` to build the full catalog. - -```sh docker build --platform linux/arm64 --target runtime -t rockchip-cv-runtime:local . python3 -m pip install PyYAML python3 tools/build_images.py --runtime rockchip-cv-runtime:local \ --repository rockchip-cv-local --model yolo26n-rk3588-int8 ``` +Set `IMAGE=rockchip-cv-local/yolo26n:rk3588-int8` in the quick-start command. + ### GitHub Actions The [C++ Rockchip model images workflow](../../.github/workflows/cpp-model-images.yml) @@ -297,7 +289,10 @@ or the full catalog when left empty. Manual runs on `main` publish images. The workflow saves one shared runtime per source commit under `runtime:`. Each model uses it as the base, verifies the model package and native module imports, and checks that its layer list matches the -runtime plus exactly one model layer. Each model is published with a +runtime plus one independent video layer and one model layer. Models that +use the same clip must have the same video layer ID. The workflow builds each video layer once from a deterministic archive. +BuildKit's `ADD --link` keeps the video layer independent so code-only +rebuilds can reuse it. Each model is published with a `-` tag and a `--` tag. Each manifest points to an immutable Hugging Face revision. The build @@ -314,3 +309,7 @@ The model packages use weights and conversion metadata from [HanzoHuang/YOLO26-RKNN2](https://huggingface.co/HanzoHuang/YOLO26-RKNN2). Model manifests and metadata record provenance, license information, and the SHA-256 checksums used during packaging. + +The bundled clips were excerpted or resized and converted to H.264 without +audio. Attributions and license links are included in each image at +`/opt/demo/ATTRIBUTION.txt` and in the [demo directory](demo/). diff --git a/src/cpp/demo/.gitattributes b/src/cpp/demo/.gitattributes new file mode 100644 index 0000000..cfbb145 --- /dev/null +++ b/src/cpp/demo/.gitattributes @@ -0,0 +1 @@ +*.mp4 -filter -diff -merge -text diff --git a/src/cpp/demo/exercise.mp4 b/src/cpp/demo/exercise.mp4 new file mode 100644 index 0000000..c4fd765 Binary files /dev/null and b/src/cpp/demo/exercise.mp4 differ diff --git a/src/cpp/demo/exercise.txt b/src/cpp/demo/exercise.txt new file mode 100644 index 0000000..19f4427 --- /dev/null +++ b/src/cpp/demo/exercise.txt @@ -0,0 +1,5 @@ +Squat exercise demonstration by FitnessScape. +Source: https://commons.wikimedia.org/wiki/File:Squat_-_exercise_demonstration_video.webm +Original: https://www.youtube.com/watch?v=0I6q9NqK9tM +License: https://creativecommons.org/licenses/by/3.0/ +Changes: resized and converted to H.264 MP4 without audio. diff --git a/src/cpp/demo/harbor.mp4 b/src/cpp/demo/harbor.mp4 new file mode 100644 index 0000000..70952f5 Binary files /dev/null and b/src/cpp/demo/harbor.mp4 differ diff --git a/src/cpp/demo/harbor.txt b/src/cpp/demo/harbor.txt new file mode 100644 index 0000000..d07121c --- /dev/null +++ b/src/cpp/demo/harbor.txt @@ -0,0 +1,4 @@ +Aerial view of sea and boats. +Source: https://commons.wikimedia.org/wiki/File:Aerial_view_of_sea_and_boats.webm +License: https://creativecommons.org/publicdomain/zero/1.0/ +Changes: excerpted, resized and converted to H.264 MP4 without audio. diff --git a/src/cpp/demo/street.mp4 b/src/cpp/demo/street.mp4 new file mode 100644 index 0000000..c876aa3 Binary files /dev/null and b/src/cpp/demo/street.mp4 differ diff --git a/src/cpp/demo/street.txt b/src/cpp/demo/street.txt new file mode 100644 index 0000000..98ad745 --- /dev/null +++ b/src/cpp/demo/street.txt @@ -0,0 +1,5 @@ +Street traffic in San Francisco by Editor. +Source: https://commons.wikimedia.org/wiki/File:Street_traffic.webm +Original: https://www.youtube.com/watch?v=_7sCYyxw4Ic +License: https://creativecommons.org/licenses/by/3.0/ +Changes: excerpted, resized and converted to H.264 MP4 without audio. diff --git a/src/cpp/native/bindings.cpp b/src/cpp/native/bindings.cpp index 5da8473..b12dadf 100644 --- a/src/cpp/native/bindings.cpp +++ b/src/cpp/native/bindings.cpp @@ -128,6 +128,7 @@ class Predictor } std::string description() const { return detector_.description.dump(); } + bool supports_candidates() const { return detector_.supports_candidates(); } }; class Live @@ -324,7 +325,8 @@ PYBIND11_MODULE(_native, m) py::class_(m, "Predictor") .def(py::init(), py::arg("model"), py::arg("options") = "{}") .def("predict", &Predictor::image, py::call_guard()) - .def("description", &Predictor::description); + .def("description", &Predictor::description) + .def("supports_candidates", &Predictor::supports_candidates); py::class_(m, "Live") .def(py::init(), py::arg("source"), py::arg("model"), py::arg("workers") = 0, py::arg("options") = "{}", diff --git a/src/cpp/rkapi/app.py b/src/cpp/rkapi/app.py index 6f018eb..16504ff 100644 --- a/src/cpp/rkapi/app.py +++ b/src/cpp/rkapi/app.py @@ -7,6 +7,7 @@ from pathlib import Path from time import perf_counter +from anyio import CancelScope import cv2 import numpy as np from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile @@ -214,16 +215,33 @@ def decode(): await upload.close() +class LiveResponse(StreamingResponse): + """Hold one live-source lease until the HTTP stream disconnects.""" + + def __init__(self, runtime, content, **kwargs): + super().__init__(content, **kwargs) + self.runtime = runtime + + async def __call__(self, scope, receive, send): + acquired = False + try: + with CancelScope(shield=True): + await run_in_threadpool(self.runtime.acquire_live) + acquired = True + await super().__call__(scope, receive, send) + except SourceUnavailable as error: + raise HTTPException(503, str(error)) from error + except UnsupportedOperation as error: + raise HTTPException(501, str(error)) from error + finally: + if acquired: + with CancelScope(shield=True): + await run_in_threadpool(self.runtime.release_live) + + @app.get("/api/video_feed") async def video_feed(): rt = app.state.runtime - try: - await run_in_threadpool(rt.preview) - except SourceUnavailable as error: - raise HTTPException(503, str(error)) from error - except UnsupportedOperation as error: - raise HTTPException(501, str(error)) from error - async def frames(): previous = None while True: @@ -243,7 +261,7 @@ async def frames(): break await asyncio.sleep(.05) - return StreamingResponse(frames(), media_type="multipart/x-mixed-replace; boundary=frame", + return LiveResponse(rt, frames(), media_type="multipart/x-mixed-replace; boundary=frame", headers={"Cache-Control": "no-store"}) @@ -276,7 +294,7 @@ async def events(): yield "data: " + json.dumps(result, separators=(",", ":")) + "\n\n" await asyncio.sleep(.015) - return StreamingResponse(events(), media_type="text/event-stream", + return LiveResponse(rt, events(), media_type="text/event-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"}) @@ -299,7 +317,7 @@ async def frames(): previous, data = packet yield data - return StreamingResponse(frames(), media_type="application/octet-stream", + return LiveResponse(rt, frames(), media_type="application/octet-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"}) diff --git a/src/cpp/rkapi/backends/base.py b/src/cpp/rkapi/backends/base.py index a831412..bf99f95 100644 --- a/src/cpp/rkapi/backends/base.py +++ b/src/cpp/rkapi/backends/base.py @@ -37,6 +37,12 @@ def image(self, image, conf, iou, source): in the returned dictionary, not in the shared HTTP layer. """ + def acquire_live(self): + raise UnsupportedOperation("this backend does not support live inference") + + def release_live(self): + pass + def source_status(self): return None diff --git a/src/cpp/rkapi/backends/yolo.py b/src/cpp/rkapi/backends/yolo.py index 60edd00..9d3f2c3 100644 --- a/src/cpp/rkapi/backends/yolo.py +++ b/src/cpp/rkapi/backends/yolo.py @@ -2,6 +2,7 @@ import json import os from pathlib import Path +from threading import Lock from time import perf_counter import cv2 @@ -78,16 +79,53 @@ def __init__(self, package): "output": prediction_output(task, package), } self.live = None - source = os.getenv("RK_SOURCE") - if os.getenv("RK_LOOP_VIDEO") == "1": - path = Path(source or "") - if task != "detection" or path.suffix.lower() != ".mp4" or not path.is_file(): - raise ValueError("RK_LOOP_VIDEO requires a detection model and a local MP4 as RK_SOURCE") + self.live_lock = Lock() + self.viewers = 0 + self.model = model + self.model_options = encoded_options + self.workers = int(os.getenv("RK_WORKERS", "0")) + if self.workers not in (0, 1): + raise ValueError("RK_WORKERS must be 0 (auto) or 1") + bundled = Path("/opt/demo/input.mp4") + override = os.getenv("RK_SOURCE") + self.source = str(bundled) if override is None and bundled.is_file() else override + loop = os.getenv("RK_LOOP_VIDEO", "1" if override is None and self.source else "0") + if loop == "1": + path = Path(self.source or "") + if path.suffix.lower() != ".mp4" or not path.is_file(): + raise ValueError("RK_LOOP_VIDEO requires a local MP4 as RK_SOURCE") self.demo_video = path.resolve() - if source: - self.live = _native.Live(source, model, int(os.getenv("RK_WORKERS", "0")), - encoded_options, loop_file=self.demo_video is not None) - self.description["live"] = json.loads(self.live.description()) + if self.source: + self.description["live"] = { + "candidate_stream": self.demo_video is not None and self.predictor.supports_candidates() + } + + def acquire_live(self): + with self.live_lock: + if not self.source: + raise SourceUnavailable("configure RK_SOURCE for realtime predictions") + if self.live is None: + try: + live = _native.Live(self.source, self.model, self.workers, + self.model_options, loop_file=self.demo_video is not None) + except RuntimeError as error: + raise SourceUnavailable(str(error)) from error + try: + with self.config_lock: + live.configure(self.config["obj_thresh"], self.config["nms_thresh"]) + self.description["live"] = json.loads(live.description()) + except Exception: + live.close() + raise + self.live = live + self.viewers += 1 + + def release_live(self): + with self.live_lock: + self.viewers -= 1 + if self.viewers == 0: + self.live.close() + self.live = None def response(self, raw, source): predictions = [] @@ -174,9 +212,12 @@ def preview(self): return state, jpeg def source_status(self): - if not self.live: - return None - return json.loads(self.live.state()) + with self.live_lock: + if not self.source: + return None + if self.live is None: + return {"active": False, "viewers": 0, "error": "", "ended": False, "dropped": 0} + return {"active": True, "viewers": self.viewers} | json.loads(self.live.state()) def live_result(self, after=0): if not self.live: @@ -192,7 +233,8 @@ def demo_result(self, after): return None result = self.response(raw, "realtime") return {key: raw[key] for key in ("frame", "media_time", "cycle")} | { - "predictions": result["predictions"], "image": result["image"]} + key: result[key] for key in ("predictions", "image", "classification", "semantic", "depth") + if key in result} def demo_candidates(self, after): try: @@ -201,17 +243,22 @@ def demo_candidates(self, after): raise SourceUnavailable(str(error)) from error def predict_realtime(self, conf, iou): - if self.live_result() is None: - raise SourceUnavailable("live source has no frame yet") - raw = self.live.predict(self.predictor, conf, iou) + with self.live_lock: + if self.live is None: + raise SourceUnavailable("open a preview stream to start live inference") + if self.live_result() is None: + raise SourceUnavailable("live source has no frame yet") + raw = self.live.predict(self.predictor, conf, iou) return self.response(json.loads(raw), "realtime") def configure(self, values): - with self.config_lock: + with self.live_lock, self.config_lock: self.config.update(values) if self.live: self.live.configure(self.config["obj_thresh"], self.config["nms_thresh"]) def close(self): - if self.live: - self.live.close() + with self.live_lock: + if self.live: + self.live.close() + self.live = None diff --git a/src/cpp/rkapi/demo.html b/src/cpp/rkapi/demo.html index de025b3..ebe5443 100644 --- a/src/cpp/rkapi/demo.html +++ b/src/cpp/rkapi/demo.html @@ -31,6 +31,7 @@ h1 { margin: 1.25rem 0 .25rem; font-size: clamp(2rem, 5vw, 3.75rem); line-height: 1.1; } #model { margin: 0 0 1.25rem; color: var(--muted); } .layout { display: grid; grid-template-columns: minmax(0, 1fr) minmax(15rem, 19rem); gap: 1rem; } + .layout.single { grid-template-columns: minmax(0, 1fr); } .monitor { background: var(--screen); color: #edf6fa; } .feed-bar { min-height: 2.75rem; padding: .5rem 1rem; border-bottom: 1px solid #39505c; } #feed-status { color: #b9ddeb; } @@ -236,6 +237,48 @@

Detection thresholds

return result.predictions = predictions; } + function drawRaster(raster, type, scale, offsetX, offsetY) { + if (!raster.canvas) { + const canvas = document.createElement("canvas"); + canvas.width = raster.width; + canvas.height = raster.height; + const context = canvas.getContext("2d"); + const pixels = context.createImageData(raster.width, raster.height); + let start = 0; + for (let i = 0; i < raster.runs.length; i += 2) { + const value = raster.runs[i], count = raster.runs[i + 1]; + const end = Math.min(start + count, raster.width * raster.height); + if ((type === "mask" && value === 0) || (type === "depth" && value === 65536)) { + start = end; + continue; + } + const shade = type === "depth" ? Math.round(255 * value / 65535) : value * 73 % 256; + const red = type === "mask" ? 38 : shade; + const green = type === "mask" ? 225 : type === "depth" ? 128 : (shade + 89) % 256; + const blue = type === "mask" ? 172 : type === "depth" ? 255 - shade : (shade + 157) % 256; + for (let index = start * 4; index < end * 4; index += 4) { + pixels.data[index] = red; + pixels.data[index + 1] = green; + pixels.data[index + 2] = blue; + pixels.data[index + 3] = 102; + } + start = end; + } + context.putImageData(pixels, 0, 0); + raster.canvas = canvas; + } + const [x1, y1, x2, y2] = raster.box; + drawing.drawImage(raster.canvas, offsetX + x1 * scale, offsetY + y1 * scale, + (x2 - x1) * scale, (y2 - y1) * scale); + } + + function drawCaption(caption, x, y, pixelRatio) { + drawing.fillStyle = "#142733"; + drawing.fillRect(x, y, drawing.measureText(caption).width + 8 * pixelRatio, 17 * pixelRatio); + drawing.fillStyle = "#edf6fa"; + drawing.fillText(caption, x + 4 * pixelRatio, y + 2 * pixelRatio); + } + function drawBoxes(_now, {mediaTime}) { if (!resultsStream) return; const contextWidth = boxes.width; @@ -245,7 +288,7 @@

Detection thresholds

if (latest && Number.isFinite(video.duration) && video.duration > 0) { const position = timeNear(mediaTime, latest.time); const result = results.findLast(item => item.time <= position + .008); - if (result && position - result.time < .15 && performance.now() - latest.received < 700) { + if (result && position - result.time < (browserNms ? .15 : .35) && performance.now() - latest.received < 700) { const scale = Math.min(contextWidth / result.image.width, contextHeight / result.image.height); const offsetX = (contextWidth - result.image.width * scale) / 2; const offsetY = (contextHeight - result.image.height * scale) / 2; @@ -254,16 +297,35 @@

Detection thresholds

drawing.lineWidth = 2 * pixelRatio; drawing.textBaseline = "top"; drawing.strokeStyle = "#a6edcf"; - for (const {box, confidence, class: label} of visiblePredictions(result)) { + if (result.semantic) drawRaster(result.semantic, "semantic", scale, offsetX, offsetY); + if (result.depth) drawRaster(result.depth, "depth", scale, offsetX, offsetY); + for (const [index, prediction] of (result.classification ?? []).slice(0, 3).entries()) { + drawCaption(`${prediction.class} ${Math.round(100 * prediction.confidence)}%`, + offsetX + 8 * pixelRatio, offsetY + (8 + index * 19) * pixelRatio, pixelRatio); + } + for (const {box, confidence, class: label, polygon, keypoints, mask} of visiblePredictions(result)) { const x = offsetX + box.x1 * scale; const y = offsetY + box.y1 * scale; + if (mask) drawRaster(mask, "mask", scale, offsetX, offsetY); + if (polygon?.length) { + drawing.beginPath(); + for (const [px, py] of polygon) drawing.lineTo(offsetX + px * scale, offsetY + py * scale); + drawing.closePath(); + drawing.stroke(); + } else { + drawing.strokeRect(x, y, (box.x2 - box.x1) * scale, (box.y2 - box.y1) * scale); + } const caption = `${label} ${Math.round(100 * confidence)}%`; - drawing.strokeRect(x, y, (box.x2 - box.x1) * scale, (box.y2 - box.y1) * scale); - const captionY = Math.max(y - 17 * pixelRatio, offsetY); - drawing.fillStyle = "#142733"; - drawing.fillRect(x, captionY, drawing.measureText(caption).width + 8 * pixelRatio, 17 * pixelRatio); - drawing.fillStyle = "#edf6fa"; - drawing.fillText(caption, x + 4 * pixelRatio, captionY + 2 * pixelRatio); + drawCaption(caption, x, Math.max(y - 17 * pixelRatio, offsetY), pixelRatio); + if (keypoints) { + drawing.fillStyle = "#a6edcf"; + for (const [px, py, score] of keypoints) { + if (score < .4) continue; + drawing.beginPath(); + drawing.arc(offsetX + px * scale, offsetY + py * scale, 3 * pixelRatio, 0, 2 * Math.PI); + drawing.fill(); + } + } } } } @@ -389,6 +451,12 @@

Detection thresholds

try { const health = await json("./health"); const { live, backend } = health; + const titles = {detection: "Live detection", classify: "Live classification", depth: "Live depth", + obb: "Live oriented boxes", pose: "Live pose", segment: "Live instance segmentation", + semantic: "Live semantic segmentation"}; + document.querySelector("h1").textContent = titles[health.model.task] ?? "Live inference"; + form.hidden = ["classify", "depth", "semantic"].includes(health.model.task); + document.querySelector(".layout").classList.toggle("single", form.hidden); model.textContent = `${health.model.name} / ${health.model.chip.toUpperCase()}`; const clientThresholds = Boolean(health.demo_video && !videoFailed && !live?.error && backend.live?.candidate_stream); @@ -493,6 +561,10 @@

Detection thresholds

} }); + window.addEventListener("pagehide", () => { + stopTimedFeed(); + feed.removeAttribute("src"); + }); refreshFeed(); loadConfig(); diff --git a/src/cpp/tools/build_images.py b/src/cpp/tools/build_images.py index c3fd3af..78561d1 100644 --- a/src/cpp/tools/build_images.py +++ b/src/cpp/tools/build_images.py @@ -6,6 +6,7 @@ import json from pathlib import Path import subprocess +import tarfile import tempfile from models import ROOT, image_references, load_catalog, prepare @@ -20,25 +21,59 @@ def layers(image): image, capture=True).stdout) -def build(spec, reference, runtime, runtime_layers, revision, publish): +DEMO_CLIPS = {"pose": "exercise", "obb": "harbor"} + + +def stage_video(clip, context): + with tarfile.open(context / "video.tar", "w", format=tarfile.USTAR_FORMAT) as archive: + for name in ("opt", "opt/demo"): + directory = tarfile.TarInfo(name) + directory.type = tarfile.DIRTYPE + directory.mode = 0o755 + archive.addfile(directory) + for source, target in ((f"{clip}.mp4", "input.mp4"), (f"{clip}.txt", "ATTRIBUTION.txt")): + source = ROOT / "demo" / source + item = tarfile.TarInfo(f"opt/demo/{target}") + item.mode = 0o644 + item.size = source.stat().st_size + with source.open("rb") as content: + archive.addfile(item, content) + + +def build_video(clip, runtime, runtime_layers, image): + with tempfile.TemporaryDirectory(prefix="rk-video-") as directory: + context = Path(directory) + stage_video(clip, context) + docker("build", "--builder", "default", "--platform", "linux/arm64", + "--quiet", "--pull=false", "--build-arg", f"RUNTIME_IMAGE={runtime}", + "--build-arg", "SOURCE_DATE_EPOCH=0", + "--file", str(ROOT / "Dockerfile.video"), "--tag", image, str(context)) + image_layers = layers(image) + if image_layers[:-1] != runtime_layers: + raise RuntimeError(f"{image} must append exactly one video layer to {runtime}") + print(f"Video layer {clip}: {image_layers[-1]}", flush=True) + return image_layers + + +def build(spec, reference, base, base_layers, revision, publish): image = f"{reference[0]}:{reference[1]}" versioned = f"{image}-{revision}" if revision else None with tempfile.TemporaryDirectory(prefix="rk-model-") as directory: context = Path(directory) prepare(spec, context / "package") docker("build", "--builder", "default", "--platform", "linux/arm64", - "--quiet", "--pull=false", "--build-arg", f"RUNTIME_IMAGE={runtime}", + "--quiet", "--pull=false", "--build-arg", f"RUNTIME_IMAGE={base}", "--file", str(ROOT / "Dockerfile.model"), "--tag", image, str(context)) - image_layers = layers(image) - if image_layers[:-1] != runtime_layers: - raise RuntimeError(f"{image} must append exactly one model layer to {runtime}") + if layers(image)[:-1] != base_layers: + raise RuntimeError(f"{image} must append exactly one model layer to {base}") docker("run", "--rm", "--entrypoint", "python", image, "-c", "import sys; from rkapi import _native; from rkapi.app import app; " "from rkapi.backends.yolo import Backend; " "from rkapi.packages import load_package; " "assert load_package('/opt/model/package.json')['id'] == sys.argv[1]; " + "from pathlib import Path; assert Path('/opt/demo/input.mp4').is_file(); " "app.openapi()", spec["id"]) if versioned: @@ -73,19 +108,31 @@ def main(): parser.error("The runtime image has no filesystem layers") failures = [] - with ThreadPoolExecutor(max_workers=4) as workers: - builds = {} - for spec in selected: - package, tag = references[spec["id"]] - future = workers.submit(build, spec, (f"{args.repository}/{package}", tag), - args.runtime, runtime_layers, args.revision, args.publish) - builds[future] = spec["id"] - for future in as_completed(builds): - try: - future.result() - except (OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as error: - failures.append(builds[future]) - print(f"{builds[future]}: {error}", flush=True) + clips = {DEMO_CLIPS.get(spec["task"], "street") for spec in selected} + bases = {} + with tempfile.TemporaryDirectory(prefix="rk-video-tag-") as tag_scope: + try: + for clip in sorted(clips): + image = f"rockchip-cv-demo-base:{clip}-{Path(tag_scope).name}" + bases[clip] = (image, build_video(clip, args.runtime, runtime_layers, image)) + with ThreadPoolExecutor(max_workers=4) as workers: + builds = {} + for spec in selected: + package, tag = references[spec["id"]] + base, base_layers = bases[DEMO_CLIPS.get(spec["task"], "street")] + future = workers.submit(build, spec, (f"{args.repository}/{package}", tag), + base, base_layers, args.revision, args.publish) + builds[future] = spec["id"] + for future in as_completed(builds): + try: + future.result() + except (OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as error: + failures.append(builds[future]) + print(f"{builds[future]}: {error}", flush=True) + finally: + if bases: + subprocess.run(["docker", "image", "rm", *(base for base, _ in bases.values())], + check=False, stdout=subprocess.DEVNULL) print(f"Verified {len(selected) - len(failures)} of {len(selected)} model images") return 1 if failures else 0