feat: backup architecture docs, source code, and scripts

This commit is contained in:
Warren
2026-04-25 17:15:45 +08:00
parent 59809dae1f
commit 1f84e5469f
368 changed files with 146329 additions and 261 deletions
+94
View File
@@ -0,0 +1,94 @@
use crate::core::config::OUTPUT_DIR;
use anyhow::{Context, Result};
use serde::Deserialize;
use sqlx::PgPool;
use std::fs;
use std::path::Path;
// --- 結構體定義 (對齊外部處理器產出格式) ---
#[derive(Debug, Deserialize)]
struct AsrSegment {
start: f64,
end: f64,
text: String,
}
#[derive(Debug, Deserialize)]
struct AsrxSegment {
start: f64,
end: f64,
speaker: String,
}
// --- 核心邏輯 ---
/// 執行 Rule 1 入庫
/// 讀取 asr.json 與 asrx.json,合併 Speaker 資訊,寫入 chunks_rule1
pub async fn ingest_rule1(pool: &PgPool, asset_uuid: &str, fps: f64) -> Result<usize> {
// 1. 讀取檔案
let asr_path = format!("{}/{}.asr.json", *OUTPUT_DIR, asset_uuid);
let asrx_path = format!("{}/{}.asrx.json", *OUTPUT_DIR, asset_uuid);
let asr_content = fs::read_to_string(&asr_path)
.with_context(|| format!("Failed to read ASR file: {}", asr_path))?;
let asrx_content = fs::read_to_string(&asrx_path)
.with_context(|| format!("Failed to read ASRX file: {}", asrx_path))?;
let asr_segments: Vec<AsrSegment> = serde_json::from_str(&asr_content)?;
let asrx_segments: Vec<AsrxSegment> = serde_json::from_str(&asrx_content)?;
let mut count = 0;
// 2. 交易處理
let mut tx = pool.begin().await?;
for seg in &asr_segments {
// 時間轉幀
let start_frame = (seg.start * fps).round() as i64;
let end_frame = (seg.end * fps).round() as i64;
// 3. 尋找重疊最多的 Speaker
let mut best_speaker: Option<String> = None;
let mut max_overlap = 0.0f64;
for spk in &asrx_segments {
let overlap = (seg.end.min(spk.end) - seg.start.max(spk.start)).max(0.0);
if overlap > max_overlap {
max_overlap = overlap;
best_speaker = Some(spk.speaker.clone());
}
}
let speaker_id = best_speaker.unwrap_or("UNKNOWN".to_string());
// 4. 寫入 DB
sqlx::query!(
r#"
INSERT INTO chunks_rule1 (
id, asset_uuid, start_frame, end_frame, content, speaker_id
) VALUES (
gen_random_uuid(), $1, $2, $3, $4, $5
)
"#,
asset_uuid,
start_frame,
end_frame,
seg.text,
speaker_id
)
.execute(&mut *tx)
.await?;
count += 1;
// 每 100 筆 Commit 一次 (可選優化)
if count % 500 == 0 {
tx.commit().await?;
tx = pool.begin().await?;
}
}
tx.commit().await?;
Ok(count)
}
+182
View File
@@ -0,0 +1,182 @@
use crate::core::config::OUTPUT_DIR;
use crate::core::llm::client::generate_5w1h_summary;
use anyhow::{Context, Result};
use serde::Deserialize;
use sqlx::PgPool;
use std::fs;
use tracing::{info, warn};
#[derive(Debug, Deserialize)]
struct CutScene {
scene_number: u32,
start_frame: u64,
end_frame: u64,
start_time: f64,
end_time: f64,
}
#[derive(Debug, Deserialize)]
struct CutResult {
scenes: Vec<CutScene>,
}
#[derive(Debug, Deserialize)]
struct AsrSegment {
start: f64,
end: f64,
text: String,
}
/// Executes Rule 3 Ingestion: Scene-based Chunking with LLM 5W1H+ Summary.
/// 1. Reads CUT data to identify scenes.
/// 2. Aggregates Rule 1 (Sentence) chunks falling within each scene.
/// 3. Calls LLM to generate 5W1H+ summary.
/// 4. Inserts parent chunks into `dev.chunks`.
pub async fn ingest_rule3(pool: &PgPool, asset_uuid: &str) -> Result<usize> {
let cut_path = format!("{}/{}.cut.json", *OUTPUT_DIR, asset_uuid);
let asr_path = format!("{}/{}.asr.json", *OUTPUT_DIR, asset_uuid);
// 1. Load CUT and ASR data
let cut_content = fs::read_to_string(&cut_path)
.with_context(|| format!("Failed to read CUT file: {}", cut_path))?;
let cut_result: CutResult = serde_json::from_str(&cut_content).context("Invalid CUT JSON")?;
let asr_segments: Vec<AsrSegment> = match fs::read_to_string(&asr_path) {
Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
Err(_) => {
warn!("ASR file not found, proceeding with empty transcript for scenes");
vec![]
}
};
let mut count = 0;
let mut tx = pool.begin().await?;
// 2. Process each scene
for scene in &cut_result.scenes {
let chunk_id = format!("scene_{}", scene.scene_number);
// Aggregate text from Rule 1 chunks
let mut scene_text = String::new();
let mut child_ids: Vec<String> = Vec::new();
for seg in &asr_segments {
if seg.start >= scene.start_time && seg.end <= scene.end_time {
scene_text.push_str(&seg.text);
scene_text.push(' ');
// We'll look up the chunk_id from Rule 1 later if needed,
// but for now we just group by text overlap.
// A better approach is to query Rule 1 table for this range.
}
}
// Query Rule 1 table for better linking
let rule1_rows: Vec<(String,)> = sqlx::query_as(
r#"
SELECT id::text FROM chunks_rule1
WHERE asset_uuid = $1
AND start_frame >= $2
AND end_frame <= $3
"#,
)
.bind(asset_uuid)
.bind(scene.start_frame as i64)
.bind(scene.end_frame as i64)
.fetch_all(&mut *tx)
.await?;
for row in &rule1_rows {
child_ids.push(row.0.clone());
}
// Fallback to simple aggregation if query didn't get text (due to frame boundaries)
if scene_text.is_empty() {
// Try to grab text directly if rule1 table doesn't have it or boundaries differ
// But rule1 table has start_frame/end_frame which should match.
// Let's re-query text directly.
}
let texts: Vec<String> = sqlx::query_scalar(
r#"
SELECT content FROM chunks_rule1
WHERE asset_uuid = $1
AND start_frame >= $2
AND end_frame <= $3
ORDER BY start_frame ASC
"#,
)
.bind(asset_uuid)
.bind(scene.start_frame as i64)
.bind(scene.end_frame as i64)
.fetch_all(&mut *tx)
.await?;
let aggregated_text = texts.join(" ");
// 3. Call LLM for Summary
let summary = if !aggregated_text.is_empty() {
match generate_5w1h_summary(&aggregated_text).await {
Ok(s) => s,
Err(e) => {
warn!("LLM Summary failed for scene {}: {}", scene.scene_number, e);
"LLM Error".to_string()
}
}
} else {
"No Audio".to_string()
};
info!(
"Scene {}: {} -> {} ({} sentences)",
scene.scene_number,
scene.start_time,
scene.end_time,
texts.len()
);
// 4. Insert into dev.chunks
let fps_query: Option<f64> = sqlx::query_scalar("SELECT fps FROM videos WHERE uuid = $1")
.bind(asset_uuid)
.fetch_optional(&mut *tx)
.await?;
let fps = fps_query.unwrap_or(29.97);
// Prepare metadata JSON
let metadata = serde_json::json!({
"type": "scene",
"scene_number": scene.scene_number
});
sqlx::query(
r#"
INSERT INTO chunks (
uuid, chunk_id, chunk_index, chunk_type,
start_time, end_time, fps, start_frame, end_frame,
content, text_content, summary_text, metadata, child_chunk_ids
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (uuid, chunk_id) DO NOTHING
"#,
)
.bind(asset_uuid)
.bind(&chunk_id)
.bind(scene.scene_number as i32)
.bind("cut") // Chunk type
.bind(scene.start_time)
.bind(scene.end_time)
.bind(fps)
.bind(scene.start_frame as i64)
.bind(scene.end_frame as i64)
.bind(&metadata) // Content JSON
.bind(&aggregated_text) // Text content
.bind(&summary) // Summary
.bind(&metadata) // Metadata
.bind(&child_ids) // Child IDs
.execute(&mut *tx)
.await?;
count += 1;
}
tx.commit().await?;
Ok(count)
}
+755
View File
@@ -0,0 +1,755 @@
use crate::core::time::FrameTime;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ChunkType {
TimeBased,
Sentence,
Cut,
Trace,
Story, // Parent chunk from story analysis
Visual, // Visual object-based chunk from YOLO detection
}
impl ChunkType {
pub fn as_str(&self) -> &'static str {
match self {
ChunkType::TimeBased => "time",
ChunkType::Sentence => "sentence",
ChunkType::Cut => "cut",
ChunkType::Trace => "trace",
ChunkType::Story => "story",
ChunkType::Visual => "visual",
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ChunkRule {
Rule1, // 直接轉換
Rule2, // 集合內容
}
/// 關鍵幀的物件列表
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyframeObjects {
/// 關鍵幀時間 (秒)
pub timestamp: f64,
/// 關鍵幀幀號
pub frame_number: u64,
/// 檢測到的物件
pub objects: Vec<DetectedObject>,
}
/// 檢測到的物件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectedObject {
/// 物件類別名稱
pub class_name: String,
/// 物件類別 ID
pub class_id: u32,
/// 信心值 (0.0-1.0)
pub confidence: f32,
/// 邊界框 (x, y, width, height)
pub bbox: Option<BoundingBox>,
/// 出現次數 (在分片內)
pub occurrence: u32,
}
/// 邊界框
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisualChunkContent {
pub start_time: f64,
pub end_time: f64,
pub keyframe_objects: Vec<KeyframeObjects>,
pub dominant_objects: Vec<String>,
pub object_relationships: Vec<(String, String, String)>, // (object1, relationship, object2)
pub scene_description: Option<String>,
pub metadata: VisualMetadata,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisualMetadata {
pub object_count: u32,
pub unique_classes: Vec<String>,
pub max_confidence: f32,
pub avg_confidence: f32,
pub spatial_density: f32, // objects per frame
}
impl ChunkRule {
pub fn as_str(&self) -> &'static str {
match self {
ChunkRule::Rule1 => "rule_1",
ChunkRule::Rule2 => "rule_2",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Chunk {
pub file_id: i32,
pub uuid: String,
pub chunk_id: String,
pub chunk_index: u32,
pub chunk_type: ChunkType,
pub rule: ChunkRule,
/// Frames per second (can be fractional, e.g., 29.97, 23.976)
pub fps: f64,
/// Start frame (0-based)
pub start_frame: i64,
/// End frame (exclusive)
pub end_frame: i64,
pub text_content: Option<String>,
pub content: serde_json::Value,
pub metadata: Option<serde_json::Value>,
pub vector_id: Option<String>,
pub frame_count: i32,
pub pre_chunk_ids: Vec<i32>,
pub parent_chunk_id: Option<String>, // For parent-child chunk hierarchy
pub child_chunk_ids: Vec<String>, // Child chunk IDs (for parent chunks)
pub visual_stats: Option<serde_json::Value>,
}
id: i64,
video_id: i64,
yolo_result: &crate::core::processor::yolo::YoloResult,
min_frames_per_chunk: usize,
similarity_threshold: f32,
) -> Vec<Self> {
if yolo_result.frames.is_empty() {
return vec![];
}
let mut chunks = Vec::new();
let mut current_chunk_frames = Vec::new();
let mut current_id = id;
for (i, frame) in yolo_result.frames.iter().enumerate() {
if current_chunk_frames.is_empty() {
current_chunk_frames.push(frame);
continue;
}
// Check similarity with last frame in current chunk
let last_frame = current_chunk_frames.last().unwrap();
let similarity = VisualChunkContent::frame_similarity(last_frame, frame);
if similarity >= similarity_threshold && current_chunk_frames.len() < 100 {
// Similar enough, add to current chunk
current_chunk_frames.push(frame);
} else {
// Not similar enough or chunk too large, create new chunk
if current_chunk_frames.len() >= min_frames_per_chunk {
if let Some(chunk) =
Self::create_chunk_from_frames(current_id, video_id, &current_chunk_frames)
{
chunks.push(chunk);
current_id += 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::processor::yolo::{YoloFrame, YoloObject, YoloResult};
#[test]
fn test_chunk_type_visual_serialization() {
let chunk_type = ChunkType::Visual;
let json = serde_json::to_string(&chunk_type).unwrap();
assert_eq!(json, "\"visual\"");
let deserialized: ChunkType = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized, ChunkType::Visual);
}
#[test]
fn test_visual_chunk_creation() {
// Create a mock YOLO result
let yolo_result = YoloResult {
frame_count: 2,
fps: 30.0,
frames: vec![
YoloFrame {
frame: 0,
timestamp: 0.0,
objects: vec![
YoloObject {
class_name: "person".to_string(),
class_id: 0,
x: 100,
y: 200,
width: 50,
height: 100,
confidence: 0.95,
},
YoloObject {
class_name: "car".to_string(),
class_id: 2,
x: 300,
y: 150,
width: 80,
height: 60,
confidence: 0.87,
},
],
},
YoloFrame {
frame: 1,
timestamp: 0.033, // 1/30 second
objects: vec![YoloObject {
class_name: "person".to_string(),
class_id: 0,
x: 110,
y: 210,
width: 52,
height: 102,
confidence: 0.92,
}],
},
],
};
// Create visual chunk from YOLO result
let chunk = Chunk::from_yolo_result(1, 100, &yolo_result, 0, 1).unwrap();
// Verify chunk properties
assert_eq!(chunk.id, 1);
assert_eq!(chunk.video_id, 100);
assert_eq!(chunk.chunk_type, ChunkType::Visual);
assert_eq!(chunk.start_time, 0.0);
assert_eq!(chunk.end_time, 0.033);
// Verify visual content
if let ChunkContent::Visual(content) = chunk.content {
assert_eq!(content.metadata.object_count, 3);
assert_eq!(content.metadata.unique_classes.len(), 2);
assert!(content
.metadata
.unique_classes
.contains(&"person".to_string()));
assert!(content.metadata.unique_classes.contains(&"car".to_string()));
assert_eq!(content.dominant_objects, vec!["person"]);
assert_eq!(content.keyframe_objects.len(), 2);
} else {
panic!("Expected Visual content type");
}
}
#[test]
fn test_visual_chunk_content_methods() {
let content = VisualChunkContent {
start_time: 0.0,
end_time: 5.0,
keyframe_objects: vec![KeyframeObjects {
frame: 0,
timestamp: 0.0,
objects: vec![
DetectedObject {
class_name: "person".to_string(),
class_id: 0,
bounding_box: BoundingBox {
x: 100,
y: 200,
width: 50,
height: 100,
},
confidence: 0.95,
},
DetectedObject {
class_name: "car".to_string(),
class_id: 2,
bounding_box: BoundingBox {
x: 300,
y: 150,
width: 80,
height: 60,
},
confidence: 0.87,
},
],
}],
dominant_objects: vec!["person".to_string()],
object_relationships: vec![],
scene_description: Some("A person near a car".to_string()),
metadata: VisualMetadata {
object_count: 2,
unique_classes: vec!["person".to_string(), "car".to_string()],
max_confidence: 0.95,
avg_confidence: 0.91,
spatial_density: 2.0,
},
};
// Test summary method
let summary = content.summary();
assert!(summary.contains("Visual chunk from 0.0s to 5.0s"));
assert!(summary.contains("person"));
// Test contains_object method
assert!(content.contains_object("person"));
assert!(content.contains_object("car"));
assert!(!content.contains_object("dog"));
// Test high_confidence_objects method
let high_conf_objects = content.high_confidence_objects(0.9);
assert_eq!(high_conf_objects.len(), 1);
assert_eq!(high_conf_objects[0].class_name, "person");
}
#[test]
fn test_frame_similarity() {
let frame1 = YoloFrame {
frame: 0,
timestamp: 0.0,
objects: vec![
YoloObject {
class_name: "person".to_string(),
class_id: 0,
x: 100,
y: 200,
width: 50,
height: 100,
confidence: 0.95,
},
YoloObject {
class_name: "car".to_string(),
class_id: 2,
x: 300,
y: 150,
width: 80,
height: 60,
confidence: 0.87,
},
],
};
let frame2 = YoloFrame {
frame: 1,
timestamp: 0.033,
objects: vec![
YoloObject {
class_name: "person".to_string(),
class_id: 0,
x: 110,
y: 210,
width: 52,
height: 102,
confidence: 0.92,
},
YoloObject {
class_name: "car".to_string(),
class_id: 2,
x: 310,
y: 155,
width: 82,
height: 62,
confidence: 0.85,
},
],
};
let frame3 = YoloFrame {
frame: 2,
timestamp: 0.066,
objects: vec![YoloObject {
class_name: "dog".to_string(),
class_id: 16,
x: 150,
y: 250,
width: 40,
height: 60,
confidence: 0.78,
}],
};
// Test similar frames (same objects)
let similarity_same =
VisualChunkContent::frame_similarity(&frame1, &frame2);
assert!((similarity_same - 1.0).abs() < 0.001);
// Test dissimilar frames (different objects)
let similarity_diff =
VisualChunkContent::frame_similarity(&frame1, &frame3);
assert!((similarity_diff - 0.0).abs() < 0.001);
// Test empty frames
let empty_frame = YoloFrame {
frame: 3,
timestamp: 0.1,
objects: vec![],
};
let similarity_empty =
VisualChunkContent::frame_similarity(&empty_frame, &empty_frame);
assert!((similarity_empty - 1.0).abs() < 0.001);
let similarity_mixed =
VisualChunkContent::frame_similarity(&empty_frame, &frame1);
assert!((similarity_mixed - 0.0).abs() < 0.001);
}
}
current_chunk_frames = vec![frame];
}
}
// Handle last chunk
if current_chunk_frames.len() >= min_frames_per_chunk {
if let Some(chunk) =
Self::create_chunk_from_frames(current_id, video_id, &current_chunk_frames)
{
chunks.push(chunk);
}
}
chunks
}
fn create_chunk_from_frames(
id: i64,
video_id: i64,
frames: &[&crate::core::processor::yolo::YoloFrame],
) -> Option<Self> {
if frames.is_empty() {
return None;
}
// Simple conversion - could use the from_yolo_result method
let start_frame = frames.first().unwrap().frame;
let end_frame = frames.last().unwrap().frame;
let dummy_yolo_result = crate::core::processor::yolo::YoloResult {
frame_count: frames.len() as u64,
fps: 0.0, // Not used in this context
frames: frames.iter().map(|f| (*f).clone()).collect(),
};
Self::from_yolo_result(id, video_id, &dummy_yolo_result, start_frame, end_frame)
}
/// Creates a new chunk from seconds (legacy conversion).
///
/// This is useful for migrating from older systems that store time as seconds.
/// The frame counts are calculated by rounding `seconds * fps`.
#[allow(clippy::too_many_arguments)]
pub fn from_seconds(
file_id: i32,
uuid: String,
chunk_index: u32,
chunk_type: ChunkType,
rule: ChunkRule,
start_time: f64,
end_time: f64,
fps: f64,
content: serde_json::Value,
) -> Self {
let start_frame = (start_time * fps).round() as i64;
let end_frame = (end_time * fps).round() as i64;
Self::new(
file_id,
uuid,
chunk_index,
chunk_type,
rule,
start_frame,
end_frame,
fps,
content,
)
}
/// Returns the start time as a `FrameTime`.
pub fn start_time(&self) -> FrameTime {
FrameTime::from_frames(self.start_frame, self.fps)
}
/// Returns the end time as a `FrameTime`.
pub fn end_time(&self) -> FrameTime {
FrameTime::from_frames(self.end_frame, self.fps)
}
/// Returns the duration in frames.
pub fn duration_frames(&self) -> i64 {
self.end_frame - self.start_frame
}
/// Returns the duration in seconds.
pub fn duration_seconds(&self) -> f64 {
self.duration_frames() as f64 / self.fps
}
/// Formats the start time as "seconds.frame" (e.g., "123.04").
pub fn format_start_sec_frame(&self) -> String {
self.start_time().format_sec_frame()
}
/// Formats the end time as "seconds.frame" (e.g., "456.15").
pub fn format_end_sec_frame(&self) -> String {
self.end_time().format_sec_frame()
}
/// Formats the start time as "HH:MM:SS".
pub fn format_start_hms(&self) -> String {
self.start_time().format_hms()
}
/// Formats the end time as "HH:MM:SS".
pub fn format_end_hms(&self) -> String {
self.end_time().format_hms()
}
/// Formats the start time as "HH:MM:SS.FF".
pub fn format_start_hms_frame(&self) -> String {
self.start_time().format_hms_frame()
}
/// Formats the end time as "HH:MM:SS.FF".
pub fn format_end_hms_frame(&self) -> String {
self.end_time().format_hms_frame()
}
/// Returns a tuple of (start_seconds, end_seconds) for compatibility.
///
/// This is provided for backward compatibility during migration.
/// Prefer using `start_time()` and `end_time()` methods.
pub fn time_range_seconds(&self) -> (f64, f64) {
(self.start_time().seconds(), self.end_time().seconds())
}
pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
self.metadata = Some(metadata);
self
}
pub fn with_vector_id(mut self, vector_id: String) -> Self {
self.vector_id = Some(vector_id);
self
}
pub fn with_text_content(mut self, text: String) -> Self {
self.text_content = Some(text);
self
}
pub fn with_frame_count(mut self, count: i32) -> Self {
self.frame_count = count;
self
}
pub fn with_pre_chunk_ids(mut self, ids: Vec<i32>) -> Self {
self.pre_chunk_ids = ids;
self
}
pub fn with_parent_chunk_id(mut self, parent_id: String) -> Self {
self.parent_chunk_id = Some(parent_id);
self
}
pub fn with_child_chunk_ids(mut self, child_ids: Vec<String>) -> Self {
self.child_chunk_ids = child_ids;
self
}
pub fn is_parent_chunk(&self) -> bool {
!self.child_chunk_ids.is_empty()
}
pub fn is_child_chunk(&self) -> bool {
self.parent_chunk_id.is_some()
}
/// 創建視覺分片
pub fn new_visual(
file_id: i32,
uuid: String,
chunk_index: u32,
start_frame: i64,
end_frame: i64,
fps: f64,
visual_content: VisualChunkContent,
) -> Self {
let content = serde_json::to_value(&visual_content)
.unwrap_or_else(|_| serde_json::json!({"error": "Failed to serialize visual content"}));
Self::new(
file_id,
uuid,
chunk_index,
ChunkType::Visual,
ChunkRule::Rule2,
start_frame,
end_frame,
fps,
content,
)
}
/// 從 YOLO 結果創建視覺分片
pub fn from_yolo_result(
file_id: i32,
uuid: String,
chunk_index: u32,
start_frame: i64,
end_frame: i64,
fps: f64,
yolo_frames: Vec<crate::core::processor::yolo::YoloFrame>,
) -> Self {
use crate::core::processor::yolo::YoloFrame;
use std::collections::HashMap;
// 分析物件統計
let mut object_counts = HashMap::new();
let mut keyframe_objects = Vec::new();
let mut all_objects = Vec::new();
for frame in &yolo_frames {
let mut frame_objects = Vec::new();
for obj in &frame.objects {
// 更新物件統計
*object_counts.entry(obj.class_name.clone()).or_insert(0) += 1;
// 創建檢測到的物件
let detected_obj = DetectedObject {
class_name: obj.class_name.clone(),
class_id: obj.class_id,
confidence: obj.confidence,
bbox: Some(BoundingBox {
x: obj.x,
y: obj.y,
width: obj.width,
height: obj.height,
}),
occurrence: 1,
};
frame_objects.push(detected_obj.clone());
all_objects.push(detected_obj);
}
if !frame_objects.is_empty() {
keyframe_objects.push(KeyframeObjects {
timestamp: frame.timestamp,
frame_number: frame.frame,
objects: frame_objects,
});
}
}
// 創建主要物件標籤
let primary_objects = object_counts
.iter()
.filter(|(_, &count)| count >= 3) // 出現至少3次的物件
.map(|(name, _)| name.clone())
.collect::<Vec<_>>()
.join(", ");
// 創建物件統計 JSON
let object_stats =
serde_json::to_value(&object_counts).unwrap_or_else(|_| serde_json::json!({}));
// 創建視覺內容
let visual_content = VisualChunkContent {
primary_objects: if primary_objects.is_empty() {
"no objects detected".to_string()
} else {
primary_objects
},
object_stats,
keyframe_objects,
object_frequency: serde_json::to_value(&object_counts)
.unwrap_or_else(|_| serde_json::json!({})),
visual_summary: None, // 可選,後續可添加 LLM 生成的摘要
};
Self::new_visual(
file_id,
uuid,
chunk_index,
start_frame,
end_frame,
fps,
visual_content,
)
}
}
impl VisualChunkContent {
/// Calculate similarity between two YOLO frames based on object composition
pub fn frame_similarity(
frame1: &crate::core::processor::yolo::YoloFrame,
frame2: &crate::core::processor::yolo::YoloFrame,
) -> f32 {
if frame1.objects.is_empty() && frame2.objects.is_empty() {
return 1.0; // Both empty frames are perfectly similar
}
if frame1.objects.is_empty() || frame2.objects.is_empty() {
return 0.0; // One empty, one non-empty are dissimilar
}
// Create sets of object class names
let set1: std::collections::HashSet<String> = frame1
.objects
.iter()
.map(|o| o.class_name.clone())
.collect();
let set2: std::collections::HashSet<String> = frame2
.objects
.iter()
.map(|o| o.class_name.clone())
.collect();
// Calculate Jaccard similarity
let intersection: Vec<_> = set1.intersection(&set2).collect();
let union: Vec<_> = set1.union(&set2).collect();
if union.is_empty() {
0.0
} else {
intersection.len() as f32 / union.len() as f32
}
}
/// Get a summary of the visual chunk
pub fn summary(&self) -> String {
let duration = self.end_time - self.start_time;
let frame_count = self.keyframe_objects.len();
format!(
"Visual chunk from {:.1}s to {:.1}s (duration: {:.1}s, {} frames). Objects: {} total, {} unique. Dominant objects: {}",
self.start_time,
self.end_time,
duration,
frame_count,
self.metadata.object_count,
self.metadata.unique_classes.len(),
if self.dominant_objects.is_empty() {
"none".to_string()
} else {
self.dominant_objects.join(", ")
}
)
}
/// Check if this chunk contains a specific object class
pub fn contains_object(&self, class_name: &str) -> bool {
self.keyframe_objects
.iter()
.any(|ko| ko.objects.iter().any(|obj| obj.class_name == class_name))
}
/// Get all objects with confidence above threshold
pub fn high_confidence_objects(&self, threshold: f32) -> Vec<&DetectedObject> {
self.keyframe_objects
.iter()
.flat_map(|ko| ko.objects.iter())
.filter(|obj| obj.confidence >= threshold)
.collect()
}
}
+320
View File
@@ -0,0 +1,320 @@
use crate::core::time::FrameTime;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ChunkType {
TimeBased,
Sentence,
Cut,
Trace,
Story, // Parent chunk from story analysis
Visual, // Visual object-based chunk from YOLO detection (Phase 2.1)
}
impl ChunkType {
pub fn as_str(&self) -> &'static str {
match self {
ChunkType::TimeBased => "time",
ChunkType::Sentence => "sentence",
ChunkType::Cut => "cut",
ChunkType::Trace => "trace",
ChunkType::Story => "story",
ChunkType::Visual => "visual",
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ChunkRule {
Rule1, // 直接轉換
Rule2, // 集合內容
}
/// 關鍵幀的物件列表
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyframeObjects {
/// 關鍵幀時間 (秒)
pub timestamp: f64,
/// 關鍵幀幀號
pub frame_number: u64,
/// 檢測到的物件
pub objects: Vec<DetectedObject>,
}
/// 檢測到的物件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectedObject {
/// 物件類別名稱
pub class_name: String,
/// 物件類別 ID
pub class_id: u32,
/// 信心值 (0.0-1.0)
pub confidence: f32,
/// 邊界框 (x, y, width, height)
pub bbox: Option<BoundingBox>,
/// 出現次數 (在分片內)
pub occurrence: u32,
}
/// 邊界框
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundingBox {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
}
/// 視覺分片內容 (Phase 2.1)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisualChunkContent {
pub start_time: f64,
pub end_time: f64,
pub keyframe_objects: Vec<KeyframeObjects>,
pub dominant_objects: Vec<String>,
pub object_relationships: Vec<(String, String, String)>, // (object1, relationship, object2)
pub scene_description: Option<String>,
pub metadata: VisualMetadata,
}
/// 視覺元數據 (Phase 2.1)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisualMetadata {
pub object_count: u32,
pub unique_classes: Vec<String>,
pub max_confidence: f32,
pub avg_confidence: f32,
pub spatial_density: f32, // objects per frame
}
impl ChunkRule {
pub fn as_str(&self) -> &'static str {
match self {
ChunkRule::Rule1 => "rule_1",
ChunkRule::Rule2 => "rule_2",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Chunk {
pub file_id: i32,
pub uuid: String,
pub chunk_id: String,
pub chunk_index: u32,
pub chunk_type: ChunkType,
pub rule: ChunkRule,
/// Frames per second (can be fractional, e.g., 29.97, 23.976)
pub fps: f64,
/// Start frame (0-based)
pub start_frame: i64,
/// End frame (exclusive)
pub end_frame: i64,
pub text_content: Option<String>,
pub content: serde_json::Value,
pub metadata: Option<serde_json::Value>,
pub vector_id: Option<String>,
pub frame_count: i32,
pub pre_chunk_ids: Vec<i32>,
pub parent_chunk_id: Option<String>, // For parent-child chunk hierarchy
pub child_chunk_ids: Vec<String>, // Child chunk IDs (for parent chunks)
pub visual_stats: Option<serde_json::Value>,
}
impl Chunk {
/// 創建視覺分片 (Phase 2.1)
pub fn new_visual(
file_id: i32,
uuid: String,
chunk_index: u32,
start_frame: i64,
end_frame: i64,
fps: f64,
visual_content: VisualChunkContent,
) -> Self {
let content = serde_json::to_value(&visual_content)
.unwrap_or_else(|_| serde_json::json!({"error": "Failed to serialize visual content"}));
Self::new(
file_id,
uuid,
chunk_index,
ChunkType::Visual,
ChunkRule::Rule2,
start_frame,
end_frame,
fps,
content,
)
}
/// 從 YOLO 結果創建視覺分片 (Phase 2.1)
pub fn from_yolo_result(
file_id: i32,
uuid: String,
chunk_index: u32,
start_frame: i64,
end_frame: i64,
fps: f64,
yolo_frames: Vec<crate::core::processor::yolo::YoloFrame>,
) -> Self {
let keyframe_objects: Vec<KeyframeObjects> = yolo_frames
.iter()
.map(|frame| {
let objects: Vec<DetectedObject> = frame
.objects
.iter()
.map(|obj| DetectedObject {
class_name: obj.class_name.clone(),
class_id: obj.class_id,
confidence: obj.confidence,
bbox: Some(BoundingBox {
x: obj.x,
y: obj.y,
width: obj.width,
height: obj.height,
}),
occurrence: 1,
})
.collect();
KeyframeObjects {
timestamp: frame.timestamp,
frame_number: frame.frame,
objects,
}
})
.collect();
// 計算物件統計
let mut object_counts = std::collections::HashMap::new();
for obj in yolo_frames.iter().flat_map(|f| &f.objects) {
*object_counts.entry(obj.class_name.clone()).or_insert(0) += 1;
}
let total_objects: u32 = yolo_frames.iter().map(|f| f.objects.len() as u32).sum();
let all_classes: Vec<String> = yolo_frames
.iter()
.flat_map(|f| f.objects.iter().map(|o| o.class_name.clone()))
.collect();
let unique_classes: Vec<String> = all_classes
.iter()
.cloned()
.collect::<std::collections::HashSet<_>>()
.into_iter()
.collect();
let confidences: Vec<f32> = yolo_frames
.iter()
.flat_map(|f| f.objects.iter().map(|o| o.confidence))
.collect();
let max_confidence = confidences.iter().copied().fold(0.0f32, f32::max);
let avg_confidence = if !confidences.is_empty() {
confidences.iter().sum::<f32>() / confidences.len() as f32
} else {
0.0
};
// 找出主要物件
let primary_objects = object_counts
.iter()
.filter(|(_, &count)| count as f32 / yolo_frames.len() as f32 > 0.5)
.map(|(name, _)| name.clone())
.collect::<Vec<_>>()
.join(", ");
let object_stats =
serde_json::to_value(&object_counts).unwrap_or_else(|_| serde_json::json!({}));
let visual_content = VisualChunkContent {
start_time: if let Some(first) = yolo_frames.first() {
first.timestamp
} else {
0.0
},
end_time: if let Some(last) = yolo_frames.last() {
last.timestamp
} else {
0.0
},
keyframe_objects,
dominant_objects: primary_objects
.split(", ")
.map(|s| s.to_string())
.filter(|s| !s.is_empty())
.collect(),
object_relationships: vec![], // 可選:後續添加關係檢測
scene_description: None, // 可選:後續添加 LLM 生成的場景描述
metadata: VisualMetadata {
object_count: total_objects,
unique_classes,
max_confidence,
avg_confidence,
spatial_density: if yolo_frames.len() > 0 {
total_objects as f32 / yolo_frames.len() as f32
} else {
0.0
},
},
};
Self::new_visual(
file_id,
uuid,
chunk_index,
start_frame,
end_frame,
fps,
visual_content,
)
}
/// 創建新分片
pub fn new(
file_id: i32,
uuid: String,
chunk_index: u32,
chunk_type: ChunkType,
rule: ChunkRule,
start_frame: i64,
end_frame: i64,
fps: f64,
content: serde_json::Value,
) -> Self {
let frame_count = (end_frame - start_frame) as i32;
let chunk_id = format!("{}_{}", uuid, chunk_index);
Self {
file_id,
uuid,
chunk_id,
chunk_index,
chunk_type,
rule,
fps,
start_frame,
end_frame,
text_content: None,
content,
metadata: None,
vector_id: None,
frame_count,
pre_chunk_ids: vec![],
parent_chunk_id: None,
child_chunk_ids: vec![],
visual_stats: None,
}
}
/// 將分片轉換為幀時間
pub fn to_frame_time(&self) -> FrameTime {
FrameTime::from_frames(self.start_frame as u64, self.end_frame as u64, self.fps)
}
/// 檢查是否是父分片
pub fn is_parent(&self) -> bool {
self.parent_chunk_id.is_some()
}
}
+486
View File
@@ -0,0 +1,486 @@
//! 視覺分片測試
//!
//! 測試視覺分片數據結構和功能
use serde::{Deserialize, Serialize};
/// 視覺分片類型
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ChunkType {
TimeBased,
Sentence,
Cut,
Trace,
Story,
Visual,
}
/// 檢測到的物件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectedObject {
/// 物件類別名稱
pub class_name: String,
/// 物件類別 ID
pub class_id: u32,
/// 信心值 (0.0-1.0)
pub confidence: f32,
/// 邊界框 (x, y, width, height)
pub bbox: Option<(i32, i32, i32, i32)>,
}
/// 關鍵幀的物件列表
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyframeObjects {
/// 關鍵幀時間 (秒)
pub timestamp: f64,
/// 關鍵幀幀號
pub frame_number: u64,
/// 檢測到的物件
pub objects: Vec<DetectedObject>,
}
/// 視覺分片內容
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisualChunkContent {
pub start_time: f64,
pub end_time: f64,
pub keyframe_objects: Vec<KeyframeObjects>,
pub dominant_objects: Vec<String>,
pub object_relationships: Vec<(String, String, String)>, // (object1, relationship, object2)
pub scene_description: Option<String>,
pub metadata: VisualMetadata,
}
/// 視覺元數據
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisualMetadata {
pub object_count: u32,
pub unique_classes: Vec<String>,
pub max_confidence: f32,
pub avg_confidence: f32,
pub spatial_density: f32, // objects per frame
}
impl VisualChunkContent {
/// 計算兩個幀之間的相似度(基於物件組成)
pub fn frame_similarity(
frame1_objects: &[DetectedObject],
frame2_objects: &[DetectedObject],
) -> f32 {
if frame1_objects.is_empty() && frame2_objects.is_empty() {
return 1.0; // 兩個空幀完全相似
}
if frame1_objects.is_empty() || frame2_objects.is_empty() {
return 0.0; // 一個空一個非空,不相似
}
// 創建物件類別名稱集合
let set1: std::collections::HashSet<String> = frame1_objects
.iter()
.map(|o| o.class_name.clone())
.collect();
let set2: std::collections::HashSet<String> = frame2_objects
.iter()
.map(|o| o.class_name.clone())
.collect();
// 計算 Jaccard 相似度
let intersection: Vec<_> = set1.intersection(&set2).collect();
let union: Vec<_> = set1.union(&set2).collect();
if union.is_empty() {
0.0
} else {
intersection.len() as f32 / union.len() as f32
}
}
/// 獲取視覺分片的摘要
pub fn summary(&self) -> String {
let duration = self.end_time - self.start_time;
let frame_count = self.keyframe_objects.len();
format!(
"視覺分片: {:.1}s 到 {:.1}s (持續時間: {:.1}s, {} 幀). 物件: {} 個總計, {} 個唯一. 主要物件: {}",
self.start_time,
self.end_time,
duration,
frame_count,
self.metadata.object_count,
self.metadata.unique_classes.len(),
if self.dominant_objects.is_empty() {
"無".to_string()
} else {
self.dominant_objects.join(", ")
}
)
}
/// 檢查是否包含特定物件類別
pub fn contains_object(&self, class_name: &str) -> bool {
self.keyframe_objects
.iter()
.any(|ko| ko.objects.iter().any(|obj| obj.class_name == class_name))
}
/// 獲取信心值高於閾值的所有物件
pub fn high_confidence_objects(&self, threshold: f32) -> Vec<&DetectedObject> {
self.keyframe_objects
.iter()
.flat_map(|ko| ko.objects.iter())
.filter(|obj| obj.confidence >= threshold)
.collect()
}
}
/// 模擬 YOLO 結果
#[derive(Debug, Clone)]
pub struct MockYoloResult {
pub frames: Vec<MockYoloFrame>,
}
#[derive(Debug, Clone)]
pub struct MockYoloFrame {
pub frame: u64,
pub timestamp: f64,
pub objects: Vec<MockYoloObject>,
}
#[derive(Debug, Clone)]
pub struct MockYoloObject {
pub class_name: String,
pub class_id: u32,
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
pub confidence: f32,
}
impl MockYoloResult {
/// 從模擬 YOLO 結果創建視覺分片
pub fn to_visual_chunk(&self, start_frame: u64, end_frame: u64) -> Option<VisualChunkContent> {
let frames: Vec<_> = self
.frames
.iter()
.filter(|f| f.frame >= start_frame && f.frame <= end_frame)
.collect();
if frames.is_empty() {
return None;
}
// 轉換幀為關鍵幀物件
let keyframe_objects: Vec<KeyframeObjects> = frames
.iter()
.map(|frame| {
let objects: Vec<DetectedObject> = frame
.objects
.iter()
.map(|obj| DetectedObject {
class_name: obj.class_name.clone(),
class_id: obj.class_id,
confidence: obj.confidence,
bbox: Some((obj.x, obj.y, obj.width, obj.height)),
})
.collect();
KeyframeObjects {
timestamp: frame.timestamp,
frame_number: frame.frame,
objects,
}
})
.collect();
// 計算元數據
let total_objects: u32 = frames.iter().map(|f| f.objects.len() as u32).sum();
let all_classes: Vec<String> = frames
.iter()
.flat_map(|f| f.objects.iter().map(|o| o.class_name.clone()))
.collect();
let unique_classes: Vec<String> = all_classes
.iter()
.cloned()
.collect::<std::collections::HashSet<_>>()
.into_iter()
.collect();
let confidences: Vec<f32> = frames
.iter()
.flat_map(|f| f.objects.iter().map(|o| o.confidence))
.collect();
let max_confidence = confidences.iter().copied().fold(0.0f32, f32::max);
let avg_confidence = if !confidences.is_empty() {
confidences.iter().sum::<f32>() / confidences.len() as f32
} else {
0.0
};
let start_time = frames.first().map(|f| f.timestamp).unwrap_or(0.0);
let end_time = frames.last().map(|f| f.timestamp).unwrap_or(0.0);
// 查找主要物件(出現在大多數幀中的物件)
let mut object_counts = std::collections::HashMap::new();
for frame in &frames {
let frame_classes: std::collections::HashSet<_> =
frame.objects.iter().map(|o| o.class_name.clone()).collect();
for class in frame_classes {
*object_counts.entry(class).or_insert(0) += 1;
}
}
let mut dominant_objects: Vec<String> = object_counts
.into_iter()
.filter(|(_, count)| *count as f32 / frames.len() as f32 > 0.5) // 出現在 >50% 的幀中
.map(|(class, _)| class)
.collect();
dominant_objects.sort();
Some(VisualChunkContent {
start_time,
end_time,
keyframe_objects,
dominant_objects,
object_relationships: vec![], // 需要關係檢測邏輯
scene_description: None, // 可由 LLM 後期生成
metadata: VisualMetadata {
object_count: total_objects,
unique_classes,
max_confidence,
avg_confidence,
spatial_density: if frames.len() > 0 {
total_objects as f32 / frames.len() as f32
} else {
0.0
},
},
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_chunk_type_visual() {
let chunk_type = ChunkType::Visual;
let json = serde_json::to_string(&chunk_type).unwrap();
assert_eq!(json, "\"visual\"");
let deserialized: ChunkType = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized, ChunkType::Visual);
}
#[test]
fn test_visual_chunk_creation() {
// 創建模擬 YOLO 結果
let yolo_result = MockYoloResult {
frames: vec![
MockYoloFrame {
frame: 0,
timestamp: 0.0,
objects: vec![
MockYoloObject {
class_name: "person".to_string(),
class_id: 0,
x: 100,
y: 200,
width: 50,
height: 100,
confidence: 0.95,
},
MockYoloObject {
class_name: "car".to_string(),
class_id: 2,
x: 300,
y: 150,
width: 80,
height: 60,
confidence: 0.87,
},
],
},
MockYoloFrame {
frame: 1,
timestamp: 0.033, // 1/30 秒
objects: vec![MockYoloObject {
class_name: "person".to_string(),
class_id: 0,
x: 110,
y: 210,
width: 52,
height: 102,
confidence: 0.92,
}],
},
],
};
// 從 YOLO 結果創建視覺分片
let chunk = yolo_result.to_visual_chunk(0, 1).unwrap();
// 驗證分片屬性
assert_eq!(chunk.start_time, 0.0);
assert_eq!(chunk.end_time, 0.033);
assert_eq!(chunk.metadata.object_count, 3);
assert_eq!(chunk.metadata.unique_classes.len(), 2);
assert!(chunk
.metadata
.unique_classes
.contains(&"person".to_string()));
assert!(chunk.metadata.unique_classes.contains(&"car".to_string()));
assert_eq!(chunk.dominant_objects, vec!["person"]);
assert_eq!(chunk.keyframe_objects.len(), 2);
}
#[test]
fn test_visual_chunk_content_methods() {
let content = VisualChunkContent {
start_time: 0.0,
end_time: 5.0,
keyframe_objects: vec![KeyframeObjects {
timestamp: 0.0,
frame_number: 0,
objects: vec![
DetectedObject {
class_name: "person".to_string(),
class_id: 0,
confidence: 0.95,
bbox: Some((100, 200, 50, 100)),
},
DetectedObject {
class_name: "car".to_string(),
class_id: 2,
confidence: 0.87,
bbox: Some((300, 150, 80, 60)),
},
],
}],
dominant_objects: vec!["person".to_string()],
object_relationships: vec![],
scene_description: Some("一個人站在車旁".to_string()),
metadata: VisualMetadata {
object_count: 2,
unique_classes: vec!["person".to_string(), "car".to_string()],
max_confidence: 0.95,
avg_confidence: 0.91,
spatial_density: 2.0,
},
};
// 測試摘要方法
let summary = content.summary();
assert!(summary.contains("視覺分片"));
assert!(summary.contains("person"));
// 測試 contains_object 方法
assert!(content.contains_object("person"));
assert!(content.contains_object("car"));
assert!(!content.contains_object("dog"));
// 測試 high_confidence_objects 方法
let high_conf_objects = content.high_confidence_objects(0.9);
assert_eq!(high_conf_objects.len(), 1);
assert_eq!(high_conf_objects[0].class_name, "person");
}
#[test]
fn test_frame_similarity() {
let frame1_objects = vec![
DetectedObject {
class_name: "person".to_string(),
class_id: 0,
confidence: 0.95,
bbox: Some((100, 200, 50, 100)),
},
DetectedObject {
class_name: "car".to_string(),
class_id: 2,
confidence: 0.87,
bbox: Some((300, 150, 80, 60)),
},
];
let frame2_objects = vec![
DetectedObject {
class_name: "person".to_string(),
class_id: 0,
confidence: 0.92,
bbox: Some((110, 210, 52, 102)),
},
DetectedObject {
class_name: "car".to_string(),
class_id: 2,
confidence: 0.85,
bbox: Some((310, 155, 82, 62)),
},
];
let frame3_objects = vec![DetectedObject {
class_name: "dog".to_string(),
class_id: 16,
confidence: 0.78,
bbox: Some((150, 250, 40, 60)),
}];
// 測試相似幀(相同物件)
let similarity_same =
VisualChunkContent::frame_similarity(&frame1_objects, &frame2_objects);
assert!((similarity_same - 1.0).abs() < 0.001);
// 測試不相似幀(不同物件)
let similarity_diff =
VisualChunkContent::frame_similarity(&frame1_objects, &frame3_objects);
assert!((similarity_diff - 0.0).abs() < 0.001);
// 測試空幀
let empty_objects: Vec<DetectedObject> = vec![];
let similarity_empty = VisualChunkContent::frame_similarity(&empty_objects, &empty_objects);
assert!((similarity_empty - 1.0).abs() < 0.001);
let similarity_mixed =
VisualChunkContent::frame_similarity(&empty_objects, &frame1_objects);
assert!((similarity_mixed - 0.0).abs() < 0.001);
}
#[test]
fn test_serialization_deserialization() {
let content = VisualChunkContent {
start_time: 0.0,
end_time: 5.0,
keyframe_objects: vec![KeyframeObjects {
timestamp: 0.0,
frame_number: 0,
objects: vec![DetectedObject {
class_name: "person".to_string(),
class_id: 0,
confidence: 0.95,
bbox: Some((100, 200, 50, 100)),
}],
}],
dominant_objects: vec!["person".to_string()],
object_relationships: vec![],
scene_description: Some("場景描述".to_string()),
metadata: VisualMetadata {
object_count: 1,
unique_classes: vec!["person".to_string()],
max_confidence: 0.95,
avg_confidence: 0.95,
spatial_density: 1.0,
},
};
// 序列化
let json = serde_json::to_string(&content).unwrap();
assert!(json.contains("person"));
assert!(json.contains("visual_chunk"));
// 反序列化
let deserialized: VisualChunkContent = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.start_time, 0.0);
assert_eq!(deserialized.end_time, 5.0);
assert_eq!(deserialized.dominant_objects, vec!["person"]);
}
}