feat: integrate embeddings storage to Face processor
- Create store_face_embeddings_to_qdrant.py script - Add automatic Qdrant storage call after FaceNet completes - Store 512D embeddings with metadata (frame, confidence, bbox) - Enables downstream face tracing and clustering This ensures embeddings are automatically stored in Qdrant without manual intervention.
This commit is contained in:
Executable
+134
@@ -0,0 +1,134 @@
|
|||||||
|
#!/opt/homebrew/bin/python3.11
|
||||||
|
"""
|
||||||
|
將 face.json 中的 embeddings 存入 Qdrant _faces collection
|
||||||
|
|
||||||
|
這個腳本應該在 Face 處理器完成後調用,將生成的 embeddings 存入 Qdrant,
|
||||||
|
供後續的 face tracing 和 clustering 使用。
|
||||||
|
|
||||||
|
使用方式:
|
||||||
|
python store_face_embeddings_to_qdrant.py --file-uuid <uuid>
|
||||||
|
|
||||||
|
流程:
|
||||||
|
1. 從 face.json 讀取 embeddings
|
||||||
|
2. 準備 Qdrant points(包含 metadata)
|
||||||
|
3. 刪除舊的 points(如果存在)
|
||||||
|
4. 插入新的 points
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import uuid as uuid_lib
|
||||||
|
import requests
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description='Store face embeddings to Qdrant')
|
||||||
|
parser.add_argument('--file-uuid', required=True, help='Video file UUID')
|
||||||
|
parser.add_argument('--face-json', help='Path to face.json (default: <output_dir>/<uuid>.face.json)')
|
||||||
|
parser.add_argument('--batch-size', type=int, default=100, help='Batch size for Qdrant upsert')
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
file_uuid = args.file_uuid
|
||||||
|
output_dir = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
|
||||||
|
qdrant_url = os.environ.get("QDRANT_URL", "http://127.0.0.1:6333")
|
||||||
|
qdrant_api_key = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
|
||||||
|
|
||||||
|
face_json_path = args.face_json or f"{output_dir}/{file_uuid}.face.json"
|
||||||
|
|
||||||
|
if not os.path.exists(face_json_path):
|
||||||
|
print(f"[ERROR] face.json not found: {face_json_path}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"[STORE] Loading face data from {face_json_path}...")
|
||||||
|
with open(face_json_path) as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
# 準備 points
|
||||||
|
points = []
|
||||||
|
frames = data.get("frames", [])
|
||||||
|
fps = data.get("fps", 24.0)
|
||||||
|
|
||||||
|
for frame_data in frames:
|
||||||
|
frame_num = frame_data.get("frame", 0)
|
||||||
|
timestamp = frame_num / fps
|
||||||
|
faces = frame_data.get("faces", [])
|
||||||
|
|
||||||
|
for face in faces:
|
||||||
|
embedding = face.get("embedding")
|
||||||
|
if not embedding:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 生成唯一的 point ID
|
||||||
|
point_id = str(uuid_lib.uuid4())
|
||||||
|
|
||||||
|
# 構建 payload
|
||||||
|
payload = {
|
||||||
|
"file_uuid": file_uuid,
|
||||||
|
"frame": frame_num,
|
||||||
|
"timestamp_secs": timestamp,
|
||||||
|
"face_id": face.get("face_id", ""),
|
||||||
|
"confidence": face.get("confidence", 0.0),
|
||||||
|
"x": face.get("x", 0),
|
||||||
|
"y": face.get("y", 0),
|
||||||
|
"width": face.get("width", 0),
|
||||||
|
"height": face.get("height", 0),
|
||||||
|
"trace_id": -1, # 初始值,稍後由 face tracing 更新
|
||||||
|
}
|
||||||
|
|
||||||
|
points.append({
|
||||||
|
"id": point_id,
|
||||||
|
"vector": embedding,
|
||||||
|
"payload": payload
|
||||||
|
})
|
||||||
|
|
||||||
|
print(f"[STORE] Prepared {len(points)} points")
|
||||||
|
|
||||||
|
if len(points) == 0:
|
||||||
|
print(f"[STORE] No embeddings found, skipping Qdrant storage")
|
||||||
|
return
|
||||||
|
|
||||||
|
headers = {"api-key": qdrant_api_key, "Content-Type": "application/json"}
|
||||||
|
|
||||||
|
# 刪除舊的 points
|
||||||
|
print(f"[STORE] Deleting old points for {file_uuid}...")
|
||||||
|
response = requests.post(
|
||||||
|
f"{qdrant_url}/collections/_faces/points/delete",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"filter": {
|
||||||
|
"must": [
|
||||||
|
{"key": "file_uuid", "match": {"value": file_uuid}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.status_code != 200:
|
||||||
|
print(f"[WARN] Delete failed: {response.status_code}")
|
||||||
|
else:
|
||||||
|
print(f"[STORE] Old points deleted")
|
||||||
|
|
||||||
|
# 插入新的 points(分批)
|
||||||
|
batch_size = args.batch_size
|
||||||
|
for i in range(0, len(points), batch_size):
|
||||||
|
batch = points[i:i+batch_size]
|
||||||
|
batch_num = i//batch_size + 1
|
||||||
|
total_batches = (len(points)-1)//batch_size + 1
|
||||||
|
|
||||||
|
print(f"[STORE] Inserting batch {batch_num}/{total_batches}...")
|
||||||
|
response = requests.put(
|
||||||
|
f"{qdrant_url}/collections/_faces/points",
|
||||||
|
headers=headers,
|
||||||
|
json={"points": batch}
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.status_code != 200:
|
||||||
|
print(f"[ERROR] Batch insert failed: {response.status_code}")
|
||||||
|
print(response.text)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"[STORE] ✅ Done: {len(points)} embeddings stored in Qdrant")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -199,6 +199,37 @@ pub async fn process_face(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Store embeddings to Qdrant after FaceNet completes
|
||||||
|
if let Some(file_uuid) = uuid {
|
||||||
|
tracing::info!("[FACE] Storing embeddings to Qdrant for {}", file_uuid);
|
||||||
|
let store_script = std::path::Path::new("/Users/accusys/momentry_core/scripts/store_face_embeddings_to_qdrant.py");
|
||||||
|
if store_script.exists() {
|
||||||
|
let store_output = tokio::process::Command::new("python3")
|
||||||
|
.arg(store_script)
|
||||||
|
.arg("--file-uuid")
|
||||||
|
.arg(file_uuid)
|
||||||
|
.output()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match store_output {
|
||||||
|
Ok(output) if output.status.success() => {
|
||||||
|
tracing::info!("[FACE] Embeddings stored to Qdrant successfully");
|
||||||
|
}
|
||||||
|
Ok(output) => {
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
tracing::warn!("[FACE] Embedding storage failed: {}", stderr);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("[FACE] Embedding storage error: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tracing::warn!("[FACE] store_face_embeddings_to_qdrant.py not found");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tracing::warn!("[FACE] No UUID provided, skipping Qdrant storage");
|
||||||
|
}
|
||||||
|
|
||||||
let json_str = std::fs::read_to_string(output_path).context("Failed to read FACE output")?;
|
let json_str = std::fs::read_to_string(output_path).context("Failed to read FACE output")?;
|
||||||
let mut result: FaceResult = serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
let mut result: FaceResult = serde_json::from_str(&json_str).context("Failed to parse FACE output")?;
|
||||||
result.compute_status();
|
result.compute_status();
|
||||||
|
|||||||
Reference in New Issue
Block a user