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:
Accusys
2026-08-26 02:37:47 +08:00
parent 8732c3e0a4
commit 20f5974b52
7 changed files with 440 additions and 6 deletions
+2
View File
@@ -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};
+355
View File
@@ -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
}
}
+2
View File
@@ -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",
}
}
}