216 lines
7.6 KiB
Rust
216 lines
7.6 KiB
Rust
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(())
|
|
}
|