File size: 21,988 Bytes
5779747 |
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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 |
import streamlit as st
import pandas as pd
from datetime import datetime
import cv2
from pydub import AudioSegment
import imageio
import av
import moviepy as mp
import os
import numpy as np
from io import BytesIO
import threading
import time
# ππ₯ Initialize session state like a galactic DJ spinning tracks!
if 'file_history' not in st.session_state:
st.session_state['file_history'] = []
if 'ping_code' not in st.session_state:
st.session_state['ping_code'] = ""
if 'uploaded_files' not in st.session_state:
st.session_state['uploaded_files'] = []
if 'auto_capture_running' not in st.session_state:
st.session_state['auto_capture_running'] = False
# ππΎ Save to history like a time-traveling scribe! | π
β¨ save_to_history("Image", "pic.jpg") - Stamps a pic in the history books like a boss!
def save_to_history(file_type, file_path):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
st.session_state['file_history'].append({
"Timestamp": timestamp,
"Type": file_type,
"Path": file_path
})
# πΈβ° Auto-capture every 10 secs like a sneaky shutterbug!
def auto_capture():
if st.session_state['auto_capture_running']:
cap = None
for i in range(10): # Try indices 0-9
cap = cv2.VideoCapture(i)
if cap.isOpened():
break
cap.release()
if cap and cap.isOpened():
ret, frame = cap.read()
if ret:
file_path = f"auto_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
cv2.imwrite(file_path, frame)
save_to_history("πΌοΈ Image", file_path)
cap.release()
else:
st.warning("π¨ No camera found!")
threading.Timer(10, auto_capture).start()
# ποΈ Sidebar config like a spaceship control panel!
with st.sidebar:
st.header("ποΈπΈ Tune-Up Zone")
library_choice = st.selectbox("π Pick a Tool", ["OpenCV", "PyDub", "ImageIO", "PyAV", "MoviePy", "JS Audio"])
resolution = st.select_slider("π Snap Size", options=["320x240", "640x480", "1280x720"], value="640x480")
fps = st.slider("β±οΈ Speed Snap", 1, 60, 30)
if st.button("β° Start Auto-Snap"):
st.session_state['auto_capture_running'] = True
auto_capture()
if st.button("βΉοΈ Stop Auto-Snap"):
st.session_state['auto_capture_running'] = False
# π’ DTMF ping code like a retro phone hacker!
st.subheader("π Ping-a-Tron")
col1, col2, col3, col4 = st.columns(4)
with col1:
digit1 = st.selectbox("1οΈβ£", [str(i) for i in range(10)], key="d1")
with col2:
digit2 = st.selectbox("2οΈβ£", [str(i) for i in range(10)], key="d2")
with col3:
digit3 = st.selectbox("3οΈβ£", [str(i) for i in range(10)], key="d3")
with col4:
digit4 = st.selectbox("4οΈβ£", [str(i) for i in range(10)], key="d4")
ping_code = digit1 + digit2 + digit3 + digit4
st.session_state['ping_code'] = ping_code
st.write(f"π Code: {ping_code}")
# π Sidebar file outline with emoji flair!
st.subheader("π File Vault")
if st.session_state['file_history']:
images = [f for f in st.session_state['file_history'] if f['Type'] == "πΌοΈ Image"]
videos = [f for f in st.session_state['file_history'] if f['Type'] in ["π₯ Video", "ποΈ GIF"]]
audios = [f for f in st.session_state['file_history'] if f['Type'] == "π΅ Audio"]
if images:
st.write("πΌοΈ Images")
for img in images:
st.write(f"- {img['Path']} @ {img['Timestamp']}")
if videos:
st.write("π₯ Videos/GIFs")
for vid in videos:
st.write(f"- {vid['Path']} @ {vid['Timestamp']}")
if audios:
st.write("π΅ Audios")
for aud in audios:
st.write(f"- {aud['Path']} @ {aud['Timestamp']}")
else:
st.write("π³οΈ Empty Vault!")
# ππ¨ Main UI kicks off like a cosmic art show!
st.title("πΈποΈ Capture Craze")
# πΈπ Library showcase like a tech talent show!
st.header("πΈποΈ Tool Titans")
# 1. OpenCV - π· Pixel party time!
with st.expander("1οΈβ£ π· OpenCV Fiesta"):
st.write("π₯ Snap Star: Real-time pixel magic!")
st.subheader("π₯ Top Tricks")
st.write("πΈπ₯ Video Snap")
if st.button("π¬ Go Live", key="opencv_1"):
# π·π₯ Snags webcam like a paparazzi pro! | πΈ cap = cv2.VideoCapture(0) - Grabs live feed faster than gossip spreads!
cap = None
for i in range(10):
cap = cv2.VideoCapture(i)
if cap.isOpened():
break
cap.release()
if cap and cap.isOpened():
frame_placeholder = st.empty()
for _ in range(50):
ret, frame = cap.read()
if ret:
frame_placeholder.image(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
cap.release()
else:
st.error("π¨ No camera found!")
st.write("ποΈβ¨ Gray Snap")
if st.button("π· Save Gray", key="opencv_2"):
# ποΈβ¨ Saves grayscale like an artsy ghost! | π cv2.imwrite("gray.jpg", cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)) - Ditches color like a moody poet!
cap = None
for i in range(10):
cap = cv2.VideoCapture(i)
if cap.isOpened():
break
cap.release()
if cap and cap.isOpened():
ret, frame = cap.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
file_path = f"opencv_gray_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
cv2.imwrite(file_path, gray)
save_to_history("πΌοΈ Image", file_path)
st.image(file_path, caption="π€ Gray Vibes")
cap.release()
else:
st.error("π¨ No camera found!")
st.write("π΅οΈββοΈπ Edge Snap")
if st.button("πͺ Edge It", key="opencv_3"):
# π΅οΈββοΈπ Finds edges sharper than a detectiveβs wit! | πΌοΈ edges = cv2.Canny(frame, 100, 200) - Outlines like a crime scene sketch!
cap = None
for i in range(10):
cap = cv2.VideoCapture(i)
if cap.isOpened():
break
cap.release()
if cap and cap.isOpened():
ret, frame = cap.read()
if ret:
edges = cv2.Canny(frame, 100, 200)
file_path = f"opencv_edges_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
cv2.imwrite(file_path, edges)
save_to_history("πΌοΈ Image", file_path)
st.image(file_path, caption="π Edge Lord")
cap.release()
else:
st.error("π¨ No camera found!")
# 2. PyDub - ποΈ Audio mixing madness!
with st.expander("2οΈβ£ ποΈ PyDub Party"):
st.write("π Audio Ace: Mixmaster vibes!")
st.subheader("π₯ Top Tricks")
st.write("π€π©οΈ Load Jam")
if st.button("π΅ Load Sound", key="pydub_1"):
# π€π©οΈ Grabs audio like a sonic thief! | ποΈ AudioSegment.from_file("sound.wav") - Nabs tracks like a sound bandit!
uploaded_audio = st.file_uploader("ποΈ Drop a WAV", type=['wav'], key="pydub_load")
if uploaded_audio:
sound = AudioSegment.from_file(uploaded_audio)
file_path = f"pydub_load_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
sound.export(file_path, format="wav")
save_to_history("π΅ Audio", file_path)
st.audio(file_path)
st.write("ππ‘ Export Snap")
if st.button("πΆ MP3 It", key="pydub_2"):
# ππ‘ Spits out tracks like a beat factory! | π΅ sound.export("out.mp3") - Pumps tunes like a hit machine!
uploaded_audio = st.file_uploader("ποΈ Drop a WAV", type=['wav'], key="pydub_export")
if uploaded_audio:
sound = AudioSegment.from_file(uploaded_audio)
file_path = f"pydub_mp3_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp3"
sound.export(file_path, format="mp3")
save_to_history("π΅ Audio", file_path)
st.audio(file_path)
st.write("πΆπΎ Reverse Blast")
if st.button("π Flip It", key="pydub_3"):
# πΆπΎ Flips sound like a time-travel DJ! | π§ sound.reverse() - Spins audio back like a retro remix!
uploaded_audio = st.file_uploader("ποΈ Drop a WAV", type=['wav'], key="pydub_reverse")
if uploaded_audio:
sound = AudioSegment.from_file(uploaded_audio)
reversed_sound = sound.reverse()
file_path = f"pydub_rev_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
reversed_sound.export(file_path, format="wav")
save_to_history("π΅ Audio", file_path)
st.audio(file_path)
# 3. ImageIO - πΌοΈ Pixel playtime!
with st.expander("3οΈβ£ πΉ ImageIO Bash"):
st.write("π₯ Easy Snap: Pixel lightweight champ!")
st.subheader("π₯ Top Tricks")
st.write("πΉπ Frame Peek")
if st.button("πΈ Snap It", key="imageio_1"):
# πΉπ Grabs frames like a shy stalker! | π· reader = imageio.get_reader('<video0>') - Sneaks a peek at your cam!
try:
reader = imageio.get_reader('<video0>')
frame = reader.get_next_data()
file_path = f"imageio_frame_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
imageio.imwrite(file_path, frame)
save_to_history("πΌοΈ Image", file_path)
st.image(file_path)
except Exception as e:
st.error(f"π¨ Camera snag: {str(e)}")
st.write("π¨οΈπ Crunch Snap")
if st.button("π Slim Pic", key="imageio_2"):
# π¨οΈπ Compresses like a diet guru! | πΌοΈ imageio.imwrite("pic.jpg", frame, quality=85) - Shrinks pics like a tight squeeze!
try:
reader = imageio.get_reader('<video0>')
frame = reader.get_next_data()
file_path = f"imageio_comp_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
imageio.imwrite(file_path, frame, quality=85)
save_to_history("πΌοΈ Image", file_path)
st.image(file_path, caption="π Slim Fit")
except Exception as e:
st.error(f"π¨ Camera snag: {str(e)}")
st.write("ποΈπ€‘ GIF Blast")
if st.button("π GIF It", key="imageio_3"):
# ποΈπ€‘ Makes GIFs like a circus juggler! | π₯ imageio.mimwrite("gif.gif", [f1, f2], fps=5) - Flips frames into fun!
try:
reader = imageio.get_reader('<video0>')
frames = [reader.get_next_data() for _ in range(10)]
file_path = f"imageio_gif_{datetime.now().strftime('%Y%m%d_%H%M%S')}.gif"
imageio.mimwrite(file_path, frames, fps=5)
save_to_history("ποΈ GIF", file_path)
st.image(file_path, caption="π€‘ GIF Party")
except Exception as e:
st.error(f"π¨ Camera snag: {str(e)}")
# 4. PyAV - π¬ AV rock fest!
with st.expander("4οΈβ£ π¬ PyAV Rave"):
st.write("π₯ AV King: FFmpeg-powered chaos!")
st.subheader("π₯ Top Tricks")
st.write("π₯π₯ Video Jam")
if st.button("π¬ Roll It", key="pyav_1"):
# π₯π₯ Captures like a rockstar shredding! | πΉ container = av.open('/dev/video0') - Rocks the cam like a live gig!
try:
container = av.open('/dev/video0')
stream = container.streams.video[0]
file_path = f"pyav_vid_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
output = av.open(file_path, 'w')
out_stream = output.add_stream('h264', rate=30)
for i, frame in enumerate(container.decode(stream)):
if i > 30: break
out_frame = frame.reformat(out_stream.width, out_stream.height)
output.mux(out_stream.encode(out_frame))
output.close()
container.close()
save_to_history("π₯ Video", file_path)
st.video(file_path)
except Exception as e:
st.error(f"π¨ Camera snag: {str(e)}")
st.write("π¬πΏ Audio Rip")
if st.button("π΅ Snag Sound", key="pyav_2"):
# π¬πΏ Pulls audio like a popcorn thief! | ποΈ frames = [f for f in av.open('vid.mp4').decode()] - Steals sound like a ninja!
try:
container = av.open('/dev/video0', 'r', format='v4l2')
file_path = f"pyav_audio_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
output = av.open(file_path, 'w')
out_stream = output.add_stream('pcm_s16le', rate=44100)
for packet in container.demux():
for frame in packet.decode():
if frame.is_corrupt: continue
if hasattr(frame, 'to_ndarray'):
output.mux(out_stream.encode(frame))
if os.path.getsize(file_path) > 100000: break
output.close()
container.close()
save_to_history("π΅ Audio", file_path)
st.audio(file_path)
except Exception as e:
st.error(f"π¨ Camera snag: {str(e)}")
st.write("π€β¨ Flip Snap")
if st.button("π Twist It", key="pyav_3"):
# π€β¨ Flips colors like a rebel teen! | π¨ graph = av.filter.Graph().add("negate").pull() - Inverts like a goth makeover!
try:
container = av.open('/dev/video0')
stream = container.streams.video[0]
file_path = f"pyav_filter_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
output = av.open(file_path, 'w')
out_stream = output.add_stream('h264', rate=30)
graph = av.filter.Graph()
filt = graph.add("negate")
for i, frame in enumerate(container.decode(stream)):
if i > 30: break
filt.push(frame)
out_frame = filt.pull()
output.mux(out_stream.encode(out_frame.reformat(out_stream.width, out_stream.height)))
output.close()
container.close()
save_to_history("π₯ Video", file_path)
st.video(file_path, caption="π€ Flip Vibes")
except Exception as e:
st.error(f"π¨ Camera snag: {str(e)}")
# 5. MoviePy - π₯ Editing extravaganza!
with st.expander("5οΈβ£ πΌ MoviePy Gala"):
st.write("π₯ Edit Queen: Video diva vibes!")
st.subheader("π₯ Top Tricks")
st.write("ποΈπ Frame Dance")
if st.button("π¬ Spin It", key="moviepy_1"):
# ποΈπ Twirls frames like a dance diva! | π₯ clip = mp.ImageSequenceClip([f1, f2], fps=15) - Makes vids like a pro choreographer!
cap = None
for i in range(10):
cap = cv2.VideoCapture(i)
if cap.isOpened():
break
cap.release()
if cap and cap.isOpened():
frames = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(30)]
cap.release()
file_path = f"moviepy_seq_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
clip = mp.ImageSequenceClip(frames, fps=15)
clip.write_videofile(file_path)
save_to_history("π₯ Video", file_path)
st.video(file_path)
else:
st.error("π¨ No camera found!")
st.write("ππ Size Snap")
if st.button("βοΈ Trim It", key="moviepy_2"):
# ππ Resizes like a royal tailor! | βοΈ clip = mp.VideoFileClip("vid.mp4").resize((320, 240)) - Fits vids like a bespoke suit!
cap = None
for i in range(10):
cap = cv2.VideoCapture(i)
if cap.isOpened():
break
cap.release()
if cap and cap.isOpened():
frames = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(30)]
cap.release()
temp_path = "temp.mp4"
mp.ImageSequenceClip(frames, fps=15).write_videofile(temp_path)
clip = mp.VideoFileClip(temp_path).resize((320, 240))
file_path = f"moviepy_resized_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
clip.write_videofile(file_path)
save_to_history("π₯ Video", file_path)
st.video(file_path, caption="π Tiny King")
else:
st.error("π¨ No camera found!")
st.write("π¬π€ Join Jam")
if st.button("π Link It", key="moviepy_3"):
# π¬π€ Stitches clips like a love guru! | π₯ final = mp.concatenate_videoclips([clip1, clip2]) - Hooks up vids like a matchmaker!
cap = None
for i in range(10):
cap = cv2.VideoCapture(i)
if cap.isOpened():
break
cap.release()
if cap and cap.isOpened():
frames1 = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(15)]
frames2 = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(15)]
cap.release()
clip1 = mp.ImageSequenceClip(frames1, fps=15)
clip2 = mp.ImageSequenceClip(frames2, fps=15)
final_clip = mp.concatenate_videoclips([clip1, clip2])
file_path = f"moviepy_concat_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
final_clip.write_videofile(file_path)
save_to_history("π₯ Video", file_path)
st.video(file_path, caption="π€ Duo Dance")
else:
st.error("π¨ No camera found!")
# 6. JS Audio - π΅ Browser beats!
with st.expander("6οΈβ£ π΅ JS Audio Jam"):
st.write("π Web Wizard: Browser-based sound sorcery!")
st.subheader("π₯ Top Tricks")
# π€π©οΈ Record audio with MediaRecorder
record_js = """
<div>
<button id="recordBtn" onclick="startRecording()">ποΈ Record</button>
<button id="stopBtn" onclick="stopRecording()" disabled>βΉοΈ Stop</button>
<audio id="audioPlayback" controls></audio>
</div>
<script>
let mediaRecorder;
let audioChunks = [];
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
mediaRecorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
document.getElementById('audioPlayback').src = audioUrl;
audioChunks = [];
};
});
function startRecording() {
mediaRecorder.start();
document.getElementById('recordBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
}
function stopRecording() {
mediaRecorder.stop();
document.getElementById('recordBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
}
</script>
"""
st.write("π€π©οΈ Mic Drop")
st.markdown(record_js, unsafe_allow_html=True)
# ππ‘ Play tone with Web Audio API
tone_js = """
<button onclick="playTone()">πΆ Beep!</button>
<script>
function playTone() {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioCtx.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(440, audioCtx.currentTime);
oscillator.connect(audioCtx.destination);
oscillator.start();
setTimeout(() => oscillator.stop(), 500);
}
</script>
"""
st.write("ππ‘ Tone Snap")
st.markdown(tone_js, unsafe_allow_html=True)
# π Upload zone like a media drop party!
st.header("π₯π Drop Zone")
uploaded_files = st.file_uploader("πΈπ΅π₯ Toss Media", accept_multiple_files=True, type=['jpg', 'png', 'mp4', 'wav', 'mp3'])
if uploaded_files:
for uploaded_file in uploaded_files:
file_type = uploaded_file.type.split('/')[0]
file_path = f"uploaded_{uploaded_file.name}"
with open(file_path, 'wb') as f:
f.write(uploaded_file.read())
emoji_type = "πΌοΈ Image" if file_type == 'image' else "π₯ Video" if file_type == 'video' else "π΅ Audio"
save_to_history(emoji_type, file_path)
# πΌοΈπ΅π₯ Gallery like a media circus!
st.header("πͺ Media Mania")
if st.session_state['file_history']:
images = [f for f in st.session_state['file_history'] if f['Type'] == "πΌοΈ Image"]
audios = [f for f in st.session_state['file_history'] if f['Type'] == "π΅ Audio"]
videos = [f for f in st.session_state['file_history'] if f['Type'] in ["π₯ Video", "ποΈ GIF"]]
if images:
st.subheader("πΌοΈ Pic Parade")
cols = st.columns(3)
for i, img in enumerate(images):
with cols[i % 3]:
st.image(img['Path'], caption=img['Path'], use_column_width=True)
if audios:
st.subheader("π΅ Sound Splash")
for audio in audios:
st.audio(audio['Path'], format=f"audio/{audio['Path'].split('.')[-1]}")
st.write(f"π€ {audio['Path']}")
if videos:
st.subheader("π₯ Vid Vortex")
for video in videos:
st.video(video['Path'])
st.write(f"π¬ {video['Path']}")
else:
st.write("π« No loot yet!")
# π History log like a time machine!
st.header("β³ Snap Saga")
if st.session_state['file_history']:
df = pd.DataFrame(st.session_state['file_history'])
st.dataframe(df)
else:
st.write("π³οΈ Nothing snapped yet!") |