feat: update backend services, frontend views, and cleanup obsolete scripts

This commit is contained in:
yilv committed 2026-09-20 17:24:37 +08:00
1 parent 62e0197fe9
commit 7747442035
28 files changed
+307 -1939

No files matched your search

+26 -16
View File
@@ -3,8 +3,8 @@
## 项目概览
RCT Vue 是一个集数据采集、AI 推理、RBAC 权限管理于一体的前后端分离平台。
- **后端**: Flask 3.1 + SQLAlchemy 2.0 + Flask-Migrate,MySQL 8.0(阿里云 RDS)
- **前端**: Vue 3.5 + Vite 7 + Element Plus + Pinia
- **后端**: Flask 3.1.1 + SQLAlchemy 2.0.43 + Flask-Migrate 4.1.0,MySQL 8.0(阿里云 RDS)
- **前端**: Vue 3.5.25 + Vite 7.3.1 + Element Plus 2.13.2 + Pinia 3.0.4
- **位置**: 后端在 `backend/`,前端在 `frontend/`
## 快速命令
@@ -17,8 +17,8 @@ cp .env.example .env # 编辑数据库连接和密钥
flask db upgrade # 执行数据库迁移建表
python run.py # 启动开发服务 (端口 5000)
# 创建管理员用户
flask create-user <用户名> <邮箱> <密码> --role admin
# 创建用户
flask create-user <用户名> <邮箱> <密码> [--role admin|user]
# 前端
cd frontend
@@ -33,12 +33,12 @@ cd backend && pytest # 或: pytest backend/tests/
## 架构边界与层级规则
### 后端(`backend/app/`)
- **App 工厂模式**: `create_app()` 在 `__init__.py` 中,通过 `config_name` 选择配置类
- **App 工厂模式**: `create_app()` 在 `__init__.py` 中,通过 `config_name` 选择配置类(`development`/`testing`/`production`)
- **三层分离架构**: 接口层(`api/`)-> 业务层(`services/`)-> 数据层(`models.py`),详见 `docs/ARCHITECTURE.md`
- **接口层** (`api/`): 仅负责 HTTP 适配--参数解析、认证装饰器、调用 service、返回标准化响应(`success()`/`error()`)。不含 DB 查询或文件 I/O。异常处理使用 `@handle_service_errors` 装饰器(`core/exception_handler.py`),不在路由函数内写 try/except
- **业务层** (`services/`): 所有业务逻辑--DB 操作、文件处理、后台线程编排。不依赖 Flask 请求上下文(`request`/`current_app` 仅用于配置/日志),返回原始数据,抛出业务异常
- **业务异常** (`services/exceptions.py`): `BusinessError`/`NotFoundError`/`ValidationError`/`ConflictError`/`PermissionDeniedError`/`UnauthorizedError`,路由层通过 `@handle_service_errors` 装饰器统一捕获
- **Blueprint 路由**: `main`, `auth`, `admin`, `api`(上传蓝图通过 `api/uploads.py` 工厂注册)
- **Blueprint 路由**: `main`, `auth`, `admin`, `api`, `system`(上传蓝图通过 `api/uploads.py` 工厂注册为 `crawler_uploads_v2` 和 `models_uploads`)
- **模型统一在**: `backend/app/models.py`,关联表(`data_visibility`, `user_roles`, `role_permissions`, `user_tags`, `inference_task_folders`)也在其中以 `db.Table` 定义
- **装饰器**: 权限装饰器统一在 `core/security.py`,通过 `decorators.py` 向后兼容导出(`admin_required`, `permission_required`, `data_access_required`),**不要在路由函数上直接使用旧导入路径**
- **认证双模式**: Flask-Login 会话 + JWT,`login_manager.login_view = 'auth.login'`
@@ -52,14 +52,16 @@ cd backend && pytest # 或: pytest backend/tests/
- **状态管理**: Pinia stores 在 `store/`
- **国际化**: `i18n.js` + `locales/` 目录
- **API 层**: `api/` 目录统一管理 axios 请求
- **组合式函数**: `composables/` 目录存放可复用逻辑
## 数据库
- **ORM**: SQLAlchemy 2.0,通过 Flask-Migrate(Alembic)管理迁移
- **ORM**: SQLAlchemy 2.0.43,通过 Flask-Migrate(Alembic)管理迁移
- **迁移脚本**: `backend/migrations/versions/`,新增表或字段改表结构必须生成迁移
- **建表方式**: `flask db upgrade` 自动执行全部迁移,不要手动写 SQL 建表
- **运行时配置**: 自动推理等配置已从环境变量迁移到 `system_setting` / `system_config` 表,通过 `get_setting()` 读取
- **连接池**: 生产环境在 `config.py` 中配置(pool_size=20, pool_recycle=1800, max_overflow=40)
- **连接池**: 生产环境在 `config.py` 中配置(`pool_size=20`, `pool_recycle=1800`, `max_overflow=40`)
- **数据库驱动**: 使用 `PyMySQL`(`mysql+pymysql://`),注意 `.env.example` 中的 `DATABASE_URL` 示例使用的是 `mysql+pymysql` 格式
## 安全与认证
@@ -68,6 +70,8 @@ cd backend && pytest # 或: pytest backend/tests/
- **Session Cookie**: 生产推荐启用 `SESSION_COOKIE_SECURE=True`
- **文件上传**: 爬虫上传需 `UPLOAD_API_TOKEN`,支持断点续传
- **反向代理**: `ProxyFix` 已配置(支持 ngrok/frp),CORS 白域名列表在 vite config 中
- **Swagger 文档**: 开发环境默认启用,生产环境需显式设置 `SWAGGER_ENABLED=true`,访问路径 `/api/docs/`
- **CSRF 保护**: 已启用 `Flask-WTF` CSRFProtect,API 路由已豁免
## 关键文档
@@ -77,6 +81,7 @@ cd backend && pytest # 或: pytest backend/tests/
- 推理/模型 → `backend/docs/INFERENCE_OPTIMIZATION.md`
- 爬虫上传 → `backend/docs/crawler_rate_limit.md`
- 项目全貌 → `readme.md` / `backend/readme.md`
- 架构设计 → `backend/docs/ARCHITECTURE.md`
## 已知注意事项
@@ -85,27 +90,32 @@ cd backend && pytest # 或: pytest backend/tests/
- 数据存储目录在 `backend/` 下:`raw_data_storage/`, `processed_data_output/`, `uploads/`, `attachments/`
- Flask 错误处理器中已包含 `db.session.rollback()`,新增路由遇到异常无需手动回滚
- 生产构建前端时 terser 会 `drop_console` / `drop_debugger`
- **推理任务 SSE 推送**: 推理进度通过 SSE(Server-Sent Events)实时推送到前端,相关实现在 `backend/app/api/routes.py` 和 `backend/app/inference/engine.py`
- **缓存与队列**: 使用 `Flask-Caching`(`cache` 对象)+ `APScheduler` 后台任务 + `redis` 缓存后端 + `Flask-Limiter` 限流
- **推理任务 SSE 推送**: 推理进度通过 SSE(Server-Sent Events)实时推送到前端,相关实现在 `backend/app/api/inference_new.py`(`/api/inference/tasks/<task_id>/progress` 和 `/api/inference/tasks/progress`)和 `backend/app/services/inference_service.py`
- **缓存与队列**: 使用 `Flask-Caching`(`cache` 对象)+ `APScheduler` 后台任务 + `redis` 可选缓存后端 + `Flask-Limiter` 限流
- **模型架构扩展**: 新增 `models_pkg/mixins.py` 提供通用 mixin,`schemas/` 目录存放序列化层
- **业务服务层** (`services/`): 接口层与数据层之间的业务逻辑层,包含:
- CRUD 服务: `auth_service`, `user_service`, `tag_service`, `role_service`, `permission_service`, `notification_service`, `data_entry_service`, `model_management_service`, `search_service`, `dashboard_service`
- 上传服务: `resumable_upload_service`(合并 crawler + models 上传去重)
- 集成/推理服务: `integration_service`, `inference_service`(已完整迁移业务逻辑,不再为 façade 重导出。当前为巨型模块,拆分规划见 `docs/ARCHITECTURE.md`)
- 流式处理: `signal_processing_helpers`(ZIP 解压、CSV 滤波、TXT 转 CSV)
- 队列管理: `inference_queue`, `filter_queue`, `zip_filter_queue`, `base_queue_manager`
- 业务异常: `exceptions.py`(`BusinessError` 及子类)
- 原有服务: `config_service`(含 `update_configs_batch` 批量更新), `email_service`, 队列管理器, `model_cache`
- 原有服务: `config_service`(含 `update_configs_batch` 批量更新), `email_service`, `model_cache`
- **核心层工具** (`core/`):
- `exception_handler.py`: `@handle_service_errors` 装饰器,统一捕获 `BusinessError` 家族,消除路由层 try/except 样板
- `responses.py`: 统一响应格式(`success`/`error`/`paginate`)
- `security.py`: `SecurityManager` 认证/权限装饰器
- `upload_auth.py`: 上传令牌验证装饰器
- `responses.py`: 统一响应格式(`success`/`error`/`paginate`/`bad_request`/`unauthorized`/`forbidden`/`not_found`/`conflict`/`internal_error`)
- `security.py`: `SecurityManager` 认证/权限装饰器,支持 Flask-Login + JWT 双模式
- `upload_auth.py`: 上传令牌验证装饰器(`require_upload_token`)
- `task_executor.py`: 线程池任务执行器
- `validators.py`: 请求参数校验
- **上传蓝图工厂**: `api/uploads.py` 的 `register_upload_blueprint(name, url_prefix, config)` 工厂函数统一了 crawler + models 上传路由,不再有 `crawler_uploads.py` 和 `models_uploads.py` 两个孪生文件
- **仪表盘缓存 key**: `dashboard_service.build_dashboard_cache_key(user_id)` 封装了用户角色判断,路由层不直接查询 DB
- **集成任务状态管理**: `integration_service._get_or_create_app_state_dict(attr_name)` 封装 `current_app.inference_tasks/pipeline_tasks` 初始化,路由层不再直接操作 `current_app` 状态
- **app 级工具模块**: `auto_update_service.py`(自动更新)、`integrator_pipeline.py`(数据管线集成)、`rbac_utils.py`(RBAC 辅助工具)
- **app 级工具模块**: `auto_update_service.py`(自动更新/系统设置)、`integrator_pipeline.py`(数据管线集成)、`rbac_utils.py`(RBAC 辅助工具)、`system.py`(系统管理蓝图)
- **推理引擎模块**: `inference/` 目录包含 `engine.py`(引擎基类)、`registry.py`(模型注册)、`implementations/`(具体实现)
- **前端 allowedHosts**: vite 配置了 `allowedHosts`(`rct.if4.ttyt.cc`, `8.135.66.203` 等),反向代理部署时注意域名匹配
- **包体积分析**: 构建时使用 `rollup-plugin-visualizer`,输出 `dist/stats.html` 用于分析打包结果
- **无专用 lint/typecheck**: 项目未配置 ruff/flake8/mypy 等工具,后端遵循 PEP 8 手工规范
- **大文件忽略**: `.pth`, `.pt`, `.onnx`, `.bin` 模型文件已加入 `.gitignore`,勿提交
- **巨型 service 待拆分**: `integration_service.py`(~4000 行)和 `inference_service.py`(~2400 行)当前为巨型模块,拆分规划见 `docs/ARCHITECTURE.md` 第五节,本期不实施
- **巨型 service 待拆分**: `integration_service.py`(~4200 行)和 `inference_service.py`(~2400 行)当前为巨型模块,拆分规划见 `docs/ARCHITECTURE.md` 第五节,本期不实施
- **Swagger API 文档**: 访问 `/api/docs/`,仅在开发环境或 `SWAGGER_ENABLED=true` 时可用
+5 -3
View File
@@ -34,7 +34,7 @@ compress = Compress()
jwt = JWTManager()
limiter = Limiter(
key_func=get_remote_address,
storage_uri='memory://',
storage_uri=os.environ.get('RATELIMIT_STORAGE_URL', 'memory://'),
default_limits=[]
)
cache = Cache()
@@ -166,8 +166,10 @@ def create_app(config_name):
limiter.exempt(crawler_upload_bp)
limiter.exempt(models_upload_bp)
# Initialize Swagger (must be after blueprint registration)
swagger.init_app(app)
# Swagger 文档:开发环境默认启用,生产环境需显式设置 SWAGGER_ENABLED=true
swagger_enabled = os.environ.get('SWAGGER_ENABLED', 'false').lower() == 'true'
if config_name == 'development' or swagger_enabled:
swagger.init_app(app)
# 生产环境日志配置:添加 RotatingFileHandler,防止日志文件无限增长
if config_name != 'development':
+3
View File
@@ -732,6 +732,9 @@ def test_model_output():
num_classes:
type: integer
description: 推断的类别数量
output_kind:
type: string
description: 输出类型(logits 或 binary_single_probability)
output_shape:
type: array
description: 输出张量形状
+7 -4
View File
@@ -14,13 +14,16 @@ from ..services.dashboard_service import (
def _dashboard_cache_key():
"""为每个用户+角色生成独立的缓存 key。
"""为每个用户+角色生成独立的缓存 key(带版本号,支持缓存失效)。
委托给 dashboard_service.build_dashboard_cache_key,
确保路由层不直接进行 DB 查询。
委托给 dashboard_service.build_dashboard_cache_key 生成基础 key,
并附加 app 级版本号,数据变更时递增版本号即可使旧缓存自然失效。
"""
from flask import current_app
current_user_id = get_jwt_identity()
return _build_dashboard_cache_key(current_user_id)
version = getattr(current_app, '_dashboard_cache_version', 0)
base_key = _build_dashboard_cache_key(current_user_id)
return f'{base_key}_v{version}'
@api.route('/dashboard', methods=['GET'])
+24 -5
View File
@@ -12,6 +12,11 @@ import logging
from ..models import User, SecurityLog, db
from datetime import datetime
try:
from flask_jwt_extended.exceptions import JWTError
except ImportError:
JWTError = Exception # 降级兼容
logger = logging.getLogger(__name__)
@@ -23,7 +28,7 @@ def log_security_event(action, resource=None, status='denied', details=None):
user = _get_current_user_internal()
if user:
user_id = user.id
except:
except Exception:
pass
log = SecurityLog(
@@ -37,7 +42,17 @@ def log_security_event(action, resource=None, status='denied', details=None):
db.session.add(log)
db.session.commit()
except Exception as e:
logger.error(f"Failed to log security event: {e}")
# 安全审计日志写入失败时,回退到 Flask 日志(避免静默丢弃)
logger.error(f"Failed to log security event to DB, fallback to app log: {e}")
try:
from flask import current_app
current_app.logger.warning(
f"[SECURITY] action={action} resource={resource} status={status} "
f"user_id={user_id} details={details} "
f"(DB write failed: {e})"
)
except Exception:
pass # 极端情况:应用上下文也不可用
# 兼容旧代码的别名
@@ -57,10 +72,14 @@ def _get_current_user_internal() -> Optional[User]:
except (TypeError, ValueError):
logger.debug(f"Invalid user_id from JWT: {user_id}")
return None
except Exception as e:
# JWT 验证失败,静默回退到 Session
logger.debug(f"JWT authentication failed: {type(e).__name__}")
except JWTError as e:
# JWT 验证失败(过期/签名无效/缺失),静默回退到 Session
logger.debug(f"JWT authentication failed: {type(e).__name__}: {e}")
pass
except Exception as e:
# 非 JWT 异常(如数据库错误),向上抛出
logger.warning(f"Unexpected error during JWT verification: {type(e).__name__}: {e}")
raise
# 回退到 Session/Flask-Login
try:
+6 -3
View File
@@ -56,6 +56,7 @@ class User(UserMixin, db.Model):
def __init__(self, **kwargs):
super(User, self).__init__(**kwargs)
self._perm_cache = None
self._perm_cache_version = -1 # 权限缓存版本,用于失效检测
def set_password(self, password):
self.password_hash = generate_password_hash(password)
@@ -64,10 +65,12 @@ class User(UserMixin, db.Model):
return check_password_hash(self.password_hash, password)
def has_permission(self, permission_name):
"""检查用户是否具有特定权限(支持角色继承),带缓存"""
# 使用 getattr 确保从数据库加载的对象也能正常工作
if getattr(self, '_perm_cache', None) is None:
"""检查用户是否具有特定权限(支持角色继承),带版本化缓存"""
from flask import current_app
current_version = getattr(current_app, '_perm_version', 0)
if getattr(self, '_perm_cache_version', -1) != current_version:
self._perm_cache = self.get_all_permissions()
self._perm_cache_version = current_version
return permission_name in self._perm_cache
def _role_has_permission(self, role, permission_name):
+8 -1
View File
@@ -18,7 +18,14 @@ def check_circular_inheritance(role_id, parent_id):
return check_circular_inheritance(role_id, parent.parent_id)
def log_permission_change(operator_id, action, target_type, target_id, details=None):
"""记录权限变更日志"""
"""记录权限变更日志并失效权限缓存"""
# 递增权限版本号,使所有用户的 _perm_cache 失效
try:
from flask import current_app
current_app._perm_version = getattr(current_app, '_perm_version', 0) + 1
except RuntimeError:
pass # 不在应用上下文内时跳过
log = PermissionLog(
user_id=operator_id,
action=action,
+11 -9
View File
@@ -46,16 +46,18 @@ def allowed_attachment(filename: str, file_size: int) -> bool:
def invalidate_dashboard_cache():
"""清除 Dashboard 相关缓存(仅删除 dashboard_stats_ 前缀的缓存键,避免全量缓存失效)。"""
"""递增仪表盘缓存版本号,使旧缓存 key 自然失效。
相比 cache.clear() 全量清除,此方式:
- O(1) 复杂度,不触发缓存击穿
- 旧缓存条目在 timeout 到期后自动清理
- 不影响其他前缀的缓存(如通知、搜索)
"""
try:
# Flask-Caching 基于 SimpleCache/Redis 时没有直接的 scan/迭代 API,
# 使用 delete_memcached_objects 的替代方案:尝试删除已知前缀的缓存
# 由于无法枚举所有用户的 key,这里使用 cache.clear() 但添加注释说明优化方向
# TODO: 迁移到带版本号的缓存 key(如 dashboard_v{version}_user_{id}),
# 数据变更时递增 version,实现 O(1) 失效
cache.clear()
except Exception:
pass
from flask import current_app
current_app._dashboard_cache_version = getattr(current_app, '_dashboard_cache_version', 0) + 1
except RuntimeError:
pass # 不在应用上下文内时跳过
def get_data_entry(entry_id: int, entry=None) -> dict:
+136 -16
View File
@@ -71,6 +71,18 @@ DEFAULT_TRIM_RATIO = 0.05
DEFAULT_IQR_SCALE = 1.5
# ================= PPG CHD 模型常量 =================
# ppg_chd_model.onnx 的固定契约:
# 输入:归一化 [N,1,3000] float32(100Hz 单通道 PPG,30 秒窗)
# 输出:[N] 窗口 CHD 概率(已 sigmoid)
# 前处理(逐窗 z-score + clip)和患者级算术平均留在 Python 侧,不进 ONNX 图。
PPG_CHD_SIGNAL_LEN = 3000
PPG_CHD_STRIDE = 3000 # 非重叠 30 秒窗,与模型标定一致
PPG_CHD_THRESHOLD = 0.5 # 固定分类阈值,不可被任务参数覆盖
PPG_CHD_WINDOW_BATCH = 8 # 2H4G 环境下每批窗口数(每窗口=3 张 224 图过 ConvNeXt)
PPG_CHD_SAMPLING_RATE_HZ = 100
# ================= SSE 进度事件总线 =================
class ProgressEventBus:
"""线程安全的进度事件总线,用于 SSE 实时推送"""
@@ -346,6 +358,66 @@ def check_basic_validity(signal):
return True
def is_ppg_chd_session(session) -> bool:
"""按 ONNX 输入/输出签名判断是否为 PPG CHD 模型。
CHD 签名:单输入 [batch,1,3000] + 单输出 1D [batch]。
batch 维允许为符号维(str/None),仅校验后两维。
"""
try:
inputs = session.get_inputs()
outputs = session.get_outputs()
except Exception:
return False
if len(inputs) != 1 or len(outputs) != 1:
return False
in_shape = inputs[0].shape
out_shape = outputs[0].shape
if len(in_shape) != 3 or len(out_shape) != 1:
return False
return in_shape[1] == 1 and in_shape[2] == PPG_CHD_SIGNAL_LEN
def resample_windows_to_100hz(windows: np.ndarray, sampling_rate_hz) -> np.ndarray:
"""将窗口数据重采样到 100Hz(CHD 模型要求)。
Args:
windows: (B,1,L) float32,原始采样率下的数据
sampling_rate_hz: 原始采样率;为 None 或 100 时直接返回
Returns:
(B,1,3000) float32
"""
if sampling_rate_hz is None:
return windows
try:
src_hz = float(sampling_rate_hz)
except (TypeError, ValueError):
raise ValidationError(f"非法的 sampling_rate_hz:{sampling_rate_hz}")
if src_hz == PPG_CHD_SAMPLING_RATE_HZ:
return windows
if src_hz <= 0:
raise ValidationError(f"非法的 sampling_rate_hz:{sampling_rate_hz}")
try:
from scipy import signal as scipy_signal
except ImportError:
raise BusinessError("需要 scipy 才能重采样到 100Hz", code=500)
target_len = PPG_CHD_SIGNAL_LEN
resampled = scipy_signal.resample(windows, target_len, axis=-1)
return np.ascontiguousarray(resampled, dtype=np.float32)
def chd_probs_to_two_class(window_probs: np.ndarray) -> np.ndarray:
"""将 CHD 窗口概率 [N] 转为二分类概率矩阵 [N,2]。
保持下游(均值聚合/argmax/positive 计数/诊断映射)逻辑不变:
第 0 列为 negative 概率,第 1 列为 positive(CHD)概率。
"""
w = np.asarray(window_probs).reshape(-1).astype(np.float64)
w = np.clip(w, 0.0, 1.0)
return np.stack([1.0 - w, w], axis=1).astype(np.float32)
class AdaptivePatientDataset:
"""
自适应患者数据集 - 与 inference.py 的 AdaptivePatientDataset 一致
@@ -626,6 +698,17 @@ def _execute_inference(app, task_uuid):
model_inputs = session.get_inputs()
has_channel_mask = any(i.name == 'channel_mask' for i in model_inputs)
# PPG CHD 模型分支:按 ONNX 签名检测,后续走固定契约
#(3000 点单通道窗、1D 概率输出、阈值 0.5),任务参数中的
# signal_len/stride/threshold 对该模型不生效。
is_chd = is_ppg_chd_session(session)
if is_chd:
logger.info(
"检测到 PPG CHD 模型签名([N,1,3000]->[N]),"
f"强制 signal_len={PPG_CHD_SIGNAL_LEN} stride={PPG_CHD_STRIDE} "
f"threshold={PPG_CHD_THRESHOLD}"
)
total_patients = len(patient_ids)
recovery_info = queue_manager.get_recovery_info(task)
@@ -729,7 +812,22 @@ def _execute_inference(app, task_uuid):
logger.info(f"[{idx}/{total_patients}] 找到 {len(pkl_files)} 个 PKL 文件")
dataset = AdaptivePatientDataset(pkl_files, signal_len=args.get('signal_len', DEFAULT_SIGNAL_LEN), stride=args.get('stride', DEFAULT_STRIDE))
if is_chd:
req_len = args.get('signal_len', PPG_CHD_SIGNAL_LEN)
req_stride = args.get('stride', PPG_CHD_STRIDE)
if req_len != PPG_CHD_SIGNAL_LEN or req_stride != PPG_CHD_STRIDE:
logger.warning(
f"[{idx}/{total_patients}] CHD 模型固定使用 "
f"signal_len={PPG_CHD_SIGNAL_LEN} stride={PPG_CHD_STRIDE},"
f"忽略任务参数 signal_len={req_len} stride={req_stride}"
)
dataset = AdaptivePatientDataset(
pkl_files,
signal_len=PPG_CHD_SIGNAL_LEN,
stride=PPG_CHD_STRIDE,
)
else:
dataset = AdaptivePatientDataset(pkl_files, signal_len=args.get('signal_len', DEFAULT_SIGNAL_LEN), stride=args.get('stride', DEFAULT_STRIDE))
if len(dataset) == 0:
logger.warning(f"[{idx}/{total_patients}] 无有效数据段:{patient_id}")
@@ -749,8 +847,12 @@ def _execute_inference(app, task_uuid):
logger.info(f"[{idx}/{total_patients}] 有效数据段数量:{len(dataset)}")
all_probs = []
# 使用队列管理器的动态 batch_size,上限 32 防止内存溢出
effective_batch_size = min(args.get('batch_size') or get_batch_size(), 32)
# 使用队列管理器的动态 batch_size,上限 32 防止内存溢出;
# CHD 模型每窗口=3 张 224 图过 ConvNeXt,窗口 batch 上限收紧到 8。
if is_chd:
effective_batch_size = min(args.get('batch_size') or get_batch_size(), PPG_CHD_WINDOW_BATCH)
else:
effective_batch_size = min(args.get('batch_size') or get_batch_size(), 32)
total_batches = (len(dataset) + effective_batch_size - 1) // effective_batch_size
def numpy_data_loader(dataset, batch_size):
@@ -786,21 +888,37 @@ def _execute_inference(app, task_uuid):
x, modality_ids, y, channel_mask = batch
x = x.astype(np.float32)
ort_inputs = {input_name: x}
if has_channel_mask:
ort_inputs['channel_mask'] = channel_mask.astype(np.int64)
if is_chd:
# CHD:单通道 PPG,取第 0 通道;非 100Hz 时按任务参数重采样。
if x.shape[1] != 1:
logger.warning(
f"[{idx}/{total_patients}] CHD 模型只使用第 0 通道 "
f"(当前 batch 通道数={x.shape[1]})"
)
x_chd = np.ascontiguousarray(x[:, 0:1, :], dtype=np.float32)
x_chd = resample_windows_to_100hz(
x_chd, args.get('sampling_rate_hz')
)
outputs = session.run(None, {input_name: x_chd})
# 已 sigmoid 的窗口概率 [N] -> 二分类矩阵 [N,2],
# 后续均值聚合/argmax/诊断映射与老链路共用。
probs = chd_probs_to_two_class(outputs[0])
else:
ort_inputs = {input_name: x}
if has_channel_mask:
ort_inputs['channel_mask'] = channel_mask.astype(np.int64)
outputs = session.run(None, ort_inputs)
probs = outputs[0]
outputs = session.run(None, ort_inputs)
probs = outputs[0]
if probs.shape[1] > 1 and not np.allclose(np.sum(probs, axis=1), 1.0, atol=1e-5):
# 使用 scipy softmax 或 numpy 备用实现
if HAS_SCIPY and softmax:
probs = softmax(probs, axis=1)
else:
# numpy softmax 备用实现
probs_max = np.max(probs, axis=1, keepdims=True)
probs = np.exp(probs - probs_max) / np.sum(np.exp(probs - probs_max), axis=1, keepdims=True)
if probs.ndim == 2 and probs.shape[1] > 1 and not np.allclose(np.sum(probs, axis=1), 1.0, atol=1e-5):
# 使用 scipy softmax 或 numpy 备用实现
if HAS_SCIPY and softmax:
probs = softmax(probs, axis=1)
else:
# numpy softmax 备用实现
probs_max = np.max(probs, axis=1, keepdims=True)
probs = np.exp(probs - probs_max) / np.sum(np.exp(probs - probs_max), axis=1, keepdims=True)
all_probs.append(probs)
@@ -1409,6 +1527,8 @@ def run_inference_service(patient_ids, model_path, inference_params, user_id):
'fallback_top_k': inference_params.get('fallback_top_k', DEFAULT_FALLBACK_TOP_K),
'trim_ratio': inference_params.get('trim_ratio', DEFAULT_TRIM_RATIO),
'iqr_scale': inference_params.get('iqr_scale', DEFAULT_IQR_SCALE),
# CHD 模型用:原始采样率(Hz),非 100Hz 时自动重采样;None 表示已是 100Hz
'sampling_rate_hz': inference_params.get('sampling_rate_hz'),
},
progress={
'current_patient': 0,
@@ -593,12 +593,22 @@ def test_model_output(model_path: str, upload_folder: str) -> dict:
input_shape = inputs[0].shape
output_shape = outputs[0].shape
example_input = np.random.randn(*input_shape).astype(np.float32)
def _resolve_dim(dim, default=1):
# ONNX 符号维(batch 等)可能是 str 或 None,用具体值代替
return dim if isinstance(dim, int) and dim > 0 else default
concrete_shape = [_resolve_dim(d) for d in input_shape]
example_input = np.random.randn(*concrete_shape).astype(np.float32)
result = session.run([output_name], {input_name: example_input})
output_data = result[0]
num_classes = 1
if len(output_data.shape) >= 2:
output_kind = "logits"
if len(output_data.shape) == 1:
# 单概率输出(如 PPG CHD 模型 [N]):二分类单 logit
num_classes = 2
output_kind = "binary_single_probability"
elif len(output_data.shape) >= 2:
num_classes = output_data.shape[-1]
elif len(output_shape) >= 2:
num_classes = output_shape[-1] if isinstance(output_shape[-1], int) else 2
@@ -609,10 +619,14 @@ def test_model_output(model_path: str, upload_folder: str) -> dict:
else:
sample_output = output_data.flatten().tolist()[:10]
def _shape_to_list(shape):
return [d if isinstance(d, int) else str(d) for d in shape]
return {
"num_classes": num_classes,
"output_shape": list(output_shape) if isinstance(output_shape, tuple) else output_shape,
"input_shape": list(input_shape) if isinstance(input_shape, tuple) else input_shape,
"output_kind": output_kind,
"output_shape": _shape_to_list(output_shape),
"input_shape": _shape_to_list(input_shape),
"sample_output": sample_output,
}
@@ -9,6 +9,7 @@ from contextlib import contextmanager
from flask import current_app
from sqlalchemy import and_, or_, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import StaleDataError
from .. import db
-68
View File
@@ -1,68 +0,0 @@
#!/usr/bin/env python
"""
检查数据库中的文件夹记录
用法:
python check_folders.py
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dotenv import load_dotenv
load_dotenv()
import pymysql
# 数据库配置
DB_HOST = os.environ.get('DB_HOST', 'localhost')
DB_USER = os.environ.get('DB_USER', 'root')
DB_PASSWORD = os.environ.get('DB_PASSWORD', '')
DB_NAME = os.environ.get('DB_NAME', 'rct')
print(f"连接数据库:{DB_HOST}/{DB_NAME}")
try:
conn = pymysql.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME,
charset='utf8mb4'
)
cursor = conn.cursor()
# 检查 raw_data_folder 表结构
print("\n=== raw_data_folder 表结构 ===")
cursor.execute("DESCRIBE raw_data_folder")
for row in cursor.fetchall():
print(row)
# 检查前 20 条记录(使用参数化查询)
print("\n=== 前 20 条文件夹记录 ===")
cursor.execute("SELECT id, folder_name, status FROM raw_data_folder LIMIT %s", (20,))
for row in cursor.fetchall():
print(f" ID={row[0]}, folder_name={row[1]}, status={row[2]}")
# 检查是否有 folder_name 为纯数字的记录(使用参数化查询)
print("\n=== folder_name 为纯数字的记录 ===")
cursor.execute("SELECT id, folder_name, status FROM raw_data_folder WHERE folder_name REGEXP '^[0-9]+$' LIMIT %s", (20,))
for row in cursor.fetchall():
print(f" ID={row[0]}, folder_name={row[1]}, status={row[2]}")
# 统计总数
print("\n=== 统计信息 ===")
cursor.execute("SELECT COUNT(*) FROM raw_data_folder")
print(f" 总记录数:{cursor.fetchone()[0]}")
cursor.execute("SELECT COUNT(*) FROM raw_data_folder WHERE folder_name REGEXP '^[0-9]+$'")
print(f" folder_name 为纯数字的记录数:{cursor.fetchone()[0]}")
cursor.close()
conn.close()
except Exception as e:
print(f"错误:{e}")
import traceback
traceback.print_exc()
-314
View File
@@ -1,314 +0,0 @@
"""
清理所有推理任务脚本
用于清理所有推理任务(包括 queued、running、completed、failed 状态)
警告:此操作不可逆,请谨慎使用!
"""
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 从环境变量读取配置,默认为 'default'
config_name = os.environ.get('FLASK_CONFIG', 'default')
from app import create_app, db
from app.models import InferenceTask, InferenceTaskResult
from datetime import datetime
def cleanup_all_tasks(confirm=True):
"""
清理所有推理任务及关联的结果
Args:
confirm: 是否需要确认
"""
app = create_app(config_name)
with app.app_context():
# 统计各状态任务数量
all_tasks = InferenceTask.query.all()
status_count = {}
for task in all_tasks:
status_count[task.status] = status_count.get(task.status, 0) + 1
print("=" * 60)
print("推理任务清理脚本")
print("=" * 60)
print(f"\n当前数据库中任务统计:")
print(f" 总任务数:{len(all_tasks)}")
for status, count in sorted(status_count.items()):
print(f" - {status}: {count} 个")
# 统计关联的结果数量
result_count = InferenceTaskResult.query.count()
print(f"\n关联的推理结果数:{result_count}")
if confirm:
print("\n" + "!" * 60)
print("警告:此操作将删除所有推理任务和结果,且不可恢复!")
print("!" * 60)
confirm_text = input(f"\n请输入 'YES' 确认清理所有任务:")
if confirm_text != 'YES':
print("已取消操作")
return
print("\n开始清理...")
# 先删除关联的结果(外键约束)
print("正在删除推理结果...")
deleted_results = 0
batch_size = 1000
while True:
results = InferenceTaskResult.query.limit(batch_size).all()
if not results:
break
for r in results:
db.session.delete(r)
db.session.commit()
deleted_results += len(results)
print(f" 已删除 {deleted_results} 条结果...")
# 删除所有任务
print("正在删除推理任务...")
deleted_tasks = 0
for task in all_tasks:
db.session.delete(task)
deleted_tasks += 1
if deleted_tasks % 100 == 0:
print(f" 已删除 {deleted_tasks} 个任务...")
db.session.commit()
print("\n" + "=" * 60)
print("清理完成!")
print(f" - 删除任务数:{deleted_tasks}")
print(f" - 删除结果数:{deleted_results}")
print("=" * 60)
def cleanup_by_status(status_list, confirm=True):
"""
按状态清理任务
Args:
status_list: 要清理的状态列表,如 ['queued', 'running']
confirm: 是否需要确认
"""
app = create_app(config_name)
with app.app_context():
# 查询指定状态的任务
tasks = InferenceTask.query.filter(InferenceTask.status.in_(status_list)).all()
print("=" * 60)
print("按状态清理推理任务")
print("=" * 60)
print(f"\n将清理以下状态的任务:{', '.join(status_list)}")
print(f" 任务数量:{len(tasks)}")
# 统计关联的结果数量
task_ids = [t.id for t in tasks]
results = InferenceTaskResult.query.filter(
InferenceTaskResult.task_id.in_(task_ids)
).all()
print(f" 关联结果数:{len(results)}")
if confirm:
confirm_text = input(f"\n请输入 'YES' 确认清理:")
if confirm_text != 'YES':
print("已取消操作")
return
print("\n开始清理...")
# 先删除关联的结果
deleted_results = 0
for result in results:
db.session.delete(result)
deleted_results += 1
# 删除任务
deleted_tasks = 0
for task in tasks:
db.session.delete(task)
deleted_tasks += 1
db.session.commit()
print("\n" + "=" * 60)
print("清理完成!")
print(f" - 删除任务数:{deleted_tasks}")
print(f" - 删除结果数:{deleted_results}")
print("=" * 60)
def cleanup_old_tasks(days_threshold=30, confirm=True):
"""
清理超过指定天数的历史任务
Args:
days_threshold: 超过多少天的任务视为历史任务
confirm: 是否需要确认
"""
app = create_app(config_name)
with app.app_context():
from datetime import datetime, timedelta
threshold = datetime.utcnow() - timedelta(days=days_threshold)
# 查询超过阈值的任务
old_tasks = InferenceTask.query.filter(
InferenceTask.created_at < threshold
).all()
print("=" * 60)
print(f"清理 {days_threshold} 天前的历史任务")
print("=" * 60)
print(f"\n将清理 {days_threshold} 天前的任务")
print(f" 阈值日期:{threshold.strftime('%Y-%m-%d %H:%M:%S')}")
print(f" 任务数量:{len(old_tasks)}")
# 统计关联的结果数量
task_ids = [t.id for t in old_tasks]
results = InferenceTaskResult.query.filter(
InferenceTaskResult.task_id.in_(task_ids)
).all()
print(f" 关联结果数:{len(results)}")
if confirm:
confirm_text = input(f"\n请输入 'YES' 确认清理:")
if confirm_text != 'YES':
print("已取消操作")
return
print("\n开始清理...")
# 先删除关联的结果
deleted_results = 0
for result in results:
db.session.delete(result)
deleted_results += 1
# 删除任务
deleted_tasks = 0
for task in old_tasks:
db.session.delete(task)
deleted_tasks += 1
db.session.commit()
print("\n" + "=" * 60)
print("清理完成!")
print(f" - 删除任务数:{deleted_tasks}")
print(f" - 删除结果数:{deleted_results}")
print("=" * 60)
def show_task_list():
"""
显示当前所有任务列表(不执行删除)
"""
app = create_app(config_name)
with app.app_context():
tasks = InferenceTask.query.order_by(InferenceTask.created_at.desc()).limit(50).all()
print("=" * 80)
print("当前推理任务列表(最近 50 条)")
print("=" * 80)
print(f"{'任务 UUID':<40} {'状态':<12} {'创建时间':<22} {'患者数':<8}")
print("-" * 80)
for task in tasks:
patient_count = len(task.folders)
created = task.created_at.strftime('%Y-%m-%d %H:%M:%S') if task.created_at else 'N/A'
print(f"{task.task_uuid:<40} {task.status:<12} {created:<22} {patient_count:<8}")
print("-" * 80)
# 统计总数
total = InferenceTask.query.count()
print(f"总任务数:{total}")
if __name__ == '__main__':
if len(sys.argv) < 2:
print("""
推理任务清理脚本
用法:
python cleanup_all_inference_tasks.py <命令> [选项]
命令:
all 清理所有任务(包括 queued/running/completed/failed)
status <状态> 清理指定状态的任务(如:queued, running, completed, failed)
old [天数] 清理超过指定天数的历史任务(默认 30 天)
list 显示当前任务列表(不执行删除)
help 显示帮助信息
示例:
python cleanup_all_inference_tasks.py all # 清理所有任务
python cleanup_all_inference_tasks.py status queued # 清理所有排队中的任务
python cleanup_all_inference_tasks.py old 7 # 清理 7 天前的任务
python cleanup_all_inference_tasks.py list # 查看任务列表
""")
sys.exit(0)
command = sys.argv[1].lower()
if command == 'all':
cleanup_all_tasks(confirm=True)
elif command == 'status':
if len(sys.argv) < 3:
print("错误:请指定要清理的状态(queued/running/completed/failed)")
sys.exit(1)
status = sys.argv[2].lower()
valid_statuses = ['queued', 'running', 'completed', 'failed']
if status not in valid_statuses:
print(f"错误:无效的状态 '{status}',有效状态:{', '.join(valid_statuses)}")
sys.exit(1)
cleanup_by_status([status], confirm=True)
elif command == 'old':
days = 30
if len(sys.argv) >= 3:
try:
days = int(sys.argv[2])
except ValueError:
print("错误:天数必须是整数")
sys.exit(1)
cleanup_old_tasks(days_threshold=days, confirm=True)
elif command == 'list':
show_task_list()
elif command == 'help':
print("""
推理任务清理脚本
用法:
python cleanup_all_inference_tasks.py <命令> [选项]
命令:
all 清理所有任务(包括 queued/running/completed/failed)
status <状态> 清理指定状态的任务(如:queued, running, completed, failed)
old [天数] 清理超过指定天数的历史任务(默认 30 天)
list 显示当前任务列表(不执行删除)
help 显示帮助信息
示例:
python cleanup_all_inference_tasks.py all # 清理所有任务
python cleanup_all_inference_tasks.py status queued # 清理所有排队中的任务
python cleanup_all_inference_tasks.py old 7 # 清理 7 天前的任务
python cleanup_all_inference_tasks.py list # 查看任务列表
""")
else:
print(f"错误:未知命令 '{command}'")
print("使用 'python cleanup_all_inference_tasks.py help' 查看帮助")
sys.exit(1)
-463
View File
@@ -1,463 +0,0 @@
#!/usr/bin/env python
"""
滤波任务清理脚本
用于清理已完成、失败或超时的滤波任务,包括:
- ZipFilterTask 记录
- ProcessingJob 记录
- ProcessedFileLog 记录
- 可选:清理滤波后的文件
用法:
python cleanup_filter_tasks.py [选项]
示例:
# 干跑模式(预览清理结果)
python cleanup_filter_tasks.py --dry-run
# 清理完成超过 24 小时的任务
python cleanup_filter_tasks.py --status completed --hours 24
# 清理失败的任务
python cleanup_filter_tasks.py --status failed
# 清理指定文件夹的任务
python cleanup_filter_tasks.py --folder patient_001
# 清理所有已完成任务(包括文件)
python cleanup_filter_tasks.py --status completed --remove-files
# 清理超时任务(心跳超过 10 分钟无更新)
python cleanup_filter_tasks.py --timeout
"""
import os
import sys
import argparse
import logging
from datetime import datetime, timedelta
from typing import List, Tuple, Optional
# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app import create_app, db
from app.models import ZipFilterTask, ProcessingJob, ProcessedFileLog, RawDataFolder
from config import Config
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('cleanup_filter_tasks.log', encoding='utf-8')
]
)
logger = logging.getLogger(__name__)
class FilterTaskCleaner:
"""滤波任务清理器"""
def __init__(self, dry_run: bool = False, remove_files: bool = False):
"""
初始化清理器
Args:
dry_run: 干跑模式,不实际执行删除
remove_files: 是否删除滤波后的文件
"""
self.dry_run = dry_run
self.remove_files = remove_files
self.stats = {
'zip_tasks_deleted': 0,
'processing_jobs_deleted': 0,
'processed_files_deleted': 0,
'files_deleted': 0,
'errors': 0
}
def cleanup_by_status(self, status: str, hours: Optional[int] = None) -> Tuple[int, int, int]:
"""
清理指定状态的任务
Args:
status: 任务状态 (completed, failed, cancelled, stopped)
hours: 可选,只清理完成超过指定小时数的任务
Returns:
(zip_tasks_count, processing_jobs_count, processed_files_count)
"""
logger.info(f"开始清理状态为 '{status}' 的任务{',完成时间超过 ' + str(hours) + ' 小时' if hours else ''}")
# 构建查询条件
query = ZipFilterTask.query.filter(ZipFilterTask.status == status)
# 如果指定了小时数,添加时间条件
if hours:
cutoff_time = datetime.utcnow() - timedelta(hours=hours)
query = query.filter(ZipFilterTask.completed_at < cutoff_time)
zip_tasks = query.all()
logger.info(f"找到 {len(zip_tasks)} 个符合条件的 ZipFilterTask")
for task in zip_tasks:
self._delete_zip_task(task)
# 清理没有关联任务的 ProcessingJob
if hours:
cutoff_time = datetime.utcnow() - timedelta(hours=hours)
jobs = ProcessingJob.query.filter(
ProcessingJob.status == status,
ProcessingJob.completed_at < cutoff_time
).all()
else:
jobs = ProcessingJob.query.filter(ProcessingJob.status == status).all()
logger.info(f"找到 {len(jobs)} 个符合条件的 ProcessingJob")
for job in jobs:
self._delete_processing_job(job)
self._log_stats()
return (
self.stats['zip_tasks_deleted'],
self.stats['processing_jobs_deleted'],
self.stats['processed_files_deleted']
)
def cleanup_by_folder(self, folder_name: str) -> Tuple[int, int, int]:
"""
清理指定文件夹的所有滤波任务
Args:
folder_name: 文件夹名称(患者 ID)
Returns:
(zip_tasks_count, processing_jobs_count, processed_files_count)
"""
logger.info(f"开始清理文件夹 '{folder_name}' 的所有滤波任务")
# 查找文件夹
folder = RawDataFolder.query.filter(
RawDataFolder.folder_name == folder_name
).first()
if not folder:
logger.warning(f"文件夹 '{folder_name}' 不存在")
return (0, 0, 0)
# 清理关联的 ZipFilterTask
zip_tasks = ZipFilterTask.query.filter(
ZipFilterTask.folder_id == folder.id
).all()
logger.info(f"找到 {len(zip_tasks)} 个 ZipFilterTask")
for task in zip_tasks:
self._delete_zip_task(task)
# 清理关联的 ProcessingJob
jobs = ProcessingJob.query.filter(
ProcessingJob.folder_id == folder.id
).all()
logger.info(f"找到 {len(jobs)} 个 ProcessingJob")
for job in jobs:
self._delete_processing_job(job)
# 清理关联的 ProcessedFileLog
file_logs = ProcessedFileLog.query.join(ProcessingJob).filter(
ProcessingJob.folder_id == folder.id
).all()
logger.info(f"找到 {len(file_logs)} 个 ProcessedFileLog")
for file_log in file_logs:
if not self.dry_run:
db.session.delete(file_log)
self.stats['processed_files_deleted'] += 1
# 可选:删除滤波后的文件
if self.remove_files:
self._delete_folder_files(folder.folder_name)
if not self.dry_run:
db.session.commit()
self._log_stats()
return (
self.stats['zip_tasks_deleted'],
self.stats['processing_jobs_deleted'],
self.stats['processed_files_deleted']
)
def cleanup_timeout_tasks(self, timeout_minutes: int = 10) -> int:
"""
清理超时任务(心跳超时)
Args:
timeout_minutes: 超时时间(分钟)
Returns:
恢复的任务数量
"""
logger.info(f"开始清理超时任务(超时阈值:{timeout_minutes} 分钟)")
cutoff_time = datetime.utcnow() - timedelta(minutes=timeout_minutes)
# 查找超时的 running 状态任务
timeout_tasks = ZipFilterTask.query.filter(
ZipFilterTask.status == 'running',
ZipFilterTask.heartbeat < cutoff_time
).all()
logger.info(f"找到 {len(timeout_tasks)} 个超时任务")
recovered_count = 0
for task in timeout_tasks:
if task.retry_count < 3: # 最多重试 3 次
logger.info(f"恢复超时任务:{task.zip_filename} (重试次数:{task.retry_count})")
if not self.dry_run:
task.status = 'queued'
task.heartbeat = datetime.utcnow()
task.retry_count += 1
task.error_message = f"任务超时,自动恢复(重试 {task.retry_count}/3)"
recovered_count += 1
else:
logger.warning(f"任务 {task.zip_filename} 已达到最大重试次数,标记为失败")
if not self.dry_run:
task.status = 'failed'
task.error_message = "任务超时,已达到最大重试次数"
if not self.dry_run:
db.session.commit()
logger.info(f"恢复了 {recovered_count} 个任务,标记失败 {len(timeout_tasks) - recovered_count} 个")
return recovered_count
def cleanup_all_completed(self, remove_files: bool = False) -> Tuple[int, int, int]:
"""
清理所有已完成的任务(包括 completed, failed, cancelled, stopped)
Args:
remove_files: 是否删除滤波后的文件
Returns:
(zip_tasks_count, processing_jobs_count, files_count)
"""
self.remove_files = remove_files
total_zip = 0
total_jobs = 0
total_files = 0
for status in ['completed', 'failed', 'cancelled', 'stopped']:
logger.info(f"--- 清理 '{status}' 状态的任务 ---")
zip_count, job_count, file_count = self.cleanup_by_status(status)
total_zip += zip_count
total_jobs += job_count
total_files += file_count
logger.info(f"总计清理:{total_zip} 个 ZipFilterTask, {total_jobs} 个 ProcessingJob, {total_files} 个 ProcessedFileLog")
return (total_zip, total_jobs, total_files)
def _delete_zip_task(self, task: ZipFilterTask):
"""删除单个 ZipFilterTask"""
try:
logger.debug(f"删除 ZipFilterTask: {task.zip_filename} (状态:{task.status})")
if not self.dry_run:
db.session.delete(task)
self.stats['zip_tasks_deleted'] += 1
except Exception as e:
logger.error(f"删除 ZipFilterTask 失败:{task.zip_filename}, 错误:{e}")
self.stats['errors'] += 1
def _delete_processing_job(self, job: ProcessingJob):
"""删除单个 ProcessingJob"""
try:
logger.debug(f"删除 ProcessingJob: {job.id} (状态:{job.status})")
# 先删除关联的 ProcessedFileLog
file_logs = ProcessedFileLog.query.filter(
ProcessedFileLog.job_id == job.id
).all()
for file_log in file_logs:
if not self.dry_run:
db.session.delete(file_log)
self.stats['processed_files_deleted'] += 1
if not self.dry_run:
db.session.delete(job)
self.stats['processing_jobs_deleted'] += 1
except Exception as e:
logger.error(f"删除 ProcessingJob 失败:{job.id}, 错误:{e}")
self.stats['errors'] += 1
def _delete_folder_files(self, folder_name: str):
"""删除指定文件夹的滤波后文件"""
try:
from config import PROCESSED_DATA_OUTPUT_FOLDER
folder_path = os.path.join(PROCESSED_DATA_OUTPUT_FOLDER, folder_name)
if not os.path.exists(folder_path):
logger.info(f"文件夹不存在:{folder_path}")
return
# 统计文件数量
files = []
for root, dirs, filenames in os.walk(folder_path):
for filename in filenames:
if filename.endswith('_filtered.csv') or filename.endswith('_processed.pkl'):
files.append(os.path.join(root, filename))
logger.info(f"找到 {len(files)} 个滤波后文件")
# 删除文件
for file_path in files:
try:
if not self.dry_run:
os.remove(file_path)
logger.debug(f"删除文件:{file_path}")
self.stats['files_deleted'] += 1
except Exception as e:
logger.error(f"删除文件失败:{file_path}, 错误:{e}")
self.stats['errors'] += 1
# 如果文件夹为空,删除文件夹
if not self.dry_run and files:
try:
if not os.listdir(folder_path):
os.rmdir(folder_path)
logger.info(f"删除空文件夹:{folder_path}")
except Exception as e:
logger.error(f"删除文件夹失败:{folder_path}, 错误:{e}")
except Exception as e:
logger.error(f"删除文件夹文件失败:{folder_name}, 错误:{e}")
self.stats['errors'] += 1
def _log_stats(self):
"""记录统计信息"""
if self.dry_run:
logger.info("=== 干跑模式 - 预览统计 ===")
else:
logger.info("=== 清理完成统计 ===")
logger.info(f" ZipFilterTask 删除:{self.stats['zip_tasks_deleted']}")
logger.info(f" ProcessingJob 删除:{self.stats['processing_jobs_deleted']}")
logger.info(f" ProcessedFileLog 删除:{self.stats['processed_files_deleted']}")
if self.remove_files:
logger.info(f" 物理文件删除:{self.stats['files_deleted']}")
if self.stats['errors'] > 0:
logger.warning(f" 错误数量:{self.stats['errors']}")
def main():
"""主函数"""
parser = argparse.ArgumentParser(
description='滤波任务清理脚本',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__
)
parser.add_argument(
'--dry-run',
action='store_true',
help='干跑模式,只预览不实际执行删除'
)
parser.add_argument(
'--status',
type=str,
choices=['completed', 'failed', 'cancelled', 'stopped'],
help='要清理的任务状态'
)
parser.add_argument(
'--hours',
type=int,
help='只清理完成超过指定小时数的任务'
)
parser.add_argument(
'--folder',
type=str,
help='指定要清理的文件夹名称(患者 ID)'
)
parser.add_argument(
'--timeout',
action='store_true',
help='清理超时任务(恢复为 queued 状态或标记为 failed)'
)
parser.add_argument(
'--timeout-minutes',
type=int,
default=10,
help='超时阈值(分钟),默认 10 分钟'
)
parser.add_argument(
'--all-completed',
action='store_true',
help='清理所有已完成的任务(completed, failed, cancelled, stopped)'
)
parser.add_argument(
'--remove-files',
action='store_true',
help='删除滤波后的文件(*_filtered.csv, *_processed.pkl)'
)
parser.add_argument(
'--verbose', '-v',
action='store_true',
help='显示详细日志'
)
args = parser.parse_args()
# 设置日志级别
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
# 创建应用上下文
app = create_app('default')
with app.app_context():
cleaner = FilterTaskCleaner(
dry_run=args.dry_run,
remove_files=args.remove_files
)
if args.all_completed:
cleaner.cleanup_all_completed(remove_files=args.remove_files)
elif args.folder:
cleaner.cleanup_by_folder(args.folder)
elif args.timeout:
cleaner.cleanup_timeout_tasks(timeout_minutes=args.timeout_minutes)
elif args.status:
cleaner.cleanup_by_status(args.status, hours=args.hours)
else:
logger.warning("未指定清理模式,使用 --help 查看用法")
parser.print_help()
sys.exit(1)
if __name__ == '__main__':
main()
-430
View File
@@ -1,430 +0,0 @@
#!/usr/bin/env python
"""
滤波任务清理脚本(简化版)
不依赖 torch 等重型依赖,直接使用 SQLAlchemy 操作数据库
用法:
python cleanup_filter_tasks_simple.py [选项]
示例:
# 干跑模式(预览清理结果)
python cleanup_filter_tasks_simple.py --dry-run
# 清理完成超过 24 小时的任务
python cleanup_filter_tasks_simple.py --status completed --hours 24
# 清理失败的任务
python cleanup_filter_tasks_simple.py --status failed
# 清理所有已完成任务
python cleanup_filter_tasks_simple.py --all-completed
"""
import os
import sys
import argparse
import logging
from datetime import datetime, timedelta
from typing import List, Tuple, Optional
# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dotenv import load_dotenv
load_dotenv()
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('cleanup_filter_tasks.log', encoding='utf-8')
]
)
logger = logging.getLogger(__name__)
class DatabaseManager:
"""数据库管理器(简化版,避免导入重型依赖)"""
def __init__(self):
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
# 获取数据库 URL
db_url = os.environ.get('DATABASE_URL')
if not db_url:
DB_HOST = os.environ.get('DB_HOST', 'localhost')
DB_USER = os.environ.get('DB_USER', 'root')
DB_PASSWORD = os.environ.get('DB_PASSWORD', '')
DB_NAME = os.environ.get('DB_NAME', 'rct')
db_url = f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}?charset=utf8mb4"
logger.info(f"连接数据库:{db_url}")
# 创建引擎
self.engine = create_engine(
db_url,
pool_size=10,
pool_recycle=3600,
pool_pre_ping=True
)
# 创建会话
session_factory = sessionmaker(bind=self.engine)
self.Session = scoped_session(session_factory)
# 定义模型
Base = declarative_base()
# 定义表模型
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey, Index
class ZipFilterTask(Base):
__tablename__ = 'zip_filter_task'
id = Column(Integer, primary_key=True)
folder_id = Column(Integer, ForeignKey('raw_data_folder.id'), nullable=False, index=True)
job_id = Column(Integer, ForeignKey('processing_job.id'), nullable=True, index=True)
zip_filename = Column(String(255), nullable=False, index=True)
status = Column(String(50), default='queued', nullable=False, index=True)
created_at = Column(DateTime, default=datetime.utcnow, index=True)
started_at = Column(DateTime, nullable=True)
completed_at = Column(DateTime, nullable=True)
heartbeat = Column(DateTime, nullable=True, index=True)
error_message = Column(Text, nullable=True)
files_processed = Column(Integer, default=0)
segments_created = Column(Integer, default=0)
retry_count = Column(Integer, default=0)
cancelled = Column(Boolean, default=False, index=True)
__table_args__ = (
Index('idx_zip_status', 'status', 'completed_at'),
)
class ProcessingJob(Base):
__tablename__ = 'processing_job'
id = Column(Integer, primary_key=True)
folder_id = Column(Integer, ForeignKey('raw_data_folder.id'), nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
start_time = Column(DateTime, default=datetime.utcnow)
end_time = Column(DateTime, nullable=True)
completed_at = Column(DateTime, nullable=True)
status = Column(String(50), default='queued', nullable=False, index=True)
log = Column(Text, nullable=True)
heartbeat = Column(DateTime, nullable=True, index=True)
error_message = Column(Text, nullable=True)
class ProcessedFileLog(Base):
__tablename__ = 'processed_file_log'
id = Column(Integer, primary_key=True)
job_id = Column(Integer, ForeignKey('processing_job.id'), nullable=False)
zip_filename = Column(String(255), nullable=False)
processed_at = Column(DateTime, default=datetime.utcnow)
class RawDataFolder(Base):
__tablename__ = 'raw_data_folder'
id = Column(Integer, primary_key=True)
folder_name = Column(String(255), nullable=False, index=True)
self.ZipFilterTask = ZipFilterTask
self.ProcessingJob = ProcessingJob
self.ProcessedFileLog = ProcessedFileLog
self.RawDataFolder = RawDataFolder
def get_session(self):
return self.Session()
class FilterTaskCleaner:
"""滤波任务清理器"""
def __init__(self, db_manager: DatabaseManager, dry_run: bool = False, remove_files: bool = False):
self.db = db_manager
self.dry_run = dry_run
self.remove_files = remove_files
self.stats = {
'zip_tasks_deleted': 0,
'processing_jobs_deleted': 0,
'processed_files_deleted': 0,
'files_deleted': 0,
'errors': 0
}
def cleanup_by_status(self, status: str, hours: Optional[int] = None) -> Tuple[int, int, int]:
"""清理指定状态的任务"""
logger.info(f"开始清理状态为 '{status}' 的任务{',完成时间超过 ' + str(hours) + ' 小时' if hours else ''}")
session = self.db.get_session()
try:
# 查询 ZipFilterTask
query = session.query(self.db.ZipFilterTask).filter(
self.db.ZipFilterTask.status == status
)
if hours:
cutoff_time = datetime.utcnow() - timedelta(hours=hours)
query = query.filter(self.db.ZipFilterTask.completed_at < cutoff_time)
zip_tasks = query.all()
logger.info(f"找到 {len(zip_tasks)} 个符合条件的 ZipFilterTask")
for task in zip_tasks:
self._delete_zip_task(session, task)
# 查询 ProcessingJob
job_query = session.query(self.db.ProcessingJob).filter(
self.db.ProcessingJob.status == status
)
if hours:
job_query = job_query.filter(self.db.ProcessingJob.completed_at < cutoff_time)
jobs = job_query.all()
logger.info(f"找到 {len(jobs)} 个符合条件的 ProcessingJob")
for job in jobs:
self._delete_processing_job(session, job)
if not self.dry_run:
session.commit()
self._log_stats()
return (
self.stats['zip_tasks_deleted'],
self.stats['processing_jobs_deleted'],
self.stats['processed_files_deleted']
)
except Exception as e:
if not self.dry_run:
session.rollback()
logger.error(f"清理失败:{e}")
raise
finally:
session.close()
def cleanup_by_folder(self, folder_name: str) -> Tuple[int, int, int]:
"""清理指定文件夹的所有滤波任务"""
logger.info(f"开始清理文件夹 '{folder_name}' 的所有滤波任务")
session = self.db.get_session()
try:
# 查找文件夹
folder = session.query(self.db.RawDataFolder).filter(
self.db.RawDataFolder.folder_name == folder_name
).first()
if not folder:
logger.warning(f"文件夹 '{folder_name}' 不存在")
return (0, 0, 0)
# 清理 ZipFilterTask
zip_tasks = session.query(self.db.ZipFilterTask).filter(
self.db.ZipFilterTask.folder_id == folder.id
).all()
logger.info(f"找到 {len(zip_tasks)} 个 ZipFilterTask")
for task in zip_tasks:
self._delete_zip_task(session, task)
# 清理 ProcessingJob
jobs = session.query(self.db.ProcessingJob).filter(
self.db.ProcessingJob.folder_id == folder.id
).all()
logger.info(f"找到 {len(jobs)} 个 ProcessingJob")
for job in jobs:
self._delete_processing_job(session, job)
if not self.dry_run:
session.commit()
self._log_stats()
return (
self.stats['zip_tasks_deleted'],
self.stats['processing_jobs_deleted'],
self.stats['processed_files_deleted']
)
except Exception as e:
if not self.dry_run:
session.rollback()
logger.error(f"清理失败:{e}")
raise
finally:
session.close()
def cleanup_timeout_tasks(self, timeout_minutes: int = 10) -> int:
"""清理超时任务"""
logger.info(f"开始清理超时任务(超时阈值:{timeout_minutes} 分钟)")
session = self.db.get_session()
try:
cutoff_time = datetime.utcnow() - timedelta(minutes=timeout_minutes)
# 查找超时的 running 状态任务
timeout_tasks = session.query(self.db.ZipFilterTask).filter(
self.db.ZipFilterTask.status == 'running',
self.db.ZipFilterTask.heartbeat < cutoff_time
).all()
logger.info(f"找到 {len(timeout_tasks)} 个超时任务")
recovered_count = 0
for task in timeout_tasks:
if task.retry_count < 3:
logger.info(f"恢复超时任务:{task.zip_filename} (重试次数:{task.retry_count})")
if not self.dry_run:
task.status = 'queued'
task.heartbeat = datetime.utcnow()
task.retry_count += 1
task.error_message = f"任务超时,自动恢复(重试 {task.retry_count}/3)"
recovered_count += 1
else:
logger.warning(f"任务 {task.zip_filename} 已达到最大重试次数,标记为失败")
if not self.dry_run:
task.status = 'failed'
task.error_message = "任务超时,已达到最大重试次数"
if not self.dry_run:
session.commit()
logger.info(f"恢复了 {recovered_count} 个任务,标记失败 {len(timeout_tasks) - recovered_count} 个")
return recovered_count
except Exception as e:
if not self.dry_run:
session.rollback()
logger.error(f"清理失败:{e}")
raise
finally:
session.close()
def cleanup_all_completed(self, remove_files: bool = False) -> Tuple[int, int, int]:
"""清理所有已完成的任务"""
self.remove_files = remove_files
total_zip = 0
total_jobs = 0
total_files = 0
for status in ['completed', 'failed', 'cancelled', 'stopped']:
logger.info(f"--- 清理 '{status}' 状态的任务 ---")
zip_count, job_count, file_count = self.cleanup_by_status(status)
total_zip += zip_count
total_jobs += job_count
total_files += file_count
logger.info(f"总计清理:{total_zip} 个 ZipFilterTask, {total_jobs} 个 ProcessingJob, {total_files} 个 ProcessedFileLog")
return (total_zip, total_jobs, total_files)
def _delete_zip_task(self, session, task):
"""删除单个 ZipFilterTask"""
try:
logger.debug(f"删除 ZipFilterTask: {task.zip_filename} (状态:{task.status})")
if not self.dry_run:
session.delete(task)
self.stats['zip_tasks_deleted'] += 1
except Exception as e:
logger.error(f"删除 ZipFilterTask 失败:{task.zip_filename}, 错误:{e}")
self.stats['errors'] += 1
def _delete_processing_job(self, session, job):
"""删除单个 ProcessingJob"""
try:
logger.debug(f"删除 ProcessingJob: {job.id} (状态:{job.status})")
# 先删除关联的 ProcessedFileLog
file_logs = session.query(self.db.ProcessedFileLog).filter(
self.db.ProcessedFileLog.job_id == job.id
).all()
for file_log in file_logs:
if not self.dry_run:
session.delete(file_log)
self.stats['processed_files_deleted'] += 1
if not self.dry_run:
session.delete(job)
self.stats['processing_jobs_deleted'] += 1
except Exception as e:
logger.error(f"删除 ProcessingJob 失败:{job.id}, 错误:{e}")
self.stats['errors'] += 1
def _log_stats(self):
"""记录统计信息"""
if self.dry_run:
logger.info("=== 干跑模式 - 预览统计 ===")
else:
logger.info("=== 清理完成统计 ===")
logger.info(f" ZipFilterTask 删除:{self.stats['zip_tasks_deleted']}")
logger.info(f" ProcessingJob 删除:{self.stats['processing_jobs_deleted']}")
logger.info(f" ProcessedFileLog 删除:{self.stats['processed_files_deleted']}")
if self.stats['errors'] > 0:
logger.warning(f" 错误数量:{self.stats['errors']}")
def main():
"""主函数"""
parser = argparse.ArgumentParser(
description='滤波任务清理脚本(简化版)',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__
)
parser.add_argument('--dry-run', action='store_true', help='干跑模式,只预览不实际执行删除')
parser.add_argument('--status', type=str, choices=['completed', 'failed', 'cancelled', 'stopped'], help='要清理的任务状态')
parser.add_argument('--hours', type=int, help='只清理完成超过指定小时数的任务')
parser.add_argument('--folder', type=str, help='指定要清理的文件夹名称(患者 ID)')
parser.add_argument('--timeout', action='store_true', help='清理超时任务')
parser.add_argument('--timeout-minutes', type=int, default=10, help='超时阈值(分钟)')
parser.add_argument('--all-completed', action='store_true', help='清理所有已完成的任务')
parser.add_argument('--remove-files', action='store_true', help='删除滤波后的文件')
parser.add_argument('--verbose', '-v', action='store_true', help='显示详细日志')
args = parser.parse_args()
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
try:
db_manager = DatabaseManager()
cleaner = FilterTaskCleaner(db_manager, dry_run=args.dry_run)
if args.all_completed:
cleaner.cleanup_all_completed()
elif args.folder:
cleaner.cleanup_by_folder(args.folder)
elif args.timeout:
cleaner.cleanup_timeout_tasks(timeout_minutes=args.timeout_minutes)
elif args.status:
cleaner.cleanup_by_status(args.status, hours=args.hours)
else:
logger.warning("未指定清理模式,使用 --help 查看用法")
parser.print_help()
sys.exit(1)
except Exception as e:
logger.error(f"脚本执行失败:{e}")
sys.exit(1)
if __name__ == '__main__':
main()
-97
View File
@@ -1,97 +0,0 @@
"""
清理卡住的推理任务脚本
用于清理因服务器重启或异常终止而卡住的历史任务
"""
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 从环境变量读取配置,默认为 'default'
config_name = os.environ.get('FLASK_CONFIG', 'default')
from app import create_app, db
from app.models import InferenceTask, InferenceTaskResult
from datetime import datetime, timedelta
def cleanup_stuck_tasks(days_threshold=3):
"""
清理卡住的任务
Args:
days_threshold: 超过多少天的任务视为卡住
"""
app = create_app(config_name)
with app.app_context():
# 查询超过阈值天数的运行中任务
threshold = datetime.utcnow() - timedelta(days=days_threshold)
stuck_tasks = InferenceTask.query.filter(
InferenceTask.status == 'running',
InferenceTask.created_at < threshold
).all()
if not stuck_tasks:
print(f"没有找到超过 {days_threshold} 天的卡住任务")
return
print(f"找到 {len(stuck_tasks)} 个卡住的任务:")
for task in stuck_tasks:
print(f" - {task.task_uuid}: created_at={task.created_at}, last_heartbeat={task.heartbeat}")
confirm = input(f"\n是否要将这些任务重置为 queued 状态?(y/N): ")
if confirm.lower() != 'y':
print("已取消")
return
# 重置任务状态
for task in stuck_tasks:
task.status = 'queued'
task.heartbeat = datetime.utcnow()
task.error_message = f"Task recovered from stuck state (last heartbeat: {task.heartbeat})"
print(f"已重置任务:{task.task_uuid}")
db.session.commit()
print(f"\n已成功重置 {len(stuck_tasks)} 个任务")
def cleanup_all_running_tasks():
"""
强制清理所有 running 状态的任务(用于紧急情况)
"""
app = create_app(config_name)
with app.app_context():
running_tasks = InferenceTask.query.filter_by(status='running').all()
if not running_tasks:
print("没有正在运行的任务")
return
print(f"找到 {len(running_tasks)} 个 running 状态的任务:")
for task in running_tasks:
print(f" - {task.task_uuid}: created_at={task.created_at}, last_heartbeat={task.heartbeat}")
confirm = input(f"\n是否要将所有 running 任务重置为 queued 状态?(y/N): ")
if confirm.lower() != 'y':
print("已取消")
return
for task in running_tasks:
task.status = 'queued'
task.heartbeat = datetime.utcnow()
print(f"已重置任务:{task.task_uuid}")
db.session.commit()
print(f"\n已成功重置 {len(running_tasks)} 个任务")
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == '--force':
cleanup_all_running_tasks()
else:
cleanup_stuck_tasks()
-71
View File
@@ -1,71 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
创建管理员账号脚本
用户名:admin
密码:password
"""
import os
import sys
os.environ['FLASK_CONFIG'] = 'development'
from app import create_app, db
from app.models import User, Role
app = create_app('development')
try:
with app.app_context():
# 删除旧的 admin 用户
old_admin = User.query.filter_by(username='admin').first()
if old_admin:
db.session.delete(old_admin)
db.session.commit() # 提交删除操作
print('✓ 已删除旧的 admin 用户')
else:
print('旧的 admin 用户不存在')
# 创建新的 admin 用户
print('创建新的 admin 用户...')
admin = User(username='admin', email='admin@example.com')
admin.set_password('password')
admin.is_active_account = True
db.session.add(admin)
db.session.commit() # 先提交用户
print(f'✓ 用户已创建,ID={admin.id}')
# 分配 Administrator 角色
admin_role = Role.query.filter_by(name='Administrator').first()
if not admin_role:
admin_role = Role(name='Administrator', description='System Administrator')
db.session.add(admin_role)
db.session.commit()
print(f'✓ Administrator 角色已创建,ID={admin_role.id}')
else:
print(f'✓ Administrator 角色已存在,ID={admin_role.id}')
# 关联用户和角色
admin.roles.append(admin_role)
db.session.commit()
print(f'✓ 角色已分配')
# 验证
print()
print('=' * 40)
print('管理员账号创建成功!')
print('=' * 40)
print(f'用户名:admin')
print(f'密码:password')
print()
print(f'密码验证:{admin.check_password("password")}')
print(f'是管理员:{admin.is_admin()}')
print(f'拥有角色:{[r.name for r in admin.roles]}')
print('=' * 40)
except Exception as e:
import traceback
print(f'✗ 错误:{e}')
traceback.print_exc()
db.session.rollback()
sys.exit(1)
-10
View File
@@ -1,10 +0,0 @@
import os
from app import create_app
from app.services.config_service import init_default_configs
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
with app.app_context():
print("正在初始化系统默认配置...")
init_default_configs()
print("✓ 配置初始化完成")
-78
View File
@@ -1,78 +0,0 @@
#!/usr/bin/env python3
"""
手动数据库迁移脚本 - 添加推理任务断点恢复字段
使用方法: python manual_migration.py
"""
import sys
import os
from pathlib import Path
# 添加 backend 到 Python 路径
BASE_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(BASE_DIR))
# 加载环境变量
from dotenv import load_dotenv
env_file = BASE_DIR / '.env'
if env_file.exists():
load_dotenv(env_file, override=True)
from app import create_app, db
from sqlalchemy import text
def run_migration():
"""执行数据库迁移"""
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
with app.app_context():
conn = db.engine.connect()
# 检查字段是否已存在
result = conn.execute(text("SHOW COLUMNS FROM inference_task LIKE 'current_patient_index'"))
exists = result.fetchone()
if exists:
print("✓ 字段 'current_patient_index' 已存在,跳过")
else:
print("正在添加字段 'current_patient_index'...")
conn.execute(text("ALTER TABLE inference_task ADD COLUMN current_patient_index INT DEFAULT 0"))
conn.commit()
print("✓ 字段 'current_patient_index' 添加成功")
# 检查 processed_folders 字段
result = conn.execute(text("SHOW COLUMNS FROM inference_task LIKE 'processed_folders'"))
exists = result.fetchone()
if exists:
print("✓ 字段 'processed_folders' 已存在,跳过")
else:
print("正在添加字段 'processed_folders'...")
conn.execute(text("ALTER TABLE inference_task ADD COLUMN processed_folders JSON"))
conn.commit()
print("✓ 字段 'processed_folders' 添加成功")
# 检查 last_checkpoint_at 字段
result = conn.execute(text("SHOW COLUMNS FROM inference_task LIKE 'last_checkpoint_at'"))
exists = result.fetchone()
if exists:
print("✓ 字段 'last_checkpoint_at' 已存在,跳过")
else:
print("正在添加字段 'last_checkpoint_at'...")
conn.execute(text("ALTER TABLE inference_task ADD COLUMN last_checkpoint_at DATETIME"))
conn.commit()
print("✓ 字段 'last_checkpoint_at' 添加成功")
conn.close()
print("\n✅ 所有迁移字段添加完成!")
if __name__ == '__main__':
print("=" * 60)
print("推理任务断点恢复字段迁移")
print("=" * 60)
try:
run_migration()
except Exception as e:
print(f"\n❌ 迁移失败: {e}")
sys.exit(1)
-83
View File
@@ -1,83 +0,0 @@
#!/usr/bin/env python
"""
直接通过 SQL 创建管理员账号
"""
import pymysql
from werkzeug.security import generate_password_hash
from config import Config
import re
print("=" * 50)
print("创建管理员账号")
print("=" * 50)
print(f"\n数据库配置:{Config.SQLALCHEMY_DATABASE_URI}")
# 解析数据库配置
match = re.match(r'mysql\+pymysql://([^:]+):([^@]+)@([^/]+)/([^?]+)', Config.SQLALCHEMY_DATABASE_URI)
if not match:
print("✗ 无法解析数据库配置")
exit(1)
user, password, host, db = match.groups()
# 移除可能的查询参数
db = db.split('?')[0]
print(f"连接到 {host}/{db}...")
try:
conn = pymysql.connect(host=host, user=user, password=password, database=db)
cursor = conn.cursor()
# 检查 admin 用户是否存在(使用参数化查询)
cursor.execute('SELECT id FROM user WHERE username=%s', ('admin',))
admin_result = cursor.fetchone()
if admin_result:
user_id = admin_result[0]
print(f'\n找到 admin 用户,ID: {user_id}')
# 更新密码和激活状态(不再设置 role 字段)
pwd_hash = generate_password_hash('password')
cursor.execute('''
UPDATE user SET password_hash=%s, is_active_account=1
WHERE username=%s
''', (pwd_hash, 'admin'))
print(' ✓ 密码已更新为:password')
# 清理关联(使用参数化查询)
cursor.execute('DELETE FROM user_roles WHERE user_id=%s', (user_id,))
print(f' 删除 user_roles 关联:{cursor.rowcount} 条')
# 分配 Administrator 角色(使用参数化查询)
cursor.execute('SELECT id FROM role WHERE name=%s', ('Administrator',))
role_result = cursor.fetchone()
if role_result:
role_id = role_result[0]
cursor.execute('INSERT INTO user_roles (user_id, role_id) VALUES (%s, %s)', (user_id, role_id))
print(f' ✓ 已分配 Administrator 角色')
else:
print(' ✗ Administrator 角色不存在')
else:
print('\n✗ admin 用户不存在,请先创建用户')
exit(1)
conn.commit()
print()
print('=' * 50)
print('✓ 管理员账号创建成功!')
print('=' * 50)
print('用户名:admin')
print('密码:password')
print('=' * 50)
cursor.close()
conn.close()
except Exception as e:
print(f'✗ 错误:{e}')
import traceback
traceback.print_exc()
if 'conn' in locals():
conn.rollback()
-114
View File
@@ -1,114 +0,0 @@
"""
导出 CWT-MAE 分类模型为 ONNX 格式
使用说明:
1. 将此脚本复制到你的模型训练目录
2. 确保 model.py 和 model_finetune.py 在同一目录
3. 运行:python export_onnx.py --checkpoint path/to/checkpoint.pth --output model.onnx
或者,直接在后端项目中使用:
python backend/scripts/export_onnx.py --checkpoint ... --output ...
"""
import os
import sys
import argparse
import torch
def main():
parser = argparse.ArgumentParser(description='Export CWT-MAE classifier to ONNX')
parser.add_argument('--checkpoint', type=str, required=True, help='PyTorch checkpoint path')
parser.add_argument('--output', type=str, required=True, help='Output ONNX file path')
# 模型参数(必须与训练时一致)
parser.add_argument('--signal_len', type=int, default=1000)
parser.add_argument('--embed_dim', type=int, default=768)
parser.add_argument('--depth', type=int, default=12)
parser.add_argument('--num_heads', type=int, default=12)
parser.add_argument('--num_classes', type=int, default=2)
parser.add_argument('--cwt_scales', type=int, default=64)
parser.add_argument('--patch_size_time', type=int, default=25)
parser.add_argument('--patch_size_freq', type=int, default=8)
parser.add_argument('--use_cot', type=bool, default=True)
args = parser.parse_args()
# 动态导入模型(从当前目录或指定路径)
# 这样可以在训练目录中直接运行此脚本
try:
# 尝试从当前目录导入
from model_finetune import TF_MAE_Classifier
except ImportError:
print("Error: model_finetune.py not found in current directory.")
print("Please copy this script to your training directory or add the path to PYTHONPATH.")
sys.exit(1)
# 1. 加载模型
print(f"Loading model from {args.checkpoint}...")
model = TF_MAE_Classifier(
pretrained_path=None,
num_classes=args.num_classes,
signal_len=args.signal_len,
cwt_scales=args.cwt_scales,
patch_size_time=args.patch_size_time,
patch_size_freq=args.patch_size_freq,
embed_dim=args.embed_dim,
depth=args.depth,
num_heads=args.num_heads,
use_cot=args.use_cot
)
# 加载权重
state_dict = torch.load(args.checkpoint, map_location='cpu')
# 处理 DDP 保存的 'module.' 前缀
new_state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()}
model.load_state_dict(new_state_dict, strict=False)
model.eval()
# 2. 准备导出
device = torch.device('cpu')
model.to(device)
# 创建 dummy input (B, M, L)
batch_size = 1
num_channels = 4 # 示例通道数
dummy_input = torch.randn(batch_size, num_channels, args.signal_len, device=device)
# 设置动态轴
dynamic_axes = {
'input': {0: 'batch_size', 1: 'num_channels'},
'output': {0: 'batch_size'}
}
# 3. 导出 ONNX
print(f"Exporting to {args.output}...")
torch.onnx.export(
model,
dummy_input,
args.output,
export_params=True,
opset_version=17,
do_constant_folding=True,
input_names=['input'],
output_names=['output'],
dynamic_axes=dynamic_axes,
verbose=False
)
print(f"✓ ONNX model exported successfully to {args.output}")
# 4. 验证导出
try:
import onnx
onnx_model = onnx.load(args.output)
onnx.checker.check_model(onnx_model)
print("✓ ONNX model validation passed")
except ImportError:
print("Note: Install 'onnx' package to validate the exported model")
except Exception as e:
print(f"Warning: ONNX validation failed: {e}")
if __name__ == '__main__':
main()
-121
View File
@@ -1,121 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
将 User.role 字段迁移到 RBAC roles 关联表
执行方式:
python scripts/migrate_role_data.py
执行前请确保:
1. 已备份数据库
2. 应用可以正常连接数据库
"""
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app import create_app, db
from app.models import User, Role
def migrate_role_to_rbac():
"""执行数据迁移"""
app = create_app(os.getenv('FLASK_ENV', 'production'))
with app.app_context():
print("=" * 50)
print("开始迁移 User.role 到 RBAC roles")
print("=" * 50)
# 确保 Administrator 角色存在
admin_role = Role.query.filter_by(name='Administrator').first()
if not admin_role:
admin_role = Role(name='Administrator', description='System Administrator')
db.session.add(admin_role)
db.session.commit()
print("✓ 创建 Administrator 角色")
else:
print("✓ Administrator 角色已存在")
# 确保 Researcher 角色存在
researcher_role = Role.query.filter_by(name='Researcher').first()
if not researcher_role:
researcher_role = Role(name='Researcher', description='Researcher role')
db.session.add(researcher_role)
db.session.commit()
print("✓ 创建 Researcher 角色")
else:
print("✓ Researcher 角色已存在")
# 确保 User 角色存在(用于普通用户)
user_role = Role.query.filter_by(name='User').first()
if not user_role:
user_role = Role(name='User', description='Regular user')
db.session.add(user_role)
db.session.commit()
print("✓ 创建 User 角色")
else:
print("✓ User 角色已存在")
# 统计需要迁移的用户
admin_users = User.query.filter_by(role='admin').all()
researcher_users = User.query.filter_by(role='researcher').all()
regular_users = User.query.filter(
(User.role == 'user') | (User.role == None)
).all()
print(f"\n待迁移用户统计:")
print(f" - Admin 用户:{len(admin_users)}")
print(f" - Researcher 用户:{len(researcher_users)}")
print(f" - 普通用户:{len(regular_users)}")
# 迁移 admin 用户
migrated_admin_count = 0
for user in admin_users:
if admin_role not in user.roles:
user.roles.append(admin_role)
migrated_admin_count += 1
print(f" → 添加 Administrator 角色给用户:{user.username}")
# 迁移 researcher 用户
migrated_researcher_count = 0
for user in researcher_users:
if researcher_role not in user.roles:
user.roles.append(researcher_role)
migrated_researcher_count += 1
print(f" → 添加 Researcher 角色给用户:{user.username}")
# 为普通用户添加 User 角色(可选)
migrated_user_count = 0
for user in regular_users:
# 跳过已经有角色的用户
if user.roles:
continue
user.roles.append(user_role)
migrated_user_count += 1
print(f" → 添加 User 角色给用户:{user.username}")
db.session.commit()
print("\n" + "=" * 50)
print("迁移完成!")
print("=" * 50)
print(f" - 迁移 Admin 用户:{migrated_admin_count}/{len(admin_users)}")
print(f" - 迁移 Researcher 用户:{migrated_researcher_count}/{len(researcher_users)}")
print(f" - 迁移普通用户:{migrated_user_count}/{len(regular_users)}")
print("\n请验证关键用户权限是否正常,然后运行:")
print(" flask db upgrade # 执行删除 role 列的 migration")
return True
if __name__ == '__main__':
try:
migrate_role_to_rbac()
except Exception as e:
print(f"\n❌ 迁移失败:{e}")
import traceback
traceback.print_exc()
sys.exit(1)
-24
View File
@@ -1,24 +0,0 @@
@echo off
echo ============================================================
echo 数据库测试脚本
echo ============================================================
echo.
cd /d %~dp0..
if exist venv\Scripts\activate.bat (
echo 激活虚拟环境...
call venv\Scripts\activate.bat
) else (
echo 未找到虚拟环境,使用系统 Python
)
echo.
echo 运行数据库测试...
python tests\test_database.py
echo.
echo ============================================================
echo 测试完成
echo ============================================================
pause
+1 -1
View File
@@ -48,7 +48,7 @@ export const authApi = {
* @param {string} passwords.new_password 新密码
*/
changePassword(passwords) {
return api.put('/auth/change-password', passwords)
return api.post('/auth/change-password', passwords)
}
}
+6 -1
View File
@@ -1,7 +1,12 @@
/**
* Token 管理模块
*
*
* 独立的 token 存储和读取功能,避免 api/index.js 和 store/user.js 之间的循环依赖
*
* SECURITY NOTE: Token 存储在 localStorage 中,存在 XSS 风险。
* 如果前端存在 XSS 漏洞,攻击者可通过 document.cookie 或 localStorage 窃取 Token。
* 更安全的方案:Refresh Token 存放于 httpOnly Cookie(需后端支持),Access Token 保持短过期时间(1h)。
* 当前架构下,确保无 XSS 注入点是关键防线(Element Plus 组件自带转义,自定义 innerHTML 需谨慎)。
*/
const TOKEN_KEY = 'token'
+1 -1
View File
@@ -75,7 +75,7 @@
</template>
<script setup>
import { reactive } from 'vue'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import { useI18n } from 'vue-i18n'
@@ -27,6 +27,7 @@
:min="100"
:max="5000"
:step="100"
:disabled="isChdModel"
/>
</el-form-item>
@@ -36,6 +37,7 @@
:min="100"
:max="2000"
:step="100"
:disabled="isChdModel"
/>
</el-form-item>
@@ -58,9 +60,31 @@
:min="0"
:max="1"
:step="0.05"
:disabled="isChdModel"
/>
</el-form-item>
<el-form-item v-if="isChdModel" label="采样率">
<el-input-number
v-model="formData.sampling_rate_hz"
:min="10"
:max="1000"
:step="10"
/>
<div style="font-size: 12px; color: #909399; margin-top: 4px">
数据原始采样率(Hz)。非 100Hz 时后端自动重采样;已是 100Hz 请保持 100
</div>
</el-form-item>
<el-alert
v-if="isChdModel"
title="PPG CHD 模型:固定 30 秒窗口(3000 点)/ 非重叠步长 / 阈值 0.5,参数已锁定"
type="warning"
:closable="false"
show-icon
style="margin-bottom: 12px"
/>
<el-form-item :label="$t('common.description')">
<el-alert
:title="$t('admin.inferenceHint')"
@@ -116,7 +140,20 @@ const formData = ref({
signal_len: 1000,
stride: 1000,
batch_size: 1,
confidence_threshold: 0.75
confidence_threshold: 0.75,
sampling_rate_hz: 100
})
// PPG CHD 模型:按文件名启发式识别(模型注册表无类型字段)
const isChdModel = computed(() => /chd/i.test(formData.value.model_path || ''))
// 选中 CHD 模型时锁定固定契约参数
watch(() => formData.value.model_path, (newPath) => {
if (/chd/i.test(newPath || '')) {
formData.value.signal_len = 3000
formData.value.stride = 3000
formData.value.confidence_threshold = 0.5
}
})
// 监听打开时加载模型列表
@@ -179,7 +216,8 @@ const resetForm = () => {
signal_len: 1000,
stride: 1000,
batch_size: 1,
confidence_threshold: 0.75
confidence_threshold: 0.75,
sampling_rate_hz: 100
}
}
@@ -182,9 +182,22 @@ const removeInferenceTask = (index) => {
})
}
// PPG CHD 模型:按文件名启发式识别,固定 30s 窗口契约
const isChdModelPath = (p) => /chd/i.test(p || '')
const applyChdContract = (form, label) => {
if (isChdModelPath(form.model_path || form.auto_inference_model_path)) {
form.signal_len !== undefined && (form.signal_len = 3000)
form.stride !== undefined && (form.stride = 3000)
form.auto_inference_signal_len !== undefined && (form.auto_inference_signal_len = 3000)
form.auto_inference_stride !== undefined && (form.auto_inference_stride = 3000)
ElMessage.info(`${label}:CHD 模型固定 signal_len=3000 / stride=3000 / 阈值 0.5`)
}
}
const saveInferenceTasks = async () => {
for (let i = 0; i < inferenceTasks.value.length; i++) {
const task = inferenceTasks.value[i]
applyChdContract(task, `任务 ${i + 1}`)
if (!task.model_path) {
ElMessage.error(`任务 ${i + 1} 未选择模型`)
return
@@ -229,6 +242,7 @@ const loadInferenceTasks = () => {
}
const saveAutoInferenceSettings = async () => {
applyChdContract(autoInferenceForm, '自动推理')
if (autoInferenceForm.auto_inference_interval < 60) {
ElMessage.error('执行间隔不能小于 60 秒')
return