awacke1 commited on
Commit
2148864
·
verified ·
1 Parent(s): adeee4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -139
app.py CHANGED
@@ -188,149 +188,129 @@ def zip_files(files, zip_name):
188
  zipf.write(file, os.path.basename(file))
189
  return zip_name
190
 
191
- # JavaScript/HTML Components
192
- camera_selector_html = """
193
- <div>
194
- <h3>Camera & Audio Source Selector</h3>
195
- <select id="videoSource"></select>
196
- <select id="audioSource"></select>
197
- <button onclick="startStream()">Start Stream</button>
198
- <video id="video" autoplay playsinline style="width: 100%;"></video>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  </div>
200
  <script>
201
- const videoSource = document.getElementById('videoSource');
202
- const audioSource = document.getElementById('audioSource');
203
- const video = document.getElementById('video');
204
- let stream;
 
 
 
 
 
205
 
206
  navigator.mediaDevices.enumerateDevices().then(devices => {
 
207
  devices.forEach(device => {
208
  const option = document.createElement('option');
209
  option.value = device.deviceId;
210
  option.text = device.label || `${device.kind} ${device.deviceId}`;
211
  if (device.kind === 'videoinput') {
212
- videoSource.appendChild(option);
 
 
213
  } else if (device.kind === 'audioinput') {
214
- audioSource.appendChild(option);
 
215
  }
216
  });
 
 
 
217
  }).catch(err => console.error('Error enumerating devices:', err));
218
 
219
- function startStream() {
220
- if (stream) {
221
- stream.getTracks().forEach(track => track.stop());
222
- }
223
- const constraints = {
224
- video: { deviceId: videoSource.value ? { exact: videoSource.value } : undefined },
225
- audio: { deviceId: audioSource.value ? { exact: audioSource.value } : undefined }
226
- };
227
- navigator.mediaDevices.getUserMedia(constraints)
228
- .then(mediaStream => {
229
- stream = mediaStream;
230
- video.srcObject = stream;
231
- console.log('Stream started');
232
- })
233
- .catch(err => console.error('Error starting stream:', err));
 
 
 
 
 
 
 
 
 
 
234
  }
235
- </script>
236
- """
237
 
238
- image_capture_html = """
239
- <div>
240
- <h3>Image Capture - Camera {id}</h3>
241
- <video id="video{id}" autoplay playsinline style="width: 100%;"></video>
242
- <button onclick="captureFrame{id}()">Capture Frame 📸</button>
243
- <canvas id="canvas{id}" style="display: none;"></canvas>
244
- </div>
245
- <script>
246
- const video{id} = document.getElementById('video{id}');
247
- const canvas{id} = document.getElementById('canvas{id}');
248
- let stream{id};
249
 
250
- navigator.mediaDevices.getUserMedia({ video: true })
251
- .then(mediaStream => {
252
- stream{id} = mediaStream;
253
- video{id}.srcObject = stream{id};
254
- console.log('Camera {id} stream started');
255
- })
256
- .catch(err => console.error('Error starting Camera {id}:', err));
257
 
258
- function captureFrame{id}() {
259
- canvas{id}.width = video{id}.videoWidth;
260
- canvas{id}.height = video{id}.videoHeight;
261
- const ctx = canvas{id}.getContext('2d');
262
- ctx.drawImage(video{id}, 0, 0, canvas{id}.width, canvas{id}.height);
263
- const dataUrl = canvas{id}.toDataURL('image/png');
264
- const filename = `{id}${new Date().toISOString().replace(/[^0-9]/g, '')}.png`;
265
  const link = document.createElement('a');
266
- link.href = dataUrl;
267
  link.download = filename;
268
  link.click();
269
- console.log('Captured frame:', filename);
270
  }
271
- </script>
272
- """
273
-
274
- video_capture_html = """
275
- <div>
276
- <h3>Video Capture - Camera {id}</h3>
277
- <video id="video{id}" autoplay playsinline style="width: 100%;"></video>
278
- <button onclick="captureVideo{id}()">Capture Video 🎥</button>
279
- <canvas id="canvas{id}" style="display: none;"></canvas>
280
- </div>
281
- <script>
282
- const video{id} = document.getElementById('video{id}');
283
- const canvas{id} = document.getElementById('canvas{id}');
284
- let stream{id}, recorder{id};
285
 
286
- navigator.mediaDevices.getUserMedia({ video: true, audio: true })
287
- .then(mediaStream => {
288
- stream{id} = mediaStream;
289
- video{id}.srcObject = stream{id};
290
- recorder{id} = new MediaRecorder(stream{id});
291
- const chunks = [];
292
- recorder{id}.ondataavailable = e => chunks.push(e.data);
293
- recorder{id}.onstop = () => {
294
- const blob = new Blob(chunks, { type: 'video/mp4' });
295
- const filename = `{id}${new Date().toISOString().replace(/[^0-9]/g, '')}.mp4`;
296
- const url = URL.createObjectURL(blob);
297
- const link = document.createElement('a');
298
- link.href = url;
299
- link.download = filename;
300
- link.click();
301
- console.log('Captured video:', filename);
302
- sliceVideo{id}(blob);
303
- };
304
- console.log('Camera {id} stream started');
305
- })
306
- .catch(err => console.error('Error starting Camera {id}:', err));
307
-
308
- function captureVideo{id}() {
309
- recorder{id}.start();
310
- setTimeout(() => recorder{id}.stop(), 10000); // 10 seconds
311
- console.log('Recording started for Camera {id}');
312
- }
313
-
314
- function sliceVideo{id}(blob) {
315
  const video = document.createElement('video');
316
  video.src = URL.createObjectURL(blob);
317
  video.onloadedmetadata = () => {
318
- const ctx = canvas{id}.getContext('2d');
319
- canvas{id}.width = video.videoWidth;
320
- canvas{id}.height = video.videoHeight;
321
  let frameCount = 0;
322
  const interval = video.duration / 10;
323
  video.currentTime = 0;
324
  const captureFrame = () => {
325
  if (frameCount < 10) {
326
- ctx.drawImage(video, 0, 0, canvas{id}.width, canvas{id}.height);
327
- const dataUrl = canvas{id}.toDataURL('image/png');
328
- const filename = `{id}${new Date().toISOString().replace(/[^0-9]/g, '')}_${frameCount}.png`;
329
- const link = document.createElement('a');
330
- link.href = dataUrl;
331
- link.download = filename;
332
- link.click();
333
- console.log('Captured frame:', filename);
334
  frameCount++;
335
  video.currentTime += interval;
336
  setTimeout(captureFrame, 100);
@@ -381,7 +361,7 @@ if selected_model != "None" and st.sidebar.button("Load Model 📂"):
381
  st.error(f"Load failed: {str(e)}")
382
 
383
  # Tabs
384
- tab1, tab2, tab3, tab4 = st.tabs(["Build Titan 🌱", "Camera Snap 📷", "Fine-Tune Titans 🔧", "Test Titans 🧪"])
385
 
386
  with tab1:
387
  st.header("Build Titan 🌱 (Quick Start!)")
@@ -401,13 +381,7 @@ with tab1:
401
 
402
  with tab2:
403
  st.header("Camera Snap 📷 (Dual Live Feed!)")
404
- st.subheader("Source Configuration")
405
- html(camera_selector_html, height=400)
406
- cols = st.columns(2)
407
- for i in range(2):
408
- with cols[i]:
409
- html(image_capture_html.format(id=i), height=300)
410
- html(video_capture_html.format(id=i), height=300)
411
  st.subheader("Upload Captured Files")
412
  uploaded_files = st.file_uploader("Upload PNGs/MP4s from Downloads", type=["png", "mp4"], accept_multiple_files=True)
413
  if uploaded_files:
@@ -423,7 +397,7 @@ with tab2:
423
  update_gallery()
424
 
425
  with tab3:
426
- st.header("Fine-Tune Titans 🔧 (Tune Fast!)")
427
  if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
428
  st.warning("Load a Titan first! ⚠️")
429
  else:
@@ -439,6 +413,15 @@ with tab3:
439
  st.success("NLP sharpened! 🎉")
440
  except Exception as e:
441
  st.error(f"NLP fine-tune failed: {str(e)}")
 
 
 
 
 
 
 
 
 
442
  elif isinstance(st.session_state['builder'], DiffusionBuilder):
443
  st.subheader("CV Tune 🎨")
444
  captured_images = get_gallery_files(["png"])
@@ -454,25 +437,7 @@ with tab3:
454
  st.error(f"CV fine-tune failed: {str(e)}")
455
  else:
456
  st.warning("Upload at least 2 PNGs in Camera Snap first! ⚠️")
457
-
458
- with tab4:
459
- st.header("Test Titans 🧪 (Image Agent Demo!)")
460
- if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
461
- st.warning("Load a Titan first! ⚠️")
462
- else:
463
- if isinstance(st.session_state['builder'], ModelBuilder):
464
- st.subheader("NLP Test 🧠")
465
- prompt = st.text_area("Prompt", "What’s a superhero?", key="nlp_test")
466
- if st.button("Test NLP ▶️"):
467
- logger.info("Running NLP test")
468
- try:
469
- result = st.session_state['builder'].evaluate(prompt)
470
- st.write(f"**Answer**: {result}")
471
- except Exception as e:
472
- st.error(f"NLP test failed: {str(e)}")
473
- elif isinstance(st.session_state['builder'], DiffusionBuilder):
474
  st.subheader("CV Test 🎨 (Image Set Demo)")
475
- captured_images = get_gallery_files(["png"])
476
  if len(captured_images) >= 2:
477
  if st.button("Run CV Demo ▶️"):
478
  logger.info("Running CV image set demo")
 
188
  zipf.write(file, os.path.basename(file))
189
  return zip_name
190
 
191
+ # JavaScript/HTML Dual Camera Component
192
+ dual_camera_html = """
193
+ <div style="width: 100%;">
194
+ <h3>Dual Camera Capture</h3>
195
+ <div>
196
+ <label>Camera 0 Video: </label>
197
+ <select id="videoSource0"></select>
198
+ <label>Audio: </label>
199
+ <select id="audioSource0"></select>
200
+ <video id="video0" autoplay playsinline style="width: 45%; margin: 5px;"></video>
201
+ </div>
202
+ <div>
203
+ <label>Camera 1 Video: </label>
204
+ <select id="videoSource1"></select>
205
+ <label>Audio: </label>
206
+ <select id="audioSource1"></select>
207
+ <video id="video1" autoplay playsinline style="width: 45%; margin: 5px;"></video>
208
+ </div>
209
+ <button onclick="startStreams()">Start Streams</button>
210
+ <button onclick="captureFrame(0)">Capture Frame 📸 Cam 0</button>
211
+ <button onclick="captureFrame(1)">Capture Frame 📸 Cam 1</button>
212
+ <button onclick="captureVideo(0)">Capture Video 🎥 Cam 0</button>
213
+ <button onclick="captureVideo(1)">Capture Video 🎥 Cam 1</button>
214
+ <canvas id="canvas" style="display: none;"></canvas>
215
  </div>
216
  <script>
217
+ const videoSource0 = document.getElementById('videoSource0');
218
+ const audioSource0 = document.getElementById('audioSource0');
219
+ const videoSource1 = document.getElementById('videoSource1');
220
+ const audioSource1 = document.getElementById('audioSource1');
221
+ const video0 = document.getElementById('video0');
222
+ const video1 = document.getElementById('video1');
223
+ const canvas = document.getElementById('canvas');
224
+ let streams = [null, null];
225
+ let recorders = [null, null];
226
 
227
  navigator.mediaDevices.enumerateDevices().then(devices => {
228
+ let videoCount = 0;
229
  devices.forEach(device => {
230
  const option = document.createElement('option');
231
  option.value = device.deviceId;
232
  option.text = device.label || `${device.kind} ${device.deviceId}`;
233
  if (device.kind === 'videoinput') {
234
+ videoSource0.appendChild(option.cloneNode(true));
235
+ videoSource1.appendChild(option.cloneNode(true));
236
+ videoCount++;
237
  } else if (device.kind === 'audioinput') {
238
+ audioSource0.appendChild(option.cloneNode(true));
239
+ audioSource1.appendChild(option.cloneNode(true));
240
  }
241
  });
242
+ if (videoCount > 1) {
243
+ videoSource1.selectedIndex = 1; // Default to second camera
244
+ }
245
  }).catch(err => console.error('Error enumerating devices:', err));
246
 
247
+ function startStreams() {
248
+ [0, 1].forEach(i => {
249
+ if (streams[i]) {
250
+ streams[i].getTracks().forEach(track => track.stop());
251
+ }
252
+ const constraints = {
253
+ video: { deviceId: document.getElementById(`videoSource${i}`).value ? { exact: document.getElementById(`videoSource${i}`).value } : undefined },
254
+ audio: { deviceId: document.getElementById(`audioSource${i}`).value ? { exact: document.getElementById(`audioSource${i}`).value } : undefined }
255
+ };
256
+ navigator.mediaDevices.getUserMedia(constraints)
257
+ .then(mediaStream => {
258
+ streams[i] = mediaStream;
259
+ document.getElementById(`video${i}`).srcObject = streams[i];
260
+ recorders[i] = new MediaRecorder(streams[i]);
261
+ const chunks = [];
262
+ recorders[i].ondataavailable = e => chunks.push(e.data);
263
+ recorders[i].onstop = () => {
264
+ const blob = new Blob(chunks, { type: 'video/mp4' });
265
+ saveFile(blob, `${i}${new Date().toISOString().replace(/[^0-9]/g, '')}.mp4`);
266
+ sliceVideo(blob, i);
267
+ };
268
+ console.log(`Camera ${i} stream started`);
269
+ })
270
+ .catch(err => console.error(`Error starting Camera ${i}:`, err));
271
+ });
272
  }
 
 
273
 
274
+ function captureFrame(id) {
275
+ const video = document.getElementById(`video${id}`);
276
+ canvas.width = video.videoWidth;
277
+ canvas.height = video.videoHeight;
278
+ const ctx = canvas.getContext('2d');
279
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
280
+ const dataUrl = canvas.toDataURL('image/png');
281
+ saveFile(dataUrl, `${id}${new Date().toISOString().replace(/[^0-9]/g, '')}.png`);
282
+ console.log(`Captured frame from Camera ${id}`);
283
+ }
 
284
 
285
+ function captureVideo(id) {
286
+ recorders[id].start();
287
+ setTimeout(() => recorders[id].stop(), 10000); // 10 seconds
288
+ console.log(`Recording started for Camera ${id}`);
289
+ }
 
 
290
 
291
+ function saveFile(data, filename) {
 
 
 
 
 
 
292
  const link = document.createElement('a');
293
+ link.href = data instanceof Blob ? URL.createObjectURL(data) : data;
294
  link.download = filename;
295
  link.click();
 
296
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
 
298
+ function sliceVideo(blob, id) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  const video = document.createElement('video');
300
  video.src = URL.createObjectURL(blob);
301
  video.onloadedmetadata = () => {
302
+ const ctx = canvas.getContext('2d');
303
+ canvas.width = video.videoWidth;
304
+ canvas.height = video.videoHeight;
305
  let frameCount = 0;
306
  const interval = video.duration / 10;
307
  video.currentTime = 0;
308
  const captureFrame = () => {
309
  if (frameCount < 10) {
310
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
311
+ const dataUrl = canvas.toDataURL('image/png');
312
+ saveFile(dataUrl, `${id}${new Date().toISOString().replace(/[^0-9]/g, '')}_${frameCount}.png`);
313
+ console.log(`Captured frame ${frameCount} from Camera ${id}`);
 
 
 
 
314
  frameCount++;
315
  video.currentTime += interval;
316
  setTimeout(captureFrame, 100);
 
361
  st.error(f"Load failed: {str(e)}")
362
 
363
  # Tabs
364
+ tab1, tab2, tab3 = st.tabs(["Build Titan 🌱", "Camera Snap 📷", "Fine-Tune & Test 🔧🧪"])
365
 
366
  with tab1:
367
  st.header("Build Titan 🌱 (Quick Start!)")
 
381
 
382
  with tab2:
383
  st.header("Camera Snap 📷 (Dual Live Feed!)")
384
+ html(dual_camera_html, height=600)
 
 
 
 
 
 
385
  st.subheader("Upload Captured Files")
386
  uploaded_files = st.file_uploader("Upload PNGs/MP4s from Downloads", type=["png", "mp4"], accept_multiple_files=True)
387
  if uploaded_files:
 
397
  update_gallery()
398
 
399
  with tab3:
400
+ st.header("Fine-Tune & Test 🔧🧪")
401
  if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
402
  st.warning("Load a Titan first! ⚠️")
403
  else:
 
413
  st.success("NLP sharpened! 🎉")
414
  except Exception as e:
415
  st.error(f"NLP fine-tune failed: {str(e)}")
416
+ st.subheader("NLP Test 🧠")
417
+ prompt = st.text_area("Prompt", "What’s a superhero?", key="nlp_test")
418
+ if st.button("Test NLP ▶️"):
419
+ logger.info("Running NLP test")
420
+ try:
421
+ result = st.session_state['builder'].evaluate(prompt)
422
+ st.write(f"**Answer**: {result}")
423
+ except Exception as e:
424
+ st.error(f"NLP test failed: {str(e)}")
425
  elif isinstance(st.session_state['builder'], DiffusionBuilder):
426
  st.subheader("CV Tune 🎨")
427
  captured_images = get_gallery_files(["png"])
 
437
  st.error(f"CV fine-tune failed: {str(e)}")
438
  else:
439
  st.warning("Upload at least 2 PNGs in Camera Snap first! ⚠️")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  st.subheader("CV Test 🎨 (Image Set Demo)")
 
441
  if len(captured_images) >= 2:
442
  if st.button("Run CV Demo ▶️"):
443
  logger.info("Running CV image set demo")