awacke1's picture
Update app.py
ab5b911 verified
raw
history blame
15.4 kB
import streamlit as st
import pandas as pd
from datetime import datetime
import cv2
import pyaudio
import wave
import imageio
import av
import moviepy.editor as mp
import os
import numpy as np
from io import BytesIO
# 🌟πŸ”₯ 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'] = []
# πŸ“œπŸ’Ύ 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
})
# 🌍🎨 Main UI kicks off like a cosmic art show!
st.title("πŸ“ΈπŸŽ™οΈ Capture Craze")
# πŸŽ›οΈ Sidebar config like a spaceship control panel!
with st.sidebar:
st.header("πŸŽšοΈπŸ“Έ Tune-Up Zone")
library_choice = st.selectbox("πŸ“š Pick a Tool", ["OpenCV", "PyAudio", "ImageIO", "PyAV", "MoviePy"])
resolution = st.select_slider("πŸ“ Snap Size", options=["320x240", "640x480", "1280x720"], value="640x480")
fps = st.slider("⏱️ Speed Snap", 1, 60, 30)
# πŸ”’ 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}")
# πŸ“ΈπŸ“š 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 = cv2.VideoCapture(0)
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()
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 = cv2.VideoCapture(0)
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()
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 = cv2.VideoCapture(0)
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()
# 2. PyAudio - πŸŽ™οΈ Soundwave showdown!
with st.expander("2️⃣ πŸŽ™οΈ PyAudio Party"):
st.write("πŸ”Š Audio Ace: Sound control ninja!")
st.subheader("πŸ”₯ Top Tricks")
st.write("🎀🌩️ Record Jam")
if st.button("🎡 Grab Sound", key="pyaudio_1"):
# 🎀🌩️ Records like a storm-chasing bard! | πŸŽ™οΈ stream = pyaudio.PyAudio().open(...) - Captures audio like thunder in a bottle!
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
frames = [stream.read(1024) for _ in range(int(44100 / 1024 * 3))]
stream.stop_stream()
stream.close()
p.terminate()
file_path = f"pyaudio_rec_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
with wave.open(file_path, 'wb') as wf:
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wf.setframerate(44100)
wf.writeframes(b''.join(frames))
save_to_history("Audio", file_path)
st.audio(file_path)
st.write("πŸ•΅οΈβ€β™€οΈπŸ“‘ Mic Spy")
if st.button("πŸ” List Mics", key="pyaudio_2"):
# πŸ•΅οΈβ€β™€οΈπŸ“‘ Spies mics like a gossip queen! | πŸ“‘ info = pyaudio.PyAudio().get_device_info_by_index(0) - Sniffs out devices like a tech bloodhound!
p = pyaudio.PyAudio()
devices = [p.get_device_info_by_index(i) for i in range(p.get_device_count())]
st.write("πŸŽ™οΈ Mic Squad:", devices)
p.terminate()
st.write("πŸŽΆπŸ’Ύ Sound Bite")
if st.button("🎧 Quick Grab", key="pyaudio_3"):
# πŸŽΆπŸ’Ύ Snags audio like a DJ mid-set! | 🎡 data = stream.read(1024) - Bites sound faster than a snack attack!
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
data = stream.read(1024)
st.write("🎡 Bytes Nabbed:", len(data))
stream.stop_stream()
stream.close()
p.terminate()
# 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!
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)
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!
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")
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!
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")
# 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!
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)
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!
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)
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!
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")
# 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 = cv2.VideoCapture(0)
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 - init_block_and_save_video_file(file_path)
save_to_history("VideoΨ―ΫŒΩ† st.session_state['file_history'].append({"Timestamp": timestamp, "Type": "Video", "Path": file_path})
st.session_state['file_history'].append({"Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "Type": "Video", "Path": file_path})
st.video(file_path)
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 = cv2.VideoCapture(0)
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")
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 = cv2.VideoCapture(0)
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")
# πŸ“‚ 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())
st.session_state['uploaded_files'].append({
"Name": uploaded_file.name,
"Type": file_type,
"Path": file_path
})
# πŸ–ΌοΈπŸŽ΅πŸŽ₯ Gallery like a media circus!
st.header("πŸŽͺ Media Mania")
if st.session_state['uploaded_files']:
images = [f for f in st.session_state['uploaded_files'] if f['Type'] == 'image']
audios = [f for f in st.session_state['uploaded_files'] if f['Type'] == 'audio']
videos = [f for f in st.session_state['uploaded_files'] if f['Type'] == 'video']
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['Name'], use_column_width=True)
if audios:
st.subheader("🎡 Sound Splash")
for audio in audios:
st.audio(audio['Path'], format=f"audio/{audio['Name'].split('.')[-1]}")
st.write(f"🎀 {audio['Name']}")
if videos:
st.subheader("πŸŽ₯ Vid Vortex")
for video in videos:
st.video(video['Path'])
st.write(f"🎬 {video['Name']}")
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!")