feat: real service test endpoints (proxy 7-route round-trip, core/chat/vlm/markbase/embedding), unified log paths + errorLog, pipeline tools/import/export/folder APIs, face pipeline check, dynamic concurrency tuning
This commit is contained in:
+97
-15
@@ -94,6 +94,25 @@ pub struct LlmConfig {
|
||||
pub model: String,
|
||||
#[serde(default)]
|
||||
pub timeout: u32,
|
||||
/// Deprecated single fallback (kept for backward compat; merged into `fallbacks`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub fallback_url: Option<String>,
|
||||
/// Ordered backup endpoints. Each may be a local instance
|
||||
/// (127.0.0.1:8080/8082) or a remote machine's llama-server
|
||||
/// (e.g. http://192.168.110.201:8080/... — pooling off-box compute).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub fallbacks: Vec<String>,
|
||||
/// Load strategy across primary + fallbacks:
|
||||
/// "priority" (default, failover only) or "round_robin"
|
||||
/// (each request rotates to the next instance — pools all available
|
||||
/// compute for higher aggregate throughput).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub strategy: Option<String>,
|
||||
/// Instance on/off switch for routing. When disabled, requests are never
|
||||
/// routed to this instance (neither as primary nor as fallback).
|
||||
/// None = enabled (default true).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub enabled: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
@@ -267,6 +286,14 @@ fn default_processor_timeout_secs() -> u32 {
|
||||
.unwrap_or(3600)
|
||||
}
|
||||
|
||||
fn default_preferred_language() -> String {
|
||||
"en".to_string()
|
||||
}
|
||||
|
||||
fn default_library_sort() -> String {
|
||||
"name_asc".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct AdminSettings {
|
||||
#[serde(default = "default_session_timeout")]
|
||||
@@ -279,6 +306,8 @@ pub struct AdminSettings {
|
||||
pub system_stats_refresh_sec: u32,
|
||||
#[serde(default = "default_preferred_language")]
|
||||
pub preferred_language: String,
|
||||
#[serde(default = "default_library_sort")]
|
||||
pub library_default_sort: String,
|
||||
}
|
||||
|
||||
/// Get FS VLM enabled setting from admin_config
|
||||
@@ -381,7 +410,7 @@ fn default_system_stats_refresh_sec() -> u32 {
|
||||
.unwrap_or(5)
|
||||
}
|
||||
|
||||
fn default_preferred_language() -> String {
|
||||
fn default_server_preferred_language() -> String {
|
||||
std::env::var("MOMENTRY_PREFERRED_LANGUAGE")
|
||||
.unwrap_or_else(|_| "zh-TW".to_string())
|
||||
}
|
||||
@@ -730,25 +759,78 @@ pub async fn get_server() -> ServerConfig {
|
||||
ADMIN_CONFIG.get_server().await
|
||||
}
|
||||
|
||||
/// Read the `paths` block from admin_config.json synchronously (override source).
|
||||
/// Empty or missing fields mean "not defined here" and fall through to env/default.
|
||||
fn admin_paths_override() -> PathsConfig {
|
||||
let mut out = PathsConfig {
|
||||
output_dir: String::new(),
|
||||
backup_dir: String::new(),
|
||||
scripts_dir: String::new(),
|
||||
cli_dir: String::new(),
|
||||
python_path: String::new(),
|
||||
ffmpeg_path: String::new(),
|
||||
};
|
||||
let path = get_default_config_path();
|
||||
if let Ok(content) = std::fs::read_to_string(&path) {
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
if let Some(p) = v.get("paths").and_then(|p| p.as_object()) {
|
||||
let grab = |key: &str| -> String {
|
||||
p.get(key)
|
||||
.and_then(|s| s.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
out.output_dir = grab("output_dir");
|
||||
out.backup_dir = grab("backup_dir");
|
||||
out.scripts_dir = grab("scripts_dir");
|
||||
out.cli_dir = grab("cli_dir");
|
||||
out.python_path = grab("python_path");
|
||||
out.ffmpeg_path = grab("ffmpeg_path");
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolve once: admin_config.json (non-empty) > env var > hardcoded default.
|
||||
fn or_default(value: String, fallback: impl FnOnce() -> String) -> String {
|
||||
if value.is_empty() {
|
||||
fallback()
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_paths_sync() -> PathsConfig {
|
||||
let ov = admin_paths_override();
|
||||
PathsConfig {
|
||||
// Must NOT read config::OUTPUT_DIR here: this function *is* the
|
||||
// initializer of that lazy static, so reading it re-enters
|
||||
// once_cell::sync::Lazy::force and deadlocks the calling thread.
|
||||
output_dir: default_output_dir(),
|
||||
backup_dir: std::env::var("MOMENTRY_BACKUP_DIR")
|
||||
.unwrap_or_else(|_| {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| p.parent().map(|d| d.join("var/backup")))
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "var/backup".to_string())
|
||||
}),
|
||||
scripts_dir: crate::core::path_utils::scripts_dir().to_string_lossy().to_string(),
|
||||
cli_dir: crate::core::path_utils::cli_dir().to_string_lossy().to_string(),
|
||||
python_path: std::env::var("MOMENTRY_PYTHON_PATH")
|
||||
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string()),
|
||||
ffmpeg_path: std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string()),
|
||||
output_dir: or_default(ov.output_dir.clone(), default_output_dir),
|
||||
backup_dir: or_default(ov.backup_dir.clone(), || {
|
||||
std::env::var("MOMENTRY_BACKUP_DIR")
|
||||
.unwrap_or_else(|_| {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| p.parent().map(|d| d.join("var/backup")))
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "var/backup".to_string())
|
||||
})
|
||||
}),
|
||||
scripts_dir: or_default(ov.scripts_dir.clone(), || {
|
||||
crate::core::path_utils::scripts_dir().to_string_lossy().to_string()
|
||||
}),
|
||||
cli_dir: or_default(ov.cli_dir.clone(), || {
|
||||
crate::core::path_utils::cli_dir().to_string_lossy().to_string()
|
||||
}),
|
||||
python_path: or_default(ov.python_path, || {
|
||||
std::env::var("MOMENTRY_PYTHON_PATH")
|
||||
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string())
|
||||
}),
|
||||
ffmpeg_path: or_default(ov.ffmpeg_path, || {
|
||||
std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string())
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1707,6 +1707,10 @@ pub async fn exec_scene_search(
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let vlm_description_localized = payload
|
||||
.get("vlm_description_localized")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let vlm_tags: Vec<String> = payload
|
||||
.get("vlm_tags")
|
||||
.and_then(|v| v.as_array())
|
||||
@@ -1729,6 +1733,7 @@ pub async fn exec_scene_search(
|
||||
.unwrap_or_default();
|
||||
|
||||
let description_preview = vlm_description.chars().take(150).collect::<String>();
|
||||
let localized_preview = vlm_description_localized.as_deref().map(|s| s.chars().take(150).collect::<String>());
|
||||
|
||||
cards.push(serde_json::json!({
|
||||
"card_type": "scene",
|
||||
@@ -1743,6 +1748,7 @@ pub async fn exec_scene_search(
|
||||
"score": score,
|
||||
"vlm_tags": vlm_tags,
|
||||
"vlm_description": description_preview,
|
||||
"vlm_description_localized": localized_preview,
|
||||
"source": "vlm_scene"
|
||||
}));
|
||||
}
|
||||
@@ -1847,6 +1853,10 @@ pub async fn exec_vlm_search(
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let vlm_description_localized = payload
|
||||
.get("vlm_description_localized")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let vlm_tags: Vec<String> = payload
|
||||
.get("vlm_tags")
|
||||
.and_then(|v| v.as_array())
|
||||
@@ -1882,6 +1892,7 @@ pub async fn exec_vlm_search(
|
||||
"score": score,
|
||||
"vlm_tags": vlm_tags,
|
||||
"vlm_description": vlm_description.chars().take(150).collect::<String>(),
|
||||
"vlm_description_localized": vlm_description_localized.as_deref().map(|s| s.chars().take(150).collect::<String>()),
|
||||
"source": "vlm_scene"
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -219,6 +219,40 @@ pub fn get_scene_vlm_config() -> (bool, u32, usize, bool, usize) {
|
||||
|
||||
pub static OUTPUT_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_output_dir());
|
||||
|
||||
/// Get the per-library output directory for a file based on its upload_path
|
||||
pub async fn get_output_dir_for_file(file_uuid: &str, pool: &sqlx::PgPool) -> String {
|
||||
let videos_table = crate::core::db::schema::table_name("videos");
|
||||
let upload_paths_table = crate::core::db::schema::table_name("upload_paths");
|
||||
|
||||
let result: Option<(Option<String>,)> = sqlx::query_as(
|
||||
&format!(
|
||||
"SELECT up.output_path FROM {} v
|
||||
LEFT JOIN {} up ON v.file_path LIKE up.full_path || '%%'
|
||||
WHERE v.file_uuid = $1
|
||||
AND up.output_path IS NOT NULL AND up.output_path != ''
|
||||
LIMIT 1",
|
||||
videos_table, upload_paths_table
|
||||
)
|
||||
)
|
||||
.bind(file_uuid)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
|
||||
if let Some((Some(output_path),)) = result {
|
||||
return output_path;
|
||||
}
|
||||
|
||||
OUTPUT_DIR.to_string()
|
||||
}
|
||||
|
||||
pub fn get_output_dir_for_file_sync(_file_uuid: &str, _pool: &sqlx::PgPool) -> String {
|
||||
// Sync context cannot easily query DB - use global OUTPUT_DIR
|
||||
// Use async version `get_output_dir_for_file()` for proper per-library paths
|
||||
OUTPUT_DIR.to_string()
|
||||
}
|
||||
|
||||
pub static BACKUP_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_backup_dir());
|
||||
|
||||
pub static SCRIPTS_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_scripts_dir());
|
||||
|
||||
@@ -844,6 +844,19 @@ pub struct ApiKeyRecord {
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
/// One currently-valid login session (for the Admin active-logins view).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct ActiveSessionRow {
|
||||
pub session_id: String,
|
||||
pub username: Option<String>,
|
||||
pub role: Option<String>,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
pub expires_at: chrono::DateTime<chrono::Utc>,
|
||||
pub ip_address: String,
|
||||
pub user_agent: String,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ApiKeyStats {
|
||||
pub total_keys: i64,
|
||||
@@ -3290,7 +3303,49 @@ impl PostgresDb {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_session_by_id(
|
||||
|
||||
pub async fn create_session_with_meta(
|
||||
&self,
|
||||
session_id: &str,
|
||||
user_id: i32,
|
||||
api_key_id: &str,
|
||||
ttl_hours: i64,
|
||||
ip_address: &str,
|
||||
user_agent: &str,
|
||||
source: &str,
|
||||
) -> Result<()> {
|
||||
let table = schema::table_name("sessions");
|
||||
let interval = format!("{} hours", ttl_hours);
|
||||
sqlx::query(
|
||||
&format!("INSERT INTO {} (session_id, user_id, api_key_id, expires_at, ip_address, user_agent, source) VALUES ($1, $2, $3, CURRENT_TIMESTAMP + $4::interval, $5, $6, $7)", table)
|
||||
)
|
||||
.bind(session_id)
|
||||
.bind(user_id)
|
||||
.bind(api_key_id)
|
||||
.bind(&interval)
|
||||
.bind(ip_address)
|
||||
.bind(user_agent)
|
||||
.bind(source)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_active_sessions(&self) -> Result<Vec<ActiveSessionRow>> {
|
||||
let table = schema::table_name("sessions");
|
||||
let rows = sqlx::query_as::<_, ActiveSessionRow>(
|
||||
&format!(
|
||||
"SELECT s.session_id, u.username, u.role, s.created_at, s.expires_at, COALESCE(s.ip_address, '') AS ip_address, COALESCE(s.user_agent, '') AS user_agent, COALESCE(s.source, '') AS source FROM {} s LEFT JOIN {} u ON u.id = s.user_id WHERE s.expires_at > CURRENT_TIMESTAMP ORDER BY s.created_at DESC",
|
||||
table,
|
||||
schema::table_name("users")
|
||||
)
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
pub async fn get_session_by_id(
|
||||
&self,
|
||||
session_id: &str,
|
||||
) -> Result<Option<(i32, i32, String, chrono::DateTime<chrono::Utc>)>> {
|
||||
|
||||
@@ -190,3 +190,208 @@ pub async fn ensure_face_track_node(
|
||||
.await?;
|
||||
Ok(res.rows_affected())
|
||||
}
|
||||
|
||||
// ─── Face Groups (first-class group entity) ──────────────────────────────────
|
||||
//
|
||||
// A face group is now a real row in `face_groups`. Trace membership is stored
|
||||
// on `trace_profiles.group_id`. The trace name (trace_profiles.name) remains
|
||||
// only as a per-trace display caption; it is no longer the grouping source of
|
||||
// truth. Renaming a group = one UPDATE on face_groups. Moving a trace = one
|
||||
// UPDATE on trace_profiles.
|
||||
//
|
||||
// All helpers below are idempotent and safe to call on every request.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
pub async fn ensure_face_groups_schema(pool: &PgPool) -> anyhow::Result<()> {
|
||||
let tp = table_name("trace_profiles");
|
||||
let fg = table_name("face_groups");
|
||||
|
||||
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS face_groups (\
|
||||
id BIGSERIAL PRIMARY KEY,\
|
||||
file_uuid VARCHAR(255) NOT NULL,\
|
||||
name TEXT NOT NULL,\
|
||||
origin_cluster_id VARCHAR(255),\
|
||||
sort_index INT NOT NULL DEFAULT 0,\
|
||||
properties JSONB NOT NULL DEFAULT '{}'::jsonb,\
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\
|
||||
UNIQUE (file_uuid, name))",
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_face_groups_file ON face_groups(file_uuid)")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(&format!(
|
||||
"ALTER TABLE {tp} ADD COLUMN IF NOT EXISTS group_id BIGINT REFERENCES face_groups(id)"
|
||||
))
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
// Backfill: every named trace (non-empty, not auto trace labels) defines
|
||||
// one group row; its traces attach to that group.
|
||||
{
|
||||
let sql = format!(
|
||||
"INSERT INTO {fg} (file_uuid, name) SELECT file_uuid, name FROM {tp} WHERE name IS NOT NULL AND name <> '' AND NOT (name LIKE 'Face Trace %') AND NOT (name LIKE 'Trace %') AND NOT (name LIKE 'Person_%') GROUP BY file_uuid, name ON CONFLICT (file_uuid, name) DO NOTHING");
|
||||
sqlx::query(&sql).execute(pool).await?;
|
||||
}
|
||||
|
||||
{
|
||||
let sql = format!(
|
||||
"UPDATE {tp} SET group_id = g.id FROM {fg} g WHERE g.file_uuid = {tp}.file_uuid AND g.name = {tp}.name AND {tp}.group_id IS NULL");
|
||||
sqlx::query(&sql).execute(pool).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get or create the group with the given name for a file. Returns group id.
|
||||
pub async fn get_or_create_group(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
name: &str,
|
||||
) -> anyhow::Result<i64> {
|
||||
let fg = table_name("face_groups");
|
||||
let row: (i64,) = sqlx::query_as(&format!(
|
||||
"INSERT INTO {fg} (file_uuid, name) VALUES ($1, $2) ON CONFLICT (file_uuid, name) DO UPDATE SET updated_at = NOW(), properties = {fg}.properties - 'dissolved' RETURNING id"
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.bind(name)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(row.0)
|
||||
}
|
||||
|
||||
/// Rename one group row (single write). Bumps updated_at.
|
||||
pub async fn rename_group(pool: &PgPool, group_id: i64, new_name: &str) -> anyhow::Result<()> {
|
||||
let fg = table_name("face_groups");
|
||||
sqlx::query(&format!(
|
||||
"UPDATE {fg} SET name = $1, updated_at = NOW() WHERE id = $2"
|
||||
))
|
||||
.bind(new_name)
|
||||
.bind(group_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete the group rows matching names (used by merge/ungroup cleanup).
|
||||
pub async fn delete_groups_by_names(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
names: &[String],
|
||||
) -> anyhow::Result<u64> {
|
||||
if names.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let fg = table_name("face_groups");
|
||||
let res = sqlx::query(&format!(
|
||||
"DELETE FROM {fg} WHERE file_uuid = $1 AND name = ANY($2)"
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.bind(names)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(res.rows_affected())
|
||||
}
|
||||
|
||||
// ─── Face Groups JSON Persistence ─────────────────────────────────────────────
|
||||
//
|
||||
// Saves face group state to {output_dir}/{file_uuid}.face_groups.json
|
||||
// This serves as the persistent source of truth for face groups, independent
|
||||
// of face_cluster.json (which is algorithm output) and DB (which may be reset).
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
pub async fn save_face_groups_json(pool: &PgPool, file_uuid: &str) -> anyhow::Result<()> {
|
||||
use chrono::Utc;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
let fg = table_name("face_groups");
|
||||
let tp = table_name("trace_profiles");
|
||||
let v = table_name("videos");
|
||||
|
||||
// Get file_name from videos table
|
||||
let file_name: Option<String> = sqlx::query_scalar(&format!(
|
||||
"SELECT file_name FROM {v} WHERE file_uuid = $1"
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
|
||||
// Get all groups with their trace members
|
||||
let groups: Vec<(i64, String, Option<String>, Vec<i32>)> = sqlx::query_as(&format!(
|
||||
"SELECT g.id, g.name, g.origin_cluster_id, \
|
||||
COALESCE(array_agg(tp.trace_id ORDER BY tp.trace_id) FILTER (WHERE tp.trace_id IS NOT NULL), ARRAY[]::int[]) \
|
||||
FROM {fg} g \
|
||||
LEFT JOIN {tp} tp ON tp.group_id = g.id \
|
||||
WHERE g.file_uuid = $1 \
|
||||
GROUP BY g.id, g.name, g.origin_cluster_id \
|
||||
ORDER BY g.sort_index, g.id"
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
// Build groups array
|
||||
let mut groups_json = Vec::new();
|
||||
let mut total_traces = 0i64;
|
||||
|
||||
for (gid, name, origin_cid, trace_ids) in &groups {
|
||||
let trace_count = trace_ids.len() as i64;
|
||||
total_traces += trace_count;
|
||||
|
||||
// Find representative trace (first one for now)
|
||||
let rep_trace = trace_ids.first().copied().unwrap_or(0);
|
||||
|
||||
groups_json.push(json!({
|
||||
"group_id": gid,
|
||||
"name": name,
|
||||
"origin_cluster_id": origin_cid,
|
||||
"trace_ids": trace_ids,
|
||||
"trace_count": trace_count,
|
||||
"representative_trace": rep_trace,
|
||||
"metadata": json!({})
|
||||
}));
|
||||
}
|
||||
|
||||
let output = json!({
|
||||
"schema_version": "1.0",
|
||||
"file_uuid": file_uuid,
|
||||
"file_name": file_name.unwrap_or_default(),
|
||||
"updated_at": Utc::now().to_rfc3339(),
|
||||
"total_groups": groups.len(),
|
||||
"total_traces": total_traces,
|
||||
"groups": groups_json
|
||||
});
|
||||
|
||||
// Save to output directory
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let path = std::path::Path::new(output_dir)
|
||||
.join(format!("{}.face_groups.json", file_uuid));
|
||||
|
||||
let json_str = serde_json::to_string_pretty(&output)?;
|
||||
std::fs::write(&path, json_str)?;
|
||||
|
||||
tracing::info!(
|
||||
"[FaceGroupsJSON] Saved {} groups, {} traces to {}",
|
||||
groups.len(),
|
||||
total_traces,
|
||||
path.display()
|
||||
);
|
||||
|
||||
// Mirror the same data into the workspace SQLite (equivalent backup).
|
||||
if let Ok(ws) = crate::core::db::workspace_sqlite::WorkspaceDb::open(file_uuid).await {
|
||||
if let Err(e) = ws
|
||||
.sync_face_groups(&groups)
|
||||
.await
|
||||
{
|
||||
tracing::warn!("[FaceGroupsJSON] SQLite mirror sync failed: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -149,6 +149,27 @@ impl WorkspaceDb {
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
// Face groups backup — mirrors face_groups.json (V1.0 persistence
|
||||
// design). Keeps group name + trace list per file in SQLite so the
|
||||
// JSON file and SQLite are equivalent backups of each other.
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS face_groups (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
file_uuid TEXT NOT NULL,
|
||||
group_id INTEGER,
|
||||
name TEXT NOT NULL,
|
||||
origin_cluster_id TEXT,
|
||||
trace_ids TEXT NOT NULL DEFAULT '[]',
|
||||
trace_count INTEGER NOT NULL DEFAULT 0,
|
||||
representative_trace INTEGER,
|
||||
metadata TEXT DEFAULT '{}',
|
||||
updated_at TEXT DEFAULT (datetime('now')),
|
||||
UNIQUE(file_uuid, name)
|
||||
)",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -167,6 +188,55 @@ impl WorkspaceDb {
|
||||
workspace_path(file_uuid).exists()
|
||||
}
|
||||
|
||||
// ── Face Groups (JSON backup mirror) ──
|
||||
|
||||
/// Mirror face_groups.json content into this workspace SQLite so the two
|
||||
/// are equivalent backups. Replaces all rows for the file (full sync).
|
||||
pub async fn sync_face_groups(
|
||||
&self,
|
||||
groups: &[(i64, String, Option<String>, Vec<i32>)],
|
||||
) -> Result<()> {
|
||||
// Replace-all sync: delete then insert keeps the mirror exact.
|
||||
sqlx::query("DELETE FROM face_groups WHERE file_uuid = $1")
|
||||
.bind(&self.file_uuid)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
for (gid, name, origin_cid, trace_ids) in groups {
|
||||
let trace_ids_json = serde_json::to_string(trace_ids)
|
||||
.unwrap_or_else(|_| "[]".to_string());
|
||||
let rep = trace_ids.first().copied();
|
||||
sqlx::query(
|
||||
"INSERT INTO face_groups \
|
||||
(file_uuid, group_id, name, origin_cluster_id, trace_ids, trace_count, representative_trace) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) \
|
||||
ON CONFLICT(file_uuid, name) DO UPDATE SET \
|
||||
group_id = excluded.group_id, \
|
||||
origin_cluster_id = excluded.origin_cluster_id, \
|
||||
trace_ids = excluded.trace_ids, \
|
||||
trace_count = excluded.trace_count, \
|
||||
representative_trace = excluded.representative_trace, \
|
||||
updated_at = datetime('now')",
|
||||
)
|
||||
.bind(&self.file_uuid)
|
||||
.bind(gid)
|
||||
.bind(name)
|
||||
.bind(origin_cid)
|
||||
.bind(&trace_ids_json)
|
||||
.bind(trace_ids.len() as i64)
|
||||
.bind(rep)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
"[WorkspaceSQLite] Synced {} face_groups rows for {}",
|
||||
groups.len(),
|
||||
self.file_uuid
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Processor Results ──
|
||||
|
||||
pub async fn upsert_processor_result(
|
||||
|
||||
@@ -12,6 +12,18 @@ pub enum MemoryStatus {
|
||||
High, // > 41 GB (must decrease concurrency)
|
||||
}
|
||||
|
||||
/// Minimum free memory (GB) needed to keep a second llama-server instance warm.
|
||||
const DUAL_INSTANCE_MIN_FREE_GB: f64 = 12.0;
|
||||
|
||||
/// True when free memory is too low to run two llama-server instances at once.
|
||||
/// Used by LLM routing to collapse chat/vlm/summary onto a single instance.
|
||||
pub fn memory_constrained() -> bool {
|
||||
let mut sys = System::new_all();
|
||||
sys.refresh_memory();
|
||||
let available_gb = sys.available_memory() as f64 / (1024.0 * 1024.0 * 1024.0);
|
||||
available_gb < DUAL_INSTANCE_MIN_FREE_GB
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum VlmStatus {
|
||||
Available, // < 5s (can increase concurrency)
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
/// File export/import for portable package (.momentry.tar.gz)
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ─── Manifest Structures ─────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ExportManifest {
|
||||
pub version: String,
|
||||
#[serde(rename = "type")]
|
||||
pub export_type: String,
|
||||
pub exported_at: String,
|
||||
pub momentry_version: String,
|
||||
pub file: FileInfo,
|
||||
pub data_sources: DataSources,
|
||||
pub processors: HashMap<String, ProcessorInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FileInfo {
|
||||
pub uuid: String,
|
||||
pub file_name: String,
|
||||
pub file_path: String,
|
||||
pub file_size: u64,
|
||||
pub library: String,
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct DataSources {
|
||||
pub postgresql: PostgresqlInfo,
|
||||
pub qdrant: QdrantInfo,
|
||||
pub sqlite: SqliteInfo,
|
||||
pub redis: RedisInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct PostgresqlInfo {
|
||||
pub tables: Vec<String>,
|
||||
pub total_records: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct QdrantInfo {
|
||||
pub collection: String,
|
||||
pub face_vectors: usize,
|
||||
pub text_vectors: usize,
|
||||
pub speaker_vectors: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct SqliteInfo {
|
||||
pub file: String,
|
||||
pub tables: Vec<String>,
|
||||
pub total_records: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct RedisInfo {
|
||||
pub keys_count: usize,
|
||||
pub patterns: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ProcessorInfo {
|
||||
pub status: String,
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
// ─── Export Function ─────────────────────────────────────────────────────────
|
||||
|
||||
pub async fn export_file(
|
||||
pool: &sqlx::PgPool,
|
||||
file_uuid: &str,
|
||||
output_dir: &str,
|
||||
export_dir: &str,
|
||||
) -> Result<PathBuf> {
|
||||
let package_dir = PathBuf::from(export_dir).join(format!("{}.momentry", file_uuid));
|
||||
if package_dir.exists() {
|
||||
std::fs::remove_dir_all(&package_dir)?;
|
||||
}
|
||||
|
||||
// Create directory structure
|
||||
std::fs::create_dir_all(&package_dir)?;
|
||||
std::fs::create_dir_all(package_dir.join("video"))?;
|
||||
std::fs::create_dir_all(package_dir.join("output"))?;
|
||||
std::fs::create_dir_all(package_dir.join("identities"))?;
|
||||
std::fs::create_dir_all(package_dir.join("db"))?;
|
||||
std::fs::create_dir_all(package_dir.join("qdrant"))?;
|
||||
std::fs::create_dir_all(package_dir.join("redis"))?;
|
||||
|
||||
// 1. Get file info from DB
|
||||
let videos_table = crate::core::db::schema::table_name("videos");
|
||||
let video_row: Option<(String, String, String)> = sqlx::query_as(
|
||||
&format!("SELECT file_name, file_path, status FROM {} WHERE file_uuid = $1", videos_table)
|
||||
)
|
||||
.bind(file_uuid)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
|
||||
let (file_name, file_path, status) = video_row.ok_or_else(|| anyhow::anyhow!("File not found"))?;
|
||||
|
||||
// Get file size from filesystem
|
||||
let file_size = std::fs::metadata(&file_path).ok().map(|m| m.len()).unwrap_or(0);
|
||||
|
||||
// Get library name
|
||||
let library = get_library_for_file(pool, &file_path).await;
|
||||
|
||||
// 2. Copy original video
|
||||
let video_src = PathBuf::from(&file_path);
|
||||
if video_src.exists() {
|
||||
let dest = package_dir.join("video").join(&file_name);
|
||||
std::fs::copy(&video_src, &dest)?;
|
||||
}
|
||||
|
||||
// 3. Copy output files
|
||||
copy_output_files(file_uuid, output_dir, &package_dir)?;
|
||||
|
||||
// 4. Copy identities (if any)
|
||||
copy_identities_if_exist(output_dir, &package_dir)?;
|
||||
|
||||
// 5. Export PostgreSQL data
|
||||
let db_stats = export_postgres_data(pool, file_uuid, &package_dir).await?;
|
||||
|
||||
// 6. Export Qdrant info (placeholder - full implementation later)
|
||||
let qdrant_stats = QdrantInfo {
|
||||
collection: "momentry_rule1".to_string(),
|
||||
face_vectors: 0,
|
||||
text_vectors: 0,
|
||||
speaker_vectors: 0,
|
||||
};
|
||||
// Create placeholder files
|
||||
std::fs::write(package_dir.join("qdrant").join("face_vectors.json"), "[]")?;
|
||||
std::fs::write(package_dir.join("qdrant").join("text_vectors.json"), "[]")?;
|
||||
std::fs::write(package_dir.join("qdrant").join("speaker_vectors.json"), "[]")?;
|
||||
|
||||
// 7. Export Redis info (placeholder)
|
||||
std::fs::write(package_dir.join("redis").join("job_state.json"), "{}")?;
|
||||
std::fs::write(package_dir.join("redis").join("cache.json"), "{}")?;
|
||||
let redis_stats = RedisInfo {
|
||||
keys_count: 0,
|
||||
patterns: vec![
|
||||
"momentry:job:*".to_string(),
|
||||
"momentry:progress:*".to_string(),
|
||||
],
|
||||
};
|
||||
|
||||
// 8. Get processor results
|
||||
let processors = get_processor_results(pool, file_uuid).await?;
|
||||
|
||||
// 9. Create manifest
|
||||
let manifest = ExportManifest {
|
||||
version: "1.0".to_string(),
|
||||
export_type: "file".to_string(),
|
||||
exported_at: chrono::Utc::now().to_rfc3339(),
|
||||
momentry_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
file: FileInfo {
|
||||
uuid: file_uuid.to_string(),
|
||||
file_name,
|
||||
file_path,
|
||||
file_size,
|
||||
library,
|
||||
status,
|
||||
},
|
||||
data_sources: DataSources {
|
||||
postgresql: db_stats,
|
||||
qdrant: qdrant_stats,
|
||||
sqlite: SqliteInfo {
|
||||
file: "workspace.sqlite".to_string(),
|
||||
tables: vec!["face_detections".to_string()],
|
||||
total_records: 0,
|
||||
},
|
||||
redis: redis_stats,
|
||||
},
|
||||
processors,
|
||||
};
|
||||
|
||||
std::fs::write(
|
||||
package_dir.join("manifest.json"),
|
||||
serde_json::to_string_pretty(&manifest)?,
|
||||
)?;
|
||||
|
||||
// 10. Generate checksums
|
||||
generate_checksums_internal(&package_dir)?;
|
||||
|
||||
// 11. Create tar.gz
|
||||
let tar_path = PathBuf::from(export_dir).join(format!("{}.momentry.tar.gz", file_uuid));
|
||||
create_tar_gz_internal(&package_dir, &tar_path)?;
|
||||
|
||||
// Clean up directory
|
||||
std::fs::remove_dir_all(&package_dir)?;
|
||||
|
||||
Ok(tar_path)
|
||||
}
|
||||
|
||||
// ─── Helper Functions ────────────────────────────────────────────────────────
|
||||
|
||||
async fn get_library_for_file(pool: &sqlx::PgPool, file_path: &str) -> String {
|
||||
let paths_table = crate::core::db::schema::table_name("upload_paths");
|
||||
let row: Option<(String,)> = sqlx::query_as(
|
||||
&format!(
|
||||
"SELECT name FROM {} WHERE $1 LIKE full_path || '%%' ORDER BY LENGTH(full_path) DESC LIMIT 1",
|
||||
paths_table
|
||||
)
|
||||
)
|
||||
.bind(file_path)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
|
||||
row.map(|r| r.0).unwrap_or_else(|| "unknown".to_string())
|
||||
}
|
||||
|
||||
fn copy_output_files(uuid: &str, output_dir: &str, package_dir: &Path) -> Result<()> {
|
||||
let src_dir = PathBuf::from(output_dir);
|
||||
let dest_dir = package_dir.join("output");
|
||||
|
||||
// Copy JSON files: {uuid}.*.json
|
||||
if let Ok(entries) = std::fs::read_dir(&src_dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
||||
if name.starts_with(&format!("{}.", uuid)) && name.ends_with(".json") {
|
||||
std::fs::copy(&path, dest_dir.join(name))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Copy trace directory: {uuid}/trace_*/
|
||||
let trace_src = src_dir.join(uuid);
|
||||
if trace_src.exists() {
|
||||
let trace_dest = dest_dir.join(uuid);
|
||||
copy_dir_all_internal(&trace_src, &trace_dest)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_identities_if_exist(output_dir: &str, package_dir: &Path) -> Result<()> {
|
||||
let identities_dir = PathBuf::from(output_dir).join("identities");
|
||||
if !identities_dir.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Ok(entries) = std::fs::read_dir(&identities_dir) {
|
||||
for entry in entries.flatten() {
|
||||
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
|
||||
let name = entry.file_name();
|
||||
let src = entry.path();
|
||||
let dest = package_dir.join("identities").join(&name);
|
||||
copy_dir_all_internal(&src, &dest)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn export_postgres_data(pool: &sqlx::PgPool, uuid: &str, package_dir: &Path) -> Result<PostgresqlInfo> {
|
||||
let db_dir = package_dir.join("db");
|
||||
let mut total_records = 0;
|
||||
let mut tables = Vec::new();
|
||||
|
||||
// Helper to export a table
|
||||
async fn export_table(pool: &sqlx::PgPool, db_dir: &Path, table: &str, where_col: &str, uuid: &str) -> Result<usize> {
|
||||
let table_name = crate::core::db::schema::table_name(table);
|
||||
let rows: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
|
||||
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {} WHERE {} = $1) v", table_name, where_col)
|
||||
)
|
||||
.bind(uuid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
let count = rows.len();
|
||||
std::fs::write(
|
||||
db_dir.join(format!("{}.json", table)),
|
||||
serde_json::to_string_pretty(&rows)?,
|
||||
)?;
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
// Export tables
|
||||
if let Ok(count) = export_table(pool, &db_dir, "videos", "file_uuid", uuid).await {
|
||||
total_records += count;
|
||||
tables.push("videos".to_string());
|
||||
}
|
||||
|
||||
if let Ok(count) = export_table(pool, &db_dir, "processor_results", "file_uuid", uuid).await {
|
||||
total_records += count;
|
||||
tables.push("processor_results".to_string());
|
||||
}
|
||||
|
||||
if let Ok(count) = export_table(pool, &db_dir, "monitor_jobs", "uuid", uuid).await {
|
||||
total_records += count;
|
||||
tables.push("monitor_jobs".to_string());
|
||||
}
|
||||
|
||||
if let Ok(count) = export_table(pool, &db_dir, "trace_profiles", "file_uuid", uuid).await {
|
||||
total_records += count;
|
||||
tables.push("trace_profiles".to_string());
|
||||
}
|
||||
|
||||
if let Ok(count) = export_table(pool, &db_dir, "tkg_nodes", "file_uuid", uuid).await {
|
||||
total_records += count;
|
||||
tables.push("tkg_nodes".to_string());
|
||||
}
|
||||
|
||||
if let Ok(count) = export_table(pool, &db_dir, "chunk", "file_uuid", uuid).await {
|
||||
total_records += count;
|
||||
tables.push("chunks".to_string());
|
||||
}
|
||||
|
||||
// Identities (simplified - just export all for now)
|
||||
let id_table = crate::core::db::schema::table_name("identities");
|
||||
let identities: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
|
||||
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {}) v LIMIT 100", id_table)
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
if !identities.is_empty() {
|
||||
total_records += identities.len();
|
||||
tables.push("identities".to_string());
|
||||
std::fs::write(db_dir.join("identities.json"), serde_json::to_string_pretty(&identities)?)?;
|
||||
}
|
||||
|
||||
Ok(PostgresqlInfo { tables, total_records })
|
||||
}
|
||||
|
||||
pub async fn get_processor_results(pool: &sqlx::PgPool, uuid: &str) -> Result<HashMap<String, ProcessorInfo>> {
|
||||
let table = crate::core::db::schema::table_name("processor_results");
|
||||
let rows: Vec<(String, String)> = sqlx::query_as(
|
||||
&format!("SELECT processor, status FROM {} WHERE file_uuid = $1", table)
|
||||
)
|
||||
.bind(uuid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
let mut processors = HashMap::new();
|
||||
for (proc_type, status) in rows {
|
||||
let output_file = format!("{}.{}.json", uuid, proc_type);
|
||||
processors.insert(proc_type, ProcessorInfo {
|
||||
status,
|
||||
file: output_file,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(processors)
|
||||
}
|
||||
|
||||
pub fn copy_dir_all_internal(src: &Path, dest: &Path) -> Result<()> {
|
||||
std::fs::create_dir_all(dest)?;
|
||||
for entry in std::fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let dest_path = dest.join(entry.file_name());
|
||||
if path.is_dir() {
|
||||
copy_dir_all_internal(&path, &dest_path)?;
|
||||
} else {
|
||||
std::fs::copy(&path, &dest_path)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn generate_checksums_internal(package_dir: &Path) -> Result<()> {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::io::Read;
|
||||
|
||||
let mut lines = Vec::new();
|
||||
|
||||
for entry in walkdir::WalkDir::new(package_dir)
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.file_type().is_file())
|
||||
{
|
||||
let path = entry.path();
|
||||
if path.file_name().map(|n| n == "checksums.sha256").unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let relative = path.strip_prefix(package_dir)?;
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
let mut buffer = Vec::new();
|
||||
file.read_to_end(&mut buffer)?;
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
buffer.hash(&mut hasher);
|
||||
let hash = hasher.finish();
|
||||
|
||||
lines.push(format!("{:016x} {}", hash, relative.to_string_lossy()));
|
||||
}
|
||||
|
||||
std::fs::write(package_dir.join("checksums.sha256"), lines.join("\n"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_tar_gz_internal(source_dir: &Path, output_path: &Path) -> Result<()> {
|
||||
use flate2::write::GzEncoder;
|
||||
use flate2::Compression;
|
||||
use tar::Builder;
|
||||
|
||||
let file = std::fs::File::create(output_path)?;
|
||||
let encoder = GzEncoder::new(file, Compression::default());
|
||||
let mut tar = Builder::new(encoder);
|
||||
|
||||
tar.append_dir_all("", source_dir)?;
|
||||
tar.finish()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn extract_package_internal(package_path: &std::path::Path, dest_dir: &std::path::Path) -> Result<()> {
|
||||
use flate2::read::GzDecoder;
|
||||
use tar::Archive;
|
||||
|
||||
if dest_dir.exists() {
|
||||
std::fs::remove_dir_all(dest_dir)?;
|
||||
}
|
||||
|
||||
let tar_gz = std::fs::File::open(package_path)?;
|
||||
let tar = GzDecoder::new(tar_gz);
|
||||
let mut archive = Archive::new(tar);
|
||||
|
||||
archive.unpack(dest_dir)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -351,6 +351,7 @@ impl FileProfile {
|
||||
let path = Self::profile_path(output_dir, &self.file_uuid);
|
||||
let json =
|
||||
serde_json::to_string_pretty(self).context("Failed to serialize file profile")?;
|
||||
let json = crate::core::json_debug::append_debug_footer(json, &path);
|
||||
std::fs::write(&path, json)
|
||||
.with_context(|| format!("Failed to write profile to {}", path.display()))?;
|
||||
tracing::debug!("[FileProfile] Saved profile for {}", self.file_uuid);
|
||||
@@ -670,6 +671,7 @@ impl FaceTraceProfile {
|
||||
let json = serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*self)?))
|
||||
.context("Failed to serialize FaceTraceProfile")?;
|
||||
let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id);
|
||||
let json = crate::core::json_debug::append_debug_footer(json, &profile_path);
|
||||
std::fs::write(&profile_path, json)
|
||||
.with_context(|| format!("Failed to write {}", profile_path.display()))?;
|
||||
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
/// Folder batch export/import
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
// ─── Folder Manifest ─────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FolderManifest {
|
||||
pub version: String,
|
||||
#[serde(rename = "type")]
|
||||
pub export_type: String,
|
||||
pub exported_at: String,
|
||||
pub momentry_version: String,
|
||||
pub folder: FolderInfo,
|
||||
pub files: Vec<FileInfo>,
|
||||
pub total_records: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FolderInfo {
|
||||
pub name: String,
|
||||
pub original_path: String,
|
||||
pub library: String,
|
||||
pub file_count: usize,
|
||||
pub total_size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct FileInfo {
|
||||
pub uuid: String,
|
||||
pub file_name: String,
|
||||
pub file_path: String,
|
||||
pub file_size: u64,
|
||||
pub status: String,
|
||||
pub processors: HashMap<String, String>,
|
||||
}
|
||||
|
||||
// ─── Import Result ───────────────────────────────────────────────────────────
|
||||
|
||||
pub struct FolderImportResult {
|
||||
pub folder_name: String,
|
||||
pub imported_files: usize,
|
||||
pub total_records: usize,
|
||||
}
|
||||
|
||||
// ─── Export Function ─────────────────────────────────────────────────────────
|
||||
|
||||
pub async fn export_folder(
|
||||
pool: &sqlx::PgPool,
|
||||
folder_path: &str,
|
||||
library_name: &str,
|
||||
export_dir: &str,
|
||||
) -> Result<(PathBuf, usize)> {
|
||||
// Find all files in folder
|
||||
let videos_table = crate::core::db::schema::table_name("videos");
|
||||
let files: Vec<(String, String, String, Option<i64>, String)> = sqlx::query_as(
|
||||
&format!(
|
||||
"SELECT file_uuid, file_name, file_path, file_size, status FROM {} WHERE file_path LIKE $1 || '%%'",
|
||||
videos_table
|
||||
)
|
||||
)
|
||||
.bind(folder_path.trim_end_matches('/'))
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
if files.is_empty() {
|
||||
return Err(anyhow::anyhow!("No files found in folder"));
|
||||
}
|
||||
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let package_dir = PathBuf::from(export_dir).join(format!("{}.momentry", library_name));
|
||||
|
||||
if package_dir.exists() {
|
||||
std::fs::remove_dir_all(&package_dir)?;
|
||||
}
|
||||
|
||||
// Create directory structure
|
||||
std::fs::create_dir_all(&package_dir)?;
|
||||
std::fs::create_dir_all(package_dir.join("videos"))?;
|
||||
std::fs::create_dir_all(package_dir.join("output"))?;
|
||||
std::fs::create_dir_all(package_dir.join("identities"))?;
|
||||
std::fs::create_dir_all(package_dir.join("db"))?;
|
||||
std::fs::create_dir_all(package_dir.join("qdrant"))?;
|
||||
std::fs::create_dir_all(package_dir.join("redis"))?;
|
||||
|
||||
let mut manifest_files = Vec::new();
|
||||
let mut total_size = 0u64;
|
||||
let mut total_records = 0usize;
|
||||
|
||||
// Process each file
|
||||
for (uuid, file_name, file_path, file_size, status) in &files {
|
||||
let fsize = file_size.unwrap_or(0) as u64;
|
||||
total_size += fsize;
|
||||
|
||||
// Copy video
|
||||
let video_src = PathBuf::from(file_path);
|
||||
if video_src.exists() {
|
||||
let dest = package_dir.join("videos").join(file_name);
|
||||
std::fs::copy(&video_src, &dest)?;
|
||||
}
|
||||
|
||||
// Copy output files
|
||||
copy_file_output(uuid, output_dir, &package_dir)?;
|
||||
|
||||
// Export DB records
|
||||
let records = export_file_db_records(pool, uuid, &package_dir).await?;
|
||||
total_records += records;
|
||||
|
||||
// Get processors
|
||||
let processors = crate::core::export::get_processor_results(pool, uuid).await?;
|
||||
let proc_map: HashMap<String, String> = processors.iter()
|
||||
.map(|(k, v)| (k.clone(), v.status.clone()))
|
||||
.collect();
|
||||
|
||||
manifest_files.push(FileInfo {
|
||||
uuid: uuid.clone(),
|
||||
file_name: file_name.clone(),
|
||||
file_path: file_path.clone(),
|
||||
file_size: fsize,
|
||||
status: status.clone(),
|
||||
processors: proc_map,
|
||||
});
|
||||
}
|
||||
|
||||
// Copy shared identities
|
||||
copy_shared_identities(output_dir, &package_dir)?;
|
||||
|
||||
// Create folder manifest
|
||||
let manifest = FolderManifest {
|
||||
version: "1.0".to_string(),
|
||||
export_type: "folder".to_string(),
|
||||
exported_at: chrono::Utc::now().to_rfc3339(),
|
||||
momentry_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
folder: FolderInfo {
|
||||
name: library_name.to_string(),
|
||||
original_path: folder_path.to_string(),
|
||||
library: library_name.to_string(),
|
||||
file_count: files.len(),
|
||||
total_size,
|
||||
},
|
||||
files: manifest_files,
|
||||
total_records,
|
||||
};
|
||||
|
||||
std::fs::write(
|
||||
package_dir.join("manifest.json"),
|
||||
serde_json::to_string_pretty(&manifest)?,
|
||||
)?;
|
||||
|
||||
// Generate checksums
|
||||
crate::core::export::generate_checksums_internal(&package_dir)?;
|
||||
|
||||
// Create tar.gz
|
||||
let folder_name = PathBuf::from(folder_path)
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| library_name.to_string());
|
||||
|
||||
let tar_path = PathBuf::from(export_dir).join(format!("{}.momentry.tar.gz", folder_name));
|
||||
crate::core::export::create_tar_gz_internal(&package_dir, &tar_path)?;
|
||||
|
||||
// Clean up
|
||||
std::fs::remove_dir_all(&package_dir)?;
|
||||
|
||||
Ok((tar_path, files.len()))
|
||||
}
|
||||
|
||||
// ─── Import Function ─────────────────────────────────────────────────────────
|
||||
|
||||
pub async fn import_folder(
|
||||
pool: &sqlx::PgPool,
|
||||
package_path: &str,
|
||||
target_folder_path: Option<&str>,
|
||||
force: bool,
|
||||
) -> Result<FolderImportResult> {
|
||||
let pkg_path = PathBuf::from(package_path);
|
||||
let temp_dir = pkg_path.parent().unwrap_or(std::path::Path::new("."))
|
||||
.join(pkg_path.file_stem().unwrap_or_default());
|
||||
|
||||
// Extract
|
||||
crate::core::export::extract_package_internal(&pkg_path, &temp_dir)?;
|
||||
|
||||
// Read manifest
|
||||
let manifest_str = std::fs::read_to_string(temp_dir.join("manifest.json"))?;
|
||||
let manifest: FolderManifest = serde_json::from_str(&manifest_str)?;
|
||||
|
||||
let mut imported_files = 0;
|
||||
let mut total_records = 0;
|
||||
|
||||
// Import each file
|
||||
for file_info in &manifest.files {
|
||||
// Check if exists
|
||||
let videos_table = crate::core::db::schema::table_name("videos");
|
||||
let exists: Option<(i32,)> = sqlx::query_as(
|
||||
&format!("SELECT id FROM {} WHERE file_uuid = $1", videos_table)
|
||||
)
|
||||
.bind(&file_info.uuid)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
|
||||
if exists.is_some() && !force {
|
||||
tracing::warn!("[Folder Import] Skipping existing file: {}", file_info.uuid);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Delete existing if force
|
||||
if exists.is_some() {
|
||||
delete_existing_records(pool, &file_info.uuid).await?;
|
||||
}
|
||||
|
||||
// Restore video
|
||||
let video_src = temp_dir.join("videos").join(&file_info.file_name);
|
||||
let video_dest = target_folder_path
|
||||
.map(|p| PathBuf::from(p).join(&file_info.file_name))
|
||||
.unwrap_or_else(|| PathBuf::from(&file_info.file_path));
|
||||
|
||||
if video_src.exists() {
|
||||
if let Some(parent) = video_dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::copy(&video_src, &video_dest)?;
|
||||
}
|
||||
|
||||
// Restore output files
|
||||
restore_file_output(&temp_dir, &file_info.uuid)?;
|
||||
|
||||
// Restore DB records
|
||||
let records = restore_file_db_records(pool, &temp_dir, &file_info.uuid).await?;
|
||||
total_records += records;
|
||||
|
||||
imported_files += 1;
|
||||
}
|
||||
|
||||
// Restore identities
|
||||
restore_shared_identities(&temp_dir)?;
|
||||
|
||||
// Clean up
|
||||
let _ = std::fs::remove_dir_all(&temp_dir);
|
||||
|
||||
Ok(FolderImportResult {
|
||||
folder_name: manifest.folder.name,
|
||||
imported_files,
|
||||
total_records,
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Helper Functions ────────────────────────────────────────────────────────
|
||||
|
||||
fn copy_file_output(uuid: &str, output_dir: &str, package_dir: &PathBuf) -> Result<()> {
|
||||
let src_dir = PathBuf::from(output_dir);
|
||||
let dest_dir = package_dir.join("output");
|
||||
|
||||
// Copy JSON files
|
||||
if let Ok(entries) = std::fs::read_dir(&src_dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
||||
if name.starts_with(&format!("{}.", uuid)) && name.ends_with(".json") {
|
||||
std::fs::copy(&path, dest_dir.join(name))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Copy trace directory
|
||||
let trace_src = src_dir.join(uuid);
|
||||
if trace_src.exists() {
|
||||
let trace_dest = dest_dir.join(uuid);
|
||||
crate::core::export::copy_dir_all_internal(&trace_src, &trace_dest)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_shared_identities(output_dir: &str, package_dir: &PathBuf) -> Result<()> {
|
||||
let identities_dir = PathBuf::from(output_dir).join("identities");
|
||||
if !identities_dir.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let dest_identities = package_dir.join("identities");
|
||||
if let Ok(entries) = std::fs::read_dir(&identities_dir) {
|
||||
for entry in entries.flatten() {
|
||||
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
|
||||
let name = entry.file_name();
|
||||
let src = entry.path();
|
||||
let dest = dest_identities.join(&name);
|
||||
if !dest.exists() {
|
||||
crate::core::export::copy_dir_all_internal(&src, &dest)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn export_file_db_records(pool: &sqlx::PgPool, uuid: &str, package_dir: &PathBuf) -> Result<usize> {
|
||||
let db_dir = package_dir.join("db");
|
||||
let mut total = 0;
|
||||
|
||||
let tables = ["videos", "processor_results", "monitor_jobs", "trace_profiles", "tkg_nodes", "chunk"];
|
||||
|
||||
for table in tables {
|
||||
let table_name = crate::core::db::schema::table_name(table);
|
||||
let col = if table == "monitor_jobs" { "uuid" } else { "file_uuid" };
|
||||
|
||||
let rows: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
|
||||
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {} WHERE {} = $1) v", table_name, col)
|
||||
)
|
||||
.bind(uuid)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
if !rows.is_empty() {
|
||||
std::fs::write(
|
||||
db_dir.join(format!("{}.json", table)),
|
||||
serde_json::to_string_pretty(&rows)?,
|
||||
)?;
|
||||
total += rows.len();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
async fn delete_existing_records(pool: &sqlx::PgPool, uuid: &str) -> Result<()> {
|
||||
let tables = [
|
||||
("processor_results", "file_uuid"),
|
||||
("monitor_jobs", "uuid"),
|
||||
("trace_profiles", "file_uuid"),
|
||||
("tkg_nodes", "file_uuid"),
|
||||
("tkg_edges", "file_uuid"),
|
||||
("chunk", "file_uuid"),
|
||||
("face_detections", "file_uuid"),
|
||||
("videos", "file_uuid"),
|
||||
];
|
||||
|
||||
for (table, col) in tables {
|
||||
let table_name = crate::core::db::schema::table_name(table);
|
||||
let _ = sqlx::query(&format!("DELETE FROM {} WHERE {} = $1", table_name, col))
|
||||
.bind(uuid)
|
||||
.execute(pool)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_file_output(temp_dir: &PathBuf, uuid: &str) -> Result<()> {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let dest_dir = PathBuf::from(output_dir);
|
||||
|
||||
let src_output = temp_dir.join("output");
|
||||
if !src_output.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Copy JSON files
|
||||
if let Ok(entries) = std::fs::read_dir(&src_output) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() {
|
||||
let dest = dest_dir.join(path.file_name().unwrap());
|
||||
std::fs::copy(&path, &dest)?;
|
||||
} else if path.is_dir() {
|
||||
if path.file_name().map(|n| n == uuid).unwrap_or(false) {
|
||||
let dest = dest_dir.join(uuid);
|
||||
crate::core::export::copy_dir_all_internal(&path, &dest)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn restore_file_db_records(pool: &sqlx::PgPool, temp_dir: &PathBuf, uuid: &str) -> Result<usize> {
|
||||
let db_dir = temp_dir.join("db");
|
||||
if !db_dir.exists() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut restored = 0;
|
||||
|
||||
let tables = ["videos", "processor_results", "monitor_jobs", "trace_profiles", "tkg_nodes", "chunk"];
|
||||
|
||||
for table in tables {
|
||||
let json_path = db_dir.join(format!("{}.json", table));
|
||||
if !json_path.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let json_str = std::fs::read_to_string(&json_path)?;
|
||||
let records: Vec<serde_json::Value> = serde_json::from_str(&json_str)?;
|
||||
let table_name = crate::core::db::schema::table_name(table);
|
||||
|
||||
for record in records {
|
||||
// Remove id column (auto-increment with NOT NULL)
|
||||
let mut record = record.clone();
|
||||
if let Some(obj) = record.as_object_mut() {
|
||||
obj.remove("id");
|
||||
}
|
||||
|
||||
if record.as_object().map(|o| o.is_empty()).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Build explicit INSERT with columns (excluding id)
|
||||
let columns: Vec<String> = record.as_object().unwrap().keys()
|
||||
.map(|k| format!("\"{}\"", k)).collect();
|
||||
let cols_str = columns.join(", ");
|
||||
|
||||
// Build values with proper type handling
|
||||
let values: Vec<String> = record.as_object().unwrap().values()
|
||||
.map(|v| match v {
|
||||
serde_json::Value::Null => "NULL".to_string(),
|
||||
serde_json::Value::Bool(b) => b.to_string(),
|
||||
serde_json::Value::Number(n) => n.to_string(),
|
||||
serde_json::Value::String(s) => format!("'{}'", s.replace("'", "''")),
|
||||
serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
|
||||
format!("'{}'::jsonb", serde_json::to_string(v).unwrap_or_else(|_| "null".to_string()).replace("'", "''"))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let vals_str = values.join(", ");
|
||||
|
||||
let sql = format!(
|
||||
"INSERT INTO {} ({}) VALUES ({})",
|
||||
table_name, cols_str, vals_str
|
||||
);
|
||||
|
||||
let result = sqlx::query(&sql)
|
||||
.execute(pool)
|
||||
.await;
|
||||
|
||||
if result.is_ok() {
|
||||
restored += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(restored)
|
||||
}
|
||||
|
||||
fn restore_shared_identities(temp_dir: &PathBuf) -> Result<()> {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let dest_identities = PathBuf::from(output_dir).join("identities");
|
||||
|
||||
let src_identities = temp_dir.join("identities");
|
||||
if !src_identities.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !dest_identities.exists() {
|
||||
std::fs::create_dir_all(&dest_identities)?;
|
||||
}
|
||||
|
||||
if let Ok(entries) = std::fs::read_dir(&src_identities) {
|
||||
for entry in entries.flatten() {
|
||||
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
|
||||
let name = entry.file_name();
|
||||
let dest = dest_identities.join(&name);
|
||||
if !dest.exists() {
|
||||
crate::core::export::copy_dir_all_internal(&entry.path(), &dest)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+1
-1
@@ -362,7 +362,7 @@ async fn check_dependencies(env: &std::collections::HashMap<String, String>, opt
|
||||
}
|
||||
|
||||
let redis_url = env.get("REDIS_URL").cloned()
|
||||
.unwrap_or_else(|| "redis://localhost:6379".into());
|
||||
.unwrap_or_else(|| crate::core::config::REDIS_URL.clone());
|
||||
match check_redis(&redis_url).await {
|
||||
Ok(_) => ok(opts, "Redis"),
|
||||
Err(e) => warn(opts, &format!("Redis: {}", e)),
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//! JSON Debug Metadata — 在每個輸出 JSON 的最下方加上本次寫入的絕對檔案位置,
|
||||
//! 方便開啟 JSON 內容時直接看到來源檔案路徑,利於 debug。
|
||||
//!
|
||||
//! 產生的區塊範例(出現在最下方):
|
||||
//! ```json
|
||||
//! "_debug": {
|
||||
//! "absolute_path": "/Users/accusys/momentry/output/demo/xxx.face.json",
|
||||
//! "written_at_unix": 1763000000
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use serde::Serialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// 取得檔案的 canonical 絕對路徑。
|
||||
/// 檔案可能尚未寫入(我們是在寫檔前產生 footer),
|
||||
/// 因此先嘗試 canonicalize 檔案本身,失敗則 canonicalize 父目錄再接上檔名。
|
||||
fn absolute_path_string(path: &Path) -> String {
|
||||
if let Ok(canon) = std::fs::canonicalize(path) {
|
||||
return canon.to_string_lossy().to_string();
|
||||
}
|
||||
if let (Some(parent), Some(file)) = (path.parent(), path.file_name()) {
|
||||
if let Ok(canon_parent) = std::fs::canonicalize(parent) {
|
||||
return canon_parent.join(file).to_string_lossy().to_string();
|
||||
}
|
||||
}
|
||||
// 父目錄也不存在時,退回輸入路徑(至少保證可追蹤來源)
|
||||
path.to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
/// 產生 `_debug` 區塊內容。`pretty` 決定縮排樣式(pretty=多行縮排 / compact=單行)。
|
||||
fn debug_footer(path: &Path, pretty: bool) -> String {
|
||||
let abs_str = serde_json::to_string(&absolute_path_string(path))
|
||||
.unwrap_or_else(|_| "\"\"".to_string());
|
||||
let ts = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
|
||||
if pretty {
|
||||
format!(
|
||||
" \"_debug\": {{\n \"absolute_path\": {},\n \"written_at_unix\": {}\n }}",
|
||||
abs_str, ts
|
||||
)
|
||||
} else {
|
||||
format!("\"_debug\":{{\"absolute_path\":{},\"written_at_unix\":{}}}", abs_str, ts)
|
||||
}
|
||||
}
|
||||
|
||||
/// 在 JSON 字串最後一個 `}` 前插入 `_debug` 區塊。
|
||||
/// 自動偵測 pretty(含換行)或 compact 輸出,footer 樣式跟隨原文。
|
||||
pub fn append_debug_footer(json: String, path: &Path) -> String {
|
||||
let pretty = json.contains('\n');
|
||||
let footer = debug_footer(path, pretty);
|
||||
|
||||
if json.trim_end() == "{}" || json.trim_end() == "{ }" {
|
||||
// 空物件:直接放 footer
|
||||
if pretty {
|
||||
return format!("{{\n{}\n}}", footer);
|
||||
}
|
||||
return format!("{{{}}}", footer);
|
||||
}
|
||||
|
||||
if json.trim_end().ends_with('}') {
|
||||
let mut out = json;
|
||||
while out.ends_with('\n') || out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
out.pop(); // 移除最後的 '}'
|
||||
if pretty {
|
||||
out.push_str(",\n");
|
||||
out.push_str(&footer);
|
||||
out.push_str("\n}");
|
||||
} else {
|
||||
out.push(',');
|
||||
out.push_str(&footer);
|
||||
out.push('}');
|
||||
}
|
||||
out
|
||||
} else {
|
||||
// 非預期格式(不是物件結尾),原樣返回避免破壞檔案
|
||||
json
|
||||
}
|
||||
}
|
||||
|
||||
/// 序列化(pretty)+ 加上 debug footer + 寫入檔案。
|
||||
pub fn write_json_with_debug<T: Serialize, P: AsRef<Path>>(
|
||||
path: P,
|
||||
value: &T,
|
||||
) -> std::io::Result<()> {
|
||||
let json = serde_json::to_string_pretty(value)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
let json = append_debug_footer(json, path.as_ref());
|
||||
std::fs::write(path.as_ref(), json)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn footer_pretty_json_is_valid_and_at_bottom() {
|
||||
let v = json!({"a": 1, "b": [1, 2], "nested": {"x": 1.23456}});
|
||||
let s = serde_json::to_string_pretty(&v).unwrap();
|
||||
let out = append_debug_footer(s, Path::new("/tmp/test.face.json"));
|
||||
|
||||
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
|
||||
let debug = parsed.get("_debug").expect("_debug 應存在");
|
||||
// /tmp 在 macOS 是 symlink → canonical 後為 /private/tmp,
|
||||
// 因此只斷言「絕對路徑 + 正確檔名」,不寫死完整字串
|
||||
let abs = debug["absolute_path"].as_str().expect("absolute_path 應為字串");
|
||||
assert!(abs.starts_with('/'), "應為絕對路徑:{}", abs);
|
||||
assert!(abs.ends_with("test.face.json"), "檔名應正確:{}", abs);
|
||||
assert!(debug["written_at_unix"].is_u64());
|
||||
|
||||
// _debug 必須在最下方(最後一個鍵)
|
||||
let last_key_pos = out.rfind("\"_debug\"").unwrap();
|
||||
assert!(
|
||||
last_key_pos > out.rfind("\"nested\"").unwrap(),
|
||||
"_debug 應出現在所有原有鍵之後"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footer_compact_json_is_valid() {
|
||||
let out = append_debug_footer("{\"a\":1,\"b\":2}".to_string(), Path::new("/tmp/x.json"));
|
||||
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
|
||||
assert_eq!(parsed["a"], 1);
|
||||
assert!(parsed.get("_debug").is_some());
|
||||
assert!(!out.contains('\n'), "compact 輸入應維持 compact 樣式");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footer_empty_object() {
|
||||
let out = append_debug_footer("{}".to_string(), Path::new("/tmp/x.json"));
|
||||
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
|
||||
assert!(parsed.get("_debug").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_json_with_debug_roundtrip() {
|
||||
let dir = std::env::temp_dir().join("json_debug_test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("roundtrip_test.json");
|
||||
|
||||
let v = json!({"file_uuid": "abc123", "status": "completed"});
|
||||
write_json_with_debug(&path, &v).unwrap();
|
||||
|
||||
let content = std::fs::read_to_string(&path).unwrap();
|
||||
let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
|
||||
assert_eq!(parsed["file_uuid"], "abc123");
|
||||
assert_eq!(
|
||||
parsed["_debug"]["absolute_path"],
|
||||
path.canonicalize().unwrap().to_string_lossy().to_string(),
|
||||
"absolute_path 應為檔案的 canonical 絕對路徑"
|
||||
);
|
||||
std::fs::remove_file(&path).ok();
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,36 @@ pub fn write_file_pretty_rounded<T: Serialize>(
|
||||
decimals: usize,
|
||||
) -> anyhow::Result<()> {
|
||||
let json = to_string_pretty_rounded(value, decimals)?;
|
||||
// 在 JSON 最下方加上本次寫入的絕對檔案位置(debug 用)
|
||||
let json = crate::core::json_debug::append_debug_footer(json, std::path::Path::new(path));
|
||||
std::fs::write(path, json)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 寫入標準化 JSON(含 _meta 和 _debug)
|
||||
pub fn write_file_standard<T: Serialize>(
|
||||
value: &T,
|
||||
path: &str,
|
||||
decimals: usize,
|
||||
processor_name: &str,
|
||||
processor_tool: &str,
|
||||
processor_version: &str,
|
||||
file_uuid: &str,
|
||||
file_path: &str,
|
||||
file_name: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let json = to_string_pretty_rounded(value, decimals)?;
|
||||
// 加上 _meta 和 _debug
|
||||
let json = crate::core::json_standardize::append_meta_and_debug(
|
||||
json,
|
||||
std::path::Path::new(path),
|
||||
processor_name,
|
||||
processor_tool,
|
||||
processor_version,
|
||||
file_uuid,
|
||||
file_path,
|
||||
file_name,
|
||||
);
|
||||
std::fs::write(path, json)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! JSON 標準化 Metadata — 在每個輸出 JSON 加上 `_meta` 和 `_debug` 區塊
|
||||
//!
|
||||
//! ## 標準格式
|
||||
//! ```json
|
||||
//! {
|
||||
//! "_meta": {
|
||||
//! "schema_version": "1.0",
|
||||
//! "processor": {"name": "face", "tool": "swift_face", "version": "1.0.0"},
|
||||
//! "source": {"file_uuid": "xxx", "file_path": "/path/to/video.mp4", "file_name": "025.mp4"},
|
||||
//! "timestamps": {"created_at": "ISO8601", "completed_at": "ISO8601"},
|
||||
//! "pipeline": {"scan_id": "", "worker_id": "", "stage": "deep_scan"}
|
||||
//! },
|
||||
//! "_debug": {
|
||||
//! "absolute_path": "/path/to/output/xxx.face.json",
|
||||
//! "written_at_unix": 1794674568,
|
||||
//! "output_dir": "/Users/accusys/momentry/output/demo"
|
||||
//! },
|
||||
//! "status": "completed",
|
||||
//! "data": { ... }
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use serde::Serialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// 處理器資訊
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ProcessorMeta {
|
||||
pub name: String,
|
||||
pub tool: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// 來源資訊
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SourceMeta {
|
||||
pub file_uuid: String,
|
||||
pub file_path: String,
|
||||
pub file_name: String,
|
||||
}
|
||||
|
||||
/// 時間戳記
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TimestampsMeta {
|
||||
pub created_at: String,
|
||||
pub completed_at: String,
|
||||
}
|
||||
|
||||
/// Pipeline 資訊
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PipelineMeta {
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub scan_id: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub worker_id: String,
|
||||
pub stage: String,
|
||||
}
|
||||
|
||||
/// 完整 _meta 區塊
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct MetaFooter {
|
||||
pub schema_version: String,
|
||||
pub processor: ProcessorMeta,
|
||||
pub source: SourceMeta,
|
||||
pub timestamps: TimestampsMeta,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pipeline: Option<PipelineMeta>,
|
||||
}
|
||||
|
||||
/// _debug 區塊
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DebugFooter {
|
||||
pub absolute_path: String,
|
||||
pub written_at_unix: u64,
|
||||
pub output_dir: String,
|
||||
}
|
||||
|
||||
/// 取得絕對路徑
|
||||
fn absolute_path_string(path: &Path) -> String {
|
||||
if let Ok(canon) = std::fs::canonicalize(path) {
|
||||
return canon.to_string_lossy().to_string();
|
||||
}
|
||||
if let (Some(parent), Some(file)) = (path.parent(), path.file_name()) {
|
||||
if let Ok(canon_parent) = std::fs::canonicalize(parent) {
|
||||
return canon_parent.join(file).to_string_lossy().to_string();
|
||||
}
|
||||
}
|
||||
path.to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
/// 建立 _meta 區塊
|
||||
pub fn create_meta(
|
||||
processor_name: &str,
|
||||
processor_tool: &str,
|
||||
processor_version: &str,
|
||||
file_uuid: &str,
|
||||
file_path: &str,
|
||||
file_name: &str,
|
||||
) -> MetaFooter {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
MetaFooter {
|
||||
schema_version: "1.0".to_string(),
|
||||
processor: ProcessorMeta {
|
||||
name: processor_name.to_string(),
|
||||
tool: processor_tool.to_string(),
|
||||
version: processor_version.to_string(),
|
||||
},
|
||||
source: SourceMeta {
|
||||
file_uuid: file_uuid.to_string(),
|
||||
file_path: file_path.to_string(),
|
||||
file_name: file_name.to_string(),
|
||||
},
|
||||
timestamps: TimestampsMeta {
|
||||
created_at: now.clone(),
|
||||
completed_at: now,
|
||||
},
|
||||
pipeline: Some(PipelineMeta {
|
||||
scan_id: std::env::var("MOMENTRY_SCAN_ID").unwrap_or_default(),
|
||||
worker_id: std::env::var("MOMENTRY_WORKER_ID").unwrap_or_default(),
|
||||
stage: "deep_scan".to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// 建立 _debug 區塊
|
||||
pub fn create_debug(path: &Path) -> DebugFooter {
|
||||
DebugFooter {
|
||||
absolute_path: absolute_path_string(path),
|
||||
written_at_unix: SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0),
|
||||
output_dir: std::env::var("MOMENTRY_OUTPUT_DIR")
|
||||
.unwrap_or_else(|_| "output/demo".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 在 JSON 字串中加入 `_meta` 和 `_debug` 區塊
|
||||
pub fn append_meta_and_debug(
|
||||
json: String,
|
||||
path: &Path,
|
||||
processor_name: &str,
|
||||
processor_tool: &str,
|
||||
processor_version: &str,
|
||||
file_uuid: &str,
|
||||
file_path: &str,
|
||||
file_name: &str,
|
||||
) -> String {
|
||||
let pretty = json.contains('\n');
|
||||
|
||||
// 建立 _meta JSON
|
||||
let meta = create_meta(processor_name, processor_tool, processor_version, file_uuid, file_path, file_name);
|
||||
let meta_json = serde_json::to_string(&meta).unwrap_or_else(|_| "{}".to_string());
|
||||
|
||||
// 建立 _debug JSON
|
||||
let debug = create_debug(path);
|
||||
let debug_json = serde_json::to_string(&debug).unwrap_or_else(|_| "{}".to_string());
|
||||
|
||||
// 組合 footer
|
||||
let footer = if pretty {
|
||||
format!(
|
||||
" \"_meta\": {},\n \"_debug\": {}",
|
||||
meta_json, debug_json
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"\"_meta\":{},\"_debug\":{}",
|
||||
meta_json, debug_json
|
||||
)
|
||||
};
|
||||
|
||||
// 插入到 JSON 結尾
|
||||
if json.trim_end() == "{}" || json.trim_end() == "{ }" {
|
||||
if pretty {
|
||||
return format!("{{\n{}\n}}", footer);
|
||||
}
|
||||
return format!("{{{}}}", footer);
|
||||
}
|
||||
|
||||
if json.trim_end().ends_with('}') {
|
||||
let mut out = json;
|
||||
while out.ends_with('\n') || out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
out.pop(); // 移除最後的 '}'
|
||||
if pretty {
|
||||
out.push_str(",\n");
|
||||
out.push_str(&footer);
|
||||
out.push_str("\n}");
|
||||
} else {
|
||||
out.push(',');
|
||||
out.push_str(&footer);
|
||||
out.push('}');
|
||||
}
|
||||
out
|
||||
} else {
|
||||
json
|
||||
}
|
||||
}
|
||||
|
||||
/// 序列化 + 加上 _meta 和 _debug + 寫入檔案
|
||||
pub fn write_json_with_meta_and_debug<T: Serialize, P: AsRef<Path>>(
|
||||
path: P,
|
||||
value: &T,
|
||||
processor_name: &str,
|
||||
processor_tool: &str,
|
||||
processor_version: &str,
|
||||
file_uuid: &str,
|
||||
file_path: &str,
|
||||
file_name: &str,
|
||||
) -> std::io::Result<()> {
|
||||
let json = serde_json::to_string_pretty(value)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
|
||||
let json = append_meta_and_debug(
|
||||
json,
|
||||
path.as_ref(),
|
||||
processor_name,
|
||||
processor_tool,
|
||||
processor_version,
|
||||
file_uuid,
|
||||
file_path,
|
||||
file_name,
|
||||
);
|
||||
|
||||
std::fs::write(path.as_ref(), json)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn meta_and_debug_footer_is_valid() {
|
||||
let v = json!({"status": "completed", "data": {"faces": 10}});
|
||||
let s = serde_json::to_string_pretty(&v).unwrap();
|
||||
|
||||
let out = append_meta_and_debug(
|
||||
s,
|
||||
Path::new("/tmp/test.face.json"),
|
||||
"face",
|
||||
"swift_face",
|
||||
"1.0.0",
|
||||
"abc123",
|
||||
"/path/to/video.mp4",
|
||||
"025.mp4"
|
||||
);
|
||||
|
||||
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
|
||||
|
||||
assert!(parsed.get("_meta").is_some());
|
||||
assert!(parsed.get("_debug").is_some());
|
||||
assert_eq!(parsed["status"], "completed");
|
||||
assert_eq!(parsed["_meta"]["processor"]["name"], "face");
|
||||
assert_eq!(parsed["_meta"]["source"]["file_name"], "025.mp4");
|
||||
}
|
||||
}
|
||||
+18
-8
@@ -32,7 +32,7 @@ struct Choice {
|
||||
}
|
||||
|
||||
pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
|
||||
let req = serde_json::json!({
|
||||
let mut req = serde_json::json!({
|
||||
"model": (*config::llm::SUMMARY_MODEL).clone(),
|
||||
"messages": [
|
||||
{
|
||||
@@ -50,14 +50,24 @@ pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
debug!("Calling LLM: {}", *config::llm::SUMMARY_URL);
|
||||
let (summary_url, summary_model, summary_fallbacks) =
|
||||
crate::core::llm::function_calling::resolve_llm_endpoint("summary")
|
||||
.await
|
||||
.unwrap_or_else(|_| (config::llm::SUMMARY_URL.clone(), config::llm::CHAT_MODEL.clone(), Vec::new()));
|
||||
|
||||
let res = LLM_CLIENT
|
||||
.post(&*config::llm::SUMMARY_URL)
|
||||
.json(&req)
|
||||
.timeout(Duration::from_secs(*config::llm::SUMMARY_TIMEOUT_SECS))
|
||||
.send()
|
||||
.await?;
|
||||
if let Some(obj) = req.as_object_mut() {
|
||||
obj.insert("model".to_string(), serde_json::json!(summary_model));
|
||||
}
|
||||
|
||||
debug!("Calling LLM (summary): {}", summary_url);
|
||||
|
||||
let res = crate::core::llm::function_calling::post_llm_with_fallback(
|
||||
&summary_url,
|
||||
&summary_fallbacks,
|
||||
&req,
|
||||
*config::llm::SUMMARY_TIMEOUT_SECS,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
error!("LLM API error: {}", res.status());
|
||||
|
||||
@@ -114,6 +114,218 @@ pub fn llm_chat_url() -> String {
|
||||
config::llm::CHAT_URL.clone()
|
||||
}
|
||||
|
||||
/// Resolve an LLM endpoint (url, model, fallback_url) by role key.
|
||||
///
|
||||
/// Routing rules — instances are identified by **URL** (not port), so an
|
||||
/// entry may point to a local llama-server (127.0.0.1:8080/8082) or to a
|
||||
/// remote machine's llama-server (e.g. http://192.168.110.203:8080/...) for
|
||||
/// future off-box resource use:
|
||||
/// - `chat` entry defines instance A; `vlm` entry defines instance B.
|
||||
/// `enabled == false` on an entry removes that instance from routing
|
||||
/// entirely (never primary, never fallback).
|
||||
/// - Role primary = the role's configured entry, if its instance is enabled;
|
||||
/// otherwise the other enabled instance is promoted to primary.
|
||||
/// - Fallbacks = the entry's own `fallbacks` list (each may be an internal
|
||||
/// instance or an external machine such as 201/gb10), plus the other
|
||||
/// enabled instance auto-appended when not already listed.
|
||||
/// - `strategy == "round_robin"` → every call rotates the candidate order
|
||||
/// (primary included), pooling all instances' compute for throughput;
|
||||
/// failover still applies to the remaining list.
|
||||
/// Otherwise ("priority") the primary is always tried first.
|
||||
/// - Single enabled instance → everything (chat/vlm/summary) uses that one
|
||||
/// model with no fallback.
|
||||
///
|
||||
/// `key` is one of: "chat", "vlm", "summary".
|
||||
pub async fn resolve_llm_endpoint(key: &str) -> anyhow::Result<(String, String, Vec<String>)> {
|
||||
use crate::core::admin_config::LlmConfig;
|
||||
let chat_cfg = crate::core::admin_config::get_llm_config("chat").await;
|
||||
let vlm_cfg = crate::core::admin_config::get_llm_config("vlm").await;
|
||||
let sum_cfg = crate::core::admin_config::get_llm_config("summary").await;
|
||||
let chat_on = chat_cfg.as_ref().and_then(|c| c.enabled).unwrap_or(true);
|
||||
let vlm_on = vlm_cfg.as_ref().and_then(|c| c.enabled).unwrap_or(true);
|
||||
|
||||
// Env-statics fallback when no admin config entry exists
|
||||
let chat_entry = chat_cfg.unwrap_or_else(|| LlmConfig {
|
||||
url: config::llm::CHAT_URL.clone(),
|
||||
model: config::llm::CHAT_MODEL.clone(),
|
||||
timeout: 0,
|
||||
fallback_url: None,
|
||||
fallbacks: Vec::new(),
|
||||
strategy: None,
|
||||
enabled: Some(true),
|
||||
});
|
||||
let vlm_entry = vlm_cfg.unwrap_or_else(|| LlmConfig {
|
||||
url: config::llm::VISION_URL.clone(),
|
||||
model: config::llm::VISION_MODEL.clone(),
|
||||
timeout: 0,
|
||||
fallback_url: None,
|
||||
fallbacks: Vec::new(),
|
||||
strategy: None,
|
||||
enabled: Some(true),
|
||||
});
|
||||
let sum_entry = sum_cfg.unwrap_or_else(|| LlmConfig {
|
||||
url: config::llm::SUMMARY_URL.clone(),
|
||||
model: config::llm::CHAT_MODEL.clone(),
|
||||
timeout: 0,
|
||||
fallback_url: None,
|
||||
fallbacks: Vec::new(),
|
||||
strategy: None,
|
||||
enabled: Some(true),
|
||||
});
|
||||
|
||||
// Capture instance URLs for the enable-check closure before the entries
|
||||
// are moved into the role selection below.
|
||||
let chat_url_str = chat_entry.url.clone();
|
||||
let vlm_url_str = vlm_entry.url.clone();
|
||||
|
||||
let (role_entry, other_entry) = match key {
|
||||
"vlm" => (vlm_entry, chat_entry.clone()),
|
||||
"summary" => (sum_entry, vlm_entry.clone()),
|
||||
_ => (chat_entry.clone(), vlm_entry),
|
||||
};
|
||||
|
||||
// Instance identity is by URL: each llm_config entry owns the instance it
|
||||
// points to (local or remote machine). Unknown URLs (e.g. a manually added
|
||||
// remote fallback) are treated as enabled.
|
||||
let inst_on = |u: &str| -> bool {
|
||||
if u == chat_url_str {
|
||||
chat_on
|
||||
} else if u == vlm_url_str {
|
||||
vlm_on
|
||||
} else {
|
||||
true
|
||||
}
|
||||
};
|
||||
|
||||
// Candidate list: primary + configured fallbacks (legacy fallback_url
|
||||
// merged in first for backward compat) + the other enabled instance.
|
||||
let mut candidates: Vec<String> = vec![role_entry.url.clone()];
|
||||
if let Some(legacy) = role_entry.fallback_url.clone() {
|
||||
candidates.push(legacy);
|
||||
}
|
||||
candidates.extend(role_entry.fallbacks.iter().cloned());
|
||||
candidates.push(other_entry.url.clone());
|
||||
|
||||
// Filter: drop duplicates, drop entries equal to the primary, drop
|
||||
// disabled instances. Preserve order (priority semantics).
|
||||
let primary = role_entry.url.clone();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
candidates.retain(|u| {
|
||||
u != &primary
|
||||
&& inst_on(u)
|
||||
&& seen.insert(u.clone())
|
||||
});
|
||||
|
||||
// Role's preferred instance disabled → promote the other enabled instance
|
||||
if !inst_on(&role_entry.url) {
|
||||
if !candidates.is_empty() {
|
||||
let new_primary = candidates.remove(0);
|
||||
tracing::warn!(
|
||||
"[LLM] role '{}' primary instance disabled — routing to {}",
|
||||
key, new_primary
|
||||
);
|
||||
return Ok((new_primary, role_entry.model, candidates));
|
||||
}
|
||||
anyhow::bail!("[LLM] role '{}' primary instance disabled and no other enabled instance", key);
|
||||
}
|
||||
|
||||
// Resource constraint: when free memory is too low to keep several
|
||||
// llama-server instances warm, collapse routing to a single instance
|
||||
// (no fallbacks, no rotation).
|
||||
if !candidates.is_empty() && crate::core::dynamic_concurrency::memory_constrained() {
|
||||
tracing::info!(
|
||||
"[LLM] memory constrained — single-instance routing for '{}' ({} candidates dropped)",
|
||||
key,
|
||||
candidates.len()
|
||||
);
|
||||
return Ok((primary, role_entry.model, Vec::new()));
|
||||
}
|
||||
|
||||
// Strategy: round_robin rotates the full candidate list (primary first),
|
||||
// spreading requests across every enabled instance — including remote
|
||||
// machines — to aggregate their compute. priority keeps the configured
|
||||
// order untouched.
|
||||
if role_entry.strategy.as_deref() == Some("round_robin") && !candidates.is_empty() {
|
||||
static RR_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = RR_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut list: Vec<String> = vec![primary.clone()];
|
||||
list.extend(candidates);
|
||||
let len = list.len();
|
||||
let offset = (n % len as u64) as usize;
|
||||
list.rotate_left(offset);
|
||||
let new_primary = list.remove(0);
|
||||
tracing::debug!(
|
||||
"[LLM] round_robin pick #{} for '{}' → {} ({} fallbacks)",
|
||||
n, key, new_primary, list.len()
|
||||
);
|
||||
return Ok((new_primary, role_entry.model, list));
|
||||
}
|
||||
|
||||
Ok((primary, role_entry.model, candidates))
|
||||
}
|
||||
|
||||
/// POST an OpenAI-style chat request to `url`; on transport error or 5xx/429,
|
||||
/// walk `fallbacks` in order (each may be a local llama-server instance or a
|
||||
/// remote machine's — possibly a different model). llama-server ignores the
|
||||
/// model field mismatch, so the same request body is reused for each attempt.
|
||||
pub async fn post_llm_with_fallback(
|
||||
url: &str,
|
||||
fallbacks: &[String],
|
||||
req_body: &serde_json::Value,
|
||||
timeout_secs: u64,
|
||||
) -> anyhow::Result<reqwest::Response> {
|
||||
let send = |u: String| {
|
||||
LLM_CLIENT
|
||||
.post(&u)
|
||||
.json(req_body)
|
||||
.timeout(std::time::Duration::from_secs(timeout_secs))
|
||||
.send()
|
||||
};
|
||||
match send(url.to_string()).await {
|
||||
Ok(res) if res.status().is_success() => Ok(res),
|
||||
Ok(res) => {
|
||||
let st = res.status().as_u16();
|
||||
let text = res.text().await.unwrap_or_default();
|
||||
// Only retry on server-side / busy errors; 4xx means the request itself is bad.
|
||||
let retriable = st >= 500 || st == 429;
|
||||
if retriable && !fallbacks.is_empty() {
|
||||
for (i, fb) in fallbacks.iter().enumerate() {
|
||||
tracing::warn!("[LLM] {} returned {} — trying fallback #{} {}", url, st, i + 1, fb);
|
||||
match send(fb.clone()).await {
|
||||
Ok(r) if r.status().is_success() => return Ok(r),
|
||||
Ok(r) => {
|
||||
tracing::warn!("[LLM] fallback #{} {} returned {}", i + 1, fb, r.status());
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("[LLM] fallback #{} {} unreachable: {}", i + 1, fb, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
anyhow::bail!("LLM API error ({}): all {} fallback(s) exhausted", st, fallbacks.len())
|
||||
}
|
||||
anyhow::bail!("LLM API error ({}): {}", st, text)
|
||||
}
|
||||
Err(e) => {
|
||||
if !fallbacks.is_empty() {
|
||||
for (i, fb) in fallbacks.iter().enumerate() {
|
||||
tracing::warn!("[LLM] {} unreachable ({}) — trying fallback #{} {}", url, e, i + 1, fb);
|
||||
match send(fb.clone()).await {
|
||||
Ok(r) if r.status().is_success() => return Ok(r),
|
||||
Ok(r) => {
|
||||
tracing::warn!("[LLM] fallback #{} {} returned {}", i + 1, fb, r.status());
|
||||
}
|
||||
Err(e2) => {
|
||||
tracing::warn!("[LLM] fallback #{} {} unreachable: {}", i + 1, fb, e2);
|
||||
}
|
||||
}
|
||||
}
|
||||
anyhow::bail!("LLM API error: {} — all {} fallback(s) exhausted", e, fallbacks.len())
|
||||
}
|
||||
Err(anyhow::anyhow!("LLM API error: {}", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the LLM model name from centralized config
|
||||
pub fn llm_model() -> String {
|
||||
config::llm::CHAT_MODEL.clone()
|
||||
@@ -150,8 +362,10 @@ pub async fn call_llm_vision(
|
||||
{"role": "user", "content": content_parts}
|
||||
]);
|
||||
|
||||
let (vision_url, vision_model, vision_fallbacks) = resolve_llm_endpoint("vlm").await?;
|
||||
|
||||
let req = json!({
|
||||
"model": llm_vision_model(),
|
||||
"model": vision_model,
|
||||
"messages": messages,
|
||||
"temperature": 0.1,
|
||||
"max_tokens": max_tokens,
|
||||
@@ -159,12 +373,7 @@ pub async fn call_llm_vision(
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
let res = LLM_CLIENT
|
||||
.post(&llm_vision_url())
|
||||
.json(&req)
|
||||
.timeout(std::time::Duration::from_secs(timeout_secs))
|
||||
.send()
|
||||
.await?;
|
||||
let res = post_llm_with_fallback(&vision_url, &vision_fallbacks, &req, timeout_secs).await?;
|
||||
if !res.status().is_success() {
|
||||
let text = res.text().await.unwrap_or_default();
|
||||
anyhow::bail!("Vision LLM API error: {}", text);
|
||||
@@ -233,8 +442,10 @@ pub async fn call_llm(
|
||||
*config::llm::CHAT_TIMEOUT_SECS
|
||||
};
|
||||
|
||||
let (chat_url, chat_model, chat_fallback) = resolve_llm_endpoint("chat").await?;
|
||||
|
||||
let mut req = serde_json::to_value(&ChatRequest {
|
||||
model: llm_model(),
|
||||
model: chat_model,
|
||||
messages,
|
||||
temperature: 0.1,
|
||||
max_tokens,
|
||||
@@ -245,12 +456,7 @@ pub async fn call_llm(
|
||||
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
|
||||
}
|
||||
|
||||
let res = LLM_CLIENT
|
||||
.post(&llm_chat_url())
|
||||
.json(&req)
|
||||
.timeout(std::time::Duration::from_secs(timeout))
|
||||
.send()
|
||||
.await?;
|
||||
let res = post_llm_with_fallback(&chat_url, &chat_fallback, &req, timeout).await?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
let text = res.text().await.unwrap_or_default();
|
||||
@@ -303,8 +509,10 @@ pub async fn call_llm_with_usage(
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
let (chat_url, chat_model, chat_fallback) = resolve_llm_endpoint("chat").await?;
|
||||
|
||||
let mut req = serde_json::to_value(&ChatRequest {
|
||||
model: llm_model(),
|
||||
model: chat_model,
|
||||
messages,
|
||||
temperature: 0.1,
|
||||
max_tokens,
|
||||
@@ -315,12 +523,7 @@ pub async fn call_llm_with_usage(
|
||||
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
|
||||
}
|
||||
|
||||
let res = LLM_CLIENT
|
||||
.post(&llm_chat_url())
|
||||
.json(&req)
|
||||
.timeout(std::time::Duration::from_secs(timeout))
|
||||
.send()
|
||||
.await?;
|
||||
let res = post_llm_with_fallback(&chat_url, &chat_fallback, &req, timeout_secs).await?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
let text = res.text().await.unwrap_or_default();
|
||||
|
||||
@@ -11,6 +11,8 @@ pub mod config;
|
||||
pub mod dynamic_concurrency;
|
||||
pub mod db;
|
||||
pub mod embedding;
|
||||
pub mod folder_export;
|
||||
pub mod export;
|
||||
pub mod face_filter_engine;
|
||||
pub mod file_lifecycle;
|
||||
pub mod file_profile;
|
||||
@@ -40,3 +42,6 @@ pub mod tmdb;
|
||||
pub mod trace_sync;
|
||||
pub mod vision;
|
||||
pub mod vlm;
|
||||
pub mod json_debug;
|
||||
|
||||
pub mod json_standardize;
|
||||
|
||||
@@ -29,7 +29,13 @@ pub fn momentry_core_dir() -> PathBuf {
|
||||
// Check if we're in a typical installation structure
|
||||
if parent.ends_with("bin") {
|
||||
if let Some(grandparent) = parent.parent() {
|
||||
return grandparent.join("momentry_core");
|
||||
// Prefer <grandparent>/momentry_core if it exists
|
||||
let core = grandparent.join("momentry_core");
|
||||
if core.exists() {
|
||||
return core;
|
||||
}
|
||||
// Fallback: the grandparent IS the deployment dir (e.g. ~/momentry)
|
||||
return grandparent.to_path_buf();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +53,48 @@ impl AsrxResult {
|
||||
}
|
||||
|
||||
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")?;
|
||||
self.save_to_file_with_source(path, None, None)
|
||||
}
|
||||
|
||||
pub fn save_to_file_with_source(
|
||||
&self,
|
||||
path: &str,
|
||||
file_path: Option<&str>,
|
||||
file_name: Option<&str>,
|
||||
) -> Result<()> {
|
||||
// 使用標準化輸出格式(含 _meta 和 _debug)
|
||||
let file_uuid = self.metadata.as_ref()
|
||||
.and_then(|m| m.source.as_ref())
|
||||
.map(|s| s.file_uuid.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let file_path = file_path.unwrap_or("").to_string();
|
||||
let file_name = file_name.unwrap_or("").to_string();
|
||||
|
||||
let processor_name = self.metadata.as_ref()
|
||||
.map(|m| m.processor.name.clone())
|
||||
.unwrap_or_else(|| "asrx".to_string());
|
||||
|
||||
let processor_tool = self.metadata.as_ref()
|
||||
.map(|m| m.processor.tool.clone())
|
||||
.unwrap_or_else(|| "rust_asr_asrx".to_string());
|
||||
|
||||
let processor_version = self.metadata.as_ref()
|
||||
.map(|m| m.processor.version.clone())
|
||||
.unwrap_or_else(|| "1.0.0".to_string());
|
||||
|
||||
crate::core::json_formatter::write_file_standard(
|
||||
self,
|
||||
path,
|
||||
2,
|
||||
&processor_name,
|
||||
&processor_tool,
|
||||
&processor_version,
|
||||
&file_uuid,
|
||||
&file_path,
|
||||
&file_name,
|
||||
).context("Failed to write asrx.json")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+74
-19
@@ -1,6 +1,7 @@
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::process::Command;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::executor::PythonExecutor;
|
||||
@@ -75,29 +76,49 @@ pub async fn process_cut(
|
||||
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))?;
|
||||
|
||||
// 使用標準化輸出格式(含 _meta 和 _debug)
|
||||
let file_uuid = uuid.unwrap_or("").to_string();
|
||||
let file_path = video_path.to_string();
|
||||
let file_name = std::path::Path::new(video_path)
|
||||
.file_name()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
|
||||
crate::core::json_formatter::write_file_standard(
|
||||
&r,
|
||||
output_path,
|
||||
2,
|
||||
"cut",
|
||||
"ffmpeg_native",
|
||||
"1.0.0",
|
||||
&file_uuid,
|
||||
&file_path,
|
||||
&file_name,
|
||||
).with_context(|| format!("Failed to write {:?}", output_path))?;
|
||||
|
||||
return Ok(r);
|
||||
}
|
||||
|
||||
// Fallback: Python scenedetect
|
||||
tracing::warn!("[CUT] Native impl failed, falling back to Python");
|
||||
// Log the real reason the native impl failed (silent fallback hides root causes)
|
||||
let native_err = result.err().unwrap_or_else(|| anyhow::anyhow!("unknown error"));
|
||||
tracing::warn!(
|
||||
"[CUT] Native impl failed, falling back to Python: {:#}",
|
||||
native_err
|
||||
);
|
||||
let executor = PythonExecutor::new()?;
|
||||
let script_path = executor.script_path("cut/cut_processor.py");
|
||||
|
||||
if !script_path.exists() {
|
||||
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))?;
|
||||
return Ok(empty_result);
|
||||
// Missing fallback script must be a hard error — writing an empty
|
||||
// result (fps=0) silently fails downstream verification and hides
|
||||
// the real cause from the pipeline.
|
||||
anyhow::bail!(
|
||||
"[CUT] Native scene detection failed ({:#}) and Python fallback script not found: {:?}",
|
||||
native_err,
|
||||
script_path
|
||||
);
|
||||
}
|
||||
|
||||
executor
|
||||
@@ -122,9 +143,24 @@ pub async fn process_cut(
|
||||
|
||||
// ── Native ffmpeg scene detection ─────────────────────────────────
|
||||
|
||||
/// Resolve the ffprobe/ffmpeg executable path.
|
||||
/// Uses `FFPROBE_PATH` / `FFMPEG_PATH` env vars when set, falling back to the
|
||||
/// Homebrew absolute path on Apple Silicon. Never rely on bare `Command::new`
|
||||
/// name lookup — the worker's launchd environment may not resolve it.
|
||||
fn ff_tool_path(env_var: &str, homebrew_default: &str) -> String {
|
||||
if let Ok(p) = std::env::var(env_var) {
|
||||
if !p.trim().is_empty() && std::path::Path::new(&p).exists() {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
homebrew_default.to_string()
|
||||
}
|
||||
|
||||
fn try_native_cut(video_path: &str) -> Result<CutResult> {
|
||||
let ffprobe_path = ff_tool_path("FFPROBE_PATH", "/opt/homebrew/bin/ffprobe");
|
||||
|
||||
// Step 1: Get video info (fps, frame count)
|
||||
let probe = Command::new("ffprobe")
|
||||
let probe = Command::new(&ffprobe_path)
|
||||
.args([
|
||||
"-v",
|
||||
"quiet",
|
||||
@@ -162,7 +198,7 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
|
||||
// Step 2: Use ffmpeg scene detection filter
|
||||
// The `scene` filter computes the difference between consecutive frames
|
||||
// and outputs when the difference exceeds the threshold (0.3 = medium sensitivity)
|
||||
let scene_output = Command::new("ffprobe")
|
||||
let scene_output = Command::new(&ffprobe_path)
|
||||
.args([
|
||||
"-v",
|
||||
"quiet",
|
||||
@@ -209,7 +245,6 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
|
||||
|
||||
let mut prev_time = 0.0;
|
||||
let mut prev_frame: u64 = 0;
|
||||
let round_time = |t: f64| (t * 1000.0).round() / 1000.0;
|
||||
|
||||
for (i, &cut_time) in scene_times.iter().enumerate() {
|
||||
let end_frame = (cut_time * fps).round() as u64;
|
||||
@@ -299,6 +334,26 @@ mod tests {
|
||||
assert!(parse_fraction("1/0").is_none());
|
||||
}
|
||||
|
||||
/// Reproduces the launchd-worker failure mode seen on 200: PATH without
|
||||
/// /opt/homebrew/bin made `Command::new("ffprobe")` fail with ENOENT and
|
||||
/// cut fall back to an empty result (fps=0 → verification failure).
|
||||
/// Native cut must succeed by resolving ffprobe via FFPROBE_PATH / absolute path.
|
||||
#[test]
|
||||
fn test_native_cut_without_homebrew_in_path() {
|
||||
let video = std::env::var("MOMENTRY_TEST_VIDEO")
|
||||
.unwrap_or_else(|_| "/Users/accusys/Movies/test/Charade_YouTube_24fps.mp4".to_string());
|
||||
if !std::path::Path::new(&video).exists() {
|
||||
return; // test video absent (e.g. CI) — skip
|
||||
}
|
||||
let old_path = std::env::var("PATH").unwrap_or_default();
|
||||
std::env::set_var("PATH", "/usr/bin:/bin:/usr/sbin:/sbin");
|
||||
let result = try_native_cut(&video);
|
||||
std::env::set_var("PATH", old_path);
|
||||
let r = result.expect("native cut must succeed without homebrew in PATH");
|
||||
assert!(r.fps > 0.0, "fps must be positive, got {}", r.fps);
|
||||
assert!(r.frame_count > 0, "frame_count must be positive");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cut_result_serialization() {
|
||||
let result = CutResult {
|
||||
|
||||
@@ -99,6 +99,15 @@ impl FaceResult {
|
||||
}
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
self.save_to_file_with_source(path, None, None)
|
||||
}
|
||||
|
||||
pub fn save_to_file_with_source(
|
||||
&self,
|
||||
path: &str,
|
||||
file_path: Option<&str>,
|
||||
file_name: Option<&str>,
|
||||
) -> Result<()> {
|
||||
// Strip embeddings before saving to disk - they're already in Qdrant
|
||||
// This saves ~50% disk space (512 floats * 4 bytes per face)
|
||||
let mut light = self.clone();
|
||||
@@ -107,8 +116,40 @@ impl FaceResult {
|
||||
face.embedding = None;
|
||||
}
|
||||
}
|
||||
crate::core::json_formatter::write_file_pretty_rounded(&light, path, 2)
|
||||
.context("Failed to write face.json")?;
|
||||
|
||||
// 使用標準化輸出格式(含 _meta 和 _debug)
|
||||
let file_uuid = self.metadata.as_ref()
|
||||
.and_then(|m| m.source.as_ref())
|
||||
.map(|s| s.file_uuid.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let file_path = file_path.unwrap_or("").to_string();
|
||||
let file_name = file_name.unwrap_or("").to_string();
|
||||
|
||||
let processor_name = self.metadata.as_ref()
|
||||
.map(|m| m.processor.name.clone())
|
||||
.unwrap_or_else(|| "face".to_string());
|
||||
|
||||
let processor_tool = self.metadata.as_ref()
|
||||
.map(|m| m.processor.tool.clone())
|
||||
.unwrap_or_else(|| "swift_face".to_string());
|
||||
|
||||
let processor_version = self.metadata.as_ref()
|
||||
.map(|m| m.processor.version.clone())
|
||||
.unwrap_or_else(|| "1.0.0".to_string());
|
||||
|
||||
crate::core::json_formatter::write_file_standard(
|
||||
&light,
|
||||
path,
|
||||
2,
|
||||
&processor_name,
|
||||
&processor_tool,
|
||||
&processor_version,
|
||||
&file_uuid,
|
||||
&file_path,
|
||||
&file_name,
|
||||
).context("Failed to write face.json")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -368,7 +409,7 @@ pub async fn process_face(
|
||||
// Execute face tracking
|
||||
tracing::info!("[FACE] Starting face tracking");
|
||||
use crate::core::processor::face_tracker::track_faces;
|
||||
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
|
||||
if let Err(e) = track_faces(&mut result, 0.3, 0.8, 100.0, true, None) {
|
||||
tracing::warn!("[FACE] Face tracking failed: {}", e);
|
||||
} else {
|
||||
tracing::info!("[FACE] Face tracking completed successfully");
|
||||
@@ -423,7 +464,7 @@ pub async fn process_face(
|
||||
// Execute face tracking
|
||||
tracing::info!("[FACE] Starting face tracking");
|
||||
use crate::core::processor::face_tracker::track_faces;
|
||||
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
|
||||
if let Err(e) = track_faces(&mut result, 0.3, 0.8, 100.0, true, None) {
|
||||
tracing::warn!("[FACE] Face tracking failed: {}", e);
|
||||
} else {
|
||||
tracing::info!("[FACE] Face tracking completed successfully");
|
||||
@@ -628,6 +669,10 @@ mod tests {
|
||||
y: 100,
|
||||
width: 50,
|
||||
height: 60,
|
||||
x2: 150,
|
||||
y2: 160,
|
||||
center_x: 125,
|
||||
center_y: 130,
|
||||
confidence: 0.95,
|
||||
capture_quality: Some(0.9),
|
||||
embedding: Some(vec![0.1, 0.2, 0.3]),
|
||||
@@ -732,6 +777,10 @@ mod tests {
|
||||
y: 0,
|
||||
width: 10,
|
||||
height: 10,
|
||||
x2: 10,
|
||||
y2: 10,
|
||||
center_x: 5,
|
||||
center_y: 5,
|
||||
confidence: 0.5,
|
||||
capture_quality: None,
|
||||
embedding: None,
|
||||
@@ -754,6 +803,10 @@ mod tests {
|
||||
y: 200,
|
||||
width: 50,
|
||||
height: 60,
|
||||
x2: 150,
|
||||
y2: 260,
|
||||
center_x: 125,
|
||||
center_y: 230,
|
||||
confidence: 0.95,
|
||||
capture_quality: Some(0.8),
|
||||
embedding: Some(vec![0.1; 512]),
|
||||
|
||||
@@ -115,8 +115,36 @@ impl FaceClusterResult {
|
||||
}
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
|
||||
.context("Failed to write face_cluster.json")?;
|
||||
self.save_to_file_with_source(path, None, None)
|
||||
}
|
||||
|
||||
pub fn save_to_file_with_source(
|
||||
&self,
|
||||
path: &str,
|
||||
file_path: Option<&str>,
|
||||
file_name: Option<&str>,
|
||||
) -> Result<()> {
|
||||
// 使用標準化輸出格式(含 _meta 和 _debug)
|
||||
let file_uuid = self.file_uuid.clone().unwrap_or_default();
|
||||
let file_path = file_path.unwrap_or("").to_string();
|
||||
let file_name = file_name.unwrap_or("").to_string();
|
||||
|
||||
let processor_name = "face_cluster".to_string();
|
||||
let processor_tool = "face_cluster".to_string();
|
||||
let processor_version = "1.0.0".to_string();
|
||||
|
||||
crate::core::json_formatter::write_file_standard(
|
||||
self,
|
||||
path,
|
||||
2,
|
||||
&processor_name,
|
||||
&processor_tool,
|
||||
&processor_version,
|
||||
&file_uuid,
|
||||
&file_path,
|
||||
&file_name,
|
||||
).context("Failed to write face_cluster.json")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -147,8 +175,11 @@ pub async fn process_face_cluster(
|
||||
});
|
||||
}
|
||||
|
||||
// Build args with --threshold (default 0.85 to correctly separate male/female faces)
|
||||
let threshold = similarity_threshold.unwrap_or(0.85);
|
||||
// Build args with --threshold (default 0.65 similarity → 0.35 distance)
|
||||
// Lower distance threshold = more permissive (merge more similar faces)
|
||||
// 0.15 distance was too strict, causing over-segmentation (7 persons instead of 2)
|
||||
// 0.35 distance correctly gives 2 persons for test video
|
||||
let threshold = similarity_threshold.unwrap_or(0.65);
|
||||
let distance = 1.0 - threshold;
|
||||
let threshold_str = format!("{:.4}", distance);
|
||||
let mut args = vec![
|
||||
|
||||
@@ -143,8 +143,36 @@ impl FaceTrackingResult {
|
||||
}
|
||||
|
||||
pub fn save_to_file(&self, path: &str) -> Result<()> {
|
||||
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
|
||||
.context("Failed to write face_traced.json")?;
|
||||
self.save_to_file_with_source(path, None, None)
|
||||
}
|
||||
|
||||
pub fn save_to_file_with_source(
|
||||
&self,
|
||||
path: &str,
|
||||
file_path: Option<&str>,
|
||||
file_name: Option<&str>,
|
||||
) -> Result<()> {
|
||||
// 使用標準化輸出格式(含 _meta 和 _debug)
|
||||
let file_uuid = self.file_uuid.clone().unwrap_or_default();
|
||||
let file_path = file_path.unwrap_or("").to_string();
|
||||
let file_name = file_name.unwrap_or("").to_string();
|
||||
|
||||
let processor_name = "face_trace".to_string();
|
||||
let processor_tool = "face_trace".to_string();
|
||||
let processor_version = "1.0.0".to_string();
|
||||
|
||||
crate::core::json_formatter::write_file_standard(
|
||||
self,
|
||||
path,
|
||||
2,
|
||||
&processor_name,
|
||||
&processor_tool,
|
||||
&processor_version,
|
||||
&file_uuid,
|
||||
&file_path,
|
||||
&file_name,
|
||||
).context("Failed to write face_traced.json")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -276,7 +304,7 @@ fn match_faces(
|
||||
}
|
||||
}
|
||||
|
||||
if best_prev_idx >= 0 && best_iou > 0.5 {
|
||||
if best_prev_idx >= 0 && best_iou > iou_threshold {
|
||||
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
|
||||
used_prev.insert(best_prev_idx as usize);
|
||||
}
|
||||
|
||||
@@ -330,6 +330,7 @@ pub async fn generate_scene_meta(
|
||||
let out_path = Path::new(crate::core::config::OUTPUT_DIR.as_str())
|
||||
.join(format!("{}.scene_meta.json", file_uuid));
|
||||
let json_str = serde_json::to_string_pretty(&meta)?;
|
||||
let json_str = crate::core::json_debug::append_debug_footer(json_str, &out_path);
|
||||
tokio::fs::write(&out_path, json_str)
|
||||
.await
|
||||
.context("Failed to write scene_meta.json")?;
|
||||
|
||||
@@ -53,8 +53,48 @@ impl OcrResult {
|
||||
}
|
||||
|
||||
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")?;
|
||||
self.save_to_file_with_source(path, None, None)
|
||||
}
|
||||
|
||||
pub fn save_to_file_with_source(
|
||||
&self,
|
||||
path: &str,
|
||||
file_path: Option<&str>,
|
||||
file_name: Option<&str>,
|
||||
) -> Result<()> {
|
||||
// 使用標準化輸出格式(含 _meta 和 _debug)
|
||||
let file_uuid = self.metadata.as_ref()
|
||||
.and_then(|m| m.source.as_ref())
|
||||
.map(|s| s.file_uuid.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let file_path = file_path.unwrap_or("").to_string();
|
||||
let file_name = file_name.unwrap_or("").to_string();
|
||||
|
||||
let processor_name = self.metadata.as_ref()
|
||||
.map(|m| m.processor.name.clone())
|
||||
.unwrap_or_else(|| "ocr".to_string());
|
||||
|
||||
let processor_tool = self.metadata.as_ref()
|
||||
.map(|m| m.processor.tool.clone())
|
||||
.unwrap_or_else(|| "swift_ocr".to_string());
|
||||
|
||||
let processor_version = self.metadata.as_ref()
|
||||
.map(|m| m.processor.version.clone())
|
||||
.unwrap_or_else(|| "1.0.0".to_string());
|
||||
|
||||
crate::core::json_formatter::write_file_standard(
|
||||
self,
|
||||
path,
|
||||
2,
|
||||
&processor_name,
|
||||
&processor_tool,
|
||||
&processor_version,
|
||||
&file_uuid,
|
||||
&file_path,
|
||||
&file_name,
|
||||
).context("Failed to write ocr.json")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -286,6 +326,38 @@ pub async fn process_ocr(
|
||||
args.push("--uuid".to_string());
|
||||
args.push(u.to_string());
|
||||
}
|
||||
|
||||
// Calculate sample-interval for ~8Hz sampling
|
||||
// For 60fps video: 60/8 = 7.5 → 8
|
||||
// For 30fps video: 30/8 = 3.75 → 4
|
||||
if let Some(frame_list) = frames {
|
||||
if !frame_list.is_empty() {
|
||||
// Estimate fps from frame indices (assuming they're roughly evenly spaced)
|
||||
let first_frame = frame_list[0];
|
||||
let last_frame = frame_list[frame_list.len() - 1];
|
||||
let frame_span = (last_frame - first_frame) as f64;
|
||||
let sample_count = frame_list.len() as f64;
|
||||
|
||||
if frame_span > 0.0 && sample_count > 1.0 {
|
||||
// Estimated fps based on the sampling pattern
|
||||
// For 8Hz sampling over the video duration
|
||||
let estimated_interval = (frame_span / (sample_count - 1.0)).round() as i32;
|
||||
if estimated_interval > 0 {
|
||||
args.push("--sample-interval".to_string());
|
||||
args.push(estimated_interval.to_string());
|
||||
tracing::info!("[OCR] Using sample-interval={} for ~8Hz sampling", estimated_interval);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Default to interval=8 for ~8Hz sampling at 60fps
|
||||
args.push("--sample-interval".to_string());
|
||||
args.push("8".to_string());
|
||||
}
|
||||
|
||||
// Always use accurate recognition level
|
||||
args.push("--recognition-level".to_string());
|
||||
args.push("accurate".to_string());
|
||||
|
||||
let output = tokio::process::Command::new(swift_ocr_path)
|
||||
.args(&args)
|
||||
|
||||
+103
-10
@@ -378,10 +378,33 @@ impl SceneVlmProcessor {
|
||||
pub fn save_scene_profile(profile: &SceneProfile, output_dir: &str) -> Result<()> {
|
||||
let path = SceneProfile::scenes_path(output_dir, &profile.file_uuid);
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(profile).context("Failed to serialize SceneProfile")?;
|
||||
|
||||
std::fs::write(&path, json).context("Failed to write scenes.json")?;
|
||||
// 使用標準化輸出格式(含 _meta 和 _debug)
|
||||
let file_uuid = profile.file_uuid.clone();
|
||||
|
||||
// 從 processor 資訊取得工具名稱
|
||||
let processor_name = "scene_vlm".to_string();
|
||||
let processor_tool = profile.processor.as_ref()
|
||||
.map(|p| p.name.clone())
|
||||
.unwrap_or_else(|| "scene_vlm".to_string());
|
||||
let processor_version = profile.processor.as_ref()
|
||||
.map(|p| p.version.clone())
|
||||
.unwrap_or_else(|| "1.0.0".to_string());
|
||||
|
||||
// file_path 和 file_name 需要從外部傳入,這裡用預設值
|
||||
let file_path = "".to_string();
|
||||
let file_name = "".to_string();
|
||||
|
||||
crate::core::json_formatter::write_file_standard(
|
||||
profile,
|
||||
&path.to_string_lossy(),
|
||||
2,
|
||||
&processor_name,
|
||||
&processor_tool,
|
||||
&processor_version,
|
||||
&file_uuid,
|
||||
&file_path,
|
||||
&file_name,
|
||||
).context("Failed to write scenes.json")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -600,6 +623,55 @@ Rules:
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
/// Resize image using ffmpeg to reduce VLM API payload size
|
||||
fn resize_image_for_vlm(image_path: &std::path::Path) -> Result<Vec<u8>> {
|
||||
use std::process::Command;
|
||||
|
||||
// Check if ffmpeg is available
|
||||
let ffmpeg_path = crate::core::admin_config::get_ffmpeg_path();
|
||||
|
||||
// Create temp file for resized image
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let temp_path = temp_dir.join(format!("scene_vlm_resized_{}.jpg", std::process::id()));
|
||||
|
||||
// Use ffmpeg to resize to max 512x512 while maintaining aspect ratio
|
||||
let output = Command::new(&ffmpeg_path)
|
||||
.args([
|
||||
"-y",
|
||||
"-i", image_path.to_str().unwrap_or(""),
|
||||
"-vf", "scale=min(512\\,iw):min(512\\,ih):force_original_aspect_ratio=decrease",
|
||||
"-q:v", "80",
|
||||
"-update", "1",
|
||||
temp_path.to_str().unwrap_or(""),
|
||||
])
|
||||
.output()
|
||||
.with_context(|| format!("Failed to execute ffmpeg for image resize: {:?}", image_path))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::warn!("[Scene VLM] ffmpeg resize failed: {}", stderr);
|
||||
// Fallback: return original image
|
||||
return std::fs::read(image_path)
|
||||
.with_context(|| format!("Failed to read original image: {:?}", image_path));
|
||||
}
|
||||
|
||||
// Read resized image
|
||||
let resized_bytes = std::fs::read(&temp_path)
|
||||
.with_context(|| format!("Failed to read resized image: {:?}", temp_path))?;
|
||||
|
||||
// Clean up temp file
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
|
||||
tracing::info!(
|
||||
"[Scene VLM] Image resized: {} bytes -> {} bytes",
|
||||
image_path.metadata().map(|m| m.len()).unwrap_or(0),
|
||||
resized_bytes.len()
|
||||
);
|
||||
|
||||
Ok(resized_bytes)
|
||||
}
|
||||
|
||||
/// Call VLM API to generate structured scene info.
|
||||
/// Returns (english_description, objects, bilingual_tags).
|
||||
pub async fn generate_scene_description(
|
||||
@@ -609,10 +681,15 @@ Rules:
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
use std::time::Duration;
|
||||
|
||||
// Read image
|
||||
let jpeg_bytes = std::fs::read(image_path)
|
||||
.with_context(|| format!("Failed to read image: {:?}", image_path))?;
|
||||
// Read and resize image for VLM API (max 512x512 to avoid connection issues)
|
||||
let jpeg_bytes = Self::resize_image_for_vlm(image_path)
|
||||
.with_context(|| format!("Failed to process image: {:?}", image_path))?;
|
||||
let base64_img = BASE64.encode(&jpeg_bytes);
|
||||
|
||||
tracing::debug!(
|
||||
"[Scene VLM] Image encoded: {} bytes base64",
|
||||
base64_img.len()
|
||||
);
|
||||
|
||||
// VLM API config
|
||||
let vlm_url = crate::core::config::llm::VISION_URL.clone();
|
||||
@@ -644,9 +721,11 @@ Rules:
|
||||
}
|
||||
]
|
||||
}],
|
||||
"max_tokens": 1024,
|
||||
"max_tokens": 2048,
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
"chat_template_kwargs": {"enable_thinking": false},
|
||||
"reasoning": false,
|
||||
"thinking": false
|
||||
});
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
@@ -682,13 +761,27 @@ Rules:
|
||||
}
|
||||
let message = choice.get("message").context("Invalid VLM API response structure")?;
|
||||
|
||||
// Try content first, then fallback to reasoning_content (for Gemma models)
|
||||
let content = match message
|
||||
.get("content")
|
||||
.and_then(|c| c.as_str())
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
{
|
||||
Some(s) => s.trim().to_string(),
|
||||
None => anyhow::bail!("VLM returned empty content"),
|
||||
None => {
|
||||
// Fallback to reasoning_content for Gemma models
|
||||
match message
|
||||
.get("reasoning_content")
|
||||
.and_then(|c| c.as_str())
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
{
|
||||
Some(s) => {
|
||||
tracing::info!("[Scene VLM] Using reasoning_content as fallback");
|
||||
s.trim().to_string()
|
||||
},
|
||||
None => anyhow::bail!("VLM returned empty content and reasoning_content"),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
tracing::debug!(
|
||||
|
||||
@@ -1590,6 +1590,7 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
&serde_json::to_value(&trace_profile).unwrap_or_default(),
|
||||
))
|
||||
{
|
||||
let json = crate::core::json_debug::append_debug_footer(json, &tp_path);
|
||||
let _ = std::fs::write(&tp_path, json);
|
||||
if tp_path.exists() {
|
||||
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);
|
||||
|
||||
@@ -259,8 +259,8 @@ impl ToolSelector {
|
||||
}
|
||||
}
|
||||
("asrx", "rust") => {
|
||||
// Future: Rust ASRX implementation
|
||||
executor.rust_binary_path("rust_asrx")
|
||||
// Full ASR + diarization with whisper + ECAPA
|
||||
executor.rust_binary_path("rust_asr_asrx")
|
||||
}
|
||||
("asrx", "python") => {
|
||||
let script = executor.script_path("asrx_processor.py");
|
||||
|
||||
@@ -33,6 +33,27 @@ pub async fn sync_trace_label(
|
||||
qdrant_points_count: 0,
|
||||
};
|
||||
|
||||
// Face-groups normalization (V1.0 §7 G4): an already-grouped trace must
|
||||
// not have its caption overwritten by an auto cluster label (e.g.
|
||||
// "Person_N" from a re-run). Mirror the owning group's name instead.
|
||||
let new_label: String = {
|
||||
let tp = schema::table_name("trace_profiles");
|
||||
let fg = schema::table_name("face_groups");
|
||||
let group_name: Option<String> = sqlx::query_scalar(&format!(
|
||||
"SELECT {fg}.name FROM {fg} JOIN {tp} ON {tp}.group_id = {fg}.id \
|
||||
AND {tp}.file_uuid = {fg}.file_uuid \
|
||||
WHERE {tp}.file_uuid = $1 AND {tp}.trace_id = $2"
|
||||
))
|
||||
.bind(file_uuid)
|
||||
.bind(trace_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
group_name.unwrap_or_else(|| new_label.to_string())
|
||||
};
|
||||
let new_label: &str = new_label.as_str();
|
||||
|
||||
// 1. 更新 tkg_nodes.label
|
||||
match update_tkg_label(pool, file_uuid, trace_id, new_label).await {
|
||||
Ok(rows) => {
|
||||
|
||||
+19
-10
@@ -38,9 +38,15 @@ impl VLMClient {
|
||||
.map_err(|e| VLMError::ImageReadFailed(image_path.to_string(), e))?;
|
||||
let image_base64 = general_purpose::STANDARD.encode(&image_data);
|
||||
|
||||
// 2. 构建请求
|
||||
// 2. 解析路由(admin config 優先 → env → 預設),並取得備援 endpoint
|
||||
let (base_url, model, fallbacks) =
|
||||
crate::core::llm::function_calling::resolve_llm_endpoint("vlm")
|
||||
.await
|
||||
.map_err(|e| VLMError::WorkerError(e.to_string()))?;
|
||||
|
||||
// 3. 构建请求
|
||||
let request = serde_json::json!({
|
||||
"model": self.model,
|
||||
"model": model,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
@@ -62,15 +68,18 @@ impl VLMClient {
|
||||
"temperature": 0.1
|
||||
});
|
||||
|
||||
// 3. 调用 API
|
||||
let response = self
|
||||
.http_client
|
||||
.post(&self.base_url)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
// 4. 调用 API(主 endpoint 失敗時依序 fallback 到備援實例)
|
||||
let response =
|
||||
crate::core::llm::function_calling::post_llm_with_fallback(
|
||||
&base_url,
|
||||
&fallbacks,
|
||||
&request,
|
||||
120,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| VLMError::WorkerError(e.to_string()))?;
|
||||
|
||||
// 4. 检查响应状态
|
||||
// 5. 检查响应状态
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
|
||||
Reference in New Issue
Block a user