@blueharford/scrypted-spatial-awareness 0.6.14 → 0.6.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/plugin.zip CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blueharford/scrypted-spatial-awareness",
3
- "version": "0.6.14",
3
+ "version": "0.6.16",
4
4
  "description": "Cross-camera object tracking for Scrypted NVR with spatial awareness",
5
5
  "author": "Joshua Seidel <blueharford>",
6
6
  "license": "Apache-2.0",
@@ -23,6 +23,8 @@ import {
23
23
  DiscoveryStatus,
24
24
  DEFAULT_DISCOVERY_STATUS,
25
25
  RATE_LIMIT_WARNING_THRESHOLD,
26
+ DistanceEstimate,
27
+ distanceToFeet,
26
28
  } from '../models/discovery';
27
29
  import {
28
30
  CameraTopology,
@@ -40,60 +42,141 @@ interface ChatCompletionDevice extends ScryptedDevice {
40
42
  }
41
43
 
42
44
  /** Scene analysis prompt for single camera */
43
- const SCENE_ANALYSIS_PROMPT = `Analyze this security camera image and identify what you see.
45
+ const SCENE_ANALYSIS_PROMPT = `You are analyzing a security camera image. Describe EVERYTHING you can see in detail.
46
+
47
+ ## INSTRUCTIONS
48
+ Look at this image carefully and identify ALL visible objects, structures, and areas. Be thorough - even small or partially visible items are important for security awareness.
49
+
50
+ ## 1. LANDMARKS - List EVERY distinct object or feature you can see:
51
+
52
+ **Structures** (buildings, parts of buildings):
53
+ - Houses, garages, sheds, porches, decks, patios, carports, gazebos
54
+ - Walls, pillars, columns, railings, stairs, steps
55
+
56
+ **Vegetation** (plants, trees, landscaping):
57
+ - Trees (describe type if identifiable: oak, palm, pine, etc.)
58
+ - Bushes, shrubs, hedges
59
+ - Flower beds, gardens, planters, potted plants
60
+ - Grass/lawn areas, mulch beds
61
+
62
+ **Boundaries & Barriers**:
63
+ - Fences (wood, chain-link, aluminum, vinyl, iron, privacy)
64
+ - Walls (brick, stone, concrete, retaining)
65
+ - Gates, gate posts
66
+ - Hedges used as boundaries
67
+
68
+ **Access Points & Pathways**:
69
+ - Doors (front, side, garage, screen)
70
+ - Driveways (concrete, asphalt, gravel, pavers)
71
+ - Walkways, sidewalks, paths, stepping stones
72
+ - Stairs, ramps, porches
73
+
74
+ **Utility & Fixtures**:
75
+ - Mailboxes, package boxes
76
+ - Light fixtures, lamp posts, solar lights
77
+ - A/C units, utility boxes, meters
78
+ - Trash cans, recycling bins
79
+ - Hoses, spigots, sprinklers
80
+
81
+ **Outdoor Items**:
82
+ - Vehicles (cars, trucks, motorcycles, boats, trailers)
83
+ - Furniture (chairs, tables, benches, swings)
84
+ - Grills, fire pits, outdoor kitchens
85
+ - Play equipment, trampolines, pools
86
+ - Decorations, flags, signs
87
+
88
+ **Off-Property Elements** (important for security context):
89
+ - Street, road, sidewalk
90
+ - Neighbor's property/fence/house
91
+ - Public areas visible
92
+
93
+ For EACH landmark, estimate its DISTANCE from the camera:
94
+ - "close" = 0-10 feet (within arm's reach of camera)
95
+ - "near" = 10-30 feet
96
+ - "medium" = 30-60 feet
97
+ - "far" = 60-100 feet
98
+ - "distant" = 100+ feet (edge of property or beyond)
99
+
100
+ ## 2. ZONES - Identify distinct AREAS visible:
101
+ - Front yard, backyard, side yard
102
+ - Driveway, parking area
103
+ - Patio, deck, porch
104
+ - Garden area, lawn
105
+ - Street/road
106
+ - Neighbor's yard
107
+
108
+ For each zone, estimate what percentage of the image it covers (0.0 to 1.0).
109
+
110
+ ## 3. EDGES - What's at each edge of the frame:
111
+ This helps understand what's just out of view.
112
+
113
+ ## 4. CAMERA CONTEXT:
114
+ - Estimated mounting height (ground level, 8ft, 12ft, roofline, etc.)
115
+ - Approximate field of view (narrow, medium, wide)
116
+ - Facing direction if determinable (north, south, street-facing, etc.)
44
117
 
45
- 1. LANDMARKS - Identify fixed features visible:
46
- - Structures (house, garage, shed, porch, deck)
47
- - Features (mailbox, tree, pool, garden, fountain)
48
- - Access points (door, gate, driveway entrance, walkway)
49
- - Boundaries (fence, wall, hedge)
50
-
51
- 2. ZONES - Identify area types visible:
52
- - What type of area is this? (front yard, backyard, driveway, street, patio, walkway)
53
- - Estimate what percentage of the frame each zone covers (0.0 to 1.0)
54
-
55
- 3. EDGES - What's visible at the frame edges:
56
- - Top edge: (sky, roof, trees, etc.)
57
- - Left edge: (fence, neighbor, street, etc.)
58
- - Right edge: (fence, garage, etc.)
59
- - Bottom edge: (ground, driveway, grass, etc.)
60
-
61
- 4. ORIENTATION - Estimate camera facing direction based on shadows, sun position, or landmarks
62
-
63
- Respond with ONLY valid JSON in this exact format:
118
+ Respond with ONLY valid JSON:
64
119
  {
65
120
  "landmarks": [
66
- {"name": "Front Door", "type": "access", "confidence": 0.9, "description": "White front door with black frame"}
121
+ {"name": "Mailbox", "type": "feature", "distance": "medium", "confidence": 0.95, "description": "Black metal mailbox on wooden post, approximately 40 feet from camera"},
122
+ {"name": "Aluminum Fence", "type": "boundary", "distance": "near", "confidence": 0.9, "description": "Silver aluminum fence running along left side of property, about 15-20 feet away"},
123
+ {"name": "Large Oak Tree", "type": "feature", "distance": "far", "confidence": 0.85, "description": "Mature oak tree near property line, roughly 80 feet from camera"}
67
124
  ],
68
125
  "zones": [
69
- {"name": "Front Yard", "type": "yard", "coverage": 0.4, "description": "Grass lawn area"}
126
+ {"name": "Front Yard", "type": "yard", "coverage": 0.5, "description": "Grass lawn with some bare patches"},
127
+ {"name": "Driveway", "type": "driveway", "coverage": 0.25, "description": "Concrete driveway leading to garage"}
70
128
  ],
71
- "edges": {"top": "sky with clouds", "left": "fence and trees", "right": "garage wall", "bottom": "concrete walkway"},
72
- "orientation": "north"
73
- }`;
129
+ "edges": {
130
+ "top": "sky, tree canopy",
131
+ "left": "aluminum fence, neighbor's yard beyond",
132
+ "right": "side of house, garage door",
133
+ "bottom": "concrete walkway, grass edge"
134
+ },
135
+ "cameraContext": {
136
+ "mountHeight": "8 feet",
137
+ "fieldOfView": "wide",
138
+ "facingDirection": "street-facing"
139
+ }
140
+ }
141
+
142
+ BE THOROUGH. List every distinct item you can identify. A typical outdoor scene should have 5-15+ landmarks.`;
74
143
 
75
144
  /** Multi-camera correlation prompt */
76
- const CORRELATION_PROMPT = `I have scene analyses from multiple security cameras at the same property. Help me correlate them to understand the property layout.
145
+ const CORRELATION_PROMPT = `I have detailed scene analyses from multiple security cameras at the same property. Help me understand which landmarks appear in multiple camera views.
77
146
 
78
147
  CAMERA SCENES:
79
148
  {scenes}
80
149
 
81
- Identify:
82
- 1. Shared landmarks - Features that appear in multiple camera views
83
- 2. Camera connections - How someone could move between camera views and estimated walking time
84
- 3. Overall layout - Describe the property layout based on what you see
150
+ ## PRIORITY ORDER (most important first):
151
+
152
+ ### 1. SHARED LANDMARKS (HIGHEST PRIORITY)
153
+ Identify features that are visible from MULTIPLE cameras. This is crucial for understanding the property layout.
154
+ - Look for the SAME fence, tree, mailbox, driveway, structure, etc. appearing in different camera views
155
+ - Even partial visibility counts (e.g., a tree visible in full from one camera and just the edge from another)
156
+ - Include landmarks that are at the boundary between camera views
157
+
158
+ ### 2. PROPERTY LAYOUT
159
+ Based on what each camera sees and their overlapping features, describe:
160
+ - Which areas each camera covers
161
+ - How the cameras relate spatially (e.g., "Camera A looks toward Camera B's direction")
162
+ - Overall property shape and features
163
+
164
+ ### 3. CONNECTIONS (Lower Priority)
165
+ Only if clearly determinable, suggest walking paths between camera views.
85
166
 
86
167
  IMPORTANT: For camera references, use the EXACT device ID shown in parentheses (e.g., "device_123"), NOT the camera name.
87
168
 
88
169
  Respond with ONLY valid JSON:
89
170
  {
90
171
  "sharedLandmarks": [
91
- {"name": "Driveway", "type": "access", "seenByCameras": ["device_123", "device_456"], "confidence": 0.8, "description": "Concrete driveway"}
172
+ {"name": "Aluminum Fence", "type": "boundary", "seenByCameras": ["device_123", "device_456"], "confidence": 0.85, "description": "Silver aluminum fence visible on right edge of Camera A and left edge of Camera B"},
173
+ {"name": "Large Oak Tree", "type": "feature", "seenByCameras": ["device_123", "device_789"], "confidence": 0.9, "description": "Mature oak tree in front yard, visible from both front and side cameras"},
174
+ {"name": "Concrete Driveway", "type": "access", "seenByCameras": ["device_123", "device_456", "device_789"], "confidence": 0.95, "description": "Driveway visible from multiple angles"}
92
175
  ],
93
176
  "connections": [
94
- {"from": "device_123", "to": "device_456", "transitSeconds": 10, "via": "driveway", "confidence": 0.7, "bidirectional": true}
177
+ {"from": "device_123", "to": "device_456", "transitSeconds": 8, "via": "along driveway", "confidence": 0.6, "bidirectional": true}
95
178
  ],
96
- "layoutDescription": "Single-story house with front yard facing street, driveway on the left side, backyard accessible through side gate"
179
+ "layoutDescription": "Ranch-style house. Front camera covers front yard and street. Garage camera covers driveway entrance. Side camera covers side yard with aluminum fence separating from neighbor. Backyard camera shows deck and pool area."
97
180
  }`;
98
181
 
99
182
  export class TopologyDiscoveryEngine {
@@ -307,7 +390,7 @@ export class TopologyDiscoveryEngine {
307
390
  ],
308
391
  },
309
392
  ],
310
- max_tokens: 1500,
393
+ max_tokens: 4000, // Increased for detailed scene analysis
311
394
  temperature: 0.3,
312
395
  });
313
396
 
@@ -320,7 +403,8 @@ export class TopologyDiscoveryEngine {
320
403
  jsonStr = jsonStr.replace(/```json?\n?/g, '').replace(/```$/g, '').trim();
321
404
  }
322
405
 
323
- const parsed = JSON.parse(jsonStr);
406
+ // Try to recover truncated JSON
407
+ const parsed = this.parseJsonWithRecovery(jsonStr, cameraName);
324
408
 
325
409
  // Map parsed data to our types
326
410
  if (Array.isArray(parsed.landmarks)) {
@@ -328,6 +412,7 @@ export class TopologyDiscoveryEngine {
328
412
  name: l.name || 'Unknown',
329
413
  type: this.mapLandmarkType(l.type),
330
414
  confidence: typeof l.confidence === 'number' ? l.confidence : 0.7,
415
+ distance: this.mapDistance(l.distance),
331
416
  description: l.description || '',
332
417
  boundingBox: l.boundingBox,
333
418
  }));
@@ -449,6 +534,110 @@ export class TopologyDiscoveryEngine {
449
534
  return 'unknown';
450
535
  }
451
536
 
537
+ /** Map LLM distance to our type */
538
+ private mapDistance(distance: string): DistanceEstimate {
539
+ const dist = distance?.toLowerCase();
540
+ if (dist?.includes('close')) return 'close';
541
+ if (dist?.includes('near')) return 'near';
542
+ if (dist?.includes('medium')) return 'medium';
543
+ if (dist?.includes('far') && !dist?.includes('distant')) return 'far';
544
+ if (dist?.includes('distant')) return 'distant';
545
+ return 'medium'; // Default to medium if not specified
546
+ }
547
+
548
+ /** Try to parse JSON with recovery for truncated responses */
549
+ private parseJsonWithRecovery(jsonStr: string, context: string): any {
550
+ // First, try direct parse
551
+ try {
552
+ return JSON.parse(jsonStr);
553
+ } catch (e) {
554
+ // Log the raw response for debugging (first 500 chars)
555
+ this.console.log(`[Discovery] Raw LLM response for ${context} (first 500 chars): ${jsonStr.substring(0, 500)}...`);
556
+ }
557
+
558
+ // Try to recover truncated JSON by finding complete sections
559
+ try {
560
+ // Find where valid JSON might end (look for last complete object/array)
561
+ let recoveredJson = jsonStr;
562
+
563
+ // Try to close unclosed strings
564
+ const lastQuote = recoveredJson.lastIndexOf('"');
565
+ const lastColon = recoveredJson.lastIndexOf(':');
566
+ if (lastQuote > lastColon) {
567
+ // We might be in the middle of a string value
568
+ const beforeQuote = recoveredJson.substring(0, lastQuote);
569
+ const afterLastCompleteEntry = beforeQuote.lastIndexOf('},');
570
+ if (afterLastCompleteEntry > 0) {
571
+ recoveredJson = beforeQuote.substring(0, afterLastCompleteEntry + 1);
572
+ }
573
+ }
574
+
575
+ // Close any unclosed arrays/objects
576
+ let openBraces = (recoveredJson.match(/{/g) || []).length;
577
+ let closeBraces = (recoveredJson.match(/}/g) || []).length;
578
+ let openBrackets = (recoveredJson.match(/\[/g) || []).length;
579
+ let closeBrackets = (recoveredJson.match(/\]/g) || []).length;
580
+
581
+ // Add missing closing brackets/braces
582
+ while (closeBrackets < openBrackets) {
583
+ recoveredJson += ']';
584
+ closeBrackets++;
585
+ }
586
+ while (closeBraces < openBraces) {
587
+ recoveredJson += '}';
588
+ closeBraces++;
589
+ }
590
+
591
+ const recovered = JSON.parse(recoveredJson);
592
+ this.console.log(`[Discovery] Recovered truncated JSON for ${context}`);
593
+ return recovered;
594
+ } catch (recoveryError) {
595
+ // Last resort: try to extract just landmarks array
596
+ try {
597
+ const landmarksMatch = jsonStr.match(/"landmarks"\s*:\s*\[([\s\S]*?)(?:\]|$)/);
598
+ const zonesMatch = jsonStr.match(/"zones"\s*:\s*\[([\s\S]*?)(?:\]|$)/);
599
+
600
+ const result: any = { landmarks: [], zones: [], edges: {}, orientation: 'unknown' };
601
+
602
+ if (landmarksMatch) {
603
+ // Try to parse individual landmark objects
604
+ const landmarksStr = landmarksMatch[1];
605
+ const landmarkObjects = landmarksStr.match(/\{[^{}]*\}/g) || [];
606
+ result.landmarks = landmarkObjects.map((obj: string) => {
607
+ try {
608
+ return JSON.parse(obj);
609
+ } catch {
610
+ return null;
611
+ }
612
+ }).filter(Boolean);
613
+ this.console.log(`[Discovery] Extracted ${result.landmarks.length} landmarks from partial response for ${context}`);
614
+ }
615
+
616
+ if (zonesMatch) {
617
+ const zonesStr = zonesMatch[1];
618
+ const zoneObjects = zonesStr.match(/\{[^{}]*\}/g) || [];
619
+ result.zones = zoneObjects.map((obj: string) => {
620
+ try {
621
+ return JSON.parse(obj);
622
+ } catch {
623
+ return null;
624
+ }
625
+ }).filter(Boolean);
626
+ this.console.log(`[Discovery] Extracted ${result.zones.length} zones from partial response for ${context}`);
627
+ }
628
+
629
+ if (result.landmarks.length > 0 || result.zones.length > 0) {
630
+ return result;
631
+ }
632
+ } catch (extractError) {
633
+ // Give up
634
+ }
635
+
636
+ this.console.warn(`[Discovery] Could not recover JSON for ${context}`);
637
+ throw new Error(`Failed to parse LLM response: truncated or malformed JSON`);
638
+ }
639
+ }
640
+
452
641
  /** Resolve a camera reference (name or deviceId) to its deviceId */
453
642
  private resolveCameraRef(ref: string): string | null {
454
643
  if (!this.topology?.cameras || !ref) return null;
@@ -644,9 +833,14 @@ export class TopologyDiscoveryEngine {
644
833
  private generateSuggestionsFromAnalysis(analysis: SceneAnalysis): void {
645
834
  if (!analysis.isValid) return;
646
835
 
836
+ this.console.log(`[Discovery] Generating suggestions from ${analysis.landmarks.length} landmarks, ${analysis.zones.length} zones`);
837
+
647
838
  // Generate landmark suggestions
648
839
  for (const landmark of analysis.landmarks) {
649
840
  if (landmark.confidence >= this.config.minLandmarkConfidence) {
841
+ // Calculate distance in feet from distance estimate
842
+ const distanceFeet = landmark.distance ? distanceToFeet(landmark.distance) : 50;
843
+
650
844
  const suggestion: DiscoverySuggestion = {
651
845
  id: `landmark_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
652
846
  type: 'landmark',
@@ -659,27 +853,31 @@ export class TopologyDiscoveryEngine {
659
853
  type: landmark.type,
660
854
  description: landmark.description,
661
855
  visibleFromCameras: [analysis.cameraId],
662
- // Include bounding box for positioning (will be used by applyDiscoverySuggestion)
856
+ // Include extra metadata for positioning
663
857
  boundingBox: landmark.boundingBox,
664
- } as any, // boundingBox is extra metadata not in Landmark interface
858
+ distance: landmark.distance,
859
+ distanceFeet: distanceFeet,
860
+ } as any, // Extra metadata not in base Landmark interface
665
861
  };
666
862
  this.suggestions.set(suggestion.id, suggestion);
863
+ this.console.log(`[Discovery] Landmark suggestion: ${landmark.name} (${landmark.type}, ${landmark.distance || 'medium'}, ~${distanceFeet}ft)`);
667
864
  }
668
865
  }
669
866
 
670
- // Generate zone suggestions
867
+ // Generate zone suggestions (even for smaller coverage - 10% is enough)
671
868
  for (const zone of analysis.zones) {
672
- if (zone.coverage >= 0.2) {
869
+ if (zone.coverage >= 0.1) {
673
870
  const suggestion: DiscoverySuggestion = {
674
871
  id: `zone_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
675
872
  type: 'zone',
676
873
  timestamp: Date.now(),
677
874
  sourceCameras: [analysis.cameraId],
678
- confidence: 0.7,
875
+ confidence: Math.min(0.9, 0.5 + zone.coverage), // Higher coverage = higher confidence
679
876
  status: 'pending',
680
877
  zone: zone,
681
878
  };
682
879
  this.suggestions.set(suggestion.id, suggestion);
880
+ this.console.log(`[Discovery] Zone suggestion: ${zone.name} (${zone.type}, ${Math.round(zone.coverage * 100)}% coverage)`);
683
881
  }
684
882
  }
685
883
  }
@@ -58,6 +58,21 @@ export interface DiscoveredZone {
58
58
  boundingBox?: [number, number, number, number];
59
59
  }
60
60
 
61
+ /** Distance estimate from camera */
62
+ export type DistanceEstimate = 'close' | 'near' | 'medium' | 'far' | 'distant';
63
+
64
+ /** Convert distance estimate to approximate feet */
65
+ export function distanceToFeet(distance: DistanceEstimate): number {
66
+ switch (distance) {
67
+ case 'close': return 5; // 0-10 feet
68
+ case 'near': return 20; // 10-30 feet
69
+ case 'medium': return 45; // 30-60 feet
70
+ case 'far': return 80; // 60-100 feet
71
+ case 'distant': return 150; // 100+ feet
72
+ default: return 50;
73
+ }
74
+ }
75
+
61
76
  /** A landmark discovered in a camera view */
62
77
  export interface DiscoveredLandmark {
63
78
  /** Name of the landmark */
@@ -66,6 +81,8 @@ export interface DiscoveredLandmark {
66
81
  type: LandmarkType;
67
82
  /** Confidence score from LLM (0-1) */
68
83
  confidence: number;
84
+ /** Estimated distance from camera */
85
+ distance?: DistanceEstimate;
69
86
  /** Bounding box in normalized coordinates [x, y, width, height] (0-1) */
70
87
  boundingBox?: [number, number, number, number];
71
88
  /** Description from LLM analysis */