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:
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
@@ -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, ¤t_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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user