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
+12 -9
View File
@@ -242,16 +242,19 @@ async fn fetch_ocr_texts(
.map(|arr| {
arr.iter()
.filter_map(|item| {
let text = item.get("text").and_then(|t| t.as_str())?;
let confidence = item
.get("confidence")
.and_then(|c| c.as_f64())
.unwrap_or(0.0);
if confidence > OCR_CONFIDENCE_THRESHOLD {
Some(text.to_string())
} else {
None
// Format A: array of objects with text/confidence fields
if let Some(obj_text) = item.get("text").and_then(|t| t.as_str()) {
let confidence = item
.get("confidence")
.and_then(|c| c.as_f64())
.unwrap_or(0.0);
if confidence > OCR_CONFIDENCE_THRESHOLD {
return Some(obj_text.to_string());
}
return None;
}
// Format B: array of plain strings
item.as_str().map(|s| s.to_string())
})
.collect()
})
+43 -25
View File
@@ -1174,6 +1174,12 @@ impl PostgresDb {
sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_identity_history_identity_time ON {}(identity_id, created_at DESC)", history_table)).execute(pool).await?;
sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_identity_history_not_undone ON {}(identity_id, created_at DESC) WHERE NOT is_undone", history_table)).execute(pool).await?;
// ── Trace Operation History (face group/trace undo) ──
let op_table = schema::table_name("trace_operation_history");
sqlx::query(&format!("CREATE TABLE IF NOT EXISTS {} (id BIGSERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, operation VARCHAR(30) NOT NULL, before_snapshot JSONB NOT NULL, after_snapshot JSONB, is_undone BOOLEAN DEFAULT FALSE, undone_at TIMESTAMPTZ, user_id VARCHAR(100), created_at TIMESTAMPTZ DEFAULT NOW())", op_table)).execute(pool).await?;
sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_trace_op_history_file_time ON {}(file_uuid, created_at DESC)", op_table)).execute(pool).await?;
sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_trace_op_history_not_undone ON {}(file_uuid, created_at DESC) WHERE NOT is_undone", op_table)).execute(pool).await?;
// ── File Identities (N:N file ↔ identity) ──
sqlx::query("CREATE TABLE IF NOT EXISTS file_identities (id SERIAL PRIMARY KEY, file_uuid VARCHAR(255) NOT NULL, identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, confidence DOUBLE PRECISION DEFAULT 1.0, metadata JSONB, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, UNIQUE(file_uuid, identity_id))").execute(pool).await?;
sqlx::query(
@@ -3099,8 +3105,8 @@ impl PostgresDb {
let table = schema::table_name("processor_results");
let ptype = processor_type.as_str();
let id: i32 = sqlx::query_scalar(&format!(
"INSERT INTO {} (job_id, processor_type, processor, uuid, status) \
VALUES ($1, $2, $2, $3, $4) \
"INSERT INTO {} (job_id, processor_type, processor, file_uuid, uuid, status) \
VALUES ($1, $2, $2, $3, $3, $4) \
ON CONFLICT (job_id, processor_type) DO UPDATE SET status = EXCLUDED.status, updated_at = CURRENT_TIMESTAMP \
RETURNING id", table
))
@@ -3433,8 +3439,16 @@ impl PostgresDb {
) -> Result<u64> {
let table = schema::table_name("processor_results");
let s = format!("{:?}", status).to_lowercase();
// Only reset results that have been stuck in 'running' for a while.
// Freshly-started / actively-running results (updated_at within the window)
// are NOT flipped back to 'pending' — this prevents the worker from
// re-queuing work that is actually in flight (e.g. an untracked
// store_traced_faces.py subprocess), which previously caused an
// unbounded re-spawn / OOM spiral.
let r = sqlx::query(&format!(
"UPDATE {} SET status = 'pending', error_message = $1 WHERE status = $2",
"UPDATE {} SET status = 'pending', error_message = $1 \
WHERE status = $2 \
AND updated_at < NOW() - INTERVAL '10 minutes'",
table
))
.bind(reason)
@@ -3486,41 +3500,45 @@ impl PostgresDb {
&self,
query: &str,
file_uuid: Option<&str>,
chunk_type: Option<&str>,
limit: i64,
) -> Result<Vec<Bm25Result>> {
let table = schema::table_name("chunk");
let like = format!("%{}%", query.replace('%', "%%"));
use sqlx::Row;
// Simple LIKE-based matching (no FTS stemming)
// Build WHERE clauses dynamically to handle optional params
let mut clauses = vec!["text_content ILIKE $2".to_string(), "text_content != ''".to_string()];
let mut next_idx = 3;
if file_uuid.is_some() {
next_idx += 1;
clauses.push(format!("file_uuid = ${}", next_idx));
}
if chunk_type.is_some() {
next_idx += 1;
clauses.push(format!("chunk_type = ${}", next_idx));
}
let where_sql = clauses.join(" AND ");
let sql = format!(
"SELECT chunk_id, file_uuid, chunk_type, text_content, start_time, end_time, \
(1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8))::float8 as score \
FROM {} \
WHERE text_content ILIKE $2 AND text_content != '' \
{}\
WHERE {} \
ORDER BY score DESC \
LIMIT $3",
table,
if file_uuid.is_some() { "AND file_uuid = $4 " } else { "" }
table, where_sql
);
let rows = if let Some(u) = file_uuid {
sqlx::query(&sql)
.bind(query)
.bind(&like)
.bind(limit)
.bind(u)
.fetch_all(&self.pool)
.await?
} else {
sqlx::query(&sql)
.bind(query)
.bind(&like)
.bind(limit)
.fetch_all(&self.pool)
.await?
};
let mut q = sqlx::query(&sql).bind(query).bind(&like).bind(limit);
if let Some(u) = file_uuid {
q = q.bind(u);
}
if let Some(ct) = chunk_type {
q = q.bind(ct);
}
let rows = q.fetch_all(&self.pool).await?;
Ok(rows
.into_iter()
@@ -3548,7 +3566,7 @@ impl PostgresDb {
_vector_weight: f32,
_bm25_weight: f32,
) -> Result<Vec<Bm25Result>> {
self.search_bm25(query, uuid, limit as i64).await
self.search_bm25(query, uuid, None, limit as i64).await
}
pub async fn list_identities(
+50
View File
@@ -913,6 +913,56 @@ impl QdrantDb {
Ok(all_points)
}
/// Scroll ALL points with vectors, for reading face embeddings
pub async fn scroll_all_points_with_vectors(
&self,
collection: &str,
filter: serde_json::Value,
page_size: usize,
) -> Result<Vec<serde_json::Value>> {
let mut all_points = Vec::new();
let mut offset: Option<serde_json::Value> = None;
loop {
let url = format!("{}/collections/{}/points/scroll", self.base_url, collection);
let mut body = serde_json::json!({
"filter": filter,
"limit": page_size,
"with_payload": true,
"with_vector": true,
});
if let Some(ref off) = offset {
body["offset"] = off.clone();
}
let resp = self
.client
.post(&url)
.header("api-key", &self.api_key)
.header("Content-Type", "application/json")
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
anyhow::bail!("Qdrant scroll failed: {}", resp.status());
}
let result: serde_json::Value = resp.json().await?;
let points = result["result"]["points"]
.as_array()
.cloned()
.unwrap_or_default();
let batch_len = points.len();
all_points.extend(points);
if batch_len < page_size {
break;
}
let next_offset = result["result"]["next_page_offset"].clone();
if next_offset.is_null() {
break;
}
offset = Some(next_offset);
}
Ok(all_points)
}
pub async fn count_points(&self, collection: &str, filter: serde_json::Value) -> Result<i64> {
let url = format!("{}/collections/{}/points/count", self.base_url, collection);
+1
View File
@@ -46,6 +46,7 @@ pub struct FaceClusterFrame {
pub struct ClusteredFace {
pub face_id: String,
pub cluster_id: String,
pub trace_id: Option<i64>,
pub confidence: f32,
}
+201
View File
@@ -1,11 +1,20 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::time::Duration;
use super::executor::PythonExecutor;
const OCR_TIMEOUT: Duration = Duration::from_secs(7200);
/// Y-axis zone thresholds (relative to frame height)
const UI_Y_THRESHOLD: f64 = 0.15;
const SUBTITLE_Y_THRESHOLD: f64 = 0.70;
/// Maximum distance (pixels) for bbox-based grouping within Scene zone
const BBOX_MAX_DISTANCE: f64 = 300.0;
/// Jaccard similarity threshold for frame-to-frame text change detection
const TEXT_SIMILARITY_THRESHOLD: f64 = 0.5;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OcrResult {
pub frame_count: u64,
@@ -30,6 +39,198 @@ pub struct OcrText {
pub confidence: f32,
}
/// Text zone classification based on Y-axis position
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TextZone {
UI, // Top 15% (titles, UI elements)
Scene, // Middle 55% (scene text, signs, labels)
Subtitle, // Bottom 30% (subtitles, captions)
}
impl TextZone {
pub fn from_y(y_center: f64, frame_height: f64) -> Self {
let ratio = y_center / frame_height;
if ratio < UI_Y_THRESHOLD {
TextZone::UI
} else if ratio >= SUBTITLE_Y_THRESHOLD {
TextZone::Subtitle
} else {
TextZone::Scene
}
}
pub fn as_str(&self) -> &'static str {
match self {
TextZone::UI => "ui",
TextZone::Scene => "scene",
TextZone::Subtitle => "subtitle",
}
}
}
/// Grouped OCR texts with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OcrGroup {
pub texts: Vec<String>,
pub zone: TextZone,
pub start_frame: i64,
pub end_frame: i64,
pub start_timestamp: f64,
pub end_timestamp: f64,
}
/// Group OCR texts by zone and proximity
pub fn group_ocr_texts_by_zone_and_proximity(
frames: &[OcrFrame],
frame_height: f64,
) -> Vec<OcrGroup> {
if frames.is_empty() {
return vec![];
}
let mut groups: Vec<OcrGroup> = Vec::new();
let mut current_zone_texts: Vec<(TextZone, Vec<String>)> = Vec::new();
let mut last_texts: HashSet<String> = HashSet::new();
let mut start_frame = frames[0].frame as i64;
let mut start_timestamp = frames[0].timestamp;
for frame in frames {
// Rule 2: Frame difference detection
let current_texts: HashSet<String> =
frame.texts.iter().map(|t| t.text.clone()).collect();
let similarity = jaccard_similarity(&last_texts, &current_texts);
if !last_texts.is_empty() && similarity < TEXT_SIMILARITY_THRESHOLD {
// Text changed significantly, finalize current groups
for (zone, texts) in std::mem::take(&mut current_zone_texts) {
if !texts.is_empty() {
groups.push(OcrGroup {
texts,
zone,
start_frame,
end_frame: (frame.frame as i64).saturating_sub(1),
start_timestamp,
end_timestamp: frame.timestamp,
});
}
}
start_frame = frame.frame as i64;
start_timestamp = frame.timestamp;
}
// Rule 1: Y-axis zone classification
let mut zone_map: std::collections::HashMap<TextZone, Vec<String>> =
std::collections::HashMap::new();
for text in &frame.texts {
let y_center = text.y as f64 + text.height as f64 / 2.0;
let zone = TextZone::from_y(y_center, frame_height);
zone_map.entry(zone).or_default().push(text.text.clone());
}
// Rule 3: Bbox distance grouping for Scene zone
let scene_texts = zone_map.remove(&TextZone::Scene).unwrap_or_default();
let scene_groups = group_by_bbox_distance(&frame.texts, &scene_texts, BBOX_MAX_DISTANCE);
// Add UI and Subtitle texts (already grouped by zone)
for (zone, texts) in zone_map {
current_zone_texts.push((zone, texts));
}
// Add scene groups
for texts in scene_groups {
current_zone_texts.push((TextZone::Scene, texts));
}
last_texts = current_texts;
}
// Finalize remaining groups
for (zone, texts) in current_zone_texts {
if !texts.is_empty() {
let last_frame = frames.last().unwrap();
groups.push(OcrGroup {
texts,
zone,
start_frame,
end_frame: last_frame.frame as i64,
start_timestamp,
end_timestamp: last_frame.timestamp,
});
}
}
groups
}
/// Calculate Jaccard similarity between two text sets
fn jaccard_similarity(set1: &HashSet<String>, set2: &HashSet<String>) -> f64 {
if set1.is_empty() && set2.is_empty() {
return 1.0;
}
let intersection = set1.intersection(set2).count();
let union = set1.union(set2).count();
if union == 0 {
1.0
} else {
intersection as f64 / union as f64
}
}
/// Group scene texts by bbox proximity
fn group_by_bbox_distance(
all_texts: &[OcrText],
scene_texts: &[String],
max_distance: f64,
) -> Vec<Vec<String>> {
if scene_texts.is_empty() {
return vec![];
}
// Find bbox centers for scene texts
let scene_bboxes: Vec<(f64, f64, &str)> = all_texts
.iter()
.filter(|t| scene_texts.contains(&t.text))
.map(|t| {
let x_center = t.x as f64 + t.width as f64 / 2.0;
let y_center = t.y as f64 + t.height as f64 / 2.0;
(x_center, y_center, t.text.as_str())
})
.collect();
// Simple clustering by distance
let mut groups: Vec<Vec<String>> = Vec::new();
let mut assigned = vec![false; scene_bboxes.len()];
for i in 0..scene_bboxes.len() {
if assigned[i] {
continue;
}
let mut group = vec![scene_bboxes[i].2.to_string()];
assigned[i] = true;
for j in (i + 1)..scene_bboxes.len() {
if assigned[j] {
continue;
}
let dist = ((scene_bboxes[i].0 - scene_bboxes[j].0).powi(2)
+ (scene_bboxes[i].1 - scene_bboxes[j].1).powi(2))
.sqrt();
if dist < max_distance {
group.push(scene_bboxes[j].2.to_string());
assigned[j] = true;
}
}
groups.push(group);
}
groups
}
pub async fn process_ocr(
video_path: &str,
output_path: &str,
+17 -5
View File
@@ -32,7 +32,7 @@ async fn scroll_face_points(file_uuid: &str) -> Vec<FacePoint> {
let filter = json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "range": {"gte": 1}}
{"key": "trace_id", "range": {"gte": 0}}
]
});
@@ -1334,11 +1334,22 @@ async fn build_face_track_nodes_from_qdrant(
});
// Save all three files to output/{file_uuid}/{trace_id}/
let _ = trace_profile.save(
let mut key_frame_file = agg.best_frame.to_string();
let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string();
match trace_profile.save(
output_dir,
key_frame_jpeg.as_deref(),
key_face_jpeg.as_deref(),
);
) {
Ok(_) => {
key_frame_file = "key_frame.jpg".to_string();
key_face_file = "key_face.jpg".to_string();
}
Err(e) => {
tracing::error!("[TKG] Failed to save trace_profile for trace {}: {}", tid, e);
}
}
// Update props with actual file paths (for DB properties JSONB)
let final_props = serde_json::json!({
@@ -1346,8 +1357,8 @@ async fn build_face_track_nodes_from_qdrant(
"frame_count": agg.frame_count,
"start_frame": agg.start_f,
"end_frame": agg.end_f,
"key_frame": agg.best_frame,
"key_face": agg.best_point_id.as_deref().unwrap_or(""),
"key_frame": key_frame_file,
"key_face": key_face_file,
"avg_bbox": props["avg_bbox"].clone(),
"avg_yaw": props["avg_yaw"].clone(),
"avg_pitch": props["avg_pitch"].clone(),
@@ -1388,6 +1399,7 @@ async fn build_face_track_nodes_from_qdrant(
count += 1;
}
tracing::info!("[TKG-face_track] built {} face_track nodes for {}", count, file_uuid);
Ok(count)
}