feat: Phase 2.6 edges migration to Qdrant (TKG-only architecture)
Phase 2.6.1: co_occurrence_edges migration - build_co_occurrence_edges_from_qdrant() - Qdrant embeddings → frame grouping → YOLO objects - Result: 6679 edges (vs 6701 PostgreSQL) Phase 2.6.2: face_face_edges migration - build_face_face_edges_from_qdrant() - Qdrant embeddings → frame grouping → face pairs - mutual_gaze detection preserved - Result: 6 edges (exact match) Phase 2.6.3: speaker_face_edges migration - build_speaker_face_edges_from_qdrant() - Qdrant embeddings → trace_id frame ranges - SPEAKS_AS edge creation Architecture: - All edges use Qdrant payload (no face_detections queries) - PostgreSQL fallback for empty Qdrant - Estimated 3.6x performance improvement Testing: - Playground (3003): ✓ All Phase 2.6 logs verified - Edge counts: ✓ Close match with PostgreSQL - Fallback: ✓ Working Docs: - docs_v1.0/DESIGN/TKG_PHASE2_6_EDGES_MIGRATION.md - docs_v1.0/M4_workspace/2026-06-21_phase2_6_test.md
This commit is contained in:
+51
-15
@@ -194,6 +194,9 @@ pub enum VideoStatus {
|
||||
Registered,
|
||||
Pending,
|
||||
Processing,
|
||||
Processed,
|
||||
Indexed,
|
||||
CheckedOut,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
@@ -205,6 +208,9 @@ impl VideoStatus {
|
||||
VideoStatus::Registered => "registered",
|
||||
VideoStatus::Pending => "pending",
|
||||
VideoStatus::Processing => "processing",
|
||||
VideoStatus::Processed => "processed",
|
||||
VideoStatus::Indexed => "indexed",
|
||||
VideoStatus::CheckedOut => "checked_out",
|
||||
VideoStatus::Completed => "completed",
|
||||
VideoStatus::Failed => "failed",
|
||||
}
|
||||
@@ -216,6 +222,9 @@ impl VideoStatus {
|
||||
"registered" => Some(VideoStatus::Registered),
|
||||
"pending" => Some(VideoStatus::Pending),
|
||||
"processing" => Some(VideoStatus::Processing),
|
||||
"processed" => Some(VideoStatus::Processed),
|
||||
"indexed" => Some(VideoStatus::Indexed),
|
||||
"checked_out" => Some(VideoStatus::CheckedOut),
|
||||
"completed" => Some(VideoStatus::Completed),
|
||||
"failed" => Some(VideoStatus::Failed),
|
||||
_ => None,
|
||||
@@ -427,6 +436,7 @@ pub enum PipelineType {
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProcessorType {
|
||||
Cut,
|
||||
Asr,
|
||||
Yolo,
|
||||
Ocr,
|
||||
Face,
|
||||
@@ -435,6 +445,8 @@ pub enum ProcessorType {
|
||||
Scene,
|
||||
Story,
|
||||
FiveW1H,
|
||||
Appearance,
|
||||
MediaPipe,
|
||||
}
|
||||
|
||||
impl sqlx::Type<sqlx::Postgres> for ProcessorType {
|
||||
@@ -462,6 +474,7 @@ impl ProcessorType {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
ProcessorType::Cut => "cut",
|
||||
ProcessorType::Asr => "asr",
|
||||
ProcessorType::Yolo => "yolo",
|
||||
ProcessorType::Ocr => "ocr",
|
||||
ProcessorType::Face => "face",
|
||||
@@ -470,12 +483,15 @@ impl ProcessorType {
|
||||
ProcessorType::Scene => "scene",
|
||||
ProcessorType::Story => "story",
|
||||
ProcessorType::FiveW1H => "5w1h",
|
||||
ProcessorType::Appearance => "appearance",
|
||||
ProcessorType::MediaPipe => "mediapipe",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_db_str(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"cut" => Some(ProcessorType::Cut),
|
||||
"asr" => Some(ProcessorType::Asr),
|
||||
"yolo" => Some(ProcessorType::Yolo),
|
||||
"ocr" => Some(ProcessorType::Ocr),
|
||||
"face" => Some(ProcessorType::Face),
|
||||
@@ -484,6 +500,8 @@ impl ProcessorType {
|
||||
"scene" => Some(ProcessorType::Scene),
|
||||
"story" => Some(ProcessorType::Story),
|
||||
"5w1h" => Some(ProcessorType::FiveW1H),
|
||||
"appearance" => Some(ProcessorType::Appearance),
|
||||
"mediapipe" => Some(ProcessorType::MediaPipe),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -491,6 +509,7 @@ impl ProcessorType {
|
||||
pub fn estimated_cpu(&self) -> f64 {
|
||||
match self {
|
||||
ProcessorType::Cut => 0.5,
|
||||
ProcessorType::Asr => 0.5,
|
||||
ProcessorType::Yolo => 0.3,
|
||||
ProcessorType::Ocr => 0.8,
|
||||
ProcessorType::Face => 0.6,
|
||||
@@ -499,12 +518,15 @@ impl ProcessorType {
|
||||
ProcessorType::Scene => 0.3,
|
||||
ProcessorType::Story => 0.1,
|
||||
ProcessorType::FiveW1H => 0.1,
|
||||
ProcessorType::Appearance => 0.3,
|
||||
ProcessorType::MediaPipe => 0.3,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn uses_gpu(&self) -> bool {
|
||||
match self {
|
||||
ProcessorType::Yolo | ProcessorType::Face | ProcessorType::Pose => true,
|
||||
ProcessorType::MediaPipe => false,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -512,6 +534,7 @@ impl ProcessorType {
|
||||
pub fn estimated_memory_mb(&self) -> u64 {
|
||||
match self {
|
||||
ProcessorType::Cut => 512,
|
||||
ProcessorType::Asr => 1024,
|
||||
ProcessorType::Yolo => 1024,
|
||||
ProcessorType::Ocr => 1024,
|
||||
ProcessorType::Face => 1536,
|
||||
@@ -520,12 +543,15 @@ impl ProcessorType {
|
||||
ProcessorType::Scene => 512,
|
||||
ProcessorType::Story => 256,
|
||||
ProcessorType::FiveW1H => 256,
|
||||
ProcessorType::Appearance => 512,
|
||||
ProcessorType::MediaPipe => 1024,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn model_name(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
ProcessorType::Cut => None,
|
||||
ProcessorType::Asr => Some("whisper-small"),
|
||||
ProcessorType::Yolo => Some("yolov8n"),
|
||||
ProcessorType::Ocr => Some("paddleocr"),
|
||||
ProcessorType::Face => Some("insightface/buffalo_l"),
|
||||
@@ -534,12 +560,14 @@ impl ProcessorType {
|
||||
ProcessorType::Scene => Some("places365"),
|
||||
ProcessorType::Story => None,
|
||||
ProcessorType::FiveW1H => Some("gemma4"),
|
||||
ProcessorType::Appearance => None,
|
||||
ProcessorType::MediaPipe => Some("mediapipe/holistic"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dependencies(&self) -> Vec<ProcessorType> {
|
||||
match self {
|
||||
ProcessorType::Asrx => vec![ProcessorType::Cut],
|
||||
ProcessorType::Asrx => vec![ProcessorType::Cut, ProcessorType::Asr],
|
||||
ProcessorType::Scene => vec![ProcessorType::Cut],
|
||||
ProcessorType::Story => vec![
|
||||
ProcessorType::Asrx,
|
||||
@@ -548,6 +576,8 @@ impl ProcessorType {
|
||||
ProcessorType::Face,
|
||||
],
|
||||
ProcessorType::FiveW1H => vec![ProcessorType::Story],
|
||||
ProcessorType::Appearance => vec![ProcessorType::Pose],
|
||||
ProcessorType::MediaPipe => vec![],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
@@ -555,11 +585,14 @@ impl ProcessorType {
|
||||
pub fn all() -> Vec<ProcessorType> {
|
||||
vec![
|
||||
ProcessorType::Cut,
|
||||
ProcessorType::Asr,
|
||||
ProcessorType::Asrx,
|
||||
ProcessorType::Yolo,
|
||||
ProcessorType::Ocr,
|
||||
ProcessorType::Face,
|
||||
ProcessorType::Pose,
|
||||
ProcessorType::MediaPipe,
|
||||
ProcessorType::Appearance,
|
||||
ProcessorType::Story,
|
||||
]
|
||||
}
|
||||
@@ -569,9 +602,12 @@ impl ProcessorType {
|
||||
ProcessorType::Yolo
|
||||
| ProcessorType::Ocr
|
||||
| ProcessorType::Face
|
||||
| ProcessorType::Pose => PipelineType::Frame,
|
||||
| ProcessorType::Pose
|
||||
| ProcessorType::Appearance
|
||||
| ProcessorType::MediaPipe => PipelineType::Frame,
|
||||
|
||||
ProcessorType::Cut
|
||||
| ProcessorType::Asr
|
||||
| ProcessorType::Asrx
|
||||
| ProcessorType::Scene
|
||||
| ProcessorType::Story
|
||||
@@ -1659,7 +1695,7 @@ impl PostgresDb {
|
||||
MonitorJobStatus::from_db_str(&status_str).unwrap_or(MonitorJobStatus::Pending);
|
||||
|
||||
Ok(Some(MonitorJob {
|
||||
id: r.get(0),
|
||||
id: r.get::<i32, _>(0),
|
||||
uuid: r.get(1),
|
||||
video_path: r.get(2),
|
||||
status,
|
||||
@@ -1707,7 +1743,7 @@ impl PostgresDb {
|
||||
MonitorJobStatus::from_db_str(&status_str).unwrap_or(MonitorJobStatus::Pending);
|
||||
|
||||
MonitorJob {
|
||||
id: r.get(0),
|
||||
id: r.get::<i32, _>(0),
|
||||
uuid: r.get(1),
|
||||
video_path: r.get(2),
|
||||
status,
|
||||
@@ -2444,15 +2480,15 @@ impl PostgresDb {
|
||||
pub async fn store_face_detections_batch(
|
||||
&self,
|
||||
uuid: &str,
|
||||
detections: &[(i64, f64, i32, i32, i32, i32, f32)],
|
||||
detections: &[(i64, f64, Option<String>, i32, i32, i32, i32, f32)],
|
||||
) -> Result<()> {
|
||||
let table = schema::table_name("face_detections");
|
||||
for (frame, ts, x, y, w, h, conf) in detections {
|
||||
for (frame, ts, face_id, x, y, w, h, conf) in detections {
|
||||
sqlx::query(&format!(
|
||||
"INSERT INTO {} (file_uuid, frame_number, timestamp_secs, x, y, width, height, confidence) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT DO NOTHING", table
|
||||
"INSERT INTO {} (file_uuid, frame_number, timestamp_secs, face_id, x, y, width, height, confidence) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT DO NOTHING", table
|
||||
))
|
||||
.bind(uuid).bind(frame).bind(ts).bind(x).bind(y).bind(w).bind(h).bind(conf)
|
||||
.bind(uuid).bind(frame).bind(ts).bind(face_id).bind(x).bind(y).bind(w).bind(h).bind(conf)
|
||||
.execute(&self.pool).await?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -2696,8 +2732,8 @@ impl PostgresDb {
|
||||
let ptype: &str = r.get("processor");
|
||||
let st: &str = r.get("status");
|
||||
crate::core::db::ProcessorResult {
|
||||
id: r.get("id"),
|
||||
job_id: r.get("job_id"),
|
||||
id: r.get::<i32, _>("id"),
|
||||
job_id: r.get::<i32, _>("job_id"),
|
||||
processor_type: crate::core::db::ProcessorType::from_db_str(ptype)
|
||||
.unwrap_or(crate::core::db::ProcessorType::Cut),
|
||||
status: crate::core::db::ProcessorJobStatus::from_db_str(st)
|
||||
@@ -2742,8 +2778,8 @@ impl PostgresDb {
|
||||
let ptype: &str = r.get("processor");
|
||||
let st: &str = r.get("status");
|
||||
crate::core::db::ProcessorResult {
|
||||
id: r.get("id"),
|
||||
job_id: r.get("job_id"),
|
||||
id: r.get::<i32, _>("id"),
|
||||
job_id: r.get::<i32, _>("job_id"),
|
||||
processor_type: crate::core::db::ProcessorType::from_db_str(ptype)
|
||||
.unwrap_or(crate::core::db::ProcessorType::Cut),
|
||||
status: crate::core::db::ProcessorJobStatus::from_db_str(st)
|
||||
@@ -2917,7 +2953,7 @@ impl PostgresDb {
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| crate::core::person_identity::Identity {
|
||||
id: r.get(0),
|
||||
id: r.get::<i32, _>(0),
|
||||
name: r.get(1),
|
||||
metadata: r.get(2),
|
||||
created_at: r.get(3),
|
||||
@@ -2943,7 +2979,7 @@ impl PostgresDb {
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| crate::core::person_identity::Identity {
|
||||
id: r.get(0),
|
||||
id: r.get::<i32, _>(0),
|
||||
name: r.get(1),
|
||||
metadata: r.get(2),
|
||||
created_at: r.get(3),
|
||||
|
||||
+28
-11
@@ -7,10 +7,10 @@ use std::collections::HashMap;
|
||||
use super::{Database, SearchResult, VectorStore};
|
||||
|
||||
pub struct QdrantDb {
|
||||
pub(crate) client: Client,
|
||||
pub(crate) base_url: String,
|
||||
pub(crate) api_key: String,
|
||||
pub(crate) collection_name: String,
|
||||
pub client: Client,
|
||||
pub base_url: String,
|
||||
pub api_key: String,
|
||||
pub collection_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -693,10 +693,24 @@ impl QdrantDb {
|
||||
}
|
||||
|
||||
pub async fn delete_by_uuid(&self, uuid: &str) -> Result<()> {
|
||||
let url = format!(
|
||||
"{}/collections/{}/points/delete",
|
||||
self.base_url, self.collection_name
|
||||
);
|
||||
Self::delete_by_uuid_from_collection(
|
||||
&self.client,
|
||||
&self.base_url,
|
||||
&self.api_key,
|
||||
&self.collection_name,
|
||||
uuid,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn delete_by_uuid_from_collection(
|
||||
client: &reqwest::Client,
|
||||
base_url: &str,
|
||||
api_key: &str,
|
||||
collection: &str,
|
||||
uuid: &str,
|
||||
) -> Result<()> {
|
||||
let url = format!("{}/collections/{}/points/delete", base_url, collection);
|
||||
|
||||
let body = serde_json::json!({
|
||||
"filter": {
|
||||
@@ -711,14 +725,17 @@ impl QdrantDb {
|
||||
}
|
||||
});
|
||||
|
||||
self.client
|
||||
client
|
||||
.post(&url)
|
||||
.header("api-key", &self.api_key)
|
||||
.header("api-key", api_key)
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to delete points from Qdrant")?;
|
||||
.context(format!(
|
||||
"Failed to delete points from Qdrant collection {}",
|
||||
collection
|
||||
))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
use anyhow::{Context, Result};
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Manages Qdrant workspace collections — staging area for vectors during processing.
|
||||
/// At checkin, vectors are copied from workspace to their respective production collections.
|
||||
///
|
||||
/// Workspace collections:
|
||||
/// - `{prefix}_workspace_chunks` (768d) — text chunk embeddings
|
||||
/// - `{prefix}_workspace_traces` (512d) — face trace embeddings
|
||||
///
|
||||
/// Voice embeddings use per-file collections (`{file_uuid}_voice`) stored directly, no workspace staging.
|
||||
pub struct QdrantWorkspace {
|
||||
client: Client,
|
||||
base_url: String,
|
||||
api_key: String,
|
||||
prefix: String,
|
||||
}
|
||||
|
||||
impl QdrantWorkspace {
|
||||
pub fn new() -> Self {
|
||||
let base_url =
|
||||
std::env::var("QDRANT_URL").unwrap_or_else(|_| "http://localhost:6333".to_string());
|
||||
let api_key = std::env::var("QDRANT_API_KEY")
|
||||
.unwrap_or_else(|_| "Test3200Test3200Test3200".to_string());
|
||||
let prefix = crate::core::config::REDIS_KEY_PREFIX
|
||||
.as_str()
|
||||
.trim_end_matches(':')
|
||||
.to_string();
|
||||
Self {
|
||||
client: Client::new(),
|
||||
base_url,
|
||||
api_key,
|
||||
prefix,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn chunks_collection(&self) -> String {
|
||||
format!("{}_workspace_chunks", self.prefix)
|
||||
}
|
||||
|
||||
pub fn traces_collection(&self) -> String {
|
||||
format!("{}_workspace_traces", self.prefix)
|
||||
}
|
||||
|
||||
pub async fn ensure_all(&self) -> Result<()> {
|
||||
self.ensure_collection(&self.chunks_collection(), 768)
|
||||
.await?;
|
||||
self.ensure_collection(&self.traces_collection(), 512).await
|
||||
}
|
||||
|
||||
async fn ensure_collection(&self, name: &str, dim: usize) -> Result<()> {
|
||||
let url = format!("{}/collections/{}", self.base_url, name);
|
||||
let exists = self
|
||||
.client
|
||||
.get(&url)
|
||||
.header("api-key", &self.api_key)
|
||||
.send()
|
||||
.await
|
||||
.map(|r| r.status().is_success())
|
||||
.unwrap_or(false);
|
||||
if exists {
|
||||
return Ok(());
|
||||
}
|
||||
let body = serde_json::json!({
|
||||
"vectors": { "size": dim, "distance": "Cosine" }
|
||||
});
|
||||
self.client
|
||||
.post(&format!("{}/collections", self.base_url))
|
||||
.header("api-key", &self.api_key)
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.context(format!(
|
||||
"Failed to create Qdrant workspace collection: {}",
|
||||
name
|
||||
))?;
|
||||
tracing::info!(
|
||||
"Created Qdrant workspace collection: {} (dim={})",
|
||||
name,
|
||||
dim
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn upsert_vector(
|
||||
&self,
|
||||
collection: &str,
|
||||
point_id: u64,
|
||||
vector: &[f32],
|
||||
payload: Option<serde_json::Value>,
|
||||
) -> Result<()> {
|
||||
let url = format!(
|
||||
"{}/collections/{}/points?wait=true",
|
||||
self.base_url, collection
|
||||
);
|
||||
let point = if let Some(p) = payload {
|
||||
serde_json::json!({ "points": [{ "id": point_id, "vector": vector, "payload": p }] })
|
||||
} else {
|
||||
serde_json::json!({ "points": [{ "id": point_id, "vector": vector }] })
|
||||
};
|
||||
let resp = self
|
||||
.client
|
||||
.put(&url)
|
||||
.header("api-key", &self.api_key)
|
||||
.json(&point)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to upsert to Qdrant workspace")?;
|
||||
if !resp.status().is_success() {
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("Qdrant workspace upsert failed: {}", text);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn upsert_vectors_batch(
|
||||
&self,
|
||||
collection: &str,
|
||||
points: &[(u64, &[f32], Option<serde_json::Value>)],
|
||||
) -> Result<()> {
|
||||
let url = format!(
|
||||
"{}/collections/{}/points?wait=true",
|
||||
self.base_url, collection
|
||||
);
|
||||
let qdrant_points: Vec<serde_json::Value> = points
|
||||
.iter()
|
||||
.map(|(id, vec, payload)| {
|
||||
let mut p = serde_json::json!({ "id": id, "vector": vec });
|
||||
if let Some(pl) = payload {
|
||||
p["payload"] = pl.clone();
|
||||
}
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
let body = serde_json::json!({ "points": qdrant_points });
|
||||
let resp = self
|
||||
.client
|
||||
.put(&url)
|
||||
.header("api-key", &self.api_key)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to batch upsert to Qdrant workspace")?;
|
||||
if !resp.status().is_success() {
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("Qdrant workspace batch upsert failed: {}", text);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn upsert_chunk_embedding(
|
||||
&self,
|
||||
point_id: &str,
|
||||
vector: &[f32],
|
||||
chunk_type: &str,
|
||||
file_uuid: &str,
|
||||
text: &str,
|
||||
parent_chunk_id: Option<&str>,
|
||||
start_time: f64,
|
||||
end_time: f64,
|
||||
) -> Result<()> {
|
||||
let mut payload = HashMap::new();
|
||||
payload.insert("file_uuid".to_string(), serde_json::json!(file_uuid));
|
||||
payload.insert("chunk_type".to_string(), serde_json::json!(chunk_type));
|
||||
payload.insert("text".to_string(), serde_json::json!(text));
|
||||
payload.insert("start_time".to_string(), serde_json::json!(start_time));
|
||||
payload.insert("end_time".to_string(), serde_json::json!(end_time));
|
||||
if let Some(pid) = parent_chunk_id {
|
||||
payload.insert("parent_chunk_id".to_string(), serde_json::json!(pid));
|
||||
}
|
||||
|
||||
let point_id_num = {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
point_id.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
};
|
||||
self.upsert_vector(
|
||||
&self.chunks_collection(),
|
||||
point_id_num,
|
||||
vector,
|
||||
Some(serde_json::json!(payload)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upsert_face_embedding(
|
||||
&self,
|
||||
point_id: u64,
|
||||
vector: &[f32],
|
||||
file_uuid: &str,
|
||||
trace_id: i32,
|
||||
frame_number: i64,
|
||||
) -> Result<()> {
|
||||
let payload = serde_json::json!({
|
||||
"file_uuid": file_uuid,
|
||||
"trace_id": trace_id,
|
||||
"frame_number": frame_number,
|
||||
"type": "face_embedding",
|
||||
});
|
||||
self.upsert_vector(&self.traces_collection(), point_id, vector, Some(payload))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Scroll all points for a file from all workspace collections.
|
||||
/// Used during checkin to read vectors before moving to production.
|
||||
pub async fn scroll_by_file_uuid(&self, file_uuid: &str) -> Result<WorkspaceScrollResult> {
|
||||
let chunks = self
|
||||
.scroll_collection(&self.chunks_collection(), file_uuid)
|
||||
.await?;
|
||||
let traces = self
|
||||
.scroll_collection(&self.traces_collection(), file_uuid)
|
||||
.await?;
|
||||
Ok(WorkspaceScrollResult { chunks, traces })
|
||||
}
|
||||
|
||||
async fn scroll_collection(
|
||||
&self,
|
||||
collection: &str,
|
||||
file_uuid: &str,
|
||||
) -> Result<Vec<ScrolledPoint>> {
|
||||
use serde_json::json;
|
||||
let url = format!("{}/collections/{}/points/scroll", self.base_url, collection);
|
||||
let body = json!({
|
||||
"filter": {
|
||||
"must": [{ "key": "file_uuid", "match": { "value": file_uuid } }]
|
||||
},
|
||||
"limit": 10000,
|
||||
"with_payload": true,
|
||||
"with_vector": true,
|
||||
});
|
||||
let resp = self
|
||||
.client
|
||||
.post(&url)
|
||||
.header("api-key", &self.api_key)
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.context(format!("Failed to scroll Qdrant workspace: {}", collection))?;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ScrollResp {
|
||||
result: ScrollResult,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct ScrollResult {
|
||||
points: Vec<QdrantPoint>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct QdrantPoint {
|
||||
id: serde_json::Value,
|
||||
payload: HashMap<String, serde_json::Value>,
|
||||
vector: Option<Vec<f32>>,
|
||||
}
|
||||
|
||||
let text = resp.text().await?;
|
||||
let parsed: ScrollResp = serde_json::from_str(&text).context(format!(
|
||||
"Failed to parse scroll response from {}",
|
||||
collection
|
||||
))?;
|
||||
|
||||
Ok(parsed
|
||||
.result
|
||||
.points
|
||||
.into_iter()
|
||||
.map(|p| ScrolledPoint {
|
||||
id: p.id.to_string(),
|
||||
vector: p.vector,
|
||||
payload: p.payload,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Delete all vectors for a file from all workspace collections.
|
||||
/// Used after checkin to clean up.
|
||||
pub async fn delete_by_file_uuid(&self, file_uuid: &str) -> Result<()> {
|
||||
self.delete_from_collection(&self.chunks_collection(), file_uuid)
|
||||
.await?;
|
||||
let _ = self
|
||||
.delete_from_collection(&self.traces_collection(), file_uuid)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_from_collection(&self, collection: &str, file_uuid: &str) -> Result<()> {
|
||||
let url = format!("{}/collections/{}/points/delete", self.base_url, collection);
|
||||
let body = serde_json::json!({
|
||||
"filter": {
|
||||
"must": [{ "key": "file_uuid", "match": { "value": file_uuid } }]
|
||||
}
|
||||
});
|
||||
let resp = self
|
||||
.client
|
||||
.post(&url)
|
||||
.header("api-key", &self.api_key)
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.context(format!(
|
||||
"Failed to delete from Qdrant workspace: {}",
|
||||
collection
|
||||
))?;
|
||||
if !resp.status().is_success() {
|
||||
tracing::warn!(
|
||||
"Delete from workspace {} returned {}",
|
||||
collection,
|
||||
resp.status()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for QdrantWorkspace {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ScrolledPoint {
|
||||
pub id: String,
|
||||
pub vector: Option<Vec<f32>>,
|
||||
pub payload: HashMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WorkspaceScrollResult {
|
||||
pub chunks: Vec<ScrolledPoint>,
|
||||
pub traces: Vec<ScrolledPoint>,
|
||||
}
|
||||
@@ -15,7 +15,7 @@ static SCHEMA_VERSION: AtomicU32 = AtomicU32::new(0);
|
||||
impl SchemaContext {
|
||||
/// Initialize schema context from environment
|
||||
pub fn init() -> Self {
|
||||
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "dev".to_string());
|
||||
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string());
|
||||
let prefix = if schema == "public" {
|
||||
String::new()
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
|
||||
use sqlx::Row;
|
||||
|
||||
use crate::core::config::OUTPUT_DIR;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WorkspaceDb {
|
||||
pool: SqlitePool,
|
||||
pub file_uuid: String,
|
||||
}
|
||||
|
||||
pub fn workspace_path(file_uuid: &str) -> PathBuf {
|
||||
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.workspace.sqlite", file_uuid))
|
||||
}
|
||||
|
||||
impl WorkspaceDb {
|
||||
pub async fn open(file_uuid: &str) -> Result<Self> {
|
||||
let path = workspace_path(file_uuid);
|
||||
let url = format!("sqlite:///{}?mode=rwc", path.display());
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect(&url)
|
||||
.await
|
||||
.context(format!(
|
||||
"Failed to open workspace SQLite: {}",
|
||||
path.display()
|
||||
))?;
|
||||
|
||||
let db = Self {
|
||||
pool,
|
||||
file_uuid: file_uuid.to_string(),
|
||||
};
|
||||
db.init_tables().await?;
|
||||
Ok(db)
|
||||
}
|
||||
|
||||
async fn init_tables(&self) -> Result<()> {
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS processor_results (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
job_id INTEGER NOT NULL,
|
||||
file_uuid TEXT NOT NULL,
|
||||
processor_type TEXT NOT NULL,
|
||||
processor TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
error_message TEXT,
|
||||
output_data TEXT,
|
||||
chunks_produced INTEGER DEFAULT 0,
|
||||
frames_processed INTEGER DEFAULT 0,
|
||||
started_at TEXT,
|
||||
completed_at TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
)",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS pre_chunks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
file_uuid TEXT NOT NULL,
|
||||
processor_type TEXT NOT NULL,
|
||||
chunk_type TEXT NOT NULL,
|
||||
start_frame INTEGER,
|
||||
end_frame INTEGER,
|
||||
start_time REAL,
|
||||
end_time REAL,
|
||||
data TEXT,
|
||||
text_content TEXT
|
||||
)",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS face_detections (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
file_uuid TEXT NOT NULL,
|
||||
face_id TEXT,
|
||||
frame_number INTEGER,
|
||||
timestamp_secs REAL,
|
||||
x REAL,
|
||||
y REAL,
|
||||
w REAL,
|
||||
h REAL,
|
||||
confidence REAL
|
||||
)",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS speaker_detections (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
file_uuid TEXT NOT NULL,
|
||||
speaker_id TEXT,
|
||||
start_time REAL,
|
||||
end_time REAL,
|
||||
text_content TEXT,
|
||||
chunk_id TEXT,
|
||||
confidence REAL
|
||||
)",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS chunks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
file_uuid TEXT NOT NULL,
|
||||
chunk_id TEXT NOT NULL,
|
||||
chunk_type TEXT NOT NULL,
|
||||
start_frame INTEGER,
|
||||
end_frame INTEGER,
|
||||
start_time REAL,
|
||||
end_time REAL,
|
||||
text_content TEXT,
|
||||
content TEXT,
|
||||
fps REAL
|
||||
)",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn clear(&self) -> Result<()> {
|
||||
self.pool.close().await;
|
||||
let path = workspace_path(&self.file_uuid);
|
||||
if path.exists() {
|
||||
tokio::fs::remove_file(&path)
|
||||
.await
|
||||
.context(format!("Failed to delete workspace: {}", path.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn exists(file_uuid: &str) -> bool {
|
||||
workspace_path(file_uuid).exists()
|
||||
}
|
||||
|
||||
// ── Processor Results ──
|
||||
|
||||
pub async fn upsert_processor_result(
|
||||
&self,
|
||||
job_id: i32,
|
||||
processor_type: &str,
|
||||
status: &str,
|
||||
) -> Result<i64> {
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO processor_results (job_id, file_uuid, processor_type, processor, status) \
|
||||
VALUES (?1, ?2, ?3, ?3, ?4)",
|
||||
)
|
||||
.bind(job_id)
|
||||
.bind(&self.file_uuid)
|
||||
.bind(processor_type)
|
||||
.bind(status)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(result.last_insert_rowid())
|
||||
}
|
||||
|
||||
pub async fn update_processor_result(&self, result_id: i64, status: &str) -> Result<()> {
|
||||
sqlx::query("UPDATE processor_results SET status = ?1 WHERE id = ?2")
|
||||
.bind(status)
|
||||
.bind(result_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_processor_result_with_stats(
|
||||
&self,
|
||||
result_id: i64,
|
||||
status: &str,
|
||||
error_message: Option<&str>,
|
||||
output_data: Option<&str>,
|
||||
chunks_produced: i32,
|
||||
frames_processed: i32,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
"UPDATE processor_results SET status=?1, error_message=?2, output_data=?3, \
|
||||
chunks_produced=?4, frames_processed=?5 WHERE id=?6",
|
||||
)
|
||||
.bind(status)
|
||||
.bind(error_message)
|
||||
.bind(output_data)
|
||||
.bind(chunks_produced)
|
||||
.bind(frames_processed)
|
||||
.bind(result_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_processor_results(&self) -> Result<Vec<ProcessorResultRow>> {
|
||||
let rows = sqlx::query_as::<_, ProcessorResultRow>(
|
||||
"SELECT id, job_id, file_uuid, processor_type, processor, status, \
|
||||
error_message, output_data, chunks_produced, frames_processed, \
|
||||
started_at, completed_at, created_at \
|
||||
FROM processor_results ORDER BY id",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
// ── Pre-chunks ──
|
||||
|
||||
pub async fn store_pre_chunk(
|
||||
&self,
|
||||
processor_type: &str,
|
||||
chunk_type: &str,
|
||||
start_frame: Option<i64>,
|
||||
end_frame: Option<i64>,
|
||||
start_time: Option<f64>,
|
||||
end_time: Option<f64>,
|
||||
data: Option<&str>,
|
||||
text_content: Option<&str>,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO pre_chunks (file_uuid, processor_type, chunk_type, \
|
||||
start_frame, end_frame, start_time, end_time, data, text_content) \
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
)
|
||||
.bind(&self.file_uuid)
|
||||
.bind(processor_type)
|
||||
.bind(chunk_type)
|
||||
.bind(start_frame)
|
||||
.bind(end_frame)
|
||||
.bind(start_time)
|
||||
.bind(end_time)
|
||||
.bind(data)
|
||||
.bind(text_content)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_all_pre_chunks(&self) -> Result<Vec<PreChunkRow>> {
|
||||
let rows = sqlx::query_as::<_, PreChunkRow>(
|
||||
"SELECT id, file_uuid, processor_type, chunk_type, \
|
||||
start_frame, end_frame, start_time, end_time, data, text_content \
|
||||
FROM pre_chunks ORDER BY id",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
// ── Face Detections ──
|
||||
|
||||
pub async fn store_face_detections_batch(
|
||||
&self,
|
||||
detections: &[FaceDetectionBatchItem],
|
||||
) -> Result<()> {
|
||||
for d in detections {
|
||||
sqlx::query(
|
||||
"INSERT INTO face_detections (file_uuid, face_id, frame_number, timestamp_secs, \
|
||||
x, y, w, h, confidence) \
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
)
|
||||
.bind(&self.file_uuid)
|
||||
.bind(&d.face_id)
|
||||
.bind(d.frame)
|
||||
.bind(d.ts)
|
||||
.bind(d.x)
|
||||
.bind(d.y)
|
||||
.bind(d.w)
|
||||
.bind(d.h)
|
||||
.bind(d.confidence)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_all_face_detections(&self) -> Result<Vec<FaceDetectionRow>> {
|
||||
let rows = sqlx::query_as::<_, FaceDetectionRow>(
|
||||
"SELECT id, file_uuid, face_id, frame_number, timestamp_secs, \
|
||||
x, y, w, h, confidence \
|
||||
FROM face_detections ORDER BY id",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
// ── Speaker Detections ──
|
||||
|
||||
pub async fn store_speaker_detections_batch(
|
||||
&self,
|
||||
segments: &[SpeakerDetectionBatchItem],
|
||||
) -> Result<()> {
|
||||
for s in segments {
|
||||
sqlx::query(
|
||||
"INSERT INTO speaker_detections (file_uuid, speaker_id, start_time, end_time, \
|
||||
text_content, chunk_id, confidence) \
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||
)
|
||||
.bind(&self.file_uuid)
|
||||
.bind(&s.speaker_id)
|
||||
.bind(s.start_time)
|
||||
.bind(s.end_time)
|
||||
.bind(&s.text)
|
||||
.bind(&s.chunk_id)
|
||||
.bind(s.confidence)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_all_speaker_detections(&self) -> Result<Vec<SpeakerDetectionRow>> {
|
||||
let rows = sqlx::query_as::<_, SpeakerDetectionRow>(
|
||||
"SELECT id, file_uuid, speaker_id, start_time, end_time, \
|
||||
text_content, chunk_id, confidence \
|
||||
FROM speaker_detections ORDER BY id",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
// ── Chunks ──
|
||||
|
||||
pub async fn store_chunk(
|
||||
&self,
|
||||
chunk_id: &str,
|
||||
chunk_type: &str,
|
||||
start_frame: i64,
|
||||
end_frame: i64,
|
||||
start_time: f64,
|
||||
end_time: f64,
|
||||
text_content: Option<&str>,
|
||||
content: Option<&str>,
|
||||
fps: f64,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO chunks (file_uuid, chunk_id, chunk_type, start_frame, end_frame, \
|
||||
start_time, end_time, text_content, content, fps) \
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
)
|
||||
.bind(&self.file_uuid)
|
||||
.bind(chunk_id)
|
||||
.bind(chunk_type)
|
||||
.bind(start_frame)
|
||||
.bind(end_frame)
|
||||
.bind(start_time)
|
||||
.bind(end_time)
|
||||
.bind(text_content)
|
||||
.bind(content)
|
||||
.bind(fps)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_all_chunks(&self) -> Result<Vec<ChunkRow>> {
|
||||
let rows = sqlx::query_as::<_, ChunkRow>(
|
||||
"SELECT id, file_uuid, chunk_id, chunk_type, start_frame, end_frame, \
|
||||
start_time, end_time, text_content, content, fps \
|
||||
FROM chunks ORDER BY id",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Row types ──
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct ProcessorResultRow {
|
||||
pub id: i64,
|
||||
pub job_id: i32,
|
||||
pub file_uuid: String,
|
||||
pub processor_type: String,
|
||||
pub processor: Option<String>,
|
||||
pub status: String,
|
||||
pub error_message: Option<String>,
|
||||
pub output_data: Option<String>,
|
||||
pub chunks_produced: i32,
|
||||
pub frames_processed: i32,
|
||||
pub started_at: Option<String>,
|
||||
pub completed_at: Option<String>,
|
||||
pub created_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct PreChunkRow {
|
||||
pub id: i64,
|
||||
pub file_uuid: String,
|
||||
pub processor_type: String,
|
||||
pub chunk_type: String,
|
||||
pub start_frame: Option<i64>,
|
||||
pub end_frame: Option<i64>,
|
||||
pub start_time: Option<f64>,
|
||||
pub end_time: Option<f64>,
|
||||
pub data: Option<String>,
|
||||
pub text_content: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct FaceDetectionRow {
|
||||
pub id: i64,
|
||||
pub file_uuid: String,
|
||||
pub face_id: Option<String>,
|
||||
pub frame_number: Option<i64>,
|
||||
pub timestamp_secs: Option<f64>,
|
||||
pub x: Option<f64>,
|
||||
pub y: Option<f64>,
|
||||
pub w: Option<f64>,
|
||||
pub h: Option<f64>,
|
||||
pub confidence: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FaceDetectionBatchItem {
|
||||
pub face_id: Option<String>,
|
||||
pub frame: i64,
|
||||
pub ts: f64,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub w: i32,
|
||||
pub h: i32,
|
||||
pub confidence: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct SpeakerDetectionRow {
|
||||
pub id: i64,
|
||||
pub file_uuid: String,
|
||||
pub speaker_id: Option<String>,
|
||||
pub start_time: Option<f64>,
|
||||
pub end_time: Option<f64>,
|
||||
pub text_content: Option<String>,
|
||||
pub chunk_id: Option<String>,
|
||||
pub confidence: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SpeakerDetectionBatchItem {
|
||||
pub speaker_id: String,
|
||||
pub start_time: f64,
|
||||
pub end_time: f64,
|
||||
pub text: String,
|
||||
pub chunk_id: Option<String>,
|
||||
pub confidence: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct ChunkRow {
|
||||
pub id: i64,
|
||||
pub file_uuid: String,
|
||||
pub chunk_id: String,
|
||||
pub chunk_type: String,
|
||||
pub start_frame: i64,
|
||||
pub end_frame: i64,
|
||||
pub start_time: f64,
|
||||
pub end_time: f64,
|
||||
pub text_content: Option<String>,
|
||||
pub content: Option<String>,
|
||||
pub fps: f64,
|
||||
}
|
||||
Reference in New Issue
Block a user