Skip to content
joeyhluPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PawTrace

PawTrace combines community sightings with footage from neighbourhood doorbells, home cameras and business CCTV to direct missing-pet searches and alert owners when a likely match is found.

Report missing pet → correlate sightings → prioritise search area → ask nearby cameras → analyse footage → alert owner.

When a pet goes missing, useful information is scattered across community posts, shelters, trail cameras and individual sightings, and the best evidence often sits unseen on a neighbour's doorbell or a gas station's CCTV. PawTrace ingests the reports into Elasticsearch and fuses keyword, vector, image, geographic and time signals to decide which are credible. It turns them into a prioritised search map, then finds the registered cameras whose view covers the likeliest cells and requests footage from the hours that matter. A dog detector runs on the clips, and when it finds a likely match, the dog's heading picks the next camera. The owner is asked to verify the match; nothing is ever marked "found" without them.

Operations map while camera footage is analysed

Search area after correlation Potential-match review
Search area Review
Owner view Search complete
Owner Final map

Quick start

Requirements: macOS or Linux, Python 3.11–3.13, Node 20+, ~3 GB of disk (Elasticsearch + models). No Docker, Java or API keys needed.

./dev.sh

On first run this creates the Python virtualenv, installs the npm packages, downloads a local Elasticsearch 9.5 (it bundles its own JDK), downloads the models (bge-small, DINOv2-small, YOLOv8s), prepares the demo assets and pre-renders the demo's camera clips (about 3 minutes in total). Then it starts:

Service URL
Web app http://localhost:3000
Search operations http://localhost:3000/ops/milo
API (FastAPI, docs at /docs) http://localhost:8000
Elasticsearch http://localhost:9200

./dev.sh setup only installs and prepares. Ctrl-C stops the API and the web app; Elasticsearch keeps running until scripts/es_local.sh stop (start/status also available).

Manual setup
cp .env.example .env                      # optional: every setting has a fallback
scripts/es_local.sh start                 # or set ELASTICSEARCH_URL / ELASTICSEARCH_API_KEY for Elastic Cloud
python3.13 -m venv backend/.venv
backend/.venv/bin/pip install -r backend/requirements.txt
(cd backend && .venv/bin/python -m scripts.prepare_assets --footage)
(cd backend && .venv/bin/uvicorn app.main:app --port 8000)
(cd frontend && npm install && npm run dev)

The interface

The operations view (/ops/<pet>) is the main screen: the evidence feed on the left with every report and its score, the search map in the centre, and three tabs on the right — agent activity, retrieval, and cameras. The Cameras tab lists every footage request with its status, plays each clip, and while the detector runs, the clip follows the frame being analysed with its boxes. On the map, cameras are coloured by status (could see it, requested, footage in review, clear, match), with a wedge showing which way each faces; a dashed green track runs from the report trail through the camera matches, over the original search area (dashed) and the confirmed location. The owner view (/cases/<pet>) tells the same story in plain language, and the review page (/review/<observation>) puts the camera crop and clip beside the owner's reference photos.


Architecture

Next.js 16 · TypeScript · Tailwind 4 · react-leaflet + leaflet.heat
   │ REST + Server-Sent Events (browser → API directly)
FastAPI
   ├─ embeddings   text: Jina v3 API → bge-small (local) → hashing      image: DINOv2 → OpenCLIP → colour histogram
   ├─ retrieval    4 retrievers in one _msearch → reciprocal rank fusion → explainable weighted rerank → expansion rounds
   ├─ cells        hex grid; priority = search-theory posterior over proximity, sightings, semantics, coverage, terrain
   ├─ agent        13 tools · rule-based planner · OpenAI-compatible tool-calling planner · Agent Activity log
   ├─ cameras      registry with view cones (geo_shape) · consent + retention · footage requests
   ├─ camsim       motion-clip compositor for the demo (CC scene photos + dog cut-outs) → H.264 clips
   ├─ vision       frame sampling → YOLOv8 dog detection → tracks → crop → DINOv2 → geolocate from camera pose → index → score
   └─ demo         state machine, seed/reset, controls
Elasticsearch 9.5 (local node or Elastic Cloud)

Elasticsearch data model

Index Purpose Notable fields
pet_cases Missing-pet cases semantic_text + text_embedding (dense_vector), image_embeddings (nested dense vectors, one per photo), last_seen_location (geo_point), status
sightings Community, shelter and camera reports raw_text, normalized_description, attribute_text (BM25), text_embedding, image_embedding, location (geo_point), timestamp, source_type, reliability_score, extracted_attributes, possible_pet_ids
cameras Community camera registry location (geo_point), coverage (geo_shape view cone from heading, field of view and range), kind, consent, retention_hours
footage_requests One request per camera and time window camera_id, window_from/window_to, effective_from (clipped by retention), status, clips, analysis
camera_observations Every dog tracked in the footage cropped_detection_url, frame_url, clip_url + clip_time_s, image_embedding, object_confidence, visual_similarity, travel_bearing_deg, match (full explanation), location (geo_point), review_status
search_cells Prioritised hex cells polygon (geo_shape), centre (geo_point), priority_score, priority_level, components, status, covered_by, supporting_sighting_ids
agent_activity, owner_alerts, pawtrace_meta The agent timeline, alerts, snapshots and demo state

The spec's semantic_text is a field name, mapped as text: it holds the canonical description that gets embedded, with the vector next to it in text_embedding. The ES semantic_text field type is not used, since it needs an inference endpoint, and PawTrace keeps embedding providers swappable in the application. Vector dimensions come from the active provider and are recorded in pawtrace_meta; a reset recreates the indexes when the provider changes. ES 9.x drops vectors from _source by default, so indexes are created with index.mapping.exclude_source_vectors: false because the reranker reads them back.

Elasticsearch features used: BM25 multi_match, knn (including nested kNN over each case's reference photos), geo_distance filters, function_score with gauss decay on geo_point and on dates, _msearch, geotile_grid + geo_centroid aggregations (sighting clusters), filters aggregations (explaining exclusions), geo_shape intersects (camera view cones against a MultiPolygon of the priority cells), geo_distance + _geo_distance sort (cameras ahead of a detection), painless update scripts, mget and bulk.

Retrieval and ranking

search_related_sightings runs four retrievers in a single _msearch. All four share hard filters: a geo_distance radius (8 km) and a time range that excludes reports from before the pet went missing.

  1. BM25 over extracted attributes, normalised description and raw text (breed, collar colour, landmarks, behaviour keywords).
  2. Dense text kNN with the case description (bge-small locally, Jina v3 with a key).
  3. Image kNN with the centroid of the reference-photo embeddings (DINOv2).
  4. Geo-temporal: function_score with gauss decay from the last-seen point and from now.

The ranked lists are merged with reciprocal rank fusion (k = 60) to choose the candidates, which are then reranked into an explainable match score:

visual 30% · description 25% · geography 20% · time 15% · source reliability 10%
  • Missing signals (e.g. a report with no photo) are dropped, and the other weights are rescaled; the UI shows "n/a".
  • Description similarity blends dense cosine (65%) with normalised BM25 (35%). Cosines are calibrated per model.
  • Geography must be reachable: a report the dog could not have reached from the last-seen point in the time available scores 0, and two impossible reports cannot vouch for each other.
  • A consistency gate multiplies the score for explicit contradictions: another breed, species, size, colour or collar colour; a vague report with no identifying detail; an unreachable location; or a clear photo that doesn't resemble the reference photos. Each gate is shown with its reason.
  • Evidence expansion: credible reports (≥ 0.5) that chain back to the last-seen point become anchors for another round (geo-temporal around them, plus "more like this report" dense retrieval), repeated until the credible set is stable. This is how the second report and the blurry camera image join the first.

The match score is a ranking score, not a calibrated probability. Every result links to its Elasticsearch document (/evidence/<index>/<id>), with per-retriever ranks, the RRF score and each signal's contribution.

Search-cell priority

Cells are hexagons (60 m) within ~1 km of the last-seen point. Priority is a simplified search-theory posterior:

prior(c)      = accessibility(c) · (0.15 + 0.85 · proximity(c))     proximity widens with time missing
likelihood(c) = 1 + 12 · semantic(c) + 5 · recent_sightings(c)     kernel densities of linked reports
weight(c)     = prior · likelihood · (1 − coverage(c))              coverage = probability a previous search would have found the pet
priority(c)   = 1 − exp(−share(c) · N / κ),   share = weight / Σ weight

A projected-position term extrapolates the movement of the two latest credible reports. Accessibility comes from OpenStreetMap land cover: trail corridors and open fields high, woods lower, buildings and water low. Because the shares sum to one, evidence that concentrates probability also drains it from everywhere else, which is what makes the broad area collapse. Bands: red immediate ≥ 0.70, orange likely ≥ 0.45, yellow possible ≥ 0.20, grey searched. Each cell's popup shows its components.

Agent

The agent never sees the dataset; it works through 13 tools that query and update Elasticsearch:

get_pet_case · search_related_sightings · find_sighting_clusters · get_searched_areas · calculate_search_cells · find_nearby_cameras · request_camera_footage · analyse_camera_footage · search_camera_observations · update_search_priorities · send_owner_alert · mark_detection_confirmed · mark_detection_rejected

  • Rule-based planner (default, used by the demo): correlate → credible cluster → priority cells → cameras whose view covers them (best cells first, 5 per round) → request footage → analyse. A likely match (≥ 0.5) with a direction of travel triggers a follow-up: cameras within reach ahead on that heading, up to two hops. The owner is alerted about the most recent likely match.
  • LLM planner: any OpenAI-compatible chat-completions endpoint with tool calling (LLM_API_KEY, LLM_BASE_URL, LLM_MODEL). Use it from the API (POST /api/cases/{id}/agent/run with {"use_llm": true}). It gets 11 of the 13 tools: mark_detection_confirmed and mark_detection_rejected are withheld, so it cannot confirm or reject on the owner's behalf, and a call to them is refused even if the model invents the name. Tool errors are handed back to the model to retry. If the LLM call fails entirely, the rule planner takes over and the reason (including the provider's own message, e.g. an exhausted quota) is recorded in the Agent Activity timeline.

Every plan step, tool call, result and decision appears in the Agent Activity timeline (stored in agent_activity).

Community cameras and footage

Registry. Neighbours and businesses register a camera with its position, heading, field of view and range, a consent mode (auto_share, on_request or not_shared) and how long it keeps footage. The view cone is indexed as a geo_shape, so "which cameras could have seen the pet?" is a single geo_shape intersects query against the immediate and likely cells, ranked by the best cell each camera covers. After a detection, the follow-up query is a geo_distance search around the detection (radius from the time elapsed, capped at 1.5 km), sorted by distance, keeping cameras within 50° of the dog's heading.

Requests. Each request is a footage_requests document for the window from 15 minutes before the latest credible report (or the last-seen time) until now, clipped to what the camera still keeps. auto_share cameras deliver at once, on_request owners approve after a short simulated delay, and not_shared cameras are never asked. Analysed cameras mark the cells in their view as partly searched (probability of detection 0.5).

Footage. No real doorbell or CCTV footage ships with the project, so the demo's clips are composited. For each camera, a freely licensed photo of a similar scene (doorbell walkway, parking lot, residence path, gas-station forecourt) is the background. Cut-outs of real dog photos walk along the scenario's path wherever it crosses the camera's view cone, projected with the camera's pose and given the camera's look (doorbell fisheye, desaturated CCTV, noise, timestamp). Only the compositor reads the scenario's ground truth, and it only decides which motion clips exist, as a camera's motion trigger would. Milo's cut-out is a different photo of the same dog as the owner's references, so the similarity is computed, not an identity match.

Analysis is real and never reads the ground truth. It samples a frame every 0.3 s, runs YOLOv8s (1280 px, Apple MPS), links detections into tracks, and embeds each track's most central views with DINOv2. It describes coat colours and size, geolocates the dog from the camera pose (bearing from the box position, distance from the box height), estimates the direction of travel from the track, indexes a camera_observations document and scores it with the same reranker.

Real cameras would replace the compositor's clips_for with a camera platform's clip export for the approved window; the registry, requests, analysis and scoring stay the same. No platform integration is built.

Fallbacks

Component Preferred Fallback
Elasticsearch Elastic Cloud (ELASTICSEARCH_URL + ELASTICSEARCH_API_KEY) Local 9.5 node via scripts/es_local.sh
Text embeddings Jina v3 API (JINA_API_KEY) bge-small-en-v1.5 (local) → hashing embedder
Image embeddings DINOv2-small (local) OpenCLIP ViT-B/32 → colour histogram
Dog detection YOLOv8s Replay of detections cached per clip from an earlier YOLO run
Planner OpenAI-compatible LLM Rule-based planner
Map tiles Mapbox dark (NEXT_PUBLIC_MAPBOX_TOKEN) Stadia Alidade Smooth Dark (keyless on localhost) → Esri Dark Gray

The active providers are shown in the ops header and on GET /api/health.

Why DINOv2 by default: in our calibration on 80 px crops, DINOv2 scored the same dog in a different photo at 0.71 against 0.17 for a golden retriever. CLIP ViT-B/32, whose embeddings are tuned for captions rather than identity, gave 0.60 against 0.58. CLIP remains available with IMAGE_EMBEDDER=clip.

Configuration

Copy .env.example to .env at the repo root. All variables are optional.

Variable Default
ELASTICSEARCH_URL, ELASTICSEARCH_API_KEY http://localhost:9200 Elastic Cloud endpoint + API key
INDEX_PREFIX empty Prefix for every index on a shared cluster
JINA_API_KEY – Enables Jina v3 text embeddings (1024 d)
TEXT_EMBEDDER, IMAGE_EMBEDDER auto Force jina/local/hashing, dinov2/clip/histogram
LLM_API_KEY, LLM_BASE_URL, LLM_MODEL –, OpenAI, gpt-4.1-mini OpenAI-compatible planner
DETECTOR, YOLO_WEIGHTS auto, yolov8s.pt yolo or cached
DEMO_MODE true Demo controls and the frozen demo clock
NEXT_PUBLIC_API_URL http://localhost:8000 API base URL for the browser
NEXT_PUBLIC_MAPBOX_TOKEN, NEXT_PUBLIC_STADIA_API_KEY – Map tiles
NEXT_PUBLIC_DEMO_MODE dev only Demo dock: shown in development; true/false forces it on/off

Changing an embedding provider changes vector dimensions: reset the demo (or re-seed) afterwards.

API

GET /api/health ES status, active providers, detector, planner
GET /api/events Server-Sent Events: camera lookups, footage requests, analysed frames, observations, alerts, agent activity, cells, demo
POST /api/cases (multipart) · GET /api/cases/{id} · GET /api/cases/{id}/overview Intake and case state
POST /api/cases/{id}/correlate · GET /api/cases/{id}/correlation · GET /api/cases/{id}/clusters Retrieval
GET /api/cases/{id}/cells · POST /api/cases/{id}/cells/recalculate Search cells
POST /api/cases/{id}/agent/run · GET /api/cases/{id}/activity Agent
POST /api/sightings (multipart, optional image) · GET /api/sightings Reports
GET /api/cameras · GET /api/cases/{id}/footage-requests Camera registry, footage requests
GET /api/cases/{id}/observations · GET /api/alerts Camera detections, owner alerts
GET /api/observations/{id} · POST /api/observations/{id}/confirm / reject Potential-match review
GET /api/es/{index}/{id} Raw Elasticsearch document (vectors shortened)
POST /api/demo/reset · POST /api/demo/step/{step} · POST /api/demo/autoplay · GET /api/demo/state Demo controls

Tests

cd backend && .venv/bin/python -m pytest -q        # unit tests: scoring, geo filtering, cells, camera geometry + clip crossings, demo state machine, extraction
cd backend && .venv/bin/python -m scripts.demo_check   # end-to-end scenario against a running API
cd frontend && npx tsc --noEmit && npx eslint app components lib

Project layout

backend/app/        FastAPI app: es, embeddings, retrieval, scoring, cells, terrain, agent, cameras, camsim, vision, demo
backend/scripts/    prepare_assets (models, sprites, camera still, clips) · demo_check
backend/tests/      pytest suite
frontend/           Next.js app: / · /report · /cases/[petId] · /ops/[petId] · /review/[observationId] · /evidence/[index]/[id]
data/seed/          scenario.json (Milo, cameras, ground-truth path) · sightings_noise.json (46 noisy reports)
data/geo/           OpenStreetMap features + landmarks around the CIF fields
data/images/        CC-licensed dog photos (source/CREDITS.md), camera scene backgrounds (scenes/CREDITS.md), demo still
data/footage/       dog cut-outs; rendered clips and their cached detections
scripts/es_local.sh local Elasticsearch
dev.sh              one-command setup and run

Honest limitations

  • The camera footage is composited (CC scene photos plus dog cut-outs walking the scenario's path); detection, tracking, embedding, geolocation and scoring on it are real.
  • The camera registry is fictional: the cameras sit at real places around the University of Waterloo CIF fields, but no real owner registered them. The scene photos show similar places elsewhere (the gas-station forecourt is a station in Florida, with its brand logos pixelated).
  • Owner approval of a footage request is simulated (a short delay); there is no messaging to camera owners.
  • Milo is a demo identity: his photos show real dogs from Wikimedia Commons (credited), and the sightings are written for the scenario.
  • Match scores are ranking scores with hand-calibrated bounds per model, not probabilities. The demo's camera matches score about 0.70, and the owner makes the call.
  • Not built (by design, per the hackathon scope): authentication, payments, social-media scraping, integrations with camera platforms, SMS or push notifications.

Credits

  • Map data © OpenStreetMap contributors (ODbL). Tiles © Stadia Maps / OpenMapTiles, Esri, or Mapbox.
  • Dog photos: Wikimedia Commons, CC0 / CC BY / CC BY-SA. Authors and licences in data/images/source/CREDITS.md.
  • Camera scene photos: Wikimedia Commons, CC BY / CC BY-SA, some edited (crops, blurred plates, pixelated logos). Authors, licences and edits in data/images/scenes/CREDITS.md.
  • Models: YOLOv8 (Ultralytics, AGPL-3.0), DINOv2 (Meta, Apache-2.0), BAAI bge-small-en-v1.5 (MIT), OpenCLIP.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages