wip: additional processor improvements
- Update face clustering processor - Update TKG processor - Update Rust face cluster and trace storage - Add M4 workspace documentation Note: Work in progress, not yet tested
This commit is contained in:
@@ -692,6 +692,9 @@ fn main() {
|
||||
let mut person_face_count: BTreeMap<String, u64> = BTreeMap::new();
|
||||
let mut person_best_face: BTreeMap<String, Value> = BTreeMap::new();
|
||||
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
|
||||
let frame_num = frame_obj.get("frame")
|
||||
.and_then(|f| f.as_u64())
|
||||
.unwrap_or(frame_idx as u64);
|
||||
let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default();
|
||||
for (face_idx, face) in faces.iter().enumerate() {
|
||||
let person_id = face.get("person_id").and_then(|p| p.as_str());
|
||||
@@ -707,9 +710,9 @@ fn main() {
|
||||
});
|
||||
if confidence > entry.get("confidence").and_then(|c| c.as_f64()).unwrap_or(f64::NEG_INFINITY) {
|
||||
*entry = json!({
|
||||
"face_id": format!("face_{}_{}", frame_idx, face_idx),
|
||||
"face_id": format!("face_{}_{}", frame_num, face_idx),
|
||||
"confidence": confidence,
|
||||
"frame": frame_obj.get("frame").cloned().unwrap_or(json!(frame_idx)),
|
||||
"frame": frame_num,
|
||||
"bbox": {
|
||||
"x": face.get("x").cloned().unwrap_or(Value::Null),
|
||||
"y": face.get("y").cloned().unwrap_or(Value::Null),
|
||||
@@ -771,9 +774,12 @@ fn main() {
|
||||
// Build output frames.
|
||||
let mut output_frames: Vec<Value> = Vec::new();
|
||||
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
|
||||
let frame_num = frame_obj.get("frame")
|
||||
.and_then(|f| f.as_u64())
|
||||
.unwrap_or(frame_idx as u64);
|
||||
let timestamp = frame_obj.get("timestamp").cloned().unwrap_or_else(|| {
|
||||
if fps_value > 0.0 {
|
||||
json!(frame_obj.get("frame").and_then(|f| f.as_i64()).unwrap_or(frame_idx as i64) as f64 / fps_value)
|
||||
json!(frame_num as f64 / fps_value)
|
||||
} else {
|
||||
json!(0)
|
||||
}
|
||||
@@ -784,7 +790,7 @@ fn main() {
|
||||
let person_id = face.get("person_id").and_then(|p| p.as_str());
|
||||
if let Some(person_id) = person_id {
|
||||
output_faces.push(json!({
|
||||
"face_id": format!("face_{}_{}", frame_idx, face_idx),
|
||||
"face_id": format!("face_{}_{}", frame_num, face_idx),
|
||||
"cluster_id": person_id,
|
||||
"trace_id": face.get("trace_id").cloned().unwrap_or(Value::Null),
|
||||
"confidence": face.get("confidence").cloned().unwrap_or(json!(0.9)),
|
||||
@@ -793,7 +799,7 @@ fn main() {
|
||||
}
|
||||
if !output_faces.is_empty() {
|
||||
output_frames.push(json!({
|
||||
"frame": frame_obj.get("frame").cloned().unwrap_or(json!(frame_idx)),
|
||||
"frame": frame_num,
|
||||
"timestamp": timestamp,
|
||||
"faces": output_faces,
|
||||
}));
|
||||
|
||||
@@ -473,7 +473,7 @@ fn update_qdrant_trace_ids(
|
||||
// Load all points for this file
|
||||
let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url);
|
||||
let mut offset: Option<Value> = None;
|
||||
let mut updates: Vec<Value> = Vec::new();
|
||||
let mut trace_updates: HashMap<i32, Vec<Value>> = HashMap::new();
|
||||
|
||||
loop {
|
||||
let mut body = json!({
|
||||
@@ -513,10 +513,10 @@ fn update_qdrant_trace_ids(
|
||||
let key = (frame, x, y, width, height);
|
||||
if let Some(&trace_id) = trace_mapping.get(&key) {
|
||||
if let Some(id) = point_id {
|
||||
updates.push(json!({
|
||||
"id": id,
|
||||
"payload": {"trace_id": trace_id}
|
||||
}));
|
||||
trace_updates
|
||||
.entry(trace_id)
|
||||
.or_default()
|
||||
.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -538,16 +538,18 @@ fn update_qdrant_trace_ids(
|
||||
}
|
||||
}
|
||||
|
||||
if updates.is_empty() {
|
||||
if trace_updates.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Batch update points
|
||||
let update_url = format!("{}/collections/_faces/points", qdrant_url);
|
||||
let batch_size = 100;
|
||||
for chunk in updates.chunks(batch_size) {
|
||||
let update_url = format!("{}/collections/_faces/points/payload", qdrant_url);
|
||||
|
||||
for (trace_id, point_ids) in trace_updates {
|
||||
let body = json!({
|
||||
"points": chunk
|
||||
"payload": {
|
||||
"trace_id": trace_id
|
||||
},
|
||||
"points": point_ids
|
||||
});
|
||||
|
||||
let resp = ureq::post(&update_url)
|
||||
@@ -556,7 +558,9 @@ fn update_qdrant_trace_ids(
|
||||
.send_json(body);
|
||||
|
||||
if let Err(e) = resp {
|
||||
eprintln!("[TRACE] Failed to update Qdrant: {}", e);
|
||||
eprintln!("[TRACE] Failed to update Qdrant trace_id {} for {} points: {}", trace_id, point_ids.len(), e);
|
||||
} else {
|
||||
println!("[TRACE] Updated trace_id {} for {} points", trace_id, point_ids.len());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,512 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const DEFAULT_QDRANT_URL: &str = "http://localhost:6333";
|
||||
const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200";
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rust_store_traced_faces", about = "Store Traced Faces (Rust)")]
|
||||
struct Args {
|
||||
/// File UUID
|
||||
file_uuid: String,
|
||||
/// Face JSON path (optional)
|
||||
#[arg(long)]
|
||||
face_json: Option<PathBuf>,
|
||||
/// Output directory
|
||||
#[arg(long, default_value = "/Users/accusys/momentry/output")]
|
||||
output_dir: PathBuf,
|
||||
/// Minimum trace length
|
||||
#[arg(long, default_value = "0")]
|
||||
min_trace_len: usize,
|
||||
/// Minimum average confidence
|
||||
#[arg(long, default_value = "0.0")]
|
||||
min_confidence: f32,
|
||||
/// Similarity threshold for face matching
|
||||
#[arg(long, default_value = "0.85")]
|
||||
similarity_threshold: f64,
|
||||
/// Distance threshold (pixels)
|
||||
#[arg(long, default_value = "100.0")]
|
||||
distance_threshold: f64,
|
||||
}
|
||||
|
||||
fn env_var(name: &str, default: &str) -> String {
|
||||
std::env::var(name).unwrap_or_else(|_| default.to_string())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FacePoint {
|
||||
payload: Value,
|
||||
vector: Vec<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct FaceDetection {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
trace_id: Option<i32>,
|
||||
confidence: f32,
|
||||
bbox: BBox,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
embedding: Option<Vec<f32>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pose: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
landmarks: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
lips: Option<serde_json::Value>,
|
||||
#[serde(rename = "captureQuality", skip_serializing_if = "Option::is_none")]
|
||||
capture_quality: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct BBox {
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct FaceFrame {
|
||||
frame: i64,
|
||||
timestamp: f64,
|
||||
faces: Vec<FaceDetection>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct TraceInfo {
|
||||
trace_id: i32,
|
||||
total_appearances: usize,
|
||||
avg_confidence: f32,
|
||||
path: Vec<TracePoint>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct TracePoint {
|
||||
frame: i64,
|
||||
bbox: BBox,
|
||||
confidence: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct FaceData {
|
||||
fps: f64,
|
||||
frame_count: i64,
|
||||
frames: Vec<FaceFrame>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct FaceTracedData {
|
||||
fps: f64,
|
||||
frames: Vec<FaceFrame>,
|
||||
traces: HashMap<String, TraceInfo>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
println!("[TRACE_STORE] Processing file: {}", args.file_uuid);
|
||||
|
||||
// Determine input path
|
||||
let face_json_path = args.face_json.unwrap_or_else(|| {
|
||||
args.output_dir.join(format!("{}.face.json", args.file_uuid))
|
||||
});
|
||||
|
||||
println!("[TRACE_STORE] Reading face.json from: {:?}", face_json_path);
|
||||
|
||||
// Read face.json
|
||||
let face_json_str = std::fs::read_to_string(&face_json_path)
|
||||
.with_context(|| format!("Failed to read {:?}", face_json_path))?;
|
||||
|
||||
let mut face_data: FaceData = serde_json::from_str(&face_json_str)
|
||||
.with_context(|| "Failed to parse face.json")?;
|
||||
|
||||
println!("[TRACE_STORE] Frames: {}", face_data.frames.len());
|
||||
|
||||
// Run face tracking
|
||||
println!("[TRACE_STORE] Loading embeddings from Qdrant...");
|
||||
let qdrant_faces = load_qdrant_faces(&args.file_uuid);
|
||||
|
||||
println!("[TRACE_STORE] Running face tracking with embedding similarity (threshold={})...", args.similarity_threshold);
|
||||
let traces = run_face_tracking(
|
||||
&mut face_data,
|
||||
&qdrant_faces,
|
||||
args.min_trace_len,
|
||||
args.min_confidence,
|
||||
args.similarity_threshold,
|
||||
args.distance_threshold,
|
||||
)?;
|
||||
|
||||
println!("[TRACE_STORE] Traces: {}", traces.len());
|
||||
|
||||
// Create output
|
||||
let traced_data = FaceTracedData {
|
||||
fps: face_data.fps,
|
||||
frames: face_data.frames,
|
||||
traces,
|
||||
};
|
||||
|
||||
// Write face_traced.json
|
||||
let traced_json_path = args.output_dir.join(format!("{}.face_traced.json", args.file_uuid));
|
||||
println!("[TRACE_STORE] Writing face_traced.json to: {:?}", traced_json_path);
|
||||
|
||||
let traced_json_str = serde_json::to_string_pretty(&traced_data)
|
||||
.with_context(|| "Failed to serialize face_traced.json")?;
|
||||
|
||||
std::fs::write(&traced_json_path, traced_json_str)
|
||||
.with_context(|| format!("Failed to write {:?}", traced_json_path))?;
|
||||
|
||||
println!("[TRACE_STORE] Done");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_face_tracking(
|
||||
face_data: &mut FaceData,
|
||||
qdrant_faces: &[FacePoint],
|
||||
min_trace_len: usize,
|
||||
min_confidence: f32,
|
||||
similarity_threshold: f64,
|
||||
distance_threshold: f64,
|
||||
) -> Result<HashMap<String, TraceInfo>> {
|
||||
let mut traces: HashMap<String, TraceInfo> = HashMap::new();
|
||||
let mut next_trace_id = 1;
|
||||
|
||||
// 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 {
|
||||
let frame = point.payload.get("frame")
|
||||
.and_then(|f| f.as_i64())
|
||||
.unwrap_or(0);
|
||||
let confidence = point.payload.get("confidence")
|
||||
.and_then(|c| c.as_f64())
|
||||
.unwrap_or(0.9) as f32;
|
||||
let bbox = point.payload.get("bbox");
|
||||
let bbox_struct = if let Some(bbox_obj) = bbox {
|
||||
BBox {
|
||||
x: bbox_obj.get("x").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
|
||||
y: bbox_obj.get("y").and_then(|y| y.as_i64()).unwrap_or(0) as i32,
|
||||
width: bbox_obj.get("width").and_then(|w| w.as_i64()).unwrap_or(0) as i32,
|
||||
height: bbox_obj.get("height").and_then(|h| h.as_i64()).unwrap_or(0) as i32,
|
||||
}
|
||||
} else {
|
||||
BBox { x: 0, y: 0, width: 0, height: 0 }
|
||||
};
|
||||
|
||||
frame_embeddings
|
||||
.entry(frame)
|
||||
.or_insert_with(Vec::new)
|
||||
.push((point.vector.clone(), confidence, bbox_struct));
|
||||
}
|
||||
|
||||
eprintln!("[TRACE] Built embedding map for {} frames", frame_embeddings.len());
|
||||
|
||||
// Face matching with embedding similarity
|
||||
let mut face_trace_ids: HashMap<(i64, usize), i32> = HashMap::new(); // (frame, face_idx) -> trace_id
|
||||
|
||||
let frames_len = face_data.frames.len();
|
||||
|
||||
for frame_idx in 0..frames_len {
|
||||
let frame = &face_data.frames[frame_idx];
|
||||
let current_frame_num = frame.frame;
|
||||
|
||||
// Get embeddings for current frame
|
||||
let current_embeddings = frame_embeddings.get(¤t_frame_num).cloned().unwrap_or_default();
|
||||
|
||||
for face_idx in 0..frame.faces.len() {
|
||||
let current_face = &frame.faces[face_idx];
|
||||
|
||||
// Find matching embedding
|
||||
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
|
||||
})
|
||||
.map(|(emb, _, _)| emb.clone());
|
||||
|
||||
let mut best_match: Option<(i32, f64, f64)> = None; // (trace_id, distance, similarity)
|
||||
let mut best_distance = f64::MAX;
|
||||
let mut best_similarity = 0.0;
|
||||
|
||||
if frame_idx > 0 {
|
||||
let prev_frame = &face_data.frames[frame_idx - 1];
|
||||
|
||||
// Check previous frame or frame - 3
|
||||
if prev_frame.frame == current_frame_num - 3 || prev_frame.frame == current_frame_num - 1 {
|
||||
for (prev_face_idx, prev_face) in prev_frame.faces.iter().enumerate() {
|
||||
if let Some(&prev_trace_id) = face_trace_ids.get(&(prev_frame.frame, prev_face_idx)) {
|
||||
let distance = calculate_bbox_distance(
|
||||
¤t_face.bbox,
|
||||
&prev_face.bbox,
|
||||
);
|
||||
|
||||
// Get previous embedding
|
||||
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
|
||||
})
|
||||
.map(|(emb, _, _)| emb);
|
||||
|
||||
// Calculate similarity if both embeddings exist
|
||||
let similarity = match (¤t_embedding, &prev_embedding) {
|
||||
(Some(curr), Some(prev)) => calculate_cosine_similarity(curr, prev),
|
||||
_ => 0.0,
|
||||
};
|
||||
|
||||
// Match if distance AND similarity meet thresholds
|
||||
if distance < best_distance
|
||||
&& distance < distance_threshold
|
||||
&& similarity > similarity_threshold {
|
||||
best_distance = distance;
|
||||
best_similarity = similarity;
|
||||
best_match = Some((prev_trace_id, distance, similarity));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let trace_id = if let Some((matched_trace_id, _, _)) = best_match {
|
||||
matched_trace_id
|
||||
} else {
|
||||
let tid = next_trace_id;
|
||||
next_trace_id += 1;
|
||||
tid
|
||||
};
|
||||
|
||||
face_trace_ids.insert((current_frame_num, face_idx), trace_id);
|
||||
|
||||
let trace_key = trace_id.to_string();
|
||||
let trace = traces.entry(trace_key).or_insert(TraceInfo {
|
||||
trace_id,
|
||||
total_appearances: 0,
|
||||
avg_confidence: 0.0,
|
||||
path: Vec::new(),
|
||||
});
|
||||
|
||||
trace.total_appearances += 1;
|
||||
trace.path.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
bbox: current_face.bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Assign trace_ids to faces
|
||||
for frame in &mut face_data.frames {
|
||||
for (face_idx, face) in frame.faces.iter_mut().enumerate() {
|
||||
if let Some(&trace_id) = face_trace_ids.get(&(frame.frame, face_idx)) {
|
||||
face.trace_id = Some(trace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate average confidence for each trace
|
||||
for trace in traces.values_mut() {
|
||||
if !trace.path.is_empty() {
|
||||
let sum: f32 = trace.path.iter().map(|p| p.confidence).sum();
|
||||
trace.avg_confidence = sum / trace.path.len() as f32;
|
||||
}
|
||||
}
|
||||
|
||||
// Filter traces by min_trace_len and min_confidence
|
||||
if min_trace_len > 0 || min_confidence > 0.0 {
|
||||
traces.retain(|_, trace| {
|
||||
trace.total_appearances >= min_trace_len
|
||||
&& (min_confidence == 0.0 || trace.avg_confidence >= min_confidence)
|
||||
});
|
||||
}
|
||||
|
||||
Ok(traces)
|
||||
}
|
||||
|
||||
let frames_len = face_data.frames.len();
|
||||
|
||||
for frame_idx in 0..frames_len {
|
||||
let frame = &face_data.frames[frame_idx];
|
||||
let current_frame_num = frame.frame;
|
||||
let current_faces = frame.faces.clone();
|
||||
|
||||
let mut face_trace_ids = Vec::new();
|
||||
|
||||
for face_idx in 0..current_faces.len() {
|
||||
let current_face = ¤t_faces[face_idx];
|
||||
|
||||
let mut best_match: Option<(i32, f64)> = None;
|
||||
let mut best_distance = f64::MAX;
|
||||
|
||||
if frame_idx > 0 {
|
||||
let prev_frame = &face_data.frames[frame_idx - 1];
|
||||
|
||||
if prev_frame.frame == current_frame_num - 3 || prev_frame.frame == current_frame_num - 1 {
|
||||
for prev_face in &prev_frame.faces {
|
||||
if let Some(prev_trace_id) = prev_face.trace_id {
|
||||
let distance = calculate_bbox_distance(
|
||||
¤t_face.bbox,
|
||||
&prev_face.bbox,
|
||||
);
|
||||
|
||||
if distance < best_distance && distance < distance_threshold {
|
||||
best_distance = distance;
|
||||
best_match = Some((prev_trace_id, distance));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let trace_id = if let Some((matched_trace_id, _distance)) = best_match {
|
||||
matched_trace_id
|
||||
} else {
|
||||
let tid = next_trace_id;
|
||||
next_trace_id += 1;
|
||||
tid
|
||||
};
|
||||
|
||||
face_trace_ids.push(trace_id);
|
||||
|
||||
let trace_key = trace_id.to_string();
|
||||
let trace = traces.entry(trace_key).or_insert(TraceInfo {
|
||||
trace_id,
|
||||
total_appearances: 0,
|
||||
avg_confidence: 0.0,
|
||||
path: Vec::new(),
|
||||
});
|
||||
|
||||
trace.total_appearances += 1;
|
||||
trace.path.push(TracePoint {
|
||||
frame: current_frame_num,
|
||||
bbox: current_face.bbox.clone(),
|
||||
confidence: current_face.confidence,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Assign trace_ids to faces
|
||||
for frame in &mut face_data.frames {
|
||||
for (face_idx, face) in frame.faces.iter_mut().enumerate() {
|
||||
if let Some(&trace_id) = face_trace_ids.get(&(frame.frame, face_idx)) {
|
||||
face.trace_id = Some(trace_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for trace in traces.values_mut() {
|
||||
if !trace.path.is_empty() {
|
||||
let sum: f32 = trace.path.iter().map(|p| p.confidence).sum();
|
||||
trace.avg_confidence = sum / trace.path.len() as f32;
|
||||
}
|
||||
}
|
||||
|
||||
if min_trace_len > 0 || min_confidence > 0.0 {
|
||||
traces.retain(|_, trace| {
|
||||
trace.total_appearances >= min_trace_len
|
||||
&& (min_confidence == 0.0 || trace.avg_confidence >= min_confidence)
|
||||
});
|
||||
}
|
||||
|
||||
Ok(traces)
|
||||
}
|
||||
|
||||
fn calculate_bbox_distance(bbox1: &BBox, bbox2: &BBox) -> f64 {
|
||||
let cx1 = bbox1.x as f64 + bbox1.width as f64 / 2.0;
|
||||
let cy1 = bbox1.y as f64 + bbox1.height as f64 / 2.0;
|
||||
let cx2 = bbox2.x as f64 + bbox2.width as f64 / 2.0;
|
||||
let cy2 = bbox2.y as f64 + bbox2.height as f64 / 2.0;
|
||||
|
||||
((cx1 - cx2).powi(2) + (cy1 - cy2).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
fn calculate_cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
|
||||
if a.len() != b.len() || a.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let dot: f64 = a.iter().zip(b).map(|(x, y)| x * y).sum();
|
||||
let na: f64 = a.iter().map(|x| x * x).sum::<f64>().sqrt();
|
||||
let nb: f64 = b.iter().map(|x| x * x).sum::<f64>().sqrt();
|
||||
if na == 0.0 || nb == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
dot / (na * nb)
|
||||
}
|
||||
}
|
||||
|
||||
/// Scroll all Qdrant `_faces` points (payload + vector) for a file via HTTP.
|
||||
fn load_qdrant_faces(uuid: &str) -> Vec<FacePoint> {
|
||||
let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL);
|
||||
let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY);
|
||||
let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url);
|
||||
|
||||
let mut all_points: Vec<FacePoint> = Vec::new();
|
||||
let mut offset: Option<Value> = None;
|
||||
|
||||
loop {
|
||||
let mut body = json!({
|
||||
"limit": 10000,
|
||||
"with_payload": true,
|
||||
"with_vector": true,
|
||||
"filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]},
|
||||
});
|
||||
if let Some(ref off) = offset {
|
||||
body["offset"] = off.clone();
|
||||
}
|
||||
|
||||
let resp = ureq::post(&scroll_url)
|
||||
.set("api-key", &qdrant_api_key)
|
||||
.timeout(Duration::from_secs(60))
|
||||
.send_json(body);
|
||||
|
||||
match resp {
|
||||
Ok(r) => {
|
||||
let data: Value = r.into_json().unwrap_or(Value::Null);
|
||||
let points = data
|
||||
.pointer("/result/points")
|
||||
.and_then(|p| p.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
for p in points {
|
||||
let payload = p.get("payload").cloned().unwrap_or(Value::Null);
|
||||
let vector = p
|
||||
.get("vector")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|v| {
|
||||
v.iter()
|
||||
.filter_map(|x| x.as_f64())
|
||||
.collect::<Vec<f64>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
all_points.push(FacePoint { payload, vector });
|
||||
}
|
||||
|
||||
let next = data.pointer("/result/next_page_offset").cloned();
|
||||
match next {
|
||||
Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)),
|
||||
Some(Value::Number(_)) => break,
|
||||
Some(Value::Null) | None => break,
|
||||
other => {
|
||||
offset = other;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[TRACE] Qdrant scroll error: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("[TRACE] Loaded {} points from Qdrant _faces", all_points.len());
|
||||
all_points
|
||||
}
|
||||
Reference in New Issue
Block a user