awacke1's picture
Update app.py
98946ea verified
raw
history blame
7.13 kB
import streamlit as st
import pandas as pd
from datetime import datetime
import os
import threading
import time
from PIL import Image
from io import BytesIO
import base64
from imutils.video import VideoStream
import cv2
from pydub import AudioSegment
from pydub.playback import play
import pypdf
import numpy as np
# 🌟πŸ”₯ Initialize session state
if 'file_history' not in st.session_state:
st.session_state['file_history'] = []
if 'auto_capture_running' not in st.session_state:
st.session_state['auto_capture_running'] = False
# πŸ“œπŸ’Ύ Save to history
def save_to_history(file_type, file_path, data=None):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if file_type == "πŸ–ΌοΈ Image" and data is not None:
cv2.imwrite(file_path, cv2.cvtColor(data, cv2.COLOR_RGB2BGR))
elif file_type == "🎡 Audio" and data is not None:
data.export(file_path, format="wav")
elif file_type == "πŸ“œ PDF" and data is not None:
with open(file_path, "wb") as f:
f.write(data)
st.session_state['file_history'].append({
"Timestamp": timestamp,
"Type": file_type,
"Path": file_path
})
# πŸ“Έβ° Auto-capture every 10 secs
def auto_capture(streams):
while st.session_state['auto_capture_running']:
for i, stream in enumerate(streams):
frame = stream.read()
if frame is not None:
filename = f"cam{i}_auto_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
save_to_history("πŸ–ΌοΈ Image", filename, frame)
time.sleep(10)
# πŸŽ›οΈ Sidebar config
with st.sidebar:
st.header("πŸŽšοΈπŸ“Έ Snap Shack")
streams = [
VideoStream(src=0).start(), # Camera 0
VideoStream(src=1).start() # Camera 1
]
if st.button("⏰ Start Auto-Snap"):
st.session_state['auto_capture_running'] = True
threading.Thread(target=auto_capture, args=(streams,), daemon=True).start()
if st.button("⏹️ Stop Auto-Snap"):
st.session_state['auto_capture_running'] = False
# Audio recording control
if st.button("πŸŽ™οΈ Record Audio (5s)"):
audio = AudioSegment.silent(duration=5000) # Placeholder; real mic capture needs pyaudio
filename = f"audio_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
save_to_history("🎡 Audio", filename, audio)
st.subheader("πŸ“œ Snap Stash")
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"]
pdfs = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ“œ PDF"]
if images:
st.write("πŸ–ΌοΈ Images")
for img in images:
st.write(f"- {img['Path']} @ {img['Timestamp']}")
if audios:
st.write("🎡 Audios")
for aud in audios:
st.write(f"- {aud['Path']} @ {aud['Timestamp']}")
if pdfs:
st.write("πŸ“œ PDFs")
for pdf in pdfs:
st.write(f"- {pdf['Path']} @ {pdf['Timestamp']}")
else:
st.write("πŸ•³οΈ Empty Stash!")
# 🌍🎨 Main UI
st.title("πŸ“Έ Multi-Lib Snap Craze")
# πŸ“ΈπŸ“· Camera snap zone
st.header("πŸ“ΈπŸŽ₯ Snap Zone")
cols = st.columns(2)
placeholders = [cols[0].empty(), cols[1].empty()]
for i, (placeholder, stream) in enumerate(zip(placeholders, streams)):
frame = stream.read()
if frame is not None:
placeholder.image(frame, caption=f"Live Cam {i}", use_container_width=True)
else:
placeholder.error(f"🚨 No feed from Cam {i}")
if st.button(f"πŸ“Έ Snap Cam {i}", key=f"snap{i}"):
frame = stream.read()
if frame is not None:
filename = f"cam{i}_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
save_to_history("πŸ–ΌοΈ Image", filename, frame)
# πŸ“‚ Upload zone (PDFs and Images)
st.header("πŸ“₯πŸŽ‰ Drop Zone")
uploaded_files = st.file_uploader("πŸ“œπŸ“Έ Upload PDFs or Images", accept_multiple_files=True, type=['pdf', 'jpg', 'png'])
if uploaded_files:
for uploaded_file in uploaded_files:
file_type = "πŸ“œ PDF" if uploaded_file.type == "application/pdf" else "πŸ–ΌοΈ Image"
file_path = f"uploaded_{uploaded_file.name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{uploaded_file.name.split('.')[-1]}"
if file_type == "πŸ–ΌοΈ Image":
img = Image.open(uploaded_file)
img_array = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
save_to_history(file_type, file_path, img_array)
st.image(img, caption=uploaded_file.name, use_container_width=True)
else:
save_to_history(file_type, file_path, uploaded_file.getvalue())
with pypdf.PdfReader(uploaded_file) as reader:
st.write(f"PDF Pages: {len(reader.pages)}")
# πŸ–ΌοΈ Gallery
st.header("πŸŽͺ Snap Show")
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"]
pdfs = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ“œ PDF"]
if images:
st.subheader("πŸ–ΌοΈ Pic Parade")
cols = st.columns(3)
for i, img in enumerate(images):
with cols[i % 3]:
if os.path.exists(img['Path']):
st.image(img['Path'], caption=img['Path'], use_container_width=True)
with open(img['Path'], "rb") as f:
img_data = f.read()
st.markdown(f'<a href="data:image/jpeg;base64,{base64.b64encode(img_data).decode()}" download="{os.path.basename(img["Path"])}">πŸ“₯ Snag It!</a>', unsafe_allow_html=True)
if audios:
st.subheader("🎡 Audio Alley")
for aud in audios:
if os.path.exists(aud['Path']):
st.audio(aud['Path'])
with open(aud['Path'], "rb") as f:
aud_data = f.read()
st.markdown(f'<a href="data:audio/wav;base64,{base64.b64encode(aud_data).decode()}" download="{os.path.basename(aud["Path"])}">πŸ“₯ Snag It!</a>', unsafe_allow_html=True)
if pdfs:
st.subheader("πŸ“œ PDF Plaza")
for pdf in pdfs:
if os.path.exists(pdf['Path']):
with open(pdf['Path'], "rb") as f:
pdf_data = f.read()
st.markdown(f'<a href="data:application/pdf;base64,{base64.b64encode(pdf_data).decode()}" download="{os.path.basename(pdf["Path"])}">πŸ“₯ Download {os.path.basename(pdf["Path"])}</a>', unsafe_allow_html=True)
else:
st.write("🚫 No snaps yet!")
# πŸ“œ History log
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!")
# Cleanup
def cleanup():
for stream in streams:
stream.stop()
import atexit
atexit.register(cleanup)