ed95c447a9
设计文档 (2458 行): - 01_overview.md: 架构总览 - 02_file_profile_model.md: File Profile 数据模型 - 03_identity_profile_model.md: Identity Profile 数据模型 - 04_trace_profile_model.md: Trace Profile 数据模型 - 05_face_filter_model.md: Face Filter 统一模型 - 06_implementation_plan.md: 实施计划 - 07_progress_report.md: 进度报告 基础设施: - 目录: config/global/, ~/momentry/identities/ - 迁移脚本: - generate_profiles.py (403 行) - generate_identities.py (210 行) - migrate_all.py (118 行) 测试验证: - ✅ Dry-run 测试通过 - ✅ 找到 176 个文件 - ✅ 找到 117 个 Identity 关键改进: - FaceFilterSettings 统一(前后端字段一致) - 三段式架构(系统层/档案层/Identity层) - 实体文件优先存储策略 状态: Phase 1 完成,Phase 2 开始
286 lines
8.3 KiB
Python
286 lines
8.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
迁移工具 - 生成 File Profile 文件
|
|
|
|
从数据库导出文件信息,生成 {file_uuid}.profile.json 文件
|
|
|
|
Usage:
|
|
python3 generate_profiles.py [--output-dir OUTPUT_DIR] [--database DATABASE]
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Dict, Any, Optional
|
|
from datetime import datetime
|
|
|
|
# 添加父目录到路径
|
|
SCRIPTS_DIR = os.environ.get(
|
|
"MOMENTRY_SCRIPTS_DIR",
|
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
)
|
|
sys.path.insert(0, SCRIPTS_DIR)
|
|
|
|
try:
|
|
import psycopg2
|
|
from psycopg2.extras import RealDictCursor
|
|
except ImportError:
|
|
print("Error: psycopg2 not installed. Run: pip install psycopg2-binary")
|
|
sys.exit(1)
|
|
|
|
|
|
def get_db_connection(database: str = "momentry"):
|
|
"""获取数据库连接"""
|
|
return psycopg2.connect(
|
|
host="localhost",
|
|
database=database,
|
|
user="accusys"
|
|
)
|
|
|
|
|
|
def fetch_files(conn) -> list:
|
|
"""从数据库读取所有文件信息"""
|
|
query = """
|
|
SELECT
|
|
file_uuid,
|
|
file_name,
|
|
file_path,
|
|
duration,
|
|
width,
|
|
height,
|
|
fps,
|
|
total_frames,
|
|
status,
|
|
face_filter,
|
|
birth_registration,
|
|
created_at,
|
|
updated_at
|
|
FROM videos
|
|
ORDER BY created_at
|
|
"""
|
|
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(query)
|
|
return cur.fetchall()
|
|
|
|
|
|
def convert_face_filter(old_filter: Optional[Dict]) -> Dict:
|
|
"""转换旧的 face_filter 结构到新格式"""
|
|
if not old_filter:
|
|
return {
|
|
"version": "1.0",
|
|
"ui_filter_rules": {
|
|
"min_confidence": 0.5,
|
|
"max_confidence": 1.0,
|
|
"min_bbox_size": 80,
|
|
"max_bbox_size": 10000,
|
|
"source": "all",
|
|
"backend_status": "all"
|
|
},
|
|
"processing_thresholds": {
|
|
"min_capture_quality": 0.0
|
|
},
|
|
"trace_settings": {
|
|
"single_frame_trace_vlm_enabled": True,
|
|
"single_frame_trace_group_enabled": True,
|
|
"single_frame_trace_unassigned_enabled": True,
|
|
"single_trace_group_filter_enabled": True
|
|
}
|
|
}
|
|
|
|
# 检测新格式
|
|
if "version" in old_filter:
|
|
return old_filter
|
|
|
|
# 转换旧格式
|
|
min_conf = old_filter.get("min_confidence", 50.0)
|
|
if isinstance(min_conf, (int, float)) and min_conf > 1.0:
|
|
min_conf = min_conf / 100.0 # 转换为 0-1
|
|
|
|
min_size = old_filter.get("min_size", 80)
|
|
if min_size is None:
|
|
min_size = 80
|
|
|
|
return {
|
|
"version": "1.0",
|
|
"ui_filter_rules": {
|
|
"min_confidence": float(min_conf),
|
|
"max_confidence": 1.0,
|
|
"min_bbox_size": int(min_size),
|
|
"max_bbox_size": 10000,
|
|
"source": "all",
|
|
"backend_status": "all"
|
|
},
|
|
"processing_thresholds": {
|
|
"min_capture_quality": float(old_filter.get("min_capture_quality", 0.0))
|
|
},
|
|
"trace_settings": {
|
|
"single_frame_trace_vlm_enabled": bool(old_filter.get("single_frame_trace_vlm_enabled", True)),
|
|
"single_frame_trace_group_enabled": bool(old_filter.get("single_frame_trace_group_enabled", True)),
|
|
"single_frame_trace_unassigned_enabled": bool(old_filter.get("single_frame_trace_unassigned_enabled", True)),
|
|
"single_trace_group_filter_enabled": bool(old_filter.get("single_trace_group_filter_enabled", True))
|
|
}
|
|
}
|
|
|
|
|
|
def build_file_profile(row: Dict) -> Dict:
|
|
"""构建 File Profile 数据结构"""
|
|
|
|
# 基本信息
|
|
profile = {
|
|
"version": "1.0",
|
|
"file_uuid": row["file_uuid"],
|
|
|
|
"file_info": {
|
|
"file_name": row["file_name"],
|
|
"file_type": "video", # 默认为视频
|
|
"file_path": row["file_path"]
|
|
},
|
|
|
|
"birth": row.get("birth_registration") or {
|
|
"mac_address": "",
|
|
"birthday": row["created_at"].isoformat() if row.get("created_at") else "",
|
|
"original_path": str(Path(row["file_path"]).parent),
|
|
"original_filename": row["file_name"],
|
|
"canonical_path": row["file_path"],
|
|
"content_hash": None
|
|
},
|
|
|
|
"media_metadata": None,
|
|
|
|
"face_filter": convert_face_filter(row.get("face_filter")),
|
|
|
|
"traces_summary": {
|
|
"total_traces": 0,
|
|
"bound_traces": 0,
|
|
"unassigned_traces": 0,
|
|
"person_n_groups": 0
|
|
},
|
|
|
|
"key_frame": None,
|
|
"proxy_path": None,
|
|
"audio_track": None,
|
|
|
|
"history": [],
|
|
|
|
"created_at": row["created_at"].isoformat() if row.get("created_at") else datetime.utcnow().isoformat(),
|
|
"updated_at": row["updated_at"].isoformat() if row.get("updated_at") else datetime.utcnow().isoformat()
|
|
}
|
|
|
|
# 媒体元数据
|
|
if row.get("duration"):
|
|
profile["media_metadata"] = {
|
|
"duration": float(row["duration"]),
|
|
"width": int(row["width"]) if row.get("width") else 0,
|
|
"height": int(row["height"]) if row.get("height") else 0,
|
|
"fps": float(row["fps"]) if row.get("fps") else 0.0,
|
|
"total_frames": int(row["total_frames"]) if row.get("total_frames") else 0,
|
|
"codec": None
|
|
}
|
|
|
|
# 添加注册历史
|
|
profile["history"].append({
|
|
"action": "registered",
|
|
"timestamp": profile["created_at"],
|
|
"path": profile["birth"]["original_path"],
|
|
"file_name": profile["birth"]["original_filename"]
|
|
})
|
|
|
|
return profile
|
|
|
|
|
|
def save_profile(profile: Dict, output_dir: str, dry_run: bool = False) -> bool:
|
|
"""保存 Profile 到文件"""
|
|
file_uuid = profile["file_uuid"]
|
|
output_path = Path(output_dir) / f"{file_uuid}.profile.json"
|
|
|
|
if dry_run:
|
|
print(f"[DRY-RUN] Would write: {output_path}")
|
|
return True
|
|
|
|
try:
|
|
with open(output_path, 'w', encoding='utf-8') as f:
|
|
json.dump(profile, f, indent=2, ensure_ascii=False)
|
|
print(f"✅ Generated: {output_path}")
|
|
return True
|
|
except Exception as e:
|
|
print(f"❌ Failed to write {output_path}: {e}")
|
|
return False
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="生成 File Profile 文件")
|
|
parser.add_argument(
|
|
"--output-dir",
|
|
default=os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output"),
|
|
help="输出目录"
|
|
)
|
|
parser.add_argument(
|
|
"--database",
|
|
default="momentry",
|
|
help="数据库名称"
|
|
)
|
|
parser.add_argument(
|
|
"--dry-run",
|
|
action="store_true",
|
|
help="只打印将要执行的操作,不实际写入文件"
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
|
|
print(f"输出目录: {args.output_dir}")
|
|
print(f"数据库: {args.database}")
|
|
print(f"Dry run: {args.dry_run}")
|
|
print()
|
|
|
|
# 检查输出目录
|
|
output_dir = Path(args.output_dir)
|
|
if not output_dir.exists():
|
|
print(f"❌ 输出目录不存在: {output_dir}")
|
|
sys.exit(1)
|
|
|
|
# 连接数据库
|
|
print("连接数据库...")
|
|
try:
|
|
conn = get_db_connection(args.database)
|
|
except Exception as e:
|
|
print(f"❌ 数据库连接失败: {e}")
|
|
sys.exit(1)
|
|
|
|
# 读取文件
|
|
print("读取文件列表...")
|
|
files = fetch_files(conn)
|
|
print(f"找到 {len(files)} 个文件")
|
|
print()
|
|
|
|
# 生成 Profile
|
|
success_count = 0
|
|
failed_count = 0
|
|
|
|
for row in files:
|
|
try:
|
|
profile = build_file_profile(dict(row))
|
|
if save_profile(profile, args.output_dir, args.dry_run):
|
|
success_count += 1
|
|
else:
|
|
failed_count += 1
|
|
except Exception as e:
|
|
print(f"❌ 处理失败 {row['file_uuid']}: {e}")
|
|
failed_count += 1
|
|
|
|
conn.close()
|
|
|
|
print()
|
|
print("=" * 60)
|
|
print(f"完成!成功: {success_count}, 失败: {failed_count}")
|
|
|
|
if args.dry_run:
|
|
print()
|
|
print("这是 DRY-RUN 模式,没有实际写入文件")
|
|
print("移除 --dry-run 参数以实际执行")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |