Files
momentry_core/src/bin/cli.rs
T
Accusys 4b694a1c2d remove: Portal project (Core Team 不再維護前端)
- 移除 portal/ 目錄 (Vue 3 + Tauri 前端)
- 更新 AGENTS.md 移除 Portal 相關說明
- 更新代碼註釋移除 Portal 引用
- 前端開發統一由 Studio Team 負責

參考: docs_v1.0/OPERATIONS/GUI_ARCHITECTURE_REVIEW.md
2026-09-30 18:59:40 +08:00

269 lines
9.2 KiB
Rust

use chrono::Local;
use clap::{Parser, Subcommand};
use reqwest;
use serde_json;
use std::time::Duration;
use std::time::Instant;
fn get_timestamp() -> String {
Local::now().format("%H:%M:%S").to_string()
}
#[derive(Parser)]
#[command(name = "momentry-cli")]
#[command(about = "CLI Agent Interface for Momentry")]
struct Cli {
#[command(subcommand)]
command: Commands,
/// API Base URL (default: http://localhost:3002)
#[arg(long, default_value = "http://localhost:3002")]
api_url: String,
}
#[derive(Subcommand)]
enum Commands {
/// 註冊檔案 (Register File)
Register { path: String },
/// 取消註冊 (Unregister File)
Unregister { file_uuid: String },
/// 探測檔案 (Probe File) - 需要 UUID
Probe { file_uuid: String },
/// 開始處理 (Start Processing)
Process { file_uuid: String },
/// 監控處理進度 (Watch Progress until completed)
Watch { file_uuid: String },
/// 列出未綁定臉部 (List Unbound Faces)
ListFaces {
file_uuid: String,
#[arg(long, default_value = "0.5")]
min_conf: f64,
#[arg(long, default_value = "20")]
limit: usize,
},
/// 綁定身份 (Bind Identity)
Bind {
file_uuid: String,
face_id: String,
identity_id: String,
},
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
let start_time = Instant::now();
println!("⏱️ [TIME] Start Command: {}", get_timestamp());
let result = run_command(&cli).await;
let duration = start_time.elapsed();
println!(
"⏱️ [TIME] End Command: {} | Duration: {:.2}s",
get_timestamp(),
duration.as_secs_f64()
);
result
}
async fn run_command(cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
let api_key = "muser_test_001";
let client = reqwest::Client::new();
let auth_header = reqwest::header::HeaderMap::from_iter([
("X-API-Key".parse().unwrap(), api_key.parse().unwrap()),
(
"Content-Type".parse().unwrap(),
"application/json".parse().unwrap(),
),
]);
match &cli.command {
Commands::Register { path } => {
println!("📥 [CLI] 正在註冊: {}", path);
let res = client
.post(&format!("{}/api/v1/files/register", cli.api_url))
.headers(auth_header.clone())
.json(&serde_json::json!({ "file_path": path }))
.send()
.await?;
if res.status().is_success() {
let json: serde_json::Value = res.json().await?;
println!("✅ [CLI] 註冊成功:");
println!(
" UUID: {}",
json.get("file_uuid")
.unwrap_or(&serde_json::Value::String("-".into()))
);
} else {
println!("❌ [CLI] 註冊失敗: {}", res.status());
}
}
Commands::Unregister { file_uuid } => {
println!("🗑️ [CLI] 正在取消註冊: {}", file_uuid);
let res = client
.post(&format!("{}/api/v1/unregister", cli.api_url))
.headers(auth_header.clone())
.json(&serde_json::json!({ "uuid": file_uuid }))
.send()
.await?;
if res.status().is_success() {
println!("✅ [CLI] 取消註冊成功");
} else {
println!("❌ [CLI] 取消註冊失敗: {}", res.status());
}
}
Commands::Probe { file_uuid } => {
println!("🔍 [CLI] 正在探測檔案 (UUID): {}", file_uuid);
let res = client
.get(&format!(
"{}/api/v1/assets/{}/probe",
cli.api_url, file_uuid
))
.headers(auth_header.clone())
.send()
.await?;
if res.status().is_success() {
let json: serde_json::Value = res.json().await?;
println!("✅ [CLI] 探測成功:");
println!(
" 時長: {}s",
json.get("duration")
.map(|v| v.to_string())
.unwrap_or("-".into())
);
} else {
println!("❌ [CLI] 探測失敗: {}", res.status());
}
}
Commands::Process { file_uuid } => {
println!("⚙️ [CLI] 正在觸發處理: {}", file_uuid);
let res = client
.post(&format!(
"{}/api/v1/assets/{}/process",
cli.api_url, file_uuid
))
.headers(auth_header.clone())
.json(&serde_json::json!({})) // Send empty JSON object
.send()
.await?;
if res.status().is_success() {
println!(
"✅ [CLI] 處理已啟動。請使用 'momentry-cli watch {}' 監控進度。",
file_uuid
);
} else {
println!("❌ [CLI] 啟動處理失敗: {}", res.status());
}
}
Commands::Watch { file_uuid } => {
println!("👀 [CLI] 開始監控進度: {}", file_uuid);
loop {
let res = client
.get(&format!("{}/api/v1/progress/{}", cli.api_url, file_uuid))
.headers(auth_header.clone())
.send()
.await?;
if !res.status().is_success() {
println!("❌ [CLI] 無法取得進度: {}", res.status());
break;
}
let json: serde_json::Value = res.json().await?;
let progress = json["overall_progress"].as_u64().unwrap_or(0);
let current = json["current_processor"].as_str().unwrap_or("Unknown");
println!(" 📊 進度: {}% | 當前階段: {}", progress, current);
if progress >= 100 || json["status"].as_str().unwrap_or("") == "completed" {
println!("✅ [CLI] 處理完成!");
break;
}
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
Commands::ListFaces {
file_uuid,
min_conf,
limit,
} => {
println!("🕵️ [CLI] 正在查詢臉部: {}", file_uuid);
let url = format!(
"{}/api/v1/faces/candidates?file_uuid={}&min_confidence={}&page_size={}",
cli.api_url, file_uuid, min_conf, limit
);
let res = client.get(&url).headers(auth_header.clone()).send().await?;
if res.status().is_success() {
let json: serde_json::Value = res.json().await?;
println!("✅ [CLI] 查詢成功:");
if let Some(candidates) = json.get("candidates") {
if candidates.as_array().map_or(0, |v| v.len()) > 0 {
println!(
" 找到 {} 個未綁定臉部:",
candidates.as_array().unwrap().len()
);
for (i, c) in candidates.as_array().unwrap().iter().enumerate() {
let id = c.get("id").map(|v| v.to_string()).unwrap_or("N/A".into());
let conf = c
.get("confidence")
.map(|v| v.to_string())
.unwrap_or("0".into());
println!(" {}. ID: {} | Confidence: {}", i + 1, id, conf);
}
} else {
println!(" 未找到符合條件的臉部。");
}
}
} else {
println!("❌ [CLI] 查詢失敗: {}", res.status());
}
}
Commands::Bind {
file_uuid,
face_id,
identity_id,
} => {
println!(
"🔗 [CLI] 正在綁定 Identity {} -> Face {} (File: {})",
identity_id, face_id, file_uuid
);
let payload = serde_json::json!({
"identity_id": identity_id.parse::<i64>().unwrap_or(0),
"binding_type": "face",
"binding_value": face_id
});
let res = client
.post(&format!("{}/api/v1/identities/bind", cli.api_url))
.headers(auth_header.clone())
.json(&payload)
.send()
.await?;
if res.status().is_success() {
let json: serde_json::Value = res.json().await?;
println!(
"✅ [CLI] 綁定成功: {}",
json.get("message")
.map(|v| v.to_string())
.unwrap_or("".into())
);
} else {
let text = res.text().await?;
println!("❌ [CLI] 綁定失敗: {}", text);
}
}
}
Ok(())
}