feat: add template json

This commit is contained in:
imeepos
2025-08-15 13:41:17 +08:00
parent c37fff0d09
commit 247eebef9e
261 changed files with 89699 additions and 0 deletions

View File

@@ -0,0 +1,136 @@
use tvai_sdk::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Topaz Video AI SDK - Basic Usage Example");
println!("=========================================");
// Create a new SDK instance
let mut sdk = TvaiSdk::new();
// Example 1: Create templates using presets
println!("\n1. Creating templates using presets:");
let upscale_template = TemplatePresets::upscale_to_4k()?;
println!(" Created: {}", upscale_template.name);
let fps_template = TemplatePresets::convert_to_60fps()?;
println!(" Created: {}", fps_template.name);
let denoise_template = TemplatePresets::remove_noise()?;
println!(" Created: {}", denoise_template.name);
// Add templates to SDK
sdk.add_template(upscale_template.clone())?;
sdk.add_template(fps_template.clone())?;
sdk.add_template(denoise_template.clone())?;
println!(" Total templates loaded: {}", sdk.template_count());
// Example 2: Generate FFmpeg commands
println!("\n2. Generating FFmpeg commands:");
let input_file = "input_video.mp4";
let output_file = "output_video.mp4";
// Basic command generation
let command = sdk.generate_ffmpeg_command(&upscale_template, input_file, output_file)?;
println!(" Basic upscale command:");
println!(" {}", command);
// Command with GPU acceleration
let gpu_command = sdk.generate_ffmpeg_command_with_gpu(&upscale_template, input_file, "output_gpu.mp4", "0")?;
println!("\n GPU accelerated command:");
println!(" {}", gpu_command);
// Command with custom codec
let nvenc_command = sdk.generate_ffmpeg_command_with_codec(&upscale_template, input_file, "output_nvenc.mp4", "hevc_nvenc", Some(20))?;
println!("\n NVENC H.265 command:");
println!(" {}", nvenc_command);
// Example 3: Create custom template using builder
println!("\n3. Creating custom template:");
let custom_template = TemplateBuilder::new("Custom Enhancement")
.description("Custom video enhancement with multiple effects")
.author("Example User")
.enable_enhancement("prob-4")
.enhancement_params(25, 15, 5) // denoise=25, detail=15, sharpen=5
.enable_stabilization(70, 1) // smoothness=70, full frame
.enable_grain(3, 2) // grain amount=3, size=2
.output_settings(6, 0.0) // FHD output, original FPS
.build()?;
println!(" Created custom template: {}", custom_template.name);
println!(" Description: {}", custom_template.description);
println!(" Enhancement active: {}", custom_template.settings.enhance.active);
println!(" Stabilization active: {}", custom_template.settings.stabilize.active);
println!(" Grain active: {}", custom_template.settings.grain.active);
// Generate command for custom template
let custom_command = sdk.generate_ffmpeg_command(&custom_template, input_file, "custom_output.mp4")?;
println!("\n Custom template command:");
println!(" {}", custom_command);
// Example 4: Batch processing
println!("\n4. Batch processing:");
let input_files = vec![
"video1.mp4".to_string(),
"video2.mp4".to_string(),
"video3.mp4".to_string(),
"video4.mp4".to_string(),
];
let batch_commands = sdk.generate_batch_commands(&fps_template, &input_files, "./output")?;
println!(" Generated {} batch commands:", batch_commands.len());
for (i, command) in batch_commands.iter().enumerate() {
println!(" Batch {}: {}", i + 1, command);
}
// Example 5: Template validation
println!("\n5. Template validation:");
// Validate template for FFmpeg generation
match sdk.validate_template_for_ffmpeg(&upscale_template) {
Ok(()) => println!(" Upscale template is valid for FFmpeg generation"),
Err(e) => println!(" Validation error: {}", e),
}
// Example 6: Export and import templates
println!("\n6. Template export/import:");
// Export all templates to JSON
let json_export = sdk.export_templates_to_json()?;
println!(" Exported {} templates to JSON ({} bytes)", sdk.template_count(), json_export.len());
// Clear templates and import them back
sdk.clear_templates();
println!(" Cleared all templates. Count: {}", sdk.template_count());
let imported_count = sdk.import_templates_from_json(&json_export)?;
println!(" Imported {} templates from JSON. Count: {}", imported_count, sdk.template_count());
// Example 7: Template management
println!("\n7. Template management:");
// List all template names
let template_names = sdk.get_template_names();
println!(" Available templates:");
for name in template_names {
println!(" - {}", name);
}
// Find specific template
if let Some(template) = sdk.find_template("Upscale to 4K") {
println!(" Found template: {} (Author: {})", template.name, template.author);
}
// Check if template exists
println!(" Has 'Convert to 60 FPS' template: {}", sdk.has_template("Convert to 60 FPS"));
println!(" Has 'Non-existent' template: {}", sdk.has_template("Non-existent"));
println!("\n✅ Basic usage example completed successfully!");
Ok(())
}

View File

@@ -0,0 +1,183 @@
use tvai_sdk::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Topaz Video AI SDK - FFmpeg Command Generation Example");
println!("=====================================================");
let sdk = TvaiSdk::new();
// Example 1: Basic FFmpeg command generation
println!("\n1. Basic FFmpeg command generation:");
let upscale_template = TemplatePresets::upscale_to_4k()?;
let basic_command = sdk.generate_ffmpeg_command(&upscale_template, "input.mp4", "output_4k.mp4")?;
println!(" Template: {}", upscale_template.name);
println!(" Command: {}", basic_command);
// Example 2: Hardware acceleration commands
println!("\n2. Hardware acceleration commands:");
// NVIDIA GPU acceleration
let nvidia_command = sdk.generate_ffmpeg_command_with_gpu(&upscale_template, "input.mp4", "output_nvidia.mp4", "0")?;
println!(" NVIDIA GPU (device 0):");
println!(" {}", nvidia_command);
// Multi-GPU setup
let multi_gpu_command = sdk.generate_ffmpeg_command_with_gpu(&upscale_template, "input.mp4", "output_multi_gpu.mp4", "0.1")?;
println!("\n Multi-GPU (devices 0 and 1):");
println!(" {}", multi_gpu_command);
// Example 3: Different codec configurations
println!("\n3. Different codec configurations:");
// H.264 with NVENC
let h264_nvenc = sdk.generate_ffmpeg_command_with_codec(&upscale_template, "input.mp4", "output_h264_nvenc.mp4", "h264_nvenc", Some(20))?;
println!(" H.264 NVENC (CQ 20):");
println!(" {}", h264_nvenc);
// H.265 with NVENC
let h265_nvenc = sdk.generate_ffmpeg_command_with_codec(&upscale_template, "input.mp4", "output_h265_nvenc.mp4", "hevc_nvenc", Some(22))?;
println!("\n H.265 NVENC (CQ 22):");
println!(" {}", h265_nvenc);
// AMD AMF H.264
let h264_amf = sdk.generate_ffmpeg_command_with_codec(&upscale_template, "input.mp4", "output_h264_amf.mp4", "h264_amf", Some(25))?;
println!("\n H.264 AMF (QP 25):");
println!(" {}", h264_amf);
// Intel QSV H.264
let h264_qsv = sdk.generate_ffmpeg_command_with_codec(&upscale_template, "input.mp4", "output_h264_qsv.mp4", "h264_qsv", Some(23))?;
println!("\n H.264 QSV (Global Quality 23):");
println!(" {}", h264_qsv);
// Example 4: Different template types
println!("\n4. Commands for different template types:");
// Frame interpolation
let fps_template = TemplatePresets::convert_to_60fps()?;
let fps_command = sdk.generate_ffmpeg_command(&fps_template, "input_30fps.mp4", "output_60fps.mp4")?;
println!(" Frame interpolation (60 FPS):");
println!(" {}", fps_command);
// Noise removal
let denoise_template = TemplatePresets::remove_noise()?;
let denoise_command = sdk.generate_ffmpeg_command(&denoise_template, "noisy_input.mp4", "clean_output.mp4")?;
println!("\n Noise removal:");
println!(" {}", denoise_command);
// Video stabilization
let stabilize_template = TemplatePresets::stabilize_video()?;
let stabilize_command = sdk.generate_ffmpeg_command(&stabilize_template, "shaky_input.mp4", "stable_output.mp4")?;
println!("\n Video stabilization:");
println!(" {}", stabilize_command);
// Slow motion
let slowmo_template = TemplatePresets::slow_motion_4x()?;
let slowmo_command = sdk.generate_ffmpeg_command(&slowmo_template, "normal_speed.mp4", "slow_motion.mp4")?;
println!("\n 4x Slow motion:");
println!(" {}", slowmo_command);
// Example 5: Complex custom template
println!("\n5. Complex custom template:");
let complex_template = TemplateBuilder::new("Professional Enhancement")
.description("Professional video enhancement with multiple effects")
.enable_enhancement("prob-4")
.enhancement_params(30, 40, 20) // denoise=30, detail=40, sharpen=20
.enable_stabilization(75, 1) // high stabilization, full frame
.enable_frame_interpolation("chf-3", 1.0)
.output_settings(7, 60.0) // 4K at 60fps
.build()?;
let complex_command = sdk.generate_ffmpeg_command(&complex_template, "input_professional.mp4", "output_professional.mp4")?;
println!(" Complex template command:");
println!(" {}", complex_command);
// Example 6: Batch processing commands
println!("\n6. Batch processing commands:");
let input_files = vec![
"project/clip1.mp4".to_string(),
"project/clip2.mp4".to_string(),
"project/clip3.mp4".to_string(),
"project/clip4.mp4".to_string(),
"project/clip5.mp4".to_string(),
];
let batch_commands = sdk.generate_batch_commands(&upscale_template, &input_files, "project/output")?;
println!(" Generated {} batch commands:", batch_commands.len());
for (i, command) in batch_commands.iter().enumerate() {
println!(" Batch {}: {}", i + 1, command);
}
// Example 7: Using FFmpeg command builder for advanced scenarios
println!("\n7. Advanced FFmpeg command builder:");
// Create a custom command with multiple filters
let advanced_command = FfmpegCommandBuilder::new("input_advanced.mp4", "output_advanced.mp4")
.add_filter("tvai_up=model=ahq-12:scale=2:noise=0.3:details=0.2")
.add_filter("tvai_fi=model=chr-2:fps=60")
.add_filter("tvai_stb=model=ref-2:smoothness=8")
.codec("hevc_nvenc")
.quality(18)
.hardware_accel("cuda")
.custom_param("-preset slow")
.custom_param("-profile:v main10")
.build();
println!(" Advanced custom command:");
println!(" {}", advanced_command);
// Create a command for HDR content
let hdr_command = FfmpegCommandBuilder::new("input_hdr.mp4", "output_hdr.mp4")
.add_filter("tvai_up=model=hyp-1:scale=2:sdr_ip=0.65:hdr_ip_adjust=0.3:saturate=0.8")
.codec("hevc_nvenc")
.quality(16)
.custom_param("-color_primaries bt2020")
.custom_param("-color_trc smpte2084")
.custom_param("-colorspace bt2020nc")
.build();
println!("\n HDR processing command:");
println!(" {}", hdr_command);
// Example 8: Template validation for FFmpeg
println!("\n8. Template validation for FFmpeg generation:");
let templates_to_validate = vec![
TemplatePresets::upscale_to_4k()?,
TemplatePresets::convert_to_60fps()?,
TemplatePresets::remove_noise()?,
TemplatePresets::stabilize_video()?,
TemplatePresets::slow_motion_4x()?,
];
for template in &templates_to_validate {
match sdk.validate_template_for_ffmpeg(template) {
Ok(()) => println!(" ✅ '{}' is valid for FFmpeg generation", template.name),
Err(e) => println!(" ❌ '{}' validation failed: {}", template.name, e),
}
}
// Example 9: Performance optimization suggestions
println!("\n9. Performance optimization suggestions:");
println!(" For best performance:");
println!(" - Use GPU acceleration when available (device=0, device=0.1, etc.)");
println!(" - Choose appropriate codec based on your hardware:");
println!(" • NVIDIA: h264_nvenc, hevc_nvenc");
println!(" • AMD: h264_amf, hevc_amf");
println!(" • Intel: h264_qsv, hevc_qsv");
println!(" - Adjust quality settings based on content:");
println!(" • High quality: CQ/CRF 16-20");
println!(" • Balanced: CQ/CRF 20-25");
println!(" • Fast encoding: CQ/CRF 25-30");
println!(" - Use multiple instances for parallel processing on high-end GPUs");
println!(" - Consider VRAM usage with vram parameter (0.5-0.8 for shared systems)");
println!("\n✅ FFmpeg command generation example completed successfully!");
Ok(())
}

View File

@@ -0,0 +1,212 @@
use tvai_sdk::*;
use std::path::Path;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Topaz Video AI SDK - Template Management Example");
println!("===============================================");
// Create SDK instance
let mut sdk = TvaiSdk::new();
// Example 1: Load templates from directory
println!("\n1. Loading templates from directory:");
let template_dir = "template"; // Relative to current directory
if Path::new(template_dir).exists() {
match sdk.load_templates_from_dir(template_dir) {
Ok(()) => {
println!(" Successfully loaded templates from directory: {}", template_dir);
println!(" Total templates loaded: {}", sdk.template_count());
// List loaded templates
let template_names = sdk.get_template_names();
for name in template_names {
println!(" - {}", name);
}
},
Err(e) => {
println!(" Failed to load templates: {}", e);
println!(" Creating templates using presets instead...");
// Create some templates using presets
sdk.add_template(TemplatePresets::upscale_to_4k()?)?;
sdk.add_template(TemplatePresets::convert_to_60fps()?)?;
sdk.add_template(TemplatePresets::remove_noise()?)?;
sdk.add_template(TemplatePresets::stabilize_video()?)?;
sdk.add_template(TemplatePresets::slow_motion_4x()?)?;
println!(" Created {} preset templates", sdk.template_count());
}
}
} else {
println!(" Template directory '{}' not found, creating preset templates...", template_dir);
// Create preset templates
sdk.add_template(TemplatePresets::upscale_to_4k()?)?;
sdk.add_template(TemplatePresets::convert_to_60fps()?)?;
sdk.add_template(TemplatePresets::remove_noise()?)?;
sdk.add_template(TemplatePresets::stabilize_video()?)?;
sdk.add_template(TemplatePresets::slow_motion_4x()?)?;
sdk.add_template(TemplatePresets::comprehensive_enhancement()?)?;
println!(" Created {} preset templates", sdk.template_count());
}
// Example 2: Create and manage custom templates
println!("\n2. Creating custom templates:");
// Create a custom deinterlacing template
let deinterlace_template = TemplateBuilder::new("Deinterlace and Enhance")
.description("Deinterlace interlaced video and enhance quality")
.author("Template Manager")
.enable_enhancement("prob-4")
.enhancement_params(20, 30, 15) // moderate denoise, high detail, some sharpen
.output_settings(6, 0.0) // FHD output
.build()?;
sdk.add_template(deinterlace_template)?;
println!(" Created: Deinterlace and Enhance");
// Create a film restoration template
let film_restore_template = TemplateBuilder::new("Film Restoration")
.description("Restore old film footage with comprehensive enhancement")
.author("Template Manager")
.enable_enhancement("prob-4")
.enhancement_params(40, 50, 20) // high denoise and detail for old film
.enable_stabilization(80, 1) // high stabilization for old footage
.enable_grain(2, 1) // subtle grain to maintain film look
.output_settings(7, 24.0) // 4K output at 24fps
.build()?;
sdk.add_template(film_restore_template)?;
println!(" Created: Film Restoration");
// Create a gaming video template
let gaming_template = TemplateBuilder::new("Gaming Video Enhancement")
.description("Optimize gaming footage for streaming")
.author("Template Manager")
.enable_enhancement("prob-4")
.enhancement_params(10, 25, 30) // low denoise, good detail, high sharpen
.enable_frame_interpolation("chf-3", 1.0)
.output_settings(6, 60.0) // FHD at 60fps
.build()?;
sdk.add_template(gaming_template)?;
println!(" Created: Gaming Video Enhancement");
println!(" Total templates after additions: {}", sdk.template_count());
// Example 3: Template inspection and modification
println!("\n3. Template inspection:");
if let Some(template) = sdk.find_template("Gaming Video Enhancement") {
println!(" Template: {}", template.name);
println!(" Description: {}", template.description);
println!(" Author: {}", template.author);
println!(" Version: {}", template.veai_version);
println!(" Settings:");
println!(" Enhancement active: {}", template.settings.enhance.active);
println!(" Enhancement model: {}", template.settings.enhance.model);
println!(" Denoise: {}", template.settings.enhance.denoise);
println!(" Detail: {}", template.settings.enhance.detail);
println!(" Sharpen: {}", template.settings.enhance.sharpen);
println!(" Frame interpolation active: {}", template.settings.slow_motion.active);
println!(" Output FPS: {}", template.settings.output.out_fps);
}
// Example 4: Template validation
println!("\n4. Template validation:");
let validation_errors = sdk.validate_all_templates();
if validation_errors.is_empty() {
println!(" ✅ All templates are valid");
} else {
println!(" ❌ Found validation errors:");
for (name, error) in validation_errors {
println!(" {}: {}", name, error);
}
}
// Example 5: Export templates to files
println!("\n5. Exporting templates:");
// Create output directory
let output_dir = "exported_templates";
std::fs::create_dir_all(output_dir)?;
// Save all templates to directory
match sdk.save_templates_to_dir(output_dir) {
Ok(()) => {
println!(" ✅ Successfully exported all templates to: {}", output_dir);
// List exported files
let entries = std::fs::read_dir(output_dir)?;
println!(" Exported files:");
for entry in entries {
let entry = entry?;
if entry.path().extension().and_then(|s| s.to_str()) == Some("json") {
println!(" - {}", entry.file_name().to_string_lossy());
}
}
},
Err(e) => println!(" ❌ Failed to export templates: {}", e),
}
// Example 6: Template removal and cleanup
println!("\n6. Template management operations:");
// Remove a specific template
if let Some(removed) = sdk.remove_template("Gaming Video Enhancement") {
println!(" Removed template: {}", removed.name);
println!(" Remaining templates: {}", sdk.template_count());
}
// Show remaining templates
println!(" Current templates:");
for name in sdk.get_template_names() {
println!(" - {}", name);
}
// Example 7: JSON export/import workflow
println!("\n7. JSON export/import workflow:");
// Export to JSON string
let json_data = sdk.export_templates_to_json()?;
println!(" Exported {} templates to JSON ({} bytes)", sdk.template_count(), json_data.len());
// Save JSON to file
let json_file = format!("{}/all_templates.json", output_dir);
std::fs::write(&json_file, &json_data)?;
println!(" Saved JSON to: {}", json_file);
// Clear all templates
let original_count = sdk.template_count();
sdk.clear_templates();
println!(" Cleared all templates (was: {}, now: {})", original_count, sdk.template_count());
// Import from JSON file
let imported_json = std::fs::read_to_string(&json_file)?;
let imported_count = sdk.import_templates_from_json(&imported_json)?;
println!(" Imported {} templates from JSON file", imported_count);
println!(" Final template count: {}", sdk.template_count());
// Example 8: Model mappings
println!("\n8. Model mappings:");
let mappings = sdk.get_model_mappings();
println!(" Current model mappings:");
for (template_model, ffmpeg_model) in mappings {
println!(" {} -> {}", template_model, ffmpeg_model);
}
// Add custom model mapping
sdk.add_model_mapping("custom-model-1".to_string(), "custom-ffmpeg-1".to_string());
println!(" Added custom model mapping: custom-model-1 -> custom-ffmpeg-1");
println!("\n✅ Template management example completed successfully!");
println!(" Final statistics:");
println!(" Total templates: {}", sdk.template_count());
println!(" Model mappings: {}", sdk.get_model_mappings().len());
Ok(())
}