feat: declarative pipeline config, non-blocking Scene VLM, rust_asrx
Consolidated snapshot (previously WIP in working tree). - core/pipeline_config: new module loading config/pipeline_flows.json as the source of truth for stage execution mode (parallel/blocking) and dependencies - worker/job_worker: dispatch Scene VLM to a background task when the stage is declared parallel, unblocking the worker poll loop; resolve processor dependencies from pipeline_flows.json (fallback to built-in) - config/pipeline_flows.json: asrx depends on [cut, asr] - scripts/fix_stuck_jobs: fix UTC timezone comparison, raise default threshold to 6h, skip jobs with recent processor activity - rust_asrx: Rust speaker diarization CLI + processor wiring - processor metadata helper; fast_face_clustering script; file_progress pipeline API; scan API; VAD updates
This commit is contained in:
@@ -5,6 +5,77 @@ use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::error;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct PipelineFlow {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
pub stages: Vec<PipelineStage>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dependencies: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PipelineStage {
|
||||
pub name: String,
|
||||
pub processor_type: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
#[serde(default)]
|
||||
pub required: bool,
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
#[serde(default)]
|
||||
pub timeout_secs: u32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tool: Option<ToolSelection>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub condition: Option<StageCondition>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub on_failure: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parameters: Option<serde_json::Map<String, serde_json::Value>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ToolSelection {
|
||||
pub name: String,
|
||||
pub priority: u8,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
#[serde(default)]
|
||||
pub parameters: serde_json::Map<String, serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub usage_notes: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StageCondition {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub depends_on: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub skip_if_exists: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub run_if_missing: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct PipelineConfig {
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
#[serde(default = "default_max_concurrent_stages")]
|
||||
pub max_concurrent_stages: u32,
|
||||
#[serde(default)]
|
||||
pub default_timeout_secs: u32,
|
||||
pub flows: HashMap<String, PipelineFlow>,
|
||||
}
|
||||
|
||||
fn default_max_concurrent_stages() -> u32 {
|
||||
3
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct VlmPrompt {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -381,6 +452,8 @@ pub struct AdminConfig {
|
||||
pub admin_settings: AdminSettings,
|
||||
#[serde(default)]
|
||||
pub search: SearchConfig,
|
||||
#[serde(default)]
|
||||
pub pipeline: PipelineConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
@@ -407,6 +480,8 @@ pub struct PartialAdminConfig {
|
||||
pub admin_settings: Option<AdminSettings>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub search: Option<SearchConfig>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pipeline: Option<PipelineConfig>,
|
||||
}
|
||||
|
||||
pub struct AdminConfigManager {
|
||||
|
||||
@@ -684,6 +684,7 @@ impl ProcessorType {
|
||||
ProcessorType::Ocr,
|
||||
ProcessorType::Face,
|
||||
ProcessorType::FaceCluster,
|
||||
ProcessorType::Scene, // Scene VLM processor
|
||||
// ProcessorType::Pose, // Disabled in production pipeline
|
||||
// ProcessorType::Hand, // Disabled in production pipeline
|
||||
// ProcessorType::Appearance, // Disabled in production pipeline
|
||||
|
||||
@@ -746,6 +746,8 @@ pub fn count_face_artifacts(output_dir: &str, file_uuid: &str) -> FaceArtifactsC
|
||||
pub struct SceneProfile {
|
||||
pub version: String,
|
||||
pub file_uuid: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub processor: Option<crate::core::processor::ProcessorInfo>,
|
||||
pub status: SceneStatus,
|
||||
pub video_info: VideoInfo,
|
||||
pub config: SceneConfig,
|
||||
@@ -885,9 +887,17 @@ pub struct SceneAttributes {
|
||||
|
||||
impl SceneProfile {
|
||||
pub fn new(file_uuid: &str, video_info: VideoInfo, config: SceneConfig) -> Self {
|
||||
use crate::core::processor::{ProcessorInfo, PROCESSOR_VERSION};
|
||||
|
||||
Self {
|
||||
version: "1.0".to_string(),
|
||||
file_uuid: file_uuid.to_string(),
|
||||
processor: Some(ProcessorInfo {
|
||||
name: "scene_vlm".to_string(),
|
||||
tool: "ffmpeg_scene_detect".to_string(),
|
||||
version: PROCESSOR_VERSION.to_string(),
|
||||
config: Some(serde_json::to_value(&config).unwrap_or(serde_json::json!({}))),
|
||||
}),
|
||||
status: SceneStatus::Pending,
|
||||
video_info,
|
||||
config,
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
use serde::{ser::Serializer, Serialize};
|
||||
use std::io::{self, Write};
|
||||
|
||||
pub struct RoundedFloatFormatter {
|
||||
decimals: usize,
|
||||
}
|
||||
|
||||
impl RoundedFloatFormatter {
|
||||
pub fn new(decimals: usize) -> Self {
|
||||
Self { decimals }
|
||||
}
|
||||
}
|
||||
|
||||
impl serde_json::ser::Formatter for RoundedFloatFormatter {
|
||||
fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
|
||||
where
|
||||
W: ?Sized + io::Write,
|
||||
{
|
||||
let rounded = if self.decimals == 0 {
|
||||
value.round()
|
||||
} else {
|
||||
let factor = 10_f64.powi(self.decimals as i32);
|
||||
(value * factor).round() / factor
|
||||
};
|
||||
write!(writer, "{:.1$}", rounded, self.decimals)
|
||||
}
|
||||
|
||||
fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
|
||||
where
|
||||
W: ?Sized + io::Write,
|
||||
{
|
||||
let rounded = if self.decimals == 0 {
|
||||
f64::from(value).round() as f32
|
||||
} else {
|
||||
let factor = 10_f32.powi(self.decimals as i32);
|
||||
(value * factor).round() / factor
|
||||
};
|
||||
write!(writer, "{:.1$}", rounded, self.decimals)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_string_pretty_rounded<T: Serialize>(value: &T, decimals: usize) -> serde_json::Result<String> {
|
||||
let mut buf = Vec::new();
|
||||
let formatter = RoundedFloatFormatter::new(decimals);
|
||||
let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
|
||||
value.serialize(&mut ser)?;
|
||||
String::from_utf8(buf)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
|
||||
.map_err(|e| serde_json::Error::io(e))
|
||||
}
|
||||
|
||||
pub fn write_file_pretty_rounded<T: Serialize>(
|
||||
value: &T,
|
||||
path: &str,
|
||||
decimals: usize,
|
||||
) -> anyhow::Result<()> {
|
||||
let json = to_string_pretty_rounded(value, decimals)?;
|
||||
std::fs::write(path, json)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -18,11 +18,13 @@ pub mod health_agent;
|
||||
pub mod identity;
|
||||
pub mod init;
|
||||
pub mod ingestion;
|
||||
pub mod json_formatter;
|
||||
pub mod llm;
|
||||
pub mod overlay;
|
||||
pub mod path_utils;
|
||||
pub mod person_identity;
|
||||
pub mod pipeline;
|
||||
pub mod pipeline_config;
|
||||
pub mod probe;
|
||||
pub mod processor;
|
||||
pub mod progress;
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Declarative pipeline flow configuration (`config/pipeline_flows.json`).
|
||||
//!
|
||||
//! This module is the single source of truth for *how* the worker executes each
|
||||
//! pipeline stage. In particular, the `parallel` flag on a stage declares whether
|
||||
//! that stage runs in the background (non-blocking) or sequentially (the caller
|
||||
//! waits for it to finish). The worker reads `parallel` from here instead of
|
||||
//! hardcoding the execution mode per stage.
|
||||
//!
|
||||
//! Example: the `scene` stage (Scene VLM) is declared `"parallel": true`, so the
|
||||
//! worker dispatches it to a background task rather than awaiting it inline in the
|
||||
//! poll loop.
|
||||
//!
|
||||
//! Loaded once and cached. Edit `config/pipeline_flows.json` and restart the worker
|
||||
//! to apply changes.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// A single stage within a flow (one processor).
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Stage {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub processor_type: String,
|
||||
/// `true` = may run concurrently / dispatched to a background task (non-blocking).
|
||||
/// `false` = sequential, the caller waits for completion.
|
||||
#[serde(default = "default_true")]
|
||||
pub parallel: bool,
|
||||
#[serde(default)]
|
||||
pub dependencies: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
#[serde(default)]
|
||||
pub timeout_secs: u64,
|
||||
}
|
||||
|
||||
/// An ordered collection of stages (e.g. the `register` flow).
|
||||
#[derive(Debug, Clone, Deserialize, Default)]
|
||||
pub struct Flow {
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
#[serde(default)]
|
||||
pub stages: Vec<Stage>,
|
||||
}
|
||||
|
||||
/// A phase grouping (used for the progress UI and concurrency ceilings).
|
||||
#[derive(Debug, Clone, Deserialize, Default)]
|
||||
pub struct Phase {
|
||||
#[serde(default)]
|
||||
pub id: i64,
|
||||
#[serde(default)]
|
||||
pub name_en: Option<String>,
|
||||
#[serde(default)]
|
||||
pub parallel_strategy: String,
|
||||
#[serde(default)]
|
||||
pub max_concurrent: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub processors: Vec<String>,
|
||||
}
|
||||
|
||||
/// Root of `config/pipeline_flows.json`.
|
||||
#[derive(Debug, Clone, Deserialize, Default)]
|
||||
pub struct PipelineFlows {
|
||||
#[serde(default)]
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
#[serde(default)]
|
||||
pub max_concurrent_stages: u32,
|
||||
#[serde(default)]
|
||||
pub default_timeout_secs: u64,
|
||||
#[serde(default)]
|
||||
pub phases: Vec<Phase>,
|
||||
#[serde(default)]
|
||||
pub flows: HashMap<String, Flow>,
|
||||
}
|
||||
|
||||
static CONFIG: OnceLock<PipelineFlows> = OnceLock::new();
|
||||
|
||||
/// Get the loaded pipeline flow configuration (loaded once, cached).
|
||||
pub fn get() -> &'static PipelineFlows {
|
||||
CONFIG.get_or_init(load)
|
||||
}
|
||||
|
||||
fn load() -> PipelineFlows {
|
||||
let candidates = [
|
||||
crate::core::path_utils::config_dir().join("pipeline_flows.json"),
|
||||
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config/pipeline_flows.json"),
|
||||
];
|
||||
for path in candidates {
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(s) => match serde_json::from_str::<PipelineFlows>(&s) {
|
||||
Ok(cfg) => {
|
||||
tracing::info!(
|
||||
"pipeline_config: loaded {} (version={}, {} flows)",
|
||||
path.display(),
|
||||
cfg.version,
|
||||
cfg.flows.len()
|
||||
);
|
||||
return cfg;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("pipeline_config: failed to parse {}: {}", path.display(), e)
|
||||
}
|
||||
},
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
tracing::warn!("pipeline_config: pipeline_flows.json not found, using defaults");
|
||||
PipelineFlows {
|
||||
default_timeout_secs: 3600,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl PipelineFlows {
|
||||
/// Look up a stage by flow name and stage/processor name.
|
||||
pub fn stage(&self, flow: &str, name: &str) -> Option<&Stage> {
|
||||
self.flows.get(flow)?.stages.iter().find(|s| s.name == name)
|
||||
}
|
||||
|
||||
/// Whether a stage is declared to run in parallel (non-blocking).
|
||||
///
|
||||
/// Unknown stages default to `true` (parallel / non-blocking) so that a
|
||||
/// missing config entry never reintroduces blocking behavior.
|
||||
pub fn is_parallel(&self, flow: &str, name: &str) -> bool {
|
||||
self.stage(flow, name).map(|s| s.parallel).unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Declared dependencies for a stage (empty when unknown).
|
||||
pub fn dependencies(&self, flow: &str, name: &str) -> Vec<String> {
|
||||
self.stage(flow, name)
|
||||
.map(|s| s.dependencies.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Effective timeout for a stage (falls back to `default_timeout_secs`).
|
||||
pub fn timeout_secs(&self, flow: &str, name: &str) -> u64 {
|
||||
self.stage(flow, name)
|
||||
.map(|s| s.timeout_secs)
|
||||
.filter(|&t| t > 0)
|
||||
.unwrap_or(self.default_timeout_secs)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_unknown_stage_defaults_parallel() {
|
||||
let cfg = PipelineFlows::default();
|
||||
assert!(cfg.is_parallel("register", "does_not_exist"));
|
||||
assert!(cfg.dependencies("register", "does_not_exist").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scene_declared_parallel() {
|
||||
// The shipped config declares the scene stage as parallel.
|
||||
let cfg = get();
|
||||
assert!(
|
||||
cfg.is_parallel("register", "scene"),
|
||||
"scene stage must be parallel in pipeline_flows.json"
|
||||
);
|
||||
assert_eq!(
|
||||
cfg.dependencies("register", "scene"),
|
||||
vec!["cut".to_string()]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,13 @@ use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
use super::metadata::ProcessorMetadata;
|
||||
use super::AsrStatus;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct AsrResult {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<ProcessorMetadata>,
|
||||
#[serde(default)]
|
||||
pub status: Option<AsrStatus>,
|
||||
pub language: Option<String>,
|
||||
@@ -24,8 +27,35 @@ impl AsrResult {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
|
||||
use chrono::Utc;
|
||||
use super::metadata::{ProcessorInfo, Timestamps, SourceInfo};
|
||||
|
||||
let metadata = ProcessorMetadata {
|
||||
processor: ProcessorInfo {
|
||||
name: processor_name.to_string(),
|
||||
tool: tool.to_string(),
|
||||
version: super::metadata::PROCESSOR_VERSION.to_string(),
|
||||
config: None,
|
||||
},
|
||||
timestamps: Timestamps {
|
||||
created_at: Utc::now(),
|
||||
updated_at: None,
|
||||
processing_time_ms: None,
|
||||
},
|
||||
source: file_uuid.map(|uuid| SourceInfo {
|
||||
file_uuid: uuid.to_string(),
|
||||
video_info: None,
|
||||
}),
|
||||
custom: None,
|
||||
};
|
||||
|
||||
self.metadata = Some(metadata);
|
||||
}
|
||||
|
||||
pub fn no_audio_track() -> Self {
|
||||
AsrResult {
|
||||
metadata: None,
|
||||
status: Some(AsrStatus::NoAudioTrack),
|
||||
language: None,
|
||||
language_probability: None,
|
||||
@@ -36,6 +66,7 @@ impl AsrResult {
|
||||
|
||||
pub fn silent_audio() -> Self {
|
||||
AsrResult {
|
||||
metadata: None,
|
||||
status: Some(AsrStatus::SilentAudio),
|
||||
language: None,
|
||||
language_probability: None,
|
||||
@@ -126,11 +157,13 @@ pub async fn process_asr(
|
||||
let whisper_result: WhisperJsonOutput =
|
||||
serde_json::from_str(&json_str).context("Failed to parse whisper output")?;
|
||||
|
||||
std::fs::copy(&json_path, output_path)
|
||||
.context("Failed to copy whisper output to target path")?;
|
||||
|
||||
let mut result = convert_whisper_to_asr(whisper_result);
|
||||
result.compute_status();
|
||||
result.add_metadata("asr", "whisper_mlx", uuid);
|
||||
|
||||
// Save with metadata and precision optimization
|
||||
crate::core::json_formatter::write_file_pretty_rounded(&result, output_path, 2)
|
||||
.context("Failed to write ASR output")?;
|
||||
|
||||
tracing::info!(
|
||||
"[ASR] Whisper result: status={}, {} segments, language: {:?}",
|
||||
@@ -175,6 +208,11 @@ async fn process_asr_python(
|
||||
serde_json::from_str(&json_str).context("Failed to parse ASR output")?;
|
||||
|
||||
result.compute_status();
|
||||
result.add_metadata("asr", "python_whisper", uuid);
|
||||
|
||||
// Save with metadata and precision optimization
|
||||
crate::core::json_formatter::write_file_pretty_rounded(&result, output_path, 2)
|
||||
.context("Failed to write ASR output")?;
|
||||
|
||||
tracing::info!(
|
||||
"[ASR] Python result: status={}, {} segments, language: {:?}",
|
||||
@@ -223,6 +261,7 @@ fn convert_whisper_to_asr(whisper: WhisperJsonOutput) -> AsrResult {
|
||||
.collect();
|
||||
|
||||
AsrResult {
|
||||
metadata: None,
|
||||
status: None,
|
||||
language: whisper.language,
|
||||
language_probability: None,
|
||||
@@ -238,6 +277,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_asr_result_serialization() {
|
||||
let result = AsrResult {
|
||||
metadata: None,
|
||||
status: None,
|
||||
language: Some("en".to_string()),
|
||||
language_probability: Some(0.95),
|
||||
@@ -302,6 +342,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_asr_result_empty_segments() {
|
||||
let result = AsrResult {
|
||||
metadata: None,
|
||||
status: None,
|
||||
language: None,
|
||||
language_probability: None,
|
||||
|
||||
+210
-2
@@ -3,10 +3,13 @@ use serde::{Deserialize, Serialize};
|
||||
use tokio::process::Command;
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
use super::metadata::ProcessorMetadata;
|
||||
use super::AsrStatus;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct AsrxResult {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<ProcessorMetadata>,
|
||||
#[serde(default)]
|
||||
pub status: Option<AsrStatus>,
|
||||
pub language: Option<String>,
|
||||
@@ -23,8 +26,41 @@ impl AsrxResult {
|
||||
self.status = Some(AsrStatus::from_segments(self.segment_count));
|
||||
}
|
||||
|
||||
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
|
||||
use super::metadata::{ProcessorInfo, SourceInfo, Timestamps};
|
||||
use chrono::Utc;
|
||||
|
||||
let metadata = ProcessorMetadata {
|
||||
processor: ProcessorInfo {
|
||||
name: processor_name.to_string(),
|
||||
tool: tool.to_string(),
|
||||
version: super::metadata::PROCESSOR_VERSION.to_string(),
|
||||
config: None,
|
||||
},
|
||||
timestamps: Timestamps {
|
||||
created_at: Utc::now(),
|
||||
updated_at: None,
|
||||
processing_time_ms: None,
|
||||
},
|
||||
source: file_uuid.map(|uuid| SourceInfo {
|
||||
file_uuid: uuid.to_string(),
|
||||
video_info: None,
|
||||
}),
|
||||
custom: None,
|
||||
};
|
||||
|
||||
self.metadata = Some(metadata);
|
||||
}
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
|
||||
.context("Failed to write asrx.json")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn no_audio_track() -> Self {
|
||||
AsrxResult {
|
||||
metadata: None,
|
||||
status: Some(AsrStatus::NoAudioTrack),
|
||||
language: None,
|
||||
segments: vec![],
|
||||
@@ -35,6 +71,7 @@ impl AsrxResult {
|
||||
|
||||
pub fn silent_audio() -> Self {
|
||||
AsrxResult {
|
||||
metadata: None,
|
||||
status: Some(AsrStatus::SilentAudio),
|
||||
language: None,
|
||||
segments: vec![],
|
||||
@@ -71,8 +108,175 @@ pub async fn process_asrx(
|
||||
) -> Result<AsrxResult> {
|
||||
tracing::info!("[ASRX] Starting speaker diarization: {}", video_path);
|
||||
|
||||
// Use Python processor (Swift ASRX disabled - requires GUI authorization)
|
||||
tracing::info!("[ASRX] Using Python processor");
|
||||
use super::tool_selector::ToolSelector;
|
||||
let executor = PythonExecutor::new()?;
|
||||
let selector = ToolSelector::new("asrx");
|
||||
|
||||
if let Some(tool) = selector.select_tool(&executor).await? {
|
||||
tracing::info!(
|
||||
"[ASRX] Using {} from config (priority {})",
|
||||
tool.name,
|
||||
tool.parameters
|
||||
.get("priority")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(99)
|
||||
);
|
||||
|
||||
match tool.name.as_str() {
|
||||
"swift" => {
|
||||
let swift_path = tool.path;
|
||||
let args = if !tool.args.is_empty() {
|
||||
tool.args
|
||||
.iter()
|
||||
.map(|a| {
|
||||
a.replace("{video_path}", video_path)
|
||||
.replace("{output_path}", output_path)
|
||||
.replace("{file_uuid}", uuid.unwrap_or(""))
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
let mut args = vec![video_path.to_string(), output_path.to_string()];
|
||||
if let Some(u) = uuid {
|
||||
args.push("--uuid".to_string());
|
||||
args.push(u.to_string());
|
||||
}
|
||||
args
|
||||
};
|
||||
|
||||
let output = tokio::process::Command::new(&swift_path)
|
||||
.args(&args)
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute asrx_swift")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[ASRX] Swift processor failed: {}", stderr);
|
||||
anyhow::bail!("Swift ASRX failed: {}", stderr);
|
||||
}
|
||||
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read ASRX output")?;
|
||||
let mut result: AsrxResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse ASRX output")?;
|
||||
result.compute_status();
|
||||
result.add_metadata("asrx", "swift_asrx", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[ASRX] Swift result: status={}, {} segments",
|
||||
result
|
||||
.status
|
||||
.as_ref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default(),
|
||||
result.segment_count
|
||||
);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
"rust" => {
|
||||
let rust_path = tool.path;
|
||||
|
||||
let mut cmd = tokio::process::Command::new(&rust_path);
|
||||
cmd.arg(video_path).arg(output_path);
|
||||
|
||||
if let Some(u) = uuid {
|
||||
cmd.arg("--uuid").arg(u);
|
||||
cmd.arg("--file-uuid").arg(u);
|
||||
}
|
||||
|
||||
cmd.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.process_group(0);
|
||||
|
||||
let output = cmd.output().await.context("Failed to execute rust_asrx")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[ASRX] Rust processor failed: {}", stderr);
|
||||
anyhow::bail!("Rust ASRX failed: {}", stderr);
|
||||
}
|
||||
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read ASRX output")?;
|
||||
let mut result: AsrxResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse ASRX output")?;
|
||||
result.compute_status();
|
||||
result.add_metadata("asrx", "rust_asrx", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[ASRX] Rust result: status={}, {} segments",
|
||||
result
|
||||
.status
|
||||
.as_ref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default(),
|
||||
result.segment_count
|
||||
);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
"python" => {
|
||||
let script_path = tool.path;
|
||||
if !script_path.exists() {
|
||||
tracing::error!("[ASRX] Script not found: {:?}", script_path);
|
||||
anyhow::bail!("asrx_processor.py not found");
|
||||
}
|
||||
|
||||
let mut cmd = tokio::process::Command::new(executor.python_path());
|
||||
cmd.arg(&script_path).arg(video_path).arg(output_path);
|
||||
|
||||
if let Some(u) = uuid {
|
||||
cmd.arg("--uuid").arg(u);
|
||||
cmd.arg("--file-uuid").arg(u);
|
||||
}
|
||||
|
||||
cmd.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.process_group(0);
|
||||
|
||||
let output = cmd
|
||||
.output()
|
||||
.await
|
||||
.context("Failed to execute asrx_processor.py")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[ASRX] Python processor failed: {}", stderr);
|
||||
anyhow::bail!("Python ASRX failed: {}", stderr);
|
||||
}
|
||||
|
||||
let json_str =
|
||||
std::fs::read_to_string(output_path).context("Failed to read ASRX output")?;
|
||||
let mut result: AsrxResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse ASRX output")?;
|
||||
result.compute_status();
|
||||
result.add_metadata("asrx", "pyannote_diarization", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[ASRX] Python result: status={}, {} segments",
|
||||
result
|
||||
.status
|
||||
.as_ref()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default(),
|
||||
result.segment_count
|
||||
);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
_ => {
|
||||
tracing::warn!("[ASRX] Unknown tool from config: {}", tool.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::warn!("[ASRX] No tool available from config, falling back to Python");
|
||||
process_asrx_python(video_path, output_path, uuid).await
|
||||
}
|
||||
|
||||
@@ -183,6 +387,8 @@ async fn process_asrx_python(
|
||||
serde_json::from_str(&json_str).context("Failed to parse ASRX output")?;
|
||||
|
||||
result.compute_status();
|
||||
result.add_metadata("asrx", "pyannote_diarization", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
"[ASRX] Result: status={}, {} segments",
|
||||
@@ -204,6 +410,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_asrx_result_serialization() {
|
||||
let result = AsrxResult {
|
||||
metadata: None,
|
||||
status: None,
|
||||
language: Some("en".to_string()),
|
||||
segments: vec![AsrxSegment {
|
||||
@@ -247,6 +454,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_asrx_result_empty_segments() {
|
||||
let result = AsrxResult {
|
||||
metadata: None,
|
||||
status: None,
|
||||
language: None,
|
||||
segments: vec![],
|
||||
|
||||
@@ -4,11 +4,14 @@ use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
use super::metadata::ProcessorMetadata;
|
||||
|
||||
const CUT_TIMEOUT: Duration = Duration::from_secs(3600);
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct CutResult {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<ProcessorMetadata>,
|
||||
pub frame_count: u64,
|
||||
#[serde(serialize_with = "round_two")]
|
||||
pub fps: f64,
|
||||
@@ -35,14 +38,43 @@ where
|
||||
serializer.serialize_f64((v * 100.0).round() / 100.0)
|
||||
}
|
||||
|
||||
impl CutResult {
|
||||
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
|
||||
use chrono::Utc;
|
||||
use super::metadata::{ProcessorInfo, Timestamps, SourceInfo};
|
||||
|
||||
let metadata = ProcessorMetadata {
|
||||
processor: ProcessorInfo {
|
||||
name: processor_name.to_string(),
|
||||
tool: tool.to_string(),
|
||||
version: super::metadata::PROCESSOR_VERSION.to_string(),
|
||||
config: None,
|
||||
},
|
||||
timestamps: Timestamps {
|
||||
created_at: Utc::now(),
|
||||
updated_at: None,
|
||||
processing_time_ms: None,
|
||||
},
|
||||
source: file_uuid.map(|uuid| SourceInfo {
|
||||
file_uuid: uuid.to_string(),
|
||||
video_info: None,
|
||||
}),
|
||||
custom: None,
|
||||
};
|
||||
|
||||
self.metadata = Some(metadata);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn process_cut(
|
||||
video_path: &str,
|
||||
output_path: &str,
|
||||
uuid: Option<&str>,
|
||||
) -> Result<CutResult> {
|
||||
// Try native ffmpeg-based scene detection first
|
||||
let result = try_native_cut(video_path);
|
||||
if let Ok(r) = result {
|
||||
let mut result = try_native_cut(video_path);
|
||||
if let Ok(mut r) = result {
|
||||
r.add_metadata("cut", "ffmpeg_native", uuid);
|
||||
let json = serde_json::to_string_pretty(&r)?;
|
||||
std::fs::write(output_path, &json)
|
||||
.with_context(|| format!("Failed to write {:?}", output_path))?;
|
||||
@@ -55,11 +87,13 @@ pub async fn process_cut(
|
||||
let script_path = executor.script_path("cut_processor.py");
|
||||
|
||||
if !script_path.exists() {
|
||||
let empty_result = CutResult {
|
||||
let mut empty_result = CutResult {
|
||||
metadata: None,
|
||||
frame_count: 0,
|
||||
fps: 0.0,
|
||||
scenes: vec![],
|
||||
};
|
||||
empty_result.add_metadata("cut", "none", uuid);
|
||||
let json = serde_json::to_string_pretty(&empty_result)?;
|
||||
std::fs::write(output_path, &json)
|
||||
.with_context(|| format!("Failed to write {:?}", output_path))?;
|
||||
@@ -78,8 +112,10 @@ pub async fn process_cut(
|
||||
.with_context(|| format!("Failed to run {:?}", script_path))?;
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path).context("Failed to read CUT output")?;
|
||||
let result: CutResult =
|
||||
let mut result: CutResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse CUT output")?;
|
||||
|
||||
result.add_metadata("cut", "python_scenedetect", uuid);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
@@ -216,6 +252,7 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
|
||||
}
|
||||
|
||||
Ok(CutResult {
|
||||
metadata: None,
|
||||
frame_count: total_frames,
|
||||
fps,
|
||||
scenes,
|
||||
@@ -265,6 +302,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_cut_result_serialization() {
|
||||
let result = CutResult {
|
||||
metadata: None,
|
||||
frame_count: 100,
|
||||
fps: 30.0,
|
||||
scenes: vec![CutScene {
|
||||
@@ -305,6 +343,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_empty_scenes() {
|
||||
let result = CutResult {
|
||||
metadata: None,
|
||||
frame_count: 0,
|
||||
fps: 0.0,
|
||||
scenes: vec![],
|
||||
|
||||
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
use super::metadata::ProcessorMetadata;
|
||||
use super::FaceStatus;
|
||||
|
||||
const FACE_TIMEOUT: Duration = Duration::from_secs(7200);
|
||||
@@ -38,6 +39,8 @@ pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct FaceResult {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<ProcessorMetadata>,
|
||||
#[serde(default)]
|
||||
pub status: Option<FaceStatus>,
|
||||
pub frame_count: u64,
|
||||
@@ -45,8 +48,6 @@ pub struct FaceResult {
|
||||
pub frames: Vec<FaceFrame>,
|
||||
#[serde(default)]
|
||||
pub total_faces: usize,
|
||||
#[serde(default)]
|
||||
pub metadata: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl FaceResult {
|
||||
@@ -63,20 +64,48 @@ impl FaceResult {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
|
||||
use chrono::Utc;
|
||||
use super::metadata::{ProcessorInfo, Timestamps, SourceInfo, VideoInfo};
|
||||
|
||||
let video_info = None;
|
||||
|
||||
let metadata = ProcessorMetadata {
|
||||
processor: ProcessorInfo {
|
||||
name: processor_name.to_string(),
|
||||
tool: tool.to_string(),
|
||||
version: super::metadata::PROCESSOR_VERSION.to_string(),
|
||||
config: None,
|
||||
},
|
||||
timestamps: Timestamps {
|
||||
created_at: Utc::now(),
|
||||
updated_at: None,
|
||||
processing_time_ms: None,
|
||||
},
|
||||
source: file_uuid.map(|uuid| SourceInfo {
|
||||
file_uuid: uuid.to_string(),
|
||||
video_info,
|
||||
}),
|
||||
custom: None,
|
||||
};
|
||||
|
||||
self.metadata = Some(metadata);
|
||||
}
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
let json = serde_json::to_string_pretty(self).context("Failed to serialize FaceResult")?;
|
||||
std::fs::write(path, json).context("Failed to write face.json")?;
|
||||
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
|
||||
.context("Failed to write face.json")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn no_faces(frame_count: u64, fps: f64) -> Self {
|
||||
FaceResult {
|
||||
metadata: None,
|
||||
status: Some(FaceStatus::NoFaces),
|
||||
frame_count,
|
||||
fps,
|
||||
frames: vec![],
|
||||
total_faces: 0,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,6 +191,7 @@ pub async fn process_face(
|
||||
serde_json::from_str(&json_str).context("Failed to parse existing FACE output")?;
|
||||
|
||||
result.compute_status();
|
||||
result.add_metadata("face", "swift_face", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!(
|
||||
@@ -288,6 +318,7 @@ pub async fn process_face(
|
||||
let mut result: FaceResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
||||
result.compute_status();
|
||||
result.add_metadata("face", "swift_face", uuid);
|
||||
|
||||
// Store embeddings to Qdrant and remove from JSON
|
||||
if let Some(file_uuid) = uuid {
|
||||
@@ -357,6 +388,7 @@ pub async fn process_face(
|
||||
serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
||||
|
||||
result.compute_status();
|
||||
result.add_metadata("face", "python_face_processor", uuid);
|
||||
|
||||
// Execute face tracking
|
||||
tracing::info!("[FACE] Starting face tracking");
|
||||
@@ -478,6 +510,7 @@ async fn run_face_with_config(
|
||||
let mut result: FaceResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse Swift FACE output")?;
|
||||
result.compute_status();
|
||||
result.add_metadata("face", "swift_face", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
if let Some(uid) = uuid {
|
||||
@@ -520,6 +553,7 @@ async fn run_face_with_config(
|
||||
let mut result: FaceResult = serde_json::from_str(&json_str)
|
||||
.context("Failed to parse Python FACE output")?;
|
||||
result.compute_status();
|
||||
result.add_metadata("face", "python_face_processor", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
if let Some(uid) = uuid {
|
||||
@@ -549,11 +583,11 @@ mod tests {
|
||||
#[test]
|
||||
fn test_face_result_serialization() {
|
||||
let result = FaceResult {
|
||||
metadata: None,
|
||||
status: None,
|
||||
frame_count: 100,
|
||||
fps: 30.0,
|
||||
total_faces: 1,
|
||||
metadata: None,
|
||||
frames: vec![FaceFrame {
|
||||
frame: 0,
|
||||
timestamp: 0.0,
|
||||
|
||||
@@ -427,13 +427,37 @@ pub fn track_faces(
|
||||
.collect();
|
||||
|
||||
// Store traces in metadata
|
||||
face_data.metadata = Some(serde_json::json!({
|
||||
let trace_custom = serde_json::json!({
|
||||
"traces": trace_stats,
|
||||
"trace_stats": {
|
||||
"total_traces": next_trace_id,
|
||||
"active_traces": trace_stats.len(),
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
if let Some(ref mut metadata) = face_data.metadata {
|
||||
metadata.custom = Some(trace_custom);
|
||||
} else {
|
||||
// Create new metadata with trace info
|
||||
use super::metadata::{ProcessorMetadata, ProcessorInfo, Timestamps};
|
||||
use chrono::Utc;
|
||||
|
||||
face_data.metadata = Some(ProcessorMetadata {
|
||||
processor: ProcessorInfo {
|
||||
name: "face_tracker".to_string(),
|
||||
tool: "rust_face_tracker".to_string(),
|
||||
version: super::metadata::PROCESSOR_VERSION.to_string(),
|
||||
config: None,
|
||||
},
|
||||
timestamps: Timestamps {
|
||||
created_at: Utc::now(),
|
||||
updated_at: None,
|
||||
processing_time_ms: None,
|
||||
},
|
||||
source: None,
|
||||
custom: Some(trace_custom),
|
||||
});
|
||||
}
|
||||
|
||||
tracing::info!("✅ Tracking complete: {} traces", trace_stats.len());
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const PROCESSOR_VERSION: &str = "1.0.0";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ProcessorMetadata {
|
||||
pub processor: ProcessorInfo,
|
||||
pub timestamps: Timestamps,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<SourceInfo>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub custom: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ProcessorInfo {
|
||||
pub name: String,
|
||||
pub tool: String,
|
||||
pub version: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub config: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Timestamps {
|
||||
pub created_at: DateTime<Utc>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub processing_time_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SourceInfo {
|
||||
pub file_uuid: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub video_info: Option<VideoInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VideoInfo {
|
||||
pub duration_sec: f64,
|
||||
pub fps: f64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub total_frames: u32,
|
||||
}
|
||||
|
||||
impl ProcessorMetadata {
|
||||
pub fn new(name: String, tool: String) -> Self {
|
||||
Self {
|
||||
processor: ProcessorInfo {
|
||||
name,
|
||||
tool,
|
||||
version: PROCESSOR_VERSION.to_string(),
|
||||
config: None,
|
||||
},
|
||||
timestamps: Timestamps {
|
||||
created_at: Utc::now(),
|
||||
updated_at: None,
|
||||
processing_time_ms: None,
|
||||
},
|
||||
source: None,
|
||||
custom: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_config(mut self, config: serde_json::Value) -> Self {
|
||||
self.processor.config = Some(config);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_source(mut self, file_uuid: String, video_info: Option<VideoInfo>) -> Self {
|
||||
self.source = Some(SourceInfo {
|
||||
file_uuid,
|
||||
video_info,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_custom(mut self, custom: serde_json::Value) -> Self {
|
||||
self.custom = Some(custom);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_processing_time(mut self, start: DateTime<Utc>) -> Self {
|
||||
let end = Utc::now();
|
||||
self.timestamps.updated_at = Some(end);
|
||||
self.timestamps.processing_time_ms = Some((end - start).num_milliseconds());
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod face_recognition;
|
||||
pub mod face_tracker;
|
||||
pub mod hand;
|
||||
pub mod heuristic_scene;
|
||||
pub mod metadata;
|
||||
pub mod ocr;
|
||||
pub mod pose;
|
||||
pub mod scene_classification;
|
||||
@@ -195,5 +196,8 @@ pub use tkg::{
|
||||
build_tkg, query_auto_representative_frame, FrameTraceInfo, MainIdentityInfo,
|
||||
RepresentativeFrameResult, TkgResult,
|
||||
};
|
||||
pub use metadata::{
|
||||
ProcessorMetadata, ProcessorInfo, Timestamps, SourceInfo, VideoInfo, PROCESSOR_VERSION,
|
||||
};
|
||||
pub mod processor_config_v3;
|
||||
pub mod tool_selector;
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
use super::metadata::ProcessorMetadata;
|
||||
|
||||
const OCR_TIMEOUT: Duration = Duration::from_secs(7200);
|
||||
|
||||
@@ -17,11 +18,47 @@ const TEXT_SIMILARITY_THRESHOLD: f64 = 0.5;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct OcrResult {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<ProcessorMetadata>,
|
||||
pub frame_count: u64,
|
||||
pub fps: f64,
|
||||
pub frames: Vec<OcrFrame>,
|
||||
}
|
||||
|
||||
impl OcrResult {
|
||||
pub fn add_metadata(&mut self, processor_name: &str, tool: &str, file_uuid: Option<&str>) {
|
||||
use super::metadata::{ProcessorInfo, SourceInfo, Timestamps};
|
||||
use chrono::Utc;
|
||||
|
||||
let metadata = ProcessorMetadata {
|
||||
processor: ProcessorInfo {
|
||||
name: processor_name.to_string(),
|
||||
tool: tool.to_string(),
|
||||
version: super::metadata::PROCESSOR_VERSION.to_string(),
|
||||
config: None,
|
||||
},
|
||||
timestamps: Timestamps {
|
||||
created_at: Utc::now(),
|
||||
updated_at: None,
|
||||
processing_time_ms: None,
|
||||
},
|
||||
source: file_uuid.map(|uuid| SourceInfo {
|
||||
file_uuid: uuid.to_string(),
|
||||
video_info: None,
|
||||
}),
|
||||
custom: None,
|
||||
};
|
||||
|
||||
self.metadata = Some(metadata);
|
||||
}
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
|
||||
.context("Failed to write ocr.json")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct OcrFrame {
|
||||
pub frame: u64,
|
||||
@@ -272,6 +309,7 @@ pub async fn process_ocr(
|
||||
if !script_path.exists() {
|
||||
tracing::warn!("[OCR] Script not found, returning empty result");
|
||||
return Ok(OcrResult {
|
||||
metadata: None,
|
||||
frame_count: 0,
|
||||
fps: 0.0,
|
||||
frames: vec![],
|
||||
@@ -293,9 +331,12 @@ pub async fn process_ocr(
|
||||
|
||||
let json_str = std::fs::read_to_string(output_path).context("Failed to read OCR output")?;
|
||||
|
||||
let result: OcrResult =
|
||||
let mut result: OcrResult =
|
||||
serde_json::from_str(&json_str).context("Failed to parse OCR output")?;
|
||||
|
||||
result.add_metadata("ocr", "swift_ocr", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
|
||||
tracing::info!("[OCR] Result: {} frames", result.frames.len());
|
||||
|
||||
Ok(result)
|
||||
@@ -308,6 +349,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_ocr_result_serialization() {
|
||||
let result = OcrResult {
|
||||
metadata: None,
|
||||
frame_count: 100,
|
||||
fps: 30.0,
|
||||
frames: vec![OcrFrame {
|
||||
@@ -354,6 +396,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_ocr_result_empty_frames() {
|
||||
let result = OcrResult {
|
||||
metadata: None,
|
||||
frame_count: 0,
|
||||
fps: 0.0,
|
||||
frames: vec![],
|
||||
|
||||
Reference in New Issue
Block a user