Spaces:
Sleeping
Sleeping
File size: 7,125 Bytes
5779747 5e4c3ce 29c477e 5e4c3ce 98946ea e50e82a 98946ea 5779747 5e4c3ce 5779747 98946ea 5779747 98946ea 5779747 98946ea 5e4c3ce 98946ea 5779747 8e725cb 5e4c3ce 98946ea 8e725cb 5779747 98946ea 5779747 98946ea 5779747 8e725cb 5779747 98946ea 963c867 98946ea 5e4c3ce 98946ea 5e4c3ce c8ba898 98946ea c8ba898 98946ea c8ba898 98946ea 5779747 98946ea 8e725cb 5779747 98946ea 5779747 19de063 98946ea 5779747 8e725cb 5779747 98946ea 5779747 5e4c3ce 98946ea 5e4c3ce |
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 |
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) |