From 20f5974b521779d814677007f158bf9e9fe9ef1d Mon Sep 17 00:00:00 2001 From: Accusys Date: Wed, 26 Aug 2026 02:37:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Rule=203=20moment=20chunks=20=E2=80=94?= =?UTF-8?q?=2010s=20windows=20with=201-2=20key=20frames?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add ChunkType::Moment to types.rs - Add moment_interval to FileProfile (configurable, default 10s) - Create rule3_moment.rs: reads trace_profile.json, groups by time window, selects 1-2 diverse key frames using Jaccard similarity on VLM text - Embed moment chunks into Qdrant using trace VLM embeddings - Wire into worker: triggers after VLM completes, blocks job completion - Add moment_chunks progress stage (weight: 0.01) --- src/core/chunk/mod.rs | 2 + src/core/chunk/rule3_moment.rs | 355 +++++++++++++++++++++++++++++++++ src/core/chunk/types.rs | 2 + src/core/file_profile.rs | 5 + src/core/pipeline/mod.rs | 10 + src/core/progress.rs | 10 +- src/worker/job_worker.rs | 62 +++++- 7 files changed, 440 insertions(+), 6 deletions(-) create mode 100644 src/core/chunk/rule3_moment.rs diff --git a/src/core/chunk/mod.rs b/src/core/chunk/mod.rs index 2f44b42d..91b0adba 100644 --- a/src/core/chunk/mod.rs +++ b/src/core/chunk/mod.rs @@ -1,11 +1,13 @@ pub mod rule1_ingest; pub mod rule2_ingest; +pub mod rule3_moment; pub mod splitter; pub mod trace_ingest; pub mod types; pub use rule1_ingest::execute_rule1; pub use rule2_ingest::ingest_rule2; +pub use rule3_moment::execute_rule3_moment; pub use splitter::{AsrSegment, ChunkSplitter}; pub use trace_ingest::ingest_traces; pub use types::{Chunk, ChunkType}; diff --git a/src/core/chunk/rule3_moment.rs b/src/core/chunk/rule3_moment.rs new file mode 100644 index 00000000..6ff43d7c --- /dev/null +++ b/src/core/chunk/rule3_moment.rs @@ -0,0 +1,355 @@ +use crate::core::chunk::types::{Chunk, ChunkRule, ChunkType}; +use crate::core::db::schema; +use crate::core::db::{PostgresDb, QdrantDb}; +use crate::core::file_profile::FileProfile; +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::path::Path; +use tracing::{info, warn}; + +const DEFAULT_MOMENT_INTERVAL: f64 = 10.0; // seconds + +/// Minimal data from trace_profile.json needed for moment chunking +#[derive(Debug, Clone, Deserialize)] +struct TraceProfileLite { + trace_id: i64, + start_frame: Option, + end_frame: Option, + key_frame: Option, + vlm_summary: Option, +} + +/// A moment chunk covering a time window +#[derive(Debug, Clone)] +struct MomentWindow { + window_index: usize, + start_frame: i64, + end_frame: i64, + selected_traces: Vec, + combined_text: String, +} + +#[derive(Debug, Clone)] +struct TraceInfo { + trace_id: i64, + key_frame: String, + vlm_summary: Option, +} + +pub async fn execute_rule3_moment(db: &PostgresDb, file_uuid: &str) -> Result { + let pool = db.pool(); + let chunk_table = schema::table_name("chunk"); + + let video = db + .get_video_by_uuid(file_uuid) + .await? + .context("Video not found")?; + let fps = video.fps; + let file_id = video.id as i32; + let duration = video.duration; + + // Get moment interval from file profile + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let profile_path = Path::new(output_dir).join(format!("{}.profile.json", file_uuid)); + let moment_interval: f64 = if profile_path.exists() { + let content = std::fs::read_to_string(&profile_path)?; + let profile: FileProfile = serde_json::from_str(&content)?; + profile.moment_interval.unwrap_or(DEFAULT_MOMENT_INTERVAL) + } else { + DEFAULT_MOMENT_INTERVAL + }; + + info!( + "[Rule3-Moment] Starting for {} interval={}s duration={}s", + file_uuid, moment_interval, duration + ); + + // Read all trace_profile.json files + let trace_dir = Path::new(output_dir).join(file_uuid); + let traces = read_trace_profiles(&trace_dir)?; + + if traces.is_empty() { + info!("[Rule3-Moment] No trace profiles found for {}", file_uuid); + return Ok(0); + } + + // Group traces by moment window + let frames_per_window = (moment_interval * fps) as i64; + let mut windows: HashMap> = HashMap::new(); + + for trace in &traces { + if let Some(sf) = trace.start_frame { + let window_index = (sf / frames_per_window) as usize; + windows.entry(window_index).or_default().push(trace.clone()); + } + } + + // Delete existing moment chunks for this file + sqlx::query(&format!( + "DELETE FROM {} WHERE file_uuid = $1 AND chunk_type = 'moment'", + chunk_table + )) + .bind(file_uuid) + .execute(pool) + .await?; + + // Build moment chunks + let mut moments = Vec::new(); + let total_windows = windows.len(); + + for (window_index, traces_in_window) in windows.iter_mut() { + let window = select_key_frames(*window_index, traces_in_window, fps, frames_per_window); + moments.push(window); + + if moments.len() % 100 == 0 { + info!("[Rule3-Moment] Processed {}/{} windows", moments.len(), total_windows); + } + } + + // Sort by window index + moments.sort_by_key(|m| m.window_index); + + // Store chunks + let mut count = 0; + let mut tx = pool.begin().await?; + + for moment in &moments { + let key_frames: Vec = moment + .selected_traces + .iter() + .map(|t| { + serde_json::json!({ + "trace_id": t.trace_id, + "key_frame": t.key_frame, + }) + }) + .collect(); + + let trace_ids: Vec = moment + .selected_traces + .iter() + .map(|t| t.trace_id) + .collect(); + + let metadata = serde_json::json!({ + "window_index": moment.window_index, + "key_frames": key_frames, + "trace_ids": trace_ids, + "moment_interval": moment_interval, + }); + + let content = serde_json::json!({ + "key_frames": key_frames, + }); + + let chunk = Chunk::new( + file_id, + file_uuid.to_string(), + format!("moment_{}", moment.window_index), + ChunkType::Moment, + ChunkRule::Rule1, + moment.start_frame, + moment.end_frame, + fps, + content, + ) + .with_metadata(metadata) + .with_text_content(moment.combined_text.clone()); + + // Store chunk directly (not in tx — store_chunk uses its own tx) + if let Err(e) = db.store_chunk(&chunk).await { + warn!("[Rule3-Moment] Failed to store moment_{}: {}", moment.window_index, e); + } else { + count += 1; + } + } + + tx.commit().await?; + + // Embed into Qdrant + let qdrant = QdrantDb::new(); + let mut embedded = 0; + for moment in &moments { + // Use first selected trace's VLM embedding if available + if let Some(first_trace) = moment.selected_traces.first() { + let tp_table = schema::table_name("trace_profiles"); + let embedding: Option = sqlx::query_scalar(&format!( + "SELECT vlm_embedding FROM {tp_table} WHERE file_uuid = $1 AND trace_id = $2" + )) + .bind(file_uuid) + .bind(first_trace.trace_id) + .fetch_optional(pool) + .await + .ok() + .flatten(); + + if let Some(emb) = embedding { + let point_id_str = format!("{file_uuid}_m{:x}", moment.window_index); + if let Ok(vec) = serde_json::from_value::>(emb.clone()) { + let payload = serde_json::json!({ + "file_uuid": file_uuid, + "chunk_id": format!("moment_{}", moment.window_index), + "chunk_type": "moment", + "window_index": moment.window_index, + "text_content": moment.combined_text, + "key_frames": moment.selected_traces.iter().map(|t| &t.key_frame).collect::>(), + }); + if let Err(e) = qdrant + .upsert_vector_to_collection( + &qdrant.collection_name, + moment.window_index as u64, + &vec, + Some(payload), + ) + .await + { + warn!("[Rule3-Moment] Failed to embed moment_{}: {}", moment.window_index, e); + } else { + embedded += 1; + } + } + } + } + } + + info!( + "[Rule3-Moment] Completed: {} moments created, {} embedded for {}", + count, embedded, file_uuid + ); + + Ok(count) +} + +fn read_trace_profiles(trace_dir: &Path) -> Result> { + let mut traces = Vec::new(); + + if !trace_dir.exists() { + return Ok(traces); + } + + for entry in std::fs::read_dir(trace_dir)? { + let entry = entry?; + if !entry.path().is_dir() { + continue; + } + let profile_path = entry.path().join("trace_profile.json"); + if !profile_path.exists() { + continue; + } + if let Ok(content) = std::fs::read_to_string(&profile_path) { + if let Ok(profile) = serde_json::from_str::(&content) { + traces.push(profile); + } + } + } + + traces.sort_by_key(|t| t.start_frame.unwrap_or(0)); + Ok(traces) +} + +fn select_key_frames( + window_index: usize, + traces: &[TraceProfileLite], + fps: f64, + frames_per_window: i64, +) -> MomentWindow { + let start_frame = (window_index as i64) * frames_per_window; + let end_frame = start_frame + frames_per_window; + + if traces.is_empty() { + return MomentWindow { + window_index, + start_frame, + end_frame, + selected_traces: vec![], + combined_text: String::new(), + }; + } + + // Filter traces with valid key_frame + let valid: Vec<&TraceProfileLite> = traces + .iter() + .filter(|t| t.key_frame.is_some()) + .collect(); + + if valid.is_empty() { + return MomentWindow { + window_index, + start_frame, + end_frame, + selected_traces: vec![], + combined_text: String::new(), + }; + } + + // Select 1-2 most diverse traces + let selected = if valid.len() == 1 { + vec![valid[0]] + } else { + // Pick first trace, then find the one with most different VLM summary + let first = valid[0]; + let mut best_diversity = -1.0; + let mut best_second = valid[1]; + + for candidate in valid.iter().skip(1) { + let similarity = jaccard_similarity( + first.vlm_summary.as_deref().unwrap_or(""), + candidate.vlm_summary.as_deref().unwrap_or(""), + ); + if similarity < best_diversity || best_diversity < 0.0 { + best_diversity = similarity; + best_second = candidate; + } + } + + // Only add second if it's sufficiently different (similarity < 0.5) + if best_diversity < 0.5 { + vec![first, best_second] + } else { + vec![first] + } + }; + + let trace_infos: Vec = selected + .iter() + .map(|t| TraceInfo { + trace_id: t.trace_id, + key_frame: t.key_frame.clone().unwrap_or_default(), + vlm_summary: t.vlm_summary.clone(), + }) + .collect(); + + let combined_text = trace_infos + .iter() + .filter_map(|t| t.vlm_summary.as_deref()) + .collect::>() + .join(" "); + + MomentWindow { + window_index, + start_frame, + end_frame, + selected_traces: trace_infos, + combined_text, + } +} + +/// Simple Jaccard similarity between two strings (word-level) +fn jaccard_similarity(a: &str, b: &str) -> f64 { + if a.is_empty() || b.is_empty() { + return 0.0; + } + + let words_a: std::collections::HashSet<&str> = a.split_whitespace().collect(); + let words_b: std::collections::HashSet<&str> = b.split_whitespace().collect(); + + let intersection = words_a.intersection(&words_b).count(); + let union = words_a.union(&words_b).count(); + + if union == 0 { + 0.0 + } else { + intersection as f64 / union as f64 + } +} diff --git a/src/core/chunk/types.rs b/src/core/chunk/types.rs index 28a7b594..fccedca6 100644 --- a/src/core/chunk/types.rs +++ b/src/core/chunk/types.rs @@ -11,6 +11,7 @@ pub enum ChunkType { Story, Relationship, Ocr, + Moment, } impl ChunkType { @@ -23,6 +24,7 @@ impl ChunkType { ChunkType::Story => "story", ChunkType::Relationship => "relationship", ChunkType::Ocr => "ocr", + ChunkType::Moment => "moment", } } } diff --git a/src/core/file_profile.rs b/src/core/file_profile.rs index 18aee092..bad1fbfe 100644 --- a/src/core/file_profile.rs +++ b/src/core/file_profile.rs @@ -45,6 +45,8 @@ pub struct FileProfile { pub proxy_path: Option, // 720p proxy path for 1080p+ videos pub audio_track: Option, // audio track classification: no_audio/silent_audio/music_only/speech_only/speech_with_music pub face_filter: Option, + #[serde(default)] + pub moment_interval: Option, // seconds per moment window, default 10.0 } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -149,6 +151,7 @@ impl FileProfile { proxy_path: None, audio_track: None, face_filter: None, + moment_interval: None, } } @@ -188,6 +191,7 @@ impl FileProfile { proxy_path: None, audio_track: None, face_filter: None, + moment_interval: None, } } @@ -317,6 +321,7 @@ impl FileProfile { proxy_path: None, audio_track: None, face_filter: None, + moment_interval: None, } } diff --git a/src/core/pipeline/mod.rs b/src/core/pipeline/mod.rs index f138602a..3481a1a9 100644 --- a/src/core/pipeline/mod.rs +++ b/src/core/pipeline/mod.rs @@ -1,6 +1,7 @@ use anyhow::{Context, Result}; use crate::core::chunk::rule1_ingest; +use crate::core::chunk::rule3_moment; use crate::core::config; use crate::core::db::postgres_db::PostgresDb; use crate::core::db::qdrant_db::QdrantDb; @@ -74,6 +75,15 @@ pub async fn execute_rule1(db: &PostgresDb, uuid: &str) -> Result { Ok(count) } +pub async fn execute_rule3_moment(db: &PostgresDb, uuid: &str) -> Result { + let count = rule3_moment::execute_rule3_moment(db, uuid) + .await + .context("Rule 3 moment chunks failed")?; + + println!("Rule 3 completed: {} moment chunks for {}", count, uuid); + Ok(count) +} + pub async fn vectorize_chunks(uuid: &str) -> Result<()> { let db = PostgresDb::new(&config::DATABASE_URL).await?; let qdrant = QdrantDb::new(); diff --git a/src/core/progress.rs b/src/core/progress.rs index 4fcdab2b..e04fed63 100644 --- a/src/core/progress.rs +++ b/src/core/progress.rs @@ -95,7 +95,15 @@ impl PipelineProgress { // VLM Summary (5%) PipelineStage { name: "vlm_summary".into(), - weight: 0.05, + weight: 0.04, + progress: 0.0, + status: "pending".into(), + detail: None, + }, + // Rule 3 Moment Chunks (1%) + PipelineStage { + name: "moment_chunks".into(), + weight: 0.01, progress: 0.0, status: "pending".into(), detail: None, diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index a503af48..d7e5bbf3 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -21,6 +21,7 @@ static FACE_TRACE_INFLIGHT: LazyLock 0 { + // VLM is done but no moment chunks yet — trigger Rule 3 + info!("[Moment-poll] VLM done ({}), no moments yet — triggering Rule 3", vlm_done); + let db_clone = self.db.clone(); + let uuid_clone = uuid.to_string(); + let redis_clone2 = self.redis.clone(); + tokio::spawn(async move { + match crate::core::pipeline::execute_rule3_moment(&db_clone, &uuid_clone).await { + Ok(count) => { + info!("[Rule3-Moment] Completed: {} moments for {}", count, uuid_clone); + if let Ok(mut conn) = redis_clone2.get_conn().await { + let prefix = crate::core::config::REDIS_KEY_PREFIX.as_str(); + let redis_key = format!("{}progress:{}:pipeline", prefix, uuid_clone); + let _: Result<(), _> = + redis::AsyncCommands::set(&mut conn, &redis_key, + serde_json::json!({ + "stage": "moment_chunks", + "progress": 1.0, + "status": "completed", + "detail": format!("{} moments created", count) + }).to_string() + ).await; + } + } + Err(e) => { + tracing::error!("[Rule3-Moment] Failed for {}: {}", uuid_clone, e); + } + } + }); + } + let mut created_deferred = false; // Find processors in job_processors that are not in results yet