awacke1 commited on
Commit
2ad1d64
Β·
verified Β·
1 Parent(s): 8e725cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -37
app.py CHANGED
@@ -4,19 +4,15 @@ from datetime import datetime
4
  import os
5
  import threading
6
  import time
7
- from PIL import Image
8
- from io import BytesIO
9
- import aiofiles
10
- import asyncio
11
  import base64
12
 
13
  # 🌟πŸ”₯ Initialize session state like a galactic DJ spinning tracks!
14
  if 'file_history' not in st.session_state:
15
  st.session_state['file_history'] = []
16
- if 'auto_capture_running' not_in st.session_state:
17
  st.session_state['auto_capture_running'] = False
18
- if 'cam_file' not_in st.session_state:
19
- st.session_state['cam_file'] = None
20
 
21
  # πŸ“œπŸ’Ύ Save to history like a time-traveling scribe! | πŸ“…βœ¨ save_to_history("πŸ–ΌοΈ Image", "pic.jpg") - Stamps a pic in the history books like a boss!
22
  def save_to_history(file_type, file_path):
@@ -29,13 +25,12 @@ def save_to_history(file_type, file_path):
29
 
30
  # πŸ“Έβ° Auto-capture every 10 secs like a sneaky shutterbug!
31
  def auto_capture():
32
- if st.session_state['auto_capture_running'] and 'cam_img' in st.session_state:
33
- cam_img = st.session_state['cam_img']
34
- if cam_img:
35
- filename = f"auto_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
36
- with open(filename, "wb") as f:
37
- f.write(cam_img.getvalue())
38
- save_to_history("πŸ–ΌοΈ Image", filename)
39
  threading.Timer(10, auto_capture).start()
40
 
41
  # πŸŽ›οΈ Sidebar config like a spaceship control panel!
@@ -59,31 +54,119 @@ with st.sidebar:
59
  st.write("πŸ•³οΈ Empty Stash!")
60
 
61
  # 🌍🎨 Main UI kicks off like a cosmic art show!
62
- st.title("πŸ“Έ Snap Craze")
63
 
64
- # πŸ“ΈπŸ“· Camera snap zone!
65
  st.header("πŸ“ΈπŸŽ₯ Snap Zone")
66
- cam_img = st.camera_input("πŸ“· Snap It!", key="cam")
67
- if cam_img:
68
- filename = f"cam_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
69
- if st.session_state['cam_file'] and os.path.exists(st.session_state['cam_file']):
70
- os.remove(st.session_state['cam_file'])
71
- with open(filename, "wb") as f:
72
- f.write(cam_img.getvalue())
73
- st.session_state['cam_file'] = filename
74
- st.session_state['cam_img'] = cam_img # Store for auto-capture
75
- save_to_history("πŸ–ΌοΈ Image", filename)
76
- st.image(Image.open(filename), caption="Latest Snap", use_column_width=True)
77
-
78
- # πŸ“‚ Upload zone like a media drop party!
79
- st.header("πŸ“₯πŸŽ‰ Drop Zone")
80
- uploaded_files = st.file_uploader("πŸ“Έ Toss Pics", accept_multiple_files=True, type=['jpg', 'png'])
81
- if uploaded_files:
82
- for uploaded_file in uploaded_files:
83
- file_path = f"uploaded_{uploaded_file.name}"
84
- with open(file_path, "wb") as f:
85
- f.write(uploaded_file.read())
86
- save_to_history("πŸ–ΌοΈ Image", file_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  # πŸ–ΌοΈ Gallery like a media circus!
89
  st.header("πŸŽͺ Snap Show")
 
4
  import os
5
  import threading
6
  import time
 
 
 
 
7
  import base64
8
 
9
  # 🌟πŸ”₯ Initialize session state like a galactic DJ spinning tracks!
10
  if 'file_history' not in st.session_state:
11
  st.session_state['file_history'] = []
12
+ if 'auto_capture_running' not in st.session_state:
13
  st.session_state['auto_capture_running'] = False
14
+ if 'snapshot_data' not in st.session_state:
15
+ st.session_state['snapshot_data'] = None
16
 
17
  # πŸ“œπŸ’Ύ Save to history like a time-traveling scribe! | πŸ“…βœ¨ save_to_history("πŸ–ΌοΈ Image", "pic.jpg") - Stamps a pic in the history books like a boss!
18
  def save_to_history(file_type, file_path):
 
25
 
26
  # πŸ“Έβ° Auto-capture every 10 secs like a sneaky shutterbug!
27
  def auto_capture():
28
+ if st.session_state['auto_capture_running'] and st.session_state['snapshot_data']:
29
+ snapshot_data = st.session_state['snapshot_data']
30
+ filename = f"auto_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
31
+ with open(filename, "wb") as f:
32
+ f.write(base64.b64decode(snapshot_data.split(',')[1]))
33
+ save_to_history("πŸ–ΌοΈ Image", filename)
 
34
  threading.Timer(10, auto_capture).start()
35
 
36
  # πŸŽ›οΈ Sidebar config like a spaceship control panel!
 
54
  st.write("πŸ•³οΈ Empty Stash!")
55
 
56
  # 🌍🎨 Main UI kicks off like a cosmic art show!
57
+ st.title("πŸ“Έ WebRTC Snap Craze")
58
 
59
+ # πŸ“ΈπŸ“· WebRTC camera snap zone!
60
  st.header("πŸ“ΈπŸŽ₯ Snap Zone")
61
+ webrtc_html = """
62
+ <div>
63
+ <select id="cameraSelect"></select>
64
+ <button onclick="startStream()">πŸ“· Start Stream</button>
65
+ <button onclick="takeSnapshot()">πŸ“Έ Snap It!</button>
66
+ <button onclick="stopStream()">⏹️ Stop Stream</button>
67
+ <video id="video" autoplay playsinline></video>
68
+ <canvas id="canvas" style="display:none;"></canvas>
69
+ <img id="snapshot" style="display:none;">
70
+ </div>
71
+ <script>
72
+ let stream = null;
73
+ let peerConnection = null;
74
+ const config = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] };
75
+
76
+ // πŸ“ΉπŸ” Enumerate cameras like a tech detective!
77
+ async function enumerateCameras() {
78
+ const devices = await navigator.mediaDevices.enumerateDevices();
79
+ const videoDevices = devices.filter(device => device.kind === 'videoinput');
80
+ const select = document.getElementById('cameraSelect');
81
+ select.innerHTML = '';
82
+ videoDevices.forEach((device, index) => {
83
+ const option = document.createElement('option');
84
+ option.value = device.deviceId;
85
+ option.text = device.label || `Camera ${index + 1}`;
86
+ select.appendChild(option);
87
+ });
88
+ }
89
+
90
+ // πŸ“ΈπŸŽ₯ Start streaming like a live broadcast pro!
91
+ async function startStream() {
92
+ if (stream) stopStream();
93
+ const cameraId = document.getElementById('cameraSelect').value;
94
+ const constraints = { video: { deviceId: cameraId ? { exact: cameraId } : undefined } };
95
+ stream = await navigator.mediaDevices.getUserMedia(constraints);
96
+ const video = document.getElementById('video');
97
+ video.srcObject = stream;
98
+
99
+ peerConnection = new RTCPeerConnection(config);
100
+ stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));
101
+ peerConnection.onicecandidate = event => {
102
+ if (event.candidate) console.log('ICE Candidate:', event.candidate);
103
+ };
104
+ const offer = await peerConnection.createOffer();
105
+ await peerConnection.setLocalDescription(offer);
106
+ // Simulate remote answer (self-loop for demo)
107
+ await peerConnection.setRemoteDescription(offer);
108
+ }
109
+
110
+ // πŸ“Έβœ‚οΈ Snap a pic like a stealthy paparazzi!
111
+ function takeSnapshot() {
112
+ const video = document.getElementById('video');
113
+ const canvas = document.getElementById('canvas');
114
+ const snapshot = document.getElementById('snapshot');
115
+ canvas.width = video.videoWidth;
116
+ canvas.height = video.videoHeight;
117
+ canvas.getContext('2d').drawImage(video, 0, 0);
118
+ const dataUrl = canvas.toDataURL('image/jpeg');
119
+ snapshot.src = dataUrl;
120
+ snapshot.style.display = 'block';
121
+ // Send snapshot to Python via session state
122
+ window.parent.postMessage({ type: 'snapshot', data: dataUrl }, '*');
123
+ }
124
+
125
+ // βΉοΈπŸ“΄ Stop the stream like a broadcast kill switch!
126
+ function stopStream() {
127
+ if (stream) {
128
+ stream.getTracks().forEach(track => track.stop());
129
+ stream = null;
130
+ }
131
+ if (peerConnection) {
132
+ peerConnection.close();
133
+ peerConnection = null;
134
+ }
135
+ document.getElementById('video').srcObject = null;
136
+ document.getElementById('snapshot').style.display = 'none';
137
+ }
138
+
139
+ // 🎬 Kick off the camera party!
140
+ enumerateCameras();
141
+ </script>
142
+ """
143
+ st.markdown(webrtc_html, unsafe_allow_html=True)
144
+
145
+ # πŸ“ΈπŸ“₯ Handle snapshots from JS
146
+ def handle_snapshot():
147
+ if "snapshot" in st.session_state:
148
+ st.session_state['snapshot_data'] = st.session_state["snapshot"]
149
+ filename = f"snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
150
+ with open(filename, "wb") as f:
151
+ f.write(base64.b64decode(st.session_state['snapshot_data'].split(',')[1]))
152
+ save_to_history("πŸ–ΌοΈ Image", filename)
153
+ st.image(filename, caption="Latest Snap", use_column_width=True)
154
+ del st.session_state["snapshot"] # Clear after saving
155
+
156
+ # Listen for JS messages
157
+ st.components.v1.html(
158
+ """
159
+ <script>
160
+ window.addEventListener('message', function(event) {
161
+ if (event.data.type === 'snapshot') {
162
+ window.streamlitAPI.setComponentValue({snapshot: event.data.data});
163
+ }
164
+ });
165
+ </script>
166
+ """,
167
+ height=0
168
+ )
169
+ handle_snapshot()
170
 
171
  # πŸ–ΌοΈ Gallery like a media circus!
172
  st.header("πŸŽͺ Snap Show")