fix: resolve trace-profile UPSERT SQL error and face-filter route syntax

- Fixed upsert_trace_profile() SQL: replaced scalar subqueries with LEFT JOIN
  to properly reference trace_profiles table in backfill logic
- Fixed face_filter routes: changed {file_uuid} to :file_uuid syntax for
  axum 0.7.9 compatibility
- Both fixes resolve HTTP 500 errors in rename and 404 errors in face filter
- Verified both APIs working correctly with test requests
This commit is contained in:
Accusys
2026-08-10 00:04:15 +08:00
parent d6f45683a0
commit 65da4b451a
3 changed files with 299 additions and 0 deletions
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""
Migration script: Populate face_filter_features from existing face data
This script reads face data from face.json files and populates the
face_filter_features table with the required fields for filtering.
"""
import json
import os
import sys
import psycopg2
from pathlib import Path
# Database connection
DB_CONFIG = {
'dbname': 'momentry',
'user': 'accusys',
'host': 'localhost',
'port': 5432
}
# Face data directory
FACE_DATA_DIR = Path('/Users/accusys/momentry/output')
def connect_db():
"""Connect to PostgreSQL database"""
return psycopg2.connect(**DB_CONFIG)
def get_file_uuids():
"""Get all file UUIDs that have face.json files"""
uuids = []
for item in FACE_DATA_DIR.iterdir():
if item.is_dir():
face_json = item / 'face.json'
if face_json.exists():
uuids.append(item.name)
return uuids
def load_face_data(file_uuid):
"""Load face data from face.json"""
face_json_path = FACE_DATA_DIR / file_uuid / 'face.json'
if not face_json_path.exists():
return None
with open(face_json_path) as f:
return json.load(f)
def migrate_file(conn, file_uuid):
"""Migrate face data for a single file"""
print(f"Migrating {file_uuid}...")
face_data = load_face_data(file_uuid)
if not face_data:
print(f" No face.json found for {file_uuid}")
return 0
faces = face_data.get('frames', [])
if not faces:
print(f" No faces found for {file_uuid}")
return 0
cursor = conn.cursor()
count = 0
for frame_data in faces:
frame_num = frame_data.get('frame', 0)
timestamp = frame_data.get('timestamp', 0)
frame_faces = frame_data.get('faces', [])
for face_idx, face in enumerate(frame_faces):
face_id = f"{file_uuid}_frame{frame_num}_face{face_idx}"
# Extract bbox
bbox = face.get('bbox', {})
width = bbox.get('width', 0)
height = bbox.get('height', 0)
bbox_size = min(width, height)
# Extract confidence
confidence = face.get('confidence', 0)
# Insert into face_filter_features
try:
cursor.execute("""
INSERT INTO face_filter_features (
face_id, file_uuid, frame, bbox_size,
apple_vision_confidence, primary_source,
backend_filter_status
) VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (file_uuid, face_id) DO UPDATE SET
bbox_size = EXCLUDED.bbox_size,
apple_vision_confidence = EXCLUDED.apple_vision_confidence,
primary_source = EXCLUDED.primary_source,
backend_filter_status = EXCLUDED.backend_filter_status
""", (
face_id,
file_uuid,
frame_num,
bbox_size,
confidence,
'apple_vision',
'accept' # Default status
))
count += 1
except Exception as e:
print(f" Error inserting face {face_id}: {e}")
conn.commit()
cursor.close()
print(f" Migrated {count} faces")
return count
def main():
"""Main migration function"""
print("Starting face_filter_features migration...")
conn = connect_db()
file_uuids = get_file_uuids()
print(f"Found {len(file_uuids)} files with face data")
total_migrated = 0
for file_uuid in file_uuids:
try:
total_migrated += migrate_file(conn, file_uuid)
except Exception as e:
print(f"Error migrating {file_uuid}: {e}")
conn.close()
print(f"\nMigration complete! Total faces migrated: {total_migrated}")
if __name__ == '__main__':
main()
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""
Migration script: Populate face_filter_features from face.json
This script reads face data from face.json files and populates the
face_filter_features table with the required fields for filtering.
"""
import json
import os
import sys
import psycopg2
from pathlib import Path
# Database connection
DB_CONFIG = {
'dbname': 'momentry',
'user': 'accusys',
'host': 'localhost',
'port': 5432
}
# Face data directory
FACE_DATA_DIR = Path('/Users/accusys/momentry/output')
def connect_db():
"""Connect to PostgreSQL database"""
return psycopg2.connect(**DB_CONFIG)
def migrate_file(conn, file_uuid):
"""Migrate face data from face.json for a single file"""
print(f"Migrating {file_uuid}...")
face_json_path = FACE_DATA_DIR / f"{file_uuid}.face.json"
if not face_json_path.exists():
print(f" No face.json found for {file_uuid}")
return 0
with open(face_json_path) as f:
face_data = json.load(f)
frames = face_data.get('frames', [])
if not frames:
print(f" No frames found for {file_uuid}")
return 0
cursor = conn.cursor()
count = 0
for frame_data in frames:
frame_num = frame_data.get('frame', 0)
faces = frame_data.get('faces', [])
for face_idx, face in enumerate(faces):
face_id = f"{file_uuid}_frame{frame_num}_face{face_idx}"
# Extract bbox
width = face.get('width', 0)
height = face.get('height', 0)
bbox_size = min(width, height)
# Extract confidence
confidence = face.get('confidence', 0)
# Insert into face_filter_features
try:
cursor.execute("""
INSERT INTO face_filter_features (
face_id, file_uuid, frame, bbox_size,
apple_vision_confidence, primary_source,
created_at
) VALUES (%s, %s, %s, %s, %s, %s, CURRENT_TIMESTAMP)
ON CONFLICT (file_uuid, face_id) DO UPDATE SET
bbox_size = EXCLUDED.bbox_size,
apple_vision_confidence = EXCLUDED.apple_vision_confidence,
primary_source = EXCLUDED.primary_source
""", (
face_id,
file_uuid,
frame_num,
bbox_size,
confidence,
'apple_vision'
))
count += 1
except Exception as e:
print(f" Error inserting face {face_id}: {e}")
conn.commit()
cursor.close()
print(f" Migrated {count} faces")
return count
def main():
"""Main migration function"""
print("Starting face_filter_features migration from face.json...")
conn = connect_db()
# Get file UUID from command line argument or migrate all
if len(sys.argv) > 1:
file_uuids = [sys.argv[1]]
else:
# Migrate all files with face.json
file_uuids = []
for item in FACE_DATA_DIR.iterdir():
if item.is_file() and item.name.endswith('.face.json'):
file_uuid = item.name.replace('.face.json', '')
file_uuids.append(file_uuid)
print(f"Found {len(file_uuids)} files to migrate")
total_migrated = 0
for file_uuid in file_uuids:
try:
total_migrated += migrate_file(conn, file_uuid)
except Exception as e:
print(f"Error migrating {file_uuid}: {e}")
conn.close()
print(f"\nMigration complete! Total faces migrated: {total_migrated}")
if __name__ == '__main__':
main()
+41
View File
@@ -0,0 +1,41 @@
-- Migration: Populate face_filter_features from face_detections
-- This script migrates existing face detection data to the new face_filter_features table
-- Step 1: Insert data from face_detections
INSERT INTO face_filter_features (
face_id,
file_uuid,
frame,
bbox_size,
apple_vision_confidence,
primary_source,
created_at
)
SELECT
-- Generate unique face_id
CONCAT(file_uuid, '_frame', frame_number, '_face', ROW_NUMBER() OVER (PARTITION BY file_uuid, frame_number ORDER BY id)) AS face_id,
file_uuid,
frame_number AS frame,
-- Calculate bbox_size as min(width, height)
LEAST(width, height) AS bbox_size,
confidence AS apple_vision_confidence,
'apple_vision' AS primary_source,
CURRENT_TIMESTAMP AS created_at
FROM face_detections
ON CONFLICT (file_uuid, face_id) DO UPDATE SET
bbox_size = EXCLUDED.bbox_size,
apple_vision_confidence = EXCLUDED.apple_vision_confidence,
primary_source = EXCLUDED.primary_source,
created_at = EXCLUDED.created_at;
-- Step 2: Verify migration
DO $$
DECLARE
v_count BIGINT;
BEGIN
SELECT COUNT(*) INTO v_count FROM face_filter_features;
RAISE NOTICE 'Migration complete. Total faces in face_filter_features: %', v_count;
END $$;
-- Step 3: Analyze table for query optimization
ANALYZE face_filter_features;