From 6c85d2e871819ccd471cfb4bc04cf5e8397bfafc Mon Sep 17 00:00:00 2001 From: Accusys Date: Mon, 2 Nov 2026 17:00:20 +0800 Subject: [PATCH] feat: add upgrade_face_json_v2.sh and sync_face_data.sh scripts, fix SQLite path --- scripts/sync_face_data.sh | 207 ++++++++++++++++++++++++++++++++ scripts/upgrade_face_json_v2.sh | 172 ++++++++++++++++++++++++++ 2 files changed, 379 insertions(+) create mode 100755 scripts/sync_face_data.sh create mode 100755 scripts/upgrade_face_json_v2.sh diff --git a/scripts/sync_face_data.sh b/scripts/sync_face_data.sh new file mode 100755 index 00000000..c7227602 --- /dev/null +++ b/scripts/sync_face_data.sh @@ -0,0 +1,207 @@ +#!/bin/bash +# Sync face JSON files to SQLite and Qdrant +# Usage: ./scripts/sync_face_data.sh [file_uuid] + +OUTPUT_DIR="${MOMENTRY_OUTPUT_DIR:-/Users/accusys/momentry/output}" + +sync_face_data() { + local uuid=$1 + local face_json="$OUTPUT_DIR/${uuid}.face.json" + local traced_json="$OUTPUT_DIR/${uuid}.face_traced.json" + local cluster_json="$OUTPUT_DIR/${uuid}.face_cluster.json" + local trace_dir="$OUTPUT_DIR/${uuid}" + + if [ ! -f "$face_json" ]; then + echo "⚠️ face.json not found for $uuid" + return + fi + + echo "🔄 Syncing $uuid..." + + # Create face_operations.sqlite + python3 << 'PYEOF' +import json +import sqlite3 +import os +import sys +from datetime import datetime + +uuid = sys.argv[1] if len(sys.argv) > 1 else "" +output_dir = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output") + +face_json = f"{output_dir}/{uuid}.face.json" +traced_json = f"{output_dir}/{uuid}.face_traced.json" +cluster_json = f"{output_dir}/{uuid}.face_cluster.json" +trace_dir = f"{output_dir}/{uuid}" +db_path = f"{trace_dir}/face_operations.sqlite" + +# Ensure directory exists +os.makedirs(trace_dir, exist_ok=True) + +# Connect to SQLite +conn = sqlite3.connect(db_path) +c = conn.cursor() + +# Create tables +c.executescript(""" +CREATE TABLE IF NOT EXISTS processing_status ( + file_uuid TEXT PRIMARY KEY, + detection_done BOOLEAN DEFAULT FALSE, + traces_done BOOLEAN DEFAULT FALSE, + clusters_done BOOLEAN DEFAULT FALSE, + vlm_done BOOLEAN DEFAULT FALSE, + last_updated DATETIME DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS face_groups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + file_uuid TEXT NOT NULL, + group_name TEXT NOT NULL, + trace_ids TEXT, + total_faces INTEGER DEFAULT 0, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(file_uuid, group_name) +); + +CREATE TABLE IF NOT EXISTS trace_custom ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + file_uuid TEXT NOT NULL, + trace_id INTEGER NOT NULL, + label TEXT, + group_name TEXT, + notes TEXT, + custom_properties TEXT, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(file_uuid, trace_id) +); + +CREATE TABLE IF NOT EXISTS group_operations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + file_uuid TEXT NOT NULL, + operation TEXT NOT NULL, + before_json TEXT, + after_json TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP +); +""") + +# Update processing status +now = datetime.now().isoformat() + +# Check face.json +if os.path.exists(face_json): + c.execute("INSERT OR REPLACE INTO processing_status (file_uuid, detection_done, last_updated) VALUES (?, ?, ?)", + (uuid, True, now)) + print(" ✅ processing_status: detection_done=True") + +# Check face_traced.json +if os.path.exists(traced_json): + c.execute("UPDATE processing_status SET traces_done = ?, last_updated = ? WHERE file_uuid = ?", + (True, now, uuid)) + print(" ✅ processing_status: traces_done=True") + + # Load traces and insert into trace_custom + with open(traced_json) as f: + traced = json.load(f) + + for trace in traced.get('traces', []): + trace_id = trace.get('trace_id') + if trace_id is not None: + # Check if trace_profile.json exists + tp_path = f"{trace_dir}/trace_{trace_id}/trace_profile.json" + label = None + group_name = None + if os.path.exists(tp_path): + with open(tp_path) as tf: + tp = json.load(tf) + label = tp.get('label') or tp.get('name') + + c.execute(""" + INSERT INTO trace_custom (file_uuid, trace_id, label, updated_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(file_uuid, trace_id) DO UPDATE SET + label = ?, updated_at = ? + """, (uuid, trace_id, label, now, label, now)) + + print(f" ✅ trace_custom: {len(traced.get('traces', []))} traces synced") + +# Check face_cluster.json +if os.path.exists(cluster_json): + c.execute("UPDATE processing_status SET clusters_done = ?, last_updated = ? WHERE file_uuid = ?", + (True, now, uuid)) + print(" ✅ processing_status: clusters_done=True") + + # Load clusters and insert into face_groups + with open(cluster_json) as f: + cluster = json.load(f) + + for cl in cluster.get('clusters', []): + group_name = cl.get('group_name', f"Person_{cl.get('cluster_id', 0)}") + trace_ids = json.dumps(cl.get('trace_ids', [])) + total_faces = cl.get('total_faces', 0) + + c.execute(""" + INSERT OR IGNORE INTO face_groups (file_uuid, group_name, trace_ids, total_faces) + VALUES (?, ?, ?, ?) + """, (uuid, group_name, trace_ids, total_faces)) + + print(f" ✅ face_groups: {len(cluster.get('clusters', []))} groups synced") + +# Check VLM (trace_profile.json with vlm_summary) +vlm_done = False +if os.path.exists(trace_dir): + for td in os.listdir(trace_dir): + tp_path = f"{trace_dir}/{td}/trace_profile.json" + if os.path.exists(tp_path): + with open(tp_path) as f: + tp = json.load(f) + if tp.get('vlm_summary'): + vlm_done = True + break + +if vlm_done: + c.execute("UPDATE processing_status SET vlm_done = ?, last_updated = ? WHERE file_uuid = ?", + (True, now, uuid)) + print(" ✅ processing_status: vlm_done=True") + +# Commit and close +conn.commit() +conn.close() + +print(f" ✅ face_operations.sqlite created at {db_path}") +PYEOF + + # Sync to Qdrant (if face.json has embeddings) + python3 -c " +import json +import subprocess + +face_json = '$face_json' +with open(face_json) as f: + d = json.load(f) + +has_embeddings = any(face.get('embedding') for frame in d.get('frames', []) for face in frame.get('faces', [])) + +if has_embeddings: + print(' 🔄 Syncing embeddings to Qdrant...') + # Note: The actual Qdrant sync is done by rust_store_traced_faces + # This is just a placeholder for future direct sync + print(' ⏭️ Qdrant sync skipped (use rust_store_traced_faces)') +else: + print(' ⏭️ No embeddings to sync') +" + + echo "✅ $uuid sync complete" +} + +# Main +if [ -n "$1" ]; then + sync_face_data "$1" +else + echo "Syncing all face data..." + for f in "$OUTPUT_DIR"/*.face.json; do + uuid=$(basename "$f" .face.json) + sync_face_data "$uuid" + done + echo "✅ All syncs complete" +fi diff --git a/scripts/upgrade_face_json_v2.sh b/scripts/upgrade_face_json_v2.sh new file mode 100755 index 00000000..8576cd66 --- /dev/null +++ b/scripts/upgrade_face_json_v2.sh @@ -0,0 +1,172 @@ +#!/bin/bash +# Upgrade face JSON files from v1 to v2 schema +# Usage: ./scripts/upgrade_face_json_v2.sh [file_uuid] + +OUTPUT_DIR="${MOMENTRY_OUTPUT_DIR:-/Users/accusys/momentry/output}" + +upgrade_face_json() { + local uuid=$1 + local face_json="$OUTPUT_DIR/${uuid}.face.json" + local traced_json="$OUTPUT_DIR/${uuid}.face_traced.json" + local cluster_json="$OUTPUT_DIR/${uuid}.face_cluster.json" + + if [ ! -f "$face_json" ]; then + echo "⚠️ face.json not found for $uuid" + return + fi + + echo "🔄 Upgrading $uuid to v2..." + + # Upgrade face.json + python3 -c " +import json + +with open('$face_json') as f: + d = json.load(f) + +# Add schema_version +d['schema_version'] = '2.0' + +# Add x2, y2, center_x, center_y to each face +for frame in d.get('frames', []): + for face in frame.get('faces', []): + x = face.get('x', 0) + y = face.get('y', 0) + w = face.get('width', 0) + h = face.get('height', 0) + face['x2'] = x + w + face['y2'] = y + h + face['center_x'] = x + w // 2 + face['center_y'] = y + h // 2 + +with open('$face_json', 'w') as f: + json.dump(d, f, indent=2) + +print(' ✅ face.json upgraded') +" + + # Upgrade face_traced.json + if [ -f "$traced_json" ]; then + python3 -c " +import json + +with open('$traced_json') as f: + d = json.load(f) + +fps = d.get('fps', 30.0) + +# Add schema_version and restructure +d['schema_version'] = '2.0' +d['file_uuid'] = '$uuid' +d['status'] = 'completed' + +# Convert traces from HashMap to Vec +traces_old = d.get('traces', {}) +traces_new = [] +for tid, t in traces_old.items(): + trace_id = int(tid) + path = t.get('path', []) + frames_list = t.get('frames', []) + + # Calculate stats + start_frame = path[0]['frame'] if path else 0 + end_frame = path[-1]['frame'] if path else 0 + start_time = start_frame / fps + end_time = end_frame / fps + avg_confidence = sum(p['confidence'] for p in path) / len(path) if path else 0 + + # Calculate avg_bbox + if path: + avg_x = sum(p['bbox']['x'] for p in path) // len(path) + avg_y = sum(p['bbox']['y'] for p in path) // len(path) + avg_w = sum(p['bbox']['width'] for p in path) // len(path) + avg_h = sum(p['bbox']['height'] for p in path) // len(path) + else: + avg_x = avg_y = avg_w = avg_h = 0 + + # Add x2/y2/center to bbox + for p in path: + b = p['bbox'] + b['x2'] = b['x'] + b['width'] + b['y2'] = b['y'] + b['height'] + b['center_x'] = b['x'] + b['width'] // 2 + b['center_y'] = b['y'] + b['height'] // 2 + + traces_new.append({ + 'trace_id': trace_id, + 'frame_count': len(path), + 'start_frame': start_frame, + 'end_frame': end_frame, + 'start_time': start_time, + 'end_time': end_time, + 'avg_confidence': avg_confidence, + 'avg_capture_quality': 0.0, + 'best_frame': max(path, key=lambda p: p['confidence'])['frame'] if path else 0, + 'best_confidence': max(p['confidence'] for p in path) if path else 0, + 'avg_bbox': { + 'x': avg_x, 'y': avg_y, 'width': avg_w, 'height': avg_h, + 'x2': avg_x + avg_w, 'y2': avg_y + avg_h, + 'center_x': avg_x + avg_w // 2, 'center_y': avg_y + avg_h // 2 + }, + 'face_instances': path, + 'total_appearances': t.get('total_appearances', 0), + 'path': path, + 'frames': frames_list + }) + +d['traces'] = traces_new +d['stats'] = { + 'total_traces': len(traces_new), + 'total_face_instances': sum(t['frame_count'] for t in traces_new), + 'avg_trace_length': sum(t['frame_count'] for t in traces_new) / len(traces_new) if traces_new else 0 +} + +with open('$traced_json', 'w') as f: + json.dump(d, f, indent=2) + +print(' ✅ face_traced.json upgraded') +" + fi + + # Upgrade face_cluster.json + if [ -f "$cluster_json" ]; then + python3 -c " +import json + +with open('$cluster_json') as f: + d = json.load(f) + +# Add schema_version and stats +d['schema_version'] = '2.0' +d['status'] = d.get('status', 'completed') + +# Add stats +clusters = d.get('clusters', []) +total_traces = sum(len(c.get('trace_ids', [])) for c in clusters) +d['stats'] = { + 'total_clusters': len(clusters), + 'unassigned_traces': len(d.get('unassigned_traces', [])), + 'total_traces': total_traces +} + +with open('$cluster_json', 'w') as f: + json.dump(d, f, indent=2) + +print(' ✅ face_cluster.json upgraded') +" + fi + + echo "✅ $uuid upgrade complete" +} + +# Main +if [ -n "$1" ]; then + upgrade_face_json "$1" +else + echo "Upgrading all face JSON files..." + for f in "$OUTPUT_DIR"/*.face.json; do + uuid=$(basename "$f" .face.json) + upgrade_face_json "$uuid" + done + echo "✅ All upgrades complete" +fi