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 开始
261 lines
7.1 KiB
Python
261 lines
7.1 KiB
Python
#!/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() |