awacke1 commited on
Commit
5779747
Β·
verified Β·
1 Parent(s): f38f653

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +501 -0
app.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from datetime import datetime
4
+ import cv2
5
+ from pydub import AudioSegment
6
+ import imageio
7
+ import av
8
+ import moviepy as mp
9
+ import os
10
+ import numpy as np
11
+ from io import BytesIO
12
+ import threading
13
+ import time
14
+
15
+ # 🌟πŸ”₯ Initialize session state like a galactic DJ spinning tracks!
16
+ if 'file_history' not in st.session_state:
17
+ st.session_state['file_history'] = []
18
+ if 'ping_code' not in st.session_state:
19
+ st.session_state['ping_code'] = ""
20
+ if 'uploaded_files' not in st.session_state:
21
+ st.session_state['uploaded_files'] = []
22
+ if 'auto_capture_running' not in st.session_state:
23
+ st.session_state['auto_capture_running'] = False
24
+
25
+ # πŸ“œπŸ’Ύ Save to history like a time-traveling scribe! | πŸ“…βœ¨ save_to_history("Image", "pic.jpg") - Stamps a pic in the history books like a boss!
26
+ def save_to_history(file_type, file_path):
27
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
28
+ st.session_state['file_history'].append({
29
+ "Timestamp": timestamp,
30
+ "Type": file_type,
31
+ "Path": file_path
32
+ })
33
+
34
+ # πŸ“Έβ° Auto-capture every 10 secs like a sneaky shutterbug!
35
+ def auto_capture():
36
+ if st.session_state['auto_capture_running']:
37
+ cap = None
38
+ for i in range(10): # Try indices 0-9
39
+ cap = cv2.VideoCapture(i)
40
+ if cap.isOpened():
41
+ break
42
+ cap.release()
43
+ if cap and cap.isOpened():
44
+ ret, frame = cap.read()
45
+ if ret:
46
+ file_path = f"auto_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
47
+ cv2.imwrite(file_path, frame)
48
+ save_to_history("πŸ–ΌοΈ Image", file_path)
49
+ cap.release()
50
+ else:
51
+ st.warning("🚨 No camera found!")
52
+ threading.Timer(10, auto_capture).start()
53
+
54
+ # πŸŽ›οΈ Sidebar config like a spaceship control panel!
55
+ with st.sidebar:
56
+ st.header("πŸŽšοΈπŸ“Έ Tune-Up Zone")
57
+ library_choice = st.selectbox("πŸ“š Pick a Tool", ["OpenCV", "PyDub", "ImageIO", "PyAV", "MoviePy", "JS Audio"])
58
+ resolution = st.select_slider("πŸ“ Snap Size", options=["320x240", "640x480", "1280x720"], value="640x480")
59
+ fps = st.slider("⏱️ Speed Snap", 1, 60, 30)
60
+ if st.button("⏰ Start Auto-Snap"):
61
+ st.session_state['auto_capture_running'] = True
62
+ auto_capture()
63
+ if st.button("⏹️ Stop Auto-Snap"):
64
+ st.session_state['auto_capture_running'] = False
65
+
66
+ # πŸ”’ DTMF ping code like a retro phone hacker!
67
+ st.subheader("πŸ” Ping-a-Tron")
68
+ col1, col2, col3, col4 = st.columns(4)
69
+ with col1:
70
+ digit1 = st.selectbox("1️⃣", [str(i) for i in range(10)], key="d1")
71
+ with col2:
72
+ digit2 = st.selectbox("2️⃣", [str(i) for i in range(10)], key="d2")
73
+ with col3:
74
+ digit3 = st.selectbox("3️⃣", [str(i) for i in range(10)], key="d3")
75
+ with col4:
76
+ digit4 = st.selectbox("4️⃣", [str(i) for i in range(10)], key="d4")
77
+ ping_code = digit1 + digit2 + digit3 + digit4
78
+ st.session_state['ping_code'] = ping_code
79
+ st.write(f"πŸ”‘ Code: {ping_code}")
80
+
81
+ # πŸ“‚ Sidebar file outline with emoji flair!
82
+ st.subheader("πŸ“œ File Vault")
83
+ if st.session_state['file_history']:
84
+ images = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ–ΌοΈ Image"]
85
+ videos = [f for f in st.session_state['file_history'] if f['Type'] in ["πŸŽ₯ Video", "🎞️ GIF"]]
86
+ audios = [f for f in st.session_state['file_history'] if f['Type'] == "🎡 Audio"]
87
+ if images:
88
+ st.write("πŸ–ΌοΈ Images")
89
+ for img in images:
90
+ st.write(f"- {img['Path']} @ {img['Timestamp']}")
91
+ if videos:
92
+ st.write("πŸŽ₯ Videos/GIFs")
93
+ for vid in videos:
94
+ st.write(f"- {vid['Path']} @ {vid['Timestamp']}")
95
+ if audios:
96
+ st.write("🎡 Audios")
97
+ for aud in audios:
98
+ st.write(f"- {aud['Path']} @ {aud['Timestamp']}")
99
+ else:
100
+ st.write("πŸ•³οΈ Empty Vault!")
101
+
102
+ # 🌍🎨 Main UI kicks off like a cosmic art show!
103
+ st.title("πŸ“ΈπŸŽ™οΈ Capture Craze")
104
+
105
+ # πŸ“ΈπŸ“š Library showcase like a tech talent show!
106
+ st.header("πŸ“ΈπŸŽ™οΈ Tool Titans")
107
+
108
+ # 1. OpenCV - πŸ“· Pixel party time!
109
+ with st.expander("1️⃣ πŸ“· OpenCV Fiesta"):
110
+ st.write("πŸŽ₯ Snap Star: Real-time pixel magic!")
111
+ st.subheader("πŸ”₯ Top Tricks")
112
+
113
+ st.write("πŸ“ΈπŸŽ₯ Video Snap")
114
+ if st.button("🎬 Go Live", key="opencv_1"):
115
+ # πŸ“·πŸŽ₯ Snags webcam like a paparazzi pro! | πŸ“Έ cap = cv2.VideoCapture(0) - Grabs live feed faster than gossip spreads!
116
+ cap = None
117
+ for i in range(10):
118
+ cap = cv2.VideoCapture(i)
119
+ if cap.isOpened():
120
+ break
121
+ cap.release()
122
+ if cap and cap.isOpened():
123
+ frame_placeholder = st.empty()
124
+ for _ in range(50):
125
+ ret, frame = cap.read()
126
+ if ret:
127
+ frame_placeholder.image(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
128
+ cap.release()
129
+ else:
130
+ st.error("🚨 No camera found!")
131
+
132
+ st.write("πŸ–ŒοΈβœ¨ Gray Snap")
133
+ if st.button("πŸ“· Save Gray", key="opencv_2"):
134
+ # πŸ–ŒοΈβœ¨ Saves grayscale like an artsy ghost! | πŸ“ cv2.imwrite("gray.jpg", cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)) - Ditches color like a moody poet!
135
+ cap = None
136
+ for i in range(10):
137
+ cap = cv2.VideoCapture(i)
138
+ if cap.isOpened():
139
+ break
140
+ cap.release()
141
+ if cap and cap.isOpened():
142
+ ret, frame = cap.read()
143
+ if ret:
144
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
145
+ file_path = f"opencv_gray_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
146
+ cv2.imwrite(file_path, gray)
147
+ save_to_history("πŸ–ΌοΈ Image", file_path)
148
+ st.image(file_path, caption="πŸ–€ Gray Vibes")
149
+ cap.release()
150
+ else:
151
+ st.error("🚨 No camera found!")
152
+
153
+ st.write("πŸ•΅οΈβ€β™‚οΈπŸ” Edge Snap")
154
+ if st.button("πŸ”ͺ Edge It", key="opencv_3"):
155
+ # πŸ•΅οΈβ€β™‚οΈπŸ” Finds edges sharper than a detective’s wit! | πŸ–ΌοΈ edges = cv2.Canny(frame, 100, 200) - Outlines like a crime scene sketch!
156
+ cap = None
157
+ for i in range(10):
158
+ cap = cv2.VideoCapture(i)
159
+ if cap.isOpened():
160
+ break
161
+ cap.release()
162
+ if cap and cap.isOpened():
163
+ ret, frame = cap.read()
164
+ if ret:
165
+ edges = cv2.Canny(frame, 100, 200)
166
+ file_path = f"opencv_edges_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
167
+ cv2.imwrite(file_path, edges)
168
+ save_to_history("πŸ–ΌοΈ Image", file_path)
169
+ st.image(file_path, caption="πŸ” Edge Lord")
170
+ cap.release()
171
+ else:
172
+ st.error("🚨 No camera found!")
173
+
174
+ # 2. PyDub - πŸŽ™οΈ Audio mixing madness!
175
+ with st.expander("2️⃣ πŸŽ™οΈ PyDub Party"):
176
+ st.write("πŸ”Š Audio Ace: Mixmaster vibes!")
177
+ st.subheader("πŸ”₯ Top Tricks")
178
+
179
+ st.write("🎀🌩️ Load Jam")
180
+ if st.button("🎡 Load Sound", key="pydub_1"):
181
+ # 🎀🌩️ Grabs audio like a sonic thief! | πŸŽ™οΈ AudioSegment.from_file("sound.wav") - Nabs tracks like a sound bandit!
182
+ uploaded_audio = st.file_uploader("πŸŽ™οΈ Drop a WAV", type=['wav'], key="pydub_load")
183
+ if uploaded_audio:
184
+ sound = AudioSegment.from_file(uploaded_audio)
185
+ file_path = f"pydub_load_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
186
+ sound.export(file_path, format="wav")
187
+ save_to_history("🎡 Audio", file_path)
188
+ st.audio(file_path)
189
+
190
+ st.write("πŸ”ŠπŸ“‘ Export Snap")
191
+ if st.button("🎢 MP3 It", key="pydub_2"):
192
+ # πŸ”ŠπŸ“‘ Spits out tracks like a beat factory! | 🎡 sound.export("out.mp3") - Pumps tunes like a hit machine!
193
+ uploaded_audio = st.file_uploader("πŸŽ™οΈ Drop a WAV", type=['wav'], key="pydub_export")
194
+ if uploaded_audio:
195
+ sound = AudioSegment.from_file(uploaded_audio)
196
+ file_path = f"pydub_mp3_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp3"
197
+ sound.export(file_path, format="mp3")
198
+ save_to_history("🎡 Audio", file_path)
199
+ st.audio(file_path)
200
+
201
+ st.write("πŸŽΆπŸ’Ύ Reverse Blast")
202
+ if st.button("πŸ”„ Flip It", key="pydub_3"):
203
+ # πŸŽΆπŸ’Ύ Flips sound like a time-travel DJ! | 🎧 sound.reverse() - Spins audio back like a retro remix!
204
+ uploaded_audio = st.file_uploader("πŸŽ™οΈ Drop a WAV", type=['wav'], key="pydub_reverse")
205
+ if uploaded_audio:
206
+ sound = AudioSegment.from_file(uploaded_audio)
207
+ reversed_sound = sound.reverse()
208
+ file_path = f"pydub_rev_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
209
+ reversed_sound.export(file_path, format="wav")
210
+ save_to_history("🎡 Audio", file_path)
211
+ st.audio(file_path)
212
+
213
+ # 3. ImageIO - πŸ–ΌοΈ Pixel playtime!
214
+ with st.expander("3️⃣ πŸ“Ή ImageIO Bash"):
215
+ st.write("πŸŽ₯ Easy Snap: Pixel lightweight champ!")
216
+ st.subheader("πŸ”₯ Top Tricks")
217
+
218
+ st.write("πŸ“ΉπŸ‘€ Frame Peek")
219
+ if st.button("πŸ“Έ Snap It", key="imageio_1"):
220
+ # πŸ“ΉπŸ‘€ Grabs frames like a shy stalker! | πŸ“· reader = imageio.get_reader('<video0>') - Sneaks a peek at your cam!
221
+ try:
222
+ reader = imageio.get_reader('<video0>')
223
+ frame = reader.get_next_data()
224
+ file_path = f"imageio_frame_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
225
+ imageio.imwrite(file_path, frame)
226
+ save_to_history("πŸ–ΌοΈ Image", file_path)
227
+ st.image(file_path)
228
+ except Exception as e:
229
+ st.error(f"🚨 Camera snag: {str(e)}")
230
+
231
+ st.write("πŸ–¨οΈπŸ˜‚ Crunch Snap")
232
+ if st.button("πŸ“ Slim Pic", key="imageio_2"):
233
+ # πŸ–¨οΈπŸ˜‚ Compresses like a diet guru! | πŸ–ΌοΈ imageio.imwrite("pic.jpg", frame, quality=85) - Shrinks pics like a tight squeeze!
234
+ try:
235
+ reader = imageio.get_reader('<video0>')
236
+ frame = reader.get_next_data()
237
+ file_path = f"imageio_comp_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
238
+ imageio.imwrite(file_path, frame, quality=85)
239
+ save_to_history("πŸ–ΌοΈ Image", file_path)
240
+ st.image(file_path, caption="πŸ˜‚ Slim Fit")
241
+ except Exception as e:
242
+ st.error(f"🚨 Camera snag: {str(e)}")
243
+
244
+ st.write("🎞️🀑 GIF Blast")
245
+ if st.button("πŸŽ‰ GIF It", key="imageio_3"):
246
+ # 🎞️🀑 Makes GIFs like a circus juggler! | πŸŽ₯ imageio.mimwrite("gif.gif", [f1, f2], fps=5) - Flips frames into fun!
247
+ try:
248
+ reader = imageio.get_reader('<video0>')
249
+ frames = [reader.get_next_data() for _ in range(10)]
250
+ file_path = f"imageio_gif_{datetime.now().strftime('%Y%m%d_%H%M%S')}.gif"
251
+ imageio.mimwrite(file_path, frames, fps=5)
252
+ save_to_history("🎞️ GIF", file_path)
253
+ st.image(file_path, caption="🀑 GIF Party")
254
+ except Exception as e:
255
+ st.error(f"🚨 Camera snag: {str(e)}")
256
+
257
+ # 4. PyAV - 🎬 AV rock fest!
258
+ with st.expander("4️⃣ 🎬 PyAV Rave"):
259
+ st.write("πŸŽ₯ AV King: FFmpeg-powered chaos!")
260
+ st.subheader("πŸ”₯ Top Tricks")
261
+
262
+ st.write("πŸŽ₯πŸ”₯ Video Jam")
263
+ if st.button("🎬 Roll It", key="pyav_1"):
264
+ # πŸŽ₯πŸ”₯ Captures like a rockstar shredding! | πŸ“Ή container = av.open('/dev/video0') - Rocks the cam like a live gig!
265
+ try:
266
+ container = av.open('/dev/video0')
267
+ stream = container.streams.video[0]
268
+ file_path = f"pyav_vid_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
269
+ output = av.open(file_path, 'w')
270
+ out_stream = output.add_stream('h264', rate=30)
271
+ for i, frame in enumerate(container.decode(stream)):
272
+ if i > 30: break
273
+ out_frame = frame.reformat(out_stream.width, out_stream.height)
274
+ output.mux(out_stream.encode(out_frame))
275
+ output.close()
276
+ container.close()
277
+ save_to_history("πŸŽ₯ Video", file_path)
278
+ st.video(file_path)
279
+ except Exception as e:
280
+ st.error(f"🚨 Camera snag: {str(e)}")
281
+
282
+ st.write("🎬🍿 Audio Rip")
283
+ if st.button("🎡 Snag Sound", key="pyav_2"):
284
+ # 🎬🍿 Pulls audio like a popcorn thief! | πŸŽ™οΈ frames = [f for f in av.open('vid.mp4').decode()] - Steals sound like a ninja!
285
+ try:
286
+ container = av.open('/dev/video0', 'r', format='v4l2')
287
+ file_path = f"pyav_audio_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
288
+ output = av.open(file_path, 'w')
289
+ out_stream = output.add_stream('pcm_s16le', rate=44100)
290
+ for packet in container.demux():
291
+ for frame in packet.decode():
292
+ if frame.is_corrupt: continue
293
+ if hasattr(frame, 'to_ndarray'):
294
+ output.mux(out_stream.encode(frame))
295
+ if os.path.getsize(file_path) > 100000: break
296
+ output.close()
297
+ container.close()
298
+ save_to_history("🎡 Audio", file_path)
299
+ st.audio(file_path)
300
+ except Exception as e:
301
+ st.error(f"🚨 Camera snag: {str(e)}")
302
+
303
+ st.write("πŸ–€βœ¨ Flip Snap")
304
+ if st.button("πŸ”„ Twist It", key="pyav_3"):
305
+ # πŸ–€βœ¨ Flips colors like a rebel teen! | 🎨 graph = av.filter.Graph().add("negate").pull() - Inverts like a goth makeover!
306
+ try:
307
+ container = av.open('/dev/video0')
308
+ stream = container.streams.video[0]
309
+ file_path = f"pyav_filter_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
310
+ output = av.open(file_path, 'w')
311
+ out_stream = output.add_stream('h264', rate=30)
312
+ graph = av.filter.Graph()
313
+ filt = graph.add("negate")
314
+ for i, frame in enumerate(container.decode(stream)):
315
+ if i > 30: break
316
+ filt.push(frame)
317
+ out_frame = filt.pull()
318
+ output.mux(out_stream.encode(out_frame.reformat(out_stream.width, out_stream.height)))
319
+ output.close()
320
+ container.close()
321
+ save_to_history("πŸŽ₯ Video", file_path)
322
+ st.video(file_path, caption="πŸ–€ Flip Vibes")
323
+ except Exception as e:
324
+ st.error(f"🚨 Camera snag: {str(e)}")
325
+
326
+ # 5. MoviePy - πŸŽ₯ Editing extravaganza!
327
+ with st.expander("5️⃣ πŸ“Ό MoviePy Gala"):
328
+ st.write("πŸŽ₯ Edit Queen: Video diva vibes!")
329
+ st.subheader("πŸ”₯ Top Tricks")
330
+
331
+ st.write("πŸŽžοΈπŸ’ƒ Frame Dance")
332
+ if st.button("🎬 Spin It", key="moviepy_1"):
333
+ # πŸŽžοΈπŸ’ƒ Twirls frames like a dance diva! | πŸŽ₯ clip = mp.ImageSequenceClip([f1, f2], fps=15) - Makes vids like a pro choreographer!
334
+ cap = None
335
+ for i in range(10):
336
+ cap = cv2.VideoCapture(i)
337
+ if cap.isOpened():
338
+ break
339
+ cap.release()
340
+ if cap and cap.isOpened():
341
+ frames = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(30)]
342
+ cap.release()
343
+ file_path = f"moviepy_seq_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
344
+ clip = mp.ImageSequenceClip(frames, fps=15)
345
+ clip.write_videofile(file_path)
346
+ save_to_history("πŸŽ₯ Video", file_path)
347
+ st.video(file_path)
348
+ else:
349
+ st.error("🚨 No camera found!")
350
+
351
+ st.write("πŸ“πŸ‘‘ Size Snap")
352
+ if st.button("βœ‚οΈ Trim It", key="moviepy_2"):
353
+ # πŸ“πŸ‘‘ Resizes like a royal tailor! | βœ‚οΈ clip = mp.VideoFileClip("vid.mp4").resize((320, 240)) - Fits vids like a bespoke suit!
354
+ cap = None
355
+ for i in range(10):
356
+ cap = cv2.VideoCapture(i)
357
+ if cap.isOpened():
358
+ break
359
+ cap.release()
360
+ if cap and cap.isOpened():
361
+ frames = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(30)]
362
+ cap.release()
363
+ temp_path = "temp.mp4"
364
+ mp.ImageSequenceClip(frames, fps=15).write_videofile(temp_path)
365
+ clip = mp.VideoFileClip(temp_path).resize((320, 240))
366
+ file_path = f"moviepy_resized_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
367
+ clip.write_videofile(file_path)
368
+ save_to_history("πŸŽ₯ Video", file_path)
369
+ st.video(file_path, caption="πŸ‘‘ Tiny King")
370
+ else:
371
+ st.error("🚨 No camera found!")
372
+
373
+ st.write("🎬🀝 Join Jam")
374
+ if st.button("πŸ”— Link It", key="moviepy_3"):
375
+ # 🎬🀝 Stitches clips like a love guru! | πŸŽ₯ final = mp.concatenate_videoclips([clip1, clip2]) - Hooks up vids like a matchmaker!
376
+ cap = None
377
+ for i in range(10):
378
+ cap = cv2.VideoCapture(i)
379
+ if cap.isOpened():
380
+ break
381
+ cap.release()
382
+ if cap and cap.isOpened():
383
+ frames1 = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(15)]
384
+ frames2 = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(15)]
385
+ cap.release()
386
+ clip1 = mp.ImageSequenceClip(frames1, fps=15)
387
+ clip2 = mp.ImageSequenceClip(frames2, fps=15)
388
+ final_clip = mp.concatenate_videoclips([clip1, clip2])
389
+ file_path = f"moviepy_concat_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
390
+ final_clip.write_videofile(file_path)
391
+ save_to_history("πŸŽ₯ Video", file_path)
392
+ st.video(file_path, caption="🀝 Duo Dance")
393
+ else:
394
+ st.error("🚨 No camera found!")
395
+
396
+ # 6. JS Audio - 🎡 Browser beats!
397
+ with st.expander("6️⃣ 🎡 JS Audio Jam"):
398
+ st.write("πŸ”Š Web Wizard: Browser-based sound sorcery!")
399
+ st.subheader("πŸ”₯ Top Tricks")
400
+
401
+ # 🎀🌩️ Record audio with MediaRecorder
402
+ record_js = """
403
+ <div>
404
+ <button id="recordBtn" onclick="startRecording()">πŸŽ™οΈ Record</button>
405
+ <button id="stopBtn" onclick="stopRecording()" disabled>⏹️ Stop</button>
406
+ <audio id="audioPlayback" controls></audio>
407
+ </div>
408
+ <script>
409
+ let mediaRecorder;
410
+ let audioChunks = [];
411
+ navigator.mediaDevices.getUserMedia({ audio: true })
412
+ .then(stream => {
413
+ mediaRecorder = new MediaRecorder(stream);
414
+ mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
415
+ mediaRecorder.onstop = () => {
416
+ const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
417
+ const audioUrl = URL.createObjectURL(audioBlob);
418
+ document.getElementById('audioPlayback').src = audioUrl;
419
+ audioChunks = [];
420
+ };
421
+ });
422
+ function startRecording() {
423
+ mediaRecorder.start();
424
+ document.getElementById('recordBtn').disabled = true;
425
+ document.getElementById('stopBtn').disabled = false;
426
+ }
427
+ function stopRecording() {
428
+ mediaRecorder.stop();
429
+ document.getElementById('recordBtn').disabled = false;
430
+ document.getElementById('stopBtn').disabled = true;
431
+ }
432
+ </script>
433
+ """
434
+ st.write("🎀🌩️ Mic Drop")
435
+ st.markdown(record_js, unsafe_allow_html=True)
436
+
437
+ # πŸ”ŠπŸ“‘ Play tone with Web Audio API
438
+ tone_js = """
439
+ <button onclick="playTone()">🎢 Beep!</button>
440
+ <script>
441
+ function playTone() {
442
+ const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
443
+ const oscillator = audioCtx.createOscillator();
444
+ oscillator.type = 'sine';
445
+ oscillator.frequency.setValueAtTime(440, audioCtx.currentTime);
446
+ oscillator.connect(audioCtx.destination);
447
+ oscillator.start();
448
+ setTimeout(() => oscillator.stop(), 500);
449
+ }
450
+ </script>
451
+ """
452
+ st.write("πŸ”ŠπŸ“‘ Tone Snap")
453
+ st.markdown(tone_js, unsafe_allow_html=True)
454
+
455
+ # πŸ“‚ Upload zone like a media drop party!
456
+ st.header("πŸ“₯πŸŽ‰ Drop Zone")
457
+ uploaded_files = st.file_uploader("πŸ“ΈπŸŽ΅πŸŽ₯ Toss Media", accept_multiple_files=True, type=['jpg', 'png', 'mp4', 'wav', 'mp3'])
458
+ if uploaded_files:
459
+ for uploaded_file in uploaded_files:
460
+ file_type = uploaded_file.type.split('/')[0]
461
+ file_path = f"uploaded_{uploaded_file.name}"
462
+ with open(file_path, 'wb') as f:
463
+ f.write(uploaded_file.read())
464
+ emoji_type = "πŸ–ΌοΈ Image" if file_type == 'image' else "πŸŽ₯ Video" if file_type == 'video' else "🎡 Audio"
465
+ save_to_history(emoji_type, file_path)
466
+
467
+ # πŸ–ΌοΈπŸŽ΅πŸŽ₯ Gallery like a media circus!
468
+ st.header("πŸŽͺ Media Mania")
469
+ if st.session_state['file_history']:
470
+ images = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ–ΌοΈ Image"]
471
+ audios = [f for f in st.session_state['file_history'] if f['Type'] == "🎡 Audio"]
472
+ videos = [f for f in st.session_state['file_history'] if f['Type'] in ["πŸŽ₯ Video", "🎞️ GIF"]]
473
+
474
+ if images:
475
+ st.subheader("πŸ–ΌοΈ Pic Parade")
476
+ cols = st.columns(3)
477
+ for i, img in enumerate(images):
478
+ with cols[i % 3]:
479
+ st.image(img['Path'], caption=img['Path'], use_column_width=True)
480
+
481
+ if audios:
482
+ st.subheader("🎡 Sound Splash")
483
+ for audio in audios:
484
+ st.audio(audio['Path'], format=f"audio/{audio['Path'].split('.')[-1]}")
485
+ st.write(f"🎀 {audio['Path']}")
486
+
487
+ if videos:
488
+ st.subheader("πŸŽ₯ Vid Vortex")
489
+ for video in videos:
490
+ st.video(video['Path'])
491
+ st.write(f"🎬 {video['Path']}")
492
+ else:
493
+ st.write("🚫 No loot yet!")
494
+
495
+ # πŸ“œ History log like a time machine!
496
+ st.header("⏳ Snap Saga")
497
+ if st.session_state['file_history']:
498
+ df = pd.DataFrame(st.session_state['file_history'])
499
+ st.dataframe(df)
500
+ else:
501
+ st.write("πŸ•³οΈ Nothing snapped yet!")