release: v1.3.1 - Pipeline Queue Integration, OCR Fix, Worker Compatibility

Major Changes:
- Pipeline Queue integration completed (internal.file + pipeline.commands)
- Fixed old job_worker database compatibility with new command_queue table
- Compiled Swift OCR binary (was missing, causing empty OCR results)
- Added deep scan functionality through re-scan API

Fixes:
- Changed CommandJob.id from i32 to i64 for database compatibility
- Added UUID generation in create_command (message_id field)
- Fixed claim_pending_commands to query queue_name = 'internal.file'
- Fixed field mappings: command_id → message_id, job_type → command_type
- Added support for 'processing' status in CommandJobStatus

Queue System:
- internal.file queue: for register/unregister/re-scan commands (job_worker)
- pipeline.commands queue: for vectorize/store_asrx/etc commands (pipeline_worker)

Documentation:
- Added comprehensive queue system documentation
- Created M4 workspace status reports
- Updated AGENTS.md with queue system details
This commit is contained in:
Accusys
2026-10-12 10:00:51 +08:00
parent 0a18e70639
commit 63fbbe1225
418 changed files with 44084 additions and 4280 deletions
+26 -4
View File
@@ -19,6 +19,10 @@ struct Cli {
/// API Base URL (default: http://localhost:3002)
#[arg(long, default_value = "http://localhost:3002")]
api_url: String,
/// API key (defaults to $MOMENTRY_API_KEY)
#[arg(long)]
api_key: Option<String>,
}
#[derive(Subcommand)]
@@ -68,7 +72,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
async fn run_command(cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
let api_key = "muser_test_001";
let api_key = cli
.api_key
.clone()
.or_else(|| std::env::var("MOMENTRY_API_KEY").ok())
.unwrap_or_default();
if api_key.is_empty() {
return Err("missing API key: pass --api-key or set MOMENTRY_API_KEY".into());
}
let client = reqwest::Client::new();
let auth_header = reqwest::header::HeaderMap::from_iter([
("X-API-Key".parse().unwrap(), api_key.parse().unwrap()),
@@ -105,14 +116,25 @@ async fn run_command(cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
let res = client
.post(&format!("{}/api/v1/unregister", cli.api_url))
.headers(auth_header.clone())
.json(&serde_json::json!({ "uuid": file_uuid }))
.json(&serde_json::json!({ "file_uuid": file_uuid }))
.send()
.await?;
if res.status().is_success() {
println!("✅ [CLI] 取消註冊成功");
let body = res.text().await.unwrap_or_default();
match serde_json::from_str::<serde_json::Value>(&body) {
Ok(json) => println!(
"✅ [CLI] 取消註冊成功: {}",
json.get("message")
.unwrap_or(&serde_json::Value::String("-".into()))
),
Err(_) => println!("✅ [CLI] 取消註冊成功: {}", body),
}
} else {
println!("❌ [CLI] 取消註冊失敗: {}", res.status());
let status = res.status();
let body = res.text().await.unwrap_or_default();
eprintln!("❌ [CLI] 取消註冊失敗: {} - {}", status, body);
return Err(format!("unregister failed: {}", status).into());
}
}
Commands::Probe { file_uuid } => {
+55
View File
@@ -0,0 +1,55 @@
// Pipeline Worker - 独立进程,处理 command_queue 中的 Pipeline 命令
use anyhow::{Context, Result};
use momentry_core::core::command::pipeline::PipelineWorker;
use momentry_core::core::config;
use sqlx::PgPool;
use std::time::Duration;
use tracing::{error, info};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() -> Result<()> {
// 初始化日志
tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.with_target(false)
.with_thread_ids(false)
)
.init();
info!("Pipeline Worker starting...");
// 加载环境变量
dotenv::dotenv().ok();
// 连接数据库
let database_url = config::DATABASE_URL.clone();
let db = PgPool::connect(&database_url)
.await
.context("Failed to connect to database")?;
info!("Connected to database");
// 创建 Pipeline Worker
let worker = PipelineWorker::new(db);
// 启动 worker
info!("Pipeline Worker started, polling for commands...");
// 主循环
loop {
match worker.start().await {
Ok(_) => {
// start() 会无限循环,除非出错
info!("Worker loop completed unexpectedly");
}
Err(e) => {
error!("Worker error: {}", e);
error!("Restarting in 5 seconds...");
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
use sqlx::postgres::PgPoolOptions;
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 加载 .env
dotenv::dotenv().ok();
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
println!("Connecting to database...");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await?;
println!("Reading migration file...");
let sql = include_str!("../migrations/20261011_vlm_queue.sql");
println!("Running migration...");
// 分割 SQL 语句并逐个执行
for statement in sql.split(';') {
let statement = statement.trim();
if !statement.is_empty() && !statement.starts_with("--") {
match sqlx::query(statement).execute(&pool).await {
Ok(_) => {}
Err(e) => {
// 忽略已存在的错误
if !e.to_string().contains("already exists") {
eprintln!("Error executing statement: {}", e);
}
}
}
}
}
println!("✅ Migration completed successfully!");
// 验证表创建
let table_exists: bool = sqlx::query_scalar(
r#"
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_name = 'vlm_requests'
)
"#,
)
.fetch_one(&pool)
.await?;
if table_exists {
println!("✅ Table vlm_requests created");
} else {
println!("❌ Table vlm_requests not found");
}
Ok(())
}
+104 -87
View File
@@ -1,7 +1,7 @@
use anyhow::{Context, Result};
use clap::Parser;
use momentry_core::core::db::postgres_db::PostgresDb;
use momentry_core::core::config;
use momentry_core::core::db::postgres_db::PostgresDb;
use momentry_core::core::storage::uuid;
use momentry_core::Database;
use std::path::Path;
@@ -12,15 +12,15 @@ use std::path::Path;
struct Args {
/// Video file path
file: String,
/// Force register (unregister if exists)
#[arg(short = 'F', long, default_value = "false")]
force: bool,
/// Trigger auto-pipeline after registration
#[arg(short, long, default_value = "false")]
auto_pipeline: bool,
/// Verbose output
#[arg(short, long, default_value = "false")]
verbose: bool,
@@ -29,34 +29,35 @@ struct Args {
#[tokio::main]
async fn main() -> Result<()> {
let args = Args::parse();
println!("[REGISTER] Starting for: {}", args.file);
let file_path = Path::new(&args.file);
if !file_path.exists() {
anyhow::bail!("File not found: {}", args.file);
}
if args.verbose {
println!("[REGISTER] Force: {}", args.force);
println!("[REGISTER] Auto pipeline: {}", args.auto_pipeline);
}
let db = PostgresDb::init().await
let db = PostgresDb::init()
.await
.context("Failed to connect to database")?;
let result = register_file(&db, &args.file, args.force, args.verbose).await?;
println!("[REGISTER] Done");
println!("[REGISTER] File UUID: {}", result.file_uuid);
println!("[REGISTER] Duration: {:.2}s", result.duration);
if args.auto_pipeline {
println!("[REGISTER] Auto-pipeline not implemented yet");
println!("[REGISTER] Use: curl -X POST 'http://localhost:3002/api/v1/process?api_key=...&file_uuid={}'", result.file_uuid);
}
Ok(())
}
@@ -72,25 +73,25 @@ async fn register_file(
verbose: bool,
) -> Result<RegisterResult> {
use momentry_core::core::db::schema;
let path = Path::new(file_path);
let canonical_path = path
.canonicalize()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| file_path.to_string());
let file_name = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
if verbose {
println!("[REGISTER] Canonical path: {}", canonical_path);
println!("[REGISTER] File name: {}", file_name);
}
let output_dir = config::OUTPUT_DIR.to_string();
let birthday = std::fs::metadata(&path)
.ok()
.and_then(|m| m.modified().ok())
@@ -104,28 +105,23 @@ async fn register_file(
.unwrap_or_else(|| chrono::Utc::now().to_rfc3339())
})
.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
let mac_address = uuid::get_mac_address();
let file_uuid = uuid::compute_birth_uuid(
&mac_address,
&birthday,
&canonical_path,
&file_name,
);
let file_uuid = uuid::compute_birth_uuid(&mac_address, &birthday, &canonical_path, &file_name);
if verbose {
println!("[REGISTER] Birthday: {}", birthday);
println!("[REGISTER] File UUID: {}", file_uuid);
}
let content_hash = sha256_file(&path)?;
if verbose {
println!("[REGISTER] Content hash: {}", content_hash);
}
let videos_table = schema::table_name("videos");
let existing: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_uuid FROM {} WHERE file_uuid = $1",
videos_table
@@ -134,41 +130,44 @@ async fn register_file(
.fetch_optional(db.pool())
.await
.context("Failed to check existing file")?;
if existing.is_some() && !force {
println!("[REGISTER] File already registered: {}", file_uuid);
println!("[REGISTER] Use --force to overwrite");
return Ok(RegisterResult {
file_uuid,
duration: 0.0,
});
}
if existing.is_some() && force {
if verbose {
println!("[REGISTER] Force mode: unregistering existing file");
}
println!("[REGISTER] Unregistering existing file...");
unregister_by_uuid(&db, &file_uuid, verbose).await?;
}
println!("[REGISTER] Extracting metadata...");
let metadata = extract_metadata(&canonical_path)?;
if verbose {
println!("[REGISTER] Duration: {:.2}s", metadata.duration);
println!("[REGISTER] Resolution: {}x{}", metadata.width, metadata.height);
println!(
"[REGISTER] Resolution: {}x{}",
metadata.width, metadata.height
);
println!("[REGISTER] FPS: {:.2}", metadata.fps);
println!("[REGISTER] Total frames: {}", metadata.total_frames);
}
let registration_time = chrono::Utc::now();
println!("[REGISTER] Inserting into database...");
sqlx::query(&format!(
"INSERT INTO {} (
file_uuid, file_name, file_path,
@@ -190,9 +189,9 @@ async fn register_file(
.execute(db.pool())
.await
.context("Failed to insert into videos table")?;
println!("[REGISTER] Registered: {}", file_uuid);
Ok(RegisterResult {
file_uuid,
duration: metadata.duration,
@@ -209,57 +208,73 @@ struct VideoMetadata {
fn extract_metadata(file_path: &str) -> Result<VideoMetadata> {
use std::process::Command;
let output = Command::new("ffprobe")
.args([
"-v", "error",
"-select_streams", "v:0",
"-show_entries", "stream=width,height,r_frame_rate,duration",
"-show_entries", "format=duration",
"-of", "json",
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height,r_frame_rate,duration",
"-show_entries",
"format=duration",
"-of",
"json",
file_path,
])
.output()
.context("Failed to run ffprobe")?;
if !output.status.success() {
anyhow::bail!("ffprobe failed: {}", String::from_utf8_lossy(&output.stderr));
anyhow::bail!(
"ffprobe failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let json: serde_json::Value = serde_json::from_slice(&output.stdout)
.context("Failed to parse ffprobe output")?;
let json: serde_json::Value =
serde_json::from_slice(&output.stdout).context("Failed to parse ffprobe output")?;
let stream = json["streams"].get(0).context("No video stream found")?;
let width = stream["width"].as_u64().unwrap_or(0) as u32;
let height = stream["height"].as_u64().unwrap_or(0) as u32;
let fps_str = stream["r_frame_rate"].as_str().unwrap_or("0/1");
let fps = if fps_str.contains('/') {
let parts: Vec<&str> = fps_str.split('/').collect();
if parts.len() == 2 {
let num: f64 = parts[0].parse().unwrap_or(0.0);
let den: f64 = parts[1].parse().unwrap_or(1.0);
if den > 0.0 { num / den } else { 0.0 }
if den > 0.0 {
num / den
} else {
0.0
}
} else {
0.0
}
} else {
fps_str.parse().unwrap_or(0.0)
};
let duration = stream["duration"]
.as_str()
.and_then(|s| s.parse().ok())
.or_else(|| json["format"]["duration"].as_str().and_then(|s| s.parse().ok()))
.or_else(|| {
json["format"]["duration"]
.as_str()
.and_then(|s| s.parse().ok())
})
.unwrap_or(0.0);
let total_frames = if fps > 0.0 {
(duration * fps) as u64
} else {
0
};
Ok(VideoMetadata {
duration,
width,
@@ -270,15 +285,14 @@ fn extract_metadata(file_path: &str) -> Result<VideoMetadata> {
}
fn sha256_file(path: &Path) -> Result<String> {
use sha2::{Sha256, Digest};
use sha2::{Digest, Sha256};
use std::io::Read;
let mut file = std::fs::File::open(path)
.context("Failed to open file for hashing")?;
let mut file = std::fs::File::open(path).context("Failed to open file for hashing")?;
let mut hasher = Sha256::new();
let mut buffer = [0u8; 8192];
loop {
let bytes_read = file.read(&mut buffer)?;
if bytes_read == 0 {
@@ -286,14 +300,14 @@ fn sha256_file(path: &Path) -> Result<String> {
}
hasher.update(&buffer[..bytes_read]);
}
let hash = hasher.finalize();
Ok(hex::encode(hash))
}
async fn unregister_by_uuid(db: &PostgresDb, uuid: &str, verbose: bool) -> Result<()> {
use momentry_core::core::db::schema;
let tables = [
("processor_results", "file_uuid = $1"),
("chunk", "file_uuid = $1"),
@@ -301,22 +315,22 @@ async fn unregister_by_uuid(db: &PostgresDb, uuid: &str, verbose: bool) -> Resul
("pre_chunks", "file_uuid = $1"),
("tkg_nodes", "file_uuid = $1"),
("cuts", "file_uuid = $1"),
("frames", "file_id = (SELECT id FROM videos WHERE file_uuid = $1)"),
(
"frames",
"file_id = (SELECT id FROM videos WHERE file_uuid = $1)",
),
("file_identities", "file_uuid = $1"),
("speaker_detections", "file_uuid = $1"),
("face_clusters", "file_uuid = $1"),
("characters", "file_uuid = $1"),
];
for (table, where_clause) in tables.iter() {
let table_name = schema::table_name(table);
let query = format!("DELETE FROM {} WHERE {}", table_name, where_clause);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await;
let result = sqlx::query(&query).bind(uuid).execute(db.pool()).await;
if verbose {
if let Ok(r) = result {
let deleted = r.rows_affected();
@@ -326,13 +340,16 @@ async fn unregister_by_uuid(db: &PostgresDb, uuid: &str, verbose: bool) -> Resul
}
}
}
let videos_table = schema::table_name("videos");
sqlx::query(&format!("DELETE FROM {} WHERE file_uuid = $1", videos_table))
.bind(uuid)
.execute(db.pool())
.await
.context("Failed to delete from videos table")?;
sqlx::query(&format!(
"DELETE FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(uuid)
.execute(db.pool())
.await
.context("Failed to delete from videos table")?;
Ok(())
}
}
+137 -78
View File
@@ -1,12 +1,10 @@
use anyhow::{Context, Result};
use clap::Parser;
use momentry_core::core::db::{
postgres_db::PostgresDb,
qdrant_db::QdrantDb,
redis_client::RedisClient,
qdrant_workspace::QdrantWorkspace
};
use momentry_core::core::config;
use momentry_core::core::db::{
postgres_db::PostgresDb, qdrant_db::QdrantDb, qdrant_workspace::QdrantWorkspace,
redis_client::RedisClient,
};
use momentry_core::Database;
#[derive(Parser, Debug)]
@@ -15,10 +13,10 @@ use momentry_core::Database;
struct Args {
#[arg(short, long)]
uuid: String,
#[arg(short, long, default_value = "false")]
dry_run: bool,
#[arg(short, long, default_value = "false")]
verbose: bool,
}
@@ -26,51 +24,53 @@ struct Args {
#[tokio::main]
async fn main() -> Result<()> {
let args = Args::parse();
println!("[UNREGISTER] Starting for file_uuid: {}", args.uuid);
if args.dry_run {
println!("[UNREGISTER] DRY-RUN MODE - No actual deletion");
}
let schema = std::env::var("DATABASE_SCHEMA")
.unwrap_or_else(|_| "public".to_string());
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string());
if args.verbose {
println!("[UNREGISTER] Schema: {}", schema);
println!("[UNREGISTER] Output dir: {}", *config::OUTPUT_DIR);
}
if !args.dry_run {
let db = PostgresDb::init().await
let db = PostgresDb::init()
.await
.context("Failed to connect to database")?;
unregister_database(&db, &args.uuid, args.verbose).await?;
unregister_output_files(&args.uuid, args.verbose)?;
unregister_thumbnails(&args.uuid, args.verbose)?;
unregister_qdrant(&args.uuid, &schema, args.verbose).await?;
unregister_redis(&args.uuid, args.verbose).await?;
} else {
println!("[UNREGISTER] Would delete from database");
println!("[UNREGISTER] Would delete output files");
println!("[UNREGISTER] Would delete thumbnails");
println!("[UNREGISTER] Would delete Qdrant vectors");
println!("[UNREGISTER] Would delete Redis keys");
}
println!("[UNREGISTER] Done");
Ok(())
}
async fn unregister_database(db: &PostgresDb, uuid: &str, verbose: bool) -> Result<()> {
use momentry_core::core::db::schema;
println!("[UNREGISTER] Deleting database records...");
let mut deleted_total = 0i64;
let tables = [
("processor_results", "file_uuid = $1", "processor_results"),
("chunk", "file_uuid = $1", "chunks"),
@@ -84,88 +84,94 @@ async fn unregister_database(db: &PostgresDb, uuid: &str, verbose: bool) -> Resu
("file_identities", "file_uuid = $1", "file identities"),
("speaker_detections", "file_uuid = $1", "speaker detections"),
("face_clusters", "file_uuid = $1", "face clusters"),
("face_recognition_results", "file_uuid = $1", "face recognition results"),
(
"face_recognition_results",
"file_uuid = $1",
"face recognition results",
),
("characters", "file_uuid = $1", "characters"),
("chunks_rule1", "uuid = $1", "chunks_rule1"),
("processor_alerts", "file_uuid = $1", "processor alerts"),
("processor_versions", "file_uuid = $1", "processor versions"),
("trace_profiles", "file_uuid = $1", "trace profiles"),
];
for (table, where_clause, label) in tables.iter() {
let table_name = schema::table_name(table);
let query = format!("DELETE FROM {} WHERE {}", table_name, where_clause);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context(format!("Failed to delete from {}", table_name))?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} {}", deleted, label);
}
}
let frames_table = schema::table_name("frames");
let videos_table = schema::table_name("videos");
let query = format!(
"DELETE FROM {} WHERE file_id = (SELECT id FROM {} WHERE file_uuid = $1)",
frames_table, videos_table
);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context("Failed to delete frames")?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} frames", deleted);
}
let query = format!("DELETE FROM {} WHERE file_uuid = $1", videos_table);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context("Failed to delete from videos table")?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} videos", deleted);
}
println!("[UNREGISTER] Total deleted: {} database records", deleted_total);
println!(
"[UNREGISTER] Total deleted: {} database records",
deleted_total
);
Ok(())
}
fn unregister_output_files(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting output files...");
let mut deleted_count = 0u64;
let output_dir = config::OUTPUT_DIR.to_string();
if let Ok(entries) = std::fs::read_dir(&output_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let is_uuid_file = name.starts_with(uuid) && !path.is_dir();
let is_pipeline_log = name.starts_with("pipeline_")
&& name.contains(uuid)
&& name.ends_with(".log");
let is_pipeline_log =
name.starts_with("pipeline_") && name.contains(uuid) && name.ends_with(".log");
let is_scenes_json = name == &format!("{}.scenes.json", uuid);
if is_uuid_file || is_pipeline_log || is_scenes_json {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
@@ -177,7 +183,7 @@ fn unregister_output_files(uuid: &str, verbose: bool) -> Result<()> {
}
}
}
let uuid_dir = std::path::Path::new(&output_dir).join(uuid);
if uuid_dir.is_dir() {
if std::fs::remove_dir_all(&uuid_dir).is_ok() {
@@ -187,7 +193,7 @@ fn unregister_output_files(uuid: &str, verbose: bool) -> Result<()> {
}
}
}
let workspace_sqlite = format!("{}.workspace.sqlite", uuid);
let sqlite_path = std::path::Path::new(&output_dir).join(&workspace_sqlite);
if sqlite_path.exists() && std::fs::remove_file(&sqlite_path).is_ok() {
@@ -196,25 +202,25 @@ fn unregister_output_files(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleted: {}", workspace_sqlite);
}
}
println!("[UNREGISTER] Deleted {} output files", deleted_count);
Ok(())
}
async fn unregister_qdrant(uuid: &str, schema: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting Qdrant vectors...");
let qdrant = QdrantDb::new();
let speaker_collection = if schema == "public" {
"momentry_public_speaker".to_string()
} else {
format!("momentry_{}_speaker", schema)
};
let face_embeddings_collection = format!("{}_face_embeddings", schema);
let collections: Vec<String> = vec![
qdrant.collection_name.clone(),
"_faces".to_string(),
@@ -224,9 +230,9 @@ async fn unregister_qdrant(uuid: &str, schema: &str, verbose: bool) -> Result<()
face_embeddings_collection,
speaker_collection,
];
let mut success_count = 0;
for collection in &collections {
match QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
@@ -245,12 +251,15 @@ async fn unregister_qdrant(uuid: &str, schema: &str, verbose: bool) -> Result<()
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to delete from {}: {:?}", collection, e);
eprintln!(
"[UNREGISTER] Warning: Failed to delete from {}: {:?}",
collection, e
);
}
}
}
}
let workspace = QdrantWorkspace::new();
match workspace.delete_by_file_uuid(uuid).await {
Ok(_) => {
@@ -261,40 +270,90 @@ async fn unregister_qdrant(uuid: &str, schema: &str, verbose: bool) -> Result<()
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to delete from workspace: {:?}", e);
eprintln!(
"[UNREGISTER] Warning: Failed to delete from workspace: {:?}",
e
);
}
}
}
println!("[UNREGISTER] Deleted from {} Qdrant collections", success_count);
println!(
"[UNREGISTER] Deleted from {} Qdrant collections",
success_count
);
Ok(())
}
async fn unregister_redis(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting Redis keys...");
match RedisClient::new() {
Ok(redis) => {
match redis.delete_worker_job(uuid).await {
Ok(_) => {
if verbose {
println!("[UNREGISTER] Deleted Redis keys");
}
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to delete Redis keys: {:?}", e);
}
Ok(redis) => match redis.delete_worker_job(uuid).await {
Ok(_) => {
if verbose {
println!("[UNREGISTER] Deleted Redis keys");
}
}
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to delete Redis keys: {:?}", e);
}
}
},
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to connect to Redis: {:?}", e);
}
}
}
Ok(())
}
}
// 刪除縮圖函數
fn unregister_thumbnails(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting thumbnails...");
let output_dir = config::OUTPUT_DIR.to_string();
let mut deleted_count = 0u64;
// 縮圖目錄路徑
let thumbnails_dir = std::path::Path::new(&output_dir).join("thumbnails");
if thumbnails_dir.is_dir() {
// 1. 刪除以 uuid 命名的縮圖文件 (如: thumbnails/{uuid}.jpg)
if let Ok(entries) = std::fs::read_dir(&thumbnails_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
// 匹配: uuid.jpg, uuid_*.jpg, uuid.png, etc.
if name.starts_with(uuid) && !path.is_dir() {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted thumbnail: {}", name);
}
}
}
}
}
}
// 2. 刪除以 uuid 命名的縮圖目錄 (如: thumbnails/{uuid}/)
let uuid_thumb_dir = thumbnails_dir.join(uuid);
if uuid_thumb_dir.is_dir() {
if std::fs::remove_dir_all(&uuid_thumb_dir).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted thumbnail directory: {}", uuid_thumb_dir.display());
}
}
}
}
println!("[UNREGISTER] Deleted {} thumbnail files/directories", deleted_count);
Ok(())
}
+357
View File
@@ -0,0 +1,357 @@
use anyhow::{Context, Result};
use clap::Parser;
use momentry_core::core::config;
use momentry_core::core::db::{
postgres_db::PostgresDb, qdrant_db::QdrantDb, qdrant_workspace::QdrantWorkspace,
redis_client::RedisClient,
};
use momentry_core::Database;
#[derive(Parser, Debug)]
#[command(name = "rust_unregister")]
#[command(about = "Unregister a video file from Momentry database")]
struct Args {
#[arg(short, long)]
uuid: String,
#[arg(short, long, default_value = "false")]
dry_run: bool,
#[arg(short, long, default_value = "false")]
verbose: bool,
}
#[tokio::main]
async fn main() -> Result<()> {
let args = Args::parse();
println!("[UNREGISTER] Starting for file_uuid: {}", args.uuid);
if args.dry_run {
println!("[UNREGISTER] DRY-RUN MODE - No actual deletion");
}
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string());
if args.verbose {
println!("[UNREGISTER] Schema: {}", schema);
println!("[UNREGISTER] Output dir: {}", *config::OUTPUT_DIR);
}
if !args.dry_run {
let db = PostgresDb::init()
.await
.context("Failed to connect to database")?;
unregister_database(&db, &args.uuid, args.verbose).await?;
unregister_output_files(&args.uuid, args.verbose)?;
unregister_qdrant(&args.uuid, &schema, args.verbose).await?;
unregister_redis(&args.uuid, args.verbose).await?;
} else {
println!("[UNREGISTER] Would delete from database");
println!("[UNREGISTER] Would delete output files");
println!("[UNREGISTER] Would delete Qdrant vectors");
println!("[UNREGISTER] Would delete Redis keys");
}
println!("[UNREGISTER] Done");
Ok(())
}
async fn unregister_database(db: &PostgresDb, uuid: &str, verbose: bool) -> Result<()> {
use momentry_core::core::db::schema;
println!("[UNREGISTER] Deleting database records...");
let mut deleted_total = 0i64;
let tables = [
("processor_results", "file_uuid = $1", "processor_results"),
("chunk", "file_uuid = $1", "chunks"),
("parent_chunks", "uuid = $1", "parent_chunks"),
("pre_chunks", "file_uuid = $1", "pre_chunks"),
("tkg_nodes", "file_uuid = $1", "TKG nodes"),
("cuts", "file_uuid = $1", "cuts"),
("strangers", "file_uuid = $1", "strangers"),
("chunk_vectors", "uuid = $1", "chunk vectors"),
("monitor_jobs", "uuid = $1", "monitor jobs"),
("file_identities", "file_uuid = $1", "file identities"),
("speaker_detections", "file_uuid = $1", "speaker detections"),
("face_clusters", "file_uuid = $1", "face clusters"),
(
"face_recognition_results",
"file_uuid = $1",
"face recognition results",
),
("characters", "file_uuid = $1", "characters"),
("chunks_rule1", "uuid = $1", "chunks_rule1"),
("processor_alerts", "file_uuid = $1", "processor alerts"),
("processor_versions", "file_uuid = $1", "processor versions"),
("trace_profiles", "file_uuid = $1", "trace profiles"),
];
for (table, where_clause, label) in tables.iter() {
let table_name = schema::table_name(table);
let query = format!("DELETE FROM {} WHERE {}", table_name, where_clause);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context(format!("Failed to delete from {}", table_name))?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} {}", deleted, label);
}
}
let frames_table = schema::table_name("frames");
let videos_table = schema::table_name("videos");
let query = format!(
"DELETE FROM {} WHERE file_id = (SELECT id FROM {} WHERE file_uuid = $1)",
frames_table, videos_table
);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context("Failed to delete frames")?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} frames", deleted);
}
let query = format!("DELETE FROM {} WHERE file_uuid = $1", videos_table);
let result = sqlx::query(&query)
.bind(uuid)
.execute(db.pool())
.await
.context("Failed to delete from videos table")?;
let deleted = result.rows_affected() as i64;
deleted_total += deleted;
if verbose && deleted > 0 {
println!("[UNREGISTER] Deleted {} videos", deleted);
}
println!(
"[UNREGISTER] Total deleted: {} database records",
deleted_total
);
Ok(())
}
fn unregister_output_files(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting output files...");
let mut deleted_count = 0u64;
let output_dir = config::OUTPUT_DIR.to_string();
if let Ok(entries) = std::fs::read_dir(&output_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let is_uuid_file = name.starts_with(uuid) && !path.is_dir();
let is_pipeline_log =
name.starts_with("pipeline_") && name.contains(uuid) && name.ends_with(".log");
let is_scenes_json = name == &format!("{}.scenes.json", uuid);
if is_uuid_file || is_pipeline_log || is_scenes_json {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted: {}", name);
}
}
}
}
}
}
let uuid_dir = std::path::Path::new(&output_dir).join(uuid);
if uuid_dir.is_dir() {
if std::fs::remove_dir_all(&uuid_dir).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted directory: {}", uuid_dir.display());
}
}
}
let workspace_sqlite = format!("{}.workspace.sqlite", uuid);
let sqlite_path = std::path::Path::new(&output_dir).join(&workspace_sqlite);
if sqlite_path.exists() && std::fs::remove_file(&sqlite_path).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted: {}", workspace_sqlite);
}
}
println!("[UNREGISTER] Deleted {} output files", deleted_count);
Ok(())
}
async fn unregister_qdrant(uuid: &str, schema: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting Qdrant vectors...");
let qdrant = QdrantDb::new();
let speaker_collection = if schema == "public" {
"momentry_public_speaker".to_string()
} else {
format!("momentry_{}_speaker", schema)
};
let face_embeddings_collection = format!("{}_face_embeddings", schema);
let collections: Vec<String> = vec![
qdrant.collection_name.clone(),
"_faces".to_string(),
"_scenes".to_string(),
"_vlm".to_string(),
"_seeds".to_string(),
face_embeddings_collection,
speaker_collection,
];
let mut success_count = 0;
for collection in &collections {
match QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
collection,
uuid,
)
.await
{
Ok(_) => {
success_count += 1;
if verbose {
println!("[UNREGISTER] Deleted from Qdrant: {}", collection);
}
}
Err(e) => {
if verbose {
eprintln!(
"[UNREGISTER] Warning: Failed to delete from {}: {:?}",
collection, e
);
}
}
}
}
let workspace = QdrantWorkspace::new();
match workspace.delete_by_file_uuid(uuid).await {
Ok(_) => {
success_count += 1;
if verbose {
println!("[UNREGISTER] Deleted from Qdrant workspace");
}
}
Err(e) => {
if verbose {
eprintln!(
"[UNREGISTER] Warning: Failed to delete from workspace: {:?}",
e
);
}
}
}
println!(
"[UNREGISTER] Deleted from {} Qdrant collections",
success_count
);
Ok(())
}
async fn unregister_redis(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting Redis keys...");
match RedisClient::new() {
Ok(redis) => match redis.delete_worker_job(uuid).await {
Ok(_) => {
if verbose {
println!("[UNREGISTER] Deleted Redis keys");
}
}
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to delete Redis keys: {:?}", e);
}
}
},
Err(e) => {
if verbose {
eprintln!("[UNREGISTER] Warning: Failed to connect to Redis: {:?}", e);
}
}
}
Ok(())
}
// 新增:刪除縮圖函數
fn unregister_thumbnails(uuid: &str, verbose: bool) -> Result<()> {
println!("[UNREGISTER] Deleting thumbnails...");
let output_dir = config::OUTPUT_DIR.to_string();
let mut deleted_count = 0u64;
// 縮圖目錄路徑
let thumbnails_dir = std::path::Path::new(&output_dir).join("thumbnails");
if thumbnails_dir.is_dir() {
// 1. 刪除以 uuid 命名的縮圖文件 (如: thumbnails/{uuid}.jpg)
if let Ok(entries) = std::fs::read_dir(&thumbnails_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
// 匹配: uuid.jpg, uuid_*.jpg, uuid.png, etc.
if name.starts_with(uuid) && !path.is_dir() {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted thumbnail: {}", name);
}
}
}
}
}
}
// 2. 刪除以 uuid 命名的縮圖目錄 (如: thumbnails/{uuid}/)
let uuid_thumb_dir = thumbnails_dir.join(uuid);
if uuid_thumb_dir.is_dir() {
if std::fs::remove_dir_all(&uuid_thumb_dir).is_ok() {
deleted_count += 1;
if verbose {
println!("[UNREGISTER] Deleted thumbnail directory: {}", uuid_thumb_dir.display());
}
}
}
}
println!("[UNREGISTER] Deleted {} thumbnail files/directories", deleted_count);
Ok(())
}
+14 -9
View File
@@ -3,33 +3,38 @@ use momentry_core::core::processor::face::process_face;
#[tokio::main]
async fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
eprintln!("Usage: test_rust_face_tracker <video_path> <output_path> [uuid]");
std::process::exit(1);
}
let video_path = &args[1];
let output_path = &args[2];
let uuid = args.get(3).map(|s| s.as_str());
println!("Processing video: {}", video_path);
println!("Output: {}", output_path);
println!("UUID: {:?}", uuid);
match process_face(video_path, output_path, uuid, None).await {
Ok(result) => {
println!("✅ Face processing completed");
println!(" Total frames: {}", result.frames.len());
println!(" Total faces: {}", result.total_faces);
// 統計 trace_id
let with_trace = result.frames.iter()
let with_trace = result
.frames
.iter()
.flat_map(|f| &f.faces)
.filter(|face| face.trace_id.is_some())
.count();
println!(" Faces with trace_id: {}/{}", with_trace, result.total_faces);
println!(
" Faces with trace_id: {}/{}",
with_trace, result.total_faces
);
// 顯示 trace_id 分佈
let mut traces = std::collections::HashMap::new();
for frame in &result.frames {
@@ -39,7 +44,7 @@ async fn main() {
}
}
}
println!("\n Trace ID distribution:");
for (tid, count) in traces.iter() {
println!(" Trace {}: {} faces", tid, count);