Enrich camera data with a local VLM¶
Analyze frames from a laptop PC and a USB webcam with a local VLM (vision-language model) running on the PC, attach semantic text to them, and distribute that AI-enriched data over the IoT data-distribution platform. The images are not sent to an external cloud, and the analysis runs entirely on the PC.
What you'll do: analyze a webcam image with a local VLM and distribute the generated semantic data (descriptions) over the platform
Prerequisites: Prerequisites (install tools) completed, Docker and Python 3 available, and a USB webcam connected to the PC (the Quickstart stack is not used)
Keep running: nothing needs to be running. §1 starts the publisher, mosquitto and the VLM (Ollama)
What you need: laptop PC + USB webcam + Docker (including the VLM) + Python 3 (a venv with OpenCV)
Time required: approx. 40–60 min (the first model pull takes a while)
Where this page belongs
- This is 3.1 in Part 3 (intelligence integration) (Hands-on).
- Camera capture basics are covered in Detect with a USB webcam (OpenCV).
- This page covers "camera → local VLM → distribute semantic data" as a single flow.
- You can do this page on its own, once the prerequisites are done and you have Docker, Python (a venv with OpenCV) and a USB webcam. You do not need to have finished the Part 2 pages.
- Per-tier projection with a VLM is covered in §12 of Tier by semantic level (VLM and semantic representation / Stage T) in Part 2. It uses the same
--profile vlmVLM and the samedescription_full/description_summaryas §12. You can do §12 and this page in either order. - Previous page: Trace a VLM summary back to the image (C2PA / Stage P, P3)
- Next page: Protect camera images before handing them to AI (local vs cloud)
Goal¶
Instead of distributing raw images, distribute the semantic derivatives a local VLM produces. You generate a detailed description (description_full) and a privacy-scrubbed summary (description_summary), and check a design that preserves privacy and data sovereignty by running the AI locally.
What this page covers¶
- how to embed a local VLM (Ollama) into the platform and generate semantic data from an image
- the idea of distributing "semantic derivatives" rather than raw images
- separating a PII-bearing detailed description from a redacted summary
- that the model used and any degraded steps (
processing_warnings) are auditable
Overview¶
flowchart LR
CAM["USB webcam<br>+ laptop"]
subgraph PUB["publisher (--profile vlm)"]
OL["Ollama (llava/moondream)"]
end
ING["distributed to<br>/platform/ingest"]
CAM -->|"snapshot.jpg"| PUB
PUB -->|"description_full / summary"| ING
Required environment¶
- Docker is available and you can run
docker compose -f infra/docker-compose.yml ...at the top of the course repository - If the IPFS from the Quickstart (run the stack) is still running, stop it first (
cd ~/program/Blockchain_IoT_Marketplace/ipfs && docker compose down); IPFS and the publisher both use port 8080 - a USB webcam is recognized by the PC (trying Detect with a USB webcam (OpenCV) first makes this easier)
- A Python 3 virtual environment at the top of the course repository with OpenCV installed (
cd ~/program/Blockchain_IoT_Marketplace && python3 -m venv .venv && source .venv/bin/activate && pip install "opencv-python<5"). In every new terminal, runsource ~/program/Blockchain_IoT_Marketplace/.venv/bin/activate. With Homebrew Python and similar setups,pip installoutside a venv fails - Docker can use the
--profile vlmprofile (the first model pull downloads several GB)
Shortest path¶
For a first pass, these four steps are enough.
- start the services with
--profile vlmand wait for the model pull - capture a single still image from the webcam
- submit that image to the platform and let the local VLM analyze it
- confirm with
/platform/ingestthat the distributed row carries the semantic data (description_*)
1. Start the services with the VLM¶
The VLM is opt-in. Adding --profile vlm also starts the Ollama service and vlm-pull, which pre-fetches the model. Run this at the top of the course repository (the example below assumes you cloned it under ~/program/).
cd ~/program/Blockchain_IoT_Marketplace
export VLM_BACKEND=ollama
# For a CPU-only laptop, the lightweight moondream is recommended.
# Use llava, the default, if you want higher quality and have time.
export VLM_MODEL=moondream
export IMAGE_REDACTION_BACKEND=opencv
PLATFORM_INGEST_READ_ENABLED=true docker compose -f infra/docker-compose.yml --profile vlm up --build -d \
publisher mosquitto vlm vlm-pull
Wait until vlm-pull finishes fetching the model (first time only, several GB).
docker compose -f infra/docker-compose.yml logs -f vlm-pull
# exit the logs once the pull is complete
Confirm the publisher is up.
curl -s http://localhost:8080/health | jq .
Expected output:
{
"status": "ok",
"service": "publisher"
}
Choosing a model
llava gives richer descriptions but takes several minutes per image on CPU
only. moondream is small (about 1.7 GB) and responds in tens of seconds to a
few minutes even on CPU. Get the flow working with moondream first, then
switch to VLM_MODEL=llava to compare quality. On slow machines, raise
VLM_TIMEOUT_SEC (default 180 s).
2. Capture one frame from the webcam¶
Grab a single still image from the USB webcam and save it as snapshot.jpg. Save the script below as capture_snapshot.py at the top of the course repository (~/program/Blockchain_IoT_Marketplace) and run it there. The script uses OpenCV, so activate the venv from "Required environment".
# capture_snapshot.py
import cv2
cap = cv2.VideoCapture(0) # if you have multiple cameras, try 1, 2, ...
ok, frame = cap.read()
cap.release()
if not ok:
raise SystemExit("Could not capture from the camera (check index / usage)")
cv2.imwrite("snapshot.jpg", frame)
print("saved snapshot.jpg")
cd ~/program/Blockchain_IoT_Marketplace
source .venv/bin/activate
python3 capture_snapshot.py
No camera / cannot open it
You can substitute any JPEG as snapshot.jpg. If capture fails due to camera
index or usage, see the mock mode and troubleshooting in the
Detect with a USB webcam (OpenCV).
3. Get the "meaning" from the local model¶
POST the captured image to the publisher's /semantic/analyze. The local model analyzes it and returns only a structured Semantic Intermediate Representation (SIR) — never the raw pixels. No wallet or VC is required, so you can try it immediately.
cd ~/program/Blockchain_IoT_Marketplace
curl -s -X POST http://localhost:8080/semantic/analyze \
-F "file=@snapshot.jpg" \
-F "source_device_id=laptop-webcam-01" \
| jq '{scene_summary, people, sensitive_regions: [.sensitive_regions[].type], events: [.events[].type], privacy_risk_score, analyzer_version}'
With the default stub, the following fixed values come back regardless of the image. If you start with SEMANTIC_ANALYZER_BACKEND=vision, the values change with the image.
{
"scene_summary": "研究室の入口付近に1人の人物がいる(mock出力)",
"people": {"count": 1, "identities": []},
"sensitive_regions": ["face", "text", "unknown_sensitive"],
"events": ["person_detected"],
"privacy_risk_score": 0.78,
"analyzer_version": "mock-semantic-analyzer/v1"
}
Choosing the analyzer
The default is a deterministic stub. For real OpenCV face detection, set
SEMANTIC_ANALYZER_BACKEND=vision when starting the publisher. If you started
with VLM_BACKEND set as in §1, the distribution step below also attaches VLM descriptions
(description_*).
4. Distribute the semantic data over the platform¶
Submit the image to the publisher and publish an event that points at it, so the AI-derived data enters the distribution pipeline. Running the answer program of the next section (answer_program.py) with --distribute does consent registration → /media/upload → /simulate/publish in one go. Run it with the snapshot.jpg taken in §2 before the checks in §5.
cd ~/program/Blockchain_IoT_Marketplace
source .venv/bin/activate
python3 examples/hands_on/local_vlm_distribution/answer_program.py \
--base-url http://localhost:8080 --image snapshot.jpg --distribute
If you started with VLM_BACKEND set as in §1, the publisher also calls the VLM here and attaches description_full / description_summary / description_model / description_generated_at to the row. Only when the VLM or the face blur fails is processing_warnings (such as vlm_unavailable) attached as well.
Consumer-side retrieval is tier-gated
To read the attached description_* on the consumer side you need a
ViewerToken, obtained by presenting the PurchaseViewerVC issued by /marketplace/claim.
The data_user_attrs passed to the claim decide its tier (see §3 of
Tier the response by trust (DataUserVC / Stage T)) (/platform/data returns 401
for a plain GET). Projecting description_full / description_summary per
trust tier is covered in §12 of Tier by semantic level (VLM and semantic representation / Stage T).
This page covers "camera → local model semantic enrichment →
distribute over the platform".
5. Verification points¶
/semantic/analyzereturns structured semantic data (SIR) only, never the raw image- the meaning is produced with the local model only, without sending images to a cloud
-
when
VLM_BACKENDis set, the distributed row carriesdescription_*(descriptions and model ID). Because §1 started withPLATFORM_INGEST_READ_ENABLED=true, you can check the last distributed row with the command below (seeing the content without a ViewerToken works only with this check-only setting)curl -s http://localhost:8080/platform/ingest | jq '.[-1] | {description_full, description_summary, description_model, processing_warnings}'
Something to think about¶
- When you distribute "semantic derivatives" instead of the raw image, what changes from the standpoint of privacy and data sovereignty?
- Organize the benefits and limits (speed, accuracy, operations) of running locally instead of using a cloud API.
Work through the exercise¶
Exercise programs are provided so first-time students can progress step by step: read the overall structure (Step A) → fill in the template (Step B) → add a feature from scratch (Step C).
Exercise programs:
Step A. Read the structure and the program¶
From the README "Big picture", grasp the three functions: analyze_frame() (POST to /semantic/analyze to get the SIR), summarize_sir() (one-line summary of the SIR), and distribute_frame() (register consent → upload → publish). The point is to understand the "keep the image in, let the meaning out" flow.
Step B. Fill in the two TODOs (task)¶
Implement the two TODOs in problem_program.py.
- TODO 1
summarize_sir(): read people count, object/sensitive-region counts, and the scene summary from the SIR and return a one-line summary - TODO 2
build_event(): build the event payload that carries the uploaded image (image_url) into the platform
cd ~/program/Blockchain_IoT_Marketplace
source .venv/bin/activate
python3 examples/hands_on/local_vlm_distribution/problem_program.py \
--base-url http://localhost:8080 --image snapshot.jpg
Compare with answer_program.py. Add --distribute to run the distribution too.
If --distribute times out
/simulate/publish responds only after VLM inference finishes. On a CPU-only PC inference takes tens of seconds to minutes, so the program may exceed its wait time and stop with an error such as TimeoutError (the wait defaults to 600 s and can be changed with the HANDS_ON_HTTP_TIMEOUT environment variable; an older course repository uses 10 s, so run git pull). The publisher keeps processing, and the row is recorded once inference is done. Confirm that a row with raw_topic homeassistant/event/possible_littering and action allow was added (checking via /platform/data needs a ViewerToken):
curl -s localhost:8080/audit/logs \
| jq '[.[] | select(.raw_topic == "homeassistant/event/possible_littering")][0] | {ts, action, reason}'
Step C. Add a feature from scratch (advanced)¶
Without a template, implement one of these yourself:
- Richer summary: list each
sensitive_regions[].typeand warn whenprivacy_risk_scoreis high - Frame sampling: capture N frames on a timer and distribute only the one with the highest privacy risk
- New derived field: add a value computed from the SIR (e.g.
people_count) to the eventdata - Custom analyzer: implement a new
SemanticAnalyzerinpublisher/app/semantic_analyzer.pyand switch to it withSEMANTIC_ANALYZER_BACKEND
Going further (extension directions)¶
- Natural-language search and processing: run natural-language search and summarization over the accumulated semantic data with an LLM (Let an AI plan the steps (LLM Planner) / Run the regional safety assistant).
- Remote device control: based on the analysis result, separate
planandexecuteto operate a device (same Part 3). - Raspberry Pi + Pi camera: split the roles so the Pi captures and the PC/host runs inference (this page keeps everything on the laptop first).
Common issues¶
- the first model pull is large and slow → wait for completion in the
vlm-pulllogs; do it when you have bandwidth to spare - inference is slow / times out on CPU → use the lightweight
VLM_MODEL=moondream, or raiseVLM_TIMEOUT_SEC processing_warningsshowsvlm_unavailable→ check that thevlmservice is up and the model pull is complete (docker compose -f infra/docker-compose.yml --profile vlm ps/docker compose -f infra/docker-compose.yml logs vlm-pull)- the camera cannot be opened → change the camera index, stop the process holding it, or on macOS allow camera access for your terminal app (see Detect with a USB webcam (OpenCV))
Next steps¶
Next is Protect camera images before handing them to AI (local vs cloud). You hand the same camera image to AI in four ways and compare what leaves the PC.
- You can leave the publisher and the
vlmcontainer running. §1 of the next page restarts the publisher with different settings. - The next page starts Ollama in a separate container (
iw3ip-ollama, port 11434). Thevlmcontainer does not publish a port to the host, so they do not clash. - The next page also uses the virtual environment (
.venv) and OpenCV made on this page.
Related pages¶
- Helpful to try first: Detect with a USB webcam (OpenCV)
- Details: DataUserVC × tiered access (§8 media integration, §12 VLM tier) / Let an AI plan the steps (LLM Planner)
- Design: Tiered access design spec