feat: ASRX hybrid pipeline, identity history, worker fixes, checkpoint system

This commit is contained in:
Accusys
2026-06-02 07:13:23 +08:00
parent e3066c3f49
commit e1572907ae
198 changed files with 43705 additions and 8910 deletions
+42
View File
@@ -0,0 +1,42 @@
use sqlx::postgres::PgPoolOptions;
use sqlx::Row;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://accusys@localhost:5432/momentry".into());
let pool = PgPoolOptions::new()
.max_connections(1)
.connect(&url)
.await?;
// Check videos columns
let rows = sqlx::query(
"SELECT column_name, data_type FROM information_schema.columns WHERE table_schema='public' AND table_name='videos' ORDER BY ordinal_position"
).fetch_all(&pool).await?;
println!("=== public.videos columns ===");
for r in &rows {
let col: String = r.get("column_name");
let typ: String = r.get("data_type");
println!(" {}: {}", col, typ);
}
// Check chunks_rule1 columns
let rows2 = sqlx::query(
"SELECT column_name, data_type FROM information_schema.columns WHERE table_schema='public' AND table_name='chunks_rule1' ORDER BY ordinal_position"
).fetch_all(&pool).await?;
println!("=== public.chunks_rule1 columns ===");
for r in &rows2 {
let col: String = r.get("column_name");
let typ: String = r.get("data_type");
println!(" {}: {}", col, typ);
}
// Check if jobs exists
let exists: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema='public' AND table_name='jobs')"
).fetch_one(&pool).await?;
println!("=== public.jobs exists: {} ===", exists);
Ok(())
}
+95
View File
@@ -0,0 +1,95 @@
use anyhow::{Context, Result};
use momentry_core::{Database, PostgresDb, QdrantDb, VectorPayload};
#[tokio::main]
async fn main() -> Result<()> {
dotenv::from_filename("/Users/accusys/momentry_core_0.1/.env.development").ok();
tracing_subscriber::fmt::init();
let pg = PostgresDb::init().await.context("Failed to init PostgreSQL")?;
let qdrant = QdrantDb::new();
let chunk_table = momentry_core::core::db::schema::table_name("chunk");
let uuids = vec![
"63acd3bb02b5b9dfbb9d6db499fcc864",
"a6fb22eebefaef17e62af874997c5944",
"d81e01261391b45c1a14ddd5f082733e",
];
for uuid in &uuids {
let rows = sqlx::query_as::<_, (String, String, i64, i64, f64, f64, String, String)>(
&format!(
"SELECT chunk_id, text_content, start_frame, end_frame, \
start_time, end_time, embedding::text, content::text \
FROM {} \
WHERE file_uuid = $1 \
AND chunk_type = 'sentence' \
AND embedding IS NOT NULL \
AND (text_content IS NOT NULL AND text_content != '') \
ORDER BY id",
chunk_table
),
)
.bind(uuid)
.fetch_all(pg.pool())
.await?;
let total = rows.len();
println!("[{}] Found {} sentence chunks with embeddings to sync to Qdrant", uuid, total);
if total == 0 {
continue;
}
let start = std::time::Instant::now();
let mut stored = 0usize;
let mut errors = 0usize;
for (chunk_id, text, start_frame, end_frame, start_time, end_time, vector_text, _content_str) in &rows {
let vector: Vec<f32> = serde_json::from_str(vector_text)
.map_err(|e| anyhow::anyhow!("Failed to parse vector for {}: {}", chunk_id, e))?;
let payload = VectorPayload {
file_uuid: uuid.to_string(),
chunk_id: chunk_id.clone(),
chunk_type: "sentence".to_string(),
start_frame: *start_frame,
end_frame: *end_frame,
start_time: *start_time,
end_time: *end_time,
text: Some(text.clone()),
};
if let Err(e) = qdrant.upsert_vector(chunk_id, &vector, payload).await {
eprintln!("[ERROR] Qdrant upsert failed for {}: {}", chunk_id, e);
errors += 1;
continue;
}
stored += 1;
if stored % 5000 == 0 || stored == total {
let elapsed = start.elapsed();
let rate = stored as f64 / elapsed.as_secs_f64();
println!(
" [{}] {}/{} ({:.1}%) | {:.0} vec/s | {} errors",
uuid.get(..8).unwrap_or(uuid),
stored, total,
100.0 * stored as f64 / total as f64,
rate, errors,
);
}
}
let elapsed = start.elapsed();
println!(
"[{}] Done! {}/{} vectors synced ({} errors) in {:.1}s ({:.0} vec/s avg)",
uuid.get(..8).unwrap_or(uuid),
stored, total, errors,
elapsed.as_secs_f64(),
stored as f64 / elapsed.as_secs_f64(),
);
}
println!("\nAll files synced to Qdrant!");
Ok(())
}
+45
View File
@@ -0,0 +1,45 @@
use bson::bson;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestIdentitySnapshot {
id: i32,
uuid: String,
name: String,
identity_type: Option<String>,
source: Option<String>,
status: String,
tmdb_id: Option<i32>,
tmdb_profile: Option<String>,
metadata: serde_json::Value,
#[serde(
with = "bson::serde_helpers::chrono_datetime_as_bson_datetime_optional",
default
)]
created_at: Option<DateTime<Utc>>,
face_count: i64,
}
fn main() {
// 模拟 MongoDB document
let doc = bson!({
"id": bson::Bson::Int32(21),
"uuid": "1524f6a1537f48a187526d44a236584f",
"name": "Albert Daumergue",
"identity_type": "people",
"source": "tmdb",
"status": "confirmed",
"tmdb_id": bson::Bson::Int32(1100817),
"tmdb_profile": bson::Bson::Null,
"metadata": {"role": "", "notes": "", "aliases": [], "starred": false},
"created_at": bson::Bson::DateTime(bson::DateTime::from_millis(1714641951963)),
"face_count": bson::Bson::Int64(0)
});
let result: Result<TestIdentitySnapshot, _> = bson::from_bson(doc);
match result {
Ok(s) => println!("Success! {:?}", s),
Err(e) => println!("Error: {}", e),
}
}
+25
View File
@@ -0,0 +1,25 @@
use bson::bson;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FacesTransferred {
file_uuid: String,
face_ids: Vec<String>,
trace_ids: Vec<i32>,
count: i64,
}
fn main() {
let doc = bson!({
"file_uuid": "",
"face_ids": [],
"trace_ids": [],
"count": bson::Bson::Int64(0)
});
let result: Result<FacesTransferred, _> = bson::from_bson(doc);
match result {
Ok(f) => println!("Success! trace_ids len: {}", f.trace_ids.len()),
Err(e) => println!("Error: {}", e),
}
}
+131
View File
@@ -0,0 +1,131 @@
use bson::bson;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct IdentitySnapshot {
id: i32,
uuid: String,
name: String,
identity_type: Option<String>,
source: Option<String>,
status: String,
tmdb_id: Option<i32>,
tmdb_profile: Option<String>,
metadata: serde_json::Value,
#[serde(
with = "bson::serde_helpers::chrono_datetime_as_bson_datetime_optional",
default
)]
created_at: Option<DateTime<Utc>>,
face_count: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TargetIdentitySnapshot {
id: i32,
uuid: String,
name: String,
metadata_before: serde_json::Value,
metadata_after: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AliasEntry {
name: String,
locale: String,
source: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FacesTransferred {
file_uuid: String,
face_ids: Vec<String>,
trace_ids: Vec<i32>,
count: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MergeParams {
keep_history: bool,
cleared_stranger_id: bool,
performed_by_user: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct IdentityMergeHistory {
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
id: Option<bson::oid::ObjectId>,
merge_id: String,
source_identity: IdentitySnapshot,
target_identity: TargetIdentitySnapshot,
aliases_added_to_target: Vec<AliasEntry>,
metadata_fields_added: Vec<String>,
faces_transferred: FacesTransferred,
merge_params: MergeParams,
#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
merged_at: DateTime<Utc>,
#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
undo_deadline: DateTime<Utc>,
undone: bool,
#[serde(
with = "bson::serde_helpers::chrono_datetime_as_bson_datetime_optional",
skip_serializing_if = "Option::is_none"
)]
undone_at: Option<DateTime<Utc>>,
undone_by: Option<String>,
undone_snapshot: Option<serde_json::Value>,
undo_expired: bool,
}
fn main() {
let doc = bson!({
"merge_id": "test-id",
"source_identity": {
"id": bson::Bson::Int32(21),
"uuid": "test-uuid",
"name": "Test",
"identity_type": "people",
"source": "tmdb",
"status": "confirmed",
"tmdb_id": bson::Bson::Int32(123),
"tmdb_profile": bson::Bson::Null,
"metadata": {},
"created_at": bson::Bson::DateTime(bson::DateTime::from_millis(1714641951963)),
"face_count": bson::Bson::Int64(0)
},
"target_identity": {
"id": bson::Bson::Int32(22),
"uuid": "target-uuid",
"name": "Target",
"metadata_before": {},
"metadata_after": bson::Bson::Null
},
"aliases_added_to_target": [],
"metadata_fields_added": [],
"faces_transferred": {
"file_uuid": "",
"face_ids": [],
"trace_ids": [],
"count": bson::Bson::Int64(0)
},
"merge_params": {
"keep_history": false,
"cleared_stranger_id": true,
"performed_by_user": "0"
},
"merged_at": bson::Bson::DateTime(bson::DateTime::from_millis(1714641951963)),
"undo_deadline": bson::Bson::DateTime(bson::DateTime::from_millis(1714641951963)),
"undone": false,
"undone_at": bson::Bson::Null,
"undone_by": bson::Bson::Null,
"undone_snapshot": bson::Bson::Null,
"undo_expired": false
});
let result: Result<IdentityMergeHistory, _> = bson::from_bson(doc);
match result {
Ok(h) => println!("Success! {:?}", h.merge_id),
Err(e) => println!("Error: {}", e),
}
}
+31
View File
@@ -0,0 +1,31 @@
use bson::bson;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestId {
id: i32,
tmdb_id: Option<i32>,
}
fn main() {
// 测试 Int32
let doc_int32 = bson!({
"id": bson::Bson::Int32(21),
"tmdb_id": bson::Bson::Int32(1100817)
});
let result1: Result<TestId, _> = bson::from_bson(doc_int32);
println!("Int32 test: {}", result1.is_ok());
// 测试 Double (JavaScript Number 可能是这个)
let doc_double = bson!({
"id": bson::Bson::Double(21.0),
"tmdb_id": bson::Bson::Double(1100817.0)
});
let result2: Result<TestId, _> = bson::from_bson(doc_double);
println!("Double test: {}", result2.is_ok());
if result2.is_err() {
println!("Double error: {}", result2.unwrap_err());
}
}
+117
View File
@@ -0,0 +1,117 @@
use anyhow::{Context, Result};
use momentry_core::{
Database, Embedder, PostgresDb, QdrantDb, VectorPayload,
};
use std::time::{Duration, Instant};
#[tokio::main]
async fn main() -> Result<()> {
dotenv::from_filename("/Users/accusys/momentry_core_0.1/.env.development").ok();
tracing_subscriber::fmt::init();
let pg = PostgresDb::init().await.context("Failed to init PostgreSQL")?;
let qdrant = QdrantDb::new();
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let uuid = "63acd3bb02b5b9dfbb9d6db499fcc864";
let chunk_table = momentry_core::core::db::schema::table_name("chunk");
let rows = sqlx::query_as::<_, (String, String, i64, i64, f64, f64, String)>(
&format!(
"SELECT chunk_id, text_content, start_frame, end_frame, \
start_time, end_time, content::text \
FROM {} \
WHERE file_uuid = $1 \
AND chunk_type = 'sentence' \
AND embedding IS NULL \
AND (text_content IS NOT NULL AND text_content != '') \
ORDER BY id",
chunk_table
),
)
.bind(uuid)
.fetch_all(pg.pool())
.await?;
let total = rows.len();
println!("Found {} sentence chunks without embedding for {}", total, uuid);
if total == 0 {
println!("Nothing to vectorize. Exiting.");
return Ok(());
}
let start = Instant::now();
let mut stored = 0usize;
let mut errors = 0usize;
for (chunk_id, text, start_frame, end_frame, start_time, end_time, _content_str) in &rows {
if text.is_empty() {
continue;
}
match embedder.embed_document(text).await {
Ok(vector) => {
if let Err(e) = pg.store_vector(chunk_id, &vector, uuid).await {
eprintln!("[ERROR] PG store failed for {}: {}", chunk_id, e);
errors += 1;
continue;
}
let payload = VectorPayload {
file_uuid: uuid.to_string(),
chunk_id: chunk_id.clone(),
chunk_type: "sentence".to_string(),
start_frame: *start_frame,
end_frame: *end_frame,
start_time: *start_time,
end_time: *end_time,
text: Some(text.clone()),
};
if let Err(e) = qdrant.upsert_vector(chunk_id, &vector, payload).await {
eprintln!("[ERROR] Qdrant upsert failed for {}: {}", chunk_id, e);
errors += 1;
continue;
}
stored += 1;
if stored % 500 == 0 || stored == total {
let elapsed = start.elapsed();
let rate = stored as f64 / elapsed.as_secs_f64();
let eta = if stored < total {
let remaining = Duration::from_secs_f64((total - stored) as f64 / rate);
format!(" (ETA: {}s)", remaining.as_secs())
} else {
String::new()
};
println!(
" [{}/{}] {:.1}% done | {:.0} vec/s | {} errors{}",
stored,
total,
100.0 * stored as f64 / total as f64,
rate,
errors,
eta,
);
}
}
Err(e) => {
eprintln!("[ERROR] Embedding failed for {}: {}", chunk_id, e);
errors += 1;
}
}
}
let elapsed = start.elapsed();
println!(
"\nDone! {}/{} vectors stored ({} errors) in {:.1}s ({:.0} vec/s avg)",
stored,
total,
errors,
elapsed.as_secs_f64(),
stored as f64 / elapsed.as_secs_f64(),
);
Ok(())
}