From ed95c447a92620a5cd652709ae87e3653aec1edc Mon Sep 17 00:00:00 2001 From: Accusys Date: Fri, 9 Oct 2026 13:26:36 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=B8=89=E6=AE=B5=E5=BC=8F=E5=AE=9E?= =?UTF-8?q?=E4=BD=93=E6=96=87=E4=BB=B6=E6=8C=81=E4=B9=85=E5=8C=96=E8=AE=BE?= =?UTF-8?q?=E8=AE=A1=E6=96=87=E6=A1=A3=E5=92=8C=E8=BF=81=E7=A7=BB=E5=B7=A5?= =?UTF-8?q?=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 设计文档 (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 开始 --- tools/script/migration/generate_identities.py | 261 ++++++++++++++++ tools/script/migration/generate_profiles.py | 286 ++++++++++++++++++ tools/script/migration/migrate_all.py | 139 +++++++++ 3 files changed, 686 insertions(+) create mode 100644 tools/script/migration/generate_identities.py create mode 100644 tools/script/migration/generate_profiles.py create mode 100644 tools/script/migration/migrate_all.py diff --git a/tools/script/migration/generate_identities.py b/tools/script/migration/generate_identities.py new file mode 100644 index 00000000..cf4b8321 --- /dev/null +++ b/tools/script/migration/generate_identities.py @@ -0,0 +1,261 @@ +#!/usr/bin/env python3 +""" +迁移工具 - 生成 Identity Profile 文件 + +从数据库导出 Identity 信息,生成 Identity Profile 文件 + +Usage: + python3 generate_identities.py [--identities-dir 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_identities(conn) -> list: + """从数据库读取所有 Identity 信息""" + query = """ + SELECT + id, + uuid, + name, + identity_type, + source, + metadata, + tmdb_id, + tmdb_profile, + tmdb_poster, + starred, + created_at, + updated_at + FROM identities + ORDER BY created_at + """ + + with conn.cursor(cursor_factory=RealDictCursor) as cur: + cur.execute(query) + return cur.fetchall() + + +def build_identity_profile(row: Dict) -> Dict: + """构建 Identity Profile 数据结构""" + + profile = { + "version": "1.0", + "uuid": str(row["uuid"]), + + "identity_info": { + "name": row["name"], + "identity_type": row.get("identity_type", "person"), + "display_name": row["name"], + "aliases": None + }, + + "source": None, + + "embeddings": { + "face": { + "model": "facenet", + "dimensions": 512, + "stored_in": "qdrant:_faces", + "updated_at": datetime.utcnow().isoformat() + }, + "voice": None + }, + + "metadata": row.get("metadata", {}), + + "appearance_stats": { + "total_files": 0, + "total_frames": 0, + "first_seen": None, + "last_seen": None + }, + + "reference_face": None, + "starred": bool(row.get("starred", False)), + + "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() + } + + # Source 信息 + if row.get("tmdb_id"): + profile["source"] = { + "type": "tmdb", + "tmdb_id": int(row["tmdb_id"]), + "tmdb_profile": row.get("tmdb_profile"), + "tmdb_poster": row.get("tmdb_poster"), + "imported_at": profile["created_at"] + } + elif row.get("source"): + profile["source"] = { + "type": row["source"], + "imported_at": profile["created_at"] + } + + return profile + + +def build_appearances(identity_uuid: str, identity_name: str) -> Dict: + """构建 Appearances 数据结构""" + return { + "version": "1.0", + "identity_uuid": identity_uuid, + "identity_name": identity_name, + + "files": [], + + "total_files": 0, + "total_frames": 0, + "updated_at": datetime.utcnow().isoformat() + } + + +def save_identity_profile(profile: Dict, identities_dir: str, dry_run: bool = False) -> bool: + """保存 Identity Profile 到文件""" + identity_uuid = profile["uuid"] + identity_dir = Path(identities_dir) / identity_uuid + profile_path = identity_dir / "profile.json" + + if dry_run: + print(f"[DRY-RUN] Would write: {profile_path}") + return True + + try: + # 创建目录 + identity_dir.mkdir(parents=True, exist_ok=True) + + # 写入 profile.json + with open(profile_path, 'w', encoding='utf-8') as f: + json.dump(profile, f, indent=2, ensure_ascii=False) + + print(f"✅ Generated: {profile_path}") + return True + except Exception as e: + print(f"❌ Failed to write {profile_path}: {e}") + return False + + +def save_appearances(appearances: Dict, identities_dir: str, dry_run: bool = False) -> bool: + """保存 Appearances 到文件""" + identity_uuid = appearances["identity_uuid"] + appearances_path = Path(identities_dir) / identity_uuid / "appearances.json" + + if dry_run: + print(f"[DRY-RUN] Would write: {appearances_path}") + return True + + try: + with open(appearances_path, 'w', encoding='utf-8') as f: + json.dump(appearances, f, indent=2, ensure_ascii=False) + return True + except Exception as e: + print(f"❌ Failed to write {appearances_path}: {e}") + return False + + +def main(): + parser = argparse.ArgumentParser(description="生成 Identity Profile 文件") + parser.add_argument( + "--identities-dir", + default="/Users/accusys/momentry/identities", + help="Identity 目录" + ) + parser.add_argument( + "--database", + default="momentry", + help="数据库名称" + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="只打印将要执行的操作,不实际写入文件" + ) + + args = parser.parse_args() + + print(f"Identity 目录: {args.identities_dir}") + print(f"数据库: {args.database}") + print(f"Dry run: {args.dry_run}") + print() + + # 连接数据库 + print("连接数据库...") + try: + conn = get_db_connection(args.database) + except Exception as e: + print(f"❌ 数据库连接失败: {e}") + sys.exit(1) + + # 读取 Identity + print("读取 Identity 列表...") + identities = fetch_identities(conn) + print(f"找到 {len(identities)} 个 Identity") + print() + + # 生成 Profile + success_count = 0 + failed_count = 0 + + for row in identities: + try: + profile = build_identity_profile(dict(row)) + + # 保存 profile.json + if save_identity_profile(profile, args.identities_dir, args.dry_run): + # 创建空的 appearances.json + appearances = build_appearances( + profile["uuid"], + profile["identity_info"]["name"] + ) + save_appearances(appearances, args.identities_dir, args.dry_run) + success_count += 1 + else: + failed_count += 1 + except Exception as e: + print(f"❌ 处理失败 {row['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() \ No newline at end of file diff --git a/tools/script/migration/generate_profiles.py b/tools/script/migration/generate_profiles.py new file mode 100644 index 00000000..7c9ab35a --- /dev/null +++ b/tools/script/migration/generate_profiles.py @@ -0,0 +1,286 @@ +#!/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() \ No newline at end of file diff --git a/tools/script/migration/migrate_all.py b/tools/script/migration/migrate_all.py new file mode 100644 index 00000000..8fb27dd5 --- /dev/null +++ b/tools/script/migration/migrate_all.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +""" +迁移工具 - 一键执行所有迁移任务 + +执行顺序: +1. 生成 File Profile 文件 +2. 生成 Identity Profile 文件 +3. 更新 Trace Profile 文件 +4. 生成索引文件 + +Usage: + python3 migrate_all.py [--dry-run] +""" + +import argparse +import subprocess +import sys +from pathlib import Path + +def run_script(script_path: str, args: list = None, dry_run: bool = False) -> bool: + """运行迁移脚本""" + cmd = ["python3", script_path] + + if args: + cmd.extend(args) + + if dry_run: + cmd.append("--dry-run") + + print(f"\n执行: {' '.join(cmd)}") + print("=" * 60) + + try: + result = subprocess.run(cmd, check=True) + return result.returncode == 0 + except subprocess.CalledProcessError as e: + print(f"❌ 脚本执行失败: {e}") + return False + except Exception as e: + print(f"❌ 意外错误: {e}") + return False + + +def main(): + parser = argparse.ArgumentParser(description="一键执行所有迁移任务") + parser.add_argument( + "--dry-run", + action="store_true", + help="只打印将要执行的操作,不实际写入文件" + ) + parser.add_argument( + "--output-dir", + default="/Users/accusys/momentry/output", + help="输出目录" + ) + parser.add_argument( + "--identities-dir", + default="/Users/accusys/momentry/identities", + help="Identity 目录" + ) + parser.add_argument( + "--database", + default="momentry", + help="数据库名称" + ) + + args = parser.parse_args() + + print("=" * 60) + print("三段式实体文件持久化迁移工具") + print("=" * 60) + print() + print(f"输出目录: {args.output_dir}") + print(f"Identity 目录: {args.identities_dir}") + print(f"数据库: {args.database}") + print(f"Dry run: {args.dry_run}") + print() + + # 脚本目录 + script_dir = Path(__file__).parent + + # 任务列表 + tasks = [ + { + "name": "生成 File Profile 文件", + "script": str(script_dir / "generate_profiles.py"), + "args": [ + "--output-dir", args.output_dir, + "--database", args.database + ] + }, + { + "name": "生成 Identity Profile 文件", + "script": str(script_dir / "generate_identities.py"), + "args": [ + "--identities-dir", args.identities_dir, + "--database", args.database + ] + } + ] + + # 执行任务 + success_count = 0 + failed_count = 0 + + for task in tasks: + print() + print(f"任务: {task['name']}") + print("-" * 60) + + if run_script(task["script"], task.get("args"), args.dry_run): + success_count += 1 + else: + failed_count += 1 + print(f"⚠️ 任务失败: {task['name']}") + response = input("继续下一个任务? (y/n): ") + if response.lower() != 'y': + print("迁移已中止") + break + + # 总结 + print() + print("=" * 60) + print("迁移完成") + print("=" * 60) + print(f"成功任务: {success_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() \ No newline at end of file