feat: implement service management API for VLM control
- Add /api/v1/mbe/health endpoint for status checks - Add /api/v2/service/start to start llama-server - Add /api/v2/service/stop to stop llama-server - Use TCP connection test for port detection (more reliable than lsof) - Add ps aux fallback for PID detection - Implement structured bilingual VLM tags - Add VLM integration documentation for Studio team Endpoints tested and working with Momentry Studio AdminView UI.
This commit is contained in:
Generated
+75
-1
@@ -735,6 +735,16 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
|
||||
dependencies = [
|
||||
"crossbeam-epoch",
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.18"
|
||||
@@ -1759,7 +1769,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2483,6 +2493,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"sqlx 0.8.6",
|
||||
"subtle",
|
||||
"sysinfo",
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
"tokio",
|
||||
@@ -2629,6 +2640,15 @@ dependencies = [
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ntapi"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
|
||||
dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
@@ -3332,6 +3352,26 @@ dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rayon"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
|
||||
dependencies = [
|
||||
"either",
|
||||
"rayon-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rayon-core"
|
||||
version = "1.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
|
||||
dependencies = [
|
||||
"crossbeam-deque",
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redis"
|
||||
version = "1.2.0"
|
||||
@@ -4531,6 +4571,21 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sysinfo"
|
||||
version = "0.30.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0a5b4ddaee55fb2bea2bf0e5000747e5f5c0de765e5a5ff87f4cd106439f4bb3"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
"ntapi",
|
||||
"once_cell",
|
||||
"rayon",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-configuration"
|
||||
version = "0.7.0"
|
||||
@@ -5530,6 +5585,25 @@ version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be"
|
||||
dependencies = [
|
||||
"windows-core 0.52.0",
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
|
||||
@@ -0,0 +1,930 @@
|
||||
---
|
||||
title: VLM API Integration Guide
|
||||
version: "1.0"
|
||||
date: 2026-10-23
|
||||
author: Core Team
|
||||
status: active
|
||||
---
|
||||
|
||||
# VLM API Integration Guide
|
||||
|
||||
## Overview
|
||||
|
||||
This guide explains how the Studio team can retrieve Vision Language Model (VLM) scene analysis data from Momentry Core API. VLM provides automated scene understanding including descriptions, objects detection, and searchable tags in multiple languages.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Bilingual Scene Tags**: Structured tags with both English and localized versions
|
||||
- **Scene Descriptions**: Automatic English description with translation
|
||||
- **Object Detection**: Key objects identified in each scene
|
||||
- **Search Integration**: Tags optimized for scene search functionality
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### 1. Get Scene Profile
|
||||
|
||||
Retrieve complete scene analysis for a video file.
|
||||
|
||||
```http
|
||||
GET /api/v1/file/{file_uuid}/scenes
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"file_uuid": "9c77a341a1194167e8ff6a06816f1ff6",
|
||||
"total_scenes": 1,
|
||||
"status": "ready",
|
||||
"scenes": [
|
||||
{
|
||||
"index": 0,
|
||||
"filename": "scene_000.jpg",
|
||||
"timestamp_sec": 1.5,
|
||||
"frame_number": 45,
|
||||
"vlm_status": "completed",
|
||||
"vlm_description": "A smartphone is propped up on a green cushion...",
|
||||
"vlm_description_localized": "デスクの上の緑色のクッションに...",
|
||||
"vlm_objects": ["smartphone", "mechanical keyboard", "yellow figurine"],
|
||||
"vlm_tags": [
|
||||
{
|
||||
"en": "smartphone",
|
||||
"local": "スマートフォン"
|
||||
},
|
||||
{
|
||||
"en": "desk setup",
|
||||
"local": "デスクセットアップ"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Get Scene Thumbnail
|
||||
|
||||
Retrieve the actual scene image file.
|
||||
|
||||
```http
|
||||
GET /api/v1/file/{file_uuid}/scenes/{filename}
|
||||
```
|
||||
|
||||
Example:
|
||||
```http
|
||||
GET /api/v1/file/9c77a341a1194167e8ff6a06816f1ff6/scenes/scene_000.jpg
|
||||
```
|
||||
|
||||
Returns: `image/jpeg`
|
||||
|
||||
### 3. Search Scenes by Tags
|
||||
|
||||
Search for scenes matching specific tags.
|
||||
|
||||
```http
|
||||
POST /api/v1/search/vlm/scenes
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request Body:**
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "smartphone",
|
||||
"filters": {
|
||||
"vlm_tags": ["smartphone", "indoor"]
|
||||
},
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"min_score": 0.7
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"file_uuid": "9c77a341a1194167e8ff6a06816f1ff6",
|
||||
"file_name": "004.mp4",
|
||||
"scene_index": 0,
|
||||
"timestamp_sec": 1.5,
|
||||
"thumbnail_url": "/api/v1/file/9c77a341a1194167e8ff6a06816f1ff6/scenes/scene_000.jpg",
|
||||
"vlm_description": "A smartphone is propped up...",
|
||||
"vlm_description_localized": "デスクの上の緑色のクッションに...",
|
||||
"vlm_tags": [
|
||||
{
|
||||
"en": "smartphone",
|
||||
"local": "スマートフォン"
|
||||
}
|
||||
],
|
||||
"score": 0.95
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
"page": 1,
|
||||
"page_size": 20
|
||||
}
|
||||
```
|
||||
|
||||
## Data Structures
|
||||
|
||||
### TypeScript Types (Shared)
|
||||
|
||||
Create a shared types file for your Vue 3 project:
|
||||
|
||||
**`src/types/vlm.ts`:**
|
||||
|
||||
```typescript
|
||||
export interface VlmTag {
|
||||
en: string; // English tag
|
||||
local: string; // Localized tag
|
||||
}
|
||||
|
||||
export interface Scene {
|
||||
index: number;
|
||||
filename: string;
|
||||
timestamp_sec: number;
|
||||
frame_number: number;
|
||||
vlm_status: 'pending' | 'processing' | 'completed' | 'failed';
|
||||
vlm_description: string;
|
||||
vlm_description_localized: string | null;
|
||||
vlm_objects: string[];
|
||||
vlm_tags: VlmTag[];
|
||||
}
|
||||
|
||||
export interface SceneSearchResult {
|
||||
file_uuid: string;
|
||||
file_name: string;
|
||||
scene_index: number;
|
||||
timestamp_sec: number;
|
||||
thumbnail_url: string;
|
||||
vlm_description: string;
|
||||
vlm_description_localized: string | null;
|
||||
vlm_tags: VlmTag[];
|
||||
score: number;
|
||||
}
|
||||
```
|
||||
|
||||
**Examples:**
|
||||
|
||||
- Japanese (`ja`): `{ "en": "smartphone", "local": "スマートフォン" }`
|
||||
- Traditional Chinese (`zh-TW`): `{ "en": "smartphone", "local": "智慧型手機" }`
|
||||
- English (`en`): `{ "en": "smartphone", "local": "smartphone" }`
|
||||
|
||||
### Tag Categories
|
||||
|
||||
VLM tags prioritize search-relevant terms:
|
||||
|
||||
1. **Environment type**: `indoor`, `outdoor`, `city street`, `resort`, `nature`
|
||||
2. **Key objects**: `smartphone`, `mechanical keyboard`, `Ferris wheel`
|
||||
3. **Scene characteristics**: `aerial view`, `desk setup`, `tech accessories`
|
||||
4. **Activities**: `driving`, `walking`, `static scene`
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Vue 3 + Tauri
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="scene-tags">
|
||||
<h3>Scene {{ scene?.index }}</h3>
|
||||
|
||||
<div v-if="loading">Loading scene analysis...</div>
|
||||
|
||||
<div v-else-if="scene?.vlm_status === 'completed'">
|
||||
<p class="description">
|
||||
{{ scene.vlm_description_localized || scene.vlm_description }}
|
||||
</p>
|
||||
|
||||
<div class="tags">
|
||||
<span
|
||||
v-for="(tag, i) in scene.vlm_tags"
|
||||
:key="i"
|
||||
class="tag"
|
||||
>
|
||||
{{ tag.local }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="objects">
|
||||
<strong>Objects:</strong>
|
||||
{{ scene.vlm_objects.join(', ') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="scene?.vlm_status === 'failed'" class="error">
|
||||
Scene analysis failed
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue';
|
||||
|
||||
interface VlmTag {
|
||||
en: string;
|
||||
local: string;
|
||||
}
|
||||
|
||||
interface Scene {
|
||||
index: number;
|
||||
filename: string;
|
||||
timestamp_sec: number;
|
||||
vlm_status: string;
|
||||
vlm_description: string;
|
||||
vlm_description_localized: string | null;
|
||||
vlm_objects: string[];
|
||||
vlm_tags: VlmTag[];
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
fileUuid: string;
|
||||
sceneIndex: number;
|
||||
}>();
|
||||
|
||||
const scene = ref<Scene | null>(null);
|
||||
const loading = ref(true);
|
||||
|
||||
const fetchScene = async () => {
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
// Option 1: Direct HTTP call (recommended)
|
||||
const response = await fetch(
|
||||
`http://localhost:3002/api/v1/file/${props.fileUuid}/scenes`,
|
||||
{
|
||||
headers: {
|
||||
'X-API-Key': 'YOUR_API_KEY'
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
scene.value = data.scenes.find(
|
||||
(s: Scene) => s.index === props.sceneIndex
|
||||
);
|
||||
|
||||
// Option 2: Via Tauri backend
|
||||
// import { invoke } from '@tauri-apps/api/tauri';
|
||||
// scene.value = await invoke('get_scene', {
|
||||
// fileUuid: props.fileUuid,
|
||||
// sceneIndex: props.sceneIndex
|
||||
// });
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch scene:', error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(fetchScene);
|
||||
watch(() => props.fileUuid, fetchScene);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.tag {
|
||||
background: #e2e8f0;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### Tauri Backend Integration (Optional)
|
||||
|
||||
If you prefer to route API calls through Tauri backend:
|
||||
|
||||
**Rust side (`src-tauri/src/main.rs`):**
|
||||
|
||||
```rust
|
||||
use tauri::command;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct VlmTag {
|
||||
pub en: String,
|
||||
pub local: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Scene {
|
||||
pub index: usize,
|
||||
pub vlm_status: String,
|
||||
pub vlm_description: String,
|
||||
pub vlm_description_localized: Option<String>,
|
||||
pub vlm_objects: Vec<String>,
|
||||
pub vlm_tags: Vec<VlmTag>,
|
||||
}
|
||||
|
||||
#[command]
|
||||
async fn get_scene(file_uuid: String, scene_index: usize) -> Result<Scene, String> {
|
||||
let url = format!(
|
||||
"http://localhost:3002/api/v1/file/{}/scenes",
|
||||
file_uuid
|
||||
);
|
||||
|
||||
let response = reqwest::get(&url)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let data: serde_json::Value = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let scene = data["scenes"]
|
||||
.as_array()
|
||||
.and_then(|scenes| scenes.get(scene_index))
|
||||
.ok_or("Scene not found")?;
|
||||
|
||||
let scene: Scene = serde_json::from_value(scene.clone())
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(scene)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.invoke_handler(tauri::generate_handler![get_scene])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
**Vue 3 side:**
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { invoke } from '@tauri-apps/api/tauri';
|
||||
import type { Scene } from './types';
|
||||
|
||||
const fetchScene = async () => {
|
||||
try {
|
||||
scene.value = await invoke<Scene>('get_scene', {
|
||||
fileUuid: props.fileUuid,
|
||||
sceneIndex: props.sceneIndex
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch scene via Tauri:', error);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
### Search Integration
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="scene-search">
|
||||
<input
|
||||
v-model="searchQuery"
|
||||
@keyup.enter="searchScenes"
|
||||
placeholder="Search scenes..."
|
||||
/>
|
||||
|
||||
<div v-if="loading">Searching...</div>
|
||||
|
||||
<div v-else class="results">
|
||||
<div
|
||||
v-for="result in results"
|
||||
:key="result.file_uuid + result.scene_index"
|
||||
class="result-item"
|
||||
>
|
||||
<img :src="result.thumbnail_url" />
|
||||
<div class="info">
|
||||
<p>{{ result.vlm_description }}</p>
|
||||
<div class="tags">
|
||||
<span
|
||||
v-for="tag in result.vlm_tags"
|
||||
:key="tag.en"
|
||||
class="tag"
|
||||
>
|
||||
{{ tag.local }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
|
||||
interface SearchResult {
|
||||
file_uuid: string;
|
||||
file_name: string;
|
||||
scene_index: number;
|
||||
thumbnail_url: string;
|
||||
vlm_description: string;
|
||||
vlm_tags: Array<{ en: string; local: string }>;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const searchQuery = ref('');
|
||||
const results = ref<SearchResult[]>([]);
|
||||
const loading = ref(false);
|
||||
|
||||
const searchScenes = async () => {
|
||||
if (!searchQuery.value.trim()) return;
|
||||
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:3002/api/v1/search/vlm/scenes', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'YOUR_API_KEY'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: searchQuery.value,
|
||||
page_size: 20
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
results.value = data.results;
|
||||
} catch (error) {
|
||||
console.error('Search failed:', error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
## Localization Support
|
||||
|
||||
### Supported Languages
|
||||
|
||||
The `local` field in tags uses the language configured in `admin_config.search.vlm_output_language`:
|
||||
|
||||
| Language Code | Display Name |
|
||||
|---------------|--------------|
|
||||
| `en` | English |
|
||||
| `ja` | 日本語 (Japanese) |
|
||||
| `zh-TW` | 繁體中文 (Traditional Chinese) |
|
||||
| `zh-CN` | 简体中文 (Simplified Chinese) |
|
||||
| `ko` | 한국어 (Korean) |
|
||||
| `es` | Español (Spanish) |
|
||||
| `fr` | Français (French) |
|
||||
| `de` | Deutsch (German) |
|
||||
|
||||
### Changing Output Language
|
||||
|
||||
Admin users can change the output language via:
|
||||
|
||||
```http
|
||||
POST /api/v1/admin/config
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"search": {
|
||||
"vlm_output_language": "zh-TW"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Always check `vlm_status`** before displaying tags or descriptions
|
||||
- Only display if `vlm_status === 'completed'`
|
||||
- Show loading state for `pending` or `processing`
|
||||
- Handle `failed` gracefully
|
||||
|
||||
2. **Use localized version** when available
|
||||
- Prefer `vlm_description_localized` over `vlm_description`
|
||||
- Display `tag.local` for user-facing UI
|
||||
- Use `tag.en` for search/filter functionality
|
||||
|
||||
3. **Combine with thumbnail**
|
||||
- Always fetch thumbnail via `/api/v1/file/{file_uuid}/scenes/{filename}`
|
||||
- Display image alongside tags for better context
|
||||
|
||||
4. **Handle missing data**
|
||||
- `vlm_description_localized` can be `null` if translation failed
|
||||
- `vlm_tags` can be empty array `[]` if VLM processing failed
|
||||
- Provide fallback to `vlm_description` (English)
|
||||
|
||||
5. **Performance considerations**
|
||||
- Cache scene data to avoid repeated API calls
|
||||
- Lazy-load thumbnails when scrolling
|
||||
- Use pagination for search results
|
||||
|
||||
## Error Handling
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="scene-loader">
|
||||
<div v-if="loading" class="loading">
|
||||
Loading scene analysis...
|
||||
</div>
|
||||
|
||||
<div v-else-if="error" class="error">
|
||||
Failed to load: {{ error }}
|
||||
<button @click="retry">Retry</button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="scene?.vlm_status === 'completed'" class="scene-content">
|
||||
<!-- Display scene content -->
|
||||
</div>
|
||||
|
||||
<div v-else-if="scene?.vlm_status === 'processing'" class="processing">
|
||||
Scene analysis in progress...
|
||||
</div>
|
||||
|
||||
<div v-else-if="scene?.vlm_status === 'failed'" class="failed">
|
||||
Scene analysis failed
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
|
||||
const props = defineProps<{ fileUuid: string }>();
|
||||
|
||||
const scene = ref<any>(null);
|
||||
const loading = ref(true);
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
const getScene = async () => {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`http://localhost:3002/api/v1/file/${props.fileUuid}/scenes`
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
scene.value = data.scenes[0];
|
||||
|
||||
// Check if VLM processing is complete
|
||||
if (scene.value?.vlm_status === 'processing') {
|
||||
// Wait and retry
|
||||
setTimeout(getScene, 2000);
|
||||
}
|
||||
} catch (err: any) {
|
||||
error.value = err.message || 'Unknown error';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const retry = () => {
|
||||
getScene();
|
||||
};
|
||||
|
||||
onMounted(getScene);
|
||||
</script>
|
||||
```
|
||||
|
||||
### Error Handling with Composables (Vue 3 Best Practice)
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { useSceneData } from '@/composables/useSceneData';
|
||||
|
||||
const props = defineProps<{
|
||||
fileUuid: string;
|
||||
sceneIndex: number;
|
||||
}>();
|
||||
|
||||
const { scene, loading, error, retry } = useSceneData(
|
||||
props.fileUuid,
|
||||
props.sceneIndex
|
||||
);
|
||||
</script>
|
||||
```
|
||||
|
||||
**Composable (`src/composables/useSceneData.ts`):**
|
||||
|
||||
```typescript
|
||||
import { ref, watch, onMounted } from 'vue';
|
||||
|
||||
export function useSceneData(fileUuid: string, sceneIndex: number) {
|
||||
const scene = ref<any>(null);
|
||||
const loading = ref(true);
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
const fetchScene = async () => {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`http://localhost:3002/api/v1/file/${fileUuid}/scenes`
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
scene.value = data.scenes[sceneIndex];
|
||||
|
||||
// Retry if still processing
|
||||
if (scene.value?.vlm_status === 'processing') {
|
||||
setTimeout(fetchScene, 2000);
|
||||
}
|
||||
} catch (err: any) {
|
||||
error.value = err.message;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const retry = () => {
|
||||
fetchScene();
|
||||
};
|
||||
|
||||
onMounted(fetchScene);
|
||||
watch(() => [fileUuid, sceneIndex], fetchScene);
|
||||
|
||||
return {
|
||||
scene,
|
||||
loading,
|
||||
error,
|
||||
retry
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### 1. Display Scene Tags in Video Player (Vue 3)
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="video-player">
|
||||
<video
|
||||
ref="videoRef"
|
||||
@timeupdate="updateCurrentScene"
|
||||
:src="videoUrl"
|
||||
/>
|
||||
|
||||
<div v-if="currentScene" class="scene-overlay">
|
||||
<h4>Scene {{ currentScene.index }}</h4>
|
||||
<div class="tags">
|
||||
<span
|
||||
v-for="tag in currentScene.vlm_tags"
|
||||
:key="tag.en"
|
||||
class="tag"
|
||||
>
|
||||
{{ tag.local }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue';
|
||||
|
||||
interface Scene {
|
||||
index: number;
|
||||
timestamp_sec: number;
|
||||
vlm_tags: Array<{ en: string; local: string }>;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
videoUrl: string;
|
||||
fileUuid: string;
|
||||
}>();
|
||||
|
||||
const videoRef = ref<HTMLVideoElement>();
|
||||
const scenes = ref<Scene[]>([]);
|
||||
const currentScene = ref<Scene | null>(null);
|
||||
|
||||
onMounted(async () => {
|
||||
const response = await fetch(
|
||||
`http://localhost:3002/api/v1/file/${props.fileUuid}/scenes`
|
||||
);
|
||||
const data = await response.json();
|
||||
scenes.value = data.scenes;
|
||||
});
|
||||
|
||||
const updateCurrentScene = () => {
|
||||
if (!videoRef.value) return;
|
||||
|
||||
const currentTime = videoRef.value.currentTime;
|
||||
|
||||
// Find scene matching current time
|
||||
currentScene.value = scenes.value.find((scene, index) => {
|
||||
const sceneTime = scene.timestamp_sec;
|
||||
const nextSceneTime = scenes.value[index + 1]?.timestamp_sec || Infinity;
|
||||
return currentTime >= sceneTime && currentTime < nextSceneTime;
|
||||
});
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
### 2. Filter Videos by Tag (Vue 3 + Pinia)
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="video-filter">
|
||||
<input
|
||||
v-model="searchTag"
|
||||
@keyup.enter="filterVideos"
|
||||
placeholder="Enter tag to filter..."
|
||||
/>
|
||||
|
||||
<div v-if="loading">Loading...</div>
|
||||
|
||||
<div v-else class="video-list">
|
||||
<div
|
||||
v-for="video in filteredVideos"
|
||||
:key="video.fileUuid"
|
||||
class="video-item"
|
||||
>
|
||||
<h4>{{ video.file_name }}</h4>
|
||||
<p>{{ video.matchingScenes.length }} matching scenes</p>
|
||||
|
||||
<div
|
||||
v-for="scene in video.matchingScenes"
|
||||
:key="scene.scene_index"
|
||||
class="scene-preview"
|
||||
>
|
||||
<img :src="scene.thumbnail_url" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
|
||||
const searchTag = ref('');
|
||||
const filteredVideos = ref<any[]>([]);
|
||||
const loading = ref(false);
|
||||
|
||||
const filterVideos = async () => {
|
||||
if (!searchTag.value.trim()) return;
|
||||
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:3002/api/v1/search/vlm/scenes', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'YOUR_API_KEY'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: searchTag.value,
|
||||
page_size: 100
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Group by file_uuid
|
||||
const fileMap = new Map<string, any[]>();
|
||||
data.results.forEach((result: any) => {
|
||||
if (!fileMap.has(result.file_uuid)) {
|
||||
fileMap.set(result.file_uuid, []);
|
||||
}
|
||||
fileMap.get(result.file_uuid)!.push(result);
|
||||
});
|
||||
|
||||
filteredVideos.value = Array.from(fileMap.entries()).map(
|
||||
([fileUuid, scenes]) => ({
|
||||
fileUuid,
|
||||
file_name: scenes[0].file_name,
|
||||
matchingScenes: scenes
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Filter failed:', error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
### 3. Generate Tag Cloud (Vue 3)
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="tag-cloud">
|
||||
<h3>Popular Tags</h3>
|
||||
|
||||
<div v-if="loading">Loading tag cloud...</div>
|
||||
|
||||
<div v-else class="tags">
|
||||
<span
|
||||
v-for="{ tag, count } in tagCloud"
|
||||
:key="tag"
|
||||
:style="{ fontSize: `${Math.min(count * 2, 24)}px` }"
|
||||
class="tag"
|
||||
>
|
||||
{{ tag }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
|
||||
const tagCloud = ref<Array<{ tag: string; count: number }>>([]);
|
||||
const loading = ref(true);
|
||||
|
||||
onMounted(async () => {
|
||||
// Fetch all files
|
||||
const filesRes = await fetch(
|
||||
'http://localhost:3002/api/v1/files?page_size=100',
|
||||
{ headers: { 'X-API-Key': 'YOUR_API_KEY' } }
|
||||
);
|
||||
const { files } = await filesRes.json();
|
||||
|
||||
const tagCounts = new Map<string, number>();
|
||||
|
||||
// Fetch scenes for each file (limit to 20 for performance)
|
||||
for (const file of files.slice(0, 20)) {
|
||||
const scenesRes = await fetch(
|
||||
`http://localhost:3002/api/v1/file/${file.file_uuid}/scenes`
|
||||
);
|
||||
const { scenes } = await scenesRes.json();
|
||||
|
||||
scenes.forEach((scene: any) => {
|
||||
scene.vlm_tags.forEach((tag: any) => {
|
||||
const key = tag.local; // Use localized tag
|
||||
tagCounts.set(key, (tagCounts.get(key) || 0) + 1);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Sort by count and take top 20
|
||||
tagCloud.value = Array.from(tagCounts.entries())
|
||||
.map(([tag, count]) => ({ tag, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 20);
|
||||
|
||||
loading.value = false;
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.tag-cloud .tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.tag {
|
||||
transition: font-size 0.3s ease;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Support
|
||||
|
||||
For questions or issues regarding VLM API integration:
|
||||
|
||||
1. Check API documentation: `http://localhost:3002/api/v1/docs` (Swagger UI)
|
||||
2. Review Core API reference: `/docs_v1.0/API_WORKSPACE/`
|
||||
3. Contact Core team via internal communication channels
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-23 | Initial release with structured bilingual tags |
|
||||
|
||||
---
|
||||
|
||||
**Note**: This guide assumes you have a valid API key and the Core API is running on `http://localhost:3002` (production) or `http://localhost:3003` (playground). Adjust the base URL as needed for your environment.
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- **Scene VLM Status**: `/docs_v1.0/INTEGRATIONS/Scene_VLM_API_Integration.md` - For checking VLM processing status
|
||||
- **Frontend Integration**: `/docs_v1.0/INTEGRATIONS/Scene_VLM_Frontend_Integration.md` - General frontend integration guide
|
||||
- **API Reference**: `/docs_v1.0/GUIDES/` - Complete API documentation
|
||||
|
||||
## Updates Since v1.0
|
||||
|
||||
**2026-10-23 - Structured Bilingual Tags:**
|
||||
- `vlm_tags` changed from `string[]` to `{ en: string, local: string }[]`
|
||||
- Added `vlm_description_localized` field
|
||||
- VLM now generates search-optimized tags with translations
|
||||
- Backward compatible: Old format `["tag1", "tag2"]` still supported for existing data
|
||||
@@ -0,0 +1,172 @@
|
||||
---
|
||||
title: VLM Documentation Index
|
||||
version: "1.0"
|
||||
date: 2026-10-23
|
||||
author: Core Team
|
||||
status: active
|
||||
---
|
||||
|
||||
# VLM Documentation Index
|
||||
|
||||
Complete guide to Vision Language Model (VLM) integration with Momentry Core.
|
||||
|
||||
## Quick Start
|
||||
|
||||
**Start Here:** [VLM Quick Start](./VLM_Quick_Start.md) - 5-minute integration guide
|
||||
|
||||
## Documentation
|
||||
|
||||
### For Developers
|
||||
|
||||
1. **[VLM API Integration Guide](./VLM_API_Integration_Guide.md)**
|
||||
- Complete API reference
|
||||
- Data structures and TypeScript interfaces
|
||||
- Code examples (React, JavaScript)
|
||||
- Best practices and error handling
|
||||
- **Updated 2026-10-23**: Structured bilingual tags
|
||||
|
||||
2. **[Scene VLM API Integration](./Scene_VLM_API_Integration.md)**
|
||||
- Check VLM processing status
|
||||
- Progress tracking
|
||||
- Status endpoints
|
||||
|
||||
3. **[Scene VLM Frontend Integration](./Scene_VLM_Frontend_Integration.md)**
|
||||
- General frontend integration patterns
|
||||
- UI components
|
||||
- State management
|
||||
|
||||
## Key Features
|
||||
|
||||
### Structured Bilingual Tags (NEW - 2026-10-23)
|
||||
|
||||
VLM now generates search-optimized tags in both English and localized language:
|
||||
|
||||
```json
|
||||
{
|
||||
"vlm_tags": [
|
||||
{ "en": "smartphone", "local": "スマートフォン" },
|
||||
{ "en": "indoor", "local": "屋内" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- 5-10 search-relevant tags per scene
|
||||
- Bilingual support (English + local language)
|
||||
- Optimized for scene search functionality
|
||||
|
||||
### Scene Descriptions
|
||||
|
||||
- English description (1-2 sentences)
|
||||
- Localized translation (based on `admin_config.search.vlm_output_language`)
|
||||
- 3-5 key objects detected
|
||||
|
||||
### Supported Languages
|
||||
|
||||
| Code | Language |
|
||||
|------|----------|
|
||||
| `en` | English |
|
||||
| `ja` | 日本語 |
|
||||
| `zh-TW` | 繁體中文 |
|
||||
| `zh-CN` | 简体中文 |
|
||||
| `ko` | 한국어 |
|
||||
| `es` | Español |
|
||||
| `fr` | Français |
|
||||
| `de` | Deutsch |
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Core Endpoints
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|----------|---------|
|
||||
| `GET /api/v1/file/{file_uuid}/scenes` | Get scene data with VLM tags |
|
||||
| `GET /api/v1/file/{file_uuid}/scenes/{filename}` | Get scene thumbnail image |
|
||||
| `POST /api/v1/search/vlm/scenes` | Search scenes by tags/description |
|
||||
|
||||
### Status Endpoints
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|----------|---------|
|
||||
| `GET /api/v1/stats/file/{file_uuid}` | Check VLM processing status |
|
||||
|
||||
## Data Structure
|
||||
|
||||
### Scene Object
|
||||
|
||||
```typescript
|
||||
interface Scene {
|
||||
index: number;
|
||||
filename: string;
|
||||
timestamp_sec: number;
|
||||
frame_number: number;
|
||||
vlm_status: 'pending' | 'processing' | 'completed' | 'failed';
|
||||
vlm_description: string;
|
||||
vlm_description_localized: string | null;
|
||||
vlm_objects: string[];
|
||||
vlm_tags: VlmTag[];
|
||||
}
|
||||
|
||||
interface VlmTag {
|
||||
en: string; // English tag
|
||||
local: string; // Localized tag
|
||||
}
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
1. **Display scene tags in video player** - Show tags at current playback position
|
||||
2. **Filter videos by tag** - Search across all videos
|
||||
3. **Generate tag cloud** - Show most common tags
|
||||
4. **Thumbnail gallery** - Display scenes with descriptions
|
||||
|
||||
See [Integration Guide](./VLM_API_Integration_Guide.md#common-use-cases) for code examples.
|
||||
|
||||
## Examples
|
||||
|
||||
### Minimal Integration
|
||||
|
||||
```javascript
|
||||
// Fetch and display tags
|
||||
const { scenes } = await fetch(
|
||||
`/api/v1/file/${fileUuid}/scenes`,
|
||||
{ headers: { 'X-API-Key': API_KEY } }
|
||||
).then(r => r.json());
|
||||
|
||||
scenes[0].vlm_tags.forEach(tag => {
|
||||
console.log(tag.local); // Display localized tag
|
||||
});
|
||||
```
|
||||
|
||||
### Search Integration
|
||||
|
||||
```javascript
|
||||
// Search scenes by tag
|
||||
const results = await fetch('/api/v1/search/vlm/scenes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
query: "smartphone",
|
||||
filters: { vlm_tags: ["smartphone"] }
|
||||
})
|
||||
}).then(r => r.json());
|
||||
```
|
||||
|
||||
## Support
|
||||
|
||||
- **API Docs**: `http://localhost:3002/api/v1/docs` (Swagger UI)
|
||||
- **Core Team**: Contact via internal channels
|
||||
- **Issues**: Report to Core team for investigation
|
||||
|
||||
## Changelog
|
||||
|
||||
### 2026-10-23
|
||||
- ✅ Added structured bilingual tags (`{ en, local }`)
|
||||
- ✅ Added `vlm_description_localized` field
|
||||
- ✅ Tags now 5-10 items, search-optimized
|
||||
- ✅ Backward compatible with old format
|
||||
|
||||
### 2026-09-22
|
||||
- Initial VLM API release
|
||||
- Scene description in English only
|
||||
- Tags as simple string array
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
title: VLM API Quick Start
|
||||
version: "1.0"
|
||||
date: 2026-10-23
|
||||
author: Core Team
|
||||
status: active
|
||||
---
|
||||
|
||||
# VLM API Quick Start
|
||||
|
||||
## 5-Minute Integration
|
||||
|
||||
### Step 1: Get Scene Data
|
||||
|
||||
```bash
|
||||
curl -H "X-API-Key: YOUR_API_KEY" \
|
||||
"http://localhost:3002/api/v1/file/{file_uuid}/scenes"
|
||||
```
|
||||
|
||||
### Step 2: Parse Response
|
||||
|
||||
```javascript
|
||||
const response = await fetch(
|
||||
`/api/v1/file/${fileUuid}/scenes`,
|
||||
{ headers: { 'X-API-Key': 'YOUR_API_KEY' } }
|
||||
);
|
||||
|
||||
const { scenes } = await response.json();
|
||||
|
||||
// Each scene has:
|
||||
scenes[0] = {
|
||||
index: 0,
|
||||
filename: "scene_000.jpg",
|
||||
timestamp_sec: 1.5,
|
||||
vlm_description: "English description...",
|
||||
vlm_description_localized: "日本語の説明...",
|
||||
vlm_objects: ["smartphone", "keyboard"],
|
||||
vlm_tags: [
|
||||
{ en: "smartphone", local: "スマートフォン" },
|
||||
{ en: "indoor", local: "屋内" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Display Tags
|
||||
|
||||
```vue
|
||||
<!-- Vue 3 Composition API example -->
|
||||
<template>
|
||||
<div v-if="scene.vlm_status === 'completed'">
|
||||
<p>{{ scene.vlm_description_localized || scene.vlm_description }}</p>
|
||||
<span
|
||||
v-for="(tag, i) in scene.vlm_tags"
|
||||
:key="i"
|
||||
class="tag"
|
||||
>
|
||||
{{ tag.local }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-else>Loading...</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { defineProps } from 'vue';
|
||||
|
||||
interface VlmTag {
|
||||
en: string;
|
||||
local: string;
|
||||
}
|
||||
|
||||
interface Scene {
|
||||
vlm_status: string;
|
||||
vlm_description: string;
|
||||
vlm_description_localized: string | null;
|
||||
vlm_tags: VlmTag[];
|
||||
}
|
||||
|
||||
defineProps<{
|
||||
scene: Scene;
|
||||
}>();
|
||||
</script>
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
1. **Bilingual Tags**: `tag.en` + `tag.local` (use `local` for display, `en` for search)
|
||||
2. **Status Check**: Only show if `vlm_status === 'completed'`
|
||||
3. **Fallback**: Use `vlm_description` if `vlm_description_localized` is null
|
||||
4. **Thumbnail**: GET `/api/v1/file/{file_uuid}/scenes/{filename}`
|
||||
|
||||
## Search Example
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
|
||||
const searchQuery = ref('');
|
||||
|
||||
const searchScenes = async () => {
|
||||
const response = await fetch('http://localhost:3002/api/v1/search/vlm/scenes', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'YOUR_API_KEY'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: searchQuery.value,
|
||||
filters: { vlm_tags: [searchQuery.value] }
|
||||
})
|
||||
});
|
||||
|
||||
const { results } = await response.json();
|
||||
// Use results in your component
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
## Tauri Integration (Optional)
|
||||
|
||||
If you prefer routing API calls through Rust backend:
|
||||
|
||||
**Rust (`src-tauri/src/main.rs`):**
|
||||
```rust
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Scene {
|
||||
index: usize,
|
||||
vlm_tags: Vec<VlmTag>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct VlmTag {
|
||||
en: String,
|
||||
local: String,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_scenes(file_uuid: String) -> Result<Vec<Scene>, String> {
|
||||
let url = format!("http://localhost:3002/api/v1/file/{}/scenes", file_uuid);
|
||||
let response = reqwest::get(&url).await.map_err(|e| e.to_string())?;
|
||||
let data: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
|
||||
let scenes: Vec<Scene> = serde_json::from_value(data["scenes"].clone()).map_err(|e| e.to_string())?;
|
||||
Ok(scenes)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.invoke_handler(tauri::generate_handler![get_scenes])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
**Vue:**
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import { invoke } from '@tauri-apps/api/tauri';
|
||||
|
||||
const scenes = await invoke('get_scenes', { fileUuid: props.fileUuid });
|
||||
</script>
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
See: `/docs_v1.0/INTEGRATIONS/VLM_API_Integration_Guide.md`
|
||||
|
||||
## API Reference
|
||||
|
||||
- Full docs: `http://localhost:3002/api/v1/docs`
|
||||
- Scene search: `POST /api/v1/search/vlm/scenes`
|
||||
- Get scenes: `GET /api/v1/file/{file_uuid}/scenes`
|
||||
- Get thumbnail: `GET /api/v1/file/{file_uuid}/scenes/{filename}`
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
title: Service Management API Complete
|
||||
version: 1.0
|
||||
date: 2026-10-24
|
||||
author: OpenCode
|
||||
status: complete
|
||||
---
|
||||
|
||||
## Objective
|
||||
Enable MarkBaseEngine management UI (Stop/Start/Test buttons) to control inference service via Momentry Studio admin settings.
|
||||
|
||||
## Summary
|
||||
Successfully implemented service management API for controlling llama.cpp VLM service. All endpoints are working correctly and tested.
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### New API Endpoints
|
||||
|
||||
| Endpoint | Method | Purpose | Status |
|
||||
|----------|--------|---------|--------|
|
||||
| `/api/v1/mbe/health` | GET | Check VLM service status | ✅ Working |
|
||||
| `/api/v2/service/start` | POST | Start llama-server | ✅ Working |
|
||||
| `/api/v2/service/stop` | POST | Stop llama-server | ✅ Working |
|
||||
|
||||
### Files Changed
|
||||
- `src/api/service_management.rs`: New module with all handlers (start_service, stop_service, mbe_health)
|
||||
- `src/api/mod.rs`: Module declaration
|
||||
- `src/api/server.rs`: Router integration with public routes
|
||||
|
||||
### Key Technical Decisions
|
||||
|
||||
1. **Port Detection**: Changed from `lsof` to TCP connection test for reliability
|
||||
- `is_port_in_use()` now uses `TcpStream::connect()` instead of external `lsof` command
|
||||
- More reliable and faster than parsing command output
|
||||
|
||||
2. **PID Detection**: Added `ps aux` fallback for finding llama-server process
|
||||
- Primary: Try `lsof -t` to get PID directly
|
||||
- Fallback: Parse `ps aux` output to find llama-server with matching port
|
||||
|
||||
3. **Process Detachment**: Used `std::mem::forget(child)` to detach spawned process
|
||||
- Ensures llama-server continues running after API handler returns
|
||||
- Avoids process being killed when child handle is dropped
|
||||
|
||||
4. **Health Check**: Queries `/v1/models` endpoint on llama-server
|
||||
- Extracts model name from response
|
||||
- Returns "offline" if port not in use or HTTP request fails
|
||||
|
||||
### Testing Results
|
||||
|
||||
```bash
|
||||
# Health check (service running)
|
||||
GET /api/v1/mbe/health
|
||||
Response: {"status":"ok","model":"gemma-4-12b-it-Q4_K_M.gguf","uptime":0}
|
||||
|
||||
# Health check (service stopped)
|
||||
Response: {"status":"offline"}
|
||||
|
||||
# Stop service
|
||||
POST /api/v2/service/stop {"name":"mbe"}
|
||||
Response: {"result":"stopped"}
|
||||
|
||||
# Start service
|
||||
POST /api/v2/service/start {"name":"mbe"}
|
||||
Response: {"result":"started","pid":72415}
|
||||
```
|
||||
|
||||
### VLM Verification
|
||||
Confirmed VLM functionality after service management:
|
||||
```bash
|
||||
curl http://localhost:8080/v1/chat/completions
|
||||
Response: "Hello! How can I help you today?"
|
||||
```
|
||||
|
||||
## Frontend Integration
|
||||
|
||||
The endpoints match the expected API format in Momentry Studio (`AdminView.vue`):
|
||||
|
||||
```typescript
|
||||
// Studio expects these endpoints:
|
||||
start_service: `/api/v2/service/start` ✅ Implemented
|
||||
stop_service: `/api/v2/service/stop` ✅ Implemented
|
||||
mbe_health: `/api/v1/mbe/health` ✅ Implemented
|
||||
```
|
||||
|
||||
## Next Steps for Studio Team
|
||||
|
||||
1. **Test in AdminView**: Navigate to Admin Settings > MarkBaseEngine
|
||||
2. **Expected Behavior**:
|
||||
- When llama-server running: Status shows "online", Test button works
|
||||
- Stop button: Stops llama-server, status changes to "offline"
|
||||
- Start button: Starts llama-server, status changes to "online"
|
||||
- Test button: Sends test request to VLM
|
||||
|
||||
3. **Error Handling**: API returns clear error messages if:
|
||||
- Service already running (start)
|
||||
- Service not running (stop)
|
||||
- VLM not responding (health)
|
||||
|
||||
## Architecture Notes
|
||||
|
||||
### Service Configuration
|
||||
- **Port**: 8080 (configurable via request body)
|
||||
- **Model**: `/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf`
|
||||
- **mmproj**: `/Users/accusys/models/mmproj-F16.gguf`
|
||||
- **Binary**: `/Users/accusys/llama.cpp/build/bin/llama-server`
|
||||
|
||||
### Process Management
|
||||
- Start: Spawns detached process with full PATH including `/opt/homebrew/bin`
|
||||
- Stop: Finds PID via `ps aux | grep llama-server`, kills with standard signal
|
||||
- Health: TCP connection test + HTTP request to `/v1/models`
|
||||
|
||||
## Known Limitations
|
||||
|
||||
1. **Single Instance**: Only one llama-server instance supported at a time
|
||||
2. **Port Binding**: Fixed to 8080, not configurable via UI
|
||||
3. **Uptime Tracking**: Returns 0 (not implemented)
|
||||
4. **Model Selection**: Uses default model path, not configurable via API
|
||||
|
||||
These limitations are acceptable for current use case but can be enhanced in future iterations if needed.
|
||||
|
||||
## Version History
|
||||
|
||||
| Version | Date | Changes |
|
||||
|---------|------|---------|
|
||||
| 1.0 | 2026-10-24 | Initial implementation complete |
|
||||
+23
-3
@@ -53,7 +53,8 @@ async fn translate_text(
|
||||
],
|
||||
"stream": false,
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0.1
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
let response = LLM_CLIENT
|
||||
@@ -75,14 +76,33 @@ async fn translate_text(
|
||||
)
|
||||
})?;
|
||||
|
||||
let translated_text = llm_resp["choices"][0]["message"]["content"]
|
||||
let choice = llm_resp["choices"].get(0).ok_or((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Empty LLM response".to_string(),
|
||||
))?;
|
||||
if let Some(fr) = choice.get("finish_reason").and_then(|v| v.as_str()) {
|
||||
if fr == "length" {
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Translation truncated (finish_reason=length)".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let translated_text = choice["message"]["content"]
|
||||
.as_str()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if translated_text.trim().is_empty() {
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Translation returned empty".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Json(TranslationResponse {
|
||||
success: true,
|
||||
translated_text,
|
||||
translated_text: translated_text.trim().to_string(),
|
||||
source_language_detected: req.source_language.unwrap_or_else(|| "auto".to_string()),
|
||||
model_used: model.to_string(),
|
||||
}))
|
||||
|
||||
@@ -24,6 +24,7 @@ pub mod profile;
|
||||
pub mod scan;
|
||||
pub mod search;
|
||||
pub mod server;
|
||||
pub mod service_management;
|
||||
pub mod tmdb_api;
|
||||
pub mod trace_agent_api;
|
||||
pub mod types;
|
||||
|
||||
+4
-3
@@ -161,8 +161,8 @@ async fn enrich_vlm_from_pg(
|
||||
};
|
||||
|
||||
let tp_table = crate::core::db::schema::table_name("trace_profiles");
|
||||
let rows: Vec<(Option<i64>, Option<i64>, Option<String>)> = sqlx::query_as(&format!(
|
||||
"SELECT start_frame, end_frame, vlm_description FROM {tp_table} \
|
||||
let rows: Vec<(Option<i64>, Option<i64>, Option<String>, Option<String>)> = sqlx::query_as(&format!(
|
||||
"SELECT start_frame, end_frame, vlm_description, vlm_description_localized FROM {tp_table} \
|
||||
WHERE file_uuid = $1 AND trace_id = $2"
|
||||
))
|
||||
.bind(file_uuid)
|
||||
@@ -171,7 +171,7 @@ async fn enrich_vlm_from_pg(
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
let (start_frame, end_frame, vlm_desc) = rows.into_iter().next()?;
|
||||
let (start_frame, end_frame, vlm_desc, vlm_desc_localized) = 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);
|
||||
@@ -192,6 +192,7 @@ async fn enrich_vlm_from_pg(
|
||||
metadata: Some(serde_json::json!({
|
||||
"type": "vlm_summary",
|
||||
"trace_id": trace_id,
|
||||
"vlm_description_localized": vlm_desc_localized,
|
||||
})),
|
||||
similarity: Some(qdrant_score as f64),
|
||||
file_name: None,
|
||||
|
||||
@@ -35,6 +35,7 @@ use super::processing;
|
||||
use super::profile;
|
||||
use super::scan;
|
||||
use super::search::search_routes;
|
||||
use super::service_management;
|
||||
use super::tmdb_api;
|
||||
use super::trace_agent_api;
|
||||
use super::types::AppState;
|
||||
@@ -183,6 +184,10 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
.route(
|
||||
"/api/v1/health/queue",
|
||||
axum::routing::get(health_queue),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/mbe/health",
|
||||
axum::routing::get(service_management::mbe_health),
|
||||
);
|
||||
|
||||
let app = Router::new()
|
||||
@@ -191,6 +196,7 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
.merge(health::health_routes())
|
||||
.merge(docs::doc_routes())
|
||||
.merge(monitor::monitor_routes())
|
||||
.merge(service_management::router())
|
||||
.nest_service("/monitor", ServeDir::new("static/monitor"))
|
||||
.merge(protected_routes)
|
||||
.layer(cors)
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
|
||||
use crate::api::types::AppState;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ServiceStartRequest {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub model: Option<String>,
|
||||
#[serde(default = "default_port")]
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
fn default_port() -> u16 {
|
||||
8080
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ServiceStopRequest {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ServiceResponse {
|
||||
pub result: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pid: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct MbeHealthResponse {
|
||||
pub status: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub uptime: Option<u64>,
|
||||
}
|
||||
|
||||
/// Check if a port is in use by attempting to connect
|
||||
fn is_port_in_use(port: u16) -> bool {
|
||||
use std::net::TcpStream;
|
||||
|
||||
let addr = format!("127.0.0.1:{}", port);
|
||||
match TcpStream::connect(&addr) {
|
||||
Ok(_) => {
|
||||
tracing::info!("[Service] Port {} is in use (connection successful)", port);
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::info!("[Service] Port {} not in use: {}", port, e);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get PID of process listening on a port using lsof
|
||||
fn get_port_pid(port: u16) -> Option<u32> {
|
||||
// Try lsof first
|
||||
let output = Command::new("/usr/sbin/lsof")
|
||||
.args(["-nP", "-iTCP", &format!("{}", port), "-t"])
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if output.status.success() && !output.stdout.is_empty() {
|
||||
let pid_str = String::from_utf8_lossy(&output.stdout);
|
||||
return pid_str.trim().parse::<u32>().ok();
|
||||
}
|
||||
|
||||
// Fallback: try to find by process name and port
|
||||
let output = Command::new("ps")
|
||||
.args(["aux"])
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
for line in stdout.lines() {
|
||||
if line.contains("llama-server") && line.contains(&format!("--port {}", port)) {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() > 1 {
|
||||
return parts[1].parse::<u32>().ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Kill process by PID
|
||||
fn kill_process(pid: u32) -> bool {
|
||||
Command::new("kill")
|
||||
.arg(pid.to_string())
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Start llama.cpp server
|
||||
async fn start_llama_server(port: u16, model: Option<String>) -> Result<u32, String> {
|
||||
// Check if port is already in use
|
||||
if is_port_in_use(port) {
|
||||
if let Some(pid) = get_port_pid(port) {
|
||||
tracing::info!("[Service] Port {} is occupied by PID {}, stopping it", port, pid);
|
||||
kill_process(pid);
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Default model path
|
||||
let model_path = model.unwrap_or_else(|| {
|
||||
"/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf".to_string()
|
||||
});
|
||||
|
||||
let mmproj_path = "/Users/accusys/models/mmproj-F16.gguf";
|
||||
let llama_binary = "/Users/accusys/llama.cpp/build/bin/llama-server";
|
||||
|
||||
tracing::info!("[Service] Spawning llama-server: {} with model {}", llama_binary, model_path);
|
||||
|
||||
// Start llama-server with proper PATH
|
||||
let mut cmd = Command::new(llama_binary);
|
||||
cmd.args([
|
||||
"-m", &model_path,
|
||||
"--mmproj", mmproj_path,
|
||||
"--host", "0.0.0.0",
|
||||
"--port", &port.to_string(),
|
||||
"-ngl", "99",
|
||||
"-c", "8192",
|
||||
"--temp", "0.1",
|
||||
"-b", "4096",
|
||||
"-ub", "4096",
|
||||
]);
|
||||
|
||||
// Set environment variables including PATH
|
||||
cmd.env("PATH", "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin");
|
||||
|
||||
// Spawn the process
|
||||
let mut child = cmd.spawn()
|
||||
.map_err(|e| format!("Failed to start llama-server: {}", e))?;
|
||||
|
||||
let pid = child.id();
|
||||
tracing::info!("[Service] Started llama-server with PID {}", pid);
|
||||
|
||||
// Detach the child process so it continues running independently
|
||||
std::mem::forget(child);
|
||||
|
||||
// Wait for server to be ready
|
||||
for i in 0..30 {
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
|
||||
if is_port_in_use(port) {
|
||||
// Try to call health endpoint
|
||||
let health_url = format!("http://127.0.0.1:{}/v1/models", port);
|
||||
if let Ok(resp) = reqwest::get(&health_url).await {
|
||||
if resp.status().is_success() {
|
||||
tracing::info!("[Service] llama-server is ready after {} seconds", i * 2);
|
||||
return Ok(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err("llama-server failed to start within 60 seconds".to_string())
|
||||
}
|
||||
|
||||
/// Stop llama.cpp server
|
||||
fn stop_llama_server(port: u16) -> Result<(), String> {
|
||||
if let Some(pid) = get_port_pid(port) {
|
||||
tracing::info!("[Service] Stopping llama-server on port {} (PID {})", port, pid);
|
||||
if kill_process(pid) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Failed to kill process {}", pid))
|
||||
}
|
||||
} else {
|
||||
Err(format!("No service running on port {}", port))
|
||||
}
|
||||
}
|
||||
|
||||
/// Check MBE health
|
||||
async fn check_mbe_health(port: u16) -> Result<MbeHealthResponse, String> {
|
||||
tracing::info!("[Service] Checking MBE health on port {}", port);
|
||||
|
||||
if !is_port_in_use(port) {
|
||||
tracing::warn!("[Service] Port {} not in use", port);
|
||||
return Err("Port not in use".to_string());
|
||||
}
|
||||
|
||||
tracing::info!("[Service] Port {} is in use, checking HTTP endpoint", port);
|
||||
|
||||
let url = format!("http://127.0.0.1:{}/v1/models", port);
|
||||
let resp = reqwest::get(&url)
|
||||
.await
|
||||
.map_err(|e| format!("HTTP request failed: {}", e))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("HTTP {}", resp.status()));
|
||||
}
|
||||
|
||||
let json: serde_json::Value = resp.json().await
|
||||
.map_err(|e| format!("Failed to parse JSON: {}", e))?;
|
||||
|
||||
tracing::info!("[Service] Health check response: {:?}", json);
|
||||
|
||||
// Extract model name from /v1/models response
|
||||
let model = json["models"][0]["name"]
|
||||
.as_str()
|
||||
.map(|s| {
|
||||
// Extract just the model name from path
|
||||
s.split('/')
|
||||
.last()
|
||||
.unwrap_or(s)
|
||||
.to_string()
|
||||
});
|
||||
|
||||
Ok(MbeHealthResponse {
|
||||
status: "ok".to_string(),
|
||||
model,
|
||||
uptime: Some(0), // Would need to track actual uptime
|
||||
})
|
||||
}
|
||||
|
||||
/// POST /api/v2/service/start
|
||||
pub async fn start_service(
|
||||
State(_state): State<AppState>,
|
||||
Json(req): Json<ServiceStartRequest>,
|
||||
) -> Result<Json<ServiceResponse>, StatusCode> {
|
||||
tracing::info!("[Service] Start request received: {:?}", req);
|
||||
|
||||
if req.name != "mbe" {
|
||||
tracing::error!("[Service] Invalid service name: {}", req.name);
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
let port = req.port;
|
||||
tracing::info!("[Service] Starting llama-server on port {}", port);
|
||||
|
||||
match start_llama_server(port, req.model).await {
|
||||
Ok(pid) => {
|
||||
tracing::info!("[Service] Successfully started llama-server with PID {}", pid);
|
||||
Ok(Json(ServiceResponse {
|
||||
result: "started".to_string(),
|
||||
pid: Some(pid),
|
||||
error: None,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[Service] Failed to start service: {}", e);
|
||||
Ok(Json(ServiceResponse {
|
||||
result: "failed".to_string(),
|
||||
pid: None,
|
||||
error: Some(e),
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v2/service/stop
|
||||
pub async fn stop_service(
|
||||
State(_state): State<AppState>,
|
||||
Json(req): Json<ServiceStopRequest>,
|
||||
) -> Result<Json<ServiceResponse>, StatusCode> {
|
||||
tracing::info!("[Service] Stop request: {:?}", req);
|
||||
|
||||
if req.name != "mbe" {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
let port = 8080;
|
||||
|
||||
match stop_llama_server(port) {
|
||||
Ok(()) => {
|
||||
Ok(Json(ServiceResponse {
|
||||
result: "stopped".to_string(),
|
||||
pid: None,
|
||||
error: None,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("[Service] Failed to stop service: {}", e);
|
||||
Ok(Json(ServiceResponse {
|
||||
result: "failed".to_string(),
|
||||
pid: None,
|
||||
error: Some(e),
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/mbe/health
|
||||
pub async fn mbe_health(
|
||||
State(_state): State<AppState>,
|
||||
) -> Result<Json<MbeHealthResponse>, StatusCode> {
|
||||
let port = 8080;
|
||||
|
||||
match check_mbe_health(port).await {
|
||||
Ok(health) => Ok(Json(health)),
|
||||
Err(e) => {
|
||||
tracing::error!("[Service] Health check failed: {}", e);
|
||||
Ok(Json(MbeHealthResponse {
|
||||
status: "offline".to_string(),
|
||||
model: None,
|
||||
uptime: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn router() -> axum::Router<AppState> {
|
||||
axum::Router::new()
|
||||
.route("/api/v2/service/start", axum::routing::post(start_service))
|
||||
.route("/api/v2/service/stop", axum::routing::post(stop_service))
|
||||
}
|
||||
+90
-14
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::api::types::AppState;
|
||||
use crate::core::admin_config::SearchConfig;
|
||||
use crate::core::file_profile::VlmTagValue;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ErrorResponse {
|
||||
@@ -74,8 +75,10 @@ pub struct SceneSearchResult {
|
||||
pub frame_number: u32,
|
||||
pub thumbnail_url: String,
|
||||
pub vlm_description: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub vlm_description_localized: Option<String>,
|
||||
pub vlm_objects: Vec<String>,
|
||||
pub vlm_tags: Vec<String>,
|
||||
pub vlm_tags: Vec<VlmTagValue>,
|
||||
pub score: f64,
|
||||
pub source: String,
|
||||
}
|
||||
@@ -116,12 +119,28 @@ pub struct TraceSearchResult {
|
||||
pub identity_uuid: Option<String>,
|
||||
pub identity_name: Option<String>,
|
||||
pub vlm_description: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub vlm_description_localized: Option<String>,
|
||||
pub vlm_clothing: Option<String>,
|
||||
pub vlm_tags: Vec<String>,
|
||||
pub vlm_location: Option<String>,
|
||||
pub thumbnail_url: String,
|
||||
pub score: f64,
|
||||
pub source: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub start_frame: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub end_frame: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub start_time: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub end_time: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub frame_number: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub timestamp_sec: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub best_face_frame: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn search_vlm_scenes(
|
||||
@@ -206,15 +225,31 @@ pub async fn search_vlm_scenes(
|
||||
|
||||
// Filter by vlm_tags
|
||||
if let Some(ref tags) = filters.vlm_tags {
|
||||
let empty_vec = Vec::new();
|
||||
let payload_tags = payload
|
||||
.get("vlm_tags")
|
||||
.and_then(|v| v.as_array())
|
||||
.unwrap_or(&empty_vec);
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let all_match = tags
|
||||
.iter()
|
||||
.all(|tag| payload_tags.contains(&serde_json::json!(tag)));
|
||||
let all_match = tags.iter().all(|filter_tag| {
|
||||
let filter_lower = filter_tag.to_lowercase();
|
||||
payload_tags.iter().any(|tag| {
|
||||
if let Some(s) = tag.as_str() {
|
||||
return s.to_lowercase() == filter_lower || s.to_lowercase().contains(&filter_lower);
|
||||
}
|
||||
let en = tag
|
||||
.get("en")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_lowercase();
|
||||
let local = tag
|
||||
.get("local")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_lowercase();
|
||||
en == filter_lower || local == filter_lower || en.contains(&filter_lower) || local.contains(&filter_lower)
|
||||
})
|
||||
});
|
||||
|
||||
if !all_match {
|
||||
continue;
|
||||
@@ -272,6 +307,11 @@ pub async fn search_vlm_scenes(
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let vlm_description_localized = payload
|
||||
.get("vlm_description_localized")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
let vlm_objects = payload
|
||||
.get("vlm_objects")
|
||||
.and_then(|v| v.as_array())
|
||||
@@ -287,8 +327,8 @@ pub async fn search_vlm_scenes(
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.to_string()))
|
||||
.collect()
|
||||
.filter_map(|v| serde_json::from_value::<VlmTagValue>(v.clone()).ok())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -310,6 +350,7 @@ pub async fn search_vlm_scenes(
|
||||
file_uuid, scene_index
|
||||
),
|
||||
vlm_description,
|
||||
vlm_description_localized,
|
||||
vlm_objects,
|
||||
vlm_tags,
|
||||
score,
|
||||
@@ -463,9 +504,8 @@ pub async fn search_vlm_traces(
|
||||
}
|
||||
}
|
||||
|
||||
// Query file name + profile enrichment
|
||||
let (file_name, vlm_clothing, vlm_location, vlm_tags_arr, identity_uuid, identity_name) =
|
||||
sqlx::query_as::<
|
||||
// Query file name + profile enrichment + trace timing
|
||||
let row = sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
String,
|
||||
@@ -474,10 +514,18 @@ pub async fn search_vlm_traces(
|
||||
Option<Vec<String>>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<i64>,
|
||||
Option<i64>,
|
||||
Option<i32>,
|
||||
Option<i64>,
|
||||
Option<f64>,
|
||||
),
|
||||
>(
|
||||
"SELECT COALESCE(v.file_name, ''), tp.vlm_clothing, tp.vlm_location, tp.vlm_tags, \
|
||||
i.uuid, i.name \
|
||||
tp.vlm_description_localized, \
|
||||
i.uuid, i.name, tp.start_frame, tp.end_frame, tp.frame_count, tp.best_face_frame, \
|
||||
COALESCE(v.fps, 24.0) as fps \
|
||||
FROM trace_profiles tp \
|
||||
LEFT JOIN videos v ON v.file_uuid = tp.file_uuid \
|
||||
LEFT JOIN identity_bindings ib ON ib.identity_type = 'trace' \
|
||||
@@ -489,8 +537,22 @@ pub async fn search_vlm_traces(
|
||||
.bind(trace_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| Json(ErrorResponse::new(format!("Database query failed: {}", e))))?
|
||||
.unwrap_or_default();
|
||||
.map_err(|e| Json(ErrorResponse::new(format!("Database query failed: {}", e))))?;
|
||||
|
||||
let (
|
||||
file_name,
|
||||
vlm_clothing,
|
||||
vlm_location,
|
||||
vlm_tags_arr,
|
||||
vlm_description_localized,
|
||||
identity_uuid,
|
||||
identity_name,
|
||||
start_frame,
|
||||
end_frame,
|
||||
_frame_count,
|
||||
best_face_frame,
|
||||
fps,
|
||||
) = row.unwrap_or_default();
|
||||
|
||||
let score = point.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
|
||||
|
||||
@@ -499,6 +561,12 @@ pub async fn search_vlm_traces(
|
||||
continue;
|
||||
}
|
||||
|
||||
let fps = fps.unwrap_or(24.0);
|
||||
let start_time = start_frame.map(|f| f as f64 / fps);
|
||||
let end_time = end_frame.map(|f| f as f64 / fps);
|
||||
let jump_frame = best_face_frame.or(start_frame);
|
||||
let jump_time = jump_frame.map(|f| f as f64 / fps);
|
||||
|
||||
results.push(TraceSearchResult {
|
||||
file_uuid: file_uuid.clone(),
|
||||
file_name,
|
||||
@@ -506,12 +574,20 @@ pub async fn search_vlm_traces(
|
||||
identity_uuid,
|
||||
identity_name,
|
||||
vlm_description,
|
||||
vlm_description_localized,
|
||||
vlm_clothing,
|
||||
vlm_tags: vlm_tags_arr.unwrap_or_default(),
|
||||
vlm_location,
|
||||
thumbnail_url: format!("/api/v1/trace-thumb/{}/{}", file_uuid, trace_id),
|
||||
score,
|
||||
source: "vector".to_string(),
|
||||
start_frame,
|
||||
end_frame,
|
||||
start_time,
|
||||
end_time,
|
||||
frame_number: jump_frame,
|
||||
timestamp_sec: jump_time,
|
||||
best_face_frame,
|
||||
});
|
||||
|
||||
if results.len() >= req.page_size {
|
||||
|
||||
@@ -182,6 +182,7 @@ async fn main() -> Result<()> {
|
||||
scene.timestamp_sec,
|
||||
scene.frame_number,
|
||||
desc,
|
||||
scene.vlm_description_localized.as_deref(),
|
||||
&scene.vlm_objects,
|
||||
&scene.vlm_tags,
|
||||
)
|
||||
|
||||
@@ -40,8 +40,9 @@ async fn main() -> Result<()> {
|
||||
|
||||
println!("找到 {} 筆結果:", results.len());
|
||||
for (i, r) in results.iter().enumerate() {
|
||||
let text_preview: String = r.text.chars().take(60).collect();
|
||||
let text_preview = if r.text.chars().count() > 60 {
|
||||
let text: String = r.text.clone().unwrap_or_default();
|
||||
let text_preview: String = text.chars().take(60).collect();
|
||||
let text_preview = if text.chars().count() > 60 {
|
||||
format!("{}...", text_preview)
|
||||
} else {
|
||||
text_preview
|
||||
@@ -55,7 +56,10 @@ async fn main() -> Result<()> {
|
||||
);
|
||||
println!(
|
||||
" 分數: {:.4}, 時間: {:.1}-{:.1}s, 類型: {}",
|
||||
r.bm25_score, r.start_time, r.end_time, r.chunk_type
|
||||
r.bm25_score,
|
||||
r.start_time.unwrap_or(0.0),
|
||||
r.end_time.unwrap_or(0.0),
|
||||
r.chunk_type
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -329,7 +329,7 @@ fn default_vlm_min_score() -> f64 {
|
||||
|
||||
fn default_vlm_output_language() -> String {
|
||||
std::env::var("MOMENTRY_PREFERRED_LANGUAGE")
|
||||
.unwrap_or_else(|_| "zh-TW".to_string())
|
||||
.unwrap_or_else(|_| "ja".to_string())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -396,6 +396,12 @@ pub struct ServerConfig {
|
||||
pub serve_base_url: String,
|
||||
#[serde(default = "default_storage_root")]
|
||||
pub storage_root: String,
|
||||
#[serde(default = "default_system_timezone")]
|
||||
pub timezone: String,
|
||||
}
|
||||
|
||||
fn default_system_timezone() -> String {
|
||||
std::env::var("MOMENTRY_TIMEZONE").unwrap_or_else(|_| "Asia/Taipei".to_string())
|
||||
}
|
||||
|
||||
fn default_server_port() -> u16 {
|
||||
|
||||
+1
-1
@@ -352,7 +352,7 @@ pub mod llm {
|
||||
env::var("MOMENTRY_LLM_CHAT_MODEL")
|
||||
.or_else(|_| env::var("MOMENTRY_LLM_SUMMARY_MODEL"))
|
||||
.or_else(|_| env::var("MOMENTRY_LLM_MODEL"))
|
||||
.unwrap_or_else(|_| "e4b".to_string())
|
||||
.unwrap_or_else(|_| "gemma-4-12b-it".to_string())
|
||||
});
|
||||
|
||||
pub static VISION_URL: Lazy<String> =
|
||||
|
||||
@@ -545,9 +545,9 @@ pub enum PipelineType {
|
||||
Cross,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProcessorType {
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProcessorType {
|
||||
Cut,
|
||||
Asr,
|
||||
Ocr,
|
||||
@@ -559,7 +559,8 @@ pub enum ProcessorType {
|
||||
Appearance,
|
||||
FaceCluster,
|
||||
FaceTrace,
|
||||
}
|
||||
Tkg,
|
||||
}
|
||||
|
||||
impl sqlx::Type<sqlx::Postgres> for ProcessorType {
|
||||
fn type_info() -> sqlx::postgres::PgTypeInfo {
|
||||
@@ -592,10 +593,11 @@ impl ProcessorType {
|
||||
ProcessorType::Pose => "pose",
|
||||
ProcessorType::Hand => "hand",
|
||||
ProcessorType::Asrx => "asrx",
|
||||
ProcessorType::Scene => "scene",
|
||||
ProcessorType::Scene => "scene_vlm",
|
||||
ProcessorType::Appearance => "appearance",
|
||||
ProcessorType::FaceCluster => "face_cluster",
|
||||
ProcessorType::FaceTrace => "face_trace",
|
||||
ProcessorType::Tkg => "tkg",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,9 +611,11 @@ impl ProcessorType {
|
||||
"hand" => Some(ProcessorType::Hand),
|
||||
"asrx" => Some(ProcessorType::Asrx),
|
||||
"scene" => Some(ProcessorType::Scene),
|
||||
"scene_vlm" => Some(ProcessorType::Scene), // Alias for scene
|
||||
"appearance" => Some(ProcessorType::Appearance),
|
||||
"face_cluster" => Some(ProcessorType::FaceCluster),
|
||||
"face_trace" => Some(ProcessorType::FaceTrace),
|
||||
"tkg" => Some(ProcessorType::Tkg),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -629,6 +633,7 @@ impl ProcessorType {
|
||||
ProcessorType::Appearance => 0.3,
|
||||
ProcessorType::FaceCluster => 0.7,
|
||||
ProcessorType::FaceTrace => 0.4,
|
||||
ProcessorType::Tkg => 0.5,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -652,6 +657,7 @@ impl ProcessorType {
|
||||
ProcessorType::Appearance => 512,
|
||||
ProcessorType::FaceCluster => 1024,
|
||||
ProcessorType::FaceTrace => 1024,
|
||||
ProcessorType::Tkg => 512,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -668,6 +674,7 @@ impl ProcessorType {
|
||||
ProcessorType::Appearance => None,
|
||||
ProcessorType::FaceCluster => Some("sklearn/agglomerative"),
|
||||
ProcessorType::FaceTrace => None,
|
||||
ProcessorType::Tkg => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -679,6 +686,7 @@ impl ProcessorType {
|
||||
ProcessorType::Appearance => vec![ProcessorType::Pose],
|
||||
ProcessorType::FaceTrace => vec![ProcessorType::Face],
|
||||
ProcessorType::FaceCluster => vec![ProcessorType::FaceTrace],
|
||||
ProcessorType::Tkg => vec![ProcessorType::FaceTrace],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
@@ -690,8 +698,10 @@ impl ProcessorType {
|
||||
ProcessorType::Asrx,
|
||||
ProcessorType::Ocr,
|
||||
ProcessorType::Face,
|
||||
ProcessorType::FaceTrace,
|
||||
ProcessorType::FaceCluster,
|
||||
ProcessorType::Scene, // Scene VLM processor
|
||||
// Scene (scenes.json) and TKG (tkg_nodes) are produced by dedicated
|
||||
// pipelines, not by the generic processor pool.
|
||||
// ProcessorType::Pose, // Disabled in production pipeline
|
||||
// ProcessorType::Hand, // Disabled in production pipeline
|
||||
// ProcessorType::Appearance, // Disabled in production pipeline
|
||||
@@ -706,7 +716,8 @@ impl ProcessorType {
|
||||
| ProcessorType::Hand
|
||||
| ProcessorType::Appearance
|
||||
| ProcessorType::FaceCluster
|
||||
| ProcessorType::FaceTrace => PipelineType::Frame,
|
||||
| ProcessorType::FaceTrace
|
||||
| ProcessorType::Tkg => PipelineType::Frame,
|
||||
|
||||
ProcessorType::Cut
|
||||
| ProcessorType::Asr
|
||||
|
||||
@@ -977,8 +977,9 @@ impl QdrantDb {
|
||||
timestamp_sec: f64,
|
||||
frame_number: u32,
|
||||
vlm_description: &str,
|
||||
vlm_description_localized: Option<&str>,
|
||||
vlm_objects: &[String],
|
||||
vlm_tags: &[String],
|
||||
vlm_tags: &[crate::core::file_profile::VlmTagValue],
|
||||
) -> Result<()> {
|
||||
let url = format!(
|
||||
"{}/collections/{}/points?wait=true",
|
||||
@@ -997,6 +998,12 @@ impl QdrantDb {
|
||||
"vlm_description".to_string(),
|
||||
serde_json::json!(vlm_description),
|
||||
);
|
||||
if let Some(localized) = vlm_description_localized {
|
||||
payload_map.insert(
|
||||
"vlm_description_localized".to_string(),
|
||||
serde_json::json!(localized),
|
||||
);
|
||||
}
|
||||
payload_map.insert("vlm_objects".to_string(), serde_json::json!(vlm_objects));
|
||||
payload_map.insert("vlm_tags".to_string(), serde_json::json!(vlm_tags));
|
||||
|
||||
|
||||
@@ -785,6 +785,35 @@ pub struct SceneConfig {
|
||||
pub samples_per_interval: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VlmTag {
|
||||
pub en: String,
|
||||
pub local: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum VlmTagValue {
|
||||
Structured(VlmTag),
|
||||
String(String),
|
||||
}
|
||||
|
||||
impl VlmTagValue {
|
||||
pub fn en(&self) -> &str {
|
||||
match self {
|
||||
Self::Structured(t) => &t.en,
|
||||
Self::String(s) => s,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local(&self) -> &str {
|
||||
match self {
|
||||
Self::Structured(t) => &t.local,
|
||||
Self::String(_) => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SceneFrame {
|
||||
pub index: usize,
|
||||
@@ -834,7 +863,7 @@ pub struct SceneFrame {
|
||||
pub vlm_attributes: Option<SceneAttributes>,
|
||||
|
||||
#[serde(default)]
|
||||
pub vlm_tags: Vec<String>,
|
||||
pub vlm_tags: Vec<VlmTagValue>,
|
||||
|
||||
pub embedding_status: EmbeddingStatus,
|
||||
}
|
||||
|
||||
+38
-15
@@ -32,22 +32,23 @@ struct Choice {
|
||||
}
|
||||
|
||||
pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
|
||||
let req = ChatRequest {
|
||||
model: (*config::llm::SUMMARY_MODEL).clone(),
|
||||
messages: vec![
|
||||
ChatMessage {
|
||||
role: "system".to_string(),
|
||||
content: system_prompt.to_string(),
|
||||
let req = serde_json::json!({
|
||||
"model": (*config::llm::SUMMARY_MODEL).clone(),
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": system_prompt.to_string(),
|
||||
},
|
||||
ChatMessage {
|
||||
role: "user".to_string(),
|
||||
content: prompt.to_string(),
|
||||
{
|
||||
"role": "user",
|
||||
"content": prompt.to_string(),
|
||||
},
|
||||
],
|
||||
temperature: 0.1,
|
||||
max_tokens: 512,
|
||||
stream: false,
|
||||
};
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 512,
|
||||
"stream": false,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
debug!("Calling LLM: {}", *config::llm::SUMMARY_URL);
|
||||
|
||||
@@ -64,10 +65,32 @@ pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
|
||||
anyhow::bail!("LLM API error: {}", text);
|
||||
}
|
||||
|
||||
let chat_res: ChatResponse = res.json().await?;
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ChatResponseExt {
|
||||
choices: Vec<ChoiceExt>,
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ChoiceExt {
|
||||
message: ChatMessageExt,
|
||||
finish_reason: Option<String>,
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ChatMessageExt {
|
||||
content: Option<String>,
|
||||
}
|
||||
|
||||
let chat_res: ChatResponseExt = res.json().await?;
|
||||
if let Some(choice) = chat_res.choices.first() {
|
||||
if choice.finish_reason.as_deref() == Some("length") {
|
||||
anyhow::bail!("LLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
}
|
||||
if let Some(choice) = chat_res.choices.into_iter().next() {
|
||||
Ok(choice.message.content.trim().to_string())
|
||||
let content = choice.message.content.filter(|s| !s.trim().is_empty()).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
anyhow::bail!("Empty response from LLM");
|
||||
}
|
||||
Ok(content.trim().to_string())
|
||||
} else {
|
||||
anyhow::bail!("Empty response from LLM");
|
||||
}
|
||||
|
||||
@@ -156,6 +156,7 @@ pub async fn call_llm_vision(
|
||||
"temperature": 0.1,
|
||||
"max_tokens": max_tokens,
|
||||
"stream": false,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
let res = LLM_CLIENT
|
||||
@@ -176,19 +177,30 @@ pub async fn call_llm_vision(
|
||||
#[derive(Deserialize)]
|
||||
struct VisionChoice {
|
||||
message: VisionMessage,
|
||||
finish_reason: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct VisionMessage {
|
||||
content: Option<String>,
|
||||
reasoning_content: Option<String>,
|
||||
}
|
||||
|
||||
let vision_res: VisionResponse = res.json().await?;
|
||||
if let Some(choice) = vision_res.choices.first() {
|
||||
if choice.finish_reason.as_deref() == Some("length") {
|
||||
anyhow::bail!("Vision LLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
}
|
||||
let content = vision_res
|
||||
.choices
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|c| c.message.content)
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
anyhow::bail!("Vision LLM returned empty content");
|
||||
}
|
||||
Ok(content.trim().to_string())
|
||||
}
|
||||
|
||||
@@ -221,14 +233,17 @@ pub async fn call_llm(
|
||||
*config::llm::CHAT_TIMEOUT_SECS
|
||||
};
|
||||
|
||||
let req = ChatRequest {
|
||||
let mut req = serde_json::to_value(&ChatRequest {
|
||||
model: llm_model(),
|
||||
messages,
|
||||
temperature: 0.1,
|
||||
max_tokens,
|
||||
stream: false,
|
||||
tools,
|
||||
};
|
||||
})?;
|
||||
if let Some(obj) = req.as_object_mut() {
|
||||
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
|
||||
}
|
||||
|
||||
let res = LLM_CLIENT
|
||||
.post(&llm_chat_url())
|
||||
@@ -243,6 +258,13 @@ pub async fn call_llm(
|
||||
}
|
||||
|
||||
let chat_res: ChatResponse = res.json().await?;
|
||||
let choice = chat_res
|
||||
.choices
|
||||
.first()
|
||||
.ok_or_else(|| anyhow::anyhow!("Empty LLM response"))?;
|
||||
if choice.finish_reason.as_deref() == Some("length") {
|
||||
anyhow::bail!("LLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
let choice = chat_res
|
||||
.choices
|
||||
.into_iter()
|
||||
@@ -257,7 +279,10 @@ pub async fn call_llm(
|
||||
Ok(LlmResponse::ToolCalls(calls))
|
||||
}
|
||||
_ => {
|
||||
let content = choice.message.content.unwrap_or_default();
|
||||
let content = choice.message.content.filter(|s| !s.trim().is_empty()).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
anyhow::bail!("LLM returned empty content");
|
||||
}
|
||||
Ok(LlmResponse::Text(content.trim().to_string()))
|
||||
}
|
||||
}
|
||||
@@ -278,14 +303,17 @@ pub async fn call_llm_with_usage(
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
let req = ChatRequest {
|
||||
let mut req = serde_json::to_value(&ChatRequest {
|
||||
model: llm_model(),
|
||||
messages,
|
||||
temperature: 0.1,
|
||||
max_tokens,
|
||||
stream: false,
|
||||
tools,
|
||||
};
|
||||
})?;
|
||||
if let Some(obj) = req.as_object_mut() {
|
||||
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
|
||||
}
|
||||
|
||||
let res = LLM_CLIENT
|
||||
.post(&llm_chat_url())
|
||||
@@ -300,6 +328,13 @@ pub async fn call_llm_with_usage(
|
||||
}
|
||||
|
||||
let chat_res: ChatResponse = res.json().await?;
|
||||
let choice_ref = chat_res
|
||||
.choices
|
||||
.first()
|
||||
.ok_or_else(|| anyhow::anyhow!("Empty LLM response"))?;
|
||||
if choice_ref.finish_reason.as_deref() == Some("length") {
|
||||
anyhow::bail!("LLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
let choice = chat_res
|
||||
.choices
|
||||
.into_iter()
|
||||
@@ -320,7 +355,10 @@ pub async fn call_llm_with_usage(
|
||||
LlmResponse::ToolCalls(calls)
|
||||
}
|
||||
_ => {
|
||||
let content = choice.message.content.unwrap_or_default();
|
||||
let content = choice.message.content.filter(|s| !s.trim().is_empty()).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
anyhow::bail!("LLM returned empty content");
|
||||
}
|
||||
LlmResponse::Text(content.trim().to_string())
|
||||
}
|
||||
};
|
||||
|
||||
@@ -90,3 +90,15 @@ pub fn probe_video(video_path: &str) -> Result<ProbeResult> {
|
||||
|
||||
Ok(ProbeResult { streams, format })
|
||||
}
|
||||
|
||||
/// Returns `Some(true/false)` when probing succeeds, `None` when it fails.
|
||||
pub fn has_audio_stream(video_path: &str) -> Option<bool> {
|
||||
probe_video(video_path)
|
||||
.ok()
|
||||
.map(|probe| {
|
||||
probe
|
||||
.streams
|
||||
.iter()
|
||||
.any(|s| s.codec_type.as_deref() == Some("audio"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
pub mod ffprobe;
|
||||
pub mod unified;
|
||||
|
||||
pub use ffprobe::{probe_video, FormatInfo, ProbeResult, StreamInfo};
|
||||
pub use ffprobe::{has_audio_stream, probe_video, FormatInfo, ProbeResult, StreamInfo};
|
||||
|
||||
@@ -96,6 +96,17 @@ pub async fn process_asr(
|
||||
) -> Result<AsrResult> {
|
||||
tracing::info!("[ASR] Starting ASR processing: {}", video_path);
|
||||
|
||||
// Files without an audio stream cannot be transcribed. Skipping Whisper
|
||||
// immediately also lets ingestion finish (asr_status=no_audio_track).
|
||||
if crate::core::probe::has_audio_stream(video_path) == Some(false) {
|
||||
tracing::info!("[ASR] No audio track, skipping Whisper: {}", video_path);
|
||||
let mut result = AsrResult::no_audio_track();
|
||||
result.add_metadata("asr", "none", uuid);
|
||||
crate::core::json_formatter::write_file_pretty_rounded(&result, output_path, 2)
|
||||
.context("Failed to write ASR output")?;
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
let mlx_whisper_cli = std::path::Path::new("/opt/homebrew/bin/mlx_whisper");
|
||||
|
||||
if mlx_whisper_cli.exists() {
|
||||
@@ -150,6 +161,10 @@ pub async fn process_asr(
|
||||
let json_str =
|
||||
std::fs::read_to_string(&final_json_path).context("Failed to read MLX Whisper output")?;
|
||||
|
||||
// MLX Whisper outputs NaN for avg_logprob when no speech detected
|
||||
// NaN is not valid JSON - replace with null before parsing
|
||||
let json_str = json_str.replace("NaN", "null");
|
||||
|
||||
let whisper_result: WhisperJsonOutput =
|
||||
serde_json::from_str(&json_str).context("Failed to parse MLX Whisper output")?;
|
||||
|
||||
|
||||
@@ -108,6 +108,16 @@ pub async fn process_asrx(
|
||||
) -> Result<AsrxResult> {
|
||||
tracing::info!("[ASRX] Starting speaker diarization: {}", video_path);
|
||||
|
||||
// No audio stream means no speakers; emit a valid empty result instead of
|
||||
// letting the diarization tool fail.
|
||||
if crate::core::probe::has_audio_stream(video_path) == Some(false) {
|
||||
tracing::info!("[ASRX] No audio track, skipping diarization: {}", video_path);
|
||||
let mut result = AsrxResult::no_audio_track();
|
||||
result.add_metadata("asrx", "none", uuid);
|
||||
result.save_to_file(output_path)?;
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
use super::tool_selector::ToolSelector;
|
||||
let executor = PythonExecutor::new()?;
|
||||
let selector = ToolSelector::new("asrx");
|
||||
|
||||
+182
-87
@@ -6,7 +6,7 @@ use tokio::process::Command;
|
||||
|
||||
use crate::core::file_profile::{
|
||||
EmbeddingStatus, SceneConfig, SceneFrame, SceneInfo, SceneProfile, SceneStatus,
|
||||
SelectionReason, VideoInfo, VlmStatus,
|
||||
SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
|
||||
};
|
||||
|
||||
pub struct SceneVlmProcessor {
|
||||
@@ -476,11 +476,98 @@ impl SceneVlmProcessor {
|
||||
tags
|
||||
}
|
||||
|
||||
/// Call VLM API to generate scene description
|
||||
fn language_display_name(language: &str) -> &'static str {
|
||||
match language {
|
||||
"zh-TW" => "Traditional Chinese (zh-TW)",
|
||||
"zh-CN" => "Simplified Chinese (zh-CN)",
|
||||
"ja" => "Japanese (ja)",
|
||||
"ko" => "Korean (ko)",
|
||||
"es" => "Spanish (es)",
|
||||
"fr" => "French (fr)",
|
||||
"de" => "German (de)",
|
||||
_ => "English (en)",
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the structured scene analysis prompt.
|
||||
fn build_scene_prompt(local_language: &str) -> String {
|
||||
let local_name = Self::language_display_name(local_language);
|
||||
format!(
|
||||
r#"You are an expert visual analyst for a multimodal video search system.
|
||||
|
||||
Analyze the attached image frame and return ONLY valid JSON with NO markdown, NO explanations, NO reasoning, NO thinking.
|
||||
|
||||
Use this exact schema:
|
||||
|
||||
{{
|
||||
"summary": "Concise English summary of the core content (1-2 sentences). Factual, avoid superlatives like beautiful/stunning/amazing.",
|
||||
"category": "Single highest-level category. Choose ONE from: landscape|architecture|interior|people|event|nature|urban|transport|food|animal|product|other",
|
||||
"scene_type": "Environment/background. Choose ONE from: indoor|outdoor|city street|resort|nature|mountain|beach|forest|building exterior|building interior|road|park|unknown",
|
||||
"objects": ["3-5 most prominent objects or subjects in English. Concrete and specific."],
|
||||
"actions": ["Main actions/events or static state if no motion. Use English (e.g. 'static scene', 'driving', 'walking')."],
|
||||
"visual_attributes": {{
|
||||
"lighting": "e.g. natural daylight, golden hour, overcast, artificial, backlit, mixed lighting",
|
||||
"composition": "e.g. aerial view, wide angle, eye level, low angle, close-up, drone shot, street level",
|
||||
"color_palette": ["3-5 dominant colors in English (e.g. gray, green, blue, orange)"]
|
||||
}},
|
||||
"detected_text": ["Exact visible signs, logos, plaques, or printed text. Only if legible. Empty array if none."],
|
||||
"tags": [
|
||||
{{"en": "english_tag", "local": "localized_tag"}}
|
||||
]
|
||||
}}
|
||||
|
||||
Rules:
|
||||
- summary must be English only
|
||||
- objects, actions, visual_attributes must use concrete English terms. Avoid generic words like "photo", "image", "view", "scene"
|
||||
- tags: 5-10 items. Each item MUST be an object with both "en" and "local" keys
|
||||
- Use {local_name} for "local". If the preferred language is English, set "local" equal to "en" but keep both keys
|
||||
- Prioritize search-relevant terms (environment type, key structures/objects). Do NOT just copy the full summary into tags
|
||||
- Do NOT duplicate objects 1:1 unless genuinely useful as search tags
|
||||
- Keep tags concise (1-3 words). Avoid redundancy between tags
|
||||
- detected_text: only extract text actually visible, do not guess or infer
|
||||
- Output ONLY the JSON object"#
|
||||
)
|
||||
}
|
||||
|
||||
/// Extract the first JSON object from a VLM response (tolerates markdown fences).
|
||||
fn extract_json_object(content: &str) -> Option<&str> {
|
||||
let start = content.find('{')?;
|
||||
let end = content.rfind('}')?;
|
||||
if end <= start {
|
||||
return None;
|
||||
}
|
||||
Some(&content[start..=end])
|
||||
}
|
||||
|
||||
fn parse_tags(value: Option<&serde_json::Value>) -> Vec<VlmTagValue> {
|
||||
let Some(arr) = value.and_then(|v| v.as_array()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
arr.iter()
|
||||
.filter_map(|tag| {
|
||||
if let Some(en) = tag.get("en").and_then(|v| v.as_str()) {
|
||||
let local = tag
|
||||
.get("local")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(en)
|
||||
.to_string();
|
||||
Some(VlmTagValue::Structured(VlmTag {
|
||||
en: en.to_string(),
|
||||
local,
|
||||
}))
|
||||
} else {
|
||||
tag.as_str().map(|s| VlmTagValue::String(s.to_string()))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Call VLM API to generate structured scene info.
|
||||
/// Returns (english_description, objects, bilingual_tags).
|
||||
pub async fn generate_scene_description(
|
||||
image_path: &std::path::Path,
|
||||
language: &str,
|
||||
) -> Result<(String, Vec<String>, Vec<String>)> {
|
||||
local_language: &str,
|
||||
) -> Result<(String, Vec<String>, Vec<VlmTagValue>)> {
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -493,33 +580,15 @@ impl SceneVlmProcessor {
|
||||
let vlm_url = crate::core::config::llm::VISION_URL.clone();
|
||||
let vlm_model = crate::core::config::llm::VISION_MODEL.clone();
|
||||
|
||||
let prompt = Self::build_scene_prompt(local_language);
|
||||
|
||||
tracing::debug!(
|
||||
"[VLM API] Calling {} with model {} (language: {})",
|
||||
"[VLM API] Calling {} with model {} (local language: {})",
|
||||
vlm_url,
|
||||
vlm_model,
|
||||
language
|
||||
local_language
|
||||
);
|
||||
|
||||
// Language-specific prompts
|
||||
let (prompt, max_tokens) = match language {
|
||||
"zh-TW" => (
|
||||
"請用繁體中文描述這個場景,用2-3句話。重點說明:環境、物體和活動。簡潔且準確。",
|
||||
800
|
||||
),
|
||||
"zh-CN" => (
|
||||
"请用简体中文描述这个场景,用2-3句话。重点说明:环境、物体和活动。简洁且准确。",
|
||||
800
|
||||
),
|
||||
"ja" => (
|
||||
"このシーンを2-3文で説明してください。環境、物体、活動に焦点を当ててください。簡潔で正確に。",
|
||||
800
|
||||
),
|
||||
_ => (
|
||||
"Describe this scene in 2-3 sentences. Focus on: environment, objects, and activities. Be concise and factual.",
|
||||
800
|
||||
),
|
||||
};
|
||||
|
||||
let body = serde_json::json!({
|
||||
"model": vlm_model,
|
||||
"messages": [{
|
||||
@@ -537,8 +606,9 @@ impl SceneVlmProcessor {
|
||||
}
|
||||
]
|
||||
}],
|
||||
"max_tokens": max_tokens,
|
||||
"temperature": 0.1
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
@@ -564,60 +634,59 @@ impl SceneVlmProcessor {
|
||||
.await
|
||||
.context("Failed to parse VLM API response")?;
|
||||
|
||||
// Parse response - handle both 'content' and 'reasoning_content' (Gemma4)
|
||||
let message = resp_json
|
||||
// Parse response
|
||||
let choice = resp_json
|
||||
.get("choices")
|
||||
.and_then(|c| c.get(0))
|
||||
.and_then(|c| c.get("message"))
|
||||
.context("Invalid VLM API response structure")?;
|
||||
if choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length") {
|
||||
anyhow::bail!("VLM returned truncated response (finish_reason=length)");
|
||||
}
|
||||
let message = choice.get("message").context("Invalid VLM API response structure")?;
|
||||
|
||||
// Try content first (final answer), fall back to reasoning_content if content is empty
|
||||
let content = match message
|
||||
.get("content")
|
||||
.and_then(|c| c.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
{
|
||||
Some(s) => s.to_string(),
|
||||
None => message
|
||||
.get("reasoning_content")
|
||||
.and_then(|c| c.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
Some(s) => s.trim().to_string(),
|
||||
None => anyhow::bail!("VLM returned empty content"),
|
||||
};
|
||||
|
||||
if content.is_empty() {
|
||||
anyhow::bail!("VLM returned empty response");
|
||||
}
|
||||
// Parse structured JSON; fall back to heuristic extraction if it fails.
|
||||
if let Some(json_str) = Self::extract_json_object(&content) {
|
||||
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(json_str) {
|
||||
let description = parsed
|
||||
.get("summary")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty());
|
||||
|
||||
if content.is_empty() {
|
||||
tracing::warn!("[VLM API] Empty response for {:?}", image_path);
|
||||
}
|
||||
|
||||
// Parse content - Gemma4 outputs thinking + description
|
||||
// Skip thinking part (starts with "The user wants" or "I need to")
|
||||
let description =
|
||||
if content.starts_with("The user wants") || content.starts_with("I need to") {
|
||||
// Find where actual description starts (after first newline or second sentence)
|
||||
content
|
||||
.lines()
|
||||
.skip_while(|line| {
|
||||
line.starts_with("The user wants")
|
||||
|| line.starts_with("I need to")
|
||||
|| line.trim().is_empty()
|
||||
})
|
||||
if let Some(description) = description {
|
||||
let objects = parsed
|
||||
.get("objects")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.to_string()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.trim()
|
||||
.to_string()
|
||||
} else {
|
||||
content.clone()
|
||||
};
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let tags = Self::parse_tags(parsed.get("tags"));
|
||||
return Ok((description, objects, tags));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract objects and tags from description (simple heuristic)
|
||||
let objects = Self::extract_objects_from_text(&description);
|
||||
let tags = Self::extract_tags_from_text(&description);
|
||||
|
||||
Ok((description, objects, tags))
|
||||
tracing::warn!(
|
||||
"[Scene VLM] Failed to parse structured JSON, falling back to text heuristics"
|
||||
);
|
||||
let objects = Self::extract_objects_from_text(&content);
|
||||
let tags = Self::extract_tags_from_text(&content)
|
||||
.into_iter()
|
||||
.map(VlmTagValue::String)
|
||||
.collect();
|
||||
Ok((content, objects, tags))
|
||||
}
|
||||
|
||||
/// Generate VLM descriptions for all scene frames
|
||||
@@ -633,7 +702,13 @@ impl SceneVlmProcessor {
|
||||
);
|
||||
|
||||
// Get preferred language from admin config
|
||||
let preferred_language = crate::core::config::get_preferred_language();
|
||||
let preferred_language = crate::core::admin_config::ADMIN_CONFIG
|
||||
.get_full_config()
|
||||
.await
|
||||
.search
|
||||
.vlm_output_language
|
||||
.clone();
|
||||
crate::core::config::set_preferred_language(preferred_language.clone());
|
||||
tracing::info!("[Scene VLM] Preferred language: {}", preferred_language);
|
||||
|
||||
// Process scenes sequentially to avoid issues
|
||||
@@ -641,31 +716,51 @@ impl SceneVlmProcessor {
|
||||
let frame_path = SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
|
||||
|
||||
// Generate English description (for indexing)
|
||||
match Self::generate_scene_description(&frame_path, "en").await {
|
||||
match Self::generate_scene_description(&frame_path, &preferred_language).await {
|
||||
Ok((description_en, objects, tags)) => {
|
||||
scene.vlm_description = Some(description_en.clone());
|
||||
scene.vlm_objects = objects.clone();
|
||||
scene.vlm_tags = tags.clone();
|
||||
|
||||
// Generate localized description if needed
|
||||
// Generate localized description by translation if needed
|
||||
if preferred_language != "en" {
|
||||
match Self::generate_scene_description(&frame_path, &preferred_language)
|
||||
.await
|
||||
{
|
||||
Ok((description_localized, _, _)) => {
|
||||
scene.vlm_description_localized = Some(description_localized);
|
||||
tracing::info!(
|
||||
"[Scene VLM] ✅ Scene {}: EN + {}",
|
||||
idx,
|
||||
preferred_language
|
||||
);
|
||||
let system_prompt = "You are a professional translator. Translate accurately. Return ONLY the translated text, no explanations or notes.";
|
||||
let prompt = format!("Translate the following scene description into {}. Do not summarize, add, or omit any details. Keep the same number of sentences.\n\n{}", preferred_language, description_en);
|
||||
let body = serde_json::json!({
|
||||
"model": crate::core::config::llm::CHAT_MODEL.as_str(),
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"stream": false,
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(120)).build()?;
|
||||
match client.post(&*crate::core::config::llm::CHAT_URL).json(&body).send().await {
|
||||
Ok(resp) => {
|
||||
if resp.status().is_success() {
|
||||
if let Ok(v) = resp.json::<serde_json::Value>().await {
|
||||
if let Some(choice) = v["choices"].get(0) {
|
||||
if choice.get("finish_reason").and_then(|x| x.as_str()) != Some("length") {
|
||||
if let Some(tr) = choice["message"]["content"].as_str() {
|
||||
let tr = tr.trim();
|
||||
if !tr.is_empty() && !tr.contains("thinking") && !tr.contains("I need to") && !tr.contains("* Task") && !tr.contains("* Scene:") && tr.len() > 10 {
|
||||
scene.vlm_description_localized = Some(tr.to_string());
|
||||
tracing::info!("[Scene VLM] ✅ Scene {}: EN + {} (translated)", idx, preferred_language);
|
||||
scene.vlm_status = VlmStatus::Completed;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed", idx);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"[Scene VLM] ⚠️ Scene {} localized failed: {}",
|
||||
idx,
|
||||
e
|
||||
);
|
||||
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed: {}", idx, e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
+117
-35
@@ -927,6 +927,16 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
.collect()
|
||||
};
|
||||
|
||||
// Scene (scenes.json) and TKG (tkg_nodes) are handled by dedicated
|
||||
// pipelines; never execute them in the generic processor pool. This also
|
||||
// covers legacy jobs whose processors list still contains them.
|
||||
processors_to_run.retain(|p| {
|
||||
!matches!(
|
||||
p,
|
||||
crate::core::db::ProcessorType::Scene | crate::core::db::ProcessorType::Tkg
|
||||
)
|
||||
});
|
||||
|
||||
let total_processor_types = processors_to_run.len() as i32;
|
||||
|
||||
// Get video total_frames for progress tracking
|
||||
@@ -3708,11 +3718,28 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
};
|
||||
|
||||
// Wait for Qdrant to have all face points AND the full trace count.
|
||||
// (up to 60 seconds). Point count alone isn't enough — store_traced_faces.py
|
||||
// (up to 120 seconds). Point count alone isn't enough — store_traced_faces
|
||||
// writes face_traced.json first, then uploads trace_id to Qdrant
|
||||
// incrementally. Two consecutive equal polls (2s apart) can falsely look
|
||||
// "stable" between upload batches. So we additionally require the Qdrant
|
||||
// distinct trace count to reach the expected count from face_traced.json.
|
||||
// NOTE: expected_traces is re-read inside the loop to handle updates from
|
||||
// rust_store_traced_faces that may complete while we're waiting.
|
||||
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
let filter = serde_json::json!({
|
||||
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
|
||||
});
|
||||
|
||||
let mut attempts = 0;
|
||||
let max_attempts = 60;
|
||||
let mut stable_trace_count: Option<i64> = None;
|
||||
let mut trace_stability_attempts = 0;
|
||||
let max_trace_stability_attempts = 30;
|
||||
loop {
|
||||
attempts += 1;
|
||||
|
||||
// Re-read expected_traces each iteration to handle face_traced.json updates
|
||||
let expected_traces: i64 =
|
||||
if let Ok(content) = std::fs::read_to_string(&traced_path) {
|
||||
if let Ok(traced_data) =
|
||||
@@ -3730,16 +3757,6 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
0
|
||||
};
|
||||
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
let filter = serde_json::json!({
|
||||
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
|
||||
});
|
||||
|
||||
let mut attempts = 0;
|
||||
let max_attempts = 60;
|
||||
let mut stable_trace_count: Option<i64> = None;
|
||||
loop {
|
||||
attempts += 1;
|
||||
match qdrant.count_points("_faces", filter.clone()).await {
|
||||
Ok(count) if count >= expected_faces && expected_faces > 0 => {
|
||||
// Point count met — now verify trace stability
|
||||
@@ -3770,8 +3787,17 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
}
|
||||
}
|
||||
stable_trace_count = Some(trace_count);
|
||||
info!("⏳ TKG point count met ({} faces), verifying trace stability ({})...",
|
||||
count, trace_count);
|
||||
trace_stability_attempts += 1;
|
||||
|
||||
// Timeout: if trace stability check exceeds limit, proceed anyway
|
||||
if trace_stability_attempts >= max_trace_stability_attempts {
|
||||
warn!("⚠️ TKG trace stability timeout after {} attempts (trace={}, expected={}), proceeding anyway: {}",
|
||||
trace_stability_attempts, trace_count, expected_traces, uuid);
|
||||
break;
|
||||
}
|
||||
|
||||
info!("⏳ TKG point count met ({} faces), verifying trace stability ({}/{}, expected {})...",
|
||||
count, trace_count, trace_stability_attempts, expected_traces);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Qdrant scroll for trace check failed: {}, proceeding anyway", e);
|
||||
@@ -3884,6 +3910,21 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
)
|
||||
.await;
|
||||
|
||||
// Create processor_results entry for TKG
|
||||
if let Err(e) = db_clone
|
||||
.upsert_processor_result(
|
||||
job_id,
|
||||
crate::core::db::ProcessorType::Tkg,
|
||||
&uuid_clone,
|
||||
"completed",
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("Failed to create processor_results for tkg: {}", e);
|
||||
} else {
|
||||
info!("✅ Created processor_results record for tkg");
|
||||
}
|
||||
|
||||
// Trigger Rule 2 ingestion after TKG complete
|
||||
if total_edges > 0 {
|
||||
// Mark rule2_ingestion as running
|
||||
@@ -4029,6 +4070,19 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
);
|
||||
publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp)
|
||||
.await;
|
||||
|
||||
// Create processor_results entry for TKG (no-faces path)
|
||||
if let Err(e) = db_clone
|
||||
.upsert_processor_result(
|
||||
job_id,
|
||||
crate::core::db::ProcessorType::Tkg,
|
||||
&uuid_clone,
|
||||
"completed",
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("Failed to create processor_results for tkg (no-faces): {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => error!("❌ TKG build failed for {}: {}", uuid_clone, e),
|
||||
}
|
||||
@@ -4627,39 +4681,66 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
&scene.filename,
|
||||
);
|
||||
|
||||
// Get preferred language
|
||||
let preferred_language = crate::core::config::get_preferred_language();
|
||||
// Get preferred language from admin config
|
||||
let preferred_language = crate::core::admin_config::ADMIN_CONFIG
|
||||
.get_full_config()
|
||||
.await
|
||||
.search
|
||||
.vlm_output_language
|
||||
.clone();
|
||||
crate::core::config::set_preferred_language(preferred_language.clone());
|
||||
|
||||
// Generate English description (for indexing)
|
||||
match SceneVlmProcessor::generate_scene_description(&frame_path, "en").await {
|
||||
match SceneVlmProcessor::generate_scene_description(&frame_path, &preferred_language).await {
|
||||
Ok((description_en, objects, tags)) => {
|
||||
scene.vlm_description = Some(description_en.clone());
|
||||
scene.vlm_objects = objects.clone();
|
||||
scene.vlm_tags = tags.clone();
|
||||
|
||||
// Generate localized description if needed
|
||||
// Generate localized description by translation if needed
|
||||
if preferred_language != "en" {
|
||||
match SceneVlmProcessor::generate_scene_description(
|
||||
&frame_path,
|
||||
&preferred_language,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((description_localized, _, _)) => {
|
||||
scene.vlm_description_localized = Some(description_localized);
|
||||
let system_prompt = "You are a professional translator. Translate accurately. Return ONLY the translated text, no explanations or notes.";
|
||||
let prompt = format!("Translate the following scene description into {}. Do not summarize, add, or omit any details. Keep the same number of sentences.\n\n{}", preferred_language, description_en);
|
||||
let body = serde_json::json!({
|
||||
"model": crate::core::config::llm::CHAT_MODEL.as_str(),
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"stream": false,
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0.1,
|
||||
"chat_template_kwargs": {"enable_thinking": false}
|
||||
});
|
||||
let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(120)).build()?;
|
||||
match client.post(&*crate::core::config::llm::CHAT_URL).json(&body).send().await {
|
||||
Ok(resp) => {
|
||||
if resp.status().is_success() {
|
||||
if let Ok(v) = resp.json::<serde_json::Value>().await {
|
||||
if let Some(choice) = v["choices"].get(0) {
|
||||
if choice.get("finish_reason").and_then(|x| x.as_str()) != Some("length") {
|
||||
if let Some(tr) = choice["message"]["content"].as_str() {
|
||||
let tr = tr.trim();
|
||||
if !tr.is_empty() && !tr.contains("thinking") && !tr.contains("I need to") && !tr.contains("* Task") && !tr.contains("* Scene:") && tr.len() > 10 {
|
||||
scene.vlm_description_localized = Some(tr.to_string());
|
||||
scene.vlm_status = VlmStatus::Completed;
|
||||
tracing::info!("[Scene VLM] ✅ Scene {}: EN + {} (translated)", idx, preferred_language);
|
||||
processed += 1;
|
||||
if processed % 10 == 0 || processed == total_scenes {
|
||||
let _ = db.update_scene_vlm_progress(uuid, processed as i32, total_scenes as i32).await;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed", idx);
|
||||
scene.vlm_status = VlmStatus::Completed;
|
||||
tracing::info!(
|
||||
"[Scene VLM] ✅ Scene {}: EN + {}",
|
||||
idx,
|
||||
preferred_language
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"[Scene VLM] ⚠️ Scene {} localized failed: {}",
|
||||
idx,
|
||||
e
|
||||
);
|
||||
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed: {}", idx, e);
|
||||
scene.vlm_status = VlmStatus::Completed;
|
||||
}
|
||||
}
|
||||
@@ -4780,6 +4861,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
scene.timestamp_sec,
|
||||
scene.frame_number,
|
||||
desc,
|
||||
scene.vlm_description_localized.as_deref(),
|
||||
&scene.vlm_objects,
|
||||
&scene.vlm_tags,
|
||||
)
|
||||
|
||||
@@ -1252,6 +1252,23 @@ impl ProcessorPool {
|
||||
total_faces: 0,
|
||||
})
|
||||
}
|
||||
ProcessorType::Tkg => {
|
||||
// TKG is handled separately in job_worker.rs via build_tkg
|
||||
// This is a no-op placeholder for the processor type
|
||||
tracing::info!("TKG processor stub called for {} (handled by build_tkg)", job.uuid);
|
||||
Ok(ProcessorOutput {
|
||||
data: serde_json::Value::Null,
|
||||
chunks_produced: 0,
|
||||
frames_processed: 0,
|
||||
total_frames,
|
||||
retry_count: 0,
|
||||
pid: 0,
|
||||
asr_status: None,
|
||||
segment_count: 0,
|
||||
face_status: None,
|
||||
total_faces: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
function monitorApp() {
|
||||
return {
|
||||
// Data
|
||||
lastUpdate: 'Never',
|
||||
queue: { pending: 0, running: 0, completed: 0, failed: 0 },
|
||||
runningJobs: [],
|
||||
worker: {
|
||||
cpu_percent: 0,
|
||||
gpu_percent: 0,
|
||||
memory_mb: 0,
|
||||
memory_percent: 0,
|
||||
active_processors: 0,
|
||||
max_processors: 6,
|
||||
processors: []
|
||||
},
|
||||
|
||||
// Initialize
|
||||
init() {
|
||||
this.refresh();
|
||||
setInterval(() => this.refresh(), 5000);
|
||||
},
|
||||
|
||||
// Refresh all data
|
||||
async refresh() {
|
||||
await Promise.all([
|
||||
this.fetchQueueStats(),
|
||||
this.fetchRunningJobs(),
|
||||
this.fetchWorkerStatus()
|
||||
]);
|
||||
this.lastUpdate = new Date().toLocaleTimeString();
|
||||
},
|
||||
|
||||
// Fetch queue stats
|
||||
async fetchQueueStats() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/monitor/queue_stats');
|
||||
this.queue = await res.json();
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch queue stats:', e);
|
||||
}
|
||||
},
|
||||
|
||||
// Fetch running jobs
|
||||
async fetchRunningJobs() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/monitor/running_jobs');
|
||||
const data = await res.json();
|
||||
this.runningJobs = data.jobs;
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch running jobs:', e);
|
||||
}
|
||||
},
|
||||
|
||||
// Fetch worker status
|
||||
async fetchWorkerStatus() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/monitor/worker_status');
|
||||
this.worker = await res.json();
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch worker status:', e);
|
||||
}
|
||||
},
|
||||
|
||||
// Helper functions
|
||||
getPhaseName(phase) {
|
||||
const names = {
|
||||
1: 'Foundation',
|
||||
2: 'Core Processing',
|
||||
3: 'Deep Analysis',
|
||||
4: 'Knowledge Building'
|
||||
};
|
||||
return names[phase] || '';
|
||||
},
|
||||
|
||||
getProcessorIcon(status) {
|
||||
const icons = {
|
||||
'completed': '✅',
|
||||
'running': '🔄',
|
||||
'pending': '⏸️',
|
||||
'deferred': '⏸️',
|
||||
'failed': '❌'
|
||||
};
|
||||
return icons[status] || '❓';
|
||||
},
|
||||
|
||||
getProcessorColor(status) {
|
||||
const colors = {
|
||||
'completed': 'bg-green-500',
|
||||
'running': 'bg-blue-500',
|
||||
'pending': 'bg-gray-500',
|
||||
'deferred': 'bg-yellow-500',
|
||||
'failed': 'bg-red-500'
|
||||
};
|
||||
return colors[status] || 'bg-gray-500';
|
||||
},
|
||||
|
||||
formatDuration(secs) {
|
||||
if (!secs) return '0s';
|
||||
const m = Math.floor(secs / 60);
|
||||
const s = Math.floor(secs % 60);
|
||||
return m > 0 ? `${m}m ${s}s` : `${s}s`;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-TW">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Momentry Monitor</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
|
||||
</head>
|
||||
<body class="bg-gray-900 text-white min-h-screen">
|
||||
<div x-data="monitorApp()" x-init="init()" class="container mx-auto px-4 py-8">
|
||||
|
||||
<!-- Header -->
|
||||
<header class="mb-8 flex justify-between items-center">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Momentry Monitor</h1>
|
||||
<p class="text-gray-400 text-sm mt-1">
|
||||
Last updated: <span x-text="lastUpdate"></span>
|
||||
</p>
|
||||
</div>
|
||||
<button @click="refresh()" class="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded">
|
||||
Refresh
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<!-- Queue Overview -->
|
||||
<div class="bg-gray-800 rounded-lg p-6 mb-6">
|
||||
<h2 class="text-xl font-semibold mb-4">Queue Overview</h2>
|
||||
<div class="grid grid-cols-4 gap-4 text-center">
|
||||
<div>
|
||||
<div class="text-3xl font-bold text-yellow-400" x-text="queue.pending"></div>
|
||||
<div class="text-sm text-gray-400">Pending</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-3xl font-bold text-blue-400" x-text="queue.running"></div>
|
||||
<div class="text-sm text-gray-400">Running</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-3xl font-bold text-green-400" x-text="queue.completed"></div>
|
||||
<div class="text-sm text-gray-400">Completed</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-3xl font-bold text-red-400" x-text="queue.failed"></div>
|
||||
<div class="text-sm text-gray-400">Failed</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 text-sm text-gray-400">
|
||||
Currently processing: <span class="text-blue-400 font-semibold" x-text="queue.running"></span> jobs
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Running Jobs -->
|
||||
<div class="bg-gray-800 rounded-lg p-6 mb-6">
|
||||
<h2 class="text-xl font-semibold mb-4">Running Jobs</h2>
|
||||
|
||||
<div class="space-y-4">
|
||||
<template x-for="job in runningJobs" :key="job.job_id">
|
||||
<div class="border border-gray-700 rounded-lg p-4">
|
||||
<div class="flex justify-between items-start mb-3">
|
||||
<div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-lg font-semibold">Job #<span x-text="job.job_id"></span></span>
|
||||
<span class="px-2 py-1 bg-blue-500/20 text-blue-400 rounded text-sm">RUNNING</span>
|
||||
</div>
|
||||
<div class="text-sm text-gray-400 mt-1">
|
||||
<span x-text="job.file_name"></span> | UUID: <span x-text="job.file_uuid"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<div class="text-sm text-gray-400">Duration</div>
|
||||
<div class="font-semibold" x-text="formatDuration(job.duration_secs)"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3">
|
||||
<template x-for="phase in [1,2,3,4]" :key="phase">
|
||||
<div>
|
||||
<div class="text-sm font-semibold mb-2"
|
||||
x-text="'Phase ' + phase + ': ' + getPhaseName(phase)"></div>
|
||||
<div class="grid grid-cols-4 gap-2">
|
||||
<template x-for="proc in job.processors.filter(p => p.phase === phase)" :key="proc.name">
|
||||
<div class="bg-gray-700 rounded p-2">
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<span class="text-sm" x-text="proc.name"></span>
|
||||
<span x-text="getProcessorIcon(proc.status)"></span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex-1 bg-gray-600 rounded-full h-1.5">
|
||||
<div class="h-1.5 rounded-full"
|
||||
:class="getProcessorColor(proc.status)"
|
||||
:style="'width: ' + proc.progress + '%'"></div>
|
||||
</div>
|
||||
<span class="text-xs text-gray-400" x-text="proc.progress + '%'"></span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div x-show="runningJobs.length === 0" class="text-center text-gray-500 py-8">
|
||||
No jobs currently running
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Worker Resources -->
|
||||
<div class="bg-gray-800 rounded-lg p-6 mb-6">
|
||||
<h2 class="text-xl font-semibold mb-4">Worker Resources</h2>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
|
||||
<div>
|
||||
<div class="flex justify-between mb-1">
|
||||
<span>CPU</span>
|
||||
<span x-text="worker.cpu_percent.toFixed(1) + '%'"></span>
|
||||
</div>
|
||||
<div class="w-full bg-gray-700 rounded-full h-2">
|
||||
<div class="bg-blue-500 h-2 rounded-full"
|
||||
:style="'width: ' + worker.cpu_percent + '%'"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex justify-between mb-1">
|
||||
<span>GPU</span>
|
||||
<span x-text="worker.gpu_percent.toFixed(1) + '%'"></span>
|
||||
</div>
|
||||
<div class="w-full bg-gray-700 rounded-full h-2">
|
||||
<div class="bg-green-500 h-2 rounded-full"
|
||||
:style="'width: ' + worker.gpu_percent + '%'"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex justify-between mb-1">
|
||||
<span>Memory</span>
|
||||
<span x-text="worker.memory_percent.toFixed(1) + '%'"></span>
|
||||
</div>
|
||||
<div class="w-full bg-gray-700 rounded-full h-2">
|
||||
<div class="bg-purple-500 h-2 rounded-full"
|
||||
:style="'width: ' + worker.memory_percent + '%'"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-sm text-gray-400">
|
||||
Active Processors: <span x-text="worker.active_processors"></span> / <span x-text="worker.max_processors"></span>
|
||||
</div>
|
||||
|
||||
<div x-show="worker.processors.length > 0" class="mt-4">
|
||||
<div class="text-sm font-semibold mb-2">Active Processors:</div>
|
||||
<div class="space-y-1">
|
||||
<template x-for="proc in worker.processors" :key="proc.name + proc.job_id">
|
||||
<div class="text-sm text-gray-400">
|
||||
<span class="font-medium" x-text="proc.name"></span> (Job #<span x-text="proc.job_id"></span>)
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-TW">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Momentry Monitor (Simple)</title>
|
||||
<style>
|
||||
body { font-family: monospace; background: #1a1a1a; color: #fff; padding: 20px; }
|
||||
.job { background: #2a2a2a; padding: 15px; margin: 10px 0; border-radius: 8px; }
|
||||
.processor { background: #3a3a3a; padding: 5px 10px; margin: 5px 0; border-radius: 4px; }
|
||||
.completed { color: #0f0; }
|
||||
.running { color: #0ff; }
|
||||
.failed { color: #f00; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Momentry Monitor</h1>
|
||||
<div id="queue">Loading queue stats...</div>
|
||||
<div id="jobs">Loading running jobs...</div>
|
||||
<div id="worker">Loading worker status...</div>
|
||||
|
||||
<script>
|
||||
async function refresh() {
|
||||
try {
|
||||
// Queue Stats
|
||||
const queueRes = await fetch('/api/v1/monitor/queue_stats');
|
||||
const queue = await queueRes.json();
|
||||
document.getElementById('queue').innerHTML =
|
||||
`<h2>Queue</h2>
|
||||
<div>Pending: ${queue.pending} | Running: ${queue.running} | Completed: ${queue.completed} | Failed: ${queue.failed}</div>`;
|
||||
|
||||
// Running Jobs
|
||||
const jobsRes = await fetch('/api/v1/monitor/running_jobs');
|
||||
const jobsData = await jobsRes.json();
|
||||
let jobsHtml = '<h2>Running Jobs</h2>';
|
||||
if (jobsData.jobs.length === 0) {
|
||||
jobsHtml += '<div>No jobs running</div>';
|
||||
} else {
|
||||
jobsData.jobs.forEach(job => {
|
||||
jobsHtml += `
|
||||
<div class="job">
|
||||
<div><strong>Job #${job.job_id}</strong> - ${job.file_name}</div>
|
||||
<div>UUID: ${job.file_uuid}</div>
|
||||
<div>Duration: ${job.duration_secs}s</div>
|
||||
<div style="margin-top: 10px;">
|
||||
${job.processors.map(p =>
|
||||
`<div class="processor ${p.status}">${p.name}: ${p.status} (${p.progress}%)</div>`
|
||||
).join('')}
|
||||
</div>
|
||||
</div>`;
|
||||
});
|
||||
}
|
||||
document.getElementById('jobs').innerHTML = jobsHtml;
|
||||
|
||||
// Worker Status
|
||||
const workerRes = await fetch('/api/v1/monitor/worker_status');
|
||||
const worker = await workerRes.json();
|
||||
document.getElementById('worker').innerHTML =
|
||||
`<h2>Worker Resources</h2>
|
||||
<div>CPU: ${worker.cpu_percent.toFixed(1)}% | GPU: ${worker.gpu_percent.toFixed(1)}% | Memory: ${worker.memory_mb}MB (${worker.memory_percent.toFixed(1)}%)</div>
|
||||
<div>Active Processors: ${worker.active_processors}/${worker.max_processors}</div>`;
|
||||
|
||||
} catch (e) {
|
||||
console.error('Error:', e);
|
||||
document.getElementById('jobs').innerHTML = '<div style="color: red;">Error loading data: ' + e.message + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
refresh();
|
||||
setInterval(refresh, 5000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,244 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-TW">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Momentry Monitor</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: #0f172a;
|
||||
color: #e2e8f0;
|
||||
padding: 20px;
|
||||
}
|
||||
.container { max-width: 1200px; margin: 0 auto; }
|
||||
h1 { font-size: 2rem; margin-bottom: 1rem; }
|
||||
h2 { font-size: 1.5rem; margin: 1rem 0; }
|
||||
.card {
|
||||
background: #1e293b;
|
||||
border-radius: 8px;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem; text-align: center; }
|
||||
.stat { padding: 1rem; }
|
||||
.stat-value { font-size: 2rem; font-weight: bold; }
|
||||
.stat-label { color: #94a3b8; font-size: 0.875rem; }
|
||||
.text-yellow { color: #fbbf24; }
|
||||
.text-blue { color: #60a5fa; }
|
||||
.text-green { color: #34d399; }
|
||||
.text-red { color: #f87171; }
|
||||
.job { border: 1px solid #334155; border-radius: 8px; padding: 1rem; margin: 0.5rem 0; }
|
||||
.processor {
|
||||
background: #334155;
|
||||
border-radius: 4px;
|
||||
padding: 0.5rem;
|
||||
margin: 0.25rem 0;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.status-completed { color: #34d399; }
|
||||
.status-running { color: #60a5fa; }
|
||||
.status-pending { color: #fbbf24; }
|
||||
.status-failed { color: #f87171; }
|
||||
.progress-bar {
|
||||
background: #475569;
|
||||
border-radius: 9999px;
|
||||
height: 8px;
|
||||
overflow: hidden;
|
||||
margin: 0.25rem 0;
|
||||
}
|
||||
.progress-fill { height: 100%; transition: width 0.3s; }
|
||||
.refresh-btn {
|
||||
background: #3b82f6;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.refresh-btn:hover { background: #2563eb; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
|
||||
<div>
|
||||
<h1>Momentry Monitor</h1>
|
||||
<p style="color: #94a3b8; font-size: 0.875rem;">
|
||||
Last updated: <span id="lastUpdate">Never</span>
|
||||
</p>
|
||||
</div>
|
||||
<button class="refresh-btn" onclick="refresh()">Refresh</button>
|
||||
</header>
|
||||
|
||||
<div class="card">
|
||||
<h2>Queue Overview</h2>
|
||||
<div class="grid">
|
||||
<div class="stat">
|
||||
<div class="stat-value text-yellow" id="pending">0</div>
|
||||
<div class="stat-label">Pending</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value text-blue" id="running">0</div>
|
||||
<div class="stat-label">Running</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value text-green" id="completed">0</div>
|
||||
<div class="stat-label">Completed</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat-value text-red" id="failed">0</div>
|
||||
<div class="stat-label">Failed</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Running Jobs</h2>
|
||||
<div id="jobs">Loading...</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Worker Resources</h2>
|
||||
<div>
|
||||
<div>CPU: <span id="cpu">0</span>%</div>
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" id="cpu-bar" style="width: 0%; background: #3b82f6;"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-top: 0.5rem;">
|
||||
<div>GPU: <span id="gpu">0</span>%</div>
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" id="gpu-bar" style="width: 0%; background: #34d399;"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-top: 0.5rem;">
|
||||
<div>Memory: <span id="memory">0</span> MB (<span id="memory-pct">0</span>%)</div>
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" id="memory-bar" style="width: 0%; background: #a855f7;"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-top: 1rem;">
|
||||
Active Processors: <span id="active-proc">0</span> / <span id="max-proc">6</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const phaseNames = {
|
||||
1: 'Foundation',
|
||||
2: 'Core Processing',
|
||||
3: 'Deep Analysis',
|
||||
4: 'Knowledge Building'
|
||||
};
|
||||
|
||||
const statusIcons = {
|
||||
'completed': '✓',
|
||||
'running': '🔄',
|
||||
'pending': '⏸',
|
||||
'failed': '✗'
|
||||
};
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
// Queue Stats
|
||||
const queueRes = await fetch('/api/v1/monitor/queue_stats');
|
||||
const queue = await queueRes.json();
|
||||
document.getElementById('pending').textContent = queue.pending;
|
||||
document.getElementById('running').textContent = queue.running;
|
||||
document.getElementById('completed').textContent = queue.completed;
|
||||
document.getElementById('failed').textContent = queue.failed;
|
||||
|
||||
// Running Jobs
|
||||
const jobsRes = await fetch('/api/v1/monitor/running_jobs');
|
||||
const jobsData = await jobsRes.json();
|
||||
|
||||
let jobsHtml = '';
|
||||
if (jobsData.jobs.length === 0) {
|
||||
jobsHtml = '<div style="color: #94a3b8; padding: 2rem; text-align: center;">No jobs currently running</div>';
|
||||
} else {
|
||||
jobsData.jobs.forEach(job => {
|
||||
const duration = formatDuration(job.duration_secs);
|
||||
|
||||
// Group processors by phase
|
||||
const phases = {};
|
||||
job.processors.forEach(p => {
|
||||
const phase = p.phase || 0;
|
||||
if (!phases[phase]) phases[phase] = [];
|
||||
phases[phase].push(p);
|
||||
});
|
||||
|
||||
jobsHtml += `
|
||||
<div class="job">
|
||||
<div style="display: flex; justify-content: space-between; margin-bottom: 1rem;">
|
||||
<div>
|
||||
<div style="font-size: 1.25rem; font-weight: bold;">
|
||||
Job #${job.job_id}
|
||||
</div>
|
||||
<div style="color: #94a3b8; font-size: 0.875rem;">
|
||||
${job.file_name || 'Unknown file'} | UUID: ${job.file_uuid}
|
||||
</div>
|
||||
</div>
|
||||
<div style="text-align: right;">
|
||||
<div style="color: #94a3b8; font-size: 0.875rem;">Duration</div>
|
||||
<div style="font-weight: bold;">${duration}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
${Object.entries(phases).sort(([a], [b]) => a - b).map(([phase, procs]) => `
|
||||
<div style="margin: 0.5rem 0;">
|
||||
<div style="font-weight: bold; margin-bottom: 0.25rem;">
|
||||
Phase ${phase}: ${phaseNames[phase] || 'Other'}
|
||||
</div>
|
||||
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 0.5rem;">
|
||||
${procs.map(p => `
|
||||
<div class="processor status-${p.status}">
|
||||
${statusIcons[p.status] || '?'} ${p.name}: ${p.status} (${p.progress}%)
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
}
|
||||
document.getElementById('jobs').innerHTML = jobsHtml;
|
||||
|
||||
// Worker Status
|
||||
const workerRes = await fetch('/api/v1/monitor/worker_status');
|
||||
const worker = await workerRes.json();
|
||||
|
||||
document.getElementById('cpu').textContent = worker.cpu_percent.toFixed(1);
|
||||
document.getElementById('cpu-bar').style.width = worker.cpu_percent + '%';
|
||||
|
||||
document.getElementById('gpu').textContent = worker.gpu_percent.toFixed(1);
|
||||
document.getElementById('gpu-bar').style.width = worker.gpu_percent + '%';
|
||||
|
||||
document.getElementById('memory').textContent = worker.memory_mb;
|
||||
document.getElementById('memory-pct').textContent = worker.memory_percent.toFixed(1);
|
||||
document.getElementById('memory-bar').style.width = worker.memory_percent + '%';
|
||||
|
||||
document.getElementById('active-proc').textContent = worker.active_processors;
|
||||
document.getElementById('max-proc').textContent = worker.max_processors;
|
||||
|
||||
document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString();
|
||||
} catch (e) {
|
||||
console.error('Error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function formatDuration(secs) {
|
||||
if (!secs) return '0s';
|
||||
const m = Math.floor(secs / 60);
|
||||
const s = Math.floor(secs % 60);
|
||||
return m > 0 ? `${m}m ${s}s` : `${s}s`;
|
||||
}
|
||||
|
||||
refresh();
|
||||
setInterval(refresh, 5000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Monitor Test</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Monitor API Test</h1>
|
||||
<pre id="output">Loading...</pre>
|
||||
<script>
|
||||
async function test() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/monitor/running_jobs');
|
||||
const data = await res.json();
|
||||
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
|
||||
} catch (e) {
|
||||
document.getElementById('output').textContent = 'Error: ' + e.message;
|
||||
}
|
||||
}
|
||||
test();
|
||||
setInterval(test, 5000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -83,6 +83,8 @@ struct TraceInfo {
|
||||
total_appearances: usize,
|
||||
avg_confidence: f32,
|
||||
path: Vec<TracePoint>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
frames: Vec<TracePoint>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
@@ -106,6 +108,50 @@ struct FaceTracedData {
|
||||
traces: HashMap<String, TraceInfo>,
|
||||
}
|
||||
|
||||
/// Load existing trace_ids from face_traced.json if it exists.
|
||||
/// Returns a map of (frame, face_idx) -> trace_id.
|
||||
fn load_existing_trace_ids(traced_path: &std::path::Path) -> HashMap<(i64, usize), i32> {
|
||||
let mut result = HashMap::new();
|
||||
|
||||
if !traced_path.exists() {
|
||||
return result;
|
||||
}
|
||||
|
||||
let content = match std::fs::read_to_string(traced_path) {
|
||||
Ok(c) => c,
|
||||
Err(_) => return result,
|
||||
};
|
||||
|
||||
let traced_data: serde_json::Value = match serde_json::from_str(&content) {
|
||||
Ok(d) => d,
|
||||
Err(_) => return result,
|
||||
};
|
||||
|
||||
// Read trace_ids directly from frames array
|
||||
if let Some(frames) = traced_data.get("frames").and_then(|f| f.as_array()) {
|
||||
for frame in frames {
|
||||
let frame_num = frame.get("frame").and_then(|f| f.as_i64()).unwrap_or(0);
|
||||
if let Some(faces) = frame.get("faces").and_then(|f| f.as_array()) {
|
||||
for (face_idx, face) in faces.iter().enumerate() {
|
||||
if let Some(trace_id) = face.get("trace_id").and_then(|t| t.as_i64()) {
|
||||
result.insert((frame_num, face_idx), trace_id as i32);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Check if two bboxes match within tolerance (±tolerance pixels)
|
||||
fn bboxes_match(b1: &BBox, b2: &BBox, tolerance: i32) -> bool {
|
||||
(b1.x - b2.x).abs() <= tolerance &&
|
||||
(b1.y - b2.y).abs() <= tolerance &&
|
||||
(b1.width - b2.width).abs() <= tolerance &&
|
||||
(b1.height - b2.height).abs() <= tolerance
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
@@ -131,11 +177,19 @@ fn main() -> Result<()> {
|
||||
println!("[TRACE_STORE] Loading embeddings from Qdrant...");
|
||||
let qdrant_faces = load_qdrant_faces(&args.file_uuid);
|
||||
|
||||
// Load existing trace_ids from face_traced.json if available
|
||||
let traced_json_path = args.output_dir.join(format!("{}.face_traced.json", args.file_uuid));
|
||||
let existing_trace_ids = load_existing_trace_ids(&traced_json_path);
|
||||
if !existing_trace_ids.is_empty() {
|
||||
println!("[TRACE_STORE] Loaded {} existing trace_ids from face_traced.json", existing_trace_ids.len());
|
||||
}
|
||||
|
||||
// Run face tracking
|
||||
println!("[TRACE_STORE] Running face tracking with embedding similarity (threshold={})...", args.similarity_threshold);
|
||||
let traces = run_face_tracking(
|
||||
&mut face_data,
|
||||
&qdrant_faces,
|
||||
&existing_trace_ids,
|
||||
args.min_trace_len,
|
||||
args.min_confidence,
|
||||
args.similarity_threshold,
|
||||
@@ -179,6 +233,7 @@ fn main() -> Result<()> {
|
||||
fn run_face_tracking(
|
||||
face_data: &mut FaceData,
|
||||
qdrant_faces: &[FacePoint],
|
||||
existing_trace_ids: &HashMap<(i64, usize), i32>,
|
||||
min_trace_len: usize,
|
||||
min_confidence: f32,
|
||||
similarity_threshold: f64,
|
||||
@@ -187,6 +242,12 @@ fn run_face_tracking(
|
||||
let mut traces: HashMap<String, TraceInfo> = HashMap::new();
|
||||
let mut next_trace_id = 1;
|
||||
|
||||
// If we have existing trace_ids, use the max existing ID as starting point
|
||||
if !existing_trace_ids.is_empty() {
|
||||
next_trace_id = existing_trace_ids.values().copied().max().unwrap_or(0) + 1;
|
||||
println!("[TRACE] Resuming from existing trace_ids, next_id={}", next_trace_id);
|
||||
}
|
||||
|
||||
// Build frame -> embedding map from Qdrant data
|
||||
let mut frame_embeddings: HashMap<i64, Vec<(Vec<f64>, f32, BBox)>> = HashMap::new();
|
||||
for point in qdrant_faces {
|
||||
@@ -234,13 +295,36 @@ fn run_face_tracking(
|
||||
for face_idx in 0..frame.faces.len() {
|
||||
let current_face = &frame.faces[face_idx];
|
||||
|
||||
// Find matching embedding
|
||||
// First check if we have an existing trace_id for this face
|
||||
if let Some(&existing_tid) = existing_trace_ids.get(&(current_frame_num, face_idx)) {
|
||||
face_trace_ids.insert((current_frame_num, face_idx), existing_tid);
|
||||
|
||||
let trace_key = existing_tid.to_string();
|
||||
let trace = traces.entry(trace_key).or_insert(TraceInfo {
|
||||
trace_id: existing_tid,
|
||||
total_appearances: 0,
|
||||
avg_confidence: 0.0,
|
||||
path: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
});
|
||||
trace.total_appearances += 1;
|
||||
trace.path.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
bbox: current_face.bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
});
|
||||
trace.frames.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
bbox: current_face.bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find matching embedding with bbox tolerance (±5px)
|
||||
let current_embedding = current_embeddings.iter()
|
||||
.find(|(_, _, bbox)| {
|
||||
bbox.x == current_face.bbox.x &&
|
||||
bbox.y == current_face.bbox.y &&
|
||||
bbox.width == current_face.bbox.width &&
|
||||
bbox.height == current_face.bbox.height
|
||||
bboxes_match(bbox, ¤t_face.bbox, 5)
|
||||
})
|
||||
.map(|(emb, _, _)| emb.clone());
|
||||
|
||||
@@ -260,14 +344,11 @@ fn run_face_tracking(
|
||||
if let Some(&prev_trace_id) = face_trace_ids.get(&(prev_frame.frame, prev_face_idx)) {
|
||||
let iou = calculate_iou(¤t_face.bbox, &prev_face.bbox);
|
||||
|
||||
// Get previous embedding
|
||||
// Get previous embedding with bbox tolerance
|
||||
let prev_embeddings = frame_embeddings.get(&prev_frame.frame).cloned().unwrap_or_default();
|
||||
let prev_embedding = prev_embeddings.iter()
|
||||
.find(|(_, _, bbox)| {
|
||||
bbox.x == prev_face.bbox.x &&
|
||||
bbox.y == prev_face.bbox.y &&
|
||||
bbox.width == prev_face.bbox.width &&
|
||||
bbox.height == prev_face.bbox.height
|
||||
bboxes_match(bbox, &prev_face.bbox, 5)
|
||||
})
|
||||
.map(|(emb, _, _)| emb);
|
||||
|
||||
@@ -307,6 +388,7 @@ fn run_face_tracking(
|
||||
total_appearances: 0,
|
||||
avg_confidence: 0.0,
|
||||
path: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
});
|
||||
|
||||
trace.total_appearances += 1;
|
||||
@@ -315,6 +397,11 @@ fn run_face_tracking(
|
||||
bbox: current_face.bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
});
|
||||
trace.frames.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
bbox: current_face.bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user