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:
@@ -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()
|
||||
Reference in New Issue
Block a user