Files
momentry_core/src/core/progress.rs
T
Accusys b639291585 feat: 添加 Scene VLM 到 Pipeline Progress 阶段
问题:
- Scene VLM 是必要处理步骤(当有 CUT 时)
- 但在 PipelineProgress 中没有对应的阶段
- 前端无法看到 Scene VLM 的处理进度

修复:
- 添加 scene_vlm 阶段(权重 3%)
- 调整 vlm_summary 权重从 4% 到 3%
- 确保 Scene VLM 在处理流程中有明确的进度显示

阶段权重:
- processors: 30%
- rule1_ingestion: 5%
- face_tracing: 5%
- face_dedup: 10%
- tkg_nodes: 20%
- tkg_edges: 15%
- rule2_ingestion: 10%
- vlm_summary: 3%
- scene_vlm: 3%
- moment_chunks: 1%
总计: 100%

影响:
- 深度扫描文件会显示 Scene VLM 处理进度
- 用户可以看到完整的处理流程
- 更好的透明度和用户体验

测试:
✅ 编译通过(cargo build --bin momentry)
2026-10-10 14:57:13 +08:00

663 lines
22 KiB
Rust

//! Processing Progress Tracking
//!
//! Tracks progress for TKG and Identity Agent components.
//! Progress is published to Redis for real-time UI updates.
//!
//! Redis keys:
//! {prefix}progress:{file_uuid}:tkg → TKG progress JSON
//! {prefix}progress:{file_uuid}:agent → Identity Agent progress JSON
//! {prefix}progress:{file_uuid}:combined → Combined progress JSON
//! {prefix}progress:{file_uuid}:pipeline → Full pipeline progress JSON
use serde::{Deserialize, Serialize};
// ── Pipeline Stages ─────────────────────────────────────────────────────────
// Complete processing pipeline with weights for segmented progress calculation
/// Pipeline stage with weight for overall progress calculation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineStage {
pub name: String,
pub weight: f64, // Weight in overall progress (0.0-1.0)
pub progress: f64, // Stage progress (0.0-1.0)
pub status: String, // "pending", "running", "completed", "failed"
pub detail: Option<String>,
}
/// Full pipeline progress with segmented breakdown
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineProgress {
pub file_uuid: String,
pub overall_progress: f64, // 0.0-1.0 weighted sum of all stages
pub stages: Vec<PipelineStage>,
pub updated_at: String,
}
impl PipelineProgress {
pub fn new(file_uuid: &str) -> Self {
Self {
file_uuid: file_uuid.to_string(),
overall_progress: 0.0,
stages: vec![
// Processors (30% total)
PipelineStage {
name: "processors".into(),
weight: 0.30,
progress: 0.0,
status: "pending".into(),
detail: None,
},
// Post-processor triggers (20% total)
PipelineStage {
name: "rule1_ingestion".into(),
weight: 0.05,
progress: 0.0,
status: "pending".into(),
detail: None,
},
PipelineStage {
name: "face_tracing".into(),
weight: 0.05,
progress: 0.0,
status: "pending".into(),
detail: None,
},
PipelineStage {
name: "face_dedup".into(),
weight: 0.10,
progress: 0.0,
status: "pending".into(),
detail: None,
},
// TKG Build (35% total)
PipelineStage {
name: "tkg_nodes".into(),
weight: 0.20,
progress: 0.0,
status: "pending".into(),
detail: None,
},
PipelineStage {
name: "tkg_edges".into(),
weight: 0.15,
progress: 0.0,
status: "pending".into(),
detail: None,
},
// Rule 2 Ingestion (10%)
PipelineStage {
name: "rule2_ingestion".into(),
weight: 0.10,
progress: 0.0,
status: "pending".into(),
detail: None,
},
// VLM Summary (3%)
PipelineStage {
name: "vlm_summary".into(),
weight: 0.03,
progress: 0.0,
status: "pending".into(),
detail: None,
},
// Scene VLM (3%) - mandatory when cut.json exists
PipelineStage {
name: "scene_vlm".into(),
weight: 0.03,
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,
},
],
updated_at: chrono::Utc::now().to_rfc3339(),
}
}
/// Update a stage's progress and recalculate overall progress
pub fn update_stage(
&mut self,
stage_name: &str,
progress: f64,
status: &str,
detail: Option<String>,
) {
if let Some(stage) = self.stages.iter_mut().find(|s| s.name == stage_name) {
stage.progress = progress.clamp(0.0, 1.0);
stage.status = status.to_string();
stage.detail = detail;
}
self.recalculate_overall();
}
/// Recalculate overall progress as weighted sum
fn recalculate_overall(&mut self) {
self.overall_progress = self
.stages
.iter()
.map(|s| s.weight * s.progress)
.sum::<f64>()
.clamp(0.0, 1.0);
self.updated_at = chrono::Utc::now().to_rfc3339();
}
/// Mark all stages as completed
pub fn mark_completed(&mut self) {
for stage in &mut self.stages {
stage.progress = 1.0;
stage.status = "completed".into();
}
self.recalculate_overall();
}
}
// ── TKG Phases ─────────────────────────────────────────────────────────────
// Each phase corresponds to a step in the TKG build process
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TkgPhase {
FaceTracing = 0, // Phase 0: Populate trace_id from face.json
FaceTrackNodes = 1, // Build face_track nodes
GazeTrackNodes = 2, // Build gaze_track nodes
LipTrackNodes = 3, // Build lip_track nodes
TextRegionNodes = 4, // Build text_region nodes
AppearanceNodes = 5, // Build appearance_trace nodes
AccessoryNodes = 6, // Build accessory nodes
ObjectNodes = 7, // Build object nodes (deprecated - YOLO removed)
HandNodes = 8, // Build hand nodes
SpeakerNodes = 9, // Build speaker nodes
CoOccurrenceEdges = 10, // Build co_occurrence edges
SpeakerFaceEdges = 11, // Build speaker_face edges
FaceFaceEdges = 12, // Build face_face edges
MutualGazeEdges = 13, // Build mutual_gaze edges
LipSyncEdges = 14, // Build lip_sync edges
HasAppearanceEdges = 15, // Build has_appearance edges
WearsEdges = 16, // Build wears edges
HandObjectEdges = 17, // Build hand_object edges
TraceArtifacts = 18, // Save key_frame.jpg, key_face.jpg, trace_profile.json
Completed = 19,
Failed = 20,
}
impl TkgPhase {
pub const TOTAL: usize = 19; // phases 0-18
pub fn name(&self) -> &'static str {
match self {
TkgPhase::FaceTracing => "face_tracing",
TkgPhase::FaceTrackNodes => "face_track_nodes",
TkgPhase::GazeTrackNodes => "gaze_track_nodes",
TkgPhase::LipTrackNodes => "lip_track_nodes",
TkgPhase::TextRegionNodes => "text_region_nodes",
TkgPhase::AppearanceNodes => "appearance_nodes",
TkgPhase::AccessoryNodes => "accessory_nodes",
TkgPhase::ObjectNodes => "object_nodes",
TkgPhase::HandNodes => "hand_nodes",
TkgPhase::SpeakerNodes => "speaker_nodes",
TkgPhase::CoOccurrenceEdges => "co_occurrence_edges",
TkgPhase::SpeakerFaceEdges => "speaker_face_edges",
TkgPhase::FaceFaceEdges => "face_face_edges",
TkgPhase::MutualGazeEdges => "mutual_gaze_edges",
TkgPhase::LipSyncEdges => "lip_sync_edges",
TkgPhase::HasAppearanceEdges => "has_appearance_edges",
TkgPhase::WearsEdges => "wears_edges",
TkgPhase::HandObjectEdges => "hand_object_edges",
TkgPhase::TraceArtifacts => "trace_artifacts",
TkgPhase::Completed => "completed",
TkgPhase::Failed => "failed",
}
}
pub fn from_index(idx: usize) -> Self {
match idx {
0 => TkgPhase::FaceTracing,
1 => TkgPhase::FaceTrackNodes,
2 => TkgPhase::GazeTrackNodes,
3 => TkgPhase::LipTrackNodes,
4 => TkgPhase::TextRegionNodes,
5 => TkgPhase::AppearanceNodes,
6 => TkgPhase::AccessoryNodes,
7 => TkgPhase::ObjectNodes,
8 => TkgPhase::HandNodes,
9 => TkgPhase::SpeakerNodes,
10 => TkgPhase::CoOccurrenceEdges,
11 => TkgPhase::SpeakerFaceEdges,
12 => TkgPhase::FaceFaceEdges,
13 => TkgPhase::MutualGazeEdges,
14 => TkgPhase::LipSyncEdges,
15 => TkgPhase::HasAppearanceEdges,
16 => TkgPhase::WearsEdges,
17 => TkgPhase::HandObjectEdges,
18 => TkgPhase::TraceArtifacts,
_ => TkgPhase::Completed,
}
}
}
// ── Identity Agent Phases ──────────────────────────────────────────────────
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentPhase {
FaceClustering = 0,
IdentityCreation = 1,
TmdbMatching = 2,
SpeakerBinding = 3,
Confirmation = 4,
Completed = 5,
Failed = 6,
}
impl AgentPhase {
pub const TOTAL: usize = 5; // phases 0-4
pub fn name(&self) -> &'static str {
match self {
AgentPhase::FaceClustering => "face_clustering",
AgentPhase::IdentityCreation => "identity_creation",
AgentPhase::TmdbMatching => "tmdb_matching",
AgentPhase::SpeakerBinding => "speaker_binding",
AgentPhase::Confirmation => "confirmation",
AgentPhase::Completed => "completed",
AgentPhase::Failed => "failed",
}
}
pub fn from_index(idx: usize) -> Self {
match idx {
0 => AgentPhase::FaceClustering,
1 => AgentPhase::IdentityCreation,
2 => AgentPhase::TmdbMatching,
3 => AgentPhase::SpeakerBinding,
4 => AgentPhase::Confirmation,
_ => AgentPhase::Completed,
}
}
}
// ── Stats ──────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TkgStats {
pub total_faces: i64,
pub traced_faces: i64,
pub total_traces: i64,
pub matched_traces: i64,
pub seed_count: i64,
pub collisions_resolved: i64,
pub identities_bound: i64,
// Node counts
pub face_track_nodes: i64,
pub gaze_track_nodes: i64,
pub lip_track_nodes: i64,
pub text_region_nodes: i64,
pub appearance_nodes: i64,
pub accessory_nodes: i64,
pub object_nodes: i64,
pub hand_nodes: i64,
pub speaker_nodes: i64,
// Edge counts
pub co_occurrence_edges: i64,
pub speaker_face_edges: i64,
pub face_face_edges: i64,
pub mutual_gaze_edges: i64,
pub lip_sync_edges: i64,
pub has_appearance_edges: i64,
pub wears_edges: i64,
pub hand_object_edges: i64,
// Totals
pub total_nodes: i64,
pub total_edges: i64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AgentStats {
pub total_faces: i64,
pub total_traces: i64,
pub clusters: i64,
pub identities_created: i64,
pub tmdb_matches: i64,
pub speaker_bindings: i64,
pub confirmations: i64,
}
// ── Progress Records ───────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TkgProgress {
pub file_uuid: String,
pub phase: String,
pub phase_index: usize,
pub total_phases: usize,
pub phase_progress: f64,
pub overall_progress: f64,
pub stats: TkgStats,
pub message: String,
pub updated_at: String,
}
impl TkgProgress {
pub fn new(file_uuid: &str) -> Self {
Self {
file_uuid: file_uuid.to_string(),
phase: TkgPhase::FaceTracing.name().to_string(),
phase_index: 0,
total_phases: TkgPhase::TOTAL,
phase_progress: 0.0,
overall_progress: 0.0,
stats: TkgStats::default(),
message: "TKG processing starting".to_string(),
updated_at: chrono::Utc::now().to_rfc3339(),
}
}
pub fn update_phase(&mut self, phase: TkgPhase, phase_progress: f64, message: &str) {
self.phase = phase.name().to_string();
self.phase_index = phase as usize;
self.phase_progress = phase_progress.clamp(0.0, 1.0);
// Overall: (phase_index + phase_progress) / total_phases
let weighted = self.phase_index as f64 + self.phase_progress;
self.overall_progress = (weighted / self.total_phases as f64).clamp(0.0, 1.0);
self.message = message.to_string();
self.updated_at = chrono::Utc::now().to_rfc3339();
}
pub fn mark_completed(&mut self) {
self.update_phase(TkgPhase::Completed, 1.0, "TKG processing completed");
self.overall_progress = 1.0;
self.phase_progress = 1.0;
}
pub fn mark_failed(&mut self, error: &str) {
self.update_phase(TkgPhase::Failed, 0.0, &format!("TKG failed: {}", error));
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentProgress {
pub file_uuid: String,
pub phase: String,
pub phase_index: usize,
pub total_phases: usize,
pub phase_progress: f64,
pub overall_progress: f64,
pub stats: AgentStats,
pub message: String,
pub updated_at: String,
}
impl AgentProgress {
pub fn new(file_uuid: &str) -> Self {
Self {
file_uuid: file_uuid.to_string(),
phase: AgentPhase::FaceClustering.name().to_string(),
phase_index: 0,
total_phases: AgentPhase::TOTAL,
phase_progress: 0.0,
overall_progress: 0.0,
stats: AgentStats::default(),
message: "Identity Agent processing starting".to_string(),
updated_at: chrono::Utc::now().to_rfc3339(),
}
}
pub fn update_phase(&mut self, phase: AgentPhase, phase_progress: f64, message: &str) {
self.phase = phase.name().to_string();
self.phase_index = phase as usize;
self.phase_progress = phase_progress.clamp(0.0, 1.0);
let weighted = self.phase_index as f64 + self.phase_progress;
self.overall_progress = (weighted / self.total_phases as f64).clamp(0.0, 1.0);
self.message = message.to_string();
self.updated_at = chrono::Utc::now().to_rfc3339();
}
pub fn mark_completed(&mut self) {
self.update_phase(
AgentPhase::Completed,
1.0,
"Identity Agent processing completed",
);
self.overall_progress = 1.0;
self.phase_progress = 1.0;
}
pub fn mark_failed(&mut self, error: &str) {
self.update_phase(
AgentPhase::Failed,
0.0,
&format!("Identity Agent failed: {}", error),
);
}
}
// ── Combined Progress ──────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CombinedProgress {
pub file_uuid: String,
pub overall_progress: f64,
pub tkg: Option<TkgProgress>,
pub agent: Option<AgentProgress>,
pub current_phase: String,
pub message: String,
pub updated_at: String,
}
impl CombinedProgress {
pub fn from_parts(tkg: Option<TkgProgress>, agent: Option<AgentProgress>) -> Self {
// TKG weight: 40%, Agent weight: 60%
let tkg_weight = 0.4;
let agent_weight = 0.6;
let tkg_progress = tkg.as_ref().map(|t| t.overall_progress).unwrap_or(0.0);
let agent_progress = agent.as_ref().map(|a| a.overall_progress).unwrap_or(0.0);
// If TKG not started but agent is running, agent drives progress
let tkg_active = tkg.is_some();
let agent_active = agent.is_some();
let overall = if tkg_active && agent_active {
tkg_progress * tkg_weight + agent_progress * agent_weight
} else if agent_active {
agent_progress
} else if tkg_active {
tkg_progress * tkg_weight
} else {
0.0
};
let file_uuid = tkg
.as_ref()
.map(|p| p.file_uuid.clone())
.or_else(|| agent.as_ref().map(|p| p.file_uuid.clone()))
.unwrap_or_default();
let current_phase = agent
.as_ref()
.map(|a| format!("agent:{}", a.phase))
.or_else(|| tkg.as_ref().map(|t| format!("tkg:{}", t.phase)))
.unwrap_or_else(|| "idle".to_string());
let message = agent
.as_ref()
.map(|a| a.message.clone())
.or_else(|| tkg.as_ref().map(|t| t.message.clone()))
.unwrap_or_else(|| "No active processing".to_string());
let updated_at = agent
.as_ref()
.map(|a| a.updated_at.clone())
.or_else(|| tkg.as_ref().map(|t| t.updated_at.clone()))
.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
CombinedProgress {
file_uuid,
overall_progress: overall.clamp(0.0, 1.0),
tkg,
agent,
current_phase,
message,
updated_at,
}
}
}
// ── Redis Integration ──────────────────────────────────────────────────────
use crate::core::db::redis_client::RedisClient;
use std::sync::Arc;
pub async fn publish_tkg_progress(
redis: &Arc<RedisClient>,
file_uuid: &str,
progress: &TkgProgress,
) {
let key = format!(
"{}progress:{}:tkg",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
file_uuid
);
if let Ok(mut conn) = redis.get_conn().await {
let json = serde_json::to_string(progress).unwrap_or_default();
let _: Result<(), _> = redis::cmd("SET")
.arg(&[&key, &json])
.query_async(&mut conn)
.await;
}
}
pub async fn publish_agent_progress(
redis: &Arc<RedisClient>,
file_uuid: &str,
progress: &AgentProgress,
) {
let key = format!(
"{}progress:{}:agent",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
file_uuid
);
if let Ok(mut conn) = redis.get_conn().await {
let json = serde_json::to_string(progress).unwrap_or_default();
let _: Result<(), _> = redis::cmd("SET")
.arg(&[&key, &json])
.query_async(&mut conn)
.await;
}
}
pub async fn get_progress(redis: &Arc<RedisClient>, file_uuid: &str) -> Option<CombinedProgress> {
let tkg_key = format!(
"{}progress:{}:tkg",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
file_uuid
);
let agent_key = format!(
"{}progress:{}:agent",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
file_uuid
);
if let Ok(mut conn) = redis.get_conn().await {
let tkg_str: Option<String> = redis::cmd("GET")
.arg(&tkg_key)
.query_async(&mut conn)
.await
.ok();
let agent_str: Option<String> = redis::cmd("GET")
.arg(&agent_key)
.query_async(&mut conn)
.await
.ok();
let tkg = tkg_str.and_then(|s| serde_json::from_str(&s).ok());
let agent = agent_str.and_then(|s| serde_json::from_str(&s).ok());
Some(CombinedProgress::from_parts(tkg, agent))
} else {
None
}
}
/// Publish pipeline progress to Redis (accumulates with existing progress)
pub async fn publish_pipeline_progress(
redis: &RedisClient,
file_uuid: &str,
progress: &PipelineProgress,
) {
let key = format!(
"{}progress:{}:pipeline",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
file_uuid
);
if let Ok(mut conn) = redis.get_conn().await {
// Try to read existing progress first
let existing: Option<PipelineProgress> = redis::cmd("GET")
.arg(&key)
.query_async(&mut conn)
.await
.ok()
.and_then(|s: String| serde_json::from_str(&s).ok());
let merged = if let Some(mut existing) = existing {
// Merge: update stages from new progress onto existing
for new_stage in &progress.stages {
if new_stage.status == "completed" || new_stage.progress > 0.0 {
if let Some(existing_stage) = existing
.stages
.iter_mut()
.find(|s| s.name == new_stage.name)
{
existing_stage.status = new_stage.status.clone();
existing_stage.progress = new_stage.progress;
existing_stage.detail = new_stage.detail.clone();
}
}
}
existing.recalculate_overall();
existing
} else {
progress.clone()
};
let json = serde_json::to_string(&merged).unwrap_or_default();
let _: Result<(), _> = redis::cmd("SET")
.arg(&[&key, &json])
.query_async(&mut conn)
.await;
}
}
/// Get pipeline progress from Redis
pub async fn get_pipeline_progress(
redis: &RedisClient,
file_uuid: &str,
) -> Option<PipelineProgress> {
let key = format!(
"{}progress:{}:pipeline",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
file_uuid
);
if let Ok(mut conn) = redis.get_conn().await {
let str_val: Option<String> = redis::cmd("GET")
.arg(&key)
.query_async(&mut conn)
.await
.ok();
str_val.and_then(|s| serde_json::from_str(&s).ok())
} else {
None
}
}