CoolFace
Apppublic

awacke1/Pillow-PyMuPDF-ReportLab

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