memvid-rs 1.2.0

High-performance QR code video encoding for text storage and semantic retrieval
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! memvid-rs CLI application
//!
//! Command-line interface for the memvid-rs library.

use clap::{Parser, Subcommand};
use memvid_rs::{MemvidEncoder, MemvidRetriever};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "memvid-rs")]
#[command(
    about = "A high-performance QR code video encoder for text storage and semantic retrieval"
)]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Encode documents into a QR code video
    Encode {
        /// Input file(s) to encode
        #[arg(required = true)]
        inputs: Vec<PathBuf>,

        /// Output video file
        #[arg(short, long, default_value = "memory.mp4")]
        output: PathBuf,

        /// Output index file (SQLite database)
        #[arg(short, long, default_value = "memory_index.db")]
        index: PathBuf,

        /// Chunk size in characters
        #[arg(long, default_value = "1024")]
        chunk_size: usize,

        /// Overlap between chunks
        #[arg(long, default_value = "32")]
        overlap: usize,
    },

    /// Search within a QR code video
    Search {
        /// Video file to search
        #[arg(short, long)]
        video: PathBuf,

        /// Index file (SQLite database)
        #[arg(short, long)]
        index: PathBuf,

        /// Search query
        query: String,

        /// Number of results to return
        #[arg(short = 'k', long, default_value = "5")]
        top_k: usize,
    },

    /// Interactive chat with your documents
    Chat {
        /// Video file
        #[arg(short, long)]
        video: PathBuf,

        /// Index file (SQLite database)
        #[arg(short, long)]
        index: PathBuf,
    },

    /// Add new content to existing knowledge base (incremental update)
    Append {
        /// Existing video file to append to
        #[arg(short, long)]
        video: PathBuf,

        /// Existing index file (SQLite database)
        #[arg(short, long)]
        index: PathBuf,

        /// New input file(s) to add
        #[arg(required = true)]
        inputs: Vec<PathBuf>,
    },

    /// Store LLM conversation history to knowledge base
    AppendConversation {
        /// Existing video file to append to
        #[arg(short, long)]
        video: PathBuf,

        /// Existing index file (SQLite database)
        #[arg(short, long)]
        index: PathBuf,

        /// Conversation history file (JSON format: [{"human": "...", "assistant": "..."}])
        #[arg(short, long)]
        conversation_file: PathBuf,
    },
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    env_logger::init();

    let cli = Cli::parse();

    match cli.command {
        Commands::Encode {
            inputs,
            output,
            index,
            chunk_size: _,
            overlap: _,
        } => {
            encode_command(inputs, output, index).await?;
        }
        Commands::Search {
            video,
            index,
            query,
            top_k,
        } => {
            search_command(video, index, query, top_k).await?;
        }
        Commands::Chat { video, index } => {
            chat_command(video, index).await?;
        }
        Commands::Append {
            video,
            index,
            inputs,
        } => {
            append_command(video, index, inputs).await?;
        }
        Commands::AppendConversation {
            video,
            index,
            conversation_file,
        } => {
            append_conversation_command(video, index, conversation_file).await?;
        }
    }

    Ok(())
}

async fn encode_command(
    inputs: Vec<PathBuf>,
    output: PathBuf,
    index: PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("🎬 Starting memvid encoding...");

    let mut encoder = MemvidEncoder::new(None).await?;

    for input in inputs {
        println!("📄 Processing: {}", input.display());

        if !input.exists() {
            eprintln!("❌ File not found: {}", input.display());
            continue;
        }

        match input.extension().and_then(|ext| ext.to_str()) {
            Some("pdf") => {
                encoder.add_pdf(&input).await?;
            }
            Some("txt") | Some("md") | Some("markdown") => {
                encoder.add_text_file(&input).await?;
            }
            _ => {
                // Try to read as text file
                match encoder.add_text_file(&input).await {
                    Ok(_) => {}
                    Err(e) => {
                        eprintln!("❌ Failed to process {}: {}", input.display(), e);
                        continue;
                    }
                }
            }
        }
    }

    if encoder.chunk_count() == 0 {
        eprintln!("❌ No content was successfully processed");
        return Ok(());
    }

    println!("🔧 Building video with {} chunks...", encoder.chunk_count());

    let stats = encoder
        .build_video(output.to_str().unwrap(), index.to_str().unwrap())
        .await?;

    println!("✅ Encoding complete!");
    println!("   📊 Chunks: {}", stats.total_chunks);
    println!("   🎞️  Frames: {}", stats.total_frames);
    println!("   ⏱️  Time: {:.2}s", stats.processing_time);
    println!("   📹 Video: {}", output.display());
    println!("   📋 Index: {}", index.display());

    Ok(())
}

async fn search_command(
    video: PathBuf,
    index: PathBuf,
    query: String,
    top_k: usize,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("🔍 Searching for: \"{}\"", query);

    let mut retriever = MemvidRetriever::new(&video, &index).await?;
    let results = retriever.search(&query, top_k).await?;

    if results.is_empty() {
        println!("❌ No results found");
        return Ok(());
    }

    println!("📋 Found {} results:", results.len());
    println!();

    for (i, (score, text)) in results.iter().enumerate() {
        println!("{}. Score: {:.3}", i + 1, score);
        println!("   {}", text);
        println!();
    }

    Ok(())
}

async fn chat_command(video: PathBuf, index: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("💬 Starting interactive chat mode...");
    println!("   Type 'quit' or 'exit' to end the session");
    println!();

    let mut retriever = MemvidRetriever::new(&video, &index).await?;

    loop {
        print!("❓ Query: ");
        use std::io::{self, Write};
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        let input = input.trim();

        if input.is_empty() {
            continue;
        }

        if input == "quit" || input == "exit" {
            println!("👋 Goodbye!");
            break;
        }

        let results = retriever.search(input, 3).await?;

        if results.is_empty() {
            println!("❌ No results found for: \"{}\"", input);
        } else {
            println!("📋 Results:");
            for (i, (score, text)) in results.iter().enumerate() {
                println!("{}. (Score: {:.3}) {}", i + 1, score, text);
            }
        }
        println!();
    }

    Ok(())
}

async fn append_command(
    video: PathBuf,
    index: PathBuf,
    inputs: Vec<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("🎬 Starting incremental update...");

    // Verify existing files exist
    if !video.exists() {
        eprintln!("❌ Existing video file not found: {}", video.display());
        return Ok(());
    }
    if !index.exists() {
        eprintln!("❌ Existing index file not found: {}", index.display());
        return Ok(());
    }

    let mut encoder = MemvidEncoder::new(None).await?;
    let mut total_added_chunks = 0;
    let mut total_processing_time = 0.0;

    for input in inputs {
        println!("📄 Processing: {}", input.display());

        if !input.exists() {
            eprintln!("❌ File not found: {}", input.display());
            continue;
        }

        let start_time = std::time::Instant::now();

        // Use append_document_chunks for each file - this handles the incremental update correctly
        let stats = match encoder
            .append_document_chunks(
                video.to_str().unwrap(),
                index.to_str().unwrap(),
                input.to_str().unwrap(),
            )
            .await
        {
            Ok(stats) => stats,
            Err(e) => {
                eprintln!("❌ Failed to process {}: {}", input.display(), e);
                continue;
            }
        };

        total_added_chunks += stats.total_chunks;
        total_processing_time += stats.processing_time;

        println!(
            "   ✅ Added {} chunks from {} in {:.2}s",
            stats.total_chunks,
            input.display(),
            start_time.elapsed().as_secs_f64()
        );
    }

    if total_added_chunks == 0 {
        eprintln!("❌ No content was successfully processed");
        return Ok(());
    }

    println!("✅ Incremental update complete!");
    println!("   📊 Total added chunks: {}", total_added_chunks);
    println!("   🎞️  Total added frames: {}", total_added_chunks);
    println!("   ⏱️  Total time: {:.2}s", total_processing_time);
    println!("   📹 Updated video: {}", video.display());
    println!("   📋 Updated index: {}", index.display());

    Ok(())
}

async fn append_conversation_command(
    video: PathBuf,
    index: PathBuf,
    conversation_file: PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("🎬 Starting conversation history append...");

    // Verify existing files exist
    if !video.exists() {
        eprintln!("❌ Existing video file not found: {}", video.display());
        return Ok(());
    }
    if !index.exists() {
        eprintln!("❌ Existing index file not found: {}", index.display());
        return Ok(());
    }

    if !conversation_file.exists() {
        eprintln!(
            "❌ Conversation history file not found: {}",
            conversation_file.display()
        );
        return Ok(());
    }

    let mut encoder = MemvidEncoder::new(None).await?;

    println!("📄 Processing conversation history file...");

    // Try to parse as JSON conversation format first
    let file_content = std::fs::read_to_string(&conversation_file)?;

    // TODO: For now, parse JSON conversations
    // Expected format: [{"human": "...", "assistant": "..."}, ...]
    if let Ok(json_conversations) = serde_json::from_str::<Vec<serde_json::Value>>(&file_content) {
        let mut conversations = Vec::new();

        for conv in json_conversations {
            if let (Some(human), Some(assistant)) = (
                conv.get("human").and_then(|v| v.as_str()),
                conv.get("assistant").and_then(|v| v.as_str()),
            ) {
                conversations.push((human.to_string(), assistant.to_string()));
            }
        }

        if !conversations.is_empty() {
            let stats = encoder
                .append_conversation_history(
                    video.to_str().unwrap(),
                    index.to_str().unwrap(),
                    conversations,
                )
                .await?;

            println!("✅ Conversation history append complete!");
            println!("   💬 Conversation turns: {}", stats.total_chunks / 2);
            println!("   📊 Total chunks: {}", stats.total_chunks);
            println!("   🎞️  Total frames: {}", stats.total_frames);
            println!("   ⏱️  Time: {:.2}s", stats.processing_time);
            println!("   📹 Updated video: {}", video.display());
            println!("   📋 Updated index: {}", index.display());
        } else {
            eprintln!("❌ No valid conversations found in JSON file");
        }
    } else {
        // Fallback: treat as plain text file
        println!("📄 JSON parsing failed, treating as plain text file...");
        let stats = encoder
            .append_document_chunks(
                video.to_str().unwrap(),
                index.to_str().unwrap(),
                conversation_file.to_str().unwrap(),
            )
            .await?;

        println!("✅ Conversation history append complete!");
        println!("   📊 Chunks: {}", stats.total_chunks);
        println!("   🎞️  Frames: {}", stats.total_frames);
        println!("   ⏱️  Time: {:.2}s", stats.processing_time);
        println!("   📹 Updated video: {}", video.display());
        println!("   📋 Updated index: {}", index.display());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cli_parsing() {
        // Test that CLI parsing works
        let cli = Cli::try_parse_from(&["memvid-rs", "encode", "test.txt"]);
        assert!(cli.is_ok());
    }
}