Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -7,24 +7,59 @@ import time
|
|
7 |
from PIL import Image
|
8 |
from io import BytesIO
|
9 |
import base64
|
10 |
-
|
11 |
-
|
12 |
-
AUTO_CAPTURE_RUNNING = False
|
13 |
-
SELECTED_CAM_IMG = None
|
14 |
|
15 |
# ππ₯ Initialize session state like a galactic DJ spinning tracks!
|
16 |
if 'file_history' not in st.session_state:
|
17 |
st.session_state['file_history'] = []
|
18 |
-
if '
|
19 |
-
st.session_state['
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
# ππΎ Save to history like a time-traveling scribe! | π
β¨ save_to_history("πΌοΈ Image", "pic.jpg", img_data) - Stamps a pic in the history books like a boss!
|
24 |
def save_to_history(file_type, file_path, img_data):
|
25 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
26 |
-
|
27 |
-
|
|
|
28 |
st.session_state['file_history'].append({
|
29 |
"Timestamp": timestamp,
|
30 |
"Type": file_type,
|
@@ -32,30 +67,25 @@ def save_to_history(file_type, file_path, img_data):
|
|
32 |
})
|
33 |
|
34 |
# πΈβ° Auto-capture every 10 secs like a sneaky shutterbug!
|
35 |
-
def auto_capture():
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
})
|
46 |
-
threading.Timer(10, auto_capture).start()
|
47 |
|
48 |
# ποΈ Sidebar config like a spaceship control panel!
|
49 |
with st.sidebar:
|
50 |
st.header("ποΈπΈ Snap Shack")
|
51 |
-
camera_choice = st.selectbox("π· Pick a Cam", ["Camera 0", "Camera 1"])
|
52 |
if st.button("β° Start Auto-Snap"):
|
53 |
-
|
54 |
-
|
55 |
-
auto_capture()
|
56 |
if st.button("βΉοΈ Stop Auto-Snap"):
|
57 |
-
|
58 |
-
AUTO_CAPTURE_RUNNING = False
|
59 |
|
60 |
# π Sidebar file outline with emoji flair!
|
61 |
st.subheader("π Snap Stash")
|
@@ -69,33 +99,34 @@ with st.sidebar:
|
|
69 |
st.write("π³οΈ Empty Stash!")
|
70 |
|
71 |
# ππ¨ Main UI kicks off like a cosmic art show!
|
72 |
-
st.title("πΈ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
# πΈπ· Camera snap zone!
|
75 |
st.header("πΈπ₯ Snap Zone")
|
76 |
cols = st.columns(2)
|
77 |
-
|
78 |
-
|
79 |
-
if
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
filename = f"cam1_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
|
92 |
-
if st.session_state['cam1_file'] and os.path.exists(st.session_state['cam1_file']):
|
93 |
-
os.remove(st.session_state['cam1_file'])
|
94 |
-
save_to_history("πΌοΈ Image", filename, cam1_img.getvalue())
|
95 |
-
st.session_state['cam1_file'] = filename
|
96 |
-
global SELECTED_CAM_IMG
|
97 |
-
SELECTED_CAM_IMG = cam1_img.getvalue()
|
98 |
-
st.image(Image.open(BytesIO(cam1_img.getvalue())), caption="Camera 1 Snap", use_container_width=True)
|
99 |
|
100 |
# π Upload zone like a media drop party!
|
101 |
st.header("π₯π Drop Zone")
|
@@ -103,8 +134,10 @@ uploaded_files = st.file_uploader("πΈ Toss Pics", accept_multiple_files=True,
|
|
103 |
if uploaded_files:
|
104 |
for uploaded_file in uploaded_files:
|
105 |
file_path = f"uploaded_{uploaded_file.name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
|
106 |
-
|
107 |
-
|
|
|
|
|
108 |
|
109 |
# πΌοΈ Gallery like a media circus!
|
110 |
st.header("πͺ Snap Show")
|
@@ -131,4 +164,14 @@ if st.session_state['file_history']:
|
|
131 |
df = pd.DataFrame(st.session_state['file_history'])
|
132 |
st.dataframe(df)
|
133 |
else:
|
134 |
-
st.write("π³οΈ Nothing snapped yet!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
from PIL import Image
|
8 |
from io import BytesIO
|
9 |
import base64
|
10 |
+
import cv2
|
11 |
+
import queue
|
|
|
|
|
12 |
|
13 |
# ππ₯ Initialize session state like a galactic DJ spinning tracks!
|
14 |
if 'file_history' not in st.session_state:
|
15 |
st.session_state['file_history'] = []
|
16 |
+
if 'auto_capture_running' not in st.session_state:
|
17 |
+
st.session_state['auto_capture_running'] = False
|
18 |
+
|
19 |
+
# πΈπ· Camera thread class for OpenCV capture
|
20 |
+
class CamThread(threading.Thread):
|
21 |
+
def __init__(self, preview_name, cam_id, frame_queue):
|
22 |
+
threading.Thread.__init__(self)
|
23 |
+
self.preview_name = preview_name
|
24 |
+
self.cam_id = cam_id
|
25 |
+
self.frame_queue = frame_queue
|
26 |
+
self.running = True
|
27 |
+
|
28 |
+
def run(self):
|
29 |
+
print(f"Starting {self.preview_name}")
|
30 |
+
self.cam_preview()
|
31 |
+
|
32 |
+
def cam_preview(self):
|
33 |
+
cam = cv2.VideoCapture(self.cam_id)
|
34 |
+
cam.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # Set reasonable resolution
|
35 |
+
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
|
36 |
+
cam.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')) # Use MJPG for better USB compatibility
|
37 |
+
if not cam.isOpened():
|
38 |
+
st.error(f"π¨ Failed to open {self.preview_name}")
|
39 |
+
return
|
40 |
+
|
41 |
+
while self.running:
|
42 |
+
ret, frame = cam.read()
|
43 |
+
if ret:
|
44 |
+
# Convert BGR to RGB for display
|
45 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
46 |
+
try:
|
47 |
+
self.frame_queue.put_nowait(frame_rgb)
|
48 |
+
except queue.Full:
|
49 |
+
pass # Skip if queue is full
|
50 |
+
time.sleep(0.03) # ~30 FPS
|
51 |
+
|
52 |
+
cam.release()
|
53 |
+
|
54 |
+
def stop(self):
|
55 |
+
self.running = False
|
56 |
|
57 |
# ππΎ Save to history like a time-traveling scribe! | π
β¨ save_to_history("πΌοΈ Image", "pic.jpg", img_data) - Stamps a pic in the history books like a boss!
|
58 |
def save_to_history(file_type, file_path, img_data):
|
59 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
60 |
+
# Convert RGB to BGR for OpenCV saving
|
61 |
+
img_bgr = cv2.cvtColor(img_data, cv2.COLOR_RGB2BGR)
|
62 |
+
cv2.imwrite(file_path, img_bgr)
|
63 |
st.session_state['file_history'].append({
|
64 |
"Timestamp": timestamp,
|
65 |
"Type": file_type,
|
|
|
67 |
})
|
68 |
|
69 |
# πΈβ° Auto-capture every 10 secs like a sneaky shutterbug!
|
70 |
+
def auto_capture(frame_queues):
|
71 |
+
while st.session_state['auto_capture_running']:
|
72 |
+
for i, q in enumerate(frame_queues):
|
73 |
+
try:
|
74 |
+
frame = q.get_nowait()
|
75 |
+
filename = f"cam{i}_auto_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
|
76 |
+
save_to_history("πΌοΈ Image", filename, frame)
|
77 |
+
except queue.Empty:
|
78 |
+
pass # Skip if no frame available
|
79 |
+
time.sleep(10)
|
|
|
|
|
80 |
|
81 |
# ποΈ Sidebar config like a spaceship control panel!
|
82 |
with st.sidebar:
|
83 |
st.header("ποΈπΈ Snap Shack")
|
|
|
84 |
if st.button("β° Start Auto-Snap"):
|
85 |
+
st.session_state['auto_capture_running'] = True
|
86 |
+
threading.Thread(target=auto_capture, args=(frame_queues,), daemon=True).start()
|
|
|
87 |
if st.button("βΉοΈ Stop Auto-Snap"):
|
88 |
+
st.session_state['auto_capture_running'] = False
|
|
|
89 |
|
90 |
# π Sidebar file outline with emoji flair!
|
91 |
st.subheader("π Snap Stash")
|
|
|
99 |
st.write("π³οΈ Empty Stash!")
|
100 |
|
101 |
# ππ¨ Main UI kicks off like a cosmic art show!
|
102 |
+
st.title("πΈ OpenCV Snap Craze")
|
103 |
+
|
104 |
+
# πΈπ· Start camera threads
|
105 |
+
frame_queues = [queue.Queue(maxsize=1), queue.Queue(maxsize=1)]
|
106 |
+
threads = [
|
107 |
+
CamThread("Camera 0", 0, frame_queues[0]),
|
108 |
+
CamThread("Camera 1", 1, frame_queues[1])
|
109 |
+
]
|
110 |
+
for thread in threads:
|
111 |
+
thread.start()
|
112 |
|
113 |
# πΈπ· Camera snap zone!
|
114 |
st.header("πΈπ₯ Snap Zone")
|
115 |
cols = st.columns(2)
|
116 |
+
placeholders = [cols[0].empty(), cols[1].empty()]
|
117 |
+
for i, (placeholder, q, thread) in enumerate(zip(placeholders, frame_queues, threads)):
|
118 |
+
if st.button(f"πΈ Snap Cam {i}", key=f"snap{i}"):
|
119 |
+
try:
|
120 |
+
frame = q.get_nowait()
|
121 |
+
filename = f"cam{i}_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
|
122 |
+
save_to_history("πΌοΈ Image", filename, frame)
|
123 |
+
except queue.Empty:
|
124 |
+
st.error(f"π¨ No frame from Cam {i} yet!")
|
125 |
+
try:
|
126 |
+
frame = q.get_nowait()
|
127 |
+
placeholder.image(frame, caption=f"Live Cam {i}", use_container_width=True)
|
128 |
+
except queue.Empty:
|
129 |
+
placeholder.write(f"π· Waiting for Cam {i}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
|
131 |
# π Upload zone like a media drop party!
|
132 |
st.header("π₯π Drop Zone")
|
|
|
134 |
if uploaded_files:
|
135 |
for uploaded_file in uploaded_files:
|
136 |
file_path = f"uploaded_{uploaded_file.name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
|
137 |
+
img = Image.open(uploaded_file)
|
138 |
+
img_array = np.array(img)
|
139 |
+
save_to_history("πΌοΈ Image", file_path, img_array)
|
140 |
+
st.image(img, caption=uploaded_file.name, use_container_width=True)
|
141 |
|
142 |
# πΌοΈ Gallery like a media circus!
|
143 |
st.header("πͺ Snap Show")
|
|
|
164 |
df = pd.DataFrame(st.session_state['file_history'])
|
165 |
st.dataframe(df)
|
166 |
else:
|
167 |
+
st.write("π³οΈ Nothing snapped yet!")
|
168 |
+
|
169 |
+
# Cleanup on app exit (not typically needed in Streamlit, but good practice)
|
170 |
+
def cleanup():
|
171 |
+
for thread in threads:
|
172 |
+
thread.stop()
|
173 |
+
for thread in threads:
|
174 |
+
thread.join()
|
175 |
+
|
176 |
+
import atexit
|
177 |
+
atexit.register(cleanup)
|