fix: Face processor now saves status and total_faces to face.json

This commit is contained in:
Accusys
2026-09-26 23:06:11 +08:00
parent 8a736a4103
commit 357e585399
99 changed files with 13881 additions and 1065 deletions
@@ -0,0 +1,101 @@
// Example: Scene VLM Integration in job_worker.rs
use crate::core::processor::scene_vlm::SceneVlmProcessor;
use crate::core::file_profile::{SceneProfile, SceneStatus};
pub async fn process_scene_vlm(
db: &crate::core::db::PostgresDb,
redis: Option<&crate::core::db::RedisClient>,
pool: &sqlx::PgPool,
uuid: &str,
output_dir: &str,
) -> anyhow::Result<()> {
// Check if Scene VLM is enabled
let (enabled, interval_sec, samples, use_cuts, max_workers) =
crate::core::config::get_scene_vlm_config();
if !enabled {
tracing::info!("[Scene VLM] Disabled, skipping");
return Ok(());
}
// Check if scenes.json already exists
let scenes_path = format!("{}/{}.scenes.json", output_dir, uuid);
if std::path::Path::new(&scenes_path).exists() {
tracing::info!("[Scene VLM] Already processed, skipping");
return Ok(());
}
// Load video metadata from database
let video = db.get_video_by_uuid(pool, uuid).await?;
let fps = video.fps.unwrap_or(29.97);
let duration = video.duration.unwrap_or(0.0);
let width = video.width.unwrap_or(1280) as u32;
let height = video.height.unwrap_or(720) as u32;
let total_frames = video.nb_frames.unwrap_or(0) as u32;
let video_path = video.path.clone();
if duration == 0.0 || total_frames == 0 {
tracing::warn!("[Scene VLM] Invalid video metadata, skipping");
return Ok(());
}
// Load CUT data
let cut_path = format!("{}/{}.cut.json", output_dir, uuid);
let cut_data = if std::path::Path::new(&cut_path).exists() {
let json = std::fs::read_to_string(&cut_path)?;
serde_json::from_str(&json)?
} else {
tracing::warn!("[Scene VLM] No cut.json found, using empty");
serde_json::json!({"scenes": []})
};
// Create processor
let processor = SceneVlmProcessor::new(samples, use_cuts, max_workers);
// Generate scene profile
tracing::info!("[Scene VLM] Generating profile for {} ({}s)", uuid, duration);
let profile = processor.generate_scene_profile(
&video_path,
uuid,
output_dir,
interval_sec,
&cut_data,
fps,
duration,
width,
height,
total_frames,
).await?;
tracing::info!(
"[Scene VLM] Selected {} frames for {}",
profile.total_scenes,
uuid
);
// Extract frames
let extracted = SceneVlmProcessor::extract_scene_frames(
&video_path,
output_dir,
uuid,
&profile.scenes,
).await?;
tracing::info!(
"[Scene VLM] Extracted {}/{} frames",
extracted.len(),
profile.total_scenes
);
// Save profile
SceneVlmProcessor::save_scene_profile(&profile, output_dir)?;
tracing::info!(
"[Scene VLM] Saved profile to {}/{}.scenes.json",
output_dir,
uuid
);
Ok(())
}
+225
View File
@@ -0,0 +1,225 @@
# Scene VLM Usage Guide
## Overview
Scene VLM is a new module that selects key frames from video intervals for VLM analysis. It replaces the trace-based VLM approach with a time-based sampling strategy.
## Features
- **Uniform Sampling**: 10 frames per 10-second interval
- **Blur-based Selection**: Chooses the clearest frame (lowest blur score)
- **CUT Handling**: Selects 2 frames per interval if a scene cut is detected
- **Parallel Processing**: Uses concurrent FFmpeg calls for performance
## Performance
Based on real testing:
- **Accuracy**: Average blur = 5.51 (best among tested methods)
- **Speed**: ~2.4s per video (160s video, 17 intervals, parallel processing)
- **Frame Count**: 16-34 frames (depends on CUT count)
## Usage Example
### 1. Generate Scene Profile
```rust
use momentry_core::core::processor::scene_vlm::SceneVlmProcessor;
use momentry_core::core::file_profile::{SceneProfile, SceneConfig};
// Create processor with default settings
let processor = SceneVlmProcessor::new(
10, // samples_per_interval
true, // use_cuts
10, // max_workers
);
// Load cut data
let cut_json = std::fs::read_to_string(format!("{}.cut.json", uuid))?;
let cut_data: serde_json::Value = serde_json::from_str(&cut_json)?;
// Generate scene profile
let profile = processor.generate_scene_profile(
"/path/to/video.mp4",
"file_uuid",
"/output/dir",
10, // interval_sec
&cut_data,
29.97, // fps
160.99, // duration
1280, // width
720, // height
4825, // total_frames
).await?;
// Save profile
SceneVlmProcessor::save_scene_profile(&profile, "/output/dir")?;
```
### 2. Extract Scene Frames
```rust
// Extract frames
let extracted_paths = SceneVlmProcessor::extract_scene_frames(
"/path/to/video.mp4",
"/output/dir",
"file_uuid",
&profile.scenes,
).await?;
println!("Extracted {} frames", extracted_paths.len());
```
### 3. Load Scene Profile
```rust
// Load existing profile
let profile = SceneVlmProcessor::load_scene_profile(
"/output/dir",
"file_uuid",
)?;
println!("Total scenes: {}", profile.total_scenes);
for scene in &profile.scenes {
println!(
"Scene {}: {}s (blur={})",
scene.index,
scene.timestamp_sec,
scene.quality_score.unwrap_or(0.0)
);
}
```
## Output Structure
```
output/{file_uuid}.scenes.json # Metadata
output/{file_uuid}/scenes/ # Frame images
├── scene_000.jpg
├── scene_001.jpg
└── ...
```
## Configuration
### Environment Variables
```bash
# Scene VLM
MOMENTRY_SCENE_VLM_ENABLED=true
MOMENTRY_SCENE_VLM_INTERVAL=10
MOMENTRY_SCENE_VLM_SAMPLES=10
MOMENTRY_SCENE_VLM_USE_CUTS=true
MOMENTRY_SCENE_VLM_MAX_WORKERS=10
```
### Config API
```json
{
"scene_vlm": {
"enabled": true,
"interval_sec": 10,
"samples_per_interval": 10,
"use_cuts": true,
"max_workers": 10,
"quality_metric": "ffmpeg_blurdetect"
}
}
```
## Scene Profile JSON Schema
```json
{
"version": "1.0",
"file_uuid": "3677f81d232e59f13453d737ceb582cb",
"status": "ready",
"total_scenes": 17,
"created_at": "2026-09-21T12:00:00Z",
"updated_at": "2026-09-21T12:00:05Z",
"video_info": {
"duration_sec": 160.99,
"fps": 29.97,
"width": 1280,
"height": 720,
"total_frames": 4825
},
"config": {
"interval_sec": 10,
"use_cuts": true,
"use_faces": false,
"quality_metric": "ffmpeg_blurdetect",
"samples_per_interval": 10
},
"scenes": [
{
"index": 0,
"filename": "scene_000.jpg",
"timestamp_sec": 3.34,
"frame_number": 100,
"selection_reason": "best_blur",
"quality_score": 5.24,
"quality_source": "ffmpeg_blurdetect",
"has_cut": false,
"cut_count": 0,
"vlm_status": "pending",
...
}
]
}
```
## Comparison with Trace VLM
| Metric | Trace VLM | Scene VLM |
|--------|-----------|-----------|
| **VLM Calls** | 106 | 17 |
| **Processing Time** | 5.3 min | 0.8 min |
| **Speed Improvement** | - | **6.6x** |
| **Focus** | Person appearance | Scene environment |
| **Use Case** | Identity recognition | Scene search/retrieval |
## Implementation Details
### Blur Score
- **Source**: FFmpeg `blurdetect` filter
- **Output**: `blur mean: X.XX`
- **Interpretation**: Lower = clearer
### Selection Logic
1. Sample 10 frames per 10-second interval
2. Calculate blur score for each frame
3. Select frame with lowest blur (clearest)
4. If CUT exists in interval, select 2 frames (pre/post cut)
### Performance Optimization
- **Parallel Processing**: Uses `futures_util::future::join_all` for concurrent FFmpeg calls
- **Worker Limit**: Max 10 concurrent FFmpeg processes
- **Expected Time**: 2-4 seconds per video
## Future Enhancements
1. **Face Integration**: Consider face presence when selecting frames
2. **VLM Analysis**: Add VLM description generation
3. **Embedding**: Store embeddings in Qdrant for scene search
4. **Streaming**: Support streaming large videos
## Testing
Run tests with:
```bash
cargo test scene_vlm --lib
```
## References
- `/Users/accusys/momentry_core/src/core/processor/scene_vlm.rs`
- `/Users/accusys/momentry_core/src/core/file_profile.rs` (SceneProfile struct)
- `docs/FILE_CHANGE_MANAGEMENT.md` (document guidelines)