Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,284 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
# Find your Account SID and Auth Token at twilio.com/console
|
| 6 |
# and set the environment variables. See http://twil.io/secure
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
#client = Client(account_sid, auth_token)
|
| 11 |
-
#token = client.tokens.create()
|
| 12 |
-
|
| 13 |
-
webrtc_streamer(
|
| 14 |
-
key="sample",
|
| 15 |
-
# ...
|
| 16 |
-
rtc_configuration=
|
| 17 |
-
{
|
| 18 |
-
"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]
|
| 19 |
-
}
|
| 20 |
-
# ...
|
| 21 |
-
)
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import cv2
|
| 3 |
+
import time
|
| 4 |
+
from streamlit_webrtc import VideoTransformerBase, webrtc_streamer
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
import os
|
| 8 |
+
from twilio.rest import Client
|
| 9 |
+
from collections import Counter
|
| 10 |
+
import base64
|
| 11 |
|
| 12 |
+
|
| 13 |
+
# ======================
|
| 14 |
+
# 模型加载函数(缓存)
|
| 15 |
+
# ======================
|
| 16 |
+
|
| 17 |
+
@st.cache_resource
|
| 18 |
+
def load_smoke_pipeline():
|
| 19 |
+
"""初始化并缓存吸烟图片分类 pipeline。"""
|
| 20 |
+
return pipeline("image-classification", model="ccclllwww/smoker_cls_base_V9", use_fast=True)
|
| 21 |
+
|
| 22 |
+
@st.cache_resource
|
| 23 |
+
def load_gender_pipeline():
|
| 24 |
+
"""初始化并缓存性别图片分类 pipeline。"""
|
| 25 |
+
return pipeline("image-classification", model="rizvandwiki/gender-classification-2", use_fast=True)
|
| 26 |
+
|
| 27 |
+
@st.cache_resource
|
| 28 |
+
def load_age_pipeline():
|
| 29 |
+
"""初始化并缓存年龄图片分类 pipeline。"""
|
| 30 |
+
return pipeline("image-classification", model="akashmaggon/vit-base-age-classification", use_fast=True)
|
| 31 |
+
|
| 32 |
+
# 预先加载所有模型
|
| 33 |
+
load_smoke_pipeline()
|
| 34 |
+
load_gender_pipeline()
|
| 35 |
+
load_age_pipeline()
|
| 36 |
+
|
| 37 |
+
# ======================
|
| 38 |
+
# remote settings
|
| 39 |
+
# ======================
|
| 40 |
# Find your Account SID and Auth Token at twilio.com/console
|
| 41 |
# and set the environment variables. See http://twil.io/secure
|
| 42 |
+
account_sid = os.environ['TWILIO_ACCOUNT_SID']
|
| 43 |
+
auth_token = os.environ['TWILIO_AUTH_TOKEN']
|
| 44 |
+
client = Client(account_sid, auth_token)
|
| 45 |
+
|
| 46 |
+
token = client.tokens.create()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ======================
|
| 50 |
+
# 音频加载函数(缓存)
|
| 51 |
+
# ======================
|
| 52 |
+
|
| 53 |
+
@st.cache_resource
|
| 54 |
+
def load_all_audios():
|
| 55 |
+
"""加载 audio 目录中的所有 .wav 文件,并返回一个字典,
|
| 56 |
+
键为文件名(不带扩展名),值为音频字节数据。"""
|
| 57 |
+
audio_dir = "audio"
|
| 58 |
+
audio_files = [f for f in os.listdir(audio_dir) if f.endswith(".wav")]
|
| 59 |
+
audio_dict = {}
|
| 60 |
+
for audio_file in audio_files:
|
| 61 |
+
file_path = os.path.join(audio_dir, audio_file)
|
| 62 |
+
with open(file_path, "rb") as af:
|
| 63 |
+
audio_bytes = af.read()
|
| 64 |
+
# 去掉扩展名作为键
|
| 65 |
+
key = os.path.splitext(audio_file)[0]
|
| 66 |
+
audio_dict[key] = audio_bytes
|
| 67 |
+
return audio_dict
|
| 68 |
+
|
| 69 |
+
# 应用启动时加载所有音频
|
| 70 |
+
audio_data = load_all_audios()
|
| 71 |
+
|
| 72 |
+
# ======================
|
| 73 |
+
# 核心处理函数
|
| 74 |
+
# ======================
|
| 75 |
+
|
| 76 |
+
@st.cache_data(show_spinner=False, max_entries=3)
|
| 77 |
+
def smoking_classification(image: Image.Image) -> str:
|
| 78 |
+
"""接受 PIL 图片并利用吸烟分类 pipeline 进行判定,返回标签(如 "smoking")。"""
|
| 79 |
+
try:
|
| 80 |
+
smoke_pipeline = load_smoke_pipeline()
|
| 81 |
+
output = smoke_pipeline(image)
|
| 82 |
+
status = max(output, key=lambda x: x["score"])['label']
|
| 83 |
+
return status
|
| 84 |
+
except Exception as e:
|
| 85 |
+
st.error(f"🔍 图像处理错误: {str(e)}")
|
| 86 |
+
st.stop()
|
| 87 |
+
|
| 88 |
+
@st.cache_data(show_spinner=False, max_entries=3)
|
| 89 |
+
def gender_classification(image: Image.Image) -> str:
|
| 90 |
+
"""进行性别分类,返回模型输出的性别(依模型输出)。"""
|
| 91 |
+
try:
|
| 92 |
+
gender_pipeline = load_gender_pipeline()
|
| 93 |
+
output = gender_pipeline(image)
|
| 94 |
+
status = max(output, key=lambda x: x["score"])['label']
|
| 95 |
+
return status
|
| 96 |
+
except Exception as e:
|
| 97 |
+
st.error(f"🔍 图像处理错误: {str(e)}")
|
| 98 |
+
st.stop()
|
| 99 |
+
|
| 100 |
+
@st.cache_data(show_spinner=False, max_entries=3)
|
| 101 |
+
def age_classification(image: Image.Image) -> str:
|
| 102 |
+
"""进行年龄分类,返回年龄范围,例如 "10-19" 等。"""
|
| 103 |
+
try:
|
| 104 |
+
age_pipeline = load_age_pipeline()
|
| 105 |
+
output = age_pipeline(image)
|
| 106 |
+
age_range = max(output, key=lambda x: x["score"])['label']
|
| 107 |
+
return age_range
|
| 108 |
+
except Exception as e:
|
| 109 |
+
st.error(f"🔍 图像处理错误: {str(e)}")
|
| 110 |
+
st.stop()
|
| 111 |
+
|
| 112 |
+
# ======================
|
| 113 |
+
# 自定义JS播放音频函数
|
| 114 |
+
# ======================
|
| 115 |
+
|
| 116 |
+
@st.cache_resource
|
| 117 |
+
def play_audio_via_js(audio_bytes):
|
| 118 |
+
"""
|
| 119 |
+
利用自定义 HTML 和 JavaScript 播放音频。
|
| 120 |
+
将二进制音频数据转换为 Base64 后嵌入 audio 标签,
|
| 121 |
+
并用 JS 在页面加载后模拟点击进行播放。
|
| 122 |
+
"""
|
| 123 |
+
audio_base64 = base64.b64encode(audio_bytes).decode("utf-8")
|
| 124 |
+
html_content = f"""
|
| 125 |
+
<audio id="audio_player" controls style="width: 100%;">
|
| 126 |
+
<source src="data:audio/wav;base64,{audio_base64}" type="audio/wav">
|
| 127 |
+
Your browser does not support the audio element.
|
| 128 |
+
</audio>
|
| 129 |
+
<script type="text/javascript">
|
| 130 |
+
// 等待 DOMContentLoaded 事件,并在1秒后自动调用 play() 方法
|
| 131 |
+
window.addEventListener('DOMContentLoaded', function() {{
|
| 132 |
+
setTimeout(function() {{
|
| 133 |
+
var audioElement = document.getElementById("audio_player");
|
| 134 |
+
if (audioElement) {{
|
| 135 |
+
audioElement.play().catch(function(e) {{
|
| 136 |
+
console.log("播放被浏览器阻止:", e);
|
| 137 |
+
}});
|
| 138 |
+
}}
|
| 139 |
+
}}, 1000);
|
| 140 |
+
}});
|
| 141 |
+
</script>
|
| 142 |
+
"""
|
| 143 |
+
st.components.v1.html(html_content, height=150)
|
| 144 |
+
|
| 145 |
+
# ======================
|
| 146 |
+
# VideoTransformer 定义:处理摄像头帧与快照捕获
|
| 147 |
+
# ======================
|
| 148 |
+
|
| 149 |
+
class VideoTransformer(VideoTransformerBase):
|
| 150 |
+
def __init__(self):
|
| 151 |
+
self.snapshots = [] # 存储捕获的快照
|
| 152 |
+
self.last_capture_time = time.time() # 上次捕获时间
|
| 153 |
+
self.capture_interval = 0.5 # 每0.5秒捕获一张快照
|
| 154 |
+
|
| 155 |
+
def transform(self, frame):
|
| 156 |
+
"""从摄像头流捕获单帧图像,并转换为 PIL Image。"""
|
| 157 |
+
img = frame.to_ndarray(format="bgr24")
|
| 158 |
+
current_time = time.time()
|
| 159 |
+
# 每隔 capture_interval 秒捕获一张快照,直到捕获20张
|
| 160 |
+
if current_time - self.last_capture_time >= self.capture_interval and len(self.snapshots) < 20:
|
| 161 |
+
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 162 |
+
self.snapshots.append(Image.fromarray(img_rgb))
|
| 163 |
+
self.last_capture_time = current_time
|
| 164 |
+
st.write(f"已捕获快照 {len(self.snapshots)}/20")
|
| 165 |
+
return img # 返回原始帧以供前端显示
|
| 166 |
+
|
| 167 |
+
# ======================
|
| 168 |
+
# 主函数:整合视频流、自动图片分类并展示结果
|
| 169 |
+
# ======================
|
| 170 |
+
|
| 171 |
+
def main():
|
| 172 |
+
st.title("Streamlit-WebRTC 自动图片分类示例")
|
| 173 |
+
st.write("程序在一分钟内捕获20张快照进行图片分类,首先判定是否吸烟。若检测到吸烟的快照超过2次,则展示年龄与性别分类结果。")
|
| 174 |
+
|
| 175 |
+
# 创建用于显示进度文字和进度条的占位容器
|
| 176 |
+
capture_text_placeholder = st.empty()
|
| 177 |
+
capture_progress_placeholder = st.empty()
|
| 178 |
+
classification_text_placeholder = st.empty()
|
| 179 |
+
classification_progress_placeholder = st.empty()
|
| 180 |
+
detection_info_placeholder = st.empty() # 用于显示“开始侦测”
|
| 181 |
+
|
| 182 |
+
# 启动实时视频流
|
| 183 |
+
# Then, pass the ICE server information to webrtc_streamer().
|
| 184 |
+
|
| 185 |
+
ctx = webrtc_streamer(key="unique_example", video_transformer_factory=VideoTransformer,rtc_configuration={"iceServers": token.ice_servers})
|
| 186 |
+
image_placeholder = st.empty()
|
| 187 |
+
audio_placeholder = st.empty()
|
| 188 |
+
|
| 189 |
+
capture_target = 10 # 本轮捕获目标张数
|
| 190 |
+
|
| 191 |
+
if ctx.video_transformer is not None:
|
| 192 |
+
classification_result_placeholder = st.empty() # 用于显示分类结果
|
| 193 |
+
detection_info_placeholder.info("开始侦测")
|
| 194 |
+
|
| 195 |
+
while True:
|
| 196 |
+
snapshots = ctx.video_transformer.snapshots
|
| 197 |
+
|
| 198 |
+
# 更新捕获阶段进度:同时显示文字和进度条
|
| 199 |
+
if len(snapshots) < capture_target:
|
| 200 |
+
capture_text_placeholder.text(f"捕获进度: {len(snapshots)}/{capture_target} 张快照")
|
| 201 |
+
progress_value = int(len(snapshots) / capture_target * 100)
|
| 202 |
+
capture_progress_placeholder.progress(progress_value)
|
| 203 |
+
else:
|
| 204 |
+
# 捕获完成,清空捕获进度条,并显示完成提示
|
| 205 |
+
capture_text_placeholder.text("捕获进度: 捕获完成!")
|
| 206 |
+
capture_progress_placeholder.empty()
|
| 207 |
+
detection_info_placeholder.empty() # 清除“开始侦测”提示
|
| 208 |
+
|
| 209 |
+
# ---------- 分类阶段进度 ----------
|
| 210 |
+
total = len(snapshots)
|
| 211 |
+
classification_text_placeholder.text("分类进度: 正在分类...")
|
| 212 |
+
classification_progress = classification_progress_placeholder.progress(0)
|
| 213 |
+
|
| 214 |
+
# 1. 吸烟分类 (0 ~ 33%)
|
| 215 |
+
smoke_results = []
|
| 216 |
+
for idx, img in enumerate(snapshots):
|
| 217 |
+
smoke_results.append(smoking_classification(img))
|
| 218 |
+
smoking_count = sum(1 for result in smoke_results if result.lower() == "smoking")
|
| 219 |
+
classification_progress.progress(33)
|
| 220 |
+
|
| 221 |
+
# 2. 若吸烟次数超过2,再进行性别和年龄分类 (33% ~ 100%)
|
| 222 |
+
if smoking_count > 2:
|
| 223 |
+
gender_results = []
|
| 224 |
+
for idx, img in enumerate(snapshots):
|
| 225 |
+
gender_results.append(gender_classification(img))
|
| 226 |
+
classification_progress.progress(66)
|
| 227 |
+
|
| 228 |
+
age_results = []
|
| 229 |
+
for idx, img in enumerate(snapshots):
|
| 230 |
+
age_results.append(age_classification(img))
|
| 231 |
+
classification_progress.progress(100)
|
| 232 |
+
classification_text_placeholder.text("分类进度: 分类完成!")
|
| 233 |
+
|
| 234 |
+
most_common_gender = Counter(gender_results).most_common(1)[0][0]
|
| 235 |
+
most_common_age = Counter(age_results).most_common(1)[0][0]
|
| 236 |
+
|
| 237 |
+
result_text = (
|
| 238 |
+
f"**吸烟状态:** Smoking (检测到 {smoking_count} 次)\n\n"
|
| 239 |
+
f"**性别:** {most_common_gender}\n\n"
|
| 240 |
+
f"**年龄范围:** {most_common_age}"
|
| 241 |
+
)
|
| 242 |
+
classification_result_placeholder.markdown(result_text)
|
| 243 |
+
|
| 244 |
+
# 选择第一张分类结果为 "smoking" ��快照,如未检测到,则显示第一张
|
| 245 |
+
smoking_image = None
|
| 246 |
+
for idx, label in enumerate(smoke_results):
|
| 247 |
+
if label.lower() == "smoking":
|
| 248 |
+
smoking_image = snapshots[idx]
|
| 249 |
+
break
|
| 250 |
+
if smoking_image is None:
|
| 251 |
+
smoking_image = snapshots[0]
|
| 252 |
+
image_placeholder.image(smoking_image, caption="捕获的快照示例", use_container_width=True)
|
| 253 |
+
|
| 254 |
+
# 清空播放区域后再播放对应音频
|
| 255 |
+
audio_placeholder.empty()
|
| 256 |
+
audio_key = f"{most_common_age} {most_common_gender.lower()}"
|
| 257 |
+
if audio_key in audio_data:
|
| 258 |
+
audio_bytes = audio_data[audio_key]
|
| 259 |
+
play_audio_via_js(audio_bytes)
|
| 260 |
+
else:
|
| 261 |
+
st.error(f"音频文件不存在: {audio_key}.wav")
|
| 262 |
+
else:
|
| 263 |
+
result_text = "**吸烟状态:** Not Smoking"
|
| 264 |
+
classification_result_placeholder.markdown(result_text)
|
| 265 |
+
image_placeholder.empty()
|
| 266 |
+
audio_placeholder.empty()
|
| 267 |
+
classification_text_placeholder.text("分类进度: 分类完成!")
|
| 268 |
+
classification_progress.progress(100)
|
| 269 |
+
|
| 270 |
+
# 分类阶段结束后清空分类进度占位区
|
| 271 |
+
time.sleep(1)
|
| 272 |
+
classification_progress_placeholder.empty()
|
| 273 |
+
classification_text_placeholder.empty()
|
| 274 |
+
capture_text_placeholder.empty()
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# 重置快照列表,准备下一轮捕获
|
| 278 |
+
detection_info_placeholder.info("开始侦测")
|
| 279 |
+
ctx.video_transformer.snapshots = []
|
| 280 |
+
ctx.video_transformer.last_capture_time = time.time()
|
| 281 |
+
time.sleep(0.1)
|
| 282 |
|
| 283 |
+
if __name__ == "__main__":
|
| 284 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|