feat(数据管理): 实现统一数据管理功能

新增 DataItem 数据模型整合所有数据类型,包括数据条目、上传压缩包和处理文件夹
添加数据管理 API 支持批量操作、权限控制和状态跟踪
实现数据迁移脚本将现有数据同步到新模型
优化 CWT 预处理性能和线程安全性
更新推理引擎和处理器以兼容新数据模型
This commit is contained in:
向宇康 committed 2026-04-02 11:00:57 +08:00
1 parent 9b158d8ad8
commit 18c42b6b6c
14 files changed
+3102 -109

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
{
"permissions": {
"allow": [
"Bash(alembic revision:*)",
"Bash(ls -la venv/lib/python*/site-packages/)",
"Bash(./venv/Scripts/python -m pip install alembic)",
"Bash(./venv/Scripts/python -m alembic revision --autogenerate -m \"add expiration and pushed fields to inference_result\")",
"Bash(../venv/Scripts/python -m alembic -c alembic.ini revision --autogenerate -m \"add expiration and pushed fields to inference_result\")",
"Bash(./venv/Scripts/python -m pip install flask-migrate)",
"Bash(./venv/Scripts/python -m flask db revision --autogenerate -m \"add expiration and pushed fields to inference_result\")",
"Bash(./venv/Scripts/python -m pip install -r requirements.txt)",
"Bash(./venv/Scripts/python -m flask --app run:app db revision --autogenerate -m \"add expiration and pushed fields to inference_result\")",
"Bash(./venv/Scripts/python -m flask --app run:app db current)",
"Bash(grep:*)",
"Bash(python -m alembic revision --autogenerate -m \"add unified data_item model and data_item_visibility table\")",
"Bash(python migrate_db.py)",
"Bash(python create_data_item_table.py)",
"Bash(python scripts/migrate_to_unified_data.py)",
"Bash(python:*)"
]
}
}
+1
View File
@@ -8,6 +8,7 @@ from . import (
admin_rbac,
auth,
data_entries,
data_management,
inference,
integration,
models,
+827
View File
@@ -0,0 +1,827 @@
"""
统一数据管理 API
整合所有数据类型(上传压缩包、文本条目、已处理文件夹)的统一管理
支持:推理、处理、推送、分配研究者
"""
import os
import logging
from flask import jsonify, request
from flask_jwt_extended import jwt_required
from .. import db
from ..models import DataItem, User, RawDataFolder, InferenceResult, ProcessingJob
from . import api
from .security import admin_required_jwt, get_current_user, get_pagination_args, permission_required_jwt
logger = logging.getLogger(__name__)
@api.route("/admin/unified-data", methods=["GET"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("view_data")
def list_data_items():
"""
List all data items with filtering
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: query
name: q
type: string
description: Search query for name/description
- in: query
name: data_type
type: string
description: Filter by data type (raw_archive, text_csv, processed_folder)
- in: query
name: status
type: string
description: Filter by processing status
- in: query
name: inference_status
type: string
description: Filter by inference status
- in: query
name: researcher_id
type: integer
description: Filter by assigned researcher
- in: query
name: page
type: integer
default: 1
description: Page number
- in: query
name: per_page
type: integer
default: 20
description: Items per page
responses:
200:
description: Paginated list of data items
schema:
type: object
properties:
items:
type: array
items:
type: object
properties:
id:
type: integer
description: Data item ID
name:
type: string
description: Item name
data_type:
type: string
description: Type of data
status:
type: string
description: Processing status
inference_status:
type: string
description: Inference status
original_filename:
type: string
description: Original uploaded filename
file_size:
type: integer
description: File size in bytes
researcher_id:
type: integer
description: Assigned researcher ID
researcher_name:
type: string
description: Researcher username
uploader_name:
type: string
description: Uploader username
created_at:
type: string
format: date-time
description: Creation timestamp
has_inference_results:
type: boolean
description: Whether this item has inference results
inference_result_count:
type: integer
description: Number of inference results
401:
description: Unauthorized
403:
description: Forbidden
"""
page, per_page = get_pagination_args(default_per_page=20)
q = request.args.get("q", "").strip()[:100]
data_type = request.args.get("data_type", "").strip()
status = request.args.get("status", "").strip()
inference_status = request.args.get("inference_status", "").strip()
researcher_id = request.args.get("researcher_id", type=int)
query = DataItem.query
# Apply filters
if q:
like = f"%{q}%"
query = query.filter((DataItem.name.ilike(like)) | (DataItem.description.ilike(like)))
if data_type:
query = query.filter(DataItem.data_type == data_type)
if status:
query = query.filter(DataItem.status == status)
if inference_status:
query = query.filter(DataItem.inference_status == inference_status)
if researcher_id is not None:
query = query.filter(DataItem.researcher_id == researcher_id)
# Order by creation time descending
query = query.order_by(DataItem.created_at.desc())
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
# Get user info for display
user_ids = set()
for item in pagination.items:
if item.researcher_id:
user_ids.add(item.researcher_id)
if item.uploader_id:
user_ids.add(item.uploader_id)
user_map = {}
if user_ids:
for u in User.query.filter(User.id.in_(list(user_ids))).all():
user_map[u.id] = u.username
# Count inference results for each item
result = []
for item in pagination.items:
inference_count = 0
if item.raw_data_folder_id:
inference_count = InferenceResult.query.filter_by(folder_id=item.raw_data_folder_id).count()
result.append({
"id": item.id,
"name": item.name,
"description": item.description,
"data_type": item.data_type,
"status": item.status,
"inference_status": item.inference_status,
"original_filename": item.original_filename,
"file_size": item.file_size,
"researcher_id": item.researcher_id,
"researcher_name": user_map.get(item.researcher_id) if item.researcher_id else None,
"uploader_name": user_map.get(item.uploader_id) if item.uploader_id else None,
"created_at": item.created_at.isoformat() if item.created_at else None,
"has_inference_results": inference_count > 0,
"inference_result_count": inference_count,
"storage_path": item.storage_path,
})
return jsonify({
"items": result,
"page": pagination.page,
"per_page": pagination.per_page,
"total": pagination.total,
}), 200
@api.route("/admin/unified-data/<int:item_id>", methods=["GET"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("view_data")
def get_data_item_detail(item_id):
"""
Get detailed information about a data item including processing jobs and inference results
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: path
name: item_id
type: integer
required: true
description: Data item ID
responses:
200:
description: Detailed data item information
404:
description: Data item not found
"""
item = DataItem.query.get(item_id)
if not item:
return jsonify({"msg": "Not found"}), 404
# Get related information
processing_jobs = []
inference_results = []
folder_info = None
if item.raw_data_folder_id:
folder = RawDataFolder.query.get(item.raw_data_folder_id)
if folder:
folder_info = {
"id": folder.id,
"folder_name": folder.folder_name,
"status": folder.status,
"inference_status": folder.inference_status,
"processed_file_count": folder.processed_file_count,
"last_processed": folder.last_processed.isoformat() if folder.last_processed else None,
}
# Get processing jobs
jobs = ProcessingJob.query.filter_by(folder_id=folder.id).order_by(ProcessingJob.start_time.desc()).all()
for job in jobs:
processing_jobs.append({
"id": job.id,
"status": job.status,
"start_time": job.start_time.isoformat() if job.start_time else None,
"end_time": job.end_time.isoformat() if job.end_time else None,
})
# Get inference results
results = InferenceResult.query.filter_by(folder_id=folder.id).order_by(InferenceResult.timestamp.desc()).all()
for res in results:
inference_results.append({
"id": res.id,
"timestamp": res.timestamp.isoformat() if res.timestamp else None,
"total_windows": res.total_windows,
"valid_windows": res.valid_windows,
"positive_count": res.positive_count,
"positive_density": res.positive_density,
"diagnosis": res.diagnosis,
"is_pushed": res.is_pushed,
"pushed_at": res.pushed_at.isoformat() if res.pushed_at else None,
"result_csv_filename": res.result_csv_filename,
})
researcher = None
if item.researcher_id:
r = User.query.get(item.researcher_id)
if r:
researcher = {"id": r.id, "username": r.username}
uploader = None
if item.uploader_id:
u = User.query.get(item.uploader_id)
if u:
uploader = {"id": u.id, "username": u.username}
return jsonify({
"id": item.id,
"name": item.name,
"description": item.description,
"data_type": item.data_type,
"status": item.status,
"inference_status": item.inference_status,
"is_permanent": item.is_permanent,
"start_date": item.start_date.isoformat() if item.start_date else None,
"expiration_date": item.expiration_date.isoformat() if item.expiration_date else None,
"original_filename": item.original_filename,
"file_size": item.file_size,
"storage_path": item.storage_path,
"created_at": item.created_at.isoformat() if item.created_at else None,
"updated_at": item.updated_at.isoformat() if item.updated_at else None,
"last_processed": item.last_processed.isoformat() if item.last_processed else None,
"researcher_id": item.researcher_id,
"researcher": researcher,
"uploader_id": item.uploader_id,
"uploader": uploader,
"data_entry_id": item.data_entry_id,
"raw_data_folder_id": item.raw_data_folder_id,
"upload_log_id": item.upload_log_id,
"folder_info": folder_info,
"processing_jobs": processing_jobs,
"inference_results": inference_results,
}), 200
@api.route("/admin/unified-data/<int:item_id>", methods=["PATCH"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("edit_data")
def update_data_item(item_id):
"""
Update data item metadata and assign researcher
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: path
name: item_id
type: integer
required: true
description: Data item ID
- in: body
name: body
required: true
schema:
type: object
properties:
name:
type: string
description: New name
description:
type: string
description: New description
researcher_id:
type: integer
description: New researcher ID (null for unassign)
status:
type: string
description: New processing status
inference_status:
type: string
description: New inference status
responses:
200:
description: Updated successfully
404:
description: Not found
"""
item = DataItem.query.get(item_id)
if not item:
return jsonify({"msg": "Not found"}), 404
data = request.get_json() or {}
if "name" in data and data["name"] is not None:
name = data["name"].strip()
if name:
item.name = name
if "description" in data:
item.description = data["description"] or None
if "researcher_id" in data:
researcher_id = data["researcher_id"]
if researcher_id is None:
item.researcher_id = None
else:
researcher = User.query.get(researcher_id)
if researcher and (researcher.is_researcher() or researcher.is_admin()):
item.researcher_id = researcher_id
else:
return jsonify({"msg": "Invalid researcher"}), 400
if "status" in data and data["status"]:
item.status = data["status"]
if "inference_status" in data and data["inference_status"]:
item.inference_status = data["inference_status"]
# Also update RawDataFolder if linked
if item.raw_data_folder_id:
folder = RawDataFolder.query.get(item.raw_data_folder_id)
if folder:
folder.inference_status = data["inference_status"]
db.session.commit()
logger.info(f"Updated data item {item_id} by {get_current_user().username}")
return jsonify({"msg": "ok", "id": item.id}), 200
@api.route("/admin/unified-data/<int:item_id>", methods=["DELETE"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("delete_data")
def delete_data_item(item_id):
"""
Delete a data item
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: path
name: item_id
type: integer
required: true
description: Data item ID
responses:
200:
description: Deleted successfully
404:
description: Not found
"""
item = DataItem.query.get(item_id)
if not item:
return jsonify({"msg": "Not found"}), 404
db.session.delete(item)
db.session.commit()
logger.info(f"Deleted data item {item_id} by {get_current_user().username}")
return jsonify({"msg": "deleted"}), 200
@api.route("/admin/unified-data/batch-delete", methods=["POST"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("delete_data")
def batch_delete_data_items():
"""
Batch delete multiple data items
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: body
name: body
required: true
schema:
type: object
properties:
ids:
type: array
items:
type: integer
description: List of data item IDs to delete
responses:
200:
description: Batch delete completed
"""
data = request.get_json() or {}
ids = data.get("ids", [])
if not ids:
return jsonify({"msg": "No IDs provided"}), 400
deleted = 0
failed = []
current_user = get_current_user()
for item_id in ids:
item = DataItem.query.get(item_id)
if item:
db.session.delete(item)
deleted += 1
else:
failed.append(item_id)
db.session.commit()
logger.info(f"Batch deleted {deleted} data items by {current_user.username}")
result_msg = f"成功删除 {deleted} 条记录"
if failed:
result_msg += f",{len(failed)} 条记录未找到"
return jsonify({
"msg": result_msg,
"deleted_count": deleted,
"failed_ids": failed,
}), 200
@api.route("/admin/unified-data/batch-assign", methods=["POST"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("edit_data")
def batch_assign_data_items():
"""
Batch assign data items to a researcher
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: body
name: body
required: true
schema:
type: object
properties:
researcher_id:
type: integer
required: true
description: Researcher ID to assign
ids:
type: array
items:
type: integer
required: true
description: List of data item IDs
responses:
200:
description: Batch assign completed
400:
description: Invalid researcher
"""
data = request.get_json() or {}
researcher_id = data.get("researcher_id")
ids = data.get("ids", [])
if researcher_id is None:
return jsonify({"msg": "Missing researcher_id"}), 400
if not ids:
return jsonify({"msg": "No IDs provided"}), 400
# Verify researcher
if researcher_id is not None:
researcher = User.query.get(researcher_id)
if not researcher or not (researcher.is_researcher() or researcher.is_admin()):
return jsonify({"msg": "Invalid researcher"}), 400
updated = 0
failed = []
current_user = get_current_user()
for item_id in ids:
item = DataItem.query.get(item_id)
if item:
item.researcher_id = researcher_id
# Also update linked RawDataFolder
if item.raw_data_folder_id:
folder = RawDataFolder.query.get(item.raw_data_folder_id)
if folder:
folder.researcher_id = researcher_id
updated += 1
else:
failed.append(item_id)
db.session.commit()
logger.info(f"Batch assigned {updated} data items to researcher {researcher_id} by {current_user.username}")
result_msg = f"成功分配 {updated} 条记录给研究者 {researcher_id}"
if failed:
result_msg += f",{len(failed)} 条记录未找到"
return jsonify({
"msg": result_msg,
"updated_count": updated,
"failed_ids": failed,
}), 200
@api.route("/admin/unified-data/<int:item_id>/inference-results/<int:result_id>/push", methods=["POST"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("push_inference")
def push_inference_result(item_id, result_id):
"""
Push inference result to administrator (mark as pushed)
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: path
name: item_id
type: integer
required: true
description: Data item ID
- in: path
name: result_id
type: integer
required: true
description: Inference result ID
responses:
200:
description: Push completed
404:
description: Not found
"""
from datetime import datetime
item = DataItem.query.get(item_id)
if not item:
return jsonify({"msg": "Data item not found"}), 404
result = InferenceResult.query.get(result_id)
if not result:
return jsonify({"msg": "Inference result not found"}), 404
# Toggle push status
if not result.is_pushed:
result.is_pushed = True
result.pushed_at = datetime.utcnow()
message = "推理结果已推送"
else:
result.is_pushed = False
result.pushed_at = None
message = "推送状态已取消"
db.session.commit()
current_user = get_current_user()
logger.info(f"Inference result {result_id} pushed by {current_user.username}")
return jsonify({
"msg": message,
"result_id": result_id,
"is_pushed": result.is_pushed,
"pushed_at": result.pushed_at.isoformat() if result.pushed_at else None,
}), 200
@api.route("/admin/unified-data/processing-jobs", methods=["GET"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("view_data")
def list_processing_jobs():
"""
List all processing jobs across all data
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: query
name: status
type: string
description: Filter by status
- in: query
name: page
type: integer
default: 1
description: Page number
- in: query
name: per_page
type: integer
default: 20
description: Items per page
responses:
200:
description: Paginated list of processing jobs
"""
page, per_page = get_pagination_args(default_per_page=20)
status = request.args.get("status", "").strip()
query = ProcessingJob.query.order_by(ProcessingJob.start_time.desc())
if status:
query = query.filter(ProcessingJob.status == status)
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
result = []
for job in pagination.items:
folder_name = None
if job.folder:
folder_name = job.folder.folder_name
data_item = DataItem.query.filter_by(raw_data_folder_id=job.folder.id).first()
data_item_id = data_item.id if data_item else None
else:
data_item_id = None
result.append({
"id": job.id,
"folder_id": job.folder_id,
"folder_name": folder_name,
"data_item_id": data_item_id,
"status": job.status,
"start_time": job.start_time.isoformat() if job.start_time else None,
"end_time": job.end_time.isoformat() if job.end_time else None,
})
return jsonify({
"items": result,
"page": pagination.page,
"per_page": pagination.per_page,
"total": pagination.total,
}), 200
@api.route("/admin/unified-data/sync", methods=["POST"])
@jwt_required()
@admin_required_jwt
@permission_required_jwt("manage_data")
def sync_from_existing():
"""
Sync existing records to DataItem (for migration from old structure)
---
tags:
- unified-data
security:
- JWT: []
parameters:
- in: body
name: body
schema:
type: object
properties:
clear_existing:
type: boolean
default: false
description: Whether to clear existing DataItem records before sync
responses:
200:
description: Sync completed
"""
from ..models import DataEntry, UploadLog, RawDataFolder
data = request.get_json() or {}
clear_existing = data.get("clear_existing", False)
current_user = get_current_user()
if clear_existing:
count = DataItem.query.count()
DataItem.query.delete()
logger.info(f"Cleared {count} existing DataItem records for full sync by {current_user.username}")
created = 0
skipped = 0
# Sync DataEntry -> DataItem
for entry in DataEntry.query.all():
existing = DataItem.query.filter_by(data_entry_id=entry.id).first()
if existing:
skipped += 1
continue
item = DataItem(
name=entry.title,
description=entry.content,
data_type="text_csv",
status="completed",
inference_status="none",
is_permanent=entry.is_permanent,
start_date=entry.start_date,
expiration_date=entry.expiration_date,
researcher_id=entry.researcher_id,
uploader_id=None,
original_filename=entry.associated_filename,
file_size=None,
storage_path=None,
data_entry_id=entry.id,
)
db.session.add(item)
created += 1
# Sync UploadLog -> DataItem
for log in UploadLog.query.all():
existing = DataItem.query.filter_by(upload_log_id=log.id).first()
if existing:
skipped += 1
continue
# Check if there's a linked RawDataFolder
# For uploads that were extracted, find the corresponding folder
folder = None
if log.filename:
# folder name is filename without extension
folder_name = os.path.splitext(log.filename)[0]
folder = RawDataFolder.query.filter_by(folder_name=folder_name).first()
item = DataItem(
name=log.filename,
description=f"Uploaded archive: {log.filename}",
data_type="raw_archive",
status="completed" if log.status == "success" else log.status,
inference_status="none",
researcher_id=log.researcher_id,
uploader_id=log.uploader_id,
original_filename=log.filename,
file_size=log.file_size,
storage_path=None,
upload_log_id=log.id,
raw_data_folder_id=folder.id if folder else None,
)
# Sync inference status from folder
if folder:
item.inference_status = folder.inference_status
item.status = folder.status
item.last_processed = folder.last_processed
db.session.add(item)
created += 1
# Sync RawDataFolder -> DataItem (if not already created via UploadLog)
for folder in RawDataFolder.query.all():
existing = DataItem.query.filter_by(raw_data_folder_id=folder.id).first()
if existing:
skipped += 1
continue
item = DataItem(
name=folder.folder_name,
description=f"Processed folder: {folder.folder_name}",
data_type="processed_folder",
status=folder.status,
inference_status=folder.inference_status,
researcher_id=folder.researcher_id,
uploader_id=None,
original_filename=None,
file_size=None,
storage_path=None,
raw_data_folder_id=folder.id,
last_processed=folder.last_processed,
)
db.session.add(item)
created += 1
db.session.commit()
logger.info(f"Sync completed: created {created} DataItem records, skipped {skipped} by {current_user.username}")
return jsonify({
"msg": f"同步完成,创建 {created} 条记录,跳过 {skipped} 条已存在记录",
"created": created,
"skipped": skipped,
}), 200
+118 -7
View File
@@ -283,6 +283,7 @@ def init_crawler_upload():
def _create_crawler_upload_log(session):
"""辅助函数:为爬虫上传创建 UploadLog 记录,并解压到 RAW_DATA_STORAGE_FOLDER"""
from ..models import DataItem, RawDataFolder
try:
# 检查是否已存在记录(防止重复创建)
existing_log = UploadLog.query.filter_by(
@@ -310,6 +311,36 @@ def _create_crawler_upload_log(session):
error_msg=None,
)
db.session.add(log)
db.session.flush()
# 创建统一数据条目
# 检查是否已经创建过 DataItem
existing_item = DataItem.query.filter_by(upload_log_id=log.id).first()
if not existing_item:
# 获取解压后的 RawDataFolder
folder_name = os.path.splitext(session["filename"])[0]
folder = RawDataFolder.query.filter_by(folder_name=folder_name).first()
item = DataItem(
name=session["filename"],
description=f"Crawler uploaded archive: {session['filename']}",
data_type="raw_archive",
status="completed",
inference_status="none",
researcher_id=researcher_id,
uploader_id=None,
original_filename=session["filename"],
file_size=session["total_size"],
storage_path=session.get("storage_path", ""),
upload_log_id=log.id,
raw_data_folder_id=folder.id if folder else None,
)
if folder:
item.inference_status = folder.inference_status
item.status = folder.status
item.last_processed = folder.last_processed
db.session.add(item)
db.session.commit()
# 如果是压缩包,自动解压到 RAW_DATA_STORAGE_FOLDER
@@ -321,7 +352,7 @@ def _create_crawler_upload_log(session):
def _extract_archive_if_needed(session, upload_log_id):
"""如果是压缩包,解压到 RAW_DATA_STORAGE_FOLDER 并创建 RawDataFolder 记录"""
from ..models import RawDataFolder
from ..models import RawDataFolder, DataItem, UploadLog
try:
filename = session["filename"]
@@ -361,28 +392,80 @@ def _extract_archive_if_needed(session, upload_log_id):
# 创建 RawDataFolder 记录(如果不存在)
existing_folder = RawDataFolder.query.filter_by(folder_name=folder_name).first()
if not existing_folder:
db.session.add(RawDataFolder(
folder = RawDataFolder(
folder_name=folder_name,
researcher_id=session.get("researcher_id")
))
)
db.session.add(folder)
db.session.commit()
# 更新 DataItem
item = DataItem.query.filter_by(upload_log_id=upload_log_id).first()
if item:
item.raw_data_folder_id = folder.id
item.inference_status = folder.inference_status
item.status = folder.status
db.session.commit()
else:
# 更新 DataItem
item = DataItem.query.filter_by(upload_log_id=upload_log_id).first()
if item and not item.raw_data_folder_id:
item.raw_data_folder_id = existing_folder.id
item.inference_status = existing_folder.inference_status
item.status = existing_folder.status
db.session.commit()
return
# 解压
# 解压(逐个文件检查,防止路径遍历攻击)
os.makedirs(extract_path, exist_ok=True)
with zipfile.ZipFile(target_path, 'r') as zip_ref:
zip_ref.extractall(extract_path)
for info in zip_ref.infolist():
# 检查路径安全性
if info.filename.startswith('/') or '..' in info.filename:
logger.warning(f"跳过不安全路径: {info.filename}")
continue
# 确保输出路径在目标目录内
extracted_path = os.path.join(extract_path, info.filename)
normalized_extracted = os.path.normpath(extracted_path)
normalized_extract = os.path.normpath(extract_path)
if not normalized_extracted.startswith(normalized_extract + os.sep):
logger.warning(f"路径越界,跳过: {info.filename}")
continue
if info.is_dir():
os.makedirs(extracted_path, exist_ok=True)
else:
# 确保父目录存在
os.makedirs(os.path.dirname(extracted_path), exist_ok=True)
with zip_ref.open(info) as source, open(extracted_path, 'wb') as dest:
dest.write(source.read())
logger.info(f"Extracted {filename} to {extract_path}")
# 创建 RawDataFolder 记录
existing_folder = RawDataFolder.query.filter_by(folder_name=folder_name).first()
if not existing_folder:
db.session.add(RawDataFolder(
folder = RawDataFolder(
folder_name=folder_name,
researcher_id=session.get("researcher_id")
))
)
db.session.add(folder)
db.session.commit()
# 更新 DataItem 关联
item = DataItem.query.filter_by(upload_log_id=upload_log_id).first()
if item:
item.raw_data_folder_id = folder.id
item.inference_status = folder.inference_status
item.status = folder.status
db.session.commit()
else:
# 更新 DataItem 关联如果不存在
item = DataItem.query.filter_by(upload_log_id=upload_log_id).first()
if item and not item.raw_data_folder_id:
item.raw_data_folder_id = existing_folder.id
item.inference_status = existing_folder.inference_status
item.status = existing_folder.status
db.session.commit()
except Exception as e:
logger.error(f"Failed to extract archive: {e}")
@@ -614,6 +697,8 @@ def upload_archives():
else:
researcher_id = user.id
from ..models import DataItem, RawDataFolder
results = []
storage_root = current_app.config["RAW_DATA_STORAGE_FOLDER"]
@@ -640,6 +725,32 @@ def upload_archives():
status="success",
)
db.session.add(log)
db.session.flush()
# 创建统一数据条目
folder_name = os.path.splitext(original_filename)[0]
folder = RawDataFolder.query.filter_by(folder_name=folder_name).first()
item = DataItem(
name=original_filename,
description=f"Admin uploaded archive: {original_filename}",
data_type="raw_archive",
status="completed",
inference_status="none",
researcher_id=researcher_id,
uploader_id=user.id,
original_filename=original_filename,
file_size=file_size,
storage_path=storage_path,
upload_log_id=log.id,
raw_data_folder_id=folder.id if folder else None,
)
if folder:
item.inference_status = folder.inference_status
item.status = folder.status
item.last_processed = folder.last_processed
db.session.add(item)
results.append({"filename": original_filename, "status": "success", "size": file_size})
except Exception as e:
log = UploadLog(
+30 -31
View File
@@ -35,13 +35,13 @@ class ONNXInferenceEngine:
- CPU 优化配置
"""
def __init__(self,
def __init__(self,
model_path: str,
num_threads: int = 1,
use_memory_pool: bool = True):
"""
初始化推理引擎
Args:
model_path: ONNX 模型文件路径
num_threads: 每个会话的线程数(推荐 1,避免线程争抢)
@@ -52,23 +52,19 @@ class ONNXInferenceEngine:
"onnxruntime is not installed. "
"Install it with: pip install onnxruntime"
)
self.model_path = model_path
self.num_threads = num_threads
self.use_memory_pool = use_memory_pool
# 会话选项优化
self.sess_options = self._create_session_options()
# 获取输入输出信息(用于验证)
self._input_name = None
self._output_name = None
self._input_shape = None
# 延迟加载会话(首次推理时创建)
# 输入输出信息存储在线程局部,避免竞态条件
self._session = None
def _create_session_options(self) -> ort.SessionOptions:
def _create_session_options(self) -> Any:
"""创建优化的会话选项"""
sess_options = ort.SessionOptions()
@@ -89,12 +85,15 @@ class ONNXInferenceEngine:
return sess_options
def _get_session(self) -> ort.InferenceSession:
def _get_session(self) -> Any:
"""获取线程内会话(懒加载)"""
# 检查线程局部存储
# 检查线程局部存储,初始化所有需要缓存的信息
if not hasattr(_thread_local, 'session'):
_thread_local.session = None
_thread_local.input_name = None
_thread_local.output_name = None
_thread_local.input_shape = None
if _thread_local.session is None:
# 创建新会话
_thread_local.session = ort.InferenceSession(
@@ -102,41 +101,41 @@ class ONNXInferenceEngine:
sess_options=self.sess_options,
providers=['CPUExecutionProvider']
)
# 缓存输入输出信息
# 缓存输入输出信息到线程局部存储,避免竞态条件
inputs = _thread_local.session.get_inputs()
outputs = _thread_local.session.get_outputs()
self._input_name = inputs[0].name
self._output_name = outputs[0].name
self._input_shape = inputs[0].shape
_thread_local.input_name = inputs[0].name
_thread_local.output_name = outputs[0].name
_thread_local.input_shape = inputs[0].shape
logger.info(f"Loaded ONNX model: {self.model_path}")
logger.info(f"Input shape: {self._input_shape}")
logger.info(f"Input shape: {_thread_local.input_shape}")
return _thread_local.session
def infer(self, input_array: np.ndarray) -> np.ndarray:
"""
执行推理
Args:
input_array: 输入数组 (B, ...)
Returns:
推理输出
"""
session = self._get_session()
# 确保输入类型正确
input_array = np.ascontiguousarray(input_array, dtype=np.float32)
# 执行推理
# 执行推理(从线程局部读取输入输出信息)
outputs = session.run(
[self._output_name],
{self._input_name: input_array}
[_thread_local.output_name],
{_thread_local.input_name: input_array}
)
return outputs[0]
def get_input_info(self) -> dict:
@@ -11,6 +11,7 @@ import numpy as np
from ..base import BaseModel, BaseProcessor
from ..engine import ONNXInferenceEngine
from ...utils.cwt import preprocess_signal, normalize_signal, check_signal_quality
logger = logging.getLogger(__name__)
@@ -108,21 +109,17 @@ class MAEProcessor(BaseProcessor):
self.fallback_top_k = fallback_top_k
self.trim_ratio = trim_ratio
self.num_classes = num_classes
# 导入 CWT 工具
from ..utils.cwt import preprocess_signal, normalize_signal, check_signal_quality
def preprocess(self, raw_data: Any) -> np.ndarray:
"""
预处理:从原始数据到模型输入
Args:
raw_data: 原始数据字典或 numpy 数组
Returns:
模型输入 (B, M, n_patches, dim)
"""
from ..utils.cwt import preprocess_signal, normalize_signal
# 处理输入格式
if isinstance(raw_data, dict):
+97
View File
@@ -11,6 +11,12 @@ data_visibility = db.Table('data_visibility',
db.Column('data_entry_id', db.Integer, db.ForeignKey('data_entry.id'), primary_key=True)
)
# DataItem 可见性关联表
data_item_visibility = db.Table('data_item_visibility',
db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
db.Column('data_item_id', db.Integer, db.ForeignKey('data_item.id'), primary_key=True)
)
# RBAC 关联表
user_roles = db.Table('user_roles',
db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
@@ -40,6 +46,11 @@ class User(UserMixin, db.Model):
'DataEntry', secondary=data_visibility,
back_populates='visible_to_users', lazy='dynamic'
)
# 'visible_data_items' 统一数据模型的可见性反向关系
visible_data_items = db.relationship(
'DataItem', secondary=data_item_visibility,
back_populates='visible_to_users', lazy='dynamic'
)
notifications = db.relationship('Notification', backref='author', lazy='dynamic')
def __init__(self, **kwargs):
@@ -326,9 +337,21 @@ class InferenceResult(db.Model):
# 关联到使用的下游任务模型
task_id = db.Column(db.Integer, db.ForeignKey('downstream_task.id'), nullable=True, index=True)
# --- 新增字段:过期和推送 ---
expiration_date = db.Column(db.DateTime, nullable=True) # 过期时间,null=永久有效
is_pushed = db.Column(db.Boolean, default=False, nullable=False) # 是否已推送给管理员
pushed_at = db.Column(db.DateTime, nullable=True) # 推送时间
# ---------------------------
# 关系:关联到 DownstreamTask
task = db.relationship('DownstreamTask', backref='inference_results')
def is_expired(self):
"""检查是否已过期"""
if self.expiration_date is None:
return False
return self.expiration_date < datetime.utcnow()
def __repr__(self):
return f'<InferenceResult {self.id} for Folder {self.folder.folder_name}>'
@@ -398,6 +421,80 @@ class DownstreamTask(db.Model):
def __repr__(self):
return f'<DownstreamTask {self.task_name} ({self.task_type})>'
class DataItem(db.Model):
"""统一数据条目 - 合并所有数据类型(上传压缩包、传统条目、已处理文件夹)"""
id = db.Column(db.Integer, primary_key=True)
# 基本信息
name = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text, nullable=True)
data_type = db.Column(db.String(50), nullable=False) # raw_archive, text_csv, processed_folder
# 状态跟踪
status = db.Column(db.String(50), default='pending') # pending, processing, completed, failed
inference_status = db.Column(db.String(50), default='none') # none, inferencing, inferred
# 时间戳
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
last_processed = db.Column(db.DateTime, nullable=True)
# 访问控制
is_permanent = db.Column(db.Boolean, default=True)
start_date = db.Column(db.DateTime, nullable=True)
expiration_date = db.Column(db.DateTime, nullable=True)
# 分配归属
researcher_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
uploader_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
# 文件元数据
original_filename = db.Column(db.String(255), nullable=True)
file_size = db.Column(db.BigInteger, nullable=True)
storage_path = db.Column(db.String(512), nullable=True)
# 多态链接到原有表
data_entry_id = db.Column(db.Integer, db.ForeignKey('data_entry.id'), nullable=True)
raw_data_folder_id = db.Column(db.Integer, db.ForeignKey('raw_data_folder.id'), nullable=True)
upload_log_id = db.Column(db.Integer, db.ForeignKey('upload_log.id'), nullable=True)
# 关系
researcher = db.relationship('User', foreign_keys=[researcher_id], backref='assigned_data')
uploader = db.relationship('User', foreign_keys=[uploader_id], backref='uploaded_data')
data_entry = db.relationship('DataEntry', backref='data_item')
raw_data_folder = db.relationship('RawDataFolder', backref='data_item')
upload_log = db.relationship('UploadLog', backref='data_item')
# 可见性控制
visible_to_users = db.relationship(
'User', secondary=data_item_visibility,
back_populates='visible_data_items', lazy='dynamic'
)
def is_expired(self):
"""检查是否已过期"""
if self.is_permanent:
return False
if self.expiration_date is None:
return False
return self.expiration_date < datetime.utcnow()
def is_visible_now(self):
"""检查当前是否可见"""
now = datetime.utcnow()
if self.is_permanent:
return True
if self.start_date and now < self.start_date:
return False
if self.expiration_date and now > self.expiration_date:
return False
return True
def __repr__(self):
return f'<DataItem {self.name} ({self.data_type})>'
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
+69 -63
View File
@@ -11,117 +11,123 @@ from typing import Union
def create_ricker_wavelets(points: int, scales: np.ndarray) -> np.ndarray:
"""
创建 Ricker 小波(numpy 版)
Args:
points: 小波点数
scales: 尺度参数数组
Returns:
小波波形 (n_scales, points)
小波波形 (n_scales, 1, points)
"""
t = np.arange(0, points) - (points - 1) / 2.0
scales = scales[:, np.newaxis]
t = np.arange(0, points) - (points - 1.0) / 2.0
t = t.reshape(1, 1, -1)
scales = scales.reshape(-1, 1, 1)
pi_factor = np.pi ** 0.25
A = 2 / (np.sqrt(3 * scales) * pi_factor + 1e-6)
wsq = scales ** 2
xsq = t ** 2
mod = (1 - xsq / wsq)
gauss = np.exp(-xsq / (2 * wsq))
return A * mod * gauss
wavelets = A * mod * gauss
return wavelets
def cwt_ricker(x: np.ndarray, scales: np.ndarray) -> np.ndarray:
"""
对单通道信号进行 Ricker 小波变换
Args:
x: 输入信号 (L,)
scales: 尺度参数数组
Returns:
CWT 输出 (n_scales, L)
"""
sequence_length = len(x)
largest_scale = scales[-1]
# 计算小波长度
# 计算小波长度(10 倍最大尺度,与 PyTorch 版本保持一致)
wavelet_len = int(min(10.0 * largest_scale, float(sequence_length)))
if wavelet_len % 2 == 0:
wavelet_len += 1
# 创建小波
wavelets = create_ricker_wavelets(wavelet_len, scales)
wavelets = create_ricker_wavelets(wavelet_len, scales) # (n_scales, 1, wavelet_len)
pad_len = wavelet_len // 2
# 填充信号
x_padded = np.pad(x, (pad_len, pad_len), mode='reflect')
# 卷积
cwt_out = np.convolve(x_padded, wavelets, mode='valid')
# 调整形状为 (n_scales, L)
n_scales = len(scales)
cwt_out = cwt_out[:n_scales * sequence_length].reshape(n_scales, sequence_length)
# 批量卷积(使用 convolve2d 将循环移到 C 层面,性能更好)
wavelets_2d = wavelets[:, 0, :] # (n_scales, wavelet_len)
x_padded_2d = x_padded[np.newaxis, :] # (1, L_pad)
cwt_out = scipy_signal.convolve2d(x_padded_2d, wavelets_2d, mode='valid') # (n_scales, L)
return cwt_out
def cwt_wrap(x: np.ndarray, num_scales: int = 64,
def cwt_wrap(x: np.ndarray, num_scales: int = 64,
lowest_scale: float = 0.1, step: float = 1.0,
use_diff: bool = True) -> np.ndarray:
"""
完整的 CWT 预处理流程(支持多通道)
Args:
x: 输入信号 (M, L) 或 (L)
x: 输入信号 (M, L) 或 (L) 或 (B, M, L)
num_scales: 尺度数量
lowest_scale: 最小尺度
step: 尺度步长
use_diff: 是否使用微分增强
Returns:
CWT 输出 (M, C, n_scales, L) 其中 C=3 (原信号 + 一阶差分 + 二阶差分)
CWT 输出 (B, M, C, n_scales, L) 其中 C=3 (原信号 + 一阶差分 + 二阶差分)
"""
# 确保输入为 2D (M, L)
# 处理不同输入维度
if x.ndim == 1:
x = x[np.newaxis, :]
B, M, L = x.shape[0], x.shape[0], x.shape[1]
# (L,) -> (B=1, M=1, L)
x = x[np.newaxis, np.newaxis, :]
elif x.ndim == 2:
# (M, L) -> (B=1, M, L)
x = x[np.newaxis, :, :]
B, M, L = x.shape
if use_diff:
# PyTorch 版本一致的差分计算:先padding再差分
x_pad = np.pad(x, ((0, 0), (1, 1)), mode='edge') # edge == replicate
d1 = x_pad[:, 1:] - x_pad[:, :-1]
d2 = d1[:, 1:] - d1[:, :-1]
base = x
d1_cut = d1[:, :L]
d2_cut = d2[:, :L]
signals = np.stack([base, d1_cut, d2_cut], axis=1) # (M, 3, L)
else:
base = x
signals = base[:, np.newaxis, :] # (M, 1, L)
# 生成尺度数组
scales = np.arange(num_scales) * step + lowest_scale
results = []
for m in range(M):
channel_signal = x[m] # (L,)
if use_diff:
# 一阶差分
d1 = np.diff(channel_signal, prepend=channel_signal[0])
# 二阶差分
d2 = np.diff(d1, prepend=d1[0])
signals = np.stack([channel_signal, d1, d2], axis=0) # (3, L)
else:
signals = channel_signal[np.newaxis, :] # (1, L)
# 对每个子信号进行 CWT
cwt_results = []
for c in range(signals.shape[0]):
cwt_out = cwt_ricker(signals[c], scales) # (n_scales, L)
cwt_results.append(cwt_out)
# 堆叠为 (C, n_scales, L)
channel_result = np.stack(cwt_results, axis=0)
results.append(channel_result)
# 堆叠为 (M, C, n_scales, L)
output = np.stack(results, axis=0)
return output
BM, C, _ = signals.shape
signals_flat = signals.reshape(BM * C, L)
# 对每个信号分别进行 CWT
cwt_results = []
for sig in signals_flat:
cwt_out = cwt_ricker(sig, scales) # (n_scales, L)
cwt_results.append(cwt_out)
# 合并结果
cwt_out = np.stack(cwt_results, axis=0) # (BM*C, n_scales, L)
_, n_scales, _ = cwt_out.shape
# 重塑为 (B, M, C, n_scales, L)
cwt_out = cwt_out.reshape(B, M, C, n_scales, L)
return cwt_out
def cwt_to_model_input(cwt_output: np.ndarray,
+81
View File
@@ -0,0 +1,81 @@
"""
创建 DataItem 表和 data_item_visibility 表
简化版本,避开 emoji 编码问题
"""
import os
import sys
from dotenv import load_dotenv
# 加载 .env 文件
load_dotenv()
# 添加 backend 目录到路径
backend_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, backend_dir)
from app import create_app, db
from app.models import (
User, Permission, Role, PermissionLog, DataEntry, Attachment,
UploadLog, Notification, RawDataFolder, ProcessedSegment,
ProcessingJob, ProcessedFileLog, InferenceResult, SecurityLog,
SystemSetting, UpdateLog, DownstreamTask, DataItem
)
from sqlalchemy import inspect, text
def main():
print("Creating database tables for unified data management...")
print(f"DB Host: {os.environ.get('DB_HOST', 'localhost')}")
print(f"DB User: {os.environ.get('DB_USER', 'root')}")
print(f"DB Name: {os.environ.get('DB_NAME', 'rct')}")
print()
app = create_app('development')
try:
with app.app_context():
# 测试连接
result = db.session.execute(text("SELECT 1")).scalar()
if result == 1:
print("Database connection succeeded!")
else:
print("Database connection failed!")
sys.exit(1)
# 创建所有表(包括新增的)
print("\nCreating all tables (idempotent)...")
db.create_all()
print("db.create_all() completed!")
# 验证
inspector = inspect(db.engine)
tables = inspector.get_table_names()
print(f"\nTotal tables: {len(tables)}")
print()
# 检查新增表
new_tables = ['data_item', 'data_item_visibility']
for table in new_tables:
if table in tables:
columns = inspector.get_columns(table)
print(f"[OK] {table} created with {len(columns)} columns")
for col in columns[:5]:
col_name = col['name']
col_type = str(col['type'])
print(f" - {col_name}: {col_type}")
if len(columns) > 5:
print(f" ... and {len(columns) - 5} more")
else:
print(f"[FAIL] {table} NOT found")
print()
print("All done! Tables created successfully.")
except Exception as e:
print(f"\nError: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == '__main__':
main()
+1 -1
View File
@@ -18,7 +18,7 @@ from app.models import (
User, Permission, Role, PermissionLog, DataEntry, Attachment,
UploadLog, Notification, RawDataFolder, ProcessedSegment,
ProcessingJob, ProcessedFileLog, InferenceResult, SecurityLog,
SystemSetting, UpdateLog, DownstreamTask
SystemSetting, UpdateLog, DownstreamTask, DataItem
)
from sqlalchemy import inspect, text
+166
View File
@@ -0,0 +1,166 @@
"""
数据迁移脚本 - 统一数据管理
从现有的 DataEntry、UploadLog、RawDataFolder 同步数据到 DataItem 表
"""
import os
import sys
import argparse
# 加载环境变量
os.environ.setdefault('FLASK_ENV', 'development')
# 添加 backend 目录到路径
backend_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, backend_dir)
from dotenv import load_dotenv
load_dotenv()
from app import create_app, db
from app.models import DataItem, DataEntry, UploadLog, RawDataFolder
def sync_existing_data(clear_existing=False):
"""同步现有数据到 DataItem 表"""
app = create_app('development')
created = 0
skipped = 0
with app.app_context():
if clear_existing:
count = DataItem.query.count()
print(f"Clearing {count} existing DataItem records...")
DataItem.query.delete()
db.session.commit()
print("Done.")
# 1. 同步 DataEntry -> DataItem
print("\nSyncing DataEntry...")
for entry in DataEntry.query.all():
existing = DataItem.query.filter_by(data_entry_id=entry.id).first()
if existing:
skipped += 1
continue
item = DataItem(
name=entry.title,
description=entry.content,
data_type="text_csv",
status="completed",
inference_status="none",
is_permanent=entry.is_permanent,
start_date=entry.start_date,
expiration_date=entry.expiration_date,
researcher_id=entry.researcher_id,
uploader_id=None,
original_filename=entry.associated_filename,
file_size=None,
storage_path=None,
data_entry_id=entry.id,
)
db.session.add(item)
created += 1
if created % 100 == 0:
db.session.commit()
print(f" Created {created}...")
db.session.commit()
print(f" Done: created {created}, skipped {skipped}")
# 2. 同步 UploadLog -> DataItem
print("\nSyncing UploadLog...")
for log in UploadLog.query.all():
existing = DataItem.query.filter_by(upload_log_id=log.id).first()
if existing:
skipped += 1
continue
# 检查是否有对应的 RawDataFolder
folder = None
if log.filename:
folder_name = os.path.splitext(log.filename)[0]
folder = RawDataFolder.query.filter_by(folder_name=folder_name).first()
item = DataItem(
name=log.filename,
description=f"Uploaded archive: {log.filename}",
data_type="raw_archive",
status="completed" if log.status == "success" else log.status,
inference_status="none",
researcher_id=log.researcher_id,
uploader_id=log.uploader_id,
original_filename=log.filename,
file_size=log.file_size,
storage_path=None,
upload_log_id=log.id,
raw_data_folder_id=folder.id if folder else None,
)
if folder:
item.inference_status = folder.inference_status
item.status = folder.status
item.last_processed = folder.last_processed
db.session.add(item)
created += 1
if created % 100 == 0:
db.session.commit()
print(f" Created {created}...")
db.session.commit()
print(f" Done: created {created} (total so far), skipped {skipped}")
# 3. 同步 RawDataFolder -> DataItem(如果还没有通过 UploadLog 创建)
print("\nSyncing RawDataFolder (those not from upload)...")
for folder in RawDataFolder.query.all():
existing = DataItem.query.filter_by(raw_data_folder_id=folder.id).first()
if existing:
skipped += 1
continue
item = DataItem(
name=folder.folder_name,
description=f"Processed folder: {folder.folder_name}",
data_type="processed_folder",
status=folder.status,
inference_status=folder.inference_status,
researcher_id=folder.researcher_id,
uploader_id=None,
original_filename=None,
file_size=None,
storage_path=None,
raw_data_folder_id=folder.id,
last_processed=folder.last_processed,
)
db.session.add(item)
created += 1
if created % 100 == 0:
db.session.commit()
print(f" Created {created}...")
db.session.commit()
print(f" Done: created {created} (total), skipped {skipped}")
# 最终提交
db.session.commit()
total = DataItem.query.count()
print()
print("=" * 60)
print(f"Migration completed!")
print(f" Total DataItem: {total}")
print(f" Created this run: {created}")
print(f" Skipped (already existed): {skipped}")
print("=" * 60)
def main():
parser = argparse.ArgumentParser(description='Sync existing data to unified DataItem table')
parser.add_argument('--clear', action='store_true', help='Clear existing DataItem records before sync')
args = parser.parse_args()
sync_existing_data(clear_existing=args.clear)
if __name__ == '__main__':
main()
+45
View File
@@ -0,0 +1,45 @@
"""
验证统一数据管理数据
"""
import os
import sys
os.environ.setdefault('FLASK_ENV', 'development')
backend_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, backend_dir)
from dotenv import load_dotenv
load_dotenv()
from app import create_app, db
from app.models import DataItem
app = create_app('development')
with app.app_context():
total = DataItem.query.count()
print(f"Total DataItem: {total}")
print()
# 按类型统计
types = {}
for item in DataItem.query.all():
t = item.data_type
types[t] = types.get(t, 0) + 1
print("By data_type:")
for t, count in types.items():
print(f" {t}: {count}")
print()
print("First 5 items:")
for item in DataItem.query.order_by(DataItem.id).limit(5):
print(f" [{item.id}] {item.name} - {item.data_type} - researcher={item.researcher_id}")
print()
print("By inference_status:")
statuses = {}
for item in DataItem.query.all():
s = item.inference_status
statuses[s] = statuses.get(s, 0) + 1
for s, count in statuses.items():
print(f" {s}: {count}")
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,126 @@
# 数据管理重构设计
## 概述
本次重构对项目功能进行明确划分:
- **上传管理** - 管理原始压缩包上传
- **数据管理** - 集成管理患者数据处理全流程(分配 → 滤波 → 推理 → 推送 → 过期控制)
## 功能划分
### 1. 上传管理 (`/admin/uploads`)
**职责**:管理原始数据压缩包上传
**现有功能保持不变**:
- 上传zip/rar/7z压缩包
- 自动解压创建 `RawDataFolder` 患者文件夹
- 列表展示:文件名、文件大小、上传时间、状态、分配研究员
- 支持操作:查看详情、编辑分配、删除、批量删除、批量分配
### 2. 数据管理 (`/admin/data-entries`) → **重构为集成处理管理**
**职责**:管理解压后的患者数据文件夹 (`RawDataFolder`) 全生命周期
集成四大功能:
| 功能 | 说明 |
|------|------|
| **数据分配** | 管理员将患者文件夹分配给特定研究员账号 (仅管理员) |
| **滤波管理** | 查看滤波处理结果,管理滤波片段 |
| **推理管理** | 启动推理任务,查看推理结果 (整合原独立推理页面) |
| **过期控制** | 为推理结果设置过期时间,过期后研究员不可访问 |
**数据推送**:推理完成后自动记录推送状态,管理员可查看。
## 数据模型变更
### `InferenceResult` 新增字段
| 字段 | 类型 | 说明 |
|------|------|------|
| `expiration_date` | `DateTime` (nullable) | 过期时间,`null` 表示永久有效 |
| `is_pushed` | `Boolean` (default=False) | 是否已推送给管理员 |
| `pushed_at` | `DateTime` (nullable) | 推送时间 |
### 访问权限逻辑
- **研究员访问推理结果** 时:
- 如果 `expiration_date` 不为 `null` 且 `expiration_date < now()` → 拒绝访问
- 如果 `expiration_date` 为 `null` 或未过期 → 允许访问
- 管理员始终可以看到所有结果(包括过期)
### 现有模型兼容性
- `RawDataFolder` 已有 `researcher_id` 字段,可直接用于数据分配 ✓
- `RawDataFolder` 已有 `processed_segments` 关系用于滤波 ✓
- `DataEntry` 当前存储通用文本数据,重构后:
- `DataEntry` 保持不变(仍用于通用数据条目)
- 患者数据管理完全基于 `RawDataFolder`
## API 设计
### 新增/修改接口
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/admin/data-management/folders` | 获取患者文件夹列表(分页) |
| GET | `/admin/data-management/segments` | 获取滤波片段列表 |
| GET | `/admin/data-management/inference-results` | 获取推理结果列表(分页) |
| POST | `/admin/data-management/folders/{id}/assign` | 分配文件夹给研究员 |
| POST | `/admin/data-management/inference-results/{id}/set-expiration` | 设置推理结果过期时间 |
| POST | `/admin/data-management/inference-results/{id}/push` | 手动推送给管理员 |
| POST | `/admin/data-management/folders/{id}/run-inference` | 启动推理任务 |
| DELETE | `/admin/data-management/inference-results/{id}` | 删除推理结果 |
## 前端页面设计
### 页面结构 (`DataManagement.vue`)
1. **患者文件夹列表**(卡片/表格)
- 文件夹名称、研究员、状态、推理状态、处理时间
- 操作:分配研究员、滤波、运行推理
2. **滤波片段列表**
- 片段ID、光类型、时间范围、文件名
- 操作:下载、删除
3. **推理结果列表**
- 时间、文件夹、任务类型、诊断、通过率、阳性密度
- 过期时间状态标签
- 操作:下载CSV、设置过期、删除
### 对话框
1. **分配对话框** - 选择研究员
2. **设置过期对话框** - 选择过期日期(支持"永不过期")
3. **运行推理对话框** - 选择任务模型
### 菜单项更新
- 保持 `数据管理` 菜单项,内容改为集成管理
- 原推理页面 `/admin/inference` 移除菜单入口
## 权限控制
| 操作 | 权限 |
|------|------|
| 查看所有数据 | 管理员 |
| 分配数据 | 管理员 |
| 设置过期 | 管理员 |
| 启动推理 | 管理员 |
| 研究员查看自己的数据 | 需要被分配且未过期 |
## 向后兼容
- 现有上传管理功能完全保持不变
- 数据库迁移使用 Alembic 脚本
- 推理任务后台逻辑保持不变,仅UI整合
## 实现步骤
1. 数据库迁移:添加 `InferenceResult` 新字段
2. 后端:新增 `data_management.py` API 模块
3. 前端:新建 `DataManagement.vue` 集成页面
4. 前端:更新路由和菜单
5. 测试验证权限控制和过期逻辑