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
+69 -13
View File
@@ -64,6 +64,37 @@ struct MergedResult {
source: String,
}
/// Parse /ocr, /asr, /asrx suffix from the end of a query string.
/// Returns (clean_query, optional_source_filter).
/// The filter value is in source_type terms ("ocr" / "asrx") for result filtering,
/// not chunk_type terms ("ocr" / "sentence").
fn parse_source_filter(query: &str) -> (String, Option<String>) {
let trimmed = query.trim();
if let Some(rest) = trimmed
.strip_suffix("/ocr")
.or_else(|| trimmed.strip_suffix("/OCR"))
{
(rest.trim().to_string(), Some("ocr".to_string()))
} else if let Some(rest) = trimmed
.strip_suffix("/asr")
.or_else(|| trimmed.strip_suffix("/ASR"))
.or_else(|| trimmed.strip_suffix("/asrx"))
.or_else(|| trimmed.strip_suffix("/ASRX"))
{
(rest.trim().to_string(), Some("asrx".to_string()))
} else {
(query.to_string(), None)
}
}
/// Map a source_type filter ("ocr" / "asrx") to chunk_type for DB queries.
fn source_filter_to_chunk_type(filter: &str) -> &str {
match filter {
"ocr" => "ocr",
_ => "sentence", // "asrx" → "sentence"
}
}
fn map_chunk_type_to_source(chunk_type: &str) -> String {
match chunk_type.to_lowercase().as_str() {
"ocr" => "ocr".to_string(),
@@ -151,9 +182,14 @@ pub async fn smart_search(
let hard_limit = req.limit.unwrap_or(usize::MAX);
let limit = hard_limit.min(page_size);
// 1. Generate embedding
let (clean_query, source_filter) = parse_source_filter(&req.query);
let chunk_type_filter = source_filter
.as_deref()
.map(source_filter_to_chunk_type);
// 1. Generate embedding from clean query
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let embedding = embedder.embed_query(&req.query).await.map_err(
let embedding = embedder.embed_query(&clean_query).await.map_err(
|e| -> (StatusCode, Json<serde_json::Value>) {
tracing::error!("Embedding failed: {}", e);
(
@@ -199,7 +235,7 @@ pub async fn smart_search(
// 3. Keyword search via PG ILIKE
let keyword_results: Vec<(String, String, f64)> = match db
.search_bm25(&req.query, req.file_uuid.as_deref(), fetch_limit as i64)
.search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, fetch_limit as i64)
.await
{
Ok(rows) => {
@@ -221,14 +257,14 @@ pub async fn smart_search(
// 3b. Video title search: if query matches a video title, get its chunks
const TITLE_MATCH_SCORE: f64 = 0.75; // Lower than semantic max (0.85-0.9), but higher than keyword
let title_results: Vec<(String, String, f64)> = {
let clean_query = req.query.replace('\'', "''");
let clean_query_escaped = clean_query.replace('\'', "''");
let v_table = crate::core::db::schema::table_name("videos");
let c_table = crate::core::db::schema::table_name("chunk");
let video_rows: Vec<(String,)> = sqlx::query_as(&format!(
"SELECT file_uuid::text FROM {} WHERE file_name ILIKE $1 LIMIT 5",
v_table
))
.bind(format!("%{}%", clean_query))
.bind(format!("%{}%", clean_query_escaped))
.fetch_all(db.pool())
.await
.unwrap_or_default();
@@ -261,12 +297,12 @@ pub async fn smart_search(
// 4. Identity search: if query matches a person name, get their chunks
let identity_results: Vec<(String, String, f64)> = {
let id_table = crate::core::db::schema::table_name("identities");
let clean_query = req.query.replace('\'', "''");
let clean_query_escaped = clean_query.replace('\'', "''");
let id_rows: Vec<(i32, String, String)> = sqlx::query_as(&format!(
"SELECT id, name, uuid::text FROM {} WHERE name ILIKE $1 LIMIT 5",
id_table
))
.bind(format!("%{}%", clean_query))
.bind(format!("%{}%", clean_query_escaped))
.fetch_all(db.pool())
.await
.unwrap_or_default();
@@ -407,7 +443,7 @@ pub async fn smart_search(
);
// 6. Enrich top results from PG and build final response
let query_lower = req.query.to_lowercase();
let query_lower = clean_query.to_lowercase();
let mut final_results = Vec::new();
// Take all merged results to ensure keyword results are processed
// (keyword results often have low scores and rank last)
@@ -423,6 +459,14 @@ pub async fn smart_search(
.await
};
if let Some(pg) = pg_opt.ok().flatten() {
// Apply source filter (/ocr /asr /asrx)
if let Some(ref filter) = source_filter {
let st = map_chunk_type_to_source(&pg.chunk_type);
if st != *filter {
continue;
}
}
// 關鍵字結果跳過 text_match 過濾(search_bm25 已經匹配過)
// Semantic-only results 也跳過 text_match(語意匹配不需要詞彙匹配)
let is_keyword_only = mr.keyword_score.is_some() && mr.semantic_score.is_none();
@@ -583,9 +627,14 @@ pub async fn keyword_search(
let page_size = req.page_size.unwrap_or(5).max(1);
let limit = page_size;
let (clean_query, source_filter) = parse_source_filter(&req.query);
let chunk_type_filter = source_filter
.as_deref()
.map(source_filter_to_chunk_type);
// Keyword search via PG BM25
let keyword_results = db
.search_bm25(&req.query, req.file_uuid.as_deref(), limit as i64)
.search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, limit as i64)
.await
.map_err(|e| {
tracing::error!("Keyword search failed: {}", e);
@@ -650,9 +699,11 @@ pub async fn semantic_search(
let page_size = req.page_size.unwrap_or(5).max(1);
let limit = page_size;
// Generate embedding
let (clean_query, source_filter) = parse_source_filter(&req.query);
// Generate embedding from clean query
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let embedding = embedder.embed_query(&req.query).await.map_err(|e| {
let embedding = embedder.embed_query(&clean_query).await.map_err(|e| {
tracing::error!("Embedding failed: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
@@ -660,7 +711,7 @@ pub async fn semantic_search(
)
})?;
// Semantic search via Qdrant
// Semantic search via Qdrant (only has sentence vectors, so /ocr returns empty)
let semantic_results = if let Some(file_uuid) = &req.file_uuid {
qdrant
.search_in_uuid(&embedding, file_uuid, limit)
@@ -673,12 +724,17 @@ pub async fn semantic_search(
tracing::info!(
"Semantic search: {} hits for '{}'",
semantic_results.len(),
req.query
clean_query
);
let mut results = Vec::new();
for hit in semantic_results.iter() {
if let Some(p) = enrich_from_pg(db, &hit.uuid, &hit.chunk_id, hit.score).await {
if let Some(ref filter) = source_filter {
if p.source_type.as_deref() != Some(filter.as_str()) {
continue;
}
}
results.push(p);
}
}