-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.py
More file actions
226 lines (192 loc) Β· 8.33 KB
/
demo.py
File metadata and controls
226 lines (192 loc) Β· 8.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python3
"""
Demo script for the Vision-based Personal Memory Assistant.
This script demonstrates the system with sample data.
"""
import sys
from pathlib import Path
import logging
from datetime import datetime, timedelta
import json
# Add the project root to Python path
sys.path.append(str(Path(__file__).parent))
from config.settings import settings
from memory.database import MemoryDatabase
from vision.detector import ObjectDetector
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def create_sample_data():
"""Create sample memory data for demonstration."""
sample_memories = [
{
"timestamp": datetime.now() - timedelta(hours=2),
"scene_description": "A person working at a desk with a laptop, coffee cup, and phone visible",
"objects_detected": ["laptop", "cup", "phone", "chair", "desk"],
"context_info": {"location_type": "indoor", "activity_type": "working"}
},
{
"timestamp": datetime.now() - timedelta(hours=4),
"scene_description": "Kitchen scene with coffee maker, plates, and utensils on the counter",
"objects_detected": ["cup", "plate", "spoon", "bowl", "coffee maker"],
"context_info": {"location_type": "indoor", "activity_type": "cooking/eating"}
},
{
"timestamp": datetime.now() - timedelta(hours=6),
"scene_description": "Living room with TV, remote control, and couch visible",
"objects_detected": ["tv", "remote", "couch", "table", "lamp"],
"context_info": {"location_type": "indoor", "activity_type": "living/relaxing"}
},
{
"timestamp": datetime.now() - timedelta(days=1),
"scene_description": "Outdoor scene with car, trees, and buildings in the background",
"objects_detected": ["car", "tree", "building", "road", "sky"],
"context_info": {"location_type": "outdoor", "activity_type": "unknown"}
},
{
"timestamp": datetime.now() - timedelta(days=2),
"scene_description": "Bedroom with bed, nightstand, and alarm clock visible",
"objects_detected": ["bed", "clock", "lamp", "table", "chair"],
"context_info": {"location_type": "indoor", "activity_type": "sleeping"}
}
]
return sample_memories
def demo_database_operations():
"""Demonstrate database operations with sample data."""
print("ποΈ Database Operations Demo")
print("=" * 40)
# Initialize database
db = MemoryDatabase()
# Create sample data
sample_memories = create_sample_data()
# Add sample memories
print("π Adding sample memories...")
for i, memory in enumerate(sample_memories, 1):
memory_id = db.add_memory(
image_path=f"sample_image_{i}.jpg",
timestamp=memory["timestamp"],
scene_description=memory["scene_description"],
objects_detected=memory["objects_detected"],
context_info=memory["context_info"]
)
print(f" β
Added memory {i}: {memory['scene_description'][:50]}...")
# Get statistics
stats = db.get_statistics()
print(f"\nπ Statistics:")
print(f" Total memories: {stats['total_memories']}")
print(f" Memories today: {stats['memories_today']}")
print(f" Most common objects: {[obj for obj, count in stats['most_common_objects'][:5]]}")
# Search demonstrations
print(f"\nπ Search Demonstrations:")
# Search by objects
laptop_memories = db.get_memories_by_objects(["laptop"])
print(f" Memories with laptop: {len(laptop_memories)}")
# Search by date range
today_memories = db.get_memories_by_date_range(
datetime.now().replace(hour=0, minute=0, second=0),
datetime.now()
)
print(f" Memories from today: {len(today_memories)}")
# Get recent memories
recent = db.get_recent_memories(3)
print(f" Recent memories: {len(recent)}")
return db
def demo_query_simulation():
"""Simulate natural language queries."""
print("\nπ€ Natural Language Query Simulation")
print("=" * 40)
db = MemoryDatabase()
# Simulate different types of queries
queries = [
"When did I last see my laptop?",
"Show me when I was in the kitchen",
"Find memories from today",
"When was I working at my desk?",
"Show me outdoor scenes"
]
for query in queries:
print(f"\nβ Query: '{query}'")
# Simple keyword matching simulation
if "laptop" in query.lower():
results = db.get_memories_by_objects(["laptop"])
print(f" Found {len(results)} memories with laptop")
if results:
memory = results[0]
print(f" π
{memory['timestamp'].strftime('%B %d at %I:%M %p')}")
print(f" π {memory['scene_description']}")
elif "kitchen" in query.lower():
results = db.search_memories(query="kitchen")
print(f" Found {len(results)} kitchen-related memories")
if results:
memory = results[0]
print(f" π
{memory['timestamp'].strftime('%B %d at %I:%M %p')}")
print(f" π {memory['scene_description']}")
elif "today" in query.lower():
today_memories = db.get_memories_by_date_range(
datetime.now().replace(hour=0, minute=0, second=0),
datetime.now()
)
print(f" Found {len(today_memories)} memories from today")
for memory in today_memories[:2]:
print(f" π
{memory['timestamp'].strftime('%I:%M %p')}: {memory['scene_description'][:50]}...")
elif "outdoor" in query.lower():
results = db.search_memories(query="outdoor")
print(f" Found {len(results)} outdoor memories")
if results:
memory = results[0]
print(f" π
{memory['timestamp'].strftime('%B %d at %I:%M %p')}")
print(f" π {memory['scene_description']}")
def demo_object_detection():
"""Demonstrate object detection capabilities."""
print("\nπ Object Detection Demo")
print("=" * 40)
# Sample detection results
sample_detections = [
{
"objects": ["laptop", "cup", "phone", "chair", "desk"],
"scene": "Working at desk",
"context": {"location_type": "indoor", "activity_type": "working"}
},
{
"objects": ["cup", "plate", "spoon", "bowl", "coffee maker"],
"scene": "Kitchen activities",
"context": {"location_type": "indoor", "activity_type": "cooking/eating"}
},
{
"objects": ["tv", "remote", "couch", "table", "lamp"],
"scene": "Living room relaxation",
"context": {"location_type": "indoor", "activity_type": "living/relaxing"}
}
]
for i, detection in enumerate(sample_detections, 1):
print(f"\nπΈ Sample Detection {i}:")
print(f" Scene: {detection['scene']}")
print(f" Objects: {', '.join(detection['objects'])}")
print(f" Location: {detection['context']['location_type']}")
print(f" Activity: {detection['context']['activity_type']}")
def main():
"""Run the complete demo."""
print("π§ Vision-based Personal Memory Assistant - Demo")
print("=" * 60)
print("This demo shows the system capabilities with sample data.")
print("No camera or OpenAI API required for this demonstration.\n")
try:
# Demo database operations
demo_database_operations()
# Demo object detection
demo_object_detection()
# Demo query simulation
demo_query_simulation()
print("\n" + "=" * 60)
print("π Demo completed successfully!")
print("\nπ‘ To run the full application:")
print(" 1. Add your OpenAI API key to .env file")
print(" 2. Run: streamlit run app.py")
print(" 3. Grant camera permissions when prompted")
except Exception as e:
print(f"β Demo failed: {e}")
return False
return True
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)