muhammadpriv001 commited on
Commit
fdced5d
Β·
1 Parent(s): 4583f36

docs: comprehensive project documentation for portfolio

Browse files
Files changed (1) hide show
  1. PROJECT_DOCUMENTATION.md +941 -0
PROJECT_DOCUMENTATION.md ADDED
@@ -0,0 +1,941 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Object Intelligence Platform
2
+
3
+ > **Open-World Multi-Pipeline Computer Vision System**
4
+ > Real-time object detection, open-vocabulary discovery, specific object recognition, and target lock filtering β€” all in one unified platform.
5
+
6
+ [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/muhammadpriv001/Object-Intelligence-Backend)
7
+ [![Live Demo](https://img.shields.io/badge/Live%20Demo-Vercel-000?style=flat&logo=vercel)](https://object-intelligence.vercel.app/)
8
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
10
+
11
+ ---
12
+
13
+ ## Table of Contents
14
+
15
+ 1. [Project Overview](#1-project-overview)
16
+ 2. [Motivation & Intent](#2-motivation--intent)
17
+ 3. [Key Features](#3-key-features)
18
+ 4. [System Architecture](#4-system-architecture)
19
+ 5. [ML Pipeline Deep Dive](#5-ml-pipeline-deep-dive)
20
+ 6. [Backend Architecture](#6-backend-architecture)
21
+ 7. [Frontend Architecture](#7-frontend-architecture)
22
+ 8. [Database Design](#8-database-design)
23
+ 9. [API Reference](#9-api-reference)
24
+ 10. [Lock Mode β€” Target Filtering](#10-lock-mode--target-filtering)
25
+ 11. [Deployment Architecture](#11-deployment-architecture)
26
+ 12. [Getting Started](#12-getting-started)
27
+ 13. [Python SDK](#13-python-sdk)
28
+ 14. [OpenCV Examples](#14-opencv-examples)
29
+ 15. [Tech Stack](#15-tech-stack)
30
+ 16. [Project Structure](#16-project-structure)
31
+ 17. [Challenges & Solutions](#17-challenges--solutions)
32
+ 18. [Future Work](#18-future-work)
33
+ 19. [License](#19-license)
34
+
35
+ ---
36
+
37
+ ## 1. Project Overview
38
+
39
+ **Object Intelligence Platform** is a full-stack computer vision system that combines three distinct detection pipelines into a single unified framework:
40
+
41
+ | Pipeline | Model | Purpose | Capability |
42
+ |----------|-------|---------|------------|
43
+ | **Known Objects** | RT-DETR-L | Detect standard objects | 80 COCO classes with high accuracy |
44
+ | **Open Vocabulary** | YOLO-World v2 | Discover objects by text description | Zero-shot detection via natural language prompts |
45
+ | **Specific Objects** | ResNet-18 Embeddings | Recognize YOUR personal objects | Teach and identify "My Cup" vs any generic cup |
46
+
47
+ The system fuses results from all three pipelines, resolves conflicts using IoU-based NMS with priority weighting, and supports a unique **Lock Mode** that suppresses all non-target detections in real-time.
48
+
49
+ **Live Links:**
50
+ - Frontend: [object-intelligence.vercel.app](https://object-intelligence.vercel.app/)
51
+ - Backend API: [muhammadpriv001-object-intelligence-backend.hf.space](https://muhammadpriv001-object-intelligence-backend.hf.space)
52
+ - Gradio UI: [Gradio Interface](https://muhammadpriv001-object-intelligence-backend.hf.space/)
53
+
54
+ ---
55
+
56
+ ## 2. Motivation & Intent
57
+
58
+ ### The Problem
59
+
60
+ Traditional object detection systems are rigid β€” they detect what they were trained on. A YOLO model trained on COCO can tell you "there is a cup" but cannot tell you "there is **YOUR** cup." Open-vocabulary models like YOLO-World solve part of this by accepting text prompts, but they still treat all instances of a class as identical.
61
+
62
+ ### Our Vision
63
+
64
+ We wanted to build a system that understands objects at **three levels of identity**:
65
+
66
+ 1. **Category level** β€” "This is a laptop" (RT-DETR, known classes)
67
+ 2. **Concept level** β€” "This matches the description 'wireless mouse'" (YOLO-World, text prompts)
68
+ 3. **Instance level** β€” "This is specifically **MY** laptop, not just any laptop" (ResNet-18 embeddings)
69
+
70
+ By combining all three, the platform achieves a richer understanding of visual scenes that approaches how humans perceive and track objects β€” recognizing both what things are and whose they are.
71
+
72
+ ### Portfolio Intent
73
+
74
+ This project demonstrates:
75
+ - **ML Engineering**: Multi-model pipeline orchestration, embedding-based retrieval, real-time inference
76
+ - **Full-Stack Development**: Next.js 16 + React 19 frontend, FastAPI + Gradio backend, SQLite persistence
77
+ - **System Design**: Microservice-like architecture with clean separation of concerns
78
+ - **Deployment**: GPU-accelerated cloud inference (HuggingFace ZeroGPU) + edge frontend (Vercel)
79
+ - **Product Thinking**: Lock Mode as a UX innovation for focused object tracking
80
+
81
+ ---
82
+
83
+ ## 3. Key Features
84
+
85
+ ### Multi-Pipeline Detection
86
+ Run any combination of RT-DETR, YOLO-World, and embedding recognition simultaneously. Results are fused using IoU-based Non-Maximum Suppression with priority weighting (specific > known > open vocabulary).
87
+
88
+ ### Open Vocabulary Discovery
89
+ Type any text description β€” "red cup," "wireless mouse," "screwdriver" β€” and YOLO-World finds matching objects without retraining. Default vocabulary includes 20 common objects; fully customizable at runtime.
90
+
91
+ ### Specific Object Recognition
92
+ Teach the system your personal objects by uploading 3-10 reference photos. A ResNet-18 backbone extracts 512-dimensional L2-normalized feature vectors. During detection, each bounding box crop is compared against stored embeddings using cosine similarity. If the match exceeds the threshold (0.70), the detection is labeled with your object's identity.
93
+
94
+ ### Lock Mode Target Filtering
95
+ Enable Lock Mode and specify a target (e.g., "My Cup"). The system suppresses ALL non-matching detections β€” only bounding boxes matching your target are displayed. Uses fuzzy matching with synonym dictionaries and word overlap logic.
96
+
97
+ ### Real-Time AR Camera Mode
98
+ WebRTC webcam stream with canvas overlay rendering. Bounding boxes are drawn in real-time with color-coded corner brackets, fill overlays, and detection labels. FPS counter and detection count displayed live.
99
+
100
+ ### Teaching Studio
101
+ Upload reference photos via drag-and-drop or live camera snapshots. Objects are stored in a portable SQLite database with full CRUD operations and ZIP export/import.
102
+
103
+ ### Python SDK
104
+ Clean `object_intelligence` package with `ObjectDetector` class for programmatic access. Supports all modes, lock mode, teaching, and OpenCV integration.
105
+
106
+ ---
107
+
108
+ ## 4. System Architecture
109
+
110
+ ```
111
+ USER INPUT
112
+ (Image / Webcam Frame)
113
+ |
114
+ +--------------+--------------+
115
+ | | |
116
+ v v v
117
+ +-----------+ +-----------+ +------------+
118
+ | RT-DETR | | YOLO-World| | ResNet-18 |
119
+ | (Known) | | (Open Voc)| | (Specific) |
120
+ +-----------+ +-----------+ +------------+
121
+ | | |
122
+ v v v
123
+ Known Object Open Vocabulary Specific Object
124
+ Detections Detections Matches
125
+ | | |
126
+ +--------------+--------------+
127
+ |
128
+ v
129
+ +-------------------+
130
+ | RESULT FUSION |
131
+ | IoU NMS + Priority|
132
+ | Deduplication |
133
+ +-------------------+
134
+ |
135
+ +----------+----------+
136
+ | |
137
+ v v
138
+ Normal Mode Lock Mode
139
+ (All Objects) (Target Only)
140
+ | |
141
+ v v
142
+ +--------------------------------+
143
+ | VISUAL ANNOTATION |
144
+ | Color-coded bounding boxes |
145
+ | Lock status banners |
146
+ +--------------------------------+
147
+ |
148
+ v
149
+ +-------------------+
150
+ | API Response |
151
+ | Annotated Image |
152
+ | Detection Metadata |
153
+ +-------------------+
154
+ ```
155
+
156
+ ### Pipeline Modes
157
+
158
+ | Mode | RT-DETR | YOLO-World | Embeddings | Use Case |
159
+ |------|---------|------------|------------|----------|
160
+ | `combined` | Yes | Yes | Yes | Full analysis (default) |
161
+ | `known` | Yes | No | No | Fast COCO-only detection |
162
+ | `open_vocabulary` | No | Yes | No | Text-prompted discovery |
163
+ | `specific` | No | No | Yes | Teach/recognize personal objects |
164
+
165
+ ---
166
+
167
+ ## 5. ML Pipeline Deep Dive
168
+
169
+ ### 5.1 RT-DETR β€” Known Object Detection
170
+
171
+ **Model**: RT-DETR-L (Real-Time Detection Transformer, Large variant)
172
+ **Weights**: `rtdetr-l.pt` (~63 MB)
173
+ **Framework**: Ultralytics
174
+ **Classes**: 80 COCO standard classes (person, car, chair, bottle, laptop, etc.)
175
+
176
+ ```
177
+ Input Image β†’ RT-DETR-L β†’ Bounding Boxes + Labels + Confidence
178
+ ```
179
+
180
+ RT-DETR is a transformer-based detector that achieves real-time performance with accuracy comparable to slower two-stage detectors. The "L" variant uses a larger backbone for better feature extraction.
181
+
182
+ **Characteristics:**
183
+ - High confidence threshold (0.60) for reliable detections
184
+ - Strong on common objects (furniture, electronics, people, vehicles)
185
+ - Fallback to YOLOv8s if RT-DETR fails to load
186
+ - Detection output: `type="known"`, `source="rtdetr"`
187
+
188
+ ### 5.2 YOLO-World β€” Open Vocabulary Discovery
189
+
190
+ **Model**: YOLO-World v2 (S variant)
191
+ **Weights**: `yolov8s-worldv2.pt` (~25 MB)
192
+ **Framework**: Ultralytics
193
+ **Default Prompts**: 20 text descriptions loaded from `open_vocabulary_classes.txt`
194
+
195
+ ```
196
+ Input Image + Text Prompts β†’ YOLO-World β†’ Bounding Boxes + Labels + Confidence
197
+ ```
198
+
199
+ YOLO-World performs **zero-shot detection** β€” it finds objects matching any text description without task-specific training. The vocabulary is set dynamically via `model.set_classes(prompts)`.
200
+
201
+ **Default Vocabulary (20 classes):**
202
+ ```
203
+ person, cup, laptop, smartphone, water bottle, backpack, screwdriver,
204
+ coffee mug, wireless mouse, keyboard, chair, headphone, book, keychain,
205
+ glass, glasses, jacket, umbrella, helmet, desk lamp
206
+ ```
207
+
208
+ **Characteristics:**
209
+ - Lower confidence threshold (0.35) to catch more possibilities
210
+ - Vocabulary is fully customizable at runtime via API or UI
211
+ - Fallback to YOLOv8s if YOLO-World fails to load
212
+ - Detection output: `type="open_vocabulary"`, `source="yolo_world"`
213
+
214
+ ### 5.3 ResNet-18 β€” Specific Object Recognition
215
+
216
+ **Model**: ResNet-18 (pretrained on ImageNet)
217
+ **Backbone**: `torchvision.models.resnet18` with final FC layer removed
218
+ **Output**: 512-dimensional L2-normalized feature vector
219
+ **Similarity**: Cosine similarity (dot product of normalized vectors)
220
+
221
+ ```
222
+ Reference Photos β†’ ResNet-18 β†’ L2-Normalized Embeddings β†’ SQLite Storage
223
+ |
224
+ Detection Crop β†’ ResNet-18 β†’ Query Embedding β†’ Cosine Search β†’ Match?
225
+ ```
226
+
227
+ **Teaching Flow:**
228
+ 1. User provides object name + 3-10 reference photos
229
+ 2. Each photo is resized to 224x224, normalized with ImageNet stats
230
+ 3. Forward pass through ResNet-18 (minus FC layer) produces 512-dim vector
231
+ 4. Vector is L2-normalized and stored in `object_embeddings` table as JSON
232
+
233
+ **Recognition Flow:**
234
+ 1. After RT-DETR/YOLO-World produce bounding boxes
235
+ 2. Each bounding box is cropped from the original image
236
+ 3. Crop is passed through ResNet-18 to get a query embedding
237
+ 4. Brute-force cosine similarity search over ALL stored embeddings
238
+ 5. If best similarity >= threshold (0.70), detection label is overridden with the specific object name
239
+
240
+ **Characteristics:**
241
+ - Threshold: 0.70 similarity for a match
242
+ - Works best with 3-10 diverse reference photos (different angles, lighting)
243
+ - Embeddings are viewpoint-invariant to a degree (ResNet features capture shape, texture, color patterns)
244
+ - Detection output: `type="specific"`, `source="embedding"`, `specific_identity="Object Name"`
245
+
246
+ ### 5.4 Result Fusion Engine
247
+
248
+ The `ResultFusionEngine` merges detection lists from multiple pipelines:
249
+
250
+ 1. **Priority Sorting**: Detections are sorted by type priority (specific=3 > known=2 > open_vocabulary=1), then by confidence
251
+ 2. **IoU Deduplication**: For each detection pair, if IoU >= 0.50, the lower-priority detection is removed
252
+ 3. **Smart Label Override**: If a `specific` detection overlaps a `known`/`open_vocabulary` detection, the existing detection's label is replaced with the specific identity
253
+
254
+ This ensures that when the system recognizes "My Cup" in a bounding box also detected as "cup" by RT-DETR, the specific identity takes precedence.
255
+
256
+ ### 5.5 Lock Mode Controller
257
+
258
+ The `LockModeController` filters detections based on a target string:
259
+
260
+ 1. **Fuzzy Matching**:
261
+ - Strips common prefixes ("my ", "the ", "a ", "an ")
262
+ - Normalizes labels, categories, and specific_identity fields
263
+ - Synonym dictionary: "mobile" = "cell phone" = "phone" = "smartphone"
264
+ - Word overlap matching: "My Cup" matches "coffee cup" (cup is common)
265
+
266
+ 2. **Filtering**: Only detections matching the target are kept; all others are suppressed
267
+
268
+ 3. **Visual Feedback**:
269
+ - Lock active + match found: Purple lock banner
270
+ - Lock active + NOT FOUND: Red "NOT FOUND" banner
271
+ - Color scheme shifts to pink/magenta when locked
272
+
273
+ ---
274
+
275
+ ## 6. Backend Architecture
276
+
277
+ ### Entry Point: `app.py`
278
+
279
+ The backend is a single `app.py` file that combines:
280
+
281
+ 1. **Gradio Blocks UI** β€” The interactive web interface with 5 tabs (Live Testing, Object Studio, Downloads, Guides, API Reference)
282
+ 2. **FastAPI Routes** β€” Registered via ASGI middleware that intercepts `/api/*` requests before Gradio's catch-all routes
283
+ 3. **ZeroGPU Integration** β€” `@spaces.GPU` decorators on key functions for GPU allocation on HuggingFace Spaces
284
+
285
+ ### ASGI Middleware
286
+
287
+ A custom `CustomAPIMiddleware` (Starlette `BaseHTTPMiddleware`) intercepts API routes:
288
+
289
+ ```
290
+ Request β†’ CustomAPIMiddleware β†’ (matches /api/*?) β†’ Handle directly
291
+ ↓ (no match)
292
+ Gradio's route handler
293
+ ```
294
+
295
+ This architecture solves the route conflict between FastAPI custom routes and Gradio's auto-generated `/api/{api_name}` catch-all routes. The middleware runs at the ASGI level, before FastAPI route matching.
296
+
297
+ ### Key Backend Components
298
+
299
+ | File | Class | Purpose |
300
+ |------|-------|---------|
301
+ | `backend/config.py` | β€” | Central configuration: paths, thresholds, device detection |
302
+ | `backend/ml/orchestrator.py` | `ObjectIntelligenceOrchestrator` | 5-step pipeline orchestrator (lazy singleton) |
303
+ | `backend/ml/rtdetr_detector.py` | `RTDETRDetector` | RT-DETR known object detection |
304
+ | `backend/ml/yolo_world_detector.py` | `YOLOWorldDetector` | YOLO-World open vocabulary detection |
305
+ | `backend/ml/embedding_recognizer.py` | `EmbeddingRecognizer` | ResNet-18 feature extraction + cosine matching |
306
+ | `backend/ml/fusion.py` | `ResultFusionEngine` | IoU-based NMS + priority deduplication |
307
+ | `backend/ml/lock_mode.py` | `LockModeController` | Target filtering + visual annotation |
308
+ | `backend/database/storage.py` | `DatabaseManager` | SQLite CRUD, cosine search, ZIP export |
309
+ | `backend/database/models.py` | β€” | Dataclass definitions |
310
+
311
+ ### ZeroGPU Compatibility
312
+
313
+ HuggingFace ZeroGPU requires CUDA operations to happen inside `@spaces.GPU` decorated functions. The orchestrator uses **lazy loading** β€” models are only instantiated when a GPU function is first called, ensuring all CUDA operations happen within ZeroGPU's allocation context.
314
+
315
+ ```python
316
+ # Models load HERE, inside @spaces.GPU context:
317
+ @spaces.GPU
318
+ def run_gradio_detection(...):
319
+ annotated_bgr, detections, metadata = get_orchestrator().process_frame(...)
320
+ # orchestrator is created on first call, models loaded with GPU available
321
+ ```
322
+
323
+ ---
324
+
325
+ ## 7. Frontend Architecture
326
+
327
+ ### Tech Stack
328
+ - **Framework**: Next.js 16.3.3 (App Router)
329
+ - **React**: 19.2.8
330
+ - **TypeScript**: 5.x
331
+ - **3D Graphics**: Three.js 0.185 (wireframe parallax scene)
332
+ - **Animations**: GSAP 3.15
333
+ - **Icons**: Lucide React
334
+
335
+ ### Pages
336
+
337
+ | Route | Page | Description |
338
+ |-------|------|-------------|
339
+ | `/` | Home | Hero section, pipeline cards, 6-step visualization, Lock Mode preview |
340
+ | `/live` | Live Testing | Upload image or real-time AR camera with canvas overlay |
341
+ | `/objects` | Object Studio | Teach objects via file upload or camera snapshots, manage library |
342
+ | `/downloads` | Downloads | Model weights, OpenCV examples, database export |
343
+ | `/guides` | Developer Guides | 5 inline markdown guides with sidebar navigation |
344
+
345
+ ### Design System
346
+
347
+ The frontend uses a custom **neumorphism** design system:
348
+
349
+ - **Colors**: Primary blue (#1E90FF), emerald (#10b981), pink (#ec4899), dark background (#0a0e17)
350
+ - **Components**: `.neu-card`, `.neu-btn`, `.neu-input` with dual-direction shadows
351
+ - **Animations**: fadeInUp, slideInRight, scaleIn with stagger delays
352
+ - **Responsive**: Desktop navbar hidden on mobile, full-screen animated mobile menu
353
+
354
+ ### 3D Parallax Scene
355
+
356
+ The home page features a Three.js WebGL scene with:
357
+ - 7 large background wireframe shapes (Icosahedron, Octahedron, Tetrahedron, Box, Dodecahedron)
358
+ - 14 mid-layer shapes, 18 small front-layer shapes, 20 tiny scattered shapes
359
+ - 6 bounding box outlines (CV-themed), 4 crosshair markers, 4 diamond detection markers
360
+ - 300 particles, 120 twinkling stars
361
+ - Mouse parallax tracking + click scatter physics
362
+
363
+ ### Camera AR Mode
364
+
365
+ Real-time webcam processing with canvas overlay:
366
+ - WebRTC stream β†’ Canvas capture β†’ Backend detection β†’ Canvas overlay rendering
367
+ - Color-coded corner brackets: specific=purple, open_vocab=blue, known=green, lock=pink
368
+ - FPS counter and detection count displayed live
369
+ - Continuous frame loop with `requestAnimationFrame`
370
+
371
+ ### API Communication
372
+
373
+ ```typescript
374
+ // lib/api.ts β€” constructs backend URLs
375
+ export function getApiUrl(path: string): string {
376
+ const envUrl = process.env.NEXT_PUBLIC_API_URL || "";
377
+ if (envUrl) {
378
+ // Production: direct cross-origin to HuggingFace Space
379
+ return `${envUrl}/api${path}`;
380
+ }
381
+ // Development: proxied via Next.js rewrites
382
+ return `/backend-api${path}`;
383
+ }
384
+ ```
385
+
386
+ ---
387
+
388
+ ## 8. Database Design
389
+
390
+ ### Schema (SQLite)
391
+
392
+ ```sql
393
+ -- Core entity: a taught object
394
+ CREATE TABLE objects (
395
+ id TEXT PRIMARY KEY, -- "obj_<uuid_hex_10>"
396
+ user_id TEXT,
397
+ name TEXT UNIQUE NOT NULL,
398
+ category TEXT NOT NULL,
399
+ description TEXT,
400
+ status TEXT DEFAULT 'active',
401
+ created_at TEXT NOT NULL,
402
+ updated_at TEXT NOT NULL
403
+ );
404
+
405
+ -- Reference images for each object
406
+ CREATE TABLE object_images (
407
+ id TEXT PRIMARY KEY, -- "img_<uuid_hex_10>"
408
+ object_id TEXT NOT NULL, -- FK β†’ objects.id
409
+ file_path TEXT NOT NULL,
410
+ image_hash TEXT,
411
+ created_at TEXT NOT NULL
412
+ );
413
+
414
+ -- 512-dimensional embedding vectors (stored as JSON)
415
+ CREATE TABLE object_embeddings (
416
+ id TEXT PRIMARY KEY, -- "emb_<uuid_hex_10>"
417
+ object_id TEXT NOT NULL, -- FK β†’ objects.id
418
+ model_name TEXT NOT NULL, -- "resnet18"
419
+ model_version TEXT NOT NULL, -- "1.0"
420
+ embedding TEXT NOT NULL, -- JSON array of 512 floats
421
+ created_at TEXT NOT NULL
422
+ );
423
+
424
+ -- Detection event logging
425
+ CREATE TABLE detection_logs (
426
+ id TEXT PRIMARY KEY, -- "log_<uuid_hex_10>"
427
+ user_id TEXT,
428
+ object_name TEXT NOT NULL,
429
+ detection_type TEXT NOT NULL, -- "known", "open_vocabulary", "specific"
430
+ confidence REAL NOT NULL,
431
+ timestamp TEXT NOT NULL
432
+ );
433
+ ```
434
+
435
+ ### Key Operations
436
+
437
+ | Operation | SQL | Description |
438
+ |-----------|-----|-------------|
439
+ | Find best match | Brute-force cosine similarity over all embeddings | Returns object with similarity >= threshold |
440
+ | Export database | `ZIP(database.db + manifest.json)` | Portable library export |
441
+ | Cascade delete | Delete embeddings β†’ images β†’ object | Clean object removal |
442
+
443
+ ---
444
+
445
+ ## 9. API Reference
446
+
447
+ All endpoints are intercepted by `CustomAPIMiddleware` before reaching Gradio's routes.
448
+
449
+ ### `GET /api/health`
450
+
451
+ Returns system health status and model load state.
452
+
453
+ ```json
454
+ {
455
+ "status": "healthy",
456
+ "models": {
457
+ "rtdetr": true,
458
+ "yolo_world": true,
459
+ "embedding_recognizer": true
460
+ },
461
+ "database": true
462
+ }
463
+ ```
464
+
465
+ ### `POST /api/detect`
466
+
467
+ Run detection pipeline on an uploaded image.
468
+
469
+ **Request**: `multipart/form-data`
470
+
471
+ | Field | Type | Default | Description |
472
+ |-------|------|---------|-------------|
473
+ | `file` | File | required | Image file (JPEG, PNG, etc.) |
474
+ | `mode` | string | `"combined"` | Pipeline mode: combined, known, open_vocabulary, specific |
475
+ | `lock_mode` | string | `"false"` | Enable lock mode filtering |
476
+ | `lock_target` | string | `""` | Target object name for lock mode |
477
+ | `open_vocab_prompts` | string | `""` | Comma-separated YOLO-World prompts |
478
+ | `confidence` | string | `""` | Detection confidence threshold |
479
+
480
+ **Response**:
481
+ ```json
482
+ {
483
+ "status": "success",
484
+ "image_base64": "<base64-encoded annotated PNG>",
485
+ "metadata": {
486
+ "mode": "combined",
487
+ "lock_mode": false,
488
+ "lock_target": null,
489
+ "detection_count": 3,
490
+ "detections": [...]
491
+ },
492
+ "detections": [
493
+ {
494
+ "bbox": [120, 80, 340, 290],
495
+ "label": "My Cup",
496
+ "category": "cup",
497
+ "confidence": 0.94,
498
+ "type": "specific",
499
+ "source": "embedding",
500
+ "specific_identity": "My Cup"
501
+ }
502
+ ]
503
+ }
504
+ ```
505
+
506
+ ### `GET /api/objects`
507
+
508
+ List all taught objects with image and embedding counts.
509
+
510
+ ### `POST /api/objects`
511
+
512
+ Teach a new object with reference photos.
513
+
514
+ **Request**: `multipart/form-data` with `name`, `category`, `description`, `files` (multiple)
515
+
516
+ ### `DELETE /api/objects/{object_id}`
517
+
518
+ Delete a taught object and all associated data.
519
+
520
+ ### `GET /api/downloads/export-db`
521
+
522
+ Download the object database as a ZIP archive.
523
+
524
+ ---
525
+
526
+ ## 10. Lock Mode β€” Target Filtering
527
+
528
+ ### Concept
529
+
530
+ Lock Mode is a unique feature that restricts the detection output to **only** objects matching a user-specified target. When enabled:
531
+
532
+ 1. All detections are evaluated against the target string
533
+ 2. Non-matching detections are completely suppressed (not drawn, not returned)
534
+ 3. The visual overlay shifts to a pink/magenta color scheme
535
+ 4. A lock status banner appears (purple = match found, red = NOT FOUND)
536
+
537
+ ### Matching Algorithm
538
+
539
+ ```python
540
+ def is_match(detection, target):
541
+ # 1. Strip common prefixes
542
+ target = target.strip().lower()
543
+ for prefix in ["my ", "the ", "a ", "an "]:
544
+ if target.startswith(prefix):
545
+ target = target[len(prefix):]
546
+
547
+ # 2. Check against label, category, specific_identity
548
+ for field in [label, category, specific_identity]:
549
+ if field and target in field.lower():
550
+ return True
551
+
552
+ # 3. Synonym dictionary lookup
553
+ if target in synonym_dict and any(s in field for s in synonym_dict[target]):
554
+ return True
555
+
556
+ # 4. Word overlap matching
557
+ target_words = set(target.split())
558
+ field_words = set(field.lower().split())
559
+ if target_words.issubset(field_words) or field_words.issubset(target_words):
560
+ return True
561
+
562
+ return False
563
+ ```
564
+
565
+ ### Synonym Dictionary
566
+
567
+ ```python
568
+ synonyms = {
569
+ "mobile": ["cell phone", "phone", "smartphone"],
570
+ "laptop": ["computer", "notebook"],
571
+ "tv": ["television", "monitor", "screen"],
572
+ "sofa": ["couch"],
573
+ "cup": ["mug", "glass"],
574
+ "backpack": ["bag", "knapsack"],
575
+ }
576
+ ```
577
+
578
+ ### Use Cases
579
+
580
+ - **Warehouse picking**: Lock onto a specific item SKU to guide workers
581
+ - **Security**: Track a specific person or object across frames
582
+ - **Accessibility**: Help visually impaired users locate specific items
583
+ - **Quality control**: Focus on a specific defect type in manufacturing
584
+
585
+ ---
586
+
587
+ ## 11. Deployment Architecture
588
+
589
+ ```
590
+ +---------------------------+
591
+ | VERCEL (CDN) |
592
+ | Next.js 16 Frontend |
593
+ | object-intelligence. |
594
+ | vercel.app |
595
+ +-------------+-------------+
596
+ |
597
+ HTTPS API calls
598
+ |
599
+ +-------------v-------------+
600
+ | HUGGINGFACE SPACES (GPU) |
601
+ | ZeroGPU T4 Instance |
602
+ | Gradio 4.44.1 + FastAPI |
603
+ | RT-DETR + YOLO-World + |
604
+ | ResNet-18 + SQLite |
605
+ +---------------------------+
606
+ ```
607
+
608
+ ### HuggingFace Spaces (Backend)
609
+
610
+ - **SDK**: Gradio 4.44.1
611
+ - **Hardware**: GPU (T4 via ZeroGPU allocation)
612
+ - **Entry Point**: `app.py`
613
+ - **Features**:
614
+ - `@spaces.GPU` decorators for GPU allocation
615
+ - Lazy model loading to satisfy ZeroGPU initialization
616
+ - Startup probe (`_zerogpu_startup_probe`) for GPU context
617
+ - CORS enabled for cross-origin Vercel frontend
618
+ - Auto-downloads model weights on first inference
619
+
620
+ ### Vercel (Frontend)
621
+
622
+ - **Framework**: Next.js 16.3.3 with App Router
623
+ - **React**: 19.2.8
624
+ - **Build**: Static export with client-side API calls
625
+ - **Environment Variable**: `NEXT_PUBLIC_API_URL` pointing to HuggingFace Space
626
+
627
+ ### ZeroGPU Integration Details
628
+
629
+ ZeroGPU dynamically allocates GPU time to functions decorated with `@spaces.GPU`. The key challenge was ensuring model loading happens inside GPU context:
630
+
631
+ ```python
632
+ # Problem: Models loaded at import time (no GPU)
633
+ orchestrator = ObjectIntelligenceOrchestrator() # ← CUDA fails
634
+
635
+ # Solution: Lazy loading inside @spaces.GPU function
636
+ _orchestrator_instance = None
637
+ def get_orchestrator():
638
+ global _orchestrator_instance
639
+ if _orchestrator_instance is None:
640
+ _orchestrator_instance = ObjectIntelligenceOrchestrator() # ← GPU available
641
+ return _orchestrator_instance
642
+ ```
643
+
644
+ ---
645
+
646
+ ## 12. Getting Started
647
+
648
+ ### Prerequisites
649
+
650
+ - Python 3.10+
651
+ - Node.js 18+ (for frontend)
652
+ - CUDA-capable GPU (optional, falls back to CPU)
653
+
654
+ ### Installation
655
+
656
+ ```bash
657
+ # Clone repository
658
+ git clone https://github.com/muhammadpriv001/Object-Intelligence.git
659
+ cd Object-Intelligence
660
+
661
+ # Install Python dependencies
662
+ pip install -r requirements.txt
663
+
664
+ # Install frontend dependencies
665
+ cd frontend
666
+ npm install
667
+ cd ..
668
+ ```
669
+
670
+ ### Running Locally
671
+
672
+ ```bash
673
+ # Start backend (port 7860)
674
+ python app.py
675
+
676
+ # In a separate terminal, start frontend (port 3000)
677
+ cd frontend
678
+ npm run dev
679
+ ```
680
+
681
+ Open [http://localhost:3000](http://localhost:3000) for the frontend, or [http://localhost:7860](http://localhost:7860) for the Gradio UI directly.
682
+
683
+ ### Environment Variables
684
+
685
+ | Variable | Default | Description |
686
+ |----------|---------|-------------|
687
+ | `NEXT_PUBLIC_API_URL` | `""` (uses proxy) | Backend API URL. Set to `http://localhost:7860` for local dev |
688
+
689
+ ---
690
+
691
+ ## 13. Python SDK
692
+
693
+ ### Installation
694
+
695
+ ```python
696
+ from object_intelligence import ObjectDetector
697
+ import cv2
698
+ ```
699
+
700
+ ### Basic Detection
701
+
702
+ ```python
703
+ detector = ObjectDetector()
704
+
705
+ # Process a frame
706
+ frame = cv2.imread("sample.jpg")
707
+ annotated_frame, detections = detector.detect_and_draw(frame)
708
+
709
+ for det in detections:
710
+ print(f"{det['label']}: {det['confidence']:.1%} ({det['type']})")
711
+ ```
712
+
713
+ ### Lock Mode
714
+
715
+ ```python
716
+ detector = ObjectDetector()
717
+ detector.set_mode("combined")
718
+ detector.lock("My Cup")
719
+
720
+ frame = cv2.imread("sample.jpg")
721
+ annotated_frame, detections = detector.detect_and_draw(frame)
722
+ # Only "My Cup" detections are returned
723
+ ```
724
+
725
+ ### Teaching Objects
726
+
727
+ ```python
728
+ detector = ObjectDetector()
729
+ detector.add_object(
730
+ name="My Cup",
731
+ images=["cup_front.jpg", "cup_back.jpg", "cup_side.jpg"],
732
+ category="Drinkware",
733
+ description="Personal blue mug with handle"
734
+ )
735
+ ```
736
+
737
+ ### Open Vocabulary
738
+
739
+ ```python
740
+ detector = ObjectDetector()
741
+ detector.set_mode("open_vocabulary")
742
+ detector.set_vocabulary(["red cup", "laptop", "screwdriver", "wireless mouse"])
743
+
744
+ frame = cv2.imread("sample.jpg")
745
+ annotated_frame, detections = detector.detect_and_draw(frame)
746
+ ```
747
+
748
+ ---
749
+
750
+ ## 14. OpenCV Examples
751
+
752
+ Five ready-to-run OpenCV webcam scripts in `examples/`:
753
+
754
+ | Script | Description |
755
+ |--------|-------------|
756
+ | `opencv_known_objects.py` | RT-DETR detection of standard COCO objects |
757
+ | `opencv_open_vocabulary.py` | YOLO-World text-prompted detection |
758
+ | `opencv_specific_object.py` | Visual embedding recognition |
759
+ | `opencv_lock_mode.py` | Target lock filtering with real-time webcam |
760
+ | `opencv_combined.py` | Full multi-pipeline fusion |
761
+
762
+ ---
763
+
764
+ ## 15. Tech Stack
765
+
766
+ ### Backend
767
+
768
+ | Technology | Version | Purpose |
769
+ |------------|---------|---------|
770
+ | Python | 3.10+ | Core language |
771
+ | PyTorch | 2.0+ | Deep learning framework |
772
+ | Ultralytics | 8.1+ | RT-DETR and YOLO-World inference |
773
+ | Torchvision | 0.15+ | ResNet-18 backbone |
774
+ | Gradio | 4.44.1 | Web UI framework |
775
+ | FastAPI | 0.100+ | REST API framework |
776
+ | Uvicorn | 0.20+ | ASGI server |
777
+ | SQLite | β€” | Embedded database |
778
+ | OpenCV | 4.8+ | Image processing |
779
+ | NumPy | 1.22+ | Numerical operations |
780
+
781
+ ### Frontend
782
+
783
+ | Technology | Version | Purpose |
784
+ |------------|---------|---------|
785
+ | Next.js | 16.3.3 | React framework (App Router) |
786
+ | React | 19.2.8 | UI library |
787
+ | TypeScript | 5.x | Type-safe JavaScript |
788
+ | Three.js | 0.185 | 3D WebGL graphics |
789
+ | GSAP | 3.15 | Animation library |
790
+ | Lucide React | 1.37 | Icon library |
791
+
792
+ ### Deployment
793
+
794
+ | Service | Purpose |
795
+ |---------|---------|
796
+ | HuggingFace Spaces | GPU backend (ZeroGPU T4) |
797
+ | Vercel | Frontend CDN + static hosting |
798
+ | Git LFS | Model weight version control |
799
+
800
+ ---
801
+
802
+ ## 16. Project Structure
803
+
804
+ ```
805
+ Object-Intelligence/
806
+ β”œβ”€β”€ app.py # Main entry: Gradio UI + FastAPI + ZeroGPU
807
+ β”œβ”€β”€ requirements.txt # Python dependencies
808
+ β”œβ”€β”€ rtdetr-l.pt # RT-DETR weights (Git LFS)
809
+ β”œβ”€β”€ yolov8s-worldv2.pt # YOLO-World weights (Git LFS)
810
+ β”œβ”€β”€ open_vocabulary_classes.txt # Default YOLO-World prompts
811
+ β”‚
812
+ β”œβ”€β”€ backend/
813
+ β”‚ β”œβ”€β”€ config.py # Central configuration
814
+ β”‚ β”œβ”€β”€ database/
815
+ β”‚ β”‚ β”œβ”€β”€ models.py # Dataclass definitions
816
+ β”‚ β”‚ └── storage.py # SQLite manager + cosine search
817
+ β”‚ └── ml/
818
+ β”‚ β”œβ”€β”€ orchestrator.py # 5-step pipeline orchestrator
819
+ β”‚ β”œβ”€β”€ rtdetr_detector.py # RT-DETR detector
820
+ β”‚ β”œβ”€β”€ yolo_world_detector.py # YOLO-World detector
821
+ β”‚ β”œβ”€β”€ embedding_recognizer.py # ResNet-18 embeddings
822
+ β”‚ β”œβ”€β”€ fusion.py # IoU NMS + priority fusion
823
+ β”‚ └── lock_mode.py # Target filtering + annotations
824
+ β”‚
825
+ β”œβ”€β”€ object_intelligence/
826
+ β”‚ └── detector.py # Python SDK client
827
+ β”‚
828
+ β”œβ”€β”€ examples/ # OpenCV webcam scripts (5 files)
829
+ β”‚
830
+ β”œβ”€β”€ docs/ # Documentation (8 guides)
831
+ β”‚
832
+ β”œβ”€β”€ database/
833
+ β”‚ β”œβ”€β”€ objects.db # SQLite database (auto-created)
834
+ β”‚ └── object_images/ # Reference image storage
835
+ β”‚
836
+ └── frontend/ # Next.js 16 frontend
837
+ β”œβ”€β”€ app/
838
+ β”‚ β”œβ”€β”€ page.tsx # Home page
839
+ β”‚ β”œβ”€β”€ live/page.tsx # Live Testing + AR Camera
840
+ β”‚ β”œβ”€β”€ objects/page.tsx # Object Studio
841
+ β”‚ β”œβ”€β”€ downloads/page.tsx # Downloads & Resources
842
+ β”‚ └── guides/page.tsx # Developer Guides
843
+ β”œβ”€β”€ components/
844
+ β”‚ β”œβ”€β”€ Navbar.tsx # Sticky navigation
845
+ β”‚ β”œβ”€β”€ Footer.tsx # Footer with tech badges
846
+ β”‚ β”œβ”€β”€ MobileMenu.tsx # Animated mobile menu
847
+ β”‚ └── ParallaxScene.tsx # Three.js 3D background
848
+ └── lib/
849
+ └── api.ts # Backend API URL construction
850
+ ```
851
+
852
+ ---
853
+
854
+ ## 17. Challenges & Solutions
855
+
856
+ ### Challenge 1: ZeroGPU CUDA Initialization
857
+ **Problem**: Models loaded at module import time triggered CUDA operations outside ZeroGPU's GPU allocation context.
858
+
859
+ **Solution**: Implemented lazy loading via `get_orchestrator()` singleton pattern. Models are only instantiated when a `@spaces.GPU` decorated function is first called, ensuring all CUDA operations happen within ZeroGPU's allocation context.
860
+
861
+ ### Challenge 2: FastAPI Route Conflict with Gradio
862
+ **Problem**: Gradio registers a catch-all route `POST /api/{api_name}` that intercepts all `/api/*` requests, preventing custom FastAPI routes from being reached.
863
+
864
+ **Solution**: Used Starlette `BaseHTTPMiddleware` (ASGI middleware) that intercepts requests at the ASGI level, BEFORE FastAPI route matching. This allows custom API handlers to process requests before Gradio's catch-all can intercept them.
865
+
866
+ ### Challenge 3: Frontend-Backend CORS
867
+ **Problem**: Cross-origin requests from Vercel frontend to HuggingFace backend require proper CORS handling.
868
+
869
+ **Solution**: Added CORS middleware with `allow_origins=["*"]` to the FastAPI app, enabling cross-origin requests from any domain.
870
+
871
+ ### Challenge 4: Model Weight Persistence
872
+ **Problem**: Model weights (~130MB total) need to persist across HuggingFace Space restarts.
873
+
874
+ **Solution**: Used Git LFS for version control and Ultralytics auto-download on first inference. The `huggingface_hub<1.0` pin ensures Gradio 4.x compatibility.
875
+
876
+ ### Challenge 5: Real-Time AR Performance
877
+ **Problem**: Continuous webcam frame processing needs to maintain acceptable FPS while sending frames to the backend.
878
+
879
+ **Solution**: Implemented `requestAnimationFrame` loop with `isProcessingRef` guard to prevent frame pile-up. JPEG compression at 70% quality reduces upload size. Canvas overlay rendering runs independently of backend calls.
880
+
881
+ ---
882
+
883
+ ## 18. Future Work
884
+
885
+ ### Short Term
886
+ - [ ] Add batch detection for multiple images
887
+ - [ ] Implement embedding clustering for automatic object categorization
888
+ - [ ] Add WebRTC for lower-latency webcam streaming
889
+ - [ ] Support video file upload and frame-by-frame analysis
890
+
891
+ ### Medium Term
892
+ - [ ] PostgreSQL + pgvector migration for production-scale embedding search
893
+ - [ ] User authentication and multi-tenant object libraries
894
+ - [ ] Mobile app (React Native) with on-device inference
895
+ - [ ] Model fine-tuning pipeline for domain-specific objects
896
+
897
+ ### Long Term
898
+ - [ ] Edge deployment (TensorRT, ONNX Runtime) for offline use
899
+ - [ ] 3D object pose estimation integration
900
+ - [ ] Multi-camera tracking and re-identification
901
+ - [ ] Natural language scene description generation
902
+
903
+ ---
904
+
905
+ ## 19. License
906
+
907
+ Distributed under the MIT License. See `LICENSE` for details.
908
+
909
+ ```
910
+ MIT License
911
+
912
+ Copyright (c) 2026 Muhammad
913
+
914
+ Permission is hereby granted, free of charge, to any person obtaining a copy
915
+ of this software and associated documentation files (the "Software"), to deal
916
+ in the Software without restriction, including without limitation the rights
917
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
918
+ copies of the Software, and to permit persons to whom the Software is
919
+ furnished to do so, subject to the following conditions:
920
+
921
+ The above copyright notice and this permission notice shall be included in all
922
+ copies or substantial portions of the Software.
923
+
924
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
925
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
926
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
927
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
928
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
929
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
930
+ SOFTWARE.
931
+ ```
932
+
933
+ ---
934
+
935
+ <p align="center">
936
+ <strong>Object Intelligence Platform</strong><br>
937
+ Built with PyTorch, Ultralytics, Gradio, FastAPI, Next.js, and Three.js<br>
938
+ <a href="https://object-intelligence.vercel.app/">Live Demo</a> Β·
939
+ <a href="https://huggingface.co/spaces/muhammadpriv001/Object-Intelligence-Backend">Backend</a> Β·
940
+ <a href="https://github.com/muhammadpriv001/Object-Intelligence">GitHub</a>
941
+ </p>