feat: add regenerate trace thumbnail endpoint with bbox clamping
- validator::clamp_crop: clamp crop rect to frame dims (fixes OOB shift) - tkg.rs: use clamp_crop in key_face crop paths (root-cause fix) - trace_agent_api: POST /api/v1/file/:file_uuid/trace/:trace_id/regenerate-thumbnail - docs: 26_trace_thumbnail_regenerate.md for Studio team
This commit is contained in:
@@ -0,0 +1,114 @@
|
|||||||
|
# Trace Thumbnail Regenerate API 使用指南 — Studio 團隊參考
|
||||||
|
|
||||||
|
**版本**: v1.0
|
||||||
|
**日期**: 2026-08-12
|
||||||
|
**狀態**: 已實作(Core)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
修復「key_frame 正常、key_face bbox 正常、但 key_face 縮圖異常」之現象。
|
||||||
|
|
||||||
|
**根因**: bbox 部分越過 frame 邊界(如 trace 355b 案例)時,crop 未 clamp 到 frame 尺寸,ffmpeg 靜默 clamp/位移,導致縮圖內容錯位。由於縮圖端點優先回傳 `key_face.jpg` cache,異常內容被持久化顯示。
|
||||||
|
|
||||||
|
**修復**: 本端點重新選取該 trace 之 best-confidence face,將 bbox clamp 至影片尺寸後重新裁切,覆寫 `key_face.jpg`,並同步更新 `.faces` cache。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API 端點
|
||||||
|
|
||||||
|
### POST `/api/v1/file/{file_uuid}/trace/{trace_id}/regenerate-thumbnail`
|
||||||
|
|
||||||
|
**功能**: 重新產生單一 trace 的 face thumbnail(覆寫 cache)
|
||||||
|
**Auth**: Required
|
||||||
|
**Body**: 可為空。
|
||||||
|
|
||||||
|
**Response 200**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"file_uuid": "...",
|
||||||
|
"trace_id": 355,
|
||||||
|
"frame": 1835,
|
||||||
|
"bbox": { "x": 65, "y": 301, "width": 70, "height": 59 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- `frame` / `bbox` 為重新裁切使用的(clamp 後)frame 與 bbox。
|
||||||
|
|
||||||
|
**Error Responses**:
|
||||||
|
| Status | 說明 |
|
||||||
|
|--------|------|
|
||||||
|
| 404 | Video not found(該 file_uuid 無影片)或 No face found for this trace(該 trace 無 face 資料) |
|
||||||
|
| 400 | Video width/height unavailable — 影片未記錄尺寸,無法 clamp,拒絕重切 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 行為說明
|
||||||
|
|
||||||
|
1. 讀取該 trace 最高 confidence 的 frame + bbox(**不**重跑 blur 優化,取既有 best face 復原同一區域)
|
||||||
|
2. 將 bbox clamp 到影片 width/height 內(`clamp_crop`)
|
||||||
|
3. ffmpeg 自影片以 decoded frame index 切出該 frame → crop face 區域
|
||||||
|
4. 覆寫 `{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}/key_face.jpg`
|
||||||
|
5. 若 `.faces/{file_uuid}/{trace_id}/{frame}.jpg` 已存在則同步覆寫
|
||||||
|
|
||||||
|
**不影響**: Qdrant、`trace_profiles` DB、`tkg_nodes`、影片檔 — 僅重寫縮圖 cache。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Studio 整合步驟
|
||||||
|
|
||||||
|
### 1. apiCall (`src/api/index.ts`)
|
||||||
|
|
||||||
|
新增 case:
|
||||||
|
```ts
|
||||||
|
case 'regenerate_trace_thumbnail': {
|
||||||
|
return { url: `/api/v1/file/${a.fileUuid}/trace/${a.traceId}/regenerate-thumbnail`, method: 'POST' }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Face detail modal 加「Re-gen」按鈕 (`src/views/PeopleView.vue`)
|
||||||
|
|
||||||
|
於 `ms-face-detail-thumb` 附近加入按鈕,呼叫上方 apiCall,in-flight 時 disabled。
|
||||||
|
|
||||||
|
### 3. 觸發後 refresh(重要)
|
||||||
|
|
||||||
|
Face detail 縮圖顯示的是 `faceThumbsCache`(key = `${file_uuid}-${trace_id}`)。`loadTraceThumb` 對已有 cache 的 key 會直接 return,**單獨 `bumpThumbCacheBust()` 無法刷新 face detail 縮圖**。正確順序:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
await apiCall('regenerate_trace_thumbnail', { fileUuid, traceId }) // 1. 呼叫 regenerate
|
||||||
|
delete faceThumbsCache.value[`${fileUuid}-${traceId}`] // 2. 清除該 key 的 blob cache
|
||||||
|
bumpThumbCacheBust() // 3. bump 版本(避 HTTP cache)
|
||||||
|
loadTraceThumb({ file_uuid: fileUuid, trace_id: traceId }) // 4. 重新載入縮圖
|
||||||
|
```
|
||||||
|
|
||||||
|
> `candidateThumbs` 即 `faceThumbsCache` 的 alias(PeopleView.vue:722),delete 後無需額外處理。
|
||||||
|
> 若想一次清空全部縮圖可用 `clearFaceThumbs()`(較重,不建議單一 trace 場景)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 測試指示
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用已知越界案例(trace 355b 一類)驗證:
|
||||||
|
# 1) regenerate 前:GET thumbnail 顯示位移內容
|
||||||
|
# 2) 呼叫 regenerate → 回 success,含 clamp 後 bbox
|
||||||
|
# 3) 再次 GET thumbnail → 內容正確對齊 bbox
|
||||||
|
curl -X POST "http://localhost:3002/api/v1/file/<FILE_UUID>/trace/<TRACE_ID>/regenerate-thumbnail" \
|
||||||
|
-H "X-API-Key: <KEY>"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 參考
|
||||||
|
|
||||||
|
- 根因 crop 修正:`src/core/thumbnail/validator.rs::clamp_crop`、`src/core/processor/tkg.rs`
|
||||||
|
- 端點 handler:`src/api/trace_agent_api.rs::regenerate_trace_thumbnail`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 版本歷史
|
||||||
|
|
||||||
|
| 版本 | 日期 | 變更 |
|
||||||
|
|------|------|------|
|
||||||
|
| v1.0 | 2026-08-12 | 初版 |
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>26 Trace Thumbnail Regenerate - Momentry API Docs</title>
|
||||||
|
<style>
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; color: #333; padding: 40px; }
|
||||||
|
.container { max-width: 960px; margin: 0 auto; background: white; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); padding: 40px; }
|
||||||
|
h1 { font-size: 24px; margin: 24px 0 12px; }
|
||||||
|
h2 { font-size: 20px; margin: 20px 0 10px; color: #222; }
|
||||||
|
h3 { font-size: 16px; margin: 16px 0 8px; color: #444; }
|
||||||
|
p { line-height: 1.6; margin: 8px 0; }
|
||||||
|
table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
|
||||||
|
th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
|
||||||
|
th { background: #f0f0f0; font-weight: 600; }
|
||||||
|
code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; font-size: 13px; }
|
||||||
|
pre { background: #f8f8f8; border: 1px solid #ddd; border-radius: 6px; padding: 12px; overflow-x: auto; margin: 12px 0; }
|
||||||
|
pre code { background: none; padding: 0; }
|
||||||
|
a { color: #0066cc; }
|
||||||
|
.back { display: inline-block; margin-bottom: 20px; color: #666; }
|
||||||
|
.back:hover { color: #333; }
|
||||||
|
.topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
|
||||||
|
.logout-btn { font-size: 13px; color: #999; text-decoration: none; }
|
||||||
|
.logout-btn:hover { color: #cc0000; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<div class="topbar">
|
||||||
|
<a class="back" href="index.html">← Back to index</a>
|
||||||
|
<a class="logout-btn" href="#" onclick="fetch('/api/v1/auth/logout',{method:'POST'}).then(()=>window.location.reload());return false">Logout</a>
|
||||||
|
</div>
|
||||||
|
<h1>Trace Thumbnail Regenerate API 使用指南 — Studio 團隊參考</h1>
|
||||||
|
<p><strong>版本</strong>: v1.0
|
||||||
|
<strong>日期</strong>: 2026-08-12
|
||||||
|
<strong>狀態</strong>: 已實作(Core)</p>
|
||||||
|
<hr />
|
||||||
|
<h2>概述</h2>
|
||||||
|
<p>修復「key_frame 正常、key_face bbox 正常、但 key_face 縮圖異常」之現象。</p>
|
||||||
|
<p><strong>根因</strong>: bbox 部分越過 frame 邊界(如 trace 355b 案例)時,crop 未 clamp 到 frame 尺寸,ffmpeg 靜默 clamp/位移,導致縮圖內容錯位。由於縮圖端點優先回傳 <code>key_face.jpg</code> cache,異常內容被持久化顯示。</p>
|
||||||
|
<p><strong>修復</strong>: 本端點重新選取該 trace 之 best-confidence face,將 bbox clamp 至影片尺寸後重新裁切,覆寫 <code>key_face.jpg</code>,並同步更新 <code>.faces</code> cache。</p>
|
||||||
|
<hr />
|
||||||
|
<h2>API 端點</h2>
|
||||||
|
<h3>POST <code>/api/v1/file/{file_uuid}/trace/{trace_id}/regenerate-thumbnail</code></h3>
|
||||||
|
<p><strong>功能</strong>: 重新產生單一 trace 的 face thumbnail(覆寫 cache)
|
||||||
|
<strong>Auth</strong>: Required
|
||||||
|
<strong>Body</strong>: 可為空。</p>
|
||||||
|
<p><strong>Response 200</strong>:</p>
|
||||||
|
<div class="codehilite"><pre><span></span><code><span class="p">{</span>
|
||||||
|
<span class="w"> </span><span class="nt">"success"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="p">,</span>
|
||||||
|
<span class="w"> </span><span class="nt">"file_uuid"</span><span class="p">:</span><span class="w"> </span><span class="s2">"..."</span><span class="p">,</span>
|
||||||
|
<span class="w"> </span><span class="nt">"trace_id"</span><span class="p">:</span><span class="w"> </span><span class="mi">355</span><span class="p">,</span>
|
||||||
|
<span class="w"> </span><span class="nt">"frame"</span><span class="p">:</span><span class="w"> </span><span class="mi">1835</span><span class="p">,</span>
|
||||||
|
<span class="w"> </span><span class="nt">"bbox"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nt">"x"</span><span class="p">:</span><span class="w"> </span><span class="mi">65</span><span class="p">,</span><span class="w"> </span><span class="nt">"y"</span><span class="p">:</span><span class="w"> </span><span class="mi">301</span><span class="p">,</span><span class="w"> </span><span class="nt">"width"</span><span class="p">:</span><span class="w"> </span><span class="mi">70</span><span class="p">,</span><span class="w"> </span><span class="nt">"height"</span><span class="p">:</span><span class="w"> </span><span class="mi">59</span><span class="w"> </span><span class="p">}</span>
|
||||||
|
<span class="p">}</span>
|
||||||
|
</code></pre></div>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li><code>frame</code> / <code>bbox</code> 為重新裁切使用的(clamp 後)frame 與 bbox。</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Error Responses</strong>:
|
||||||
|
| Status | 說明 |
|
||||||
|
|--------|------|
|
||||||
|
| 404 | Video not found(該 file_uuid 無影片)或 No face found for this trace(該 trace 無 face 資料) |
|
||||||
|
| 400 | Video width/height unavailable — 影片未記錄尺寸,無法 clamp,拒絕重切 |</p>
|
||||||
|
<hr />
|
||||||
|
<h2>行為說明</h2>
|
||||||
|
<ol>
|
||||||
|
<li>讀取該 trace 最高 confidence 的 frame + bbox(<strong>不</strong>重跑 blur 優化,取既有 best face 復原同一區域)</li>
|
||||||
|
<li>將 bbox clamp 到影片 width/height 內(<code>clamp_crop</code>)</li>
|
||||||
|
<li>ffmpeg 自影片以 decoded frame index 切出該 frame → crop face 區域</li>
|
||||||
|
<li>覆寫 <code>{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}/key_face.jpg</code></li>
|
||||||
|
<li>若 <code>.faces/{file_uuid}/{trace_id}/{frame}.jpg</code> 已存在則同步覆寫</li>
|
||||||
|
</ol>
|
||||||
|
<p><strong>不影響</strong>: Qdrant、<code>trace_profiles</code> DB、<code>tkg_nodes</code>、影片檔 — 僅重寫縮圖 cache。</p>
|
||||||
|
<hr />
|
||||||
|
<h2>Studio 整合步驟</h2>
|
||||||
|
<h3>1. apiCall (<code>src/api/index.ts</code>)</h3>
|
||||||
|
<p>新增 case:</p>
|
||||||
|
<div class="codehilite"><pre><span></span><code><span class="k">case</span><span class="w"> </span><span class="s1">'regenerate_trace_thumbnail'</span><span class="o">:</span><span class="w"> </span><span class="p">{</span>
|
||||||
|
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nx">url</span><span class="o">:</span><span class="w"> </span><span class="sb">`/api/v1/file/</span><span class="si">${</span><span class="nx">a</span><span class="p">.</span><span class="nx">fileUuid</span><span class="si">}</span><span class="sb">/trace/</span><span class="si">${</span><span class="nx">a</span><span class="p">.</span><span class="nx">traceId</span><span class="si">}</span><span class="sb">/regenerate-thumbnail`</span><span class="p">,</span><span class="w"> </span><span class="nx">method</span><span class="o">:</span><span class="w"> </span><span class="s1">'POST'</span><span class="w"> </span><span class="p">}</span>
|
||||||
|
<span class="p">}</span>
|
||||||
|
</code></pre></div>
|
||||||
|
|
||||||
|
<h3>2. Face detail modal 加「Re-gen」按鈕 (<code>src/views/PeopleView.vue</code>)</h3>
|
||||||
|
<p>於 <code>ms-face-detail-thumb</code> 附近加入按鈕,呼叫上方 apiCall,in-flight 時 disabled。</p>
|
||||||
|
<h3>3. 觸發後 refresh(重要)</h3>
|
||||||
|
<p>Face detail 縮圖顯示的是 <code>faceThumbsCache</code>(key = <code>${file_uuid}-${trace_id}</code>)。<code>loadTraceThumb</code> 對已有 cache 的 key 會直接 return,<strong>單獨 <code>bumpThumbCacheBust()</code> 無法刷新 face detail 縮圖</strong>。正確順序:</p>
|
||||||
|
<div class="codehilite"><pre><span></span><code><span class="k">await</span><span class="w"> </span><span class="nx">apiCall</span><span class="p">(</span><span class="s1">'regenerate_trace_thumbnail'</span><span class="p">,</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nx">fileUuid</span><span class="p">,</span><span class="w"> </span><span class="nx">traceId</span><span class="w"> </span><span class="p">})</span><span class="w"> </span><span class="c1">// 1. 呼叫 regenerate</span>
|
||||||
|
<span class="ow">delete</span><span class="w"> </span><span class="nx">faceThumbsCache</span><span class="p">.</span><span class="nx">value</span><span class="p">[</span><span class="sb">`</span><span class="si">${</span><span class="nx">fileUuid</span><span class="si">}</span><span class="sb">-</span><span class="si">${</span><span class="nx">traceId</span><span class="si">}</span><span class="sb">`</span><span class="p">]</span><span class="w"> </span><span class="c1">// 2. 清除該 key 的 blob cache</span>
|
||||||
|
<span class="nx">bumpThumbCacheBust</span><span class="p">()</span><span class="w"> </span><span class="c1">// 3. bump 版本(避 HTTP cache)</span>
|
||||||
|
<span class="nx">loadTraceThumb</span><span class="p">({</span><span class="w"> </span><span class="nx">file_uuid</span><span class="o">:</span><span class="w"> </span><span class="kt">fileUuid</span><span class="p">,</span><span class="w"> </span><span class="nx">trace_id</span><span class="o">:</span><span class="w"> </span><span class="kt">traceId</span><span class="w"> </span><span class="p">})</span><span class="w"> </span><span class="c1">// 4. 重新載入縮圖</span>
|
||||||
|
</code></pre></div>
|
||||||
|
|
||||||
|
<blockquote>
|
||||||
|
<p><code>candidateThumbs</code> 即 <code>faceThumbsCache</code> 的 alias(PeopleView.vue:722),delete 後無需額外處理。
|
||||||
|
若想一次清空全部縮圖可用 <code>clearFaceThumbs()</code>(較重,不建議單一 trace 場景)。</p>
|
||||||
|
</blockquote>
|
||||||
|
<hr />
|
||||||
|
<h2>測試指示</h2>
|
||||||
|
<div class="codehilite"><pre><span></span><code><span class="c1"># 使用已知越界案例(trace 355b 一類)驗證:</span>
|
||||||
|
<span class="c1"># 1) regenerate 前:GET thumbnail 顯示位移內容</span>
|
||||||
|
<span class="c1"># 2) 呼叫 regenerate → 回 success,含 clamp 後 bbox</span>
|
||||||
|
<span class="c1"># 3) 再次 GET thumbnail → 內容正確對齊 bbox</span>
|
||||||
|
curl<span class="w"> </span>-X<span class="w"> </span>POST<span class="w"> </span><span class="s2">"http://localhost:3002/api/v1/file/<FILE_UUID>/trace/<TRACE_ID>/regenerate-thumbnail"</span><span class="w"> </span><span class="se">\</span>
|
||||||
|
<span class="w"> </span>-H<span class="w"> </span><span class="s2">"X-API-Key: <KEY>"</span>
|
||||||
|
</code></pre></div>
|
||||||
|
|
||||||
|
<hr />
|
||||||
|
<h2>參考</h2>
|
||||||
|
<ul>
|
||||||
|
<li>根因 crop 修正:<code>src/core/thumbnail/validator.rs::clamp_crop</code>、<code>src/core/processor/tkg.rs</code></li>
|
||||||
|
<li>端點 handler:<code>src/api/trace_agent_api.rs::regenerate_trace_thumbnail</code></li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h2>版本歷史</h2>
|
||||||
|
<table class="table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>版本</th>
|
||||||
|
<th>日期</th>
|
||||||
|
<th>變更</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td>v1.0</td>
|
||||||
|
<td>2026-08-12</td>
|
||||||
|
<td>初版</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -65,6 +65,10 @@ pub fn trace_agent_routes() -> Router<crate::api::types::AppState> {
|
|||||||
"/api/v1/file/:file_uuid/trace/:trace_id/merge/:target_trace_id",
|
"/api/v1/file/:file_uuid/trace/:trace_id/merge/:target_trace_id",
|
||||||
post(merge_trace),
|
post(merge_trace),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/file/:file_uuid/trace/:trace_id/regenerate-thumbnail",
|
||||||
|
post(regenerate_trace_thumbnail),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
@@ -864,6 +868,192 @@ async fn get_trace_thumbnail_inner(
|
|||||||
.unwrap())
|
.unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Regenerate a trace's key_face.jpg by re-cropping the best-confidence face
|
||||||
|
// from the video with the bbox clamped to the frame dimensions. Fixes the
|
||||||
|
// "key frame OK, bbox OK, but key_face broken" case where an out-of-bounds
|
||||||
|
// bbox made ffmpeg silently shift the crop.
|
||||||
|
async fn regenerate_trace_thumbnail(
|
||||||
|
State(state): State<crate::api::types::AppState>,
|
||||||
|
Path((file_uuid, trace_id)): Path<(String, i32)>,
|
||||||
|
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||||
|
use serde_json::json;
|
||||||
|
let videos_table = crate::core::db::schema::table_name("videos");
|
||||||
|
|
||||||
|
// Query video info: path, dimensions, fps
|
||||||
|
let row: Option<(String, Option<i32>, Option<i32>, Option<f64>)> = sqlx::query_as(&format!(
|
||||||
|
"SELECT file_path, width, height, fps FROM {} WHERE file_uuid = $1",
|
||||||
|
videos_table
|
||||||
|
))
|
||||||
|
.bind(&file_uuid)
|
||||||
|
.fetch_optional(state.db.pool())
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Json(json!({"error": e.to_string()})),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let (video_path, video_width, video_height, fps) = row.ok_or_else(|| {
|
||||||
|
(
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
Json(json!({"error": "Video not found"})),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let video_width = video_width.ok_or_else(|| {
|
||||||
|
(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
Json(json!({"error": "Video width unavailable, cannot clamp crop"})),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let video_height = video_height.ok_or_else(|| {
|
||||||
|
(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
Json(json!({"error": "Video height unavailable, cannot clamp crop"})),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let fps = fps.unwrap_or(25.0);
|
||||||
|
|
||||||
|
// Scroll Qdrant _faces for this trace and pick the highest-confidence face.
|
||||||
|
// Unlike select_rep_face, no blur-optimization happens: we reuse the
|
||||||
|
// existing best-confidence frame + bbox to restore the same region.
|
||||||
|
use crate::core::db::qdrant_db::QdrantDb;
|
||||||
|
let qdrant = QdrantDb::new();
|
||||||
|
let trace_filter = json!({
|
||||||
|
"must": [
|
||||||
|
{"key": "file_uuid", "match": {"value": file_uuid}},
|
||||||
|
{"key": "trace_id", "match": {"value": trace_id}}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
let points = qdrant
|
||||||
|
.scroll_all_points("_faces", trace_filter, 1000)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let best = points
|
||||||
|
.iter()
|
||||||
|
.filter_map(|p| {
|
||||||
|
let payload = &p["payload"];
|
||||||
|
let bbox = &payload["bbox"];
|
||||||
|
let w = bbox["width"].as_f64()? as i32;
|
||||||
|
let h = bbox["height"].as_f64()? as i32;
|
||||||
|
let conf = payload["confidence"].as_f64()?;
|
||||||
|
Some((
|
||||||
|
payload["frame"].as_i64().unwrap_or(0),
|
||||||
|
bbox["x"].as_f64()? as i32,
|
||||||
|
bbox["y"].as_f64()? as i32,
|
||||||
|
w,
|
||||||
|
h,
|
||||||
|
conf,
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.max_by(|a, b| a.5.partial_cmp(&b.5).unwrap_or(std::cmp::Ordering::Equal));
|
||||||
|
|
||||||
|
let (best_frame, bx, by, bw, bh, _conf) = best.ok_or_else(|| {
|
||||||
|
(
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
Json(json!({"error": "No face found for this trace"})),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Clamp bbox to frame dimensions
|
||||||
|
let (cx, cy, cw, ch) =
|
||||||
|
crate::core::thumbnail::validator::clamp_crop(bx, by, bw, bh, video_width, video_height);
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
"[regenerate-thumbnail] trace {} frame {} bbox {}x{} at ({},{})",
|
||||||
|
trace_id,
|
||||||
|
best_frame,
|
||||||
|
cw,
|
||||||
|
ch,
|
||||||
|
cx,
|
||||||
|
cy
|
||||||
|
);
|
||||||
|
|
||||||
|
// Crop the face region from the video using decoded frame index (VFR-safe)
|
||||||
|
let tmp = std::env::temp_dir().join(format!("regen_trace_{}_{}.jpg", file_uuid, trace_id));
|
||||||
|
let select = format!("select=eq(n\\,{})", best_frame);
|
||||||
|
let status = tokio::process::Command::new("ffmpeg")
|
||||||
|
.args([
|
||||||
|
"-y",
|
||||||
|
"-i",
|
||||||
|
&video_path,
|
||||||
|
"-vf",
|
||||||
|
&format!("{},crop={}:{}:{}:{}", select, cw, ch, cx, cy),
|
||||||
|
"-frames:v",
|
||||||
|
"1",
|
||||||
|
"-q:v",
|
||||||
|
"2",
|
||||||
|
&tmp.to_string_lossy().to_string(),
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Json(json!({"error": e.to_string()})),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if !status.status.success() {
|
||||||
|
return Err((
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Json(json!({"error": "FFmpeg failed during regeneration"})),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let bytes = tokio::fs::read(&tmp).await.map_err(|e| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Json(json!({"error": e.to_string()})),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
crate::core::thumbnail::validator::validate_jpeg(&bytes).map_err(|e| {
|
||||||
|
tracing::warn!("[regenerate-thumbnail] JPEG validation failed: {}", e);
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Json(json!({"error": "Invalid JPEG output"})),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let _ = tokio::fs::remove_file(&tmp).await;
|
||||||
|
|
||||||
|
// Overwrite key_face.jpg in the trace profile directory
|
||||||
|
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||||
|
let profile_dir = std::path::PathBuf::from(output_dir)
|
||||||
|
.join(&file_uuid)
|
||||||
|
.join(format!("trace_{}", trace_id));
|
||||||
|
if let Err(e) = tokio::fs::create_dir_all(&profile_dir).await {
|
||||||
|
tracing::warn!("[regenerate-thumbnail] Failed to create trace dir: {}", e);
|
||||||
|
}
|
||||||
|
let _ = tokio::fs::write(profile_dir.join("key_face.jpg"), &bytes).await;
|
||||||
|
|
||||||
|
// Sync .faces cache if the cached crop file exists for the best frame
|
||||||
|
let trace_dir_name = if trace_id == 0 {
|
||||||
|
"unbound".to_string()
|
||||||
|
} else {
|
||||||
|
trace_id.to_string()
|
||||||
|
};
|
||||||
|
let faces_cached = std::path::PathBuf::from(output_dir)
|
||||||
|
.join(".faces")
|
||||||
|
.join(&file_uuid)
|
||||||
|
.join(trace_dir_name)
|
||||||
|
.join(format!("{}.jpg", best_frame));
|
||||||
|
if faces_cached.exists() {
|
||||||
|
let _ = tokio::fs::write(&faces_cached, &bytes).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Json(json!({
|
||||||
|
"success": true,
|
||||||
|
"file_uuid": file_uuid,
|
||||||
|
"trace_id": trace_id,
|
||||||
|
"frame": best_frame,
|
||||||
|
"bbox": {"x": cx, "y": cy, "width": cw, "height": ch},
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
struct CoOccurIdentity {
|
struct CoOccurIdentity {
|
||||||
identity_uuid: String,
|
identity_uuid: String,
|
||||||
|
|||||||
+49
-25
@@ -1245,6 +1245,19 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
.ok()
|
.ok()
|
||||||
.flatten();
|
.flatten();
|
||||||
|
|
||||||
|
// Get video frame dimensions for bbox clamping when cropping key_face
|
||||||
|
let video_dim: Option<(Option<i32>, Option<i32>)> = sqlx::query_as(&format!(
|
||||||
|
"SELECT width, height FROM {} WHERE file_uuid = $1",
|
||||||
|
crate::core::db::schema::table_name("videos")
|
||||||
|
))
|
||||||
|
.bind(file_uuid)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten();
|
||||||
|
let video_width = video_dim.and_then(|d| d.0).unwrap_or(0);
|
||||||
|
let video_height = video_dim.and_then(|d| d.1).unwrap_or(0);
|
||||||
|
|
||||||
// Get actual fps for timestamp calculation
|
// Get actual fps for timestamp calculation
|
||||||
let actual_fps: f64 = sqlx::query_scalar(&format!(
|
let actual_fps: f64 = sqlx::query_scalar(&format!(
|
||||||
"SELECT fps FROM {} WHERE file_uuid = $1",
|
"SELECT fps FROM {} WHERE file_uuid = $1",
|
||||||
@@ -1272,12 +1285,7 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
|
let key_frame_jpeg: Option<Vec<u8>> = video_path.as_ref().and_then(|vp| {
|
||||||
let select = format!("select=eq(n\\,{})", agg.best_frame);
|
let select = format!("select=eq(n\\,{})", agg.best_frame);
|
||||||
let output = std::process::Command::new("ffmpeg")
|
let output = std::process::Command::new("ffmpeg")
|
||||||
.args([
|
.args(["-y", "-v", "quiet", "-i"])
|
||||||
"-y",
|
|
||||||
"-v",
|
|
||||||
"quiet",
|
|
||||||
"-i",
|
|
||||||
])
|
|
||||||
.arg(vp)
|
.arg(vp)
|
||||||
.args([
|
.args([
|
||||||
"-vf",
|
"-vf",
|
||||||
@@ -1325,13 +1333,15 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let crop_filter = format!(
|
let (cx, cy, cw, ch) = crate::core::thumbnail::validator::clamp_crop(
|
||||||
"crop={}:{}:{}:{}",
|
bx as i32,
|
||||||
(bw as i64).max(1),
|
by as i32,
|
||||||
(bh as i64).max(1),
|
bw as i32,
|
||||||
(bx as i64).max(0),
|
bh as i32,
|
||||||
(by as i64).max(0),
|
video_width,
|
||||||
|
video_height,
|
||||||
);
|
);
|
||||||
|
let crop_filter = format!("crop={}:{}:{}:{}", cw, ch, cx, cy);
|
||||||
let mut cmd = std::process::Command::new("ffmpeg");
|
let mut cmd = std::process::Command::new("ffmpeg");
|
||||||
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
||||||
.args(["-frames:v", "1", "-q:v", "2", "-vf"])
|
.args(["-frames:v", "1", "-q:v", "2", "-vf"])
|
||||||
@@ -1410,13 +1420,7 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
// Retry key_frame extraction
|
// Retry key_frame extraction
|
||||||
if !kf_path.exists() {
|
if !kf_path.exists() {
|
||||||
if let Ok(output) = std::process::Command::new("ffmpeg")
|
if let Ok(output) = std::process::Command::new("ffmpeg")
|
||||||
.args([
|
.args(["-y", "-v", "quiet", "-i", vp])
|
||||||
"-y",
|
|
||||||
"-v",
|
|
||||||
"quiet",
|
|
||||||
"-i",
|
|
||||||
vp,
|
|
||||||
])
|
|
||||||
.args([
|
.args([
|
||||||
"-vf",
|
"-vf",
|
||||||
&select,
|
&select,
|
||||||
@@ -1464,13 +1468,15 @@ async fn build_face_track_nodes_from_qdrant(
|
|||||||
bh
|
bh
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
let crop_filter = format!(
|
let (cx, cy, cw, ch) = crate::core::thumbnail::validator::clamp_crop(
|
||||||
"crop={}:{}:{}:{}",
|
bx as i32,
|
||||||
(bw as i64).max(1),
|
by as i32,
|
||||||
(bh as i64).max(1),
|
bw as i32,
|
||||||
(bx as i64).max(0),
|
bh as i32,
|
||||||
(by as i64).max(0),
|
video_width,
|
||||||
|
video_height,
|
||||||
);
|
);
|
||||||
|
let crop_filter = format!("crop={}:{}:{}:{}", cw, ch, cx, cy);
|
||||||
if let Ok(kf_bytes) = std::fs::read(&kf_path) {
|
if let Ok(kf_bytes) = std::fs::read(&kf_path) {
|
||||||
let mut cmd = std::process::Command::new("ffmpeg");
|
let mut cmd = std::process::Command::new("ffmpeg");
|
||||||
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"])
|
||||||
@@ -3594,6 +3600,8 @@ mod tests {
|
|||||||
y: 100.0,
|
y: 100.0,
|
||||||
w: 50.0,
|
w: 50.0,
|
||||||
h: 50.0,
|
h: 50.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
trace_id: 1,
|
trace_id: 1,
|
||||||
@@ -3602,6 +3610,8 @@ mod tests {
|
|||||||
y: 200.0,
|
y: 200.0,
|
||||||
w: 50.0,
|
w: 50.0,
|
||||||
h: 50.0,
|
h: 50.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
trace_id: 2,
|
trace_id: 2,
|
||||||
@@ -3610,6 +3620,8 @@ mod tests {
|
|||||||
y: 150.0,
|
y: 150.0,
|
||||||
w: 50.0,
|
w: 50.0,
|
||||||
h: 50.0,
|
h: 50.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
trace_id: 1,
|
trace_id: 1,
|
||||||
@@ -3618,6 +3630,8 @@ mod tests {
|
|||||||
y: 120.0,
|
y: 120.0,
|
||||||
w: 50.0,
|
w: 50.0,
|
||||||
h: 50.0,
|
h: 50.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -3646,6 +3660,8 @@ mod tests {
|
|||||||
y: 100.0,
|
y: 100.0,
|
||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
trace_id: 2,
|
trace_id: 2,
|
||||||
@@ -3654,6 +3670,8 @@ mod tests {
|
|||||||
y: 300.0,
|
y: 300.0,
|
||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
let index = build_frame_index(&points);
|
let index = build_frame_index(&points);
|
||||||
@@ -3673,6 +3691,8 @@ mod tests {
|
|||||||
y: 100.0,
|
y: 100.0,
|
||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
},
|
},
|
||||||
FacePoint {
|
FacePoint {
|
||||||
trace_id: 2,
|
trace_id: 2,
|
||||||
@@ -3681,6 +3701,8 @@ mod tests {
|
|||||||
y: 500.0,
|
y: 500.0,
|
||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
let index = build_frame_index(&points);
|
let index = build_frame_index(&points);
|
||||||
@@ -3699,6 +3721,8 @@ mod tests {
|
|||||||
y: 100.0,
|
y: 100.0,
|
||||||
w: 100.0,
|
w: 100.0,
|
||||||
h: 100.0,
|
h: 100.0,
|
||||||
|
confidence: 0.9,
|
||||||
|
point_id: None,
|
||||||
}];
|
}];
|
||||||
let index = build_frame_index(&points);
|
let index = build_frame_index(&points);
|
||||||
|
|
||||||
|
|||||||
@@ -91,6 +91,31 @@ pub fn validate_crop(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clamp a crop rectangle so it fully fits inside the frame dimensions.
|
||||||
|
///
|
||||||
|
/// `x`/`y` are clamped into `[0, frame_size)`, and `w`/`h` are reduced so the
|
||||||
|
/// rectangle never extends past the frame boundary. The result always has
|
||||||
|
/// positive dimensions. Out-of-bounds bboxes that previously made ffmpeg
|
||||||
|
/// silently shift the crop (root cause of the "key frame OK, key face broken"
|
||||||
|
/// bug) now produce a correctly-aligned crop.
|
||||||
|
pub fn clamp_crop(
|
||||||
|
x: i32,
|
||||||
|
y: i32,
|
||||||
|
w: i32,
|
||||||
|
h: i32,
|
||||||
|
video_width: i32,
|
||||||
|
video_height: i32,
|
||||||
|
) -> (i32, i32, i32, i32) {
|
||||||
|
if video_width <= 0 || video_height <= 0 {
|
||||||
|
return (x.max(0), y.max(0), w.max(1), h.max(1));
|
||||||
|
}
|
||||||
|
let cx = x.clamp(0, video_width - 1);
|
||||||
|
let cy = y.clamp(0, video_height - 1);
|
||||||
|
let cw = w.clamp(1, (video_width - cx).max(1));
|
||||||
|
let ch = h.clamp(1, (video_height - cy).max(1));
|
||||||
|
(cx, cy, cw, ch)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -167,6 +192,45 @@ mod tests {
|
|||||||
assert!(validate_crop(100, -1, 200, 200, 1920, 1080).is_err());
|
assert!(validate_crop(100, -1, 200, 200, 1920, 1080).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_clamp_crop_in_bounds_unchanged() {
|
||||||
|
assert_eq!(
|
||||||
|
clamp_crop(100, 100, 200, 200, 1920, 1080),
|
||||||
|
(100, 100, 200, 200)
|
||||||
|
);
|
||||||
|
assert_eq!(clamp_crop(0, 0, 1920, 1080, 1920, 1080), (0, 0, 1920, 1080));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_clamp_crop_exceeds_right_bottom() {
|
||||||
|
// Regression for trace 355b: bbox 11px past the frame edge used to
|
||||||
|
// make ffmpeg silently shift the crop content.
|
||||||
|
assert_eq!(clamp_crop(65, 301, 70, 70, 1280, 360), (65, 301, 70, 59));
|
||||||
|
assert_eq!(
|
||||||
|
clamp_crop(1800, 900, 200, 200, 1920, 1080),
|
||||||
|
(1800, 900, 120, 180)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_clamp_crop_negative_origin() {
|
||||||
|
assert_eq!(clamp_crop(-10, -20, 200, 100, 1920, 1080), (0, 0, 200, 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_clamp_crop_fully_outside() {
|
||||||
|
assert_eq!(
|
||||||
|
clamp_crop(3000, 3000, 50, 50, 1920, 1080),
|
||||||
|
(1919, 1079, 1, 1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_clamp_crop_zero_frame_dimensions() {
|
||||||
|
// Unknown frame size: fall back to legacy max(0)/max(1) behavior.
|
||||||
|
assert_eq!(clamp_crop(-10, -20, 0, 0, 0, 0), (0, 0, 1, 1));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_is_valid_jpeg() {
|
fn test_is_valid_jpeg() {
|
||||||
let valid_jpeg = vec![
|
let valid_jpeg = vec![
|
||||||
|
|||||||
Reference in New Issue
Block a user