awacke1 commited on
Commit
82d8aa2
Β·
verified Β·
1 Parent(s): 30111a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -54
app.py CHANGED
@@ -7,24 +7,59 @@ import time
7
  from PIL import Image
8
  from io import BytesIO
9
  import base64
10
-
11
- # 🌟πŸ”₯ Initialize global state for threading safety!
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 'cam0_file' not in st.session_state:
19
- st.session_state['cam0_file'] = None
20
- if 'cam1_file' not in st.session_state:
21
- st.session_state['cam1_file'] = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- with open(file_path, "wb") as f:
27
- f.write(img_data)
 
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
- global AUTO_CAPTURE_RUNNING, SELECTED_CAM_IMG
37
- if AUTO_CAPTURE_RUNNING and SELECTED_CAM_IMG:
38
- filename = f"auto_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
39
- with open(filename, "wb") as f:
40
- f.write(SELECTED_CAM_IMG)
41
- st.session_state['file_history'].append({
42
- "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
43
- "Type": "πŸ–ΌοΈ Image",
44
- "Path": filename
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
- global AUTO_CAPTURE_RUNNING
54
- AUTO_CAPTURE_RUNNING = True
55
- auto_capture()
56
  if st.button("⏹️ Stop Auto-Snap"):
57
- global AUTO_CAPTURE_RUNNING
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("πŸ“Έ Streamlit Snap Craze")
 
 
 
 
 
 
 
 
 
73
 
74
  # πŸ“ΈπŸ“· Camera snap zone!
75
  st.header("πŸ“ΈπŸŽ₯ Snap Zone")
76
  cols = st.columns(2)
77
- with cols[0]:
78
- cam0_img = st.camera_input("πŸ“· Camera 0", key="cam0")
79
- if cam0_img and camera_choice == "Camera 0":
80
- filename = f"cam0_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
81
- if st.session_state['cam0_file'] and os.path.exists(st.session_state['cam0_file']):
82
- os.remove(st.session_state['cam0_file'])
83
- save_to_history("πŸ–ΌοΈ Image", filename, cam0_img.getvalue())
84
- st.session_state['cam0_file'] = filename
85
- global SELECTED_CAM_IMG
86
- SELECTED_CAM_IMG = cam0_img.getvalue()
87
- st.image(Image.open(BytesIO(cam0_img.getvalue())), caption="Camera 0 Snap", use_container_width=True)
88
- with cols[1]:
89
- cam1_img = st.camera_input("πŸ“· Camera 1", key="cam1")
90
- if cam1_img and camera_choice == "Camera 1":
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
- save_to_history("πŸ–ΌοΈ Image", file_path, uploaded_file.getvalue())
107
- st.image(Image.open(BytesIO(uploaded_file.getvalue())), caption=uploaded_file.name, use_container_width=True)
 
 
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)