feat: add rust_register CLI tool

新增功能:
- 獨立的 register CLI 工具
- 不依賴 API 和 Worker
- 直接註冊視頻文件到數據庫

特性:
- ✅ 元數據提取 (ffprobe)
- ✅ Birth UUID 計算
- ✅ Force 模式 (覆蓋已存在)
- ✅ 詳細輸出模式
- ✅ 錯誤處理

使用方法:
```bash
# 註冊文件
rust_register /path/to/video.mp4

# 強制重新註冊
rust_register /path/to/video.mp4 --force

# 詳細輸出
rust_register /path/to/video.mp4 --verbose
```

功能:
1. 文件驗證
2. UUID 計算 (birth UUID)
3. 元數據提取 (duration, resolution, fps)
4. 數據庫插入
5. Force 模式 (自動 unregister)

元數據:
- Duration: 8.80s
- Resolution: 1920x1080
- FPS: 59.94
- Total frames: 527

優勢:
- 同步執行(無需等待 Worker)
- 獨立運行(無需 API Server)
- 詳細輸出(便於調試)

文檔:
- docs_v1.0/OPERATIONS/Rust_Register_CLI_Tool.md

測試:
- ✅ 編譯成功
- ✅ 基本註冊測試通過
- ✅ Force 模式測試通過
- ✅ Verbose 模式測試通過

Binary:
- target/debug/rust_register
This commit is contained in:
Accusys
2026-09-28 19:27:43 +08:00
parent 06397e5957
commit 6bac60bcf8
3 changed files with 639 additions and 0 deletions
+338
View File
@@ -0,0 +1,338 @@
use anyhow::{Context, Result};
use clap::Parser;
use momentry_core::core::db::postgres_db::PostgresDb;
use momentry_core::core::config;
use momentry_core::core::storage::uuid;
use momentry_core::Database;
use std::path::Path;
#[derive(Parser, Debug)]
#[command(name = "rust_register")]
#[command(about = "Register a video file to Momentry database")]
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,
}
#[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
.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(())
}
struct RegisterResult {
file_uuid: String,
duration: f64,
}
async fn register_file(
db: &PostgresDb,
file_path: &str,
force: bool,
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())
.map(|t| {
let secs = t
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
chrono::DateTime::from_timestamp(secs as i64, 0)
.map(|dt| dt.to_rfc3339())
.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,
);
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
))
.bind(&file_uuid)
.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] 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,
content_hash, duration, width, height,
fps, total_frames, registration_time, status
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'registered')",
videos_table
))
.bind(&file_uuid)
.bind(&file_name)
.bind(&canonical_path)
.bind(&content_hash)
.bind(metadata.duration)
.bind(metadata.width as i32)
.bind(metadata.height as i32)
.bind(metadata.fps)
.bind(metadata.total_frames as i64)
.bind(registration_time)
.execute(db.pool())
.await
.context("Failed to insert into videos table")?;
println!("[REGISTER] Registered: {}", file_uuid);
Ok(RegisterResult {
file_uuid,
duration: metadata.duration,
})
}
struct VideoMetadata {
duration: f64,
width: u32,
height: u32,
fps: f64,
total_frames: u64,
}
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",
file_path,
])
.output()
.context("Failed to run ffprobe")?;
if !output.status.success() {
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 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 }
} 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()))
.unwrap_or(0.0);
let total_frames = if fps > 0.0 {
(duration * fps) as u64
} else {
0
};
Ok(VideoMetadata {
duration,
width,
height,
fps,
total_frames,
})
}
fn sha256_file(path: &Path) -> Result<String> {
use sha2::{Sha256, Digest};
use std::io::Read;
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 {
break;
}
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"),
("parent_chunks", "uuid = $1"),
("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)"),
("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;
if verbose {
if let Ok(r) = result {
let deleted = r.rows_affected();
if deleted > 0 {
println!("[REGISTER] Deleted {} from {}", deleted, table_name);
}
}
}
}
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")?;
Ok(())
}