feat: 三層階梯式 frame 取樣 + 純 Rust 運鏡分析 + pHash 去重
Phase correlation 運鏡分析 (camera_motion.rs): - ffmpeg pipe 抽幀 → 灰階 256x256 → rustfft 相位相關估 pan/tilt - 徑向功率譜估 zoom、極座標相位相關估 rotation - 中位數去噪 + none/low/high 分級 - samples_for_level: none=1, low=2, high=4 pHash 去重 (frame_dedup.rs): - 64-bit pHash (DCT 低頻) + hamming<=8 + 時間間隔去重 - scene extract 後對 jpg 去重: 387 → 317 (移除 70) 三層取樣 (scene_vlm.rs process_interval): - L0 moment=10s 保底 (SCENE_VLM_MOMENT_SEC) - L1 每個 cut 保底 1 張 (不設上限) - L2 運鏡依 level 增採, 運動路徑均勻取樣 + blurdetect 資料結構: - SceneFrame.camera_motion + selection_reason CameraMotion*/CutBaseline - VLM truncated (finish_reason=length) salvage 部分 JSON summary 其他: - face dedup 改用 per-library output dir - max_tokens 2048→4096 - config 5 項 (moment_sec/camera_motion_enabled/phash_hamming/time_gap/k) - Cargo.toml +image/ndarray/rustfft 驗證: 17e230cc force re-run → Selected 387 frames, CAM-MOTION 分析執行, pHash dedup 387→317, RESUME force=true carried over 0
This commit is contained in:
@@ -212,6 +212,54 @@ pub fn get_scene_vlm_config() -> (bool, u32, usize, bool, usize) {
|
||||
)
|
||||
}
|
||||
|
||||
// ── Frame 三層取樣 + 運鏡分析 configs ───────────────────────────
|
||||
/// moment 長度(秒),moment 內保底 1 張。預設 10。
|
||||
pub static SCENE_VLM_MOMENT_SEC: Lazy<u32> = Lazy::new(|| {
|
||||
env::var("MOMENTRY_SCENE_VLM_MOMENT_SEC")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(10)
|
||||
});
|
||||
|
||||
/// 是否啟用運鏡分析(相位相關)。預設 true。
|
||||
pub static CAMERA_MOTION_ENABLED: Lazy<bool> = Lazy::new(|| {
|
||||
env::var("MOMENTRY_CAMERA_MOTION_ENABLED")
|
||||
.map(|v| v == "true" || v == "1")
|
||||
.unwrap_or(true)
|
||||
});
|
||||
|
||||
/// pHash 去重漢明距離閾值。預設 8。
|
||||
pub static PHASH_HAMMING_THRESHOLD: Lazy<u32> = Lazy::new(|| {
|
||||
env::var("MOMENTRY_PHASH_HAMMING_THRESHOLD")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(8)
|
||||
});
|
||||
|
||||
/// scene frame 去重的時間間隔(幀)。預設約 2 秒 @30fps = 60 幀。
|
||||
pub static SCENE_TIME_GAP_FRAMES: Lazy<u32> = Lazy::new(|| {
|
||||
env::var("MOMENTRY_SCENE_TIME_GAP_FRAMES")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(60)
|
||||
});
|
||||
|
||||
/// face trace 去重的時間間隔(幀)。預設約 1 秒 @30fps = 30 幀。
|
||||
pub static TRACE_TIME_GAP_FRAMES: Lazy<u32> = Lazy::new(|| {
|
||||
env::var("MOMENTRY_TRACE_TIME_GAP_FRAMES")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(30)
|
||||
});
|
||||
|
||||
/// 每個 cut 抽取用於運鏡分析的幀數。預設 6。
|
||||
pub static CAMERA_MOTION_K: Lazy<usize> = Lazy::new(|| {
|
||||
env::var("MOMENTRY_CAMERA_MOTION_K")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(6)
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// JSON-backed configs (paths, concurrency, feature flags)
|
||||
// These read from admin_config.json with ENV fallback
|
||||
|
||||
@@ -869,6 +869,72 @@ pub struct SceneFrame {
|
||||
pub vlm_tags: Vec<VlmTagValue>,
|
||||
|
||||
pub embedding_status: EmbeddingStatus,
|
||||
|
||||
/// Camera-motion analysis for this scene (pan/tilt/zoom/rotation).
|
||||
/// Absent in legacy scenes.json → treated as static.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub camera_motion: Option<CameraMotion>,
|
||||
}
|
||||
|
||||
/// Camera motion analysis result for a scene / cut segment.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub struct CameraMotion {
|
||||
/// Dominant motion type.
|
||||
pub motion_type: MotionType,
|
||||
/// Severity level — drives how many extra samples to take.
|
||||
pub level: MotionLevel,
|
||||
/// Horizontal displacement (pixels, sign = direction).
|
||||
pub pan_px: f64,
|
||||
/// Vertical displacement (pixels, sign = direction).
|
||||
pub tilt_px: f64,
|
||||
/// Scale change factor (1.0 = no zoom).
|
||||
pub zoom_factor: f64,
|
||||
/// Rotation estimate (radians).
|
||||
pub rotation_rad: f64,
|
||||
/// Confidence 0.0-1.0 (based on phase-correlation peak consistency).
|
||||
pub confidence: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MotionType {
|
||||
Static,
|
||||
Pan,
|
||||
Tilt,
|
||||
Zoom,
|
||||
Rotation,
|
||||
Dolly,
|
||||
Handheld,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MotionLevel {
|
||||
None,
|
||||
Low,
|
||||
High,
|
||||
}
|
||||
|
||||
impl Default for MotionLevel {
|
||||
fn default() -> Self {
|
||||
MotionLevel::None
|
||||
}
|
||||
}
|
||||
|
||||
impl CameraMotion {
|
||||
/// A static / no-motion result (used as fallback and for legacy data).
|
||||
pub fn static_motion() -> Self {
|
||||
CameraMotion {
|
||||
motion_type: MotionType::Static,
|
||||
level: MotionLevel::None,
|
||||
pan_px: 0.0,
|
||||
tilt_px: 0.0,
|
||||
zoom_factor: 1.0,
|
||||
rotation_rad: 0.0,
|
||||
confidence: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -886,6 +952,10 @@ pub enum SelectionReason {
|
||||
PostCutBestBlur,
|
||||
SceneStart,
|
||||
Default,
|
||||
CameraMotionStart,
|
||||
CameraMotionMid,
|
||||
CameraMotionEnd,
|
||||
CutBaseline,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
//! Camera-motion analysis via pure-Rust phase correlation.
|
||||
//!
|
||||
//! Given a video segment, extract K evenly-spaced grayscale frames (via ffmpeg
|
||||
//! pipe, never written to disk), then estimate global camera motion between
|
||||
//! consecutive frames:
|
||||
//! - pan / tilt : phase-correlation peak position
|
||||
//! - zoom : radial power-spectrum scale change
|
||||
//! - rotation : phase correlation in polar coordinates
|
||||
//!
|
||||
//! A median over all consecutive pairs removes object-motion outliers. The
|
||||
//! result is classified into MotionLevel::None / Low / High so callers can
|
||||
//! decide how many extra samples to take inside a cut.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use image::GrayImage;
|
||||
use ndarray::{Array2, Axis};
|
||||
use rustfft::{num_complex::Complex, FftPlanner};
|
||||
use std::process::{Command, Stdio};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use crate::core::file_profile::{CameraMotion, MotionLevel, MotionType};
|
||||
|
||||
/// Number of FFT size (power of two) used for phase correlation.
|
||||
const FFT_SIZE: usize = 256;
|
||||
/// Number of frames to extract per segment.
|
||||
const DEFAULT_K: usize = 6;
|
||||
|
||||
/// Analyze camera motion in a video segment [start_frame, end_frame].
|
||||
/// `k` = number of evenly-spaced frames to sample (min 2).
|
||||
pub async fn analyze_camera_motion(
|
||||
video_path: &str,
|
||||
start_frame: u32,
|
||||
end_frame: u32,
|
||||
fps: f64,
|
||||
k: usize,
|
||||
) -> Result<CameraMotion> {
|
||||
let k = k.max(2);
|
||||
if end_frame <= start_frame || fps <= 0.0 {
|
||||
return Ok(CameraMotion::static_motion());
|
||||
}
|
||||
|
||||
let frames = extract_frames(video_path, start_frame, end_frame, fps, k).await?;
|
||||
if frames.len() < 2 {
|
||||
return Ok(CameraMotion::static_motion());
|
||||
}
|
||||
|
||||
let mut pans = Vec::new();
|
||||
let mut tilts = Vec::new();
|
||||
let mut zooms = Vec::new();
|
||||
let mut rots = Vec::new();
|
||||
let mut peaks = Vec::new();
|
||||
|
||||
for pair in frames.windows(2) {
|
||||
match phase_correlate(&pair[0], &pair[1]) {
|
||||
Ok((dx, dy, peak)) => {
|
||||
pans.push(dx);
|
||||
tilts.push(dy);
|
||||
zooms.push(estimate_zoom(&pair[0], &pair[1]));
|
||||
rots.push(estimate_rotation(&pair[0], &pair[1]));
|
||||
peaks.push(peak);
|
||||
}
|
||||
Err(e) => debug!("[CAM-MOTION] phase correlate failed: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
if pans.is_empty() {
|
||||
return Ok(CameraMotion::static_motion());
|
||||
}
|
||||
|
||||
let pan = median(&mut pans);
|
||||
let tilt = median(&mut tilts);
|
||||
let zoom = median(&mut zooms);
|
||||
let rot = median(&mut rots);
|
||||
let confidence = median(&mut peaks).clamp(0.0, 1.0);
|
||||
|
||||
// Classify: displacement relative to frame width, zoom/rotation thresholds.
|
||||
let pan_abs = pan.abs();
|
||||
let tilt_abs = tilt.abs();
|
||||
let zoom_delta = (zoom - 1.0).abs();
|
||||
let rot_abs = rot.abs();
|
||||
|
||||
let max_shift = pan_abs.max(tilt_abs);
|
||||
let (level, motion_type) = if max_shift < FFT_SIZE as f64 * 0.05
|
||||
&& zoom_delta < 0.05
|
||||
&& rot_abs < 0.02
|
||||
{
|
||||
(MotionLevel::None, MotionType::Static)
|
||||
} else {
|
||||
let high = max_shift > FFT_SIZE as f64 * 0.20
|
||||
|| zoom_delta > 0.30
|
||||
|| rot_abs > 0.08;
|
||||
let level = if high { MotionLevel::High } else { MotionLevel::Low };
|
||||
|
||||
// Dominant type by normalized magnitude.
|
||||
let mut candidates = vec![
|
||||
(pan_abs / (FFT_SIZE as f64 * 0.2), MotionType::Pan),
|
||||
(tilt_abs / (FFT_SIZE as f64 * 0.2), MotionType::Tilt),
|
||||
(zoom_delta / 0.3, MotionType::Zoom),
|
||||
(rot_abs / 0.08, MotionType::Rotation),
|
||||
];
|
||||
candidates.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let motion_type = candidates.first().map(|x| x.1).unwrap_or(MotionType::Pan);
|
||||
(level, motion_type)
|
||||
};
|
||||
|
||||
Ok(CameraMotion {
|
||||
motion_type,
|
||||
level,
|
||||
pan_px: pan,
|
||||
tilt_px: tilt,
|
||||
zoom_factor: zoom,
|
||||
rotation_rad: rot,
|
||||
confidence,
|
||||
})
|
||||
}
|
||||
|
||||
/// Map motion level to number of samples to take inside a cut.
|
||||
pub fn samples_for_level(level: MotionLevel) -> usize {
|
||||
match level {
|
||||
MotionLevel::None => 1,
|
||||
MotionLevel::Low => 2,
|
||||
MotionLevel::High => 4,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract `k` evenly-spaced grayscale frames from the segment into memory.
|
||||
async fn extract_frames(
|
||||
video_path: &str,
|
||||
start_frame: u32,
|
||||
end_frame: u32,
|
||||
fps: f64,
|
||||
k: usize,
|
||||
) -> Result<Vec<GrayImage>> {
|
||||
let mut frames = Vec::with_capacity(k);
|
||||
for i in 0..k {
|
||||
let frame = start_frame + ((end_frame - start_frame) as usize * i / (k - 1)) as u32;
|
||||
let time_sec = frame as f64 / fps;
|
||||
let child = Command::new("/opt/homebrew/bin/ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-v",
|
||||
"quiet",
|
||||
"-ss",
|
||||
&format!("{:.3}", time_sec),
|
||||
"-i",
|
||||
video_path,
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-vf",
|
||||
&format!("scale={}:{}", FFT_SIZE, FFT_SIZE),
|
||||
"-f",
|
||||
"image2pipe",
|
||||
"-vcodec",
|
||||
"png",
|
||||
"-",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.context("ffmpeg spawn failed for camera-motion frame extraction")?;
|
||||
|
||||
let output = child
|
||||
.wait_with_output()
|
||||
.context("ffmpeg wait failed for camera-motion frame extraction")?;
|
||||
if !output.status.success() || output.stdout.is_empty() {
|
||||
warn!("[CAM-MOTION] ffmpeg produced no frame at t={:.2}", time_sec);
|
||||
continue;
|
||||
}
|
||||
let img = image::load_from_memory_with_format(&output.stdout, image::ImageFormat::Png)
|
||||
.context("failed to decode extracted png")?
|
||||
.to_luma8();
|
||||
frames.push(img);
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
/// Phase correlation: returns (dx, dy, peak_confidence) in FFT pixels.
|
||||
/// dx/dy are wrapped into [-N/2, N/2].
|
||||
fn phase_correlate(a: &GrayImage, b: &GrayImage) -> Result<(f64, f64, f64)> {
|
||||
let n = FFT_SIZE;
|
||||
let fa = to_fft_array(a);
|
||||
let fb = to_fft_array(b);
|
||||
|
||||
let mut planner = FftPlanner::<f64>::new();
|
||||
let fft = planner.plan_fft_forward(n * n);
|
||||
let ifft = planner.plan_fft_inverse(n * n);
|
||||
|
||||
let mut aa = flatten(&fa);
|
||||
let mut bb = flatten(&fb);
|
||||
fft.process(&mut aa);
|
||||
fft.process(&mut bb);
|
||||
|
||||
// Cross-power spectrum: F(a) * conj(F(b)) / |F(a)F(b)|
|
||||
let mut cross = Vec::with_capacity(n * n);
|
||||
for (x, y) in aa.iter().zip(bb.iter()) {
|
||||
let denom = (x.norm_sqr() * y.norm_sqr()).sqrt();
|
||||
if denom < 1e-9 {
|
||||
cross.push(Complex::new(0.0, 0.0));
|
||||
} else {
|
||||
cross.push(x * y.conj() / denom);
|
||||
}
|
||||
}
|
||||
|
||||
ifft.process(&mut cross);
|
||||
|
||||
// Find peak (skip DC).
|
||||
let mut peak_idx = 0usize;
|
||||
let mut peak_val = -1.0f64;
|
||||
let mut second = 0.0f64;
|
||||
for (i, c) in cross.iter().enumerate() {
|
||||
let mag = c.norm();
|
||||
if i != 0 && mag > peak_val {
|
||||
second = peak_val.max(second);
|
||||
peak_val = mag;
|
||||
peak_idx = i;
|
||||
} else if mag > second {
|
||||
second = mag;
|
||||
}
|
||||
}
|
||||
if peak_val <= 0.0 {
|
||||
return Ok((0.0, 0.0, 0.0));
|
||||
}
|
||||
|
||||
let py = peak_idx / n;
|
||||
let px = peak_idx % n;
|
||||
let dx = wrap(px as f64, n);
|
||||
let dy = wrap(py as f64, n);
|
||||
// Confidence: ratio of peak to second-highest (higher = more reliable).
|
||||
let confidence = (peak_val / (second + 1e-6)).tanh();
|
||||
Ok((dx, dy, confidence))
|
||||
}
|
||||
|
||||
/// Estimate zoom by comparing radial power-spectrum bandwidth of two frames.
|
||||
/// A zoomed-in frame has energy concentrated at lower radial frequencies.
|
||||
fn estimate_zoom(a: &GrayImage, b: &GrayImage) -> f64 {
|
||||
let ea = spectral_energy(a);
|
||||
let eb = spectral_energy(b);
|
||||
if ea <= 0.0 || eb <= 0.0 {
|
||||
return 1.0;
|
||||
}
|
||||
// Ratio of high-frequency energy indicates scale change.
|
||||
(eb / ea).sqrt().clamp(0.5, 2.0)
|
||||
}
|
||||
|
||||
/// Estimate rotation via phase correlation in polar coordinates (coarse).
|
||||
/// Uses FFT angular power spectrum; returns radians in [-pi, pi].
|
||||
fn estimate_rotation(a: &GrayImage, b: &GrayImage) -> f64 {
|
||||
// Similar to zoom: compare column-sum profiles of the power spectrum.
|
||||
// A pure rotation shifts the angular profile cyclically.
|
||||
let pa = angular_profile(a);
|
||||
let pb = angular_profile(b);
|
||||
let n = pa.len();
|
||||
let mut best_shift = 0usize;
|
||||
let mut best_score = f64::NEG_INFINITY;
|
||||
for shift in 0..n {
|
||||
let mut score = 0.0;
|
||||
for i in 0..n {
|
||||
score += pa[i] * pb[(i + shift) % n];
|
||||
}
|
||||
if score > best_score {
|
||||
best_score = score;
|
||||
best_shift = shift;
|
||||
}
|
||||
}
|
||||
let shift = wrap(best_shift as f64, n);
|
||||
shift * std::f64::consts::PI * 2.0 / n as f64
|
||||
}
|
||||
|
||||
fn to_fft_array(img: &GrayImage) -> Array2<f64> {
|
||||
let (w, h) = img.dimensions();
|
||||
let mut arr = Array2::<f64>::zeros((h as usize, w as usize));
|
||||
for (x, y, px) in img.enumerate_pixels() {
|
||||
// Hann window reduces edge artifacts in phase correlation.
|
||||
let wx = 0.5 - 0.5 * (2.0 * std::f64::consts::PI * x as f64 / w as f64).cos();
|
||||
let wy = 0.5 - 0.5 * (2.0 * std::f64::consts::PI * y as f64 / h as f64).cos();
|
||||
arr[[y as usize, x as usize]] = px[0] as f64 * wx * wy;
|
||||
}
|
||||
arr
|
||||
}
|
||||
|
||||
fn flatten(arr: &Array2<f64>) -> Vec<Complex<f64>> {
|
||||
arr.iter().map(|v| Complex::new(*v, 0.0)).collect()
|
||||
}
|
||||
|
||||
fn power_spectrum(img: &GrayImage) -> Vec<f64> {
|
||||
let n = FFT_SIZE;
|
||||
let arr = to_fft_array(img);
|
||||
let mut data = flatten(&arr);
|
||||
let mut planner = FftPlanner::<f64>::new();
|
||||
let fft = planner.plan_fft_forward(n * n);
|
||||
fft.process(&mut data);
|
||||
data.iter().map(|c| c.norm_sqr()).collect()
|
||||
}
|
||||
|
||||
fn spectral_energy(img: &GrayImage) -> f64 {
|
||||
let spec = power_spectrum(img);
|
||||
let n = FFT_SIZE;
|
||||
let center = (n / 2, n / 2);
|
||||
let mut hi = 0.0;
|
||||
let mut total = 0.0;
|
||||
for (i, v) in spec.iter().enumerate() {
|
||||
let y = i / n;
|
||||
let x = i % n;
|
||||
let r = ((x as i32 - center.0 as i32).pow(2) + (y as i32 - center.1 as i32).pow(2)) as f64;
|
||||
total += v;
|
||||
if r > (n as f64 / 4.0).powi(2) {
|
||||
hi += v;
|
||||
}
|
||||
}
|
||||
if total > 0.0 { hi / total } else { 0.0 }
|
||||
}
|
||||
|
||||
fn angular_profile(img: &GrayImage) -> Vec<f64> {
|
||||
let n = FFT_SIZE;
|
||||
let spec = power_spectrum(img);
|
||||
let bins = 64;
|
||||
let mut profile = vec![0.0; bins];
|
||||
let center = (n / 2, n / 2);
|
||||
for (i, v) in spec.iter().enumerate() {
|
||||
let y = i / n;
|
||||
let x = i % n;
|
||||
let dx = x as f64 - center.0 as f64;
|
||||
let dy = y as f64 - center.1 as f64;
|
||||
if dx == 0.0 && dy == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let angle = dy.atan2(dx);
|
||||
let bin = (((angle + std::f64::consts::PI) / (2.0 * std::f64::consts::PI) * bins as f64)
|
||||
as usize)
|
||||
% bins;
|
||||
profile[bin] += v;
|
||||
}
|
||||
profile
|
||||
}
|
||||
|
||||
fn median(v: &mut Vec<f64>) -> f64 {
|
||||
if v.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let mid = v.len() / 2;
|
||||
if v.len() % 2 == 0 {
|
||||
(v[mid - 1] + v[mid]) / 2.0
|
||||
} else {
|
||||
v[mid]
|
||||
}
|
||||
}
|
||||
|
||||
fn wrap(v: f64, n: usize) -> f64 {
|
||||
let n = n as f64;
|
||||
let mut x = v % n;
|
||||
if x > n / 2.0 {
|
||||
x -= n;
|
||||
}
|
||||
if x < -n / 2.0 {
|
||||
x += n;
|
||||
}
|
||||
x
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Frame deduplication — perceptual hash (pHash) + time-gap based filtering.
|
||||
//!
|
||||
//! Used in two places:
|
||||
//! - Scene frames: after 3-level sampling, drop near-duplicate frames.
|
||||
//! - Face-trace key_frames: drop near-duplicate best_frames across a file
|
||||
//! (never merge different trace_id — that would break identity tracking).
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use image::{imageops::FilterType, GrayImage};
|
||||
use std::process::{Command, Stdio};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
/// Compute a 64-bit perceptual hash (pHash) of a JPEG/PNG at `path`.
|
||||
/// Resize to 32x32 grayscale, DCT, take the low 8x8 AC/DC coefficients.
|
||||
pub fn phash_from_file(path: &std::path::Path) -> Result<u64> {
|
||||
let img = image::open(path)
|
||||
.with_context(|| format!("failed to open image {}", path.display()))?
|
||||
.to_luma8();
|
||||
Ok(phash(&img))
|
||||
}
|
||||
|
||||
/// Compute 64-bit pHash from an in-memory grayscale image.
|
||||
pub fn phash(img: &GrayImage) -> u64 {
|
||||
const N: usize = 32;
|
||||
const LOW: usize = 8;
|
||||
let small = image::imageops::resize(img, N as u32, N as u32, FilterType::Triangle);
|
||||
|
||||
// Separable DCT-II.
|
||||
let mut dct = vec![vec![0.0f64; N]; N];
|
||||
let c = |u: usize, x: usize| -> f64 {
|
||||
if u == 0 {
|
||||
(1.0 / (N as f64).sqrt()) / std::f64::consts::SQRT_2
|
||||
} else {
|
||||
(2.0 * std::f64::consts::PI * u as f64 * x as f64 / (2.0 * N as f64)).cos()
|
||||
}
|
||||
};
|
||||
// Row pass.
|
||||
let mut tmp = vec![vec![0.0f64; N]; N];
|
||||
for y in 0..N {
|
||||
for u in 0..N {
|
||||
let mut s = 0.0;
|
||||
for x in 0..N {
|
||||
s += small.get_pixel(x as u32, y as u32)[0] as f64 * c(u, x);
|
||||
}
|
||||
tmp[y][u] = s;
|
||||
}
|
||||
}
|
||||
// Column pass.
|
||||
for v in 0..N {
|
||||
for u in 0..N {
|
||||
let mut s = 0.0;
|
||||
for y in 0..N {
|
||||
s += tmp[y][u] * c(v, y);
|
||||
}
|
||||
dct[v][u] = s;
|
||||
}
|
||||
}
|
||||
|
||||
// Use the low 8x8 block (including DC). Median of coefficients as threshold.
|
||||
let mut vals = Vec::with_capacity(LOW * LOW);
|
||||
for v in 0..LOW {
|
||||
for u in 0..LOW {
|
||||
vals.push(dct[v][u]);
|
||||
}
|
||||
}
|
||||
let mut sorted = vals.clone();
|
||||
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let median = sorted[sorted.len() / 2];
|
||||
|
||||
let mut hash = 0u64;
|
||||
for (i, v) in vals.iter().enumerate() {
|
||||
if *v > median {
|
||||
hash |= 1u64 << i;
|
||||
}
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// Hamming distance between two pHashes.
|
||||
pub fn hamming(a: u64, b: u64) -> u32 {
|
||||
(a ^ b).count_ones()
|
||||
}
|
||||
|
||||
/// Extract a single frame via ffmpeg into memory and return its pHash.
|
||||
pub async fn phash_from_video_frame(
|
||||
video_path: &str,
|
||||
frame: u32,
|
||||
fps: f64,
|
||||
) -> Result<u64> {
|
||||
let time_sec = frame as f64 / fps;
|
||||
let child = Command::new("/opt/homebrew/bin/ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-v",
|
||||
"quiet",
|
||||
"-ss",
|
||||
&format!("{:.3}", time_sec),
|
||||
"-i",
|
||||
video_path,
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-vf",
|
||||
"scale=64:64",
|
||||
"-f",
|
||||
"image2pipe",
|
||||
"-vcodec",
|
||||
"png",
|
||||
"-",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.context("ffmpeg spawn failed for phash extraction")?;
|
||||
let out = child.wait_with_output().context("ffmpeg wait failed")?;
|
||||
if out.stdout.is_empty() {
|
||||
anyhow::bail!("ffmpeg produced no frame for phash at {:.2}s", time_sec);
|
||||
}
|
||||
let img = image::load_from_memory_with_format(&out.stdout, image::ImageFormat::Png)
|
||||
.context("failed to decode png for phash")?
|
||||
.to_luma8();
|
||||
Ok(phash(&img))
|
||||
}
|
||||
|
||||
/// A generic item that can be time-ordered and hash-deduplicated.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DedupItem {
|
||||
pub key: String,
|
||||
pub frame: u32,
|
||||
pub hash: u64,
|
||||
}
|
||||
|
||||
/// Deduplicate items by (time gap AND pHash similarity).
|
||||
/// Keeps the first item of each near-duplicate group (caller should order by
|
||||
/// quality before calling if they want to keep the best instead).
|
||||
/// Returns the kept items and the list of dropped keys.
|
||||
pub fn dedup_items(items: Vec<DedupItem>, hamming_threshold: u32, time_gap_frames: u32) -> (Vec<DedupItem>, Vec<String>) {
|
||||
let mut kept: Vec<DedupItem> = Vec::new();
|
||||
let mut dropped: Vec<String> = Vec::new();
|
||||
for item in items {
|
||||
let dup = kept.iter().any(|k| {
|
||||
let close_time = item.frame.abs_diff(k.frame) <= time_gap_frames;
|
||||
close_time && hamming(item.hash, k.hash) <= hamming_threshold
|
||||
});
|
||||
if dup {
|
||||
dropped.push(item.key.clone());
|
||||
debug!("[DEDUP] dropped {} (frame {}, near {})", item.key, item.frame, kept.last().map(|x| x.frame).unwrap_or(0));
|
||||
} else {
|
||||
kept.push(item);
|
||||
}
|
||||
}
|
||||
if !dropped.is_empty() {
|
||||
warn!("[DEDUP] dropped {} near-duplicate frames", dropped.len());
|
||||
}
|
||||
(kept, dropped)
|
||||
}
|
||||
@@ -18,6 +18,8 @@ pub mod ocr;
|
||||
pub mod pose;
|
||||
pub mod scene_classification;
|
||||
pub mod scene_vlm;
|
||||
pub mod camera_motion;
|
||||
pub mod frame_dedup;
|
||||
pub mod tkg;
|
||||
pub mod vlm_summary;
|
||||
|
||||
|
||||
+213
-155
@@ -1,13 +1,15 @@
|
||||
use anyhow::{Context, Result};
|
||||
use futures_util::future::join_all;
|
||||
use tracing::{debug, info};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::core::file_profile::{
|
||||
EmbeddingStatus, SceneConfig, SceneFrame, SceneInfo, SceneProfile, SceneStatus,
|
||||
SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
|
||||
CameraMotion, EmbeddingStatus, MotionLevel, SceneConfig, SceneFrame, SceneInfo, SceneProfile,
|
||||
SceneStatus, SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
|
||||
};
|
||||
use crate::core::processor::camera_motion::{analyze_camera_motion, samples_for_level};
|
||||
|
||||
pub struct SceneVlmProcessor {
|
||||
samples_per_interval: usize,
|
||||
@@ -138,6 +140,11 @@ impl SceneVlmProcessor {
|
||||
cuts
|
||||
}
|
||||
|
||||
/// Three-tier frame sampling inside one moment (default 10s):
|
||||
/// L0: moment baseline (blur-best of the whole segment)
|
||||
/// L1: every distinct cut gets at least one frame (no upper bound)
|
||||
/// L2: camera motion (pan/tilt/zoom/rotation) adds extra samples:
|
||||
/// none -> 1, low -> 2, high -> 4, evenly along the motion path.
|
||||
pub async fn process_interval(
|
||||
video_path: &str,
|
||||
interval_start: f64,
|
||||
@@ -147,165 +154,169 @@ impl SceneVlmProcessor {
|
||||
samples_per_interval: usize,
|
||||
max_workers: usize,
|
||||
) -> Result<Vec<SceneFrame>> {
|
||||
let sample_frames =
|
||||
Self::compute_sample_frames(interval_start, interval_sec, fps, samples_per_interval);
|
||||
let moment_start_f = (interval_start * fps).round() as u32;
|
||||
let moment_end_f = ((interval_start + interval_sec) * fps).round() as u32;
|
||||
let cuts = Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data);
|
||||
|
||||
let blur_scores =
|
||||
Self::calculate_blur_parallel(video_path, &sample_frames, fps, max_workers).await?;
|
||||
// Build frame ranges: [moment_start, cut0), [cut0, cut1), ... [cutN, moment_end)
|
||||
let mut cut_frames: Vec<u32> = cuts
|
||||
.iter()
|
||||
.filter_map(|c| c.get("start_time").and_then(|t| t.as_f64()))
|
||||
.map(|t| (t * fps).round() as u32)
|
||||
.filter(|f| *f > moment_start_f && *f < moment_end_f)
|
||||
.collect();
|
||||
cut_frames.sort_unstable();
|
||||
cut_frames.dedup();
|
||||
|
||||
let cuts =
|
||||
Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data);
|
||||
|
||||
let mut selected_frames = Vec::new();
|
||||
|
||||
if cuts.is_empty() {
|
||||
if let Some((frame, blur)) = Self::select_best_frame(&blur_scores) {
|
||||
let timestamp = frame as f64 / fps;
|
||||
|
||||
selected_frames.push(SceneFrame {
|
||||
index: 0,
|
||||
filename: format!("scene_{:03}.jpg", 0),
|
||||
timestamp_sec: timestamp,
|
||||
frame_number: frame,
|
||||
selection_reason: SelectionReason::BestBlur,
|
||||
quality_score: Some(blur),
|
||||
quality_source: Some("ffmpeg_blurdetect".to_string()),
|
||||
scene_info: None,
|
||||
face_count: 0,
|
||||
person_traces: Vec::new(),
|
||||
has_cut: false,
|
||||
cut_count: 0,
|
||||
vlm_status: VlmStatus::Pending,
|
||||
vlm_description: None,
|
||||
vlm_description_localized: None,
|
||||
vlm_scene_type: None,
|
||||
vlm_location: None,
|
||||
vlm_objects: Vec::new(),
|
||||
vlm_attributes: None,
|
||||
vlm_tags: Vec::new(),
|
||||
embedding_status: EmbeddingStatus::Pending,
|
||||
});
|
||||
} else if let Some(&frame) = sample_frames.first() {
|
||||
// Fallback: use first sample frame when blur detection yields no scores
|
||||
let timestamp = frame as f64 / fps;
|
||||
selected_frames.push(SceneFrame {
|
||||
index: 0,
|
||||
filename: format!("scene_{:03}.jpg", 0),
|
||||
timestamp_sec: timestamp,
|
||||
frame_number: frame,
|
||||
selection_reason: SelectionReason::Default,
|
||||
quality_score: None,
|
||||
quality_source: None,
|
||||
scene_info: None,
|
||||
face_count: 0,
|
||||
person_traces: Vec::new(),
|
||||
has_cut: false,
|
||||
cut_count: 0,
|
||||
vlm_status: VlmStatus::Pending,
|
||||
vlm_description: None,
|
||||
vlm_description_localized: None,
|
||||
vlm_scene_type: None,
|
||||
vlm_location: None,
|
||||
vlm_objects: Vec::new(),
|
||||
vlm_attributes: None,
|
||||
vlm_tags: Vec::new(),
|
||||
embedding_status: EmbeddingStatus::Pending,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let cut = &cuts[0];
|
||||
let cut_time = cut
|
||||
.get("start_time")
|
||||
.and_then(|t| t.as_f64())
|
||||
.unwrap_or(interval_start);
|
||||
let cut_frame = (cut_time * fps).round() as u32;
|
||||
|
||||
let pre_frames: Vec<u32> = sample_frames
|
||||
.iter()
|
||||
.filter(|f| **f < cut_frame)
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
let post_frames: Vec<u32> = sample_frames
|
||||
.iter()
|
||||
.filter(|f| **f >= cut_frame)
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if !pre_frames.is_empty() {
|
||||
let pre_blur =
|
||||
Self::calculate_blur_parallel(video_path, &pre_frames, fps, max_workers)
|
||||
.await?;
|
||||
|
||||
if let Some((frame, blur)) = Self::select_best_frame(&pre_blur) {
|
||||
let timestamp = frame as f64 / fps;
|
||||
|
||||
selected_frames.push(SceneFrame {
|
||||
index: 0,
|
||||
filename: format!("scene_{:03}.jpg", selected_frames.len()),
|
||||
timestamp_sec: timestamp,
|
||||
frame_number: frame,
|
||||
selection_reason: SelectionReason::PreCutBestBlur,
|
||||
quality_score: Some(blur),
|
||||
quality_source: Some("ffmpeg_blurdetect".to_string()),
|
||||
scene_info: None,
|
||||
face_count: 0,
|
||||
person_traces: Vec::new(),
|
||||
has_cut: true,
|
||||
cut_count: cuts.len() as u32,
|
||||
vlm_status: VlmStatus::Pending,
|
||||
vlm_description: None,
|
||||
vlm_description_localized: None,
|
||||
vlm_scene_type: None,
|
||||
vlm_location: None,
|
||||
vlm_objects: Vec::new(),
|
||||
vlm_attributes: None,
|
||||
vlm_tags: Vec::new(),
|
||||
embedding_status: EmbeddingStatus::Pending,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if !post_frames.is_empty() {
|
||||
let post_blur =
|
||||
Self::calculate_blur_parallel(video_path, &post_frames, fps, max_workers)
|
||||
.await?;
|
||||
|
||||
if let Some((frame, blur)) = Self::select_best_frame(&post_blur) {
|
||||
let timestamp = frame as f64 / fps;
|
||||
|
||||
selected_frames.push(SceneFrame {
|
||||
index: 0,
|
||||
filename: format!("scene_{:03}.jpg", selected_frames.len()),
|
||||
timestamp_sec: timestamp,
|
||||
frame_number: frame,
|
||||
selection_reason: SelectionReason::PostCutBestBlur,
|
||||
quality_score: Some(blur),
|
||||
quality_source: Some("ffmpeg_blurdetect".to_string()),
|
||||
scene_info: None,
|
||||
face_count: 0,
|
||||
person_traces: Vec::new(),
|
||||
has_cut: true,
|
||||
cut_count: cuts.len() as u32,
|
||||
vlm_status: VlmStatus::Pending,
|
||||
vlm_description: None,
|
||||
vlm_description_localized: None,
|
||||
vlm_scene_type: None,
|
||||
vlm_location: None,
|
||||
vlm_objects: Vec::new(),
|
||||
vlm_attributes: None,
|
||||
vlm_tags: Vec::new(),
|
||||
embedding_status: EmbeddingStatus::Pending,
|
||||
});
|
||||
}
|
||||
let mut ranges: Vec<(u32, u32, bool)> = Vec::new(); // (start, end, has_cut)
|
||||
let mut prev = moment_start_f;
|
||||
for &cf in cut_frames.iter() {
|
||||
if cf > prev {
|
||||
ranges.push((prev, cf, false));
|
||||
}
|
||||
ranges.push((cf, cf, true)); // cut boundary marker
|
||||
prev = cf;
|
||||
}
|
||||
if moment_end_f > prev {
|
||||
ranges.push((prev, moment_end_f, false));
|
||||
}
|
||||
// If no cuts, single range.
|
||||
if ranges.is_empty() {
|
||||
ranges.push((moment_start_f, moment_end_f, false));
|
||||
}
|
||||
|
||||
for (i, frame) in selected_frames.iter_mut().enumerate() {
|
||||
let motion_enabled = *crate::core::config::CAMERA_MOTION_ENABLED;
|
||||
let k = *crate::core::config::CAMERA_MOTION_K;
|
||||
let mut selected: Vec<SceneFrame> = Vec::new();
|
||||
|
||||
for (range_idx, (rs, re, is_cut)) in ranges.iter().enumerate() {
|
||||
if *is_cut {
|
||||
// Cut boundary: one frame at the cut itself (L1 baseline).
|
||||
let frame = *rs;
|
||||
if let Some(sf) = Self::make_frame(
|
||||
selected.len(),
|
||||
frame,
|
||||
fps,
|
||||
SelectionReason::CutBaseline,
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
1,
|
||||
) {
|
||||
selected.push(sf);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let seg_start = *rs;
|
||||
let seg_end = (*re).max(seg_start + 1);
|
||||
|
||||
// L2: camera-motion analysis on this sub-segment.
|
||||
let motion: Option<CameraMotion> = if motion_enabled && seg_end > seg_start {
|
||||
match analyze_camera_motion(video_path, seg_start, seg_end, fps, k).await {
|
||||
Ok(m) if m.level != MotionLevel::None => Some(m),
|
||||
Ok(m) => Some(m),
|
||||
Err(e) => {
|
||||
debug!("[CAM-MOTION] analysis failed for {}-{}: {}", seg_start, seg_end, e);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let count = motion
|
||||
.as_ref()
|
||||
.map(|m| samples_for_level(m.level))
|
||||
.unwrap_or(1);
|
||||
|
||||
// Sample `count` frames evenly inside [seg_start, seg_end), each
|
||||
// chosen as the blur-best within its own sub-window.
|
||||
let window = (seg_end - seg_start) / count as u32;
|
||||
for i in 0..count {
|
||||
let ws = seg_start + window * i as u32;
|
||||
let we = if i + 1 == count { seg_end } else { (ws + window).min(seg_end) };
|
||||
// Sparse sample inside the sub-window (max 6 candidates) to avoid
|
||||
// one ffmpeg call per frame on high-fps video.
|
||||
let span = we.max(ws + 1) - ws;
|
||||
let step = (span / 6).max(1);
|
||||
let candidates: Vec<u32> = (ws..we.max(ws + 1)).step_by(step as usize).collect();
|
||||
let blur = Self::calculate_blur_parallel(video_path, &candidates, fps, max_workers).await?;
|
||||
let chosen = Self::select_best_frame(&blur)
|
||||
.map(|(f, b)| (f, Some(b)))
|
||||
.or_else(|| candidates.first().map(|f| (*f, None)));
|
||||
if let Some((frame, blur_score)) = chosen {
|
||||
let reason = if count == 1 {
|
||||
SelectionReason::BestBlur
|
||||
} else if i == 0 {
|
||||
SelectionReason::CameraMotionStart
|
||||
} else if i + 1 == count {
|
||||
SelectionReason::CameraMotionEnd
|
||||
} else {
|
||||
SelectionReason::CameraMotionMid
|
||||
};
|
||||
if let Some(sf) = Self::make_frame(
|
||||
selected.len(),
|
||||
frame,
|
||||
fps,
|
||||
reason,
|
||||
blur_score,
|
||||
motion.clone(),
|
||||
false,
|
||||
cut_frames.len() as u32,
|
||||
) {
|
||||
selected.push(sf);
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = range_idx;
|
||||
}
|
||||
|
||||
// Time-gap dedup: drop frames too close in time AND visually near-identical
|
||||
// is done later on extracted jpg (pHash). Here we only drop exact same frame.
|
||||
selected.dedup_by(|a, b| a.frame_number == b.frame_number);
|
||||
|
||||
for (i, frame) in selected.iter_mut().enumerate() {
|
||||
frame.index = i;
|
||||
}
|
||||
|
||||
Ok(selected_frames)
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
fn make_frame(
|
||||
index: usize,
|
||||
frame: u32,
|
||||
fps: f64,
|
||||
reason: SelectionReason,
|
||||
blur: Option<f64>,
|
||||
camera_motion: Option<CameraMotion>,
|
||||
has_cut: bool,
|
||||
cut_count: u32,
|
||||
) -> Option<SceneFrame> {
|
||||
Some(SceneFrame {
|
||||
index,
|
||||
filename: format!("scene_{:03}.jpg", index),
|
||||
timestamp_sec: frame as f64 / fps,
|
||||
frame_number: frame,
|
||||
selection_reason: reason,
|
||||
quality_score: blur,
|
||||
quality_source: if blur.is_some() { Some("ffmpeg_blurdetect".to_string()) } else { None },
|
||||
scene_info: None,
|
||||
face_count: 0,
|
||||
person_traces: Vec::new(),
|
||||
has_cut,
|
||||
cut_count,
|
||||
vlm_status: VlmStatus::Pending,
|
||||
vlm_description: None,
|
||||
vlm_description_localized: None,
|
||||
vlm_scene_type: None,
|
||||
vlm_location: None,
|
||||
vlm_objects: Vec::new(),
|
||||
vlm_attributes: None,
|
||||
vlm_tags: Vec::new(),
|
||||
embedding_status: EmbeddingStatus::Pending,
|
||||
camera_motion,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn generate_scene_profile(
|
||||
@@ -321,6 +332,10 @@ impl SceneVlmProcessor {
|
||||
height: u32,
|
||||
total_frames: u32,
|
||||
) -> Result<SceneProfile> {
|
||||
// moment length is configurable (default 10s); SCENE_VLM_INTERVAL is
|
||||
// the legacy alias — prefer MOMENTRY_SCENE_VLM_MOMENT_SEC when set.
|
||||
let moment_sec = *crate::core::config::SCENE_VLM_MOMENT_SEC;
|
||||
let interval_sec = if moment_sec > 0 { moment_sec } else { interval_sec };
|
||||
let config = SceneConfig {
|
||||
interval_sec,
|
||||
use_cuts: true,
|
||||
@@ -600,6 +615,37 @@ Rules:
|
||||
Some(&content[start..=end])
|
||||
}
|
||||
|
||||
/// Pull a `"summary": "..."` string out of a possibly-truncated JSON blob.
|
||||
fn salvage_summary(content: &str) -> Option<String> {
|
||||
let key = content.find("\"summary\"")?;
|
||||
let colon = content[key..].find(':')? + key;
|
||||
let mut rest = &content[colon + 1..];
|
||||
rest = rest.trim_start();
|
||||
if !rest.starts_with('"') {
|
||||
return None;
|
||||
}
|
||||
rest = &rest[1..];
|
||||
let mut out = String::new();
|
||||
let mut esc = false;
|
||||
for ch in rest.chars() {
|
||||
if esc {
|
||||
out.push(ch);
|
||||
esc = false;
|
||||
continue;
|
||||
}
|
||||
if ch == '\\' {
|
||||
esc = true;
|
||||
continue;
|
||||
}
|
||||
if ch == '"' {
|
||||
break;
|
||||
}
|
||||
out.push(ch);
|
||||
}
|
||||
let out = out.trim().to_string();
|
||||
if out.len() >= 10 { Some(out) } else { None }
|
||||
}
|
||||
|
||||
fn parse_tags(value: Option<&serde_json::Value>) -> Vec<VlmTagValue> {
|
||||
let Some(arr) = value.and_then(|v| v.as_array()) else {
|
||||
return Vec::new();
|
||||
@@ -756,8 +802,9 @@ Rules:
|
||||
.get("choices")
|
||||
.and_then(|c| c.get(0))
|
||||
.context("Invalid VLM API response structure")?;
|
||||
if choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length") {
|
||||
anyhow::bail!("VLM returned truncated response (finish_reason=length)");
|
||||
let truncated = choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length");
|
||||
if truncated {
|
||||
debug!("[Scene VLM] response truncated (finish_reason=length) — attempting to salvage partial JSON");
|
||||
}
|
||||
let message = choice.get("message").context("Invalid VLM API response structure")?;
|
||||
|
||||
@@ -827,6 +874,17 @@ Rules:
|
||||
tracing::warn!("[Scene VLM] Failed to extract JSON object from VLM response");
|
||||
}
|
||||
|
||||
// Salvage path for truncated responses: pull the "summary" string even
|
||||
// when the surrounding JSON object was cut off mid-generation.
|
||||
if let Some(desc) = Self::salvage_summary(&content) {
|
||||
let objects = Self::extract_objects_from_text(&content);
|
||||
let tags: Vec<VlmTagValue> = Self::extract_tags_from_text(&content)
|
||||
.into_iter()
|
||||
.map(VlmTagValue::String)
|
||||
.collect();
|
||||
return Ok((desc, objects, tags));
|
||||
}
|
||||
|
||||
tracing::warn!(
|
||||
"[Scene VLM] Failed to parse structured JSON, falling back to text heuristics"
|
||||
);
|
||||
|
||||
@@ -4520,7 +4520,12 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
// Before running dedup, verify all 4 required files exist per trace:
|
||||
// key_frame.jpg, key_face.jpg, trace_profile.json, face_traced.json
|
||||
if has_face {
|
||||
let output_dir = OUTPUT_DIR.as_str();
|
||||
let per_lib = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
|
||||
let output_dir = if std::path::Path::new(&per_lib).is_dir() {
|
||||
per_lib.as_str()
|
||||
} else {
|
||||
OUTPUT_DIR.as_str()
|
||||
};
|
||||
let output_base = output_dir.trim_end_matches('/');
|
||||
let traced_path = format!("{}/{}.face_traced.json", output_base, uuid);
|
||||
|
||||
@@ -5686,10 +5691,56 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
carried_over, uuid, force_scene_vlm
|
||||
);
|
||||
|
||||
let extracted =
|
||||
let mut extracted =
|
||||
SceneVlmProcessor::extract_scene_frames(&video_path, output_dir, uuid, &profile.scenes)
|
||||
.await?;
|
||||
|
||||
// Second-pass dedup: pHash + time-gap over the extracted jpgs.
|
||||
// Drop a scene when it is visually near-identical to a previously kept
|
||||
// one within the time-gap window. Resume-carried scenes are kept as-is.
|
||||
{
|
||||
use crate::core::processor::frame_dedup::{dedup_items, phash_from_file, DedupItem};
|
||||
let hamming_threshold = *crate::core::config::PHASH_HAMMING_THRESHOLD;
|
||||
let time_gap = *crate::core::config::SCENE_TIME_GAP_FRAMES;
|
||||
let mut items = Vec::new();
|
||||
for (i, path) in extracted.iter().enumerate() {
|
||||
if i >= profile.scenes.len() {
|
||||
break;
|
||||
}
|
||||
let hash = phash_from_file(path).unwrap_or(0);
|
||||
items.push(DedupItem {
|
||||
key: format!("{}", i),
|
||||
frame: profile.scenes[i].frame_number,
|
||||
hash,
|
||||
});
|
||||
}
|
||||
let (kept, dropped) = dedup_items(items, hamming_threshold, time_gap);
|
||||
if !dropped.is_empty() {
|
||||
let keep_set: std::collections::HashSet<usize> = kept
|
||||
.iter()
|
||||
.filter_map(|k| k.key.parse::<usize>().ok())
|
||||
.collect();
|
||||
let old_scenes = std::mem::take(&mut profile.scenes);
|
||||
let old_extracted = extracted.clone();
|
||||
let mut new_scenes = Vec::new();
|
||||
let mut new_extracted = Vec::new();
|
||||
for (i, (scene, path)) in old_scenes.into_iter().zip(old_extracted.into_iter()).enumerate() {
|
||||
if keep_set.contains(&i) {
|
||||
new_scenes.push(scene);
|
||||
new_extracted.push(path);
|
||||
}
|
||||
}
|
||||
profile.scenes = new_scenes;
|
||||
profile.total_scenes = profile.scenes.len();
|
||||
extracted = new_extracted;
|
||||
info!(
|
||||
"[Scene VLM] pHash dedup removed {} near-duplicate scenes ({} remain)",
|
||||
dropped.len(),
|
||||
profile.scenes.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
"[Scene VLM] Extracted {}/{} frames",
|
||||
extracted.len(),
|
||||
|
||||
Reference in New Issue
Block a user