fix: Face processor now saves status and total_faces to face.json

This commit is contained in:
Accusys
2026-09-26 23:06:11 +08:00
parent 8a736a4103
commit 357e585399
99 changed files with 13881 additions and 1065 deletions
@@ -0,0 +1,385 @@
---
title: FS VLM Performance Improvement Feasibility Study
version: 1.0
date: 2026-09-22
author: Core Team
status: Evaluation
---
# FS VLM Performance Improvement Feasibility Study
## Current State Analysis
### Performance Baseline
| Metric | Value | Source |
|--------|-------|--------|
| Processing mode | **Sequential** | `vlm_summary.rs:76` |
| Time per trace | 3-4 seconds |实测 |
| Model | LLaVA (port 8091) | config.rs |
| 22 traces | ~88 seconds | Calculated |
| Pipeline impact | **Blocking** | job_worker.rs |
### Bottleneck Identification
1. **Sequential Processing** ❌
```rust
for (i, &trace_id) in trace_ids.iter().enumerate() {
process_single_trace(...).await; // One at a time
}
```
2. **Slower Model** ❌
- Using: LLaVA (llava-v1.5-7b)
- Better: Gemma4 12B (already used in Scene VLM)
- Speed difference: ~2-3x slower
3. **Pipeline Blocking** ❌
- Job waits for all traces to complete
- Status: "waiting for ingestion"
- User experience: Poor
## Improvement Proposals
### Option 1: Parallel Processing (Recommended)
**Implementation**:
```rust
// Before: Sequential
for trace_id in trace_ids {
process_single_trace(trace_id).await;
}
// After: Parallel (max 5 concurrent)
use futures::stream::{self, StreamExt};
let results: Vec<_> = stream::iter(trace_ids)
.map(|trace_id| process_single_trace(trace_id))
.buffer_unordered(5) // Max 5 concurrent
.collect()
.await;
```
**Expected Performance**:
- 22 traces: 88s → **~18s** (5x improvement)
- With 10 concurrent: **~9s**
**Pros**:
- ✅ Significant speedup (5-10x)
- ✅ Minimal code changes
- ✅ No model change needed
**Cons**:
- ⚠️ Higher memory usage
- ⚠️ Higher GPU load
- ⚠️ Need to tune concurrency limit
**Complexity**: Low
**Risk**: Low
---
### Option 2: Use Gemma4 Instead of LLaVA
**Implementation**:
```rust
// Current
VISION_URL=http://localhost:8091 (LLaVA)
VISION_MODEL=llava-v1.5-7b
// Proposed
VISION_URL=http://localhost:8080 (Gemma4)
VISION_MODEL=gemma-4-12b-it
```
**Expected Performance**:
- Per trace: 3-4s → **1.5-2s** (2x improvement)
- 22 traces: 88s → **~44s** (with sequential)
- With parallel: **~9s** (5 concurrent) → **~4s** (10 concurrent)
**Pros**:
- ✅ Faster model
- ✅ Already deployed for Scene VLM
- ✅ Better quality descriptions
**Cons**:
- ⚠️ Higher GPU memory (12B vs 7B)
- ⚠️ Need to verify model compatibility
**Complexity**: Low
**Risk**: Low
---
### Option 3: Asynchronous Processing
**Implementation**:
```rust
// Spawn in background, don't wait
tokio::spawn(async move {
generate_vlm_summaries(&db, uuid, output_dir, redis).await;
});
// Pipeline continues immediately
// FS VLM runs in background
```
**Expected Performance**:
- Pipeline completion: Immediate
- FS VLM: Still 88s, but non-blocking
- User experience: Much better
**Pros**:
- ✅ No blocking
- ✅ Pipeline completes fast
- ✅ User can see progress
**Cons**:
- ⚠️ FS VLM still slow
- ⚠️ Need progress tracking
- ⚠️ Error handling more complex
**Complexity**: Low
**Risk**: Low
---
### Option 4: Batch Processing
**Implementation**:
```rust
// Combine multiple traces into one VLM call
let batch_prompt = format!(
"Analyze these {} key frames and describe each:",
traces.len()
);
// Single VLM call with multiple images
call_llm_vision_batch(images, batch_prompt).await;
```
**Expected Performance**:
- Network overhead: Reduced
- VLM calls: 22 → 1-3
- Total time: **~10-15s**
**Pros**:
- ✅ Reduced network overhead
- ✅ Fewer VLM calls
**Cons**:
- ❌ Complex prompt engineering
- ❌ Risk of lower quality
- ❌ Need to parse batch response
**Complexity**: Medium
**Risk**: Medium
---
### Option 5: Smart Filtering
**Implementation**:
```rust
// Skip traces that don't need VLM
let skip_conditions = vec![
frame_count == 1, // Single frame
trace_duration < 1.0, // Too short
confidence < 0.7, // Low confidence
is_blurry, // Poor quality
];
// Only process meaningful traces
let filtered: Vec<_> = traces.into_iter()
.filter(|t| !skip_any(t))
.collect();
```
**Expected Performance**:
- 22 traces → **~10-15 traces** (40-50% reduction)
- Time: 88s → **~40-60s**
**Pros**:
- ✅ Reduces unnecessary work
- ✅ Better resource utilization
**Cons**:
- ⚠️ Need tuning heuristics
- ⚠️ May miss important traces
**Complexity**: Low
**Risk**: Low
---
## Recommended Strategy
### Phase 1: Quick Wins (1-2 hours)
1. **Enable Gemma4** (✅ Fastest to implement)
- Update `.env`: `MOMENTRY_LLM_VISION_URL=http://localhost:8080`
- Result: **2x speedup**
2. **Async Processing** (✅ Best UX improvement)
- Spawn in background
- Don't block pipeline
- Result: **Immediate completion**
### Phase 2: Parallel Processing (2-4 hours)
3. **Parallel Execution**
- Max 5-10 concurrent
- Result: **5-10x speedup**
4. **Combined**:
- Gemma4 + Parallel = **10-20x total speedup**
- 22 traces: 88s → **4-9s**
### Phase 3: Optimization (Optional)
5. **Smart Filtering**
- Skip unnecessary traces
- Further 40-50% reduction
## Implementation Plan
### Step 1: Gemma4 Migration
**File**: `/Users/accusys/momentry_core/.env`
```bash
# Current
MOMENTRY_LLM_VISION_URL=http://localhost:8091
MOMENTRY_LLM_VISION_MODEL=llava-v1.5-7b
# Change to
MOMENTRY_LLM_VISION_URL=http://localhost:8080
MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it
```
**Testing**:
```bash
# Test single trace
curl -X POST http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"gemma-4-12b-it","messages":[...]}'
```
### Step 2: Async Processing
**File: `/Users/accusys/momentry_core/src/worker/job_worker.rs`
```rust
// Current (blocking)
let vlm_done_bool: bool = if vlm_total > 0 {
vlm_done_count >= vlm_total
} else {
true
};
// Proposed (non-blocking)
let vlm_done_bool = true; // Skip check
if vlm_total > 0 && vlm_done_count < vlm_total {
// Spawn in background
tokio::spawn(async move {
generate_vlm_summaries(&db, uuid, output_dir, redis).await;
});
}
```
### Step 3: Parallel Processing
**File: `/Users/accusys/momentry_core/src/core/processor/vlm_summary.rs`
```rust
use futures::stream::{self, StreamExt};
let results: Vec<_> = stream::iter(trace_ids)
.map(|&trace_id| {
let db = db.clone();
let file_uuid = file_uuid.to_string();
let output_dir = output_dir.to_string();
async move {
process_single_trace(&db, &file_uuid, trace_id, &output_dir, 0, 0).await
}
})
.buffer_unordered(5) // Max 5 concurrent
.collect()
.await;
// Aggregate results
let (summarized, embedded, errors) = results.into_iter()
.filter_map(|r| r.ok())
.fold((0, 0, 0), |acc, (s, e)| (acc.0 + s as usize, acc.1 + e as usize, acc.2));
```
## Risk Assessment
| Risk | Likelihood | Impact | Mitigation |
|------|-----------|--------|-----------|
| GPU OOM (parallel) | Medium | High | Limit concurrency to 5 |
| Gemma4 quality issues | Low | Medium | Test with sample images |
| Async error handling | Low | Medium | Add retry logic |
| Memory leak | Low | Low | Monitor worker process |
## Performance Targets
| Scenario | Current | Target | Improvement |
|----------|---------|--------|-------------|
| 22 traces (sequential) | 88s | N/A | - |
| 22 traces (Gemma4) | 44s | 44s | 2x |
| 22 traces (Gemma4 + parallel) | - | **9s** | **10x** |
| 22 traces (async) | - | **0s (blocking)** | Immediate |
## Success Metrics
1. **Pipeline completion time**: < 10 seconds (after processors)
2. **FS VLM completion time**: < 15 seconds (22 traces)
3. **User experience**: No "waiting for ingestion"
4. **Resource usage**: GPU memory < 16GB
## Timeline
- **Phase 1** (Gemma4 + async): 2-4 hours
- **Phase 2** (Parallel): 4-8 hours
- **Phase 3** (Optimization): Optional
**Total**: 6-12 hours
## Conclusion
**Recommendation**: Implement Phase 1 immediately, then Phase 2.
**Expected Result**:
- Pipeline: Completes immediately
- FS VLM: 9-15 seconds for 22 traces (10x improvement)
- User experience: Significantly better
**Decision**: Ready to implement with low risk and high impact.
---
## Appendix: Benchmarks
### Test Setup
- Hardware: Apple Silicon M3 Max
- GPU Memory: 48GB
- Model: Gemma4 12B Q4_K_M
- Test file: IMG_9449.mp4 (22 face traces)
### Results (Projected)
| Configuration | Time | Speedup |
|---------------|------|---------|
| Sequential + LLaVA | 88s | 1x |
| Sequential + Gemma4 | 44s | 2x |
| Parallel (5) + LLaVA | 18s | 5x |
| Parallel (5) + Gemma4 | **9s** | **10x** |
| Parallel (10) + Gemma4 | **5s** | **18x** |
### Resource Usage
| Mode | GPU Memory | CPU | Network |
|------|-----------|-----|---------|
| Sequential | 6GB | 10% | Low |
| Parallel (5) | 10GB | 30% | Medium |
| Parallel (10) | 14GB | 50% | High |
+474
View File
@@ -0,0 +1,474 @@
---
title: VLM Search API 设计方案
version: 1.0
date: 2026-09-22
author: OpenCode
status: Draft
---
# VLM Search API 设计方案
## 目标
设计一个专门处理 VLM (Vision Language Model) 类型搜索的 API,综合兼具结构数据与向量的特性,支持 Studio 前端的高级搜索需求。
## 当前问题
### 1. Scene VLM 数据未索引
**现状**:
- Scene VLM 数据存储在 `scenes.json` 文件中
- 未建立向量索引
- 无法通过语义搜索找到场景
**影响**:
- 用户无法通过自然语言搜索场景(如 "a man with a dog in the park")
- 无法基于场景内容进行高级过滤
### 2. Trace VLM 数据已索引但搜索不完善
**现状**:
- Trace VLM 数据已存储在 PostgreSQL `trace_profiles` 表
- 向量已存储在 Qdrant `momentry_rule1` collection
- 但搜索 API 不专门处理 VLM 类型
**影响**:
- 搜索结果混合了文本 chunks 和 VLM summaries
- 无法区分场景搜索和人物搜索
## 设计方案
### 架构概览
```
┌─────────────────────────────────────────────────────────────────┐
│ VLM Search API │
└─────────────────────────────────────────────────────────────────┘
┌──────────────────┐
│ API Gateway │
│ (Axum Router) │
└────────┬─────────┘
│
├─────────────────┬─────────────────┐
│ │ │
v v v
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Scene Search │ │ Trace Search │ │ Hybrid Search │
│ /api/v1/search │ │ /api/v1/search │ │ /api/v1/search │
│ /vlm/scenes │ │ /vlm/traces │ │ /vlm │
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
│ │ │
v v v
┌─────────────────────────────────────────────────────────────────┐
│ Search Processing Layer │
├──────────────────┬──────────────────┬───────────────────────────┤
│ Vector Search │ Structured │ Hybrid Filter │
│ - Qdrant │ Filter │ - Pre-filter │
│ - Cosine │ - PostgreSQL │ - Post-filter │
│ - Embedding │ - JSONB │ - Score merge │
└──────────────────┴──────────────────┴───────────────────────────┘
│ │ │
v v v
┌─────────────────────────────────────────────────────────────────┐
│ Storage Layer │
├─────────────────┬─────────────────┬─────────────────────────────┤
│ PostgreSQL │ Qdrant │ File System │
│ │ Collections │ │
│ - scenes (NEW) │ - _scenes (NEW) │ - scenes.json │
│ - trace_profiles│ - _vlm_summary │ - scene_*.jpg │
│ - videos │ - momentry_rule1│ │
└─────────────────┴─────────────────┴─────────────────────────────┘
```
### 1. 数据存储设计
#### 1.1 新增 PostgreSQL 表:`scenes`
```sql
CREATE TABLE scenes (
id BIGSERIAL PRIMARY KEY,
file_uuid VARCHAR(32) NOT NULL REFERENCES videos(file_uuid) ON DELETE CASCADE,
scene_index INTEGER NOT NULL,
-- 时间信息
timestamp_sec DOUBLE PRECISION NOT NULL,
frame_number BIGINT NOT NULL,
-- 场景信息
filename VARCHAR(255) NOT NULL,
selection_reason VARCHAR(50),
quality_score DOUBLE PRECISION,
-- VLM 数据
vlm_status VARCHAR(20) DEFAULT 'pending',
vlm_description TEXT,
vlm_scene_type VARCHAR(100),
vlm_location VARCHAR(255),
vlm_objects JSONB DEFAULT '[]',
vlm_tags JSONB DEFAULT '[]',
vlm_attributes JSONB,
-- 向量状态
embedding_status VARCHAR(20) DEFAULT 'pending',
embedding_point_id VARCHAR(64),
-- 其他
face_count INTEGER DEFAULT 0,
person_traces JSONB DEFAULT '[]',
has_cut BOOLEAN DEFAULT false,
cut_count INTEGER DEFAULT 0,
scene_info JSONB,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(file_uuid, scene_index)
);
CREATE INDEX idx_scenes_file_uuid ON scenes(file_uuid);
CREATE INDEX idx_scenes_tags ON scenes USING GIN(vlm_tags);
CREATE INDEX idx_scenes_objects ON scenes USING GIN(vlm_objects);
CREATE INDEX idx_scenes_timestamp ON scenes(timestamp_sec);
```
#### 1.2 新增 Qdrant Collection:`_scenes`
**Vector Dimension**: 768 (embeddinggemma-300m)
**Distance**: Cosine
**Payload Schema**:
```json
{
"file_uuid": "string",
"scene_index": "integer",
"timestamp_sec": "float",
"frame_number": "integer",
"vlm_description": "string",
"vlm_objects": ["string"],
"vlm_tags": ["string"],
"vlm_scene_type": "string",
"vlm_location": "string"
}
```
**Point ID 生成**:
```rust
// hash("{file_uuid}_s{scene_index}")
let point_id_str = format!("{}_s{}", file_uuid, scene_index);
let point_id = hash(point_id_str);
```
### 2. API 设计
#### 2.1 Scene VLM Search API
**Endpoint**: `POST /api/v1/search/vlm/scenes`
**请求参数**:
```json
{
"query": "a man with a dog in the park",
"file_uuid": "optional_file_uuid",
"filters": {
"vlm_objects": ["dog", "person"],
"vlm_tags": ["outdoor", "nature"],
"vlm_scene_type": "landscape",
"vlm_location": "park",
"time_range": {
"start_sec": 0,
"end_sec": 120
}
},
"page": 1,
"page_size": 20
}
```
**响应格式**:
```json
{
"results": [
{
"file_uuid": "5285a56e0d999627b11b4479dc51dc74",
"file_name": "42DEA3A169CF2F5CC6E778F034C37B184389A089.mp4",
"scene_index": 13,
"timestamp_sec": 139.5,
"frame_number": 8370,
"thumbnail_url": "/api/v1/files/5285a56e.../scenes/scene_013.jpg",
"vlm_description": "A man is kneeling on a grassy lawn in a park-like setting with trees in the background. He is interacting with a metal frame-like object on the ground.",
"vlm_objects": ["tree", "grass"],
"vlm_tags": ["outdoor"],
"vlm_scene_type": null,
"vlm_location": null,
"score": 0.85,
"source": "vector"
}
],
"total": 1,
"page": 1,
"page_size": 20
}
```
**搜索策略**:
1. **向量搜索**(主):
- 对 `query` 生成 embedding
- Qdrant 搜索 `_scenes` collection
- 返回 cosine similarity score
2. **结构化过滤**(预过滤):
- `vlm_objects`: PostgreSQL JSONB contains 查询
- `vlm_tags`: PostgreSQL JSONB contains 查询
- `time_range`: PostgreSQL timestamp range 查询
3. **混合搜索**:
- 先执行结构化过滤获取候选集
- 再在候选集中执行向量搜索
- 合并结果
#### 2.2 Trace VLM Search API
**Endpoint**: `POST /api/v1/search/vlm/traces`
**请求参数**:
```json
{
"query": "person wearing blue shirt",
"file_uuid": "optional_file_uuid",
"filters": {
"vlm_clothing": "blue shirt",
"vlm_location": "indoor",
"vlm_tags": ["glasses", "elderly"]
},
"page": 1,
"page_size": 20
}
```
**响应格式**:
```json
{
"results": [
{
"file_uuid": "...",
"file_name": "...",
"trace_id": 5,
"identity_uuid": "a9a90105-6d6b-46ff-92da-0c3c1a57dff4",
"identity_name": "John Doe",
"vlm_description": "An elderly man wearing glasses and a blue shirt...",
"vlm_clothing": "blue shirt, dark pants",
"vlm_tags": ["glasses", "elderly"],
"vlm_location": "indoor",
"thumbnail_url": "/api/v1/files/.../traces/trace_5.jpg",
"score": 0.92,
"source": "vector"
}
],
"total": 1,
"page": 1,
"page_size": 20
}
```
#### 2.3 Hybrid VLM Search API
**Endpoint**: `POST /api/v1/search/vlm`
**请求参数**:
```json
{
"query": "person exercising in a gym",
"file_uuid": "optional_file_uuid",
"search_type": "hybrid", // "scenes", "traces", or "hybrid"
"filters": {
"vlm_objects": ["dumbbell"],
"vlm_tags": ["indoor"]
},
"page": 1,
"page_size": 20
}
```
**响应格式**:
```json
{
"results": [
{
"type": "scene", // or "trace"
"file_uuid": "...",
"file_name": "...",
"scene_index": 26, // only for scenes
"timestamp_sec": 158.5,
"trace_id": null, // only for traces
"vlm_description": "The scene takes place in a brightly lit gym...",
"vlm_objects": ["dumbbell"],
"vlm_tags": ["indoor", "text"],
"thumbnail_url": "/api/v1/files/.../scenes/scene_026.jpg",
"score": 0.88,
"source": "vector"
}
],
"total": 2,
"page": 1,
"page_size": 20
}
```
### 3. 实现步骤
#### Phase 1: 数据迁移与索引(优先级:高)
1. **创建 PostgreSQL 表**
- 执行 `CREATE TABLE scenes` SQL
- 添加索引
2. **数据迁移脚本**
- 从 `scenes.json` 导入到 PostgreSQL
- 批量处理所有已注册视频
3. **创建 Qdrant Collection**
- 创建 `_scenes` collection
- 配置 payload schema
4. **向量嵌入生成**
- 对所有 `vlm_description` 生成 embedding
- 批量插入 Qdrant
#### Phase 2: API 实现(优先级:高)
1. **实现 Scene VLM Search API**
- 文件:`/Users/accusys/momentry_core/src/api/vlm_search.rs`
- 路由:`POST /api/v1/search/vlm/scenes`
- 功能:
- 向量搜索
- 结构化过滤
- 混合搜索
2. **实现 Trace VLM Search API**
- 复用现有 `trace_profiles` 数据
- 路由:`POST /api/v1/search/vlm/traces`
3. **实现 Hybrid VLM Search API**
- 合并 scenes 和 traces 搜索
- 路由:`POST /api/v1/search/vlm`
#### Phase 3: 前端集成(优先级:中)
1. **Studio 搜索界面更新**
- 添加 "VLM Search" 标签
- 搜索结果显示场景帧图片
- 点击跳转到对应时间点
2. **搜索结果展示**
- 网格布局显示场景/人物缩略图
- 显示 VLM 描述摘要
- 显示 tags 和 objects
#### Phase 4: 优化(优先级:低)
1. **缓存优化**
- Redis 缓存热门搜索结果
- TTL: 5 minutes
2. **性能优化**
- 并行搜索多个 collection
- 预过滤减少向量搜索范围
- 分页优化
### 4. 性能预估
| 操作 | 耗时预估 | 备注 |
|------|---------|------|
| 向量搜索(1000 scenes) | ~50ms | Qdrant cosine search |
| 结构化过滤 | ~20ms | PostgreSQL JSONB query |
| 混合搜索 | ~100ms | 预过滤 + 向量搜索 |
| API 响应时间 | ~150ms | 包含网络开销 |
### 5. 兼容性
- **现有搜索 API**: 不受影响,继续支持
- **现有数据结构**: 完全兼容
- **前端集成**: 渐进式集成,不影响现有功能
### 6. 测试计划
#### 6.1 单元测试
```rust
#[tokio::test]
async fn test_scene_vlm_search() {
let response = search_vlm_scenes("man with dog", None, None, 1, 10).await;
assert!(response.results.len() > 0);
}
#[tokio::test]
async fn test_scene_filter_by_tags() {
let filters = VlmFilters {
vlm_tags: Some(vec!["outdoor".to_string()]),
..Default::default()
};
let response = search_vlm_scenes("park", None, Some(filters), 1, 10).await;
assert!(response.results.iter().all(|r| r.vlm_tags.contains(&"outdoor".to_string())));
}
```
#### 6.2 集成测试
```bash
# 测试 Scene VLM Search API
curl -X POST "http://localhost:3002/api/v1/search/vlm/scenes?api_key=..." \
-H "Content-Type: application/json" \
-d '{"query": "man with dog", "page": 1, "page_size": 10}'
# 测试 Trace VLM Search API
curl -X POST "http://localhost:3002/api/v1/search/vlm/traces?api_key=..." \
-H "Content-Type: application/json" \
-d '{"query": "blue shirt", "page": 1, "page_size": 10}'
# 测试 Hybrid VLM Search API
curl -X POST "http://localhost:3002/api/v1/search/vlm?api_key=..." \
-H "Content-Type: application/json" \
-d '{"query": "indoor gym", "search_type": "hybrid", "page": 1, "page_size": 10}'
```
### 7. 文档
- **API 文档**: `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/20_vlm_search_api.md`
- **数据模型**: `/Users/accusys/momentry_core/docs_v1.0/REFERENCE/Scene_Data_Model.md`
- **集成指南**: `/Users/accusys/momentry_core/docs_v1.0/INTEGRATIONS/VLM_Search_Integration.md`
### 8. 时间估算
| 阶段 | 任务 | 预估时间 | 优先级 |
|------|------|---------|--------|
| Phase 1 | 数据迁移与索引 | 4 hours | High |
| Phase 2 | API 实现 | 6 hours | High |
| Phase 3 | 前端集成 | 4 hours | Medium |
| Phase 4 | 优化 | 2 hours | Low |
| **总计** | | **16 hours** | |
### 9. 风险与缓解
| 风险 | 影响 | 缓解措施 |
|------|------|---------|
| 数据迁移失败 | 无法搜索 | 分批迁移,保留原始文件 |
| 向量嵌入性能瓶颈 | 延迟高 | 批量处理,使用 GPU 加速 |
| Qdrant collection 冲突 | 数据丢失 | 使用独立的 `_scenes` collection |
| 前端集成复杂 | 延期 | 渐进式集成,优先核心功能 |
### 10. 总结
VLM Search API 将为 Momentry 提供强大的场景和人物视觉搜索能力,支持自然语言查询和多维度过滤。通过向量搜索与结构化过滤的结合,用户可以快速找到特定的场景或人物,提升数字资产管理的效率。
---
## 下一步行动
1. **确认设计方案**:与用户确认 API 设计是否符合需求
2. **开始 Phase 1**:数据迁移与索引建立
3. **实现 API**:Scene VLM Search API
4. **集成测试**:与 Studio 前端联调
5. **性能优化**:缓存和并行处理
@@ -0,0 +1,271 @@
---
title: VLM Search MinScore Config Integration
version: 1.0
date: 2026-09-23
author: OpenCode
status: draft
---
# VLM Search MinScore Config Integration
## Objective
Integrate VLM search `min_score` parameter into admin config system, allowing Studio team to manage default values via `/admin/config` API without code changes.
## Background
### Problem
- VLM search endpoints (`/api/v1/search/vlm/scenes`, `/api/v1/search/vlm/traces`, `/api/v1/search/vlm/debug`) required request-level `min_score` parameter
- No centralized default value configuration
- Changing default required code modification
### Solution
- Add `SearchConfig` section to `AdminConfig` structure
- VLM search endpoints read `search.vlm_min_score` as default value
- Request parameter still overrides config default
- Studio team can update via existing `/admin/config` API
## Architecture
### Data Model
**Location:** `/Users/accusys/momentry_core/src/core/admin_config.rs`
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchConfig {
#[serde(default = "default_vlm_min_score")]
pub vlm_min_score: f64,
}
fn default_vlm_min_score() -> f64 {
std::env::var("MOMENTRY_VLM_MIN_SCORE")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.0)
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AdminConfig {
// ... existing fields ...
#[serde(default)]
pub search: SearchConfig,
}
```
### Config Hierarchy
```
Environment Variable (MOMENTRY_VLM_MIN_SCORE)
↓
AdminConfig.search.vlm_min_score (default: 0.0)
↓
Request Parameter min_score (if > 0.0, overrides config)
```
### Integration Points
**Files Modified:**
| File | Changes |
|------|---------|
| `src/core/admin_config.rs` | Added `SearchConfig` struct, integrated into `AdminConfig` and `PartialAdminConfig` |
| `src/api/vlm_search.rs` | Read `search.vlm_min_score` from config, use as default for `min_score` parameter |
## API Behavior
### Endpoint: `/api/v1/search/vlm/scenes`
**Before Integration:**
- Required `min_score` in request (default: 0.0)
- No centralized configuration
**After Integration:**
- Reads `config.search.vlm_min_score` as default
- Request parameter `min_score` > 0.0 overrides config
- Request parameter `min_score` = 0.0 uses config value
**Example:**
```bash
# Config: search.vlm_min_score = 0.5
# Request: min_score = 0.0 (or not provided)
# Effective: min_score = 0.5 (from config)
# Request: min_score = 0.7
# Effective: min_score = 0.7 (request override)
```
### Endpoints Updated
All three VLM search endpoints follow the same pattern:
| Endpoint | Request Field | Config Field | Behavior |
|----------|---------------|--------------|----------|
| `/api/v1/search/vlm/scenes` | `min_score` | `search.vlm_min_score` | Request > 0.0 overrides config |
| `/api/v1/search/vlm/traces` | `min_score` | `search.vlm_min_score` | Request > 0.0 overrides config |
| `/api/v1/search/vlm/debug` | `min_score` | `search.vlm_min_score` | Request > 0.0 overrides config |
## Studio Integration
### Admin Config API
**GET `/api/v1/admin/config`**
Returns current `AdminConfig` including `search` section:
```json
{
"version": "1.0",
"updated_at": "2026-09-23T10:15:30Z",
"updated_by": "admin",
"vlm_prompts": { ... },
"llm_config": { ... },
"processor_config": { ... },
"filter_config": { ... },
"face_filter_defaults": { ... },
"paths": { ... },
"concurrency": { ... },
"feature_flags": { ... },
"server": { ... },
"admin_settings": { ... },
"search": {
"vlm_min_score": 0.0
}
}
```
**PATCH `/api/v1/admin/config`**
Update `search` section:
```bash
curl -X PATCH http://localhost:3002/api/v1/admin/config \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <admin_token>" \
-d '{
"search": {
"vlm_min_score": 0.5
}
}'
```
**Response:**
```json
{
"success": true,
"config": {
"version": "1.0",
"updated_at": "2026-09-23T10:20:15Z",
"updated_by": "admin",
"search": {
"vlm_min_score": 0.5
},
...
}
}
```
### UI Implementation Requirements
**Admin Page Section: "Search Settings"**
| Field | Type | Default | Range | Description |
|-------|------|---------|-------|-------------|
| VLM Min Score | Number (float) | 0.0 | 0.0 - 1.0 | Minimum similarity score for VLM search results |
**UI Behavior:**
1. Load current config via `GET /api/v1/admin/config`
2. Display `search.vlm_min_score` in number input
3. Validate: 0.0 ≤ value ≤ 1.0
4. On save: `PATCH /api/v1/admin/config` with `{"search": {"vlm_min_score": <value>}}`
5. Show success/error feedback
6. Changes take effect immediately (no server restart required)
**Validation:**
- Client-side: Clamp to [0.0, 1.0]
- Server-side: Accept any f64, but recommend [0.0, 1.0] in UI
## Environment Variable
**Optional Override:**
```bash
# .env
MOMENTRY_VLM_MIN_SCORE=0.5
```
**Precedence:**
1. Request parameter `min_score > 0.0` → Use request value
2. Request parameter `min_score = 0.0` → Use `config.search.vlm_min_score`
3. Config not set → Use `MOMENTRY_VLM_MIN_SCORE` env var
4. Env var not set → Use default 0.0
## Future Extensions
### Additional Search Parameters
The `SearchConfig` structure can be extended with additional parameters:
```rust
pub struct SearchConfig {
pub vlm_min_score: f64,
// Future:
// pub keyword_bm25_min_rank: f64,
// pub qdrant_top_k_multiplier: u32,
// pub hybrid_search_alpha: f64,
}
```
### Search Mode Profiles
Consider implementing named search profiles:
```json
{
"search": {
"profiles": {
"strict": { "vlm_min_score": 0.7 },
"balanced": { "vlm_min_score": 0.5 },
"loose": { "vlm_min_score": 0.3 }
},
"default_profile": "balanced"
}
}
```
## Testing Checklist
- [ ] GET `/api/v1/admin/config` returns `search` section
- [ ] PATCH `/api/v1/admin/config` updates `search.vlm_min_score`
- [ ] VLM search endpoints use config default when `min_score = 0.0`
- [ ] VLM search endpoints use request value when `min_score > 0.0`
- [ ] Config changes take effect without server restart
- [ ] Environment variable `MOMENTRY_VLM_MIN_SCORE` sets initial default
## Deployment
**No migration required.**
- `SearchConfig` has serde defaults
- Existing `admin_config.json` files will auto-populate with `search: {"vlm_min_score": 0.0}`
- Backward compatible with existing requests
## Version History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2026-09-23 | OpenCode | Initial design document |
## References
- `/Users/accusys/momentry_core/src/core/admin_config.rs` - SearchConfig implementation
- `/Users/accusys/momentry_core/src/api/vlm_search.rs` - VLM search endpoints
- `/Users/accusys/momentry_core/docs_v1.0/DESIGN/VLM_Search_API_Design.md` - VLM search API design
- `/Users/accusys/momentry_core/docs_v1.0/DESIGN/VLM_Prompt_Admin_Editable_Plan.md` - Admin config pattern