fix: ASRX duplication, TKG edges, trace ingest, and add pipeline progress publishing

- ASRX handler no longer stores duplicate 'asr' pre_chunks
- Pre_chunks storage made idempotent (delete-before-insert)
- Rule 1 + trace_ingest changed to query 'asrx' not 'asr'
- Trace chunks removed (dynamic from TKG/Qdrant)
- TKG scroll_face_points fixed: trace_id >= 1 (not == 1)
- TKG AsrxSegmentEntry: start/end -> start_time/end_time (match ASRX JSON)
- Unregister error handling: log instead of silent discard
- Add publish_pipeline_progress calls at each pipeline stage
  (processors, rule1, face_trace, identity_agent, TKG, rule2, completion)
This commit is contained in:
Accusys
2026-07-02 10:43:46 +08:00
parent d791d138f2
commit 3eabd45882
65 changed files with 9477 additions and 3852 deletions
+4 -1
View File
@@ -103,7 +103,7 @@ async fn fetch_asr_segments(
SELECT
start_frame, end_frame, start_time, end_time, data
FROM {}
WHERE file_uuid = $1 AND processor_type = 'asr'
WHERE file_uuid = $1 AND processor_type = 'asrx'
ORDER BY start_frame
"#,
table
@@ -206,6 +206,9 @@ fn collect_ocr_text(
end_frame: i64,
ocr_map: &BTreeMap<i64, Vec<String>>,
) -> String {
if start_frame > end_frame {
return String::new();
}
let mut seen = std::collections::HashSet::new();
let mut parts = Vec::new();
+13 -3
View File
@@ -3,6 +3,8 @@ use anyhow::{Context, Result};
use serde_json::Value;
use sqlx::PgPool;
use tracing::{info, warn};
use std::sync::Arc;
use crate::core::db::redis_client::RedisClient;
fn t(name: &str) -> String {
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "dev".to_string());
@@ -13,17 +15,19 @@ fn t(name: &str) -> String {
}
}
/// Rule2 ingestion progress callback
pub type Rule2ProgressFn = Box<dyn Fn(&str, usize, usize) + Send + Sync>;
/// Executes Rule 2 Ingestion: TKG edges → relationship chunks.
///
/// 1. Query tkg_edges by priority order.
/// 2. Resolve source/target nodes and identities.
/// 3. Generate natural language description (template-based).
/// 4. Insert chunks with chunk_type='relationship'.
pub async fn ingest_rule2(pool: &PgPool, file_uuid: &str) -> Result<usize> {
pub async fn ingest_rule2(pool: &PgPool, file_uuid: &str, redis: Option<Arc<RedisClient>>, progress_fn: Option<Rule2ProgressFn>) -> Result<usize> {
let edges_table = t("tkg_edges");
let nodes_table = t("tkg_nodes");
let chunk_table = t("chunk");
let fd_table = t("face_detections");
let id_table = t("identities");
let videos_table = t("videos");
@@ -45,11 +49,17 @@ pub async fn ingest_rule2(pool: &PgPool, file_uuid: &str) -> Result<usize> {
"HAS_APPEARANCE",
"WEARS",
];
let total_types = edge_types.len();
let mut count = 0;
let mut tx = pool.begin().await?;
for edge_type in &edge_types {
for (i, edge_type) in edge_types.iter().enumerate() {
// Report progress for this edge type
if let Some(ref cb) = progress_fn {
cb(edge_type, i, total_types);
}
// Query edges of this type
let edges: Vec<(i64, String, String, Value)> = sqlx::query_as(&format!(
"SELECT id, source_node_id::text, target_node_id::text, properties \
+57 -27
View File
@@ -1,13 +1,15 @@
use crate::core::chunk::types::{Chunk, ChunkRule, ChunkType};
use crate::core::db::schema;
use crate::core::db::PostgresDb;
use crate::core::db::qdrant_db::QdrantDb;
use anyhow::{Context, Result};
use serde_json::json;
use sqlx::Row;
use tracing::{error, info};
use std::collections::HashMap;
pub async fn ingest_traces(db: &PostgresDb, file_uuid: &str) -> Result<usize> {
let pool = db.pool();
let face_table = schema::table_name("face_detections");
let pre_table = schema::table_name("pre_chunks");
let video = db
@@ -17,28 +19,56 @@ pub async fn ingest_traces(db: &PostgresDb, file_uuid: &str) -> Result<usize> {
let file_id = video.id as i32;
let fps = video.fps;
let traces = sqlx::query_as::<_, TraceAgg>(&format!(
r#"
SELECT trace_id,
MIN(frame_number) AS first_frame,
MAX(frame_number) AS last_frame,
MIN(timestamp_secs) AS first_time,
MAX(timestamp_secs) AS last_time,
COUNT(*) AS face_count,
AVG(x)::float8 AS avg_x,
AVG(y)::float8 AS avg_y,
AVG(width)::float8 AS avg_w,
AVG(height)::float8 AS avg_h
FROM {}
WHERE file_uuid = $1 AND trace_id IS NOT NULL
GROUP BY trace_id
ORDER BY trace_id
"#,
face_table
))
.bind(file_uuid)
.fetch_all(pool)
.await?;
// Aggregate by trace_id
let qdrant = QdrantDb::new();
let face_filter = json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": 1}}
]
});
let points = qdrant.scroll_all_points("_faces", face_filter, 500).await.unwrap_or_default();
let mut trace_data: HashMap<i32, (i64, i64, f64, f64, i64, f64, f64, f64, f64)> = HashMap::new();
for point in &points {
let payload = &point["payload"];
let trace_id = payload["trace_id"].as_i64().unwrap_or(0) as i32;
let frame = payload["frame"].as_i64().unwrap_or(0);
let timestamp = payload.get("timestamp_secs").and_then(|v| v.as_f64()).unwrap_or(0.0);
let bbox = &payload["bbox"];
let x = bbox["x"].as_f64().unwrap_or(0.0);
let y = bbox["y"].as_f64().unwrap_or(0.0);
let w = bbox["width"].as_f64().unwrap_or(0.0);
let h = bbox["height"].as_f64().unwrap_or(0.0);
let entry = trace_data.entry(trace_id).or_insert((i64::MAX, i64::MIN, f64::MAX, f64::MIN, 0, 0.0, 0.0, 0.0, 0.0));
entry.0 = entry.0.min(frame);
entry.1 = entry.1.max(frame);
if timestamp > 0.0 {
entry.2 = entry.2.min(timestamp);
entry.3 = entry.3.max(timestamp);
}
entry.4 += 1;
entry.5 += x;
entry.6 += y;
entry.7 += w;
entry.8 += h;
}
let traces: Vec<TraceAgg> = trace_data.into_iter().map(|(trace_id, (first_f, last_f, first_t, last_t, count, sum_x, sum_y, sum_w, sum_h))| {
TraceAgg {
trace_id,
first_frame: first_f,
last_frame: last_f,
first_time: if first_t != f64::MAX { first_t } else { first_f as f64 / fps },
last_time: if last_t != f64::MIN { last_t } else { last_f as f64 / fps },
face_count: count,
avg_x: sum_x / count as f64,
avg_y: sum_y / count as f64,
avg_w: sum_w / count as f64,
avg_h: sum_h / count as f64,
}
}).collect();
if traces.is_empty() {
info!("No traces found for {}", file_uuid);
@@ -49,8 +79,8 @@ pub async fn ingest_traces(db: &PostgresDb, file_uuid: &str) -> Result<usize> {
r#"
SELECT start_frame, end_frame, start_time, end_time, data
FROM {}
WHERE file_uuid = $1 AND processor_type = 'asr'
ORDER BY start_frame
WHERE file_uuid = $1 AND processor_type = 'asrx'
ORDER BY start_time
"#,
pre_table
))
@@ -200,8 +230,8 @@ struct TraceAgg {
}
struct AsrSegment {
start_frame: i64,
end_frame: i64,
start_frame: Option<i64>,
end_frame: Option<i64>,
start_time: f64,
end_time: f64,
data: serde_json::Value,