Files
video/core/establish.py
2025-09-16 20:17:48 +08:00

134 lines
5.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import datetime
from pathlib import Path
from typing import List, Tuple
from service.device_service import get_unique_client_ips
def create_directory_structure():
"""创建项目所需的目录结构为所有客户端IP预创建基础目录"""
try:
# 1. 创建根目录下的resource文件夹存在则跳过不覆盖子内容
resource_dir = Path("resource")
resource_dir.mkdir(exist_ok=True)
# 2. 在resource下创建dect文件夹
dect_dir = resource_dir / "dect"
dect_dir.mkdir(exist_ok=True)
# 3. 在dect下创建三个模型文件夹
model_dirs = ["ocr", "face", "yolo"]
for model in model_dirs:
model_dir = dect_dir / model
model_dir.mkdir(exist_ok=True)
# 4. 调用外部方法获取所有客户端IP地址
try:
all_ip_addresses = get_unique_client_ips()
# 确保返回的是列表类型
if not isinstance(all_ip_addresses, list):
all_ip_addresses = [all_ip_addresses]
# 过滤有效IP去除空字符串和空格
valid_ips = [ip.strip() for ip in all_ip_addresses if ip.strip()]
if not valid_ips:
print("警告: 未获取到有效的客户端IP地址")
return
print(f"获取到的所有客户端IP地址: {valid_ips}")
# 5. 获取当前日期(年、月)
now = datetime.datetime.now()
current_year = str(now.year)
current_month = str(now.month)
# 6. 为每个客户端IP在每个模型文件夹下创建年->月的基础目录结构
for ip in valid_ips:
# 处理IP地址中的特殊字符将.替换为_避免路径问题
safe_ip = ip.replace(".", "_")
for model in model_dirs:
# 构建路径: resource/dect/{model}/{safe_ip}/{year}/{month}
ip_dir = dect_dir / model / safe_ip
year_dir = ip_dir / current_year
month_dir = year_dir / current_month
# 递归创建目录(存在则跳过,不覆盖)
month_dir.mkdir(parents=True, exist_ok=True)
except Exception as e:
print(f"处理客户端IP和日期目录时发生错误: {str(e)}")
except Exception as e:
print(f"创建基础目录结构时发生错误: {str(e)}")
def get_image_save_path(model_type: str, client_ip: str) -> Tuple[str, str]:
"""
获取图片保存的「本地完整路径」和「带路由前缀的显示路径」
参数:
model_type: 模型类型,应为"ocr""face""yolo"
client_ip: 检测到违禁的客户端IP地址原始格式如192.168.1.101
返回:
元组 (本地完整保存路径, 带/api/file/前缀的显示路径);若出错则返回 ("", "")
"""
try:
# 验证模型类型有效性
valid_models = ["ocr", "face", "yolo"]
if model_type not in valid_models:
raise ValueError(f"无效的模型类型: {model_type},必须是{valid_models}之一")
# 1. 验证客户端IP有效性检查是否在已知IP列表中
all_ip_addresses = get_unique_client_ips()
if not isinstance(all_ip_addresses, list):
all_ip_addresses = [all_ip_addresses]
valid_ips = [ip.strip() for ip in all_ip_addresses if ip.strip()]
client_ip_stripped = client_ip.strip()
if client_ip_stripped not in valid_ips:
raise ValueError(f"客户端IP {client_ip} 不在已知IP列表中无法保存文件")
# 2. 处理IP地址将.替换为_避免路径问题
safe_ip = client_ip_stripped.replace(".", "_")
# 3. 获取当前日期和毫秒级时间戳(确保文件名唯一)
now = datetime.datetime.now()
current_year = str(now.year)
current_month = str(now.month).zfill(2) # 确保月份为两位数
current_day = str(now.day).zfill(2) # 确保日期为两位数
timestamp = now.strftime("%Y%m%d%H%M%S%f")[:-3] # 取毫秒级时间戳
# 4. 定义基础目录(用于生成相对路径)
base_dir = Path("resource") / "dect"
# 构建日级目录完整路径resource/dect/{model}/{safe_ip}/{年}/{月}/{日}
day_dir = base_dir / model_type / safe_ip / current_year / current_month / current_day
day_dir.mkdir(parents=True, exist_ok=True) # 确保目录存在
# 5. 构建唯一文件名
image_filename = f"dect_{model_type}_{safe_ip}_{current_year}{current_month}{current_day}_{timestamp}.jpg"
# 6. 生成「本地完整路径」(使用系统路径,但在字符串表示时统一为正斜杠)
local_full_path = day_dir / image_filename
# 转换为字符串并统一使用正斜杠
local_full_path_str = str(local_full_path).replace("\\", "/")
# 7. 生成带路由前缀的显示路径(核心修改部分)
# 获取项目根目录base_dir是resource/dect向上两级即为项目根目录
project_root = base_dir.parents[1]
# 计算相对于项目根目录的路径包含resource/dect层级
relative_path = local_full_path.relative_to(project_root)
# 转换为字符串并统一使用正斜杠
relative_path_str = str(relative_path).replace("\\", "/")
# 拼接路由前缀
routed_display_path = f"/api/file/{relative_path_str}"
return local_full_path_str, routed_display_path
except Exception as e:
print(f"获取图片保存路径时发生错误: {str(e)}")
return "", ""