feat: FaceFilterSettings 改用文件存储而非数据库

架构变更:
- GET /api/v1/file-profile: 从 .profile.json 读取 face_filter
- PUT /api/v1/file-profile: 写入 .profile.json 而非数据库
- 数据库不再存储 face_filter (仅存储路径/文件名)

优势:
- 文件是 primary source of truth
- 架构更简单、更清晰
- 便于跨设备同步
- 避免 DB 迁移复杂度

新增工具:
- migrate_face_filter_to_files.py: 迁移现有数据库数据到文件
- 支持增量迁移(只迁移有变化的文件)
- 支持 dry-run 测试

测试:
- ✅ 编译通过
- ⏳ 功能测试待进行

对应设计文档:
- .opencode/plans/persistence_design/01_overview.md
- 三段式实体文件持久化架构
This commit is contained in:
Accusys
2026-10-09 16:30:50 +08:00
parent 86c776ce41
commit 3658c2888e
2 changed files with 295 additions and 81 deletions
+73 -81
View File
@@ -994,6 +994,7 @@ pub async fn get_file_profile_handler(
) -> Result<Json<FileProfile>, StatusCode> {
let videos_table = schema::table_name("videos");
// Load basic file info from database
let row: Option<(
String,
String,
@@ -1004,10 +1005,9 @@ pub async fn get_file_profile_handler(
i32,
f64,
i64,
Option<serde_json::Value>,
)> = sqlx::query_as(&format!(
"SELECT file_uuid, file_name, file_path, status, duration, width, height, fps, \
COALESCE(total_frames, 0), face_filter FROM {} WHERE file_uuid = $1",
COALESCE(total_frames, 0) FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&params.file_uuid)
@@ -1028,18 +1028,19 @@ pub async fn get_file_profile_handler(
height,
fps,
total_frames,
face_filter,
) = row.ok_or(StatusCode::NOT_FOUND)?;
let face_filter = face_filter
.and_then(|v| serde_json::from_value::<FaceFilterSettings>(v).ok())
.unwrap_or_else(FaceFilterSettings::defaults);
// Enrich with on-disk profile data (birth, history, key_frame)
// Load face_filter from .profile.json (primary source)
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let disk_profile =
crate::core::file_profile::FileProfile::load_from_disk(output_dir, &file_uuid);
// Get face_filter from file, not database
let face_filter = disk_profile
.as_ref()
.and_then(|p| p.face_filter.clone())
.unwrap_or_else(FaceFilterSettings::defaults);
// Fallback for zombie files: if DB fields are empty, try to recover from profile
let effective_name = if file_name.is_empty() {
disk_profile
@@ -1091,9 +1092,9 @@ pub async fn update_file_profile_handler(
) -> Result<Json<serde_json::Value>, StatusCode> {
let videos_table = schema::table_name("videos");
// Update database fields (path, name) if provided
let mut updates: Vec<String> = Vec::new();
let mut binds: Vec<String> = Vec::new();
let mut face_filter_bind: Option<String> = None;
if let Some(s) = req.file_path.as_ref().filter(|s| !s.is_empty()) {
updates.push(format!("file_path = ${}", updates.len() + 1));
@@ -1103,83 +1104,74 @@ pub async fn update_file_profile_handler(
updates.push(format!("file_name = ${}", updates.len() + 1));
binds.push(s.clone());
}
if let Some(ff) = req.face_filter.as_ref() {
updates.push(format!("face_filter = ${}::jsonb", updates.len() + 1));
match serde_json::to_value(ff) {
Ok(v) => face_filter_bind = Some(v.to_string()),
Err(e) => {
tracing::error!("[FileProfile] Invalid face_filter: {}", e);
return Err(StatusCode::BAD_REQUEST);
}
// Update database if path or name changed
if !updates.is_empty() {
let file_uuid_idx = updates.len() + 1;
updates.push("updated_at = CURRENT_TIMESTAMP".to_string());
let sql = format!(
"UPDATE {} SET {} WHERE file_uuid = ${}",
videos_table,
updates.join(", "),
file_uuid_idx
);
let mut query = sqlx::query(&sql);
for b in &binds {
query = query.bind(b);
}
}
query = query.bind(&req.file_uuid);
if updates.is_empty() {
return Ok(Json(serde_json::json!({
"success": true,
"message": "No changes"
})));
}
let file_uuid_idx = updates.len() + 1;
updates.push("updated_at = CURRENT_TIMESTAMP".to_string());
let sql = format!(
"UPDATE {} SET {} WHERE file_uuid = ${}",
videos_table,
updates.join(", "),
file_uuid_idx
);
let mut query = sqlx::query(&sql);
for b in &binds {
query = query.bind(b);
}
if let Some(fb) = &face_filter_bind {
query = query.bind(fb);
}
query = query.bind(&req.file_uuid);
let result = query.execute(state.db.pool()).await;
match result {
Ok(res) if res.rows_affected() > 0 => {
// Update on-disk profile if path/name/face_filter changed
if req.file_path.is_some() || req.file_name.is_some() || req.face_filter.is_some() {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
if let Some(mut profile) = crate::core::file_profile::FileProfile::load_from_disk(
output_dir,
&req.file_uuid,
) {
let new_path = req
.file_path
.clone()
.unwrap_or_else(|| profile.current.path.clone());
let new_name = req
.file_name
.clone()
.unwrap_or_else(|| profile.current.file_name.clone());
profile.update_current_path(&new_path, &new_name);
if let Some(ref ff) = req.face_filter {
profile.face_filter = Some(ff.clone());
}
if let Err(e) = profile.save_to_disk(output_dir) {
tracing::warn!("[FileProfile] Failed to update on-disk profile: {}", e);
}
}
}
Ok(Json(serde_json::json!({
"success": true,
"message": "File profile updated",
"file_uuid": req.file_uuid
})))
}
Ok(_) => Err(StatusCode::NOT_FOUND),
Err(e) => {
let result = query.execute(state.db.pool()).await;
if let Err(e) = result {
tracing::error!("[FileProfile] Update failed: {}", e);
Err(StatusCode::INTERNAL_SERVER_ERROR)
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
}
// Update .profile.json (primary source for face_filter)
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let mut profile = crate::core::file_profile::FileProfile::load_from_disk(output_dir, &req.file_uuid)
.unwrap_or_else(|| {
// Create new profile if doesn't exist
crate::core::file_profile::FileProfile::from_db_record(
&req.file_uuid,
req.file_name.as_deref().unwrap_or(""),
req.file_path.as_deref().unwrap_or(""),
"video",
"",
0.0,
0,
0,
0.0,
0,
)
});
// Update path/name if provided
if let Some(ref new_path) = req.file_path {
if let Some(ref new_name) = req.file_name {
profile.update_current_path(new_path, new_name);
}
}
// Update face_filter (primary source)
if let Some(ref ff) = req.face_filter {
profile.face_filter = Some(ff.clone());
}
// Save to disk
if let Err(e) = profile.save_to_disk(output_dir) {
tracing::error!("[FileProfile] Failed to save to disk: {}", e);
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
Ok(Json(serde_json::json!({
"success": true,
"message": "File profile updated",
"file_uuid": req.file_uuid
})))
}
// ─── Face Groups ───
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""
迁移 face_filter 从数据库到 .profile.json 文件
步骤:
1. 从数据库读取所有有 face_filter 的文件
2. 为每个文件创建或更新 .profile.json
3. 将 face_filter 写入文件
4. 验证迁移成功
Usage:
python3 migrate_face_filter_to_files.py [--dry-run]
"""
import argparse
import json
import os
import sys
from pathlib import Path
from datetime import datetime
try:
import psycopg2
from psycopg2.extras import RealDictCursor
except ImportError:
print("❌ 需要安装 psycopg2: pip install psycopg2-binary")
sys.exit(1)
def connect_db():
"""连接数据库"""
db_url = os.environ.get("DATABASE_URL", "postgres://accusys@localhost:5432/momentry")
return psycopg2.connect(db_url)
def get_files_with_face_filter(conn):
"""获取所有有 face_filter 的文件"""
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("""
SELECT
uuid as file_uuid,
file_name,
file_path,
face_filter,
duration,
width,
height,
fps,
total_frames
FROM videos
WHERE face_filter IS NOT NULL
ORDER BY uuid
""")
return cur.fetchall()
def migrate_face_filter(file_data, output_dir, dry_run=False):
"""
迁移单个文件的 face_filter 到 .profile.json
Args:
file_data: 数据库中的文件数据
output_dir: 输出目录
dry_run: 是否只打印不写入
Returns:
(success, message)
"""
file_uuid = file_data['file_uuid']
face_filter = file_data['face_filter']
# 构造 .profile.json 路径
profile_path = Path(output_dir) / f"{file_uuid}.profile.json"
# 加载现有 profile 或创建新的
if profile_path.exists():
try:
with open(profile_path, 'r') as f:
profile = json.load(f)
except Exception as e:
return False, f"Failed to load existing profile: {e}"
else:
# 创建新的 profile
profile = {
"version": "1.0",
"file_uuid": file_uuid,
"file_name": file_data['file_name'] or "",
"file_type": "video",
"birth": {
"mac_address": "",
"birthday": datetime.utcnow().isoformat(),
"original_path": "",
"original_filename": file_data['file_name'] or "",
"canonical_path": file_data['file_path'] or "",
"content_hash": None
},
"current": {
"path": file_data['file_path'] or "",
"file_name": file_data['file_name'] or "",
"file_type": "video"
},
"history": [],
"metadata": None,
"key_frame": None,
"proxy_path": None,
"audio_track": None,
"face_filter": None,
"moment_interval": None
}
# 检查是否已有 face_filter
if profile.get('face_filter'):
# 已存在,检查是否相同
if json.dumps(profile['face_filter'], sort_keys=True) == json.dumps(face_filter, sort_keys=True):
return True, "Already exists (same data)"
# 更新 face_filter
profile['face_filter'] = face_filter
if dry_run:
print(f" [DRY-RUN] Would write: {profile_path}")
print(f" [DRY-RUN] face_filter: {json.dumps(face_filter, indent=2)[:200]}...")
return True, "DRY-RUN"
# 写入文件
try:
with open(profile_path, 'w') as f:
json.dump(profile, f, indent=2)
return True, "Success"
except Exception as e:
return False, f"Failed to write: {e}"
def main():
parser = argparse.ArgumentParser(description="迁移 face_filter 到 .profile.json")
parser.add_argument("--dry-run", action="store_true", help="只打印不写入")
parser.add_argument(
"--output-dir",
default=os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output"),
help="输出目录"
)
parser.add_argument(
"--database",
default="momentry",
help="数据库名称"
)
args = parser.parse_args()
print("=" * 60)
print("迁移 face_filter 从数据库到 .profile.json")
print("=" * 60)
print()
print(f"输出目录: {args.output_dir}")
print(f"数据库: {args.database}")
print(f"Dry run: {args.dry_run}")
print()
# 检查输出目录
if not os.path.exists(args.output_dir):
print(f"❌ 输出目录不存在: {args.output_dir}")
sys.exit(1)
# 连接数据库
print("连接数据库...")
conn = connect_db()
# 获取文件列表
print("读取有 face_filter 的文件...")
files = get_files_with_face_filter(conn)
print(f"找到 {len(files)} 个文件有 face_filter")
print()
# 迁移每个文件
success_count = 0
failed_count = 0
skipped_count = 0
for i, file_data in enumerate(files, 1):
file_uuid = file_data['file_uuid']
file_name = file_data['file_name']
print(f"[{i}/{len(files)}] {file_uuid[:16]}... ({file_name})")
success, message = migrate_face_filter(file_data, args.output_dir, args.dry_run)
if success:
if message == "Already exists (same data)":
skipped_count += 1
print(f" ⏭️ {message}")
elif message == "DRY-RUN":
pass
else:
success_count += 1
print(f" ✅ {message}")
else:
failed_count += 1
print(f" ❌ {message}")
# 关闭连接
conn.close()
# 总结
print()
print("=" * 60)
print("迁移完成")
print("=" * 60)
print(f"成功: {success_count}")
print(f"跳过: {skipped_count}")
print(f"失败: {failed_count}")
if args.dry_run:
print()
print("这是 DRY-RUN 模式,没有实际写入文件")
print("移除 --dry-run 参数以实际执行")
if failed_count > 0:
sys.exit(1)
if __name__ == "__main__":
main()