fix: Face processor now saves status and total_faces to face.json

This commit is contained in:
Accusys
2026-09-26 23:06:11 +08:00
parent 8a736a4103
commit 357e585399
99 changed files with 13881 additions and 1065 deletions
+67
View File
@@ -0,0 +1,67 @@
use anyhow::Result;
use dotenv::dotenv;
use momentry_core::core::config;
use momentry_core::core::db::PostgresDb;
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
dotenv().ok();
let db = PostgresDb::new(&config::DATABASE_URL).await?;
println!("Creating scenes table...");
sqlx::query(
"CREATE TABLE IF NOT EXISTS scenes (
id BIGSERIAL PRIMARY KEY,
file_uuid VARCHAR(32) NOT NULL,
scene_index INTEGER NOT NULL,
timestamp_sec DOUBLE PRECISION NOT NULL,
frame_number BIGINT NOT NULL,
filename VARCHAR(255) NOT NULL,
selection_reason VARCHAR(50),
quality_score DOUBLE PRECISION,
quality_source VARCHAR(100),
vlm_status VARCHAR(20) DEFAULT 'pending',
vlm_description TEXT,
vlm_scene_type VARCHAR(100),
vlm_location VARCHAR(255),
vlm_objects JSONB DEFAULT '[]',
vlm_tags JSONB DEFAULT '[]',
vlm_attributes JSONB,
face_count INTEGER DEFAULT 0,
person_traces JSONB DEFAULT '[]',
has_cut BOOLEAN DEFAULT false,
cut_count INTEGER DEFAULT 0,
scene_info JSONB,
embedding_status VARCHAR(20) DEFAULT 'pending',
embedding_point_id VARCHAR(64),
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(file_uuid, scene_index)
)",
)
.execute(db.pool())
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_file_uuid ON scenes(file_uuid)")
.execute(db.pool())
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_tags ON scenes USING GIN(vlm_tags)")
.execute(db.pool())
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_objects ON scenes USING GIN(vlm_objects)")
.execute(db.pool())
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_scenes_timestamp ON scenes(timestamp_sec)")
.execute(db.pool())
.await?;
println!("✅ Scenes table created successfully");
Ok(())
}
+215
View File
@@ -0,0 +1,215 @@
use anyhow::{Context, Result};
use dotenv::dotenv;
use momentry_core::core::config;
use momentry_core::core::db::{schema::table_name, PostgresDb, QdrantDb, SCENES_COLLECTION};
use momentry_core::core::embedding::comic_embed::Embedder;
use momentry_core::core::file_profile::SceneProfile;
use std::path::PathBuf;
fn hash_string(s: &str) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
s.hash(&mut hasher);
hasher.finish()
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
dotenv().ok();
let output_dir = config::OUTPUT_DIR.clone();
let mut dry_run = false;
let mut generate_embeddings = true;
let args: Vec<String> = std::env::args().collect();
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
"--dry-run" => dry_run = true,
"--skip-embeddings" => generate_embeddings = false,
"--help" | "-h" => {
println!("Usage: migrate_scenes [--dry-run] [--skip-embeddings]");
println!(" --dry-run: Only scan files, don't import");
println!(" --skip-embeddings: Don't generate vector embeddings");
return Ok(());
}
_ => {}
}
i += 1;
}
println!("=== Scene Data Migration ===\n");
println!("Output directory: {}", output_dir);
println!("Dry run: {}", dry_run);
println!("Generate embeddings: {}\n", generate_embeddings);
// 1. Scan .scenes.json files
let output_path = std::path::Path::new(&output_dir);
let mut scene_files: Vec<PathBuf> = Vec::new();
if output_path.exists() {
for entry in std::fs::read_dir(output_path)? {
let entry = entry?;
let path = entry.path();
if path.extension().map(|e| e == "json").unwrap_or(false) {
if let Some(filename) = path.file_name() {
if filename.to_string_lossy().ends_with(".scenes.json") {
scene_files.push(path);
}
}
}
}
}
println!("Found {} scene files\n", scene_files.len());
if dry_run {
for file in &scene_files {
println!(" {}", file.display());
}
return Ok(());
}
// 2. Connect to databases
let db = PostgresDb::new(&config::DATABASE_URL).await?;
let qdrant = QdrantDb::new();
let embedder = Embedder::new(config::EMBED_URL.clone());
// 3. Ensure Qdrant collection exists
if generate_embeddings {
println!(
"Ensuring Qdrant collection '{}' exists...",
SCENES_COLLECTION
);
qdrant.ensure_collection(SCENES_COLLECTION, 768).await?;
}
let scenes_table = table_name("scenes");
// 4. Process each file
let mut total_scenes = 0;
let mut total_imported = 0;
let mut total_embeddings = 0;
for file in &scene_files {
let json_content =
std::fs::read_to_string(file).context(format!("Failed to read {}", file.display()))?;
let profile: SceneProfile = serde_json::from_str(&json_content)
.context(format!("Failed to parse {}", file.display()))?;
println!(
"\nProcessing: {} ({} scenes)",
profile.file_uuid,
profile.scenes.len()
);
total_scenes += profile.scenes.len();
// Insert into PostgreSQL
for scene in &profile.scenes {
if scene.vlm_status != momentry_core::core::file_profile::VlmStatus::Completed {
continue;
}
let vlm_objects_json = serde_json::to_string(&scene.vlm_objects)?;
let vlm_tags_json = serde_json::to_string(&scene.vlm_tags)?;
let person_traces_json = serde_json::to_string(&scene.person_traces)?;
sqlx::query(&format!(
"INSERT INTO {} (file_uuid, scene_index, timestamp_sec, frame_number, filename,
selection_reason, quality_score, quality_source, vlm_status, vlm_description,
vlm_objects, vlm_tags, face_count, person_traces, has_cut, cut_count,
embedding_status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, $12::jsonb, $13, $14::jsonb, $15, $16, $17)
ON CONFLICT (file_uuid, scene_index) DO UPDATE SET
timestamp_sec = EXCLUDED.timestamp_sec,
frame_number = EXCLUDED.frame_number,
vlm_description = EXCLUDED.vlm_description,
vlm_objects = EXCLUDED.vlm_objects,
vlm_tags = EXCLUDED.vlm_tags",
scenes_table
))
.bind(&profile.file_uuid)
.bind(scene.index as i32)
.bind(scene.timestamp_sec)
.bind(scene.frame_number as i64)
.bind(&scene.filename)
.bind(format!("{:?}", scene.selection_reason))
.bind(scene.quality_score)
.bind(&scene.quality_source)
.bind("completed")
.bind(&scene.vlm_description)
.bind(&vlm_objects_json)
.bind(&vlm_tags_json)
.bind(scene.face_count as i32)
.bind(&person_traces_json)
.bind(scene.has_cut)
.bind(scene.cut_count as i32)
.bind("pending")
.execute(db.pool())
.await
.context("Failed to insert scene")?;
total_imported += 1;
}
// Generate embeddings
if generate_embeddings {
println!(" Generating embeddings...");
for scene in &profile.scenes {
if scene.vlm_status != momentry_core::core::file_profile::VlmStatus::Completed {
continue;
}
if let Some(ref desc) = scene.vlm_description {
// Generate embedding
let embedding = embedder.embed_document(desc).await?;
// Generate point ID
let point_id_str = format!("{}_s{}", profile.file_uuid, scene.index);
let point_id = hash_string(&point_id_str);
// Upsert to Qdrant
qdrant
.upsert_scene_embedding(
point_id,
&embedding,
&profile.file_uuid,
scene.index,
scene.timestamp_sec,
scene.frame_number,
desc,
&scene.vlm_objects,
&scene.vlm_tags,
)
.await?;
// Update PostgreSQL
sqlx::query(&format!(
"UPDATE {} SET embedding_status = 'completed', embedding_point_id = $1
WHERE file_uuid = $2 AND scene_index = $3",
scenes_table
))
.bind(format!("{:x}", point_id))
.bind(&profile.file_uuid)
.bind(scene.index as i32)
.execute(db.pool())
.await?;
total_embeddings += 1;
}
}
}
}
println!("\n=== Migration Summary ===");
println!("Total scene files: {}", scene_files.len());
println!("Total scenes: {}", total_scenes);
println!("Scenes imported: {}", total_imported);
println!("Embeddings generated: {}", total_embeddings);
Ok(())
}
+203
View File
@@ -0,0 +1,203 @@
// Standalone Scene VLM Test Tool
// This tool manually triggers Scene VLM processing for testing
use anyhow::Result;
use momentry_core::core::db::PostgresDb;
use momentry_core::core::processor::scene_vlm::SceneVlmProcessor;
use momentry_core::Database;
use sqlx::postgres::PgPoolOptions;
#[tokio::main]
async fn main() -> Result<()> {
// Initialize tracing
tracing_subscriber::fmt::init();
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <file_uuid>", args[0]);
std::process::exit(1);
}
let uuid = &args[1];
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string());
println!("=== Scene VLM Test Tool ===");
println!("UUID: {}", uuid);
println!("Output: {}", output_dir);
println!();
// Load config
let (enabled, interval_sec, samples, use_cuts, max_workers) =
momentry_core::core::config::get_scene_vlm_config();
println!("Config:");
println!(" Enabled: {}", enabled);
println!(" Interval: {}s", interval_sec);
println!(" Samples: {}", samples);
println!(" Use CUTs: {}", use_cuts);
println!(" Max Workers: {}", max_workers);
println!();
if !enabled {
println!("❌ Scene VLM is disabled");
println!("Set MOMENTRY_SCENE_VLM_ENABLED=true to enable");
return Ok(());
}
// Load video metadata
println!("Loading video metadata...");
let db_url = momentry_core::core::config::DATABASE_URL.clone();
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&db_url)
.await?;
let db = PostgresDb::from_pool(pool);
let video = db
.get_video_by_uuid(uuid)
.await?
.ok_or_else(|| anyhow::anyhow!("Video not found: {}", uuid))?;
let fps = video.fps;
let duration = video.duration;
let width = video.width;
let height = video.height;
let total_frames = video.total_frames as u32;
let video_path = video.file_path.clone();
println!("Video:");
println!(" Path: {}", video_path);
println!(" Duration: {}s", duration);
println!(" FPS: {}", fps);
println!(" Resolution: {}x{}", width, height);
println!(" Total frames: {}", total_frames);
println!();
// Load CUT data
println!("Loading CUT data...");
let cut_path = format!("{}/{}.cut.json", output_dir, uuid);
let cut_data = if std::path::Path::new(&cut_path).exists() {
let json = std::fs::read_to_string(&cut_path)?;
let data: serde_json::Value = serde_json::from_str(&json)?;
let scene_count = data
.get("scenes")
.and_then(|s| s.as_array())
.map(|a| a.len())
.unwrap_or(0);
println!(" Scenes: {}", scene_count);
data
} else {
println!(" ⚠️ No CUT data, using empty");
serde_json::json!({"scenes": []})
};
println!();
// Create processor
let processor = SceneVlmProcessor::new(samples, use_cuts, max_workers);
// Generate profile
println!("Generating scene profile...");
let start = std::time::Instant::now();
let profile = processor
.generate_scene_profile(
&video_path,
uuid,
&output_dir,
interval_sec,
&cut_data,
fps,
duration,
width,
height,
total_frames,
)
.await?;
let elapsed = start.elapsed();
println!(" ✅ Generated in {:.2}s", elapsed.as_secs_f64());
println!(" Total scenes: {}", profile.total_scenes);
println!();
// Extract frames
println!("Extracting frames...");
let start = std::time::Instant::now();
let extracted =
SceneVlmProcessor::extract_scene_frames(&video_path, &output_dir, uuid, &profile.scenes)
.await?;
let elapsed = start.elapsed();
println!(
" ✅ Extracted {} frames in {:.2}s",
extracted.len(),
elapsed.as_secs_f64()
);
println!();
// Generate VLM descriptions
println!("Generating VLM descriptions...");
let start = std::time::Instant::now();
let mut profile = profile;
match SceneVlmProcessor::generate_vlm_descriptions(
&output_dir,
uuid,
&mut profile.scenes,
max_workers,
)
.await
{
Ok(_) => {
let elapsed = start.elapsed();
println!(
" ✅ Generated VLM descriptions in {:.2}s",
elapsed.as_secs_f64()
);
}
Err(e) => {
println!(" ⚠️ VLM generation failed: {}", e);
}
}
println!();
// Save profile
println!("Saving profile...");
SceneVlmProcessor::save_scene_profile(&profile, &output_dir)?;
println!(" ✅ Saved to {}/{}.scenes.json", output_dir, uuid);
println!();
// Print summary
println!("=== Summary ===");
println!("Total frames: {}", profile.total_scenes);
println!("Processing time: {:.2}s", elapsed.as_secs_f64());
println!();
// Print first 5 scenes with VLM status
println!("First 5 scenes:");
for scene in profile.scenes.iter().take(5) {
let vlm_desc = scene.vlm_description.as_deref().unwrap_or("N/A");
let vlm_status = match scene.vlm_status {
momentry_core::core::file_profile::VlmStatus::Pending => "pending",
momentry_core::core::file_profile::VlmStatus::Processing => "processing",
momentry_core::core::file_profile::VlmStatus::Completed => "completed",
momentry_core::core::file_profile::VlmStatus::Failed => "failed",
};
println!(
" {}: {}s (frame {}, blur={:.2}) [VLM: {}]",
scene.index,
scene.timestamp_sec,
scene.frame_number,
scene.quality_score.unwrap_or(0.0),
vlm_status
);
if scene.vlm_description.is_some() {
println!(
" Description: {}...",
&vlm_desc[..vlm_desc.len().min(80)]
);
}
}
Ok(())
}