From 7c54c7b7e72dd57efaf6de3f5664e015f12a19d5 Mon Sep 17 00:00:00 2001 From: Accusys Date: Wed, 23 Sep 2026 19:28:11 +0800 Subject: [PATCH] feat(cleanup): add orphan vector cleanup bin + Studio scene VLM search design suggestions - src/bin/cleanup_orphan_vectors.rs: one-time tool to scan per-file Qdrant collections (rule1/_faces/_scenes/_vlm/_seeds/face_embeddings/speaker), dry-run support, delete points whose file_uuid is no longer registered. Used to remove 53,122 orphan vectors across all production collections. - docs: scene VLM search design suggestions for Studio team (8868 proxy) --- ...-23_scene_vlm_search_design_suggestions.md | 197 ++++++++++++++++++ src/bin/cleanup_orphan_vectors.rs | 153 ++++++++++++++ 2 files changed, 350 insertions(+) create mode 100644 docs_v1.0/STUDIO_TEAM/2026-09-23_scene_vlm_search_design_suggestions.md create mode 100644 src/bin/cleanup_orphan_vectors.rs diff --git a/docs_v1.0/STUDIO_TEAM/2026-09-23_scene_vlm_search_design_suggestions.md b/docs_v1.0/STUDIO_TEAM/2026-09-23_scene_vlm_search_design_suggestions.md new file mode 100644 index 00000000..3f39a39f --- /dev/null +++ b/docs_v1.0/STUDIO_TEAM/2026-09-23_scene_vlm_search_design_suggestions.md @@ -0,0 +1,197 @@ +--- +title: Scene VLM Search - Design Suggestions for Studio Team +version: 1.0 +date: 2026-09-23 +author: Core Team +status: proposal +--- + +# Scene VLM Search — 設計建議(Studio Team) + +**Date**: 2026-09-23 +**Priority**: Medium +**影響**: 一般搜尋(Keyword / Semantic)找不到「視覺內容」的影片,如小狗、穿粉色外套的人等 + +--- + +## 執行摘要 + +Studio 的搜尋模式目前**只搜尋「台詞文字」**(ASRX / OCR chunks),**不涵蓋 Scene VLM 的視覺描述**。因此當使用者以視覺特徵(例如 "pink dog" / "小狗穿粉色外套")搜尋時,即使 Scene VLM 已正確產生並寫入向量資料庫,一般搜尋仍是空結果。Core 團隊已完備後端能力(scene/trace 向量搜尋 API + agent vlm_search tool),**建議 Studio 在 UI 整合以提供完整的視覺搜尋體驗**。 + +--- + +## 問題描述 + +### 用戶症狀 +- 在搜尋欄(Keyword 或 Semantic 模式)輸入 "pink dog" → 找不到 019.mp4 的小狗 +- 但以 Agent 模式搜尋相同詞 → 正確找到小狗場景 + +### 根本原因 +- **Keyword 模式** (`/api/v1/search/keyword`):PostgreSQL FTS,只搜 ASRX 台詞、OCR、檔案名稱等**文字欄位**,不含 Scene VLM 描述 +- **Semantic 模式** (`/api/v1/search/semantic`):嵌入向量搜尋,但只搜**台詞 chunks**(`source_type: "asrx"`),不含 Scene VLM +- **Scene VLM 內容**存在於 `_scenes` collection 的向量 embedding(描述:\`The image shows a small dog wearing a pink jacket...\`),是唯一描述視覺特徵的來源 + +**結論**:不是資料問題,是**搜尋涵蓋範圍**問題。小狗沒有出現在任何台詞/OCR 中,只在 Scene VLM 描述裡。 + +--- + +## 後端現況(Core 已提供) + +### 現有可用 API + +| API | 說明 | +|-----|------| +| `POST /api/v1/search/vlm/scenes` | Scene VLM 向量搜尋(詳細場景描述) | +| `POST /api/v1/search/vlm/traces` | Trace VLM 向量搜尋(人物外觀描述) | +| `POST /api/v1/search/vlm/debug` | **新增(2026-09-23)**:一次嵌入、平行搜 scenes + traces,回傳**原始 raw hits**(score + 完整 payload),方便 debug / 前端開發 | +| `GET /api/v1/file/:file_uuid/scenes/scene_NNN.jpg` | Scene 縮圖(直接可顯示) | +| `POST /api/v1/agents/search` | Agent search(已整合 vlm_search tool,優先查視覺),**目前唯一能搜到視覺內容的入口** | + +### 測試結果(2026-09-23,production 3002) + +`POST /api/v1/search/vlm/debug` body `{"query":"pink dog","limit":5}`: + +``` +=== SCENES (_scenes) === +score=0.695 file=71c4436844735d25 idx=2 ts=10.01 + "The image shows a small dog wearing a pink jacket with a pattern of ..." +score=0.690 file=71c4436844735d25 idx=1 ts=8.49 +score=0.681 file=71c4436844735d25 idx=0 ts=2.50 +``` + +→ 019.mp4 的 3 個場景 embedding 全部正確命中。 + +--- + +## 設計建議(給 Studio Team) + +以下方案可**獨立採行或組合**,依 Studio 設計取捨: + +### 方案 A:Semantic 模式合併 Scene 結果(推薦先做) + +在 Semantic 模式搜尋時,**併行呼叫 scene VLM 搜尋**,與台詞結果合併顯示: + +``` +使用者輸入 → Promise.all([ + /api/v1/search/semantic (台詞, source_type: "asrx") + /api/v1/search/vlm/scenes (場景描述, source_type: "scene") +]) +→ merge 統一渲染 +``` + +**建議的 Scene 結果卡片欄位**(`SceneSearchResult`): +| 欄位 | 用途 | +|------|------| +| `file_uuid` / `file_name` | 檔案識別 | +| `scene_index` | 場景編號(顯示 "Scene 0") | +| `timestamp_sec` / `frame_number` | 定位跳轉 | +| `thumbnail_url` | 直接顯示縮圖 | +| `vlm_description` | VLM 描述文字(取 2-3 行) | +| `score` | 相似度(前端可設門檻如 0.6) | + +**前端建議**: +- 用 `thumbnail_url` 作為卡片主視覺,VLM 描述為重點文案 +- `source_type: "scene"` 以 badge/icon 與 ASRX 台詞結果區分 +- Scene 結果排序:與台詞結果合併後依 score 遞減,或分區顯示(Scenes / Speech) + +### 方案 B:新增「視覺搜尋」快速模式 + +在搜尋欄模式列新增獨立的 **"Visual"** 模式(或多一個分頁),明確給使用者「搜視覺特徵」的入口: + +``` +模式: Keyword | Semantic | Visual | Agent | People +``` + +- Visual 模式直接呼叫 `POST /api/v1/search/vlm/debug`(或 scenes/traces 分開呼叫) +- 回傳兩區塊:**Scenes** 與 **People/Traces**,各自附縮圖與描述 +- 這對「我記得畫面但不知道講了什麼」的查詢最直覺 + +### 方案 C:Agent 模式提示(低成本) + +若暫不整合,至少讓使用者知道 Agent 模式能搜視覺: +- 搜尋列 placeholder / 模式 tooltip 加上提示:「搜畫面特徵(如 *pink dog*)請用 Agent 模式」 +- 這是最低成本但務實的短期解法 + +### 方案 D(進階):Semantic + Scene 混合排序 + +將 scene 向量搜尋結果與 semantic 台詞結果**合併後統一 rerank**(依 score 混合排序),並在前端以 `source_type` 標籤呈現。這接近「一站式搜尋」體驗,適合未來整合進「全部」搜尋。 + +--- + +## 驗證方式(Studio 可自行測試) + +```bash +# 1. 確認 Scene VLM 搜尋有資料 +curl -X POST "http://localhost:3002/api/v1/search/vlm/scenes" \ + -H "Content-Type: application/json" \ + -d '{"query":"pink dog","page_size":5}' + +# 2. 確認 Scene 縮圖可用 +# GET /api/v1/file/71c4436844735d258fe76bcdd34229c6/scenes/scene_000.jpg + +# 3. Agent 模式(目前唯一可搜視覺的入口) +curl -X POST "http://localhost:3002/api/v1/agents/search" \ + -H "Content-Type: application/json" \ + -d '{"query":"pink dog"}' +``` + +> 注意:所有測試請使用 `localhost:3003`(Playground)或確認 production 行為時才用 3002。 + +--- + +## 2026-09-23 補充:Visual 模式 "dog" 空結果診斷 + +### 後端核查(Core 已驗證,全部正常 ✅) + +| 檢查項 | 結果 | +|--------|------| +| `POST /api/v1/search/vlm/scenes` `{"query":"dog"}` | ✅ 回 019.mp4 3 筆 scene(score 0.65~0.67,`scene_index` 0/1/2) | +| `POST /api/v1/search/vlm/traces` `{"query":"dog"}` | ✅ 回 10 筆 trace | +| `/api/v1/files/scan` | ✅ 含 019(`is_registered=True`, file_uuid 無連字號) | +| 8888 proxy (`momentry_server`) | ✅ 不需 api_key,正確轉發 vlm/scenes | +| 後端 registered 過濾(videos 表 whitelist) | ✅ 已套用(見本文件前段) | + +### 前端口徑(Studio 實作現況) + +- `Visual` 模式位於 `/Users/accusys/momentry_studio/src/views/SearchView.vue:934-990` +- 呼叫 `vlm/scenes` + `vlm/traces`,**無 API key**(經 8888/Vite proxy 不擋,OK) +- 前端自行用 `filesCache` 過濾 unregistered(955-956 行): + ```ts + const registeredUuids = new Set(filesCache.value.map((f: any) => f.file_uuid || f.uuid)) + const scenes = ((scenesRes?.results || scenesRes || []) as any[]).filter((s: any) => registeredUuids.has(s.file_uuid)) + ``` + +### ⚠️ 最可能問題:前端 filesCache stale + +- `ensureFiles()`(`/Users/accusys/momentry_studio/src/store.ts:574`)有 `if (filesLoaded.value) return` 快取 +- 若 SearchView 的 `filesCache` 在 019.mp4 註冊(2026-09-23 00:55)**之前**就已載入,且期間無人呼叫 `invalidateFiles()`,則 `filesCache` 不含 019 → 955 行 `registeredUuids.has("71c44368...")` 為 false → **019 全部被前端過濾掉 → "No results found"** +- 後端資料、proxy、過濾全正常,**唯前端 cache 過期即空結果** + +### Studio 建議動作 + +1. **重載頁面(Cmd+R)後再測 Visual 'dog'** → 若立即有結果,即為 cache stale 確認 +2. 程式層根治(擇一): + - Visual 模式改用 Core 提供的 `/api/v1/search/vlm/debug`(後端已內建 registered 過濾,前端可不再自做 whitelist) + - 或在 Visual 搜尋前先 `invalidateFiles()` / `ensureFiles(true)` 重抓 scan +3. `vlm/scenes` 回傳 key 為 `scene_index`(非 `index`)——目前 SearchView.vue:959 用 `s.index ?? s.scene_index` 已相容,OK + +--- + +## Core 已提供的配套 + +| 項目 | 狀態 | +|------|------| +| `vlm_search` agent tool(優先查視覺 + 人物) | ✅ 已部署至 production | +| `/api/v1/search/vlm/debug`(raw hits + registered 過濾) | ✅ 已部署至 production | +| `/api/v1/search/vlm/scenes` / `traces`(registered 過濾) | ✅ 已部署至 production | +| Scene VLM 自動索引 | ✅ Worker 正常 | +| Scene/Thumbnail 路由 | ✅ 已存在 | + +--- + +## 歷史記錄 + +| 版本 | 日期 | 變更 | +|------|------|------| +| 1.1 | 2026-09-23 | 新增 Visual 模式 "dog" 空結果診斷(後端正常/前端 cache stale 疑點) | +| 1.0 | 2026-09-23 | 初始設計建議(Scene VLM 搜尋整合方案) | \ No newline at end of file diff --git a/src/bin/cleanup_orphan_vectors.rs b/src/bin/cleanup_orphan_vectors.rs new file mode 100644 index 00000000..7abdcac5 --- /dev/null +++ b/src/bin/cleanup_orphan_vectors.rs @@ -0,0 +1,153 @@ +use std::collections::{HashMap, HashSet}; +use std::time::Instant; + +use anyhow::{Context, Result}; +use serde_json::Value; +use sqlx::Row; + +use momentry_core::{Database, PostgresDb, QdrantDb}; + +/// One-time cleanup of Qdrant orphan vectors (file_uuid no longer registered in the +/// `videos` table). Scans all per-file collections, deletes points whose file_uuid is +/// not in the registered set, and reports before/after counts. +/// +/// Points whose payload has no `file_uuid` (or null) are left untouched (e.g. TMDb +/// identity seeds not tied to any file). +/// +/// Usage: +/// cargo run --bin cleanup_orphan_vectors +/// cargo run --bin cleanup_orphan_vectors -- --dry-run +#[tokio::main] +async fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let dry_run = args.iter().any(|a| a == "--dry-run"); + + dotenv::dotenv().ok(); + tracing_subscriber::fmt::init(); + + let pg = PostgresDb::init() + .await + .context("Failed to init PostgreSQL")?; + + let registered_rows = sqlx::query("SELECT file_uuid FROM videos") + .fetch_all(pg.pool()) + .await + .context("Failed to read registered file_uuids")?; + let registered: HashSet = registered_rows + .into_iter() + .filter_map(|r| r.try_get::("file_uuid").ok()) + .collect(); + println!( + "Registered file_uuids in videos table: {}", + registered.len() + ); + + let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string()); + let speaker_collection = if schema == "public" { + "momentry_public_speaker".to_string() + } else { + format!("momentry_{}_speaker", schema) + }; + + let qdrant = QdrantDb::new(); + let collections = vec![ + qdrant.collection_name.clone(), + "_faces".to_string(), + "_scenes".to_string(), + "_vlm".to_string(), + "_seeds".to_string(), + format!("{}_face_embeddings", schema), + speaker_collection, + ]; + + let mut grand_total_deleted = 0u64; + for collection in &collections { + let start = Instant::now(); + let before = qdrant + .count_points(collection, Value::Null) + .await + .unwrap_or(0) as usize; + + let need_delete = { + let all_points = qdrant + .scroll_all_points(collection, Value::Null, 2000) + .await + .unwrap_or_else(|e| { + println!(" [warn] scroll failed for `{}`: {}", collection, e); + Vec::new() + }); + collect_orphan_uuids(all_points, ®istered) + }; + + if need_delete.is_empty() { + println!( + "{:>28}: {} points, no orphans ({:?})", + collection, + before, + start.elapsed() + ); + continue; + } + + let orphan_points: u64 = need_delete.values().sum(); + println!( + "{:>28}: {} points, {} orphan uuids, {} orphan points ({:?})", + collection, + before, + need_delete.len(), + orphan_points, + start.elapsed() + ); + + if dry_run { + for (uuid, n) in &need_delete { + println!(" [dry-run] delete {} points of {}", n, uuid); + } + continue; + } + + for (uuid, n) in need_delete { + match qdrant + .delete_points_by_filter( + collection, + serde_json::json!({ + "must": [{ "key": "file_uuid", "match": { "value": uuid } }] + }), + ) + .await + { + Ok(_) => { + grand_total_deleted += n; + println!(" deleted {} points of {}", n, uuid); + } + Err(e) => println!(" [warn] failed to delete {} ({}): {}", uuid, n, e), + } + } + } + + println!( + "\nDone. Total orphan points deleted: {}", + grand_total_deleted + ); + Ok(()) +} + +/// Collect file_uuids present in the given points that are missing from `registered`. +/// No-file_uuid (null/absent) payloads are ignored so shared seeds are preserved. +fn collect_orphan_uuids(points: Vec, registered: &HashSet) -> HashMap { + let mut counts: HashMap = HashMap::new(); + for point in points { + let file_uuid = point + .get("payload") + .and_then(|p| p.get("file_uuid")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + if file_uuid.is_empty() || file_uuid == "?" { + continue; + } + if !registered.contains(file_uuid) { + *counts.entry(file_uuid.to_string()).or_insert(0) += 1; + } + } + counts +}