feat: trace_id i64→i32 fix, OCR search filter, Rule1 OCR trigger

- Fix trace_id SQL type mismatch: i64 → i32 in profile.rs structs and queries
- Add /ocr /asr /asrx search filter suffix to keyword/semantic/smart search
- Fix fetch_ocr_texts to handle both OCR data formats (string array + object array)
- Add has_ocr trigger for Rule1 chunk ingestion in job_worker.rs
- Add search_bm25 chunk_type filter parameter
- Fix single-frame video clip duration (0-frame → 1-frame minimum)
- Re-run Rule1 for 14 files with stuck OCR in pre_chunks
This commit is contained in:
Accusys
2026-07-30 19:34:35 +08:00
parent 5d0c771a2b
commit 85d5e1fe51
20 changed files with 1783 additions and 412 deletions
+328 -136
View File
@@ -2,10 +2,24 @@ use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::Duration;
use tokio::sync::Semaphore;
use tokio::time::sleep;
use tracing::{debug, error, info, warn};
/// Bounds the number of concurrent heavy face-I/O Python tasks (store_traced_faces.py /
/// TKG build). These spawns bypass ProcessorPool (raw tokio::spawn) and each loads the
/// full face.json into numpy + scrolls all Qdrant face points, which previously caused
/// unbounded pile-up and OOM. Capacity mirrors FRAME_SLOT_MAX in processor.rs.
static FACE_IO_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(2));
/// Tracks uuids with an in-flight untracked face-trace/TKG Python spawn, to prevent the
/// same file from being spawned multiple times in a row (race between poll cycles) when
/// face_traced.json is not yet written. Guards against the duplicate-spawn loop.
static FACE_TRACE_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSet<String>>> =
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
use crate::core::chunk::rule1_ingest;
use crate::core::config::OUTPUT_DIR;
use crate::core::db::qdrant_db::QdrantDb;
@@ -101,6 +115,17 @@ impl JobWorker {
}
async fn poll_and_process(&self) -> Result<()> {
// Memory usage monitoring (every 100 polls)
static POLL_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let count = POLL_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if count % 100 == 0 {
if let Ok(mem_mb) = get_rss_mb() {
if mem_mb > 1024 {
warn!("⚠️ High memory usage: {} MB", mem_mb);
}
}
}
// 檢查系統資源並寫入 Redis
let resources = SystemResources::check();
let dynamic_max = resources.safe_max_concurrent(self.config.max_concurrent);
@@ -1137,7 +1162,7 @@ impl JobWorker {
"language_probability": 0.0
});
let asr_path = format!(
"{}{}.asr.json",
"{}/{}.asr.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
job.uuid
);
@@ -1183,10 +1208,8 @@ impl JobWorker {
// Special handling for ASRX: if ASR output exists with no_audio_track/silent_audio, skip processing
if *processor_type == crate::core::db::ProcessorType::Asrx {
let asr_output_path = format!(
"{}{}.asr.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
"{}/{}.asr.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
job.uuid
);
if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) {
@@ -1195,6 +1218,23 @@ impl JobWorker {
if let Some(status) = asr_status {
if status == "no_audio_track" || status == "silent_audio" {
info!("ASRX: ASR status={}, skipping ASRX processing", status);
// Write asrx.json output file (so sync-status sees it)
let asrx_output_path = format!(
"{}/{}.asrx.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
job.uuid
);
let asrx_result = serde_json::json!({
"status": status,
"language": asr_data.get("language").and_then(|l| l.as_str()),
"segments": [],
"segment_count": 0
});
if let Err(e) = std::fs::write(&asrx_output_path, serde_json::to_string_pretty(&asrx_result).unwrap_or_default()) {
warn!("Failed to write ASRX output file: {}", e);
}
// Create completed result with same status
if let Err(e) = self
.db
@@ -1439,6 +1479,21 @@ impl JobWorker {
Ok(())
}
/// 統一 TKG 完成檢查 — P4 trigger 和 ingestion gate 共用。
/// Face TKG:必須有 face_track_nodes > 0(代表 face tracking 已寫入 TKG)。
/// No-face TKG 由 caller 自行短路(has_face=false 或 status=no_faces 時不需檢查)。
async fn is_tkg_done(pool: &PgPool, uuid: &str) -> bool {
let nodes_table = crate::core::db::schema::table_name("tkg_nodes");
let count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {nodes_table} WHERE file_uuid = $1 AND node_type = 'face_track'"
))
.bind(uuid)
.fetch_one(pool)
.await
.unwrap_or(0);
count > 0
}
/// 檢查所有入庫步驟是否已完成(與 ingestion-status endpoint 同步邏輯)
async fn ingestion_complete(pool: &PgPool, uuid: &str, job_processors: &[String]) -> bool {
let chunk_t = schema::table_name("chunk");
@@ -1467,7 +1522,7 @@ impl JobWorker {
.await
.unwrap_or(None);
match asr_status.as_deref() {
let status_from_db = match asr_status.as_deref() {
Some("no_audio_track") | Some("silent_audio") => true,
Some("has_transcript") => {
sqlx::query_scalar::<_, i32>(&format!(
@@ -1480,6 +1535,32 @@ impl JobWorker {
.unwrap_or(0) > 0
}
_ => false,
};
if status_from_db {
true
} else {
// Fallback: check asr.json file directly
let asr_path = format!(
"{}/{}.asr.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
uuid
);
if let Ok(content) = std::fs::read_to_string(&asr_path) {
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
match data.get("status").and_then(|s| s.as_str()) {
Some("no_audio_track") | Some("silent_audio") => true,
Some("has_transcript") => {
data.get("segments").and_then(|s| s.as_array())
.map(|a| !a.is_empty()).unwrap_or(false)
}
_ => false,
}
} else {
false
}
} else {
false
}
}
} else {
true
@@ -1535,31 +1616,27 @@ impl JobWorker {
true
};
// 3. TKG: tkg_nodes 有資料(有 face 時才需要 TKG)
let tkg_done: bool = if has_face {
if trace_status == "no_faces" {
// 無臉不需要 TKG
true
} else {
let node_count: i32 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tkg_nodes_t} WHERE file_uuid = $1"
))
.bind(uuid)
.fetch_one(pool)
.await
.unwrap_or(0);
// TKG 完成 = nodes > 0(必須真正有 TKG 資料)
node_count > 0
}
// 3. TKG: face_track_nodes 有資料(Face TKG 必須有 face tracking 寫入)
let tkg_done: bool = if has_face && trace_status != "no_faces" {
Self::is_tkg_done(pool, uuid).await
} else {
// 無 face 不需要 TKG
true
};
// 4. Face Cluster: face_cluster.json 存在(有 face 時才需要)
let face_cluster_done: bool = if has_face {
if trace_status == "no_faces" {
// 直接寫入空的 face_cluster.json 讓 sync-status 能正確判斷
let cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid);
if !std::path::Path::new(&cluster_path).exists() {
let empty_output = serde_json::json!({
"status": "no_faces",
"file_uuid": uuid,
"clusters": [],
"frames": []
});
let _ = std::fs::write(&cluster_path, serde_json::to_string_pretty(&empty_output).unwrap_or_default());
}
true
} else {
let cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid);
@@ -1607,7 +1684,7 @@ impl JobWorker {
true
};
let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && rule3_done && scene_meta_done && qdrant_face_done;
let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && qdrant_face_done;
tracing::info!(
"[Ingestion] all_ok={} (asr={}, trace={}, tkg={}, face_cluster={}, rule3={}, scene_meta={}, qdrant_face={}) for uuid={}",
@@ -1761,10 +1838,8 @@ impl JobWorker {
// Special handling for ASRX: check ASR output file
if processor_type == crate::core::db::ProcessorType::Asrx {
let asr_output_path = format!(
"{}{}.asr.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
"{}/{}.asr.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
uuid
);
if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) {
@@ -1776,6 +1851,23 @@ impl JobWorker {
"ASRX: ASR status={}, creating completed result directly",
status
);
// Write asrx.json output file (so sync-status sees it)
let asrx_output_path = format!(
"{}/{}.asrx.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
uuid
);
let asrx_result = serde_json::json!({
"status": status,
"language": asr_data.get("language").and_then(|l| l.as_str()),
"segments": [],
"segment_count": 0
});
if let Err(e) = std::fs::write(&asrx_output_path, serde_json::to_string_pretty(&asrx_result).unwrap_or_default()) {
warn!("Failed to write ASRX output file: {}", e);
}
if let Err(e) = self
.db
.upsert_processor_result(
@@ -1872,15 +1964,17 @@ impl JobWorker {
let has_cut = completed_processors.iter().any(|p| p == "cut");
let has_face = completed_processors.iter().any(|p| p == "face");
let has_yolo = completed_processors.iter().any(|p| p == "yolo");
let has_ocr = completed_processors.iter().any(|p| p == "ocr");
self.db
.update_job_processors_arrays(job_id, completed_processors, failed_processors.clone())
.await?;
if has_asrx {
if has_asrx || has_ocr {
// Guard: only spawn Rule 1 if sentence chunks don't exist yet
// or if OCR completed but OCR chunks are missing (OCR came after ASRX)
let chunk_t = schema::table_name("chunk");
let already_spawned: bool = sqlx::query_scalar::<_, i32>(&format!(
let has_sentence: bool = sqlx::query_scalar::<_, i32>(&format!(
"SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'sentence' LIMIT 1"
))
.bind(uuid)
@@ -1889,7 +1983,23 @@ impl JobWorker {
.unwrap_or(0)
> 0;
if already_spawned {
let has_ocr_chunks: bool = if has_ocr {
sqlx::query_scalar::<_, i32>(&format!(
"SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'ocr' LIMIT 1"
))
.bind(uuid)
.fetch_optional(self.db.pool())
.await?
.unwrap_or(0)
> 0
} else {
true // skip OCR check if OCR hasn't completed yet
};
// Run Rule1 if no sentence chunks yet, or if OCR finished but OCR chunks missing
let needs_rule1 = !has_sentence || (has_ocr && !has_ocr_chunks);
if !needs_rule1 {
info!("✅ Rule 1 already completed for {}, skipping spawn", uuid);
} else {
info!("📝 Prerequisites met for Rule 1 Chunking. Starting ingestion...");
@@ -1968,7 +2078,7 @@ impl JobWorker {
// Note: Job status will be updated after Rule 2 (TKG) completion
// Do not mark as completed here
}
Err(e) => error!("❌ Phase 1 release pack failed: {}", e),
Err(e) => warn!("⚠️ Phase 1 release pack failed (non-fatal): {}", e),
}
}
Err(e) => error!("❌ Rule 1 Ingestion failed: {}", e),
@@ -1990,22 +2100,38 @@ impl JobWorker {
// Runs face_tracker.py (IoU+embedding tracking), stores trace_id + position in DB
if has_face {
let traced_path = format!(
"{}{}.face_traced.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
"{}/{}.face_traced.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
uuid
);
if std::path::Path::new(&traced_path).exists() {
info!("✅ Face trace already done for {}, skipping spawn", uuid);
} else {
info!("📝 Face completed, triggering face trace + DB store...");
let db_clone = self.db.clone();
let redis_clone = self.redis.clone();
let uuid_clone = uuid.to_string();
tokio::spawn(async move {
// Mark face_tracing as running
{
// Guard against the same uuid being spawned twice across poll
// cycles (race before face_traced.json is written).
let mut inflight = FACE_TRACE_INFLIGHT.lock().await;
if inflight.contains(uuid) {
info!("⏳ Face trace already in-flight for {}, skipping duplicate spawn", uuid);
} else {
inflight.insert(uuid.to_string());
drop(inflight);
info!("📝 Face completed, triggering face trace + DB store...");
let db_clone = self.db.clone();
let redis_clone = self.redis.clone();
let uuid_clone = uuid.to_string();
tokio::spawn(async move {
// Bound concurrent heavy face-I/O Python tasks to avoid OOM
// (these spawns bypass ProcessorPool). Held until block ends.
let _face_io_permit = match FACE_IO_SEM.acquire().await {
Ok(p) => p,
Err(_) => {
error!("❌ Face trace semaphore closed for {}", uuid_clone);
FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone);
return;
}
};
// Mark face_tracing as running
{
let mut pp = PipelineProgress::new(&uuid_clone);
pp.update_stage("face_tracing", 0.0, "running", None);
publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp).await;
@@ -2014,6 +2140,7 @@ impl JobWorker {
Ok(ex) => ex,
Err(e) => {
error!("Failed to create PythonExecutor for face trace: {}", e);
FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone);
return;
}
};
@@ -2100,9 +2227,13 @@ impl JobWorker {
error!("❌ Face trace + DB store failed for {}: {}", uuid_clone, e)
}
}
// Clear in-flight marker so this uuid can be retried later
// if it failed or the worker restarts before completion.
FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone);
});
}
}
}
// 🚀 P2.5 Trigger: TMDb Face Matching (after Face, if TMDb data exists)
if has_face && *crate::core::config::tmdb::PROBE_ENABLED {
@@ -2240,81 +2371,73 @@ impl JobWorker {
// 🚀 P4 Trigger: TKG Build (Face + ASRX) → then Rule2 ingestion
if has_face && has_asrx {
let tkg_table = crate::core::db::schema::table_name("tkg_edges");
let tkg_done: bool = sqlx::query_scalar::<_, i32>(&format!(
"SELECT 1 FROM {tkg_table} WHERE file_uuid = $1 LIMIT 1"
))
.bind(uuid)
.fetch_optional(self.db.pool())
.await
.unwrap_or(None)
.unwrap_or(0)
> 0;
// Check face.json status first to determine TKG type
let face_json_path = format!(
"{}/{}.face.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
uuid
);
if tkg_done {
info!("✅ TKG already built for {}, skipping spawn", uuid);
} else {
// Check face.json status first
let face_json_path = format!(
"{}{}.face.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid
);
let has_faces = if std::path::Path::new(&face_json_path).exists() {
if let Ok(content) = std::fs::read_to_string(&face_json_path) {
if let Ok(face_data) =
serde_json::from_str::<serde_json::Value>(&content)
{
face_data
.get("status")
.and_then(|s| s.as_str())
.map(|s| s == "has_faces")
.unwrap_or(false)
} else {
false
}
let has_faces = if std::path::Path::new(&face_json_path).exists() {
if let Ok(content) = std::fs::read_to_string(&face_json_path) {
if let Ok(face_data) =
serde_json::from_str::<serde_json::Value>(&content)
{
face_data
.get("status")
.and_then(|s| s.as_str())
.map(|s| s == "has_faces")
.unwrap_or(false)
} else {
false
}
} else {
false
};
}
} else {
false
};
if has_faces {
// Has faces - wait for face_traced.json
let traced_path = format!(
"{}{}.face_traced.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid
// Face TKG: must have face_track_nodes > 0
// No-face TKG: not needed
let tkg_done: bool = if has_faces {
Self::is_tkg_done(self.db.pool(), uuid).await
} else {
true
};
if tkg_done {
info!("✅ TKG already built for {}, skipping spawn", uuid);
} else if has_faces {
// Has faces - wait for face_traced.json
let traced_path = format!(
"{}/{}.face_traced.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
uuid
);
if !std::path::Path::new(&traced_path).exists() {
info!(
"⏳ TKG build waiting for face_traced.json: {} (file_uuid={})",
traced_path, uuid
);
if !std::path::Path::new(&traced_path).exists() {
info!(
"⏳ TKG build waiting for face_traced.json: {} (file_uuid={})",
traced_path, uuid
);
} else {
// Verify Qdrant has face points before TKG build
let expected_faces =
if let Ok(content) = std::fs::read_to_string(&face_json_path) {
if let Ok(face_data) =
serde_json::from_str::<serde_json::Value>(&content)
{
face_data
.get("total_faces")
.and_then(|t| t.as_i64())
.unwrap_or(0)
} else {
0
}
} else {
// Verify Qdrant has face points before TKG build
let expected_faces =
if let Ok(content) = std::fs::read_to_string(&face_json_path) {
if let Ok(face_data) =
serde_json::from_str::<serde_json::Value>(&content)
{
face_data
.get("total_faces")
.and_then(|t| t.as_i64())
.unwrap_or(0)
} else {
0
};
}
} else {
0
};
// Wait for Qdrant to have all face points (up to 30 seconds)
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
@@ -2360,6 +2483,15 @@ impl JobWorker {
let uuid_clone = uuid.to_string();
let output_dir_clone = crate::core::config::OUTPUT_DIR.clone();
tokio::spawn(async move {
// Bound concurrent heavy face-I/O Python tasks to avoid OOM
// (build_tkg may internally spawn store_traced_faces.py).
let _face_io_permit = match FACE_IO_SEM.acquire().await {
Ok(p) => p,
Err(_) => {
error!("❌ TKG build semaphore closed for {}", uuid_clone);
return;
}
};
// Mark tkg_nodes + tkg_edges as running
{
let mut pp = PipelineProgress::new(&uuid_clone);
@@ -2474,6 +2606,15 @@ impl JobWorker {
let uuid_clone = uuid.to_string();
let output_dir_clone = crate::core::config::OUTPUT_DIR.clone();
tokio::spawn(async move {
// Bound concurrent heavy face-I/O Python tasks to avoid OOM
// (build_tkg may internally spawn store_traced_faces.py).
let _face_io_permit = match FACE_IO_SEM.acquire().await {
Ok(p) => p,
Err(_) => {
error!("❌ TKG build (no-faces) semaphore closed for {}", uuid_clone);
return;
}
};
// Mark tkg_nodes + tkg_edges as running (no-faces path)
{
let mut pp = PipelineProgress::new(&uuid_clone);
@@ -2537,7 +2678,6 @@ impl JobWorker {
}
});
}
}
}
if !Self::ingestion_complete(self.db.pool(), uuid, job_processors).await {
@@ -2812,44 +2952,43 @@ impl JobWorker {
) -> Result<()> {
use std::collections::HashMap;
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
let scroll_filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": uuid}}
]
});
let all_faces = qdrant
.scroll_all_points("_faces", scroll_filter, 1000)
.await
.context("Failed to scroll _faces from Qdrant")?;
let mut frame_to_traces: HashMap<u64, Vec<i64>> = HashMap::new();
for point in &all_faces {
let payload = &point["payload"];
if let (Some(frame), Some(trace_id)) =
(payload["frame"].as_u64(), payload["trace_id"].as_i64())
{
if trace_id > 0 {
frame_to_traces.entry(frame).or_default().push(trace_id);
// Build index: (frame, face_index) → real trace_id from face_traced.json
// face_cluster.json's trace_id is cluster-internal (always 0), so we match
// by frame number + array index to get the actual traced trace_id.
let traced_path = format!("{}/{}.face_traced.json", crate::core::config::OUTPUT_DIR.as_str(), uuid);
let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new();
if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(frames) = traced_data.get("frames").and_then(|v| v.as_object()) {
for (fnum_str, frame_data) in frames {
if let (Ok(fnum), Some(faces)) = (
fnum_str.parse::<u64>(),
frame_data.get("faces").and_then(|v| v.as_array()),
) {
for (idx, face) in faces.iter().enumerate() {
if let Some(tid) = face.get("trace_id").and_then(|v| v.as_i64()) {
frame_face_to_trace.insert((fnum, idx), tid);
}
}
}
}
}
}
}
let mut trace_to_cluster: HashMap<i64, String> = HashMap::new();
for frame_data in &result.frames {
let frame = frame_data.frame;
if let Some(trace_ids) = frame_to_traces.get(&frame) {
for (idx, face) in frame_data.faces.iter().enumerate() {
if idx < trace_ids.len() {
trace_to_cluster.insert(trace_ids[idx], face.cluster_id.clone());
}
for (idx, face) in frame_data.faces.iter().enumerate() {
if let Some(&tid) = frame_face_to_trace.get(&(frame_data.frame, idx)) {
trace_to_cluster.insert(tid, face.cluster_id.clone());
}
}
}
let tkg_table = crate::core::db::schema::table_name("tkg_nodes");
let tp_table = crate::core::db::schema::table_name("trace_profiles");
// Update traces that ARE in clusters
for (trace_id, cluster_id) in &trace_to_cluster {
let external_id = format!("trace_{}", trace_id);
let label = cluster_id.clone();
@@ -2892,6 +3031,46 @@ impl JobWorker {
.await;
}
// Also update traces that are NOT in any cluster (keep default Person_N name)
if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(traces) = traced_data.get("traces") {
let trace_list = if traces.is_object() {
traces.as_object().map(|o| o.keys().filter_map(|k| k.parse::<i64>().ok()).collect::<Vec<_>>())
} else if traces.is_array() {
traces.as_array().map(|a| a.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect())
} else {
None
};
if let Some(all_trace_ids) = trace_list {
let mut updated_count = 0u64;
for tid in &all_trace_ids {
if !trace_to_cluster.contains_key(tid) {
let name = format!("Person_{}", tid);
let _ = sqlx::query(&format!(
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
tp_table
))
.bind(&name)
.bind(uuid)
.bind(tid)
.execute(db.pool())
.await;
updated_count += 1;
}
}
if updated_count > 0 {
info!(
"[FaceCluster] Updated {} unclustered trace names for {}",
updated_count, uuid
);
}
}
}
}
}
info!(
"[FaceCluster] Updated {} trace labels for {}",
trace_to_cluster.len(),
@@ -2902,6 +3081,19 @@ impl JobWorker {
}
}
/// Get current process RSS in MB
fn get_rss_mb() -> std::io::Result<u64> {
let output = std::process::Command::new("ps")
.args(["-o", "rss=", "-p", &std::process::id().to_string()])
.output()?;
let rss_kb = String::from_utf8(output.stdout)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?
.trim()
.parse::<u64>()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
Ok(rss_kb / 1024)
}
#[cfg(test)]
mod tests {
use super::*;
+37 -6
View File
@@ -1312,18 +1312,49 @@ impl ProcessorPool {
uuid: &str,
ocr_result: &OcrResult,
) -> Result<()> {
let frames_count = ocr_result.frames.len();
tracing::info!("Storing {} OCR pre-chunks for video {}", frames_count, uuid);
use crate::core::processor::ocr::{group_ocr_texts_by_zone_and_proximity, OcrGroup};
// Get frame height from videos table for Y-axis zone classification
let videos_table = crate::core::db::schema::table_name("videos");
let frame_height: Option<i32> = sqlx::query_scalar(&format!(
"SELECT height FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(uuid)
.fetch_optional(db.pool())
.await?
.flatten();
let height = frame_height.unwrap_or(720) as f64; // Default fallback
// Group OCR texts by zone and proximity
let groups: Vec<OcrGroup> = group_ocr_texts_by_zone_and_proximity(&ocr_result.frames, height);
tracing::info!(
"Storing {} OCR groups (from {} frames) for video {}",
groups.len(),
ocr_result.frames.len(),
uuid
);
let mut pre_chunks_to_store = Vec::new();
for frame in ocr_result.frames.iter() {
for group in &groups {
let data = serde_json::json!({
"texts": frame.texts,
"timestamp": frame.timestamp,
"texts": group.texts,
"zone": group.zone.as_str(),
"start_frame": group.start_frame,
"end_frame": group.end_frame,
"timestamp": group.start_timestamp,
});
pre_chunks_to_store.push((frame.frame as i64, Some(frame.timestamp), data, None, None));
pre_chunks_to_store.push((
group.start_frame,
Some(group.start_timestamp),
data,
None,
None,
));
}
db.store_raw_pre_chunks_batch(uuid, "ocr", &pre_chunks_to_store)