//! Smart Search API //! Hybrid search: semantic (Qdrant) + keyword (PG ILIKE) + identity (person name → chunks). //! Uses Reciprocal Rank Fusion (RRF) to merge and deduplicate results. use axum::{extract::State, http::StatusCode, response::Json, routing::post, Router}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use crate::core::db::postgres_db::SemanticSearchResult; use crate::core::embedding::Embedder; // --- Request / Response Structures --- #[derive(Debug, Deserialize)] pub struct SmartSearchRequest { #[serde(default)] pub file_uuid: Option, pub query: String, pub page: Option, pub page_size: Option, pub limit: Option, } #[derive(Debug, Clone, Serialize)] pub struct SearchResult { pub id: i32, pub file_uuid: Option, pub parent_id: i32, pub scene_order: Option, pub start_frame: i64, pub end_frame: i64, pub fps: f64, pub start_time: f64, pub end_time: f64, pub raw_text: Option, pub summary: Option, pub text_content: Option, pub metadata: Option, pub similarity: Option, pub file_name: Option, pub serve_url: Option, pub thumbnail_url: Option, pub source_type: Option, } #[derive(Debug, Serialize)] pub struct SmartSearchResponse { pub query: String, pub results: Vec, pub page: usize, pub page_size: usize, pub strategy: String, } /// Internal merged result with score-based merge #[derive(Debug)] struct MergedResult { file_uuid: String, chunk_id: String, score: f64, semantic_score: Option, keyword_score: Option, identity_score: Option, 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) { 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(), "sentence" => "asrx".to_string(), other => other.to_string(), } } /// Enrich a Qdrant search result with full data from PostgreSQL. /// Falls back to trace_profiles lookup for VLM summary results (matched by vlm_point_id). async fn enrich_from_pg( db: &crate::core::db::PostgresDb, file_uuid: &str, chunk_id: &str, qdrant_score: f32, ) -> Option { match db.get_chunk_by_file_and_chunk_id(file_uuid, chunk_id).await { Ok(Some(p)) => Some(SearchResult { id: 0, file_uuid: p.file_uuid.clone(), parent_id: p.scene_order, scene_order: Some(p.scene_order), start_frame: p.start_frame, end_frame: p.end_frame, fps: p.fps, start_time: p.start_time, end_time: p.end_time, raw_text: None, summary: Some(p.summary), text_content: p.text_content.clone(), metadata: p.metadata.clone(), similarity: Some(qdrant_score as f64), file_name: None, serve_url: None, thumbnail_url: None, source_type: Some(map_chunk_type_to_source(&p.chunk_type)), }), Ok(None) => { // Chunk not found — try VLM summary lookup by vlm_point_id enrich_vlm_from_pg(db, file_uuid, chunk_id, qdrant_score).await } Err(e) => { tracing::warn!("PG enrichment failed for {} {}: {}", file_uuid, chunk_id, e); None } } } /// Enrich a VLM summary search result from trace_profiles. /// The chunk_id from Qdrant is in format "{file_uuid}_t{trace_id_hex}". async fn enrich_vlm_from_pg( db: &crate::core::db::PostgresDb, file_uuid: &str, chunk_id: &str, qdrant_score: f32, ) -> Option { // Extract trace_id from chunk_id format: "{file_uuid}_t{trace_id_hex}" // file_uuid is 32 chars, then "_t" (2 chars), then hex trace_id let trace_id: i32 = if chunk_id.len() > 34 && chunk_id.starts_with(file_uuid) { let hex_part = &chunk_id[34..]; // after "{file_uuid}_t" i32::from_str_radix(hex_part, 16).ok()? } else { return None; }; let tp_table = crate::core::db::schema::table_name("trace_profiles"); let rows: Vec<(Option, Option, Option)> = sqlx::query_as(&format!( "SELECT start_frame, end_frame, vlm_description FROM {tp_table} \ WHERE file_uuid = $1 AND trace_id = $2" )) .bind(file_uuid) .bind(trace_id) .fetch_all(db.pool()) .await .ok()?; let (start_frame, end_frame, vlm_desc) = rows.into_iter().next()?; let text = vlm_desc.unwrap_or_default(); let sf = start_frame.unwrap_or(0); let ef = end_frame.unwrap_or(0); Some(SearchResult { id: 0, file_uuid: Some(file_uuid.to_string()), parent_id: 0, scene_order: None, start_frame: sf, end_frame: ef, fps: 0.0, start_time: 0.0, end_time: 0.0, raw_text: None, summary: Some(format!("VLM trace_{}", trace_id)), text_content: Some(text), metadata: Some(serde_json::json!({ "type": "vlm_summary", "trace_id": trace_id, })), similarity: Some(qdrant_score as f64), file_name: None, serve_url: None, thumbnail_url: Some(format!("/api/v1/file/{}/trace/{}/thumbnail", file_uuid, trace_id)), source_type: Some("vlm".to_string()), }) } fn pg_result_to_search(p: &SemanticSearchResult) -> SearchResult { SearchResult { id: 0, file_uuid: p.file_uuid.clone(), parent_id: p.scene_order, scene_order: Some(p.scene_order), start_frame: p.start_frame, end_frame: p.end_frame, fps: p.fps, start_time: p.start_time, end_time: p.end_time, raw_text: None, summary: Some(p.summary.clone()), text_content: p.text_content.clone(), metadata: p.metadata.clone(), similarity: p.similarity, file_name: None, serve_url: None, thumbnail_url: None, source_type: Some(map_chunk_type_to_source(&p.chunk_type)), } } // --- API Handler --- pub async fn smart_search( State(state): State, Json(req): Json, ) -> Result, (StatusCode, Json)> { let db = &state.db; let qdrant = &state.qdrant; let page = req.page.unwrap_or(1).max(1); let page_size = if req.page_size.is_some() { req.page_size.unwrap() } else if req.limit.is_some() && req.page.is_none() { req.limit.unwrap() } else { 5 } .max(1); let hard_limit = req.limit.unwrap_or(usize::MAX); let limit = hard_limit.min(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); // 1. Generate embedding from clean query let embedder = Embedder::new("embeddinggemma-300m".to_string()); let embedding = embedder.embed_query(&clean_query).await.map_err( |e| -> (StatusCode, Json) { tracing::error!("Embedding failed: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({ "error": e.to_string() })), ) }, )?; const IDENTITY_FIXED_SCORE: f64 = 0.85; let fetch_limit = limit * 3; // 2. Semantic search via Qdrant let semantic_results: Vec<(String, String, f64)> = if let Some(file_uuid) = &req.file_uuid { let qdrant_hits = qdrant .search_in_uuid(&embedding, file_uuid, fetch_limit) .await .unwrap_or_default(); tracing::info!( "Smart search: Qdrant search_in_uuid for {} returned {} hits", file_uuid, qdrant_hits.len() ); qdrant_hits .into_iter() .map(|h| (h.uuid, h.chunk_id, h.score as f64)) .collect() } else { let qdrant_hits = qdrant .search(&embedding, fetch_limit) .await .unwrap_or_default(); tracing::info!( "Smart search: Qdrant search (no uuid filter) returned {} hits", qdrant_hits.len() ); qdrant_hits .into_iter() .map(|h| (h.uuid, h.chunk_id, h.score as f64)) .collect() }; // 3. Keyword search via PG ILIKE let keyword_results: Vec<(String, String, f64)> = match db .search_bm25( &clean_query, req.file_uuid.as_deref(), chunk_type_filter, fetch_limit as i64, ) .await { Ok(rows) => { tracing::info!( "Smart search: Keyword search returned {} hits for '{}'", rows.len(), req.query ); rows.into_iter() .map(|r| (r.file_uuid, r.chunk_id, r.combined_score)) .collect() } Err(e) => { tracing::warn!("Keyword search (bm25) failed: {}", e); vec![] } }; // 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_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_escaped)) .fetch_all(db.pool()) .await .unwrap_or_default(); let mut chunks = Vec::new(); for (fu,) in video_rows.iter() { if let Some(ref f) = req.file_uuid { if fu != f { continue; } } let rows: Vec<(String, String)> = sqlx::query_as(&format!( "SELECT chunk_id, file_uuid::text FROM {} \ WHERE file_uuid = $1 AND embedding IS NOT NULL \ AND chunk_type = 'sentence' \ LIMIT 20", c_table )) .bind(fu) .fetch_all(db.pool()) .await .unwrap_or_default(); for (cid, file_uuid) in rows { chunks.push((file_uuid, cid, TITLE_MATCH_SCORE)); } } chunks }; // 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_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_escaped)) .fetch_all(db.pool()) .await .unwrap_or_default(); let mut id_chunks = Vec::new(); for (identity_id, _, uuid_text) in id_rows.iter().take(3) { let clean_uuid = uuid_text.replace('-', ""); match db.get_identity_chunks(&clean_uuid, 20, 0).await { Ok(chunks) => { for chunk in chunks { if let Some(ref fu) = req.file_uuid { if &chunk.file_uuid != fu { continue; } } id_chunks.push((chunk.file_uuid, chunk.chunk_id, 0.85)); } } Err(e) => { tracing::debug!("get_identity_chunks for {} failed: {}", clean_uuid, e); } } } id_chunks }; // 5. Score-based merge: combine results from all sources let mut merged: HashMap<(String, String), MergedResult> = HashMap::new(); // Add semantic results (use Qdrant cosine score directly) for (file_uuid, chunk_id, score) in semantic_results.iter() { let key = (file_uuid.clone(), chunk_id.clone()); merged .entry(key) .and_modify(|e| { e.score = e.score.max(*score); e.semantic_score = Some(*score); e.source = format!( "{}_{}", e.source.strip_prefix("semantic+").unwrap_or(&e.source), "semantic" ); }) .or_insert(MergedResult { file_uuid: file_uuid.clone(), chunk_id: chunk_id.clone(), score: *score, semantic_score: Some(*score), keyword_score: None, identity_score: None, source: "semantic".to_string(), }); } // Add keyword results (score from FTS rank) for (file_uuid, chunk_id, actual_score) in keyword_results.iter() { let key = (file_uuid.clone(), chunk_id.clone()); // Use actual BM25 score (typically 0.01-0.5), boost it to be competitive with semantic (0.6-0.9) let boosted = (actual_score * 2.0).min(0.85).max(0.1); // Boost BM25 score merged .entry(key) .and_modify(|e| { e.score = e.score.max(boosted); e.keyword_score = Some(boosted); e.source = format!("{}_keyword", e.source); }) .or_insert(MergedResult { file_uuid: file_uuid.clone(), chunk_id: chunk_id.clone(), score: boosted, semantic_score: None, keyword_score: Some(boosted), identity_score: None, source: "keyword".to_string(), }); } // Add title match results (high score 0.9) — query matched video title let has_title_match = !title_results.is_empty(); let title_fixed = TITLE_MATCH_SCORE; for (file_uuid, chunk_id, _) in title_results.iter() { let key = (file_uuid.clone(), chunk_id.clone()); merged .entry(key) .and_modify(|e| { e.score = e.score.max(title_fixed); e.source = format!("{}_title", e.source); }) .or_insert(MergedResult { file_uuid: file_uuid.clone(), chunk_id: chunk_id.clone(), score: title_fixed, semantic_score: None, keyword_score: None, identity_score: None, source: "title".to_string(), }); } // Add identity results (fixed score 0.85) let has_identity_match = !identity_results.is_empty(); let identity_fixed = IDENTITY_FIXED_SCORE; for (file_uuid, chunk_id, _) in identity_results.iter() { let key = (file_uuid.clone(), chunk_id.clone()); merged .entry(key) .and_modify(|e| { e.score = e.score.max(identity_fixed); e.identity_score = Some(identity_fixed); e.source = format!("{}_identity", e.source); }) .or_insert(MergedResult { file_uuid: file_uuid.clone(), chunk_id: chunk_id.clone(), score: identity_fixed, semantic_score: None, keyword_score: None, identity_score: Some(identity_fixed), source: "identity".to_string(), }); } // Sort by score descending (score-based merge) let mut ranked: Vec<&MergedResult> = merged.values().collect(); ranked.sort_by(|a, b| { b.score .partial_cmp(&a.score) .unwrap_or(std::cmp::Ordering::Equal) }); tracing::info!( "Smart search: Merged {} results (semantic={}, keyword={}, title={}, identity={})", merged.len(), semantic_results.len(), keyword_results.len(), title_results.len(), identity_results.len() ); // 6. Enrich top results from PG and build final response 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) let take_count = ranked.len(); for mr in ranked.iter().take(take_count) { // 取更多結果以便過濾 // Use no_embedding version for keyword results, regular for semantic let pg_opt = if mr.keyword_score.is_some() && mr.semantic_score.is_none() { db.get_chunk_by_id_no_embedding(&mr.file_uuid, &mr.chunk_id) .await } else { db.get_chunk_by_file_and_chunk_id(&mr.file_uuid, &mr.chunk_id) .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(); let is_semantic_only = mr.semantic_score.is_some() && mr.keyword_score.is_none(); let skip_text_match = is_keyword_only || is_semantic_only; if !skip_text_match { // 關鍵字過濾: CJK 用子字串匹配,英文用單詞邊界匹配 // 使用 text_content 或 summary 進行匹配 let match_text = if pg.summary.is_empty() { pg.text_content.clone().unwrap_or_default() } else { pg.summary.clone() }; let summary_lower = match_text.to_lowercase(); let query_words: Vec = query_lower .split_whitespace() .map(|s| s.to_string()) .collect(); let text_match = !match_text.is_empty() && { let has_cjk = |s: &str| -> bool { s.chars().any(|c| { ('\u{4E00}'..='\u{9FFF}').contains(&c) || ('\u{3040}'..='\u{309F}').contains(&c) || ('\u{30A0}'..='\u{30FF}').contains(&c) || ('\u{AC00}'..='\u{D7AF}').contains(&c) }) }; if has_cjk(&query_lower) || has_cjk(&summary_lower) { query_words.iter().all(|w| summary_lower.contains(w)) } else { let bordered = format!(" {} ", summary_lower); query_words .iter() .all(|w| bordered.contains(&format!(" {} ", w))) } }; if !text_match { continue; } } // 使用 text_content 如果 summary 為空 let display_text = if pg.summary.is_empty() { pg.text_content.clone().unwrap_or_default() } else { pg.summary.clone() }; let source_type_value = map_chunk_type_to_source(&pg.chunk_type); let source_prefix = if pg.chunk_type == "ocr" { "[OCR] " } else if pg.chunk_type == "sentence" { "[ASRX] " } else { "" }; final_results.push(SearchResult { id: 0, file_uuid: pg.file_uuid.clone(), parent_id: pg.scene_order, scene_order: Some(pg.scene_order), start_frame: pg.start_frame, end_frame: pg.end_frame, fps: pg.fps, start_time: pg.start_time, end_time: pg.end_time, raw_text: None, summary: Some(format!("{}{}", source_prefix, display_text)), text_content: Some(format!( "{}{}", source_prefix, pg.text_content.clone().unwrap_or_default() )), metadata: pg.metadata.clone(), similarity: Some(mr.score), file_name: None, serve_url: None, thumbnail_url: pg.file_uuid.as_ref().map(|fu| { format!( "/wp-json/momentry/v1/media?type=chunk_thumbnail&file_uuid={}&chunk_id={}", fu, mr.chunk_id ) }), source_type: Some(source_type_value), }); } } // Trim to requested limit final_results.truncate(limit); // 7. Enrich results with file_name and serve_url from videos table if !final_results.is_empty() { let v_table = crate::core::db::schema::table_name("videos"); let file_uuids: Vec = final_results .iter() .filter_map(|r| r.file_uuid.clone()) .collect(); let file_rows: Vec<(String, String, String)> = sqlx::query_as(&format!( "SELECT file_uuid::text, file_name, file_path FROM {} WHERE file_uuid = ANY($1)", v_table )) .bind(&file_uuids) .fetch_all(db.pool()) .await .unwrap_or_default(); let file_map: std::collections::HashMap = file_rows .into_iter() .map(|(uuid, name, path)| (uuid, (name, path))) .collect(); let storage_root = crate::core::config::STORAGE_ROOT.as_str(); let serve_base = crate::core::config::SERVE_BASE_URL.as_str(); for r in &mut final_results { if let Some(ref uuid) = r.file_uuid { if let Some((name, path)) = file_map.get(uuid) { r.file_name = Some(name.clone()); if let Some(relative) = path.strip_prefix(storage_root) { r.serve_url = Some(format!("{}{}", serve_base, relative)); } } } } } // Determine strategy string let mut strategies = vec!["semantic"]; if !keyword_results.is_empty() { strategies.push("keyword"); } if has_identity_match { strategies.push("identity"); } if has_title_match { strategies.push("title"); } Ok(Json(SmartSearchResponse { query: req.query, results: final_results, page, page_size, strategy: format!("hybrid_{}", strategies.join("+")), })) } /// Keyword-only search (BM25, no vector) pub async fn keyword_search( State(state): State, Json(req): Json, ) -> Result, (StatusCode, Json)> { let db = &state.db; let page = req.page.unwrap_or(1).max(1); let limit = req.limit.unwrap_or(req.page_size.unwrap_or(50)).max(1); 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( &clean_query, req.file_uuid.as_deref(), chunk_type_filter, limit as i64, ) .await .map_err(|e| { tracing::error!("Keyword search failed: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({ "error": e.to_string() })), ) })?; tracing::info!( "Keyword search: {} hits for '{}'", keyword_results.len(), req.query ); let mut results = Vec::new(); for row in keyword_results.iter() { if let Ok(Some(p)) = db .get_chunk_by_id_no_embedding(&row.file_uuid, &row.chunk_id) .await { // Use extracted text from BM25 result for relationships, otherwise use chunk's text_content let text = if p.chunk_type == "relationship" { row.text.clone().or_else(|| p.text_content.clone()) } else { p.text_content.clone() }; results.push(SearchResult { id: 0, file_uuid: p.file_uuid.clone(), parent_id: p.scene_order, scene_order: Some(p.scene_order), start_frame: p.start_frame, end_frame: p.end_frame, fps: p.fps, start_time: p.start_time, end_time: p.end_time, raw_text: None, summary: text.clone(), text_content: text, metadata: p.metadata.clone(), similarity: Some(row.bm25_score as f64), file_name: None, serve_url: None, thumbnail_url: None, source_type: Some(map_chunk_type_to_source(&p.chunk_type)), }); } } Ok(Json(SmartSearchResponse { query: req.query, results, page, page_size: limit, strategy: "keyword".to_string(), })) } /// Semantic-only search (vector, no keyword) pub async fn semantic_search( State(state): State, Json(req): Json, ) -> Result, (StatusCode, Json)> { let db = &state.db; let qdrant = &state.qdrant; let page = req.page.unwrap_or(1).max(1); let limit = req.limit.unwrap_or(req.page_size.unwrap_or(5)).max(1); 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(&clean_query).await.map_err(|e| { tracing::error!("Embedding failed: {}", e); ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({ "error": e.to_string() })), ) })?; // Semantic search via Qdrant (only has sentence vectors, so /ocr returns empty) let semantic_results = if let Some(file_uuid) = &req.file_uuid { match qdrant.search_in_uuid(&embedding, file_uuid, limit).await { Ok(results) => { tracing::info!("[qdrant-search] OK: {} results", results.len()); results } Err(e) => { tracing::warn!("Qdrant search_in_uuid failed: {}", e); vec![] } } } else { match qdrant.search(&embedding, limit).await { Ok(results) => results, Err(e) => { tracing::warn!("Qdrant search failed: {}", e); vec![] } } }; tracing::info!( "Semantic search: {} hits for '{}'", semantic_results.len(), 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); } } Ok(Json(SmartSearchResponse { query: req.query, results, page, page_size: limit, strategy: "semantic".to_string(), })) } // --- Router Setup --- pub fn search_routes() -> Router { Router::new() .route("/api/v1/search/smart", post(smart_search)) .route("/api/v1/search/keyword", post(keyword_search)) .route("/api/v1/search/semantic", post(semantic_search)) }