-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
307 lines (245 loc) Β· 11.6 KB
/
app.py
File metadata and controls
307 lines (245 loc) Β· 11.6 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import streamlit as st
import time
from datetime import datetime, timedelta
from pathlib import Path
import threading
import logging
from typing import List, Dict, Any
# Import our modules
from config.settings import settings
from capture.camera import Camera
from vision.detector import ObjectDetector
from memory.database import MemoryDatabase
from api.openai_client import OpenAIClient
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize components
@st.cache_resource
def initialize_components():
"""Initialize all system components."""
try:
# Validate configuration
settings.validate_config()
# Initialize components
camera = Camera()
detector = ObjectDetector()
database = MemoryDatabase()
openai_client = OpenAIClient()
# Test OpenAI connection
if not openai_client.validate_api_connection():
st.error("β οΈ OpenAI API connection failed. Please check your API key.")
return camera, detector, database, openai_client
except Exception as e:
st.error(f"β Failed to initialize components: {e}")
return None, None, None, None
def capture_and_process_image(camera: Camera, detector: ObjectDetector,
database: MemoryDatabase, openai_client: OpenAIClient):
"""Capture and process a single image."""
try:
# Capture image
result = camera.capture_and_save()
if result is None:
logger.error("Failed to capture image")
return
image_path, timestamp = result
# Detect objects
detection_results = detector.detect_objects(image_path)
if not detection_results:
logger.error("Failed to detect objects")
return
# Enhance description with ChatGPT
objects = detection_results.get('unique_objects', [])
basic_description = detection_results.get('scene_description', '')
enhanced_description = openai_client.enhance_scene_description(
objects, basic_description
)
# Analyze context
context_info = detector.analyze_scene_context(
detection_results.get('detections', [])
)
# Store in database
memory_id = database.add_memory(
image_path=str(image_path),
timestamp=timestamp,
scene_description=enhanced_description,
objects_detected=objects,
context_info=context_info
)
logger.info(f"Memory processed and stored with ID: {memory_id}")
except Exception as e:
logger.error(f"Error in capture and process: {e}")
def search_memories(query: str, database: MemoryDatabase,
openai_client: OpenAIClient) -> List[Dict[str, Any]]:
"""Search memories using natural language query."""
try:
# Analyze query with ChatGPT
query_analysis = openai_client.analyze_query(query)
# Extract search parameters
objects = query_analysis.get('objects', [])
time_reference = query_analysis.get('time_reference')
# Convert time reference to date range
start_date = None
end_date = None
if time_reference:
if 'today' in time_reference.lower():
start_date = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
end_date = datetime.now()
elif 'yesterday' in time_reference.lower():
yesterday = datetime.now() - timedelta(days=1)
start_date = yesterday.replace(hour=0, minute=0, second=0, microsecond=0)
end_date = yesterday.replace(hour=23, minute=59, second=59)
elif 'last week' in time_reference.lower():
start_date = datetime.now() - timedelta(days=7)
end_date = datetime.now()
# Search database
memories = database.search_memories(
query=query,
start_date=start_date,
end_date=end_date,
objects=objects if objects else None,
limit=20
)
# Log query
database.add_query_log(query, len(memories))
return memories
except Exception as e:
logger.error(f"Error searching memories: {e}")
return []
def main():
st.set_page_config(
page_title="Vision-based Memory Assistant",
page_icon="π§ ",
layout="wide"
)
st.title("π§ Vision-based Personal Memory Assistant")
st.markdown("A prototype AI system that helps recall visual memories using images captured throughout the day.")
# Initialize components
camera, detector, database, openai_client = initialize_components()
if not all([camera, detector, database, openai_client]):
st.error("β System initialization failed. Please check your configuration.")
return
# Sidebar for controls
st.sidebar.header("ποΈ Controls")
# Manual capture button
if st.sidebar.button("πΈ Capture Image Now"):
with st.spinner("Capturing and processing image..."):
capture_and_process_image(camera, detector, database, openai_client)
st.success("β
Image captured and processed!")
st.rerun()
# Auto-capture toggle
auto_capture = st.sidebar.checkbox("π Enable Auto-Capture", value=False)
if auto_capture:
st.sidebar.info("Auto-capture is enabled. Images will be captured every 5 minutes during active hours.")
# Main content area
tab1, tab2, tab3 = st.tabs(["π Search Memories", "π Statistics", "πΈ Recent Captures"])
with tab1:
st.header("π Search Your Visual Memories")
# Search interface
col1, col2 = st.columns([3, 1])
with col1:
query = st.text_input(
"Ask about your memories:",
placeholder="When did I last see my keys? Show me when I was working at my desk..."
)
with col2:
search_button = st.button("π Search", type="primary")
if search_button and query:
with st.spinner("Searching memories..."):
memories = search_memories(query, database, openai_client)
if memories:
# Generate AI response
ai_response = openai_client.generate_memory_response(query, memories)
st.success(f"π€ {ai_response}")
# Display results
st.subheader(f"π Found {len(memories)} memories:")
for i, memory in enumerate(memories):
with st.expander(f"π
{memory['timestamp'].strftime('%B %d at %I:%M %p')}"):
col1, col2 = st.columns([1, 2])
with col1:
# Display image if it exists
image_path = Path(memory['image_path'])
if image_path.exists():
st.image(str(image_path), caption="Captured Image")
else:
st.warning("Image file not found")
with col2:
st.write(f"**Scene:** {memory['scene_description']}")
st.write(f"**Objects:** {', '.join(memory['objects_detected'])}")
if memory['context_info']:
context = memory['context_info']
st.write(f"**Location:** {context.get('location_type', 'Unknown')}")
st.write(f"**Activity:** {context.get('activity_type', 'Unknown')}")
else:
st.warning("No memories found matching your query.")
# Suggest alternative searches
suggestions = openai_client.suggest_search_terms(query)
if suggestions:
st.info("π‘ Try these alternative searches:")
for suggestion in suggestions:
if st.button(suggestion, key=f"suggest_{suggestion}"):
st.session_state.query = suggestion
st.rerun()
# Quick search examples
st.subheader("π‘ Example Queries")
examples = [
"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"
]
cols = st.columns(len(examples))
for i, example in enumerate(examples):
with cols[i]:
if st.button(example, key=f"example_{i}"):
st.session_state.query = example
st.rerun()
with tab2:
st.header("π Memory Statistics")
stats = database.get_statistics()
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Total Memories", stats.get('total_memories', 0))
with col2:
st.metric("Memories Today", stats.get('memories_today', 0))
with col3:
st.metric("Active Hours", f"{settings.CAPTURE_ACTIVE_HOURS_START}:00 - {settings.CAPTURE_ACTIVE_HOURS_END}:00")
# Most common objects
if stats.get('most_common_objects'):
st.subheader("π·οΈ Most Common Objects")
for obj, count in stats['most_common_objects']:
st.write(f"β’ {obj}: {count} times")
# Recent query history
st.subheader("π Recent Searches")
query_history = database.get_query_history(10)
for query_record in query_history:
st.write(f"β’ **{query_record['query_text']}** ({query_record['results_count']} results) - {query_record['timestamp'].strftime('%H:%M')}")
with tab3:
st.header("πΈ Recent Captures")
recent_memories = database.get_recent_memories(10)
if recent_memories:
for memory in recent_memories:
with st.expander(f"π
{memory['timestamp'].strftime('%B %d at %I:%M %p')}"):
col1, col2 = st.columns([1, 2])
with col1:
image_path = Path(memory['image_path'])
if image_path.exists():
st.image(str(image_path), caption="Captured Image")
else:
st.warning("Image file not found")
with col2:
st.write(f"**Scene:** {memory['scene_description']}")
st.write(f"**Objects:** {', '.join(memory['objects_detected'])}")
else:
st.info("No memories captured yet. Try capturing an image manually or enable auto-capture.")
# Footer
st.markdown("---")
st.markdown("""
<div style='text-align: center; color: #666;'>
<p>π§ Vision-based Personal Memory Assistant | Prototype</p>
<p>Built with PyTorch, YOLO, OpenAI, and Streamlit</p>
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()