File size: 6,922 Bytes
14de029
8d9f842
 
fd3ecfb
26be8c4
0ce6f4c
2150861
f69b08f
26be8c4
457c927
26be8c4
8d9f842
14de029
 
 
 
e45be51
0ce6f4c
26be8c4
0ce6f4c
3aa2252
 
 
 
 
 
 
 
 
14de029
3aa2252
 
 
b33582e
2150861
26be8c4
 
 
 
 
 
 
 
 
3aa2252
 
 
26be8c4
 
 
0be7f95
457c927
 
 
 
 
26be8c4
 
4b635e1
457c927
 
 
26be8c4
457c927
 
 
 
4b635e1
26be8c4
457c927
 
 
26be8c4
457c927
 
 
 
 
 
 
 
26be8c4
457c927
4b635e1
26be8c4
 
 
 
457c927
26be8c4
457c927
26be8c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
457c927
 
 
 
 
26be8c4
457c927
da19eb4
26be8c4
457c927
da19eb4
26be8c4
 
 
 
 
457c927
26be8c4
 
 
 
 
 
 
 
 
 
da19eb4
26be8c4
8d9f842
b33582e
 
 
 
3aa2252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b33582e
3aa2252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b33582e
 
 
 
 
 
0f3261d
8d9f842
3aa2252
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import os
import gradio as gr
from ultralytics import YOLO
from fastapi import FastAPI
from PIL import Image
import torch
import spaces
import numpy as np
import cv2
from pathlib import Path
import tempfile

# 从环境变量获取密码
APP_USERNAME = "admin"  # 用户名保持固定
APP_PASSWORD = os.getenv("APP_PASSWORD", "default_password")  # 从环境变量获取密码

app = FastAPI()
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = YOLO('kunin-mice-pose.v0.1.0.pt')

# 定义认证状态
class AuthState:
    def __init__(self):
        self.is_logged_in = False

auth_state = AuthState()

def login(username, password):
    """登录验证"""
    if username == APP_USERNAME and password == APP_PASSWORD:
        auth_state.is_logged_in = True
        return gr.update(visible=False), gr.update(visible=True), "登录成功"
    return gr.update(visible=True), gr.update(visible=False), "用户名或密码错误"

@spaces.GPU
def process_video(video_path, process_seconds=20, conf_threshold=0.2, max_det=8):
    """
    处理视频并进行小鼠检测
    Args:
        video_path: 输入视频路径
        process_seconds: 处理时长(秒)
        conf_threshold: 置信度阈值(0-1)
        max_det: 每帧最大检测数量
    """
    if not auth_state.is_logged_in:
        return None, "请先登录"
    
    # 创建临时目录保存输出视频
    with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as tmp_file:
        output_path = tmp_file.name
    
    # 获取视频信息
    cap = cv2.VideoCapture(video_path)
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    total_frames = int(process_seconds * fps) if process_seconds else int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    cap.release()
    
    # 创建视频写入器
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    video_writer = cv2.VideoWriter(
        output_path, 
        fourcc, 
        fps, 
        (width, height)
    )
    
    # 设置推理参数并处理视频
    results = model.predict(
        source=video_path,
        device=device,
        conf=conf_threshold,  # 使用用户设置的置信度阈值
        save=False,
        show=False,
        stream=True,
        line_width=2,
        show_boxes=True,
        show_labels=True,
        show_conf=True,
        vid_stride=1,
        max_det=max_det,  # 使用用户设置的最大检测数量
    )
    
    # 处理结果
    frame_count = 0
    detection_info = []
    
    for r in results:
        # 获取绘制了预测结果的帧
        frame = r.plot()
        
        # 收集检测信息
        frame_info = {
            "frame": frame_count + 1,
            "count": len(r.boxes),
            "detections": []
        }
        
        for box in r.boxes:
            conf = float(box.conf[0])
            cls = int(box.cls[0])
            cls_name = r.names[cls]
            frame_info["detections"].append({
                "class": cls_name,
                "confidence": f"{conf:.2%}"
            })
        
        detection_info.append(frame_info)
        
        # 写入视频
        video_writer.write(frame)
        
        frame_count += 1
        if process_seconds and frame_count >= total_frames:
            break
    
    # 释放视频写入器
    video_writer.release()
    
    # 生成分析报告
    report = f"""视频分析报告:
参数设置:
- 置信度阈值: {conf_threshold:.2f}
- 最大检测数量: {max_det}
- 处理时长: {process_seconds}

分析结果:
- 处理帧数: {frame_count}
- 平均每帧检测到的老鼠数: {np.mean([info['count'] for info in detection_info]):.1f}
- 最大检测数: {max([info['count'] for info in detection_info])}
- 最小检测数: {min([info['count'] for info in detection_info])}

置信度分布:
{np.histogram([float(det['confidence'].strip('%'))/100 for info in detection_info for det in info['detections']], bins=5)[0].tolist()}
"""
    
    return output_path, report

# 创建 Gradio 界面
with gr.Blocks() as demo:
    gr.Markdown("# 🐁 小鼠行为分析 (Mice Behavior Analysis)")
    
    # 登录界面
    with gr.Group() as login_interface:
        username = gr.Textbox(label="用户名")
        password = gr.Textbox(label="密码", type="password")
        login_button = gr.Button("登录")
        login_msg = gr.Textbox(label="消息", interactive=False)
    
    # 主界面
    with gr.Group(visible=False) as main_interface:
        gr.Markdown("上传视频来检测和分析小鼠行为 | Upload a video to detect and analyze mice behavior")
        
        with gr.Row():
            with gr.Column():
                video_input = gr.Video(label="输入视频")
                process_seconds = gr.Number(
                    label="处理时长(秒,0表示处理整个视频)", 
                    value=20
                )
                conf_threshold = gr.Slider(
                    minimum=0.1,
                    maximum=1.0,
                    value=0.2,
                    step=0.05,
                    label="置信度阈值",
                    info="越高越严格,建议范围0.2-0.5"
                )
                max_det = gr.Slider(
                    minimum=1,
                    maximum=10,
                    value=8,
                    step=1,
                    label="最大检测数量",
                    info="每帧最多检测的目标数量"
                )
                process_btn = gr.Button("开始处理")
            
            with gr.Column():
                video_output = gr.Video(label="检测结果")
                report_output = gr.Textbox(label="分析报告")
        
        gr.Markdown("""
        ### 使用说明
        1. 上传视频文件
        2. 设置处理参数:
           - 处理时长:需要分析的视频时长(秒)
           - 置信度阈值:检测的置信度要求(越高越严格)
           - 最大检测数量:每帧最多检测的目标数量
        3. 等待处理完成
        4. 查看检测结果视频和分析报告
        
        ### 注意事项
        - 支持常见视频格式(mp4, avi 等)
        - 建议视频分辨率不超过 1920x1080
        - 处理时间与视频长度和分辨率相关
        - 置信度建议范围:0.2-0.5
        - 最大检测数量建议根据实际场景设置
        """)
    
    # 设置事件处理
    login_button.click(
        fn=login,
        inputs=[username, password],
        outputs=[login_interface, main_interface, login_msg]
    )
    
    process_btn.click(
        fn=process_video,
        inputs=[video_input, process_seconds, conf_threshold, max_det],
        outputs=[video_output, report_output]
    )

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)