tstone87 commited on
Commit
d44cea7
·
verified ·
1 Parent(s): cac62cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -39
app.py CHANGED
@@ -17,14 +17,14 @@ st.markdown(
17
  <style>
18
  .stApp {
19
  background-color: #f5f5f5;
20
- color: #1a1a1a; /* Dark text for general content */
21
  }
22
  h1 {
23
- color: #1a1a1a; /* Darker title text */
24
  }
25
  .stTabs > div > button {
26
  background-color: #e0e0e0;
27
- color: #1a1a1a; /* Darker tab text */
28
  font-weight: bold;
29
  }
30
  .stTabs > div > button:hover {
@@ -33,7 +33,7 @@ st.markdown(
33
  }
34
  .stButton > button {
35
  background-color: #e0e0e0;
36
- color: #1a1a1a; /* Darker button text */
37
  font-weight: bold;
38
  }
39
  .stButton > button:hover {
@@ -103,13 +103,13 @@ with tabs[1]:
103
  col1, col2 = st.columns([1, 1])
104
  with col1:
105
  st.markdown("**Webcam Feed**")
106
- st.write("Provide a webcam URL to check snapshots for hazards every 30 seconds.")
107
  webcam_url = st.text_input("Webcam URL", "http://<your_webcam_ip>/current.jpg", label_visibility="collapsed")
108
  confidence = st.slider("Detection Threshold", 0.25, 1.0, 0.4, key="webcam_conf")
 
109
  start = st.button("Begin Monitoring", key="webcam_start")
110
  stop = st.button("Stop Monitoring", key="webcam_stop")
111
 
112
- # Handle monitoring state
113
  if start:
114
  st.session_state.monitoring = True
115
  st.session_state.current_webcam_url = webcam_url
@@ -119,37 +119,55 @@ with tabs[1]:
119
 
120
  with col2:
121
  if st.session_state.monitoring and st.session_state.current_webcam_url:
122
- image_placeholder = st.empty()
 
123
  timer_placeholder = st.empty()
124
- refresh_interval = 30 # Refresh every 30 seconds
125
- while True:
126
- start_time = time.time()
 
 
 
127
  try:
128
- response = requests.get(st.session_state.current_webcam_url, timeout=5)
129
- if response.status_code != 200:
130
- st.error(f"Fetch failed: HTTP {response.status_code}")
131
- break
132
- image_array = np.asarray(bytearray(response.content), dtype=np.uint8)
133
- frame = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
134
- if frame is None:
135
- st.error("Image decoding failed.")
136
- break
 
 
 
 
 
 
 
 
 
137
  results = model.predict(frame, conf=confidence)
138
  detected_frame = results[0].plot()[:, :, ::-1]
139
- image_placeholder.image(detected_frame, use_column_width=True)
 
 
140
  elapsed = time.time() - start_time
141
- remaining = max(0, refresh_interval - elapsed)
142
  timer_placeholder.write(f"Next scan: {int(remaining)}s")
143
- while remaining > 0:
144
- time.sleep(1)
145
- elapsed = time.time() - start_time
146
- remaining = max(0, refresh_interval - elapsed)
147
- timer_placeholder.write(f"Next scan: {int(remaining)}s")
148
- st.experimental_rerun()
149
  except Exception as e:
150
- st.error(f"Error: {e}")
151
  st.session_state.monitoring = False
152
  break
 
 
 
153
 
154
  # Tab 3: YouTube
155
  with tabs[2]:
@@ -159,30 +177,44 @@ with tabs[2]:
159
  st.write("Enter a live YouTube URL to auto-analyze the stream.")
160
  youtube_url = st.text_input("YouTube URL", "https://www.youtube.com/watch?v=<id>", label_visibility="collapsed")
161
  confidence = st.slider("Detection Threshold", 0.25, 1.0, 0.4, key="yt_conf")
 
 
 
 
 
 
 
 
 
 
 
162
  with col2:
163
- if youtube_url and youtube_url != "https://www.youtube.com/watch?v=<id>":
164
- st.write("Analyzing live stream...")
 
165
  try:
 
166
  streams = streamlink.streams(youtube_url)
167
  if not streams:
168
- st.error("No streams found. Check the URL.")
169
  else:
170
- stream_url = streams["best"].to_url()
171
  cap = cv2.VideoCapture(stream_url)
172
  if not cap.isOpened():
173
- st.error("Unable to open stream.")
174
  else:
175
- frame_placeholder = st.empty()
176
- while cap.isOpened():
177
  ret, frame = cap.read()
178
  if not ret:
179
- st.error("Stream interrupted.")
180
  break
181
  results = model.predict(frame, conf=confidence)
182
  detected_frame = results[0].plot()[:, :, ::-1]
183
  frame_placeholder.image(detected_frame, use_column_width=True)
184
- st.write(f"Objects detected: {len(results[0].boxes)}")
185
- time.sleep(1) # Check every second
186
  cap.release()
187
  except Exception as e:
188
- st.error(f"Error: {e}")
 
 
17
  <style>
18
  .stApp {
19
  background-color: #f5f5f5;
20
+ color: #1a1a1a;
21
  }
22
  h1 {
23
+ color: #1a1a1a;
24
  }
25
  .stTabs > div > button {
26
  background-color: #e0e0e0;
27
+ color: #1a1a1a;
28
  font-weight: bold;
29
  }
30
  .stTabs > div > button:hover {
 
33
  }
34
  .stButton > button {
35
  background-color: #e0e0e0;
36
+ color: #1a1a1a;
37
  font-weight: bold;
38
  }
39
  .stButton > button:hover {
 
103
  col1, col2 = st.columns([1, 1])
104
  with col1:
105
  st.markdown("**Webcam Feed**")
106
+ st.write("Provide a webcam URL (image or video stream) to monitor for hazards.")
107
  webcam_url = st.text_input("Webcam URL", "http://<your_webcam_ip>/current.jpg", label_visibility="collapsed")
108
  confidence = st.slider("Detection Threshold", 0.25, 1.0, 0.4, key="webcam_conf")
109
+ refresh_rate = st.slider("Refresh Rate (seconds)", 1, 60, 30, key="webcam_rate")
110
  start = st.button("Begin Monitoring", key="webcam_start")
111
  stop = st.button("Stop Monitoring", key="webcam_stop")
112
 
 
113
  if start:
114
  st.session_state.monitoring = True
115
  st.session_state.current_webcam_url = webcam_url
 
119
 
120
  with col2:
121
  if st.session_state.monitoring and st.session_state.current_webcam_url:
122
+ frame_placeholder = st.empty()
123
+ status_placeholder = st.empty()
124
  timer_placeholder = st.empty()
125
+
126
+ # Try video stream first
127
+ cap = cv2.VideoCapture(webcam_url)
128
+ is_video_stream = cap.isOpened()
129
+
130
+ while st.session_state.monitoring:
131
  try:
132
+ start_time = time.time()
133
+ if is_video_stream:
134
+ ret, frame = cap.read()
135
+ if not ret:
136
+ status_placeholder.error("Video stream interrupted.")
137
+ break
138
+ else:
139
+ # Fallback to image-based webcam
140
+ response = requests.get(webcam_url, timeout=5)
141
+ if response.status_code != 200:
142
+ status_placeholder.error(f"Fetch failed: HTTP {response.status_code}")
143
+ break
144
+ image_array = np.asarray(bytearray(response.content), dtype=np.uint8)
145
+ frame = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
146
+ if frame is None:
147
+ status_placeholder.error("Image decoding failed.")
148
+ break
149
+
150
  results = model.predict(frame, conf=confidence)
151
  detected_frame = results[0].plot()[:, :, ::-1]
152
+ frame_placeholder.image(detected_frame, use_column_width=True)
153
+ status_placeholder.write(f"Objects detected: {len(results[0].boxes)}")
154
+
155
  elapsed = time.time() - start_time
156
+ remaining = max(0, refresh_rate - elapsed)
157
  timer_placeholder.write(f"Next scan: {int(remaining)}s")
158
+
159
+ if not is_video_stream:
160
+ time.sleep(remaining)
161
+ else:
162
+ time.sleep(0.1) # Faster update for video streams
163
+
164
  except Exception as e:
165
+ status_placeholder.error(f"Error: {e}")
166
  st.session_state.monitoring = False
167
  break
168
+
169
+ if is_video_stream:
170
+ cap.release()
171
 
172
  # Tab 3: YouTube
173
  with tabs[2]:
 
177
  st.write("Enter a live YouTube URL to auto-analyze the stream.")
178
  youtube_url = st.text_input("YouTube URL", "https://www.youtube.com/watch?v=<id>", label_visibility="collapsed")
179
  confidence = st.slider("Detection Threshold", 0.25, 1.0, 0.4, key="yt_conf")
180
+ start_yt = st.button("Start Analysis", key="yt_start")
181
+ stop_yt = st.button("Stop Analysis", key="yt_stop")
182
+
183
+ if 'yt_monitoring' not in st.session_state:
184
+ st.session_state.yt_monitoring = False
185
+
186
+ if start_yt:
187
+ st.session_state.yt_monitoring = True
188
+ if stop_yt:
189
+ st.session_state.yt_monitoring = False
190
+
191
  with col2:
192
+ if st.session_state.yt_monitoring and youtube_url and youtube_url != "https://www.youtube.com/watch?v=<id>":
193
+ status_placeholder = st.empty()
194
+ frame_placeholder = st.empty()
195
  try:
196
+ status_placeholder.write("Initializing stream...")
197
  streams = streamlink.streams(youtube_url)
198
  if not streams:
199
+ status_placeholder.error("No streams found. Check if the URL is a live stream.")
200
  else:
201
+ stream_url = streams["best"].url
202
  cap = cv2.VideoCapture(stream_url)
203
  if not cap.isOpened():
204
+ status_placeholder.error("Unable to open stream.")
205
  else:
206
+ status_placeholder.write("Analyzing live stream...")
207
+ while st.session_state.yt_monitoring and cap.isOpened():
208
  ret, frame = cap.read()
209
  if not ret:
210
+ status_placeholder.error("Stream interrupted.")
211
  break
212
  results = model.predict(frame, conf=confidence)
213
  detected_frame = results[0].plot()[:, :, ::-1]
214
  frame_placeholder.image(detected_frame, use_column_width=True)
215
+ status_placeholder.write(f"Objects detected: {len(results[0].boxes)}")
216
+ time.sleep(0.1) # Control frame rate
217
  cap.release()
218
  except Exception as e:
219
+ status_placeholder.error(f"Error: {e}")
220
+ st.session_state.yt_monitoring = False