awacke1/Pillow-PyMuPDF-ReportLab
2
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!")