feat: Rule 3 moment chunks — 10s windows with 1-2 key frames
- 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)
This commit is contained in:
@@ -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};
|
||||
|
||||
@@ -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<i64>,
|
||||
end_frame: Option<i64>,
|
||||
key_frame: Option<String>,
|
||||
vlm_summary: Option<String>,
|
||||
}
|
||||
|
||||
/// A moment chunk covering a time window
|
||||
#[derive(Debug, Clone)]
|
||||
struct MomentWindow {
|
||||
window_index: usize,
|
||||
start_frame: i64,
|
||||
end_frame: i64,
|
||||
selected_traces: Vec<TraceInfo>,
|
||||
combined_text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct TraceInfo {
|
||||
trace_id: i64,
|
||||
key_frame: String,
|
||||
vlm_summary: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn execute_rule3_moment(db: &PostgresDb, file_uuid: &str) -> Result<usize> {
|
||||
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<usize, Vec<TraceProfileLite>> = 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<serde_json::Value> = moment
|
||||
.selected_traces
|
||||
.iter()
|
||||
.map(|t| {
|
||||
serde_json::json!({
|
||||
"trace_id": t.trace_id,
|
||||
"key_frame": t.key_frame,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let trace_ids: Vec<i64> = 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<serde_json::Value> = 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::<Vec<f32>>(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::<Vec<_>>(),
|
||||
});
|
||||
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<Vec<TraceProfileLite>> {
|
||||
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::<TraceProfileLite>(&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<TraceInfo> = 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::<Vec<_>>()
|
||||
.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
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,8 @@ pub struct FileProfile {
|
||||
pub proxy_path: Option<String>, // 720p proxy path for 1080p+ videos
|
||||
pub audio_track: Option<String>, // audio track classification: no_audio/silent_audio/music_only/speech_only/speech_with_music
|
||||
pub face_filter: Option<FaceFilterSettings>,
|
||||
#[serde(default)]
|
||||
pub moment_interval: Option<f64>, // 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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<usize> {
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub async fn execute_rule3_moment(db: &PostgresDb, uuid: &str) -> Result<usize> {
|
||||
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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -21,6 +21,7 @@ static FACE_TRACE_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSe
|
||||
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
|
||||
|
||||
use crate::core::chunk::rule1_ingest;
|
||||
use crate::core::pipeline;
|
||||
use crate::core::config::{FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR};
|
||||
use crate::core::db::qdrant_db::QdrantDb;
|
||||
use crate::core::db::{
|
||||
@@ -1885,16 +1886,26 @@ impl JobWorker {
|
||||
);
|
||||
}
|
||||
|
||||
let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && qdrant_face_done && vlm_done_bool;
|
||||
// Moment chunks: check if moment chunks exist (requires VLM to be done first)
|
||||
let chunk_t = schema::table_name("chunk");
|
||||
let moment_done: bool = sqlx::query_scalar(&format!(
|
||||
"SELECT EXISTS(SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'moment')"
|
||||
))
|
||||
.bind(uuid)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
|
||||
let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && qdrant_face_done && vlm_done_bool && moment_done;
|
||||
|
||||
tracing::info!(
|
||||
"[Ingestion] all_ok={} (asr={}, trace={}, tkg={}, face_cluster={}, rule3={}, scene_meta={}, qdrant_face={}, vlm={}) for uuid={}",
|
||||
all_ok, asr_done, trace_done, tkg_done, face_cluster_done, rule3_done, scene_meta_done, qdrant_face_done, vlm_done_bool, uuid
|
||||
"[Ingestion] all_ok={} (asr={}, trace={}, tkg={}, face_cluster={}, rule3={}, scene_meta={}, qdrant_face={}, vlm={}, moment={}) for uuid={}",
|
||||
all_ok, asr_done, trace_done, tkg_done, face_cluster_done, rule3_done, scene_meta_done, qdrant_face_done, vlm_done_bool, moment_done, uuid
|
||||
);
|
||||
if !all_ok {
|
||||
tracing::info!(
|
||||
"[Ingestion] waiting (uuid={}): asr={} trace={} tkg={} face_cluster={} rule3={} scene_meta={} qdrant_face={} vlm={}",
|
||||
uuid, asr_done, trace_done, tkg_done, face_cluster_done, rule3_done, scene_meta_done, qdrant_face_done, vlm_done_bool
|
||||
"[Ingestion] waiting (uuid={}): asr={} trace={} tkg={} face_cluster={} rule3={} scene_meta={} qdrant_face={} vlm={} moment={}",
|
||||
uuid, asr_done, trace_done, tkg_done, face_cluster_done, rule3_done, scene_meta_done, qdrant_face_done, vlm_done_bool, moment_done
|
||||
);
|
||||
}
|
||||
all_ok
|
||||
@@ -2069,6 +2080,47 @@ impl JobWorker {
|
||||
}
|
||||
}
|
||||
|
||||
// Check moment chunks progress — trigger if VLM done but moments not created
|
||||
let chunk_t = schema::table_name("chunk");
|
||||
let moment_exists: bool = sqlx::query_scalar(&format!(
|
||||
"SELECT EXISTS(SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'moment')"
|
||||
))
|
||||
.bind(uuid)
|
||||
.fetch_one(self.db.pool())
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
|
||||
if !moment_exists && vlm_done > 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
|
||||
|
||||
Reference in New Issue
Block a user