Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -17,156 +17,151 @@ import uuid
|
|
| 17 |
import pandas as pd
|
| 18 |
|
| 19 |
# ======================
|
| 20 |
-
#
|
| 21 |
# ======================
|
| 22 |
|
| 23 |
@st.cache_resource
|
| 24 |
def load_smoke_pipeline():
|
| 25 |
-
"""
|
| 26 |
return pipeline("image-classification", model="ccclllwww/smoker_cls_base_V9", use_fast=True)
|
| 27 |
|
| 28 |
@st.cache_resource
|
| 29 |
def load_gender_pipeline():
|
| 30 |
-
"""
|
| 31 |
return pipeline("image-classification", model="rizvandwiki/gender-classification-2", use_fast=True)
|
| 32 |
|
| 33 |
@st.cache_resource
|
| 34 |
def load_age_pipeline():
|
| 35 |
-
"""
|
| 36 |
return pipeline("image-classification", model="akashmaggon/vit-base-age-classification", use_fast=True)
|
| 37 |
|
| 38 |
-
#
|
| 39 |
smoke_pipeline = load_smoke_pipeline()
|
| 40 |
gender_pipeline = load_gender_pipeline()
|
| 41 |
age_pipeline = load_age_pipeline()
|
| 42 |
|
| 43 |
# ======================
|
| 44 |
-
#
|
| 45 |
# ======================
|
| 46 |
-
# Find your Account SID and Auth Token at twilio.com/console
|
| 47 |
-
# and set the environment variables. See http://twil.io/secure
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
token =
|
| 54 |
|
| 55 |
# ======================
|
| 56 |
-
#
|
| 57 |
# ======================
|
| 58 |
|
| 59 |
@st.cache_resource
|
| 60 |
-
def
|
| 61 |
-
"""
|
| 62 |
-
键为文件名(不带扩展名),值为音频字节数据。"""
|
| 63 |
audio_dir = "audio"
|
|
|
|
|
|
|
|
|
|
| 64 |
audio_files = [f for f in os.listdir(audio_dir) if f.endswith(".wav")]
|
| 65 |
audio_dict = {}
|
| 66 |
for audio_file in audio_files:
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
audio_bytes = af.read()
|
| 70 |
-
# 去掉扩展名作为键
|
| 71 |
-
key = os.path.splitext(audio_file)[0]
|
| 72 |
-
audio_dict[key] = audio_bytes
|
| 73 |
return audio_dict
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
audio_data =
|
| 77 |
|
| 78 |
# ======================
|
| 79 |
-
#
|
| 80 |
# ======================
|
| 81 |
|
| 82 |
-
def
|
|
|
|
| 83 |
try:
|
| 84 |
output = smoke_pipeline(image)
|
| 85 |
-
|
| 86 |
-
return status
|
| 87 |
except Exception as e:
|
| 88 |
-
st.error(f"
|
| 89 |
st.stop()
|
| 90 |
-
|
| 91 |
-
def
|
|
|
|
| 92 |
try:
|
| 93 |
output = gender_pipeline(image)
|
| 94 |
-
|
| 95 |
-
return status
|
| 96 |
except Exception as e:
|
| 97 |
-
st.error(f"
|
| 98 |
st.stop()
|
| 99 |
-
|
| 100 |
-
def
|
|
|
|
| 101 |
try:
|
| 102 |
output = age_pipeline(image)
|
| 103 |
-
|
| 104 |
-
return status
|
| 105 |
except Exception as e:
|
| 106 |
-
st.error(f"
|
| 107 |
st.stop()
|
| 108 |
-
|
| 109 |
# ======================
|
| 110 |
-
#
|
| 111 |
# ======================
|
| 112 |
|
| 113 |
@st.cache_data(show_spinner=False, max_entries=3)
|
| 114 |
-
def
|
| 115 |
-
"""
|
| 116 |
try:
|
| 117 |
output = smoke_pipeline(image)
|
| 118 |
-
|
| 119 |
-
return status
|
| 120 |
except Exception as e:
|
| 121 |
-
st.error(f"
|
| 122 |
st.stop()
|
| 123 |
|
| 124 |
@st.cache_data(show_spinner=False, max_entries=3)
|
| 125 |
-
def
|
| 126 |
-
"""
|
| 127 |
try:
|
| 128 |
output = gender_pipeline(image)
|
| 129 |
-
|
| 130 |
-
return status
|
| 131 |
except Exception as e:
|
| 132 |
-
st.error(f"
|
| 133 |
st.stop()
|
| 134 |
|
| 135 |
@st.cache_data(show_spinner=False, max_entries=3)
|
| 136 |
-
def
|
| 137 |
-
"""
|
| 138 |
try:
|
| 139 |
output = age_pipeline(image)
|
| 140 |
-
|
| 141 |
-
return age_range
|
| 142 |
except Exception as e:
|
| 143 |
-
st.error(f"
|
| 144 |
st.stop()
|
| 145 |
|
| 146 |
# ======================
|
| 147 |
-
#
|
| 148 |
# ======================
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
"""
|
| 153 |
-
利用自定义 HTML 和 JavaScript 播放音频。
|
| 154 |
-
将二进制音频数据转换为 Base64 后嵌入 audio 标签,
|
| 155 |
-
并用 JS 在页面加载后模拟点击进行播放。
|
| 156 |
-
"""
|
| 157 |
audio_base64 = base64.b64encode(audio_bytes).decode("utf-8")
|
|
|
|
| 158 |
html_content = f"""
|
| 159 |
-
<audio id="
|
| 160 |
<source src="data:audio/wav;base64,{audio_base64}" type="audio/wav">
|
| 161 |
Your browser does not support the audio element.
|
| 162 |
</audio>
|
| 163 |
<script type="text/javascript">
|
| 164 |
window.addEventListener('DOMContentLoaded', function() {{
|
| 165 |
setTimeout(function() {{
|
| 166 |
-
var audioElement = document.getElementById("
|
| 167 |
if (audioElement) {{
|
| 168 |
audioElement.play().catch(function(e) {{
|
| 169 |
-
console.log("
|
| 170 |
}});
|
| 171 |
}}
|
| 172 |
}}, 1000);
|
|
@@ -176,213 +171,187 @@ def play_audio_via_js(audio_bytes):
|
|
| 176 |
st.components.v1.html(html_content, height=150)
|
| 177 |
|
| 178 |
# ======================
|
| 179 |
-
#
|
| 180 |
# ======================
|
| 181 |
|
| 182 |
class VideoTransformer(VideoTransformerBase):
|
| 183 |
def __init__(self):
|
| 184 |
-
self.snapshots = []
|
| 185 |
-
self.last_capture_time = time.time()
|
| 186 |
-
self.capture_interval = 1 #
|
|
|
|
| 187 |
|
| 188 |
def transform(self, frame):
|
| 189 |
-
"""
|
| 190 |
img = frame.to_ndarray(format="bgr24")
|
| 191 |
current_time = time.time()
|
| 192 |
-
|
| 193 |
-
|
| 194 |
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 195 |
self.snapshots.append(Image.fromarray(img_rgb))
|
| 196 |
self.last_capture_time = current_time
|
| 197 |
-
st.write(f"
|
| 198 |
-
return img
|
| 199 |
|
| 200 |
# ======================
|
| 201 |
# Cover Page
|
| 202 |
# ======================
|
| 203 |
|
| 204 |
def cover_page():
|
| 205 |
-
"""Display
|
| 206 |
-
st.title("Smoking Detection System")
|
| 207 |
-
|
| 208 |
-
st.header("Project Overview")
|
| 209 |
-
st.write("""
|
| 210 |
-
The Smoking Detection System is a Streamlit-based web application designed to detect smoking behavior
|
| 211 |
-
in images or real-time video streams. It leverages advanced machine learning models to classify images
|
| 212 |
-
for smoking activity, gender, and age range. The system is structured to provide both static image analysis
|
| 213 |
-
and real-time video processing, with audio feedback for detected smoking incidents.
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
**Significance**: The application promotes public health by enabling automated monitoring of smoking
|
| 220 |
-
activities, potentially aiding in the enforcement of smoking regulations and raising awareness about
|
| 221 |
-
smoking prevalence across different demographics.
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
- **
|
| 226 |
-
- **
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
| 228 |
""")
|
| 229 |
|
| 230 |
-
st.
|
| 231 |
-
st.
|
| 232 |
-
1. **
|
| 233 |
-
- **Cover Page**: View this
|
| 234 |
-
- **Photo Detection**: Upload
|
| 235 |
-
- **Real-Time Video Detection**:
|
| 236 |
2. **Photo Detection**:
|
| 237 |
-
-
|
| 238 |
-
- The system
|
| 239 |
-
gender and age, and play an audio alert based on the results.
|
| 240 |
3. **Real-Time Video Detection**:
|
| 241 |
-
-
|
| 242 |
-
-
|
| 243 |
-
|
| 244 |
-
-
|
| 245 |
-
|
| 246 |
-
- Ensure the 'audio' directory contains .wav files named in the format '<age_range> <gender>.wav'
|
| 247 |
-
(e.g., '10-19 male.wav') for audio feedback.
|
| 248 |
-
- Set up Twilio environment variables (TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN) for WebRTC.
|
| 249 |
""")
|
|
|
|
|
|
|
|
|
|
| 250 |
|
| 251 |
# ======================
|
| 252 |
-
#
|
| 253 |
# ======================
|
| 254 |
|
| 255 |
def photo_detection_page():
|
|
|
|
| 256 |
audio_placeholder = st.empty()
|
| 257 |
-
st.title("
|
| 258 |
-
st.
|
| 259 |
-
|
| 260 |
-
# 提供上传和摄像头选项
|
| 261 |
-
option = st.radio("选择输入方式", ["上传图片", "使用摄像头拍摄"])
|
| 262 |
|
|
|
|
|
|
|
| 263 |
image = None
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
| 267 |
image = Image.open(uploaded_file)
|
| 268 |
-
st.image(image, caption="
|
| 269 |
else:
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
camera_file
|
| 273 |
-
if camera_file is not None:
|
| 274 |
image = Image.open(camera_file)
|
| 275 |
-
st.image(image, caption="
|
| 276 |
-
|
| 277 |
-
if image
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
st.write(smoke_result)
|
| 283 |
-
|
| 284 |
if smoke_result.lower() == "smoking":
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
st.
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
age_result = age_detection(image)
|
| 294 |
-
st.success("The age result is:")
|
| 295 |
-
st.write(age_result)
|
| 296 |
-
|
| 297 |
audio_placeholder.empty()
|
| 298 |
audio_key = f"{age_result} {gender_result.lower()}"
|
| 299 |
if audio_key in audio_data:
|
| 300 |
-
|
| 301 |
-
play_audio_via_js(audio_bytes)
|
| 302 |
else:
|
| 303 |
-
st.error(f"
|
| 304 |
|
| 305 |
# ======================
|
| 306 |
-
#
|
| 307 |
# ======================
|
| 308 |
|
| 309 |
def real_time_detection_page():
|
| 310 |
-
|
| 311 |
-
st.
|
|
|
|
| 312 |
|
| 313 |
-
#
|
| 314 |
if 'detection_results' not in st.session_state:
|
| 315 |
st.session_state.detection_results = []
|
| 316 |
|
| 317 |
-
#
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
#
|
| 328 |
-
ctx = webrtc_streamer(
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
|
|
|
| 332 |
|
| 333 |
capture_target = 5
|
| 334 |
|
| 335 |
-
if ctx.video_transformer
|
| 336 |
-
|
| 337 |
-
detection_info_placeholder.info("开始侦测")
|
| 338 |
|
| 339 |
while True:
|
| 340 |
snapshots = ctx.video_transformer.snapshots
|
| 341 |
|
| 342 |
if len(snapshots) < capture_target:
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
capture_progress_placeholder.progress(progress_value)
|
| 346 |
else:
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
classification_progress = classification_progress_placeholder.progress(0)
|
| 354 |
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
smoke_results.append(smoking_classification(img))
|
| 358 |
smoking_count = sum(1 for result in smoke_results if result.lower() == "smoking")
|
| 359 |
-
|
| 360 |
|
| 361 |
if smoking_count > 2:
|
| 362 |
-
gender_results = []
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
age_results = []
|
| 368 |
-
for idx, img in enumerate(snapshots):
|
| 369 |
-
age_results.append(age_classification(img))
|
| 370 |
-
classification_progress.progress(100)
|
| 371 |
-
classification_text_placeholder.text("分类进度: 分类完成!")
|
| 372 |
|
|
|
|
| 373 |
most_common_gender = Counter(gender_results).most_common(1)[0][0]
|
| 374 |
most_common_age = Counter(age_results).most_common(1)[0][0]
|
| 375 |
|
| 376 |
-
#
|
| 377 |
-
smoking_image =
|
| 378 |
-
for idx, label in enumerate(smoke_results):
|
| 379 |
-
if label.lower() == "smoking":
|
| 380 |
-
smoking_image = snapshots[idx]
|
| 381 |
-
break
|
| 382 |
-
if smoking_image is None:
|
| 383 |
-
smoking_image = snapshots[0]
|
| 384 |
|
| 385 |
-
#
|
| 386 |
st.session_state.detection_results.append({
|
| 387 |
"Timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 388 |
"Snapshot": smoking_image,
|
|
@@ -391,7 +360,7 @@ def real_time_detection_page():
|
|
| 391 |
"Smoking Count": smoking_count
|
| 392 |
})
|
| 393 |
|
| 394 |
-
#
|
| 395 |
df = pd.DataFrame([
|
| 396 |
{
|
| 397 |
"Timestamp": result["Timestamp"],
|
|
@@ -400,28 +369,26 @@ def real_time_detection_page():
|
|
| 400 |
"Smoking Count": result["Smoking Count"]
|
| 401 |
} for result in st.session_state.detection_results
|
| 402 |
])
|
| 403 |
-
|
| 404 |
|
| 405 |
-
#
|
| 406 |
-
|
| 407 |
|
| 408 |
-
#
|
| 409 |
-
|
| 410 |
audio_key = f"{most_common_age} {most_common_gender.lower()}"
|
| 411 |
if audio_key in audio_data:
|
| 412 |
-
|
| 413 |
-
play_audio_via_js(audio_bytes)
|
| 414 |
else:
|
| 415 |
-
st.error(f"
|
| 416 |
else:
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
classification_text_placeholder.text("分类进度: 分类完成!")
|
| 422 |
classification_progress.progress(100)
|
| 423 |
|
| 424 |
-
#
|
| 425 |
if st.session_state.detection_results:
|
| 426 |
df = pd.DataFrame([
|
| 427 |
{
|
|
@@ -431,31 +398,33 @@ def real_time_detection_page():
|
|
| 431 |
"Smoking Count": result["Smoking Count"]
|
| 432 |
} for result in st.session_state.detection_results
|
| 433 |
])
|
| 434 |
-
|
| 435 |
|
|
|
|
| 436 |
time.sleep(5)
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
detection_info_placeholder.info("开始侦测")
|
| 442 |
ctx.video_transformer.snapshots = []
|
| 443 |
ctx.video_transformer.last_capture_time = time.time()
|
|
|
|
| 444 |
time.sleep(0.1)
|
| 445 |
|
| 446 |
# ======================
|
| 447 |
-
#
|
| 448 |
# ======================
|
| 449 |
|
| 450 |
def main():
|
| 451 |
-
|
| 452 |
-
|
|
|
|
| 453 |
|
| 454 |
-
if page == "
|
| 455 |
cover_page()
|
| 456 |
-
|
| 457 |
photo_detection_page()
|
| 458 |
-
|
| 459 |
real_time_detection_page()
|
| 460 |
|
| 461 |
if __name__ == "__main__":
|
|
|
|
| 17 |
import pandas as pd
|
| 18 |
|
| 19 |
# ======================
|
| 20 |
+
# Model Loading Functions
|
| 21 |
# ======================
|
| 22 |
|
| 23 |
@st.cache_resource
|
| 24 |
def load_smoke_pipeline():
|
| 25 |
+
"""Initialize and cache the smoking image classification pipeline."""
|
| 26 |
return pipeline("image-classification", model="ccclllwww/smoker_cls_base_V9", use_fast=True)
|
| 27 |
|
| 28 |
@st.cache_resource
|
| 29 |
def load_gender_pipeline():
|
| 30 |
+
"""Initialize and cache the gender image classification pipeline."""
|
| 31 |
return pipeline("image-classification", model="rizvandwiki/gender-classification-2", use_fast=True)
|
| 32 |
|
| 33 |
@st.cache_resource
|
| 34 |
def load_age_pipeline():
|
| 35 |
+
"""Initialize and cache the age image classification pipeline."""
|
| 36 |
return pipeline("image-classification", model="akashmaggon/vit-base-age-classification", use_fast=True)
|
| 37 |
|
| 38 |
+
# Preload all models
|
| 39 |
smoke_pipeline = load_smoke_pipeline()
|
| 40 |
gender_pipeline = load_gender_pipeline()
|
| 41 |
age_pipeline = load_age_pipeline()
|
| 42 |
|
| 43 |
# ======================
|
| 44 |
+
# Twilio Configuration
|
| 45 |
# ======================
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
def initialize_twilio_client():
|
| 48 |
+
"""Initialize Twilio client using environment variables."""
|
| 49 |
+
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
|
| 50 |
+
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
|
| 51 |
+
if not account_sid or not auth_token:
|
| 52 |
+
st.error("Twilio credentials not found in environment variables.")
|
| 53 |
+
st.stop()
|
| 54 |
+
client = Client(account_sid, auth_token)
|
| 55 |
+
return client.tokens.create()
|
| 56 |
|
| 57 |
+
token = initialize_twilio_client()
|
| 58 |
|
| 59 |
# ======================
|
| 60 |
+
# Audio Loading Function
|
| 61 |
# ======================
|
| 62 |
|
| 63 |
@st.cache_resource
|
| 64 |
+
def load_audio_files():
|
| 65 |
+
"""Load all .wav files from the audio directory into a dictionary."""
|
|
|
|
| 66 |
audio_dir = "audio"
|
| 67 |
+
if not os.path.exists(audio_dir):
|
| 68 |
+
st.error(f"Audio directory '{audio_dir}' not found.")
|
| 69 |
+
st.stop()
|
| 70 |
audio_files = [f for f in os.listdir(audio_dir) if f.endswith(".wav")]
|
| 71 |
audio_dict = {}
|
| 72 |
for audio_file in audio_files:
|
| 73 |
+
with open(os.path.join(audio_dir, audio_file), "rb") as file:
|
| 74 |
+
audio_dict[os.path.splitext(audio_file)[0]] = file.read()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
return audio_dict
|
| 76 |
|
| 77 |
+
# Load audio files at startup
|
| 78 |
+
audio_data = load_audio_files()
|
| 79 |
|
| 80 |
# ======================
|
| 81 |
+
# Image Processing Functions
|
| 82 |
# ======================
|
| 83 |
|
| 84 |
+
def detect_smoking(image: Image.Image) -> str:
|
| 85 |
+
"""Classify an image for smoking activity."""
|
| 86 |
try:
|
| 87 |
output = smoke_pipeline(image)
|
| 88 |
+
return output[0]["label"]
|
|
|
|
| 89 |
except Exception as e:
|
| 90 |
+
st.error(f"Image processing error: {str(e)}")
|
| 91 |
st.stop()
|
| 92 |
+
|
| 93 |
+
def detect_gender(image: Image.Image) -> str:
|
| 94 |
+
"""Classify an image for gender."""
|
| 95 |
try:
|
| 96 |
output = gender_pipeline(image)
|
| 97 |
+
return output[0]["label"]
|
|
|
|
| 98 |
except Exception as e:
|
| 99 |
+
st.error(f"Image processing error: {str(e)}")
|
| 100 |
st.stop()
|
| 101 |
+
|
| 102 |
+
def detect_age(image: Image.Image) -> str:
|
| 103 |
+
"""Classify an image for age range."""
|
| 104 |
try:
|
| 105 |
output = age_pipeline(image)
|
| 106 |
+
return output[0]["label"]
|
|
|
|
| 107 |
except Exception as e:
|
| 108 |
+
st.error(f"Image processing error: {str(e)}")
|
| 109 |
st.stop()
|
| 110 |
+
|
| 111 |
# ======================
|
| 112 |
+
# Real-Time Classification Functions
|
| 113 |
# ======================
|
| 114 |
|
| 115 |
@st.cache_data(show_spinner=False, max_entries=3)
|
| 116 |
+
def classify_smoking(image: Image.Image) -> str:
|
| 117 |
+
"""Classify an image for smoking and return the label with highest confidence."""
|
| 118 |
try:
|
| 119 |
output = smoke_pipeline(image)
|
| 120 |
+
return max(output, key=lambda x: x["score"])["label"]
|
|
|
|
| 121 |
except Exception as e:
|
| 122 |
+
st.error(f"Image processing error: {str(e)}")
|
| 123 |
st.stop()
|
| 124 |
|
| 125 |
@st.cache_data(show_spinner=False, max_entries=3)
|
| 126 |
+
def classify_gender(image: Image.Image) -> str:
|
| 127 |
+
"""Classify an image for gender and return the label with highest confidence."""
|
| 128 |
try:
|
| 129 |
output = gender_pipeline(image)
|
| 130 |
+
return max(output, key=lambda x: x["score"])["label"]
|
|
|
|
| 131 |
except Exception as e:
|
| 132 |
+
st.error(f"Image processing error: {str(e)}")
|
| 133 |
st.stop()
|
| 134 |
|
| 135 |
@st.cache_data(show_spinner=False, max_entries=3)
|
| 136 |
+
def classify_age(image: Image.Image) -> str:
|
| 137 |
+
"""Classify an image for age range and return the label with highest confidence."""
|
| 138 |
try:
|
| 139 |
output = age_pipeline(image)
|
| 140 |
+
return max(output, key=lambda x: x["score"])["label"]
|
|
|
|
| 141 |
except Exception as e:
|
| 142 |
+
st.error(f"Image processing error: {str(e)}")
|
| 143 |
st.stop()
|
| 144 |
|
| 145 |
# ======================
|
| 146 |
+
# Audio Playback Function
|
| 147 |
# ======================
|
| 148 |
|
| 149 |
+
def play_audio(audio_bytes: bytes):
|
| 150 |
+
"""Play audio using HTML and JavaScript with Base64-encoded audio data."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
audio_base64 = base64.b64encode(audio_bytes).decode("utf-8")
|
| 152 |
+
audio_id = f"audio_player_{uuid.uuid4()}"
|
| 153 |
html_content = f"""
|
| 154 |
+
<audio id="{audio_id}" controls style="width: 100%;">
|
| 155 |
<source src="data:audio/wav;base64,{audio_base64}" type="audio/wav">
|
| 156 |
Your browser does not support the audio element.
|
| 157 |
</audio>
|
| 158 |
<script type="text/javascript">
|
| 159 |
window.addEventListener('DOMContentLoaded', function() {{
|
| 160 |
setTimeout(function() {{
|
| 161 |
+
var audioElement = document.getElementById("{audio_id}");
|
| 162 |
if (audioElement) {{
|
| 163 |
audioElement.play().catch(function(e) {{
|
| 164 |
+
console.log("Playback prevented by browser:", e);
|
| 165 |
}});
|
| 166 |
}}
|
| 167 |
}}, 1000);
|
|
|
|
| 171 |
st.components.v1.html(html_content, height=150)
|
| 172 |
|
| 173 |
# ======================
|
| 174 |
+
# Video Transformer Class
|
| 175 |
# ======================
|
| 176 |
|
| 177 |
class VideoTransformer(VideoTransformerBase):
|
| 178 |
def __init__(self):
|
| 179 |
+
self.snapshots = []
|
| 180 |
+
self.last_capture_time = time.time()
|
| 181 |
+
self.capture_interval = 1 # Capture every 1 second
|
| 182 |
+
self.max_snapshots = 5
|
| 183 |
|
| 184 |
def transform(self, frame):
|
| 185 |
+
"""Process video frame and capture snapshots."""
|
| 186 |
img = frame.to_ndarray(format="bgr24")
|
| 187 |
current_time = time.time()
|
| 188 |
+
if (current_time - self.last_capture_time >= self.capture_interval and
|
| 189 |
+
len(self.snapshots) < self.max_snapshots):
|
| 190 |
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 191 |
self.snapshots.append(Image.fromarray(img_rgb))
|
| 192 |
self.last_capture_time = current_time
|
| 193 |
+
st.write(f"Captured snapshot {len(self.snapshots)}/{self.max_snapshots}")
|
| 194 |
+
return img
|
| 195 |
|
| 196 |
# ======================
|
| 197 |
# Cover Page
|
| 198 |
# ======================
|
| 199 |
|
| 200 |
def cover_page():
|
| 201 |
+
"""Display an enhanced cover page with project overview and instructions."""
|
| 202 |
+
st.title("Smoking Detection System", anchor=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
st.markdown("### Welcome to the Smoking Detection System")
|
| 205 |
+
st.markdown("""
|
| 206 |
+
This Streamlit-based application harnesses cutting-edge machine learning to detect smoking behavior in images and real-time video streams. By analyzing smoking activity, gender, and age demographics, it provides valuable insights for public health monitoring and policy enforcement.
|
| 207 |
+
""")
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
+
st.markdown("#### Project Overview")
|
| 210 |
+
st.markdown("""
|
| 211 |
+
- **Purpose**: Automatically identify smoking behavior in public or controlled environments to support compliance with no-smoking policies and facilitate behavioral studies.
|
| 212 |
+
- **Significance**: Enhances public health initiatives by enabling real-time monitoring and demographic analysis of smoking activities.
|
| 213 |
+
- **Features**:
|
| 214 |
+
- **Photo Detection**: Analyze a single image (uploaded or captured) for smoking, gender, and age.
|
| 215 |
+
- **Real-Time Video Detection**: Process webcam streams, capturing snapshots to detect smoking and demographics.
|
| 216 |
+
- **Audio Feedback**: Play alerts based on detected gender and age when smoking is confirmed.
|
| 217 |
""")
|
| 218 |
|
| 219 |
+
st.markdown("#### How to Use")
|
| 220 |
+
st.markdown("""
|
| 221 |
+
1. **Navigate**: Use the sidebar to select a page:
|
| 222 |
+
- **Cover Page**: View this overview.
|
| 223 |
+
- **Photo Detection**: Upload or capture an image for analysis.
|
| 224 |
+
- **Real-Time Video Detection**: Monitor live webcam feed.
|
| 225 |
2. **Photo Detection**:
|
| 226 |
+
- Upload an image or capture one via webcam.
|
| 227 |
+
- The system detects smoking; if detected, it analyzes gender and age, playing a corresponding audio alert.
|
|
|
|
| 228 |
3. **Real-Time Video Detection**:
|
| 229 |
+
- Captures 5 snapshots over one minute.
|
| 230 |
+
- If smoking is detected in more than 2 snapshots, it analyzes gender and age, displays results in a table, and plays an audio alert.
|
| 231 |
+
4. **Setup Requirements**:
|
| 232 |
+
- Ensure the 'audio' directory contains .wav files named as '<age_range> <gender>.wav' (e.g., '10-19 male.wav').
|
| 233 |
+
- Configure Twilio environment variables (`TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN`) for WebRTC functionality.
|
|
|
|
|
|
|
|
|
|
| 234 |
""")
|
| 235 |
+
|
| 236 |
+
st.markdown("#### Get Started")
|
| 237 |
+
st.markdown("Select a page from the sidebar to begin analyzing images or video streams.")
|
| 238 |
|
| 239 |
# ======================
|
| 240 |
+
# Photo Detection Page
|
| 241 |
# ======================
|
| 242 |
|
| 243 |
def photo_detection_page():
|
| 244 |
+
"""Handle photo detection page for smoking, gender, and age classification."""
|
| 245 |
audio_placeholder = st.empty()
|
| 246 |
+
st.title("Photo Detection", anchor=False)
|
| 247 |
+
st.markdown("Upload an image or capture a photo to detect smoking behavior. If smoking is detected, gender and age will be analyzed.")
|
|
|
|
|
|
|
|
|
|
| 248 |
|
| 249 |
+
# Image input selection
|
| 250 |
+
option = st.radio("Choose input method", ["Upload Image", "Capture with Camera"], horizontal=True)
|
| 251 |
image = None
|
| 252 |
+
|
| 253 |
+
if option == "Upload Image":
|
| 254 |
+
uploaded_file = st.file_uploader("Select an image", type=["jpg", "jpeg", "png"])
|
| 255 |
+
if uploaded_file:
|
| 256 |
image = Image.open(uploaded_file)
|
| 257 |
+
st.image(image, caption="Uploaded Image", use_container_width=True)
|
| 258 |
else:
|
| 259 |
+
enable = st.checkbox("Enable Camera")
|
| 260 |
+
camera_file = st.camera_input("Capture Photo", disabled=not enable)
|
| 261 |
+
if camera_file:
|
|
|
|
| 262 |
image = Image.open(camera_file)
|
| 263 |
+
st.image(image, caption="Captured Photo", use_container_width=True)
|
| 264 |
+
|
| 265 |
+
if image:
|
| 266 |
+
with st.spinner("Detecting smoking..."):
|
| 267 |
+
smoke_result = detect_smoking(image)
|
| 268 |
+
st.success(f"Smoking Status: {smoke_result}")
|
| 269 |
+
|
|
|
|
|
|
|
| 270 |
if smoke_result.lower() == "smoking":
|
| 271 |
+
with st.spinner("Detecting gender..."):
|
| 272 |
+
gender_result = detect_gender(image)
|
| 273 |
+
st.success(f"Gender: {gender_result}")
|
| 274 |
+
|
| 275 |
+
with st.spinner("Detecting age..."):
|
| 276 |
+
age_result = detect_age(image)
|
| 277 |
+
st.success(f"Age Range: {age_result}")
|
| 278 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
audio_placeholder.empty()
|
| 280 |
audio_key = f"{age_result} {gender_result.lower()}"
|
| 281 |
if audio_key in audio_data:
|
| 282 |
+
play_audio(audio_data[audio_key])
|
|
|
|
| 283 |
else:
|
| 284 |
+
st.error(f"Audio file not found: {audio_key}.wav")
|
| 285 |
|
| 286 |
# ======================
|
| 287 |
+
# Real-Time Detection Page
|
| 288 |
# ======================
|
| 289 |
|
| 290 |
def real_time_detection_page():
|
| 291 |
+
"""Handle real-time video detection with snapshot capture and analysis."""
|
| 292 |
+
st.title("Real-Time Video Detection", anchor=False)
|
| 293 |
+
st.markdown("Captures 5 snapshots over one minute to detect smoking. If smoking is detected in more than 2 snapshots, results include gender, age, and a snapshot in a table.")
|
| 294 |
|
| 295 |
+
# Initialize session state for detection results
|
| 296 |
if 'detection_results' not in st.session_state:
|
| 297 |
st.session_state.detection_results = []
|
| 298 |
|
| 299 |
+
# Placeholders for UI elements
|
| 300 |
+
capture_text = st.empty()
|
| 301 |
+
capture_progress = st.empty()
|
| 302 |
+
classification_text = st.empty()
|
| 303 |
+
classification_progress = st.empty()
|
| 304 |
+
detection_info = st.empty()
|
| 305 |
+
table = st.empty()
|
| 306 |
+
image_display = st.empty()
|
| 307 |
+
audio = st.empty()
|
| 308 |
+
|
| 309 |
+
# Start video stream
|
| 310 |
+
ctx = webrtc_streamer(
|
| 311 |
+
key="unique_example",
|
| 312 |
+
video_transformer_factory=VideoTransformer,
|
| 313 |
+
rtc_configuration={"iceServers": token.ice_servers}
|
| 314 |
+
)
|
| 315 |
|
| 316 |
capture_target = 5
|
| 317 |
|
| 318 |
+
if ctx.video_transformer:
|
| 319 |
+
detection_info.info("Starting detection...")
|
|
|
|
| 320 |
|
| 321 |
while True:
|
| 322 |
snapshots = ctx.video_transformer.snapshots
|
| 323 |
|
| 324 |
if len(snapshots) < capture_target:
|
| 325 |
+
capture_text.text(f"Capture Progress: {len(snapshots)}/{capture_target} snapshots")
|
| 326 |
+
capture_progress.progress(int(len(snapshots) / capture_target * 100))
|
|
|
|
| 327 |
else:
|
| 328 |
+
capture_text.text("Capture Progress: Completed!")
|
| 329 |
+
capture_progress.empty()
|
| 330 |
+
detection_info.empty()
|
| 331 |
|
| 332 |
+
classification_text.text("Classification Progress: Analyzing...")
|
| 333 |
+
classification = classification_progress.progress(0)
|
|
|
|
| 334 |
|
| 335 |
+
# Classify snapshots
|
| 336 |
+
smoke_results = [classify_smoking(img) for img in snapshots]
|
|
|
|
| 337 |
smoking_count = sum(1 for result in smoke_results if result.lower() == "smoking")
|
| 338 |
+
classification.progress(33)
|
| 339 |
|
| 340 |
if smoking_count > 2:
|
| 341 |
+
gender_results = [classify_gender(img) for img in snapshots]
|
| 342 |
+
classification.progress(66)
|
| 343 |
+
age_results = [classify_age(img) for img in snapshots]
|
| 344 |
+
classification.progress(100)
|
| 345 |
+
classification_text.text("Classification Progress: Completed!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
|
| 347 |
+
# Determine most common gender and age
|
| 348 |
most_common_gender = Counter(gender_results).most_common(1)[0][0]
|
| 349 |
most_common_age = Counter(age_results).most_common(1)[0][0]
|
| 350 |
|
| 351 |
+
# Select first smoking snapshot
|
| 352 |
+
smoking_image = next((snapshots[i] for i, label in enumerate(smoke_results) if label.lower() == "smoking"), snapshots[0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
+
# Store results
|
| 355 |
st.session_state.detection_results.append({
|
| 356 |
"Timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 357 |
"Snapshot": smoking_image,
|
|
|
|
| 360 |
"Smoking Count": smoking_count
|
| 361 |
})
|
| 362 |
|
| 363 |
+
# Update table
|
| 364 |
df = pd.DataFrame([
|
| 365 |
{
|
| 366 |
"Timestamp": result["Timestamp"],
|
|
|
|
| 369 |
"Smoking Count": result["Smoking Count"]
|
| 370 |
} for result in st.session_state.detection_results
|
| 371 |
])
|
| 372 |
+
table.dataframe(df, use_container_width=True)
|
| 373 |
|
| 374 |
+
# Display snapshot
|
| 375 |
+
image_display.image(smoking_image, caption="Detected Smoking Snapshot", use_container_width=True)
|
| 376 |
|
| 377 |
+
# Play audio
|
| 378 |
+
audio.empty()
|
| 379 |
audio_key = f"{most_common_age} {most_common_gender.lower()}"
|
| 380 |
if audio_key in audio_data:
|
| 381 |
+
play_audio(audio_data[audio_key])
|
|
|
|
| 382 |
else:
|
| 383 |
+
st.error(f"Audio file not found: {audio_key}.wav")
|
| 384 |
else:
|
| 385 |
+
st.markdown("**Smoking Status:** Not Smoking")
|
| 386 |
+
image_display.empty()
|
| 387 |
+
audio.empty()
|
| 388 |
+
classification_text.text("Classification Progress: Completed!")
|
|
|
|
| 389 |
classification_progress.progress(100)
|
| 390 |
|
| 391 |
+
# Update table if results exist
|
| 392 |
if st.session_state.detection_results:
|
| 393 |
df = pd.DataFrame([
|
| 394 |
{
|
|
|
|
| 398 |
"Smoking Count": result["Smoking Count"]
|
| 399 |
} for result in st.session_state.detection_results
|
| 400 |
])
|
| 401 |
+
table.dataframe(df, use_container_width=True)
|
| 402 |
|
| 403 |
+
# Reset for next cycle
|
| 404 |
time.sleep(5)
|
| 405 |
+
classification_progress.empty()
|
| 406 |
+
classification_text.empty()
|
| 407 |
+
capture_text.empty()
|
| 408 |
+
detection_info.info("Starting detection...")
|
|
|
|
| 409 |
ctx.video_transformer.snapshots = []
|
| 410 |
ctx.video_transformer.last_capture_time = time.time()
|
| 411 |
+
|
| 412 |
time.sleep(0.1)
|
| 413 |
|
| 414 |
# ======================
|
| 415 |
+
# Main Application
|
| 416 |
# ======================
|
| 417 |
|
| 418 |
def main():
|
| 419 |
+
"""Main function to handle page navigation."""
|
| 420 |
+
st.sidebar.title("Navigation")
|
| 421 |
+
page = st.sidebar.selectbox("Select Page", ["Cover Page", "Photo Detection", "Real-Time Video Detection"])
|
| 422 |
|
| 423 |
+
if page == "Cover Page":
|
| 424 |
cover_page()
|
| 425 |
+
elif page == "Photo Detection":
|
| 426 |
photo_detection_page()
|
| 427 |
+
elif page == "Real-Time Video Detection":
|
| 428 |
real_time_detection_page()
|
| 429 |
|
| 430 |
if __name__ == "__main__":
|