Skip to main content

basic_translation/
basic_translation.rs

1//! 基本翻译示例
2//! 
3//! 演示如何使用HTML翻译库进行基本的HTML内容翻译
4
5use html_translation_lib::{TranslationConfig, HtmlTranslator, TranslationResult};
6
7#[tokio::main]
8async fn main() -> TranslationResult<()> {
9    // 初始化日志
10    tracing_subscriber::fmt::init();
11    
12    println!("HTML翻译库 - 基本使用示例");
13    println!("{}", "=".repeat(50));
14    
15    // 创建翻译配置
16    let config = TranslationConfig::new()
17        .target_language("zh")  // 翻译为中文
18        .api_url("http://localhost:1188/translate")  // DeepLX API地址
19        .enable_cache(true)     // 启用缓存
20        .batch_size(20)         // 批处理大小
21        .max_retries(3);        // 最大重试次数
22    
23    println!("✓ 翻译配置创建完成");
24    
25    // 创建翻译器
26    let mut translator = HtmlTranslator::new(config).await?;
27    println!("✓ 翻译器初始化完成");
28    
29    // 示例HTML内容 - 使用字符串连接来避免标识符冲突
30    let sample_html = format!(r##"
31    <!DOCTYPE html>
32    <html lang="en">
33    <head>
34        <meta charset="UTF-8">
35        <title>Welcome to Our Website</title>
36        <meta name="description" content="This is a sample webpage for translation testing">
37    </head>
38    <body>
39        <header>
40            <h1>Welcome to Our Amazing Website</h1>
41            <nav>
42                <a href="{}home" title="Go to home page">Home</a>
43                <a href="{}about" title="Learn about us">About</a>
44                <a href="{}contact" title="Get in touch">Contact</a>
45            </nav>
46        </header>
47        
48        <main>
49            <section id="hero">
50                <h2>Discover Something New Today</h2>
51                <p>We provide innovative solutions for your business needs. 
52                   Our team of experts is dedicated to helping you succeed.</p>
53                <button>Get Started Now</button>
54            </section>
55            
56            <section id="features">
57                <h3>Our Features</h3>
58                <div class="feature">
59                    <h4>Fast Performance</h4>
60                    <p>Lightning-fast load times for better user experience.</p>
61                </div>
62                <div class="feature">
63                    <h4>Secure & Reliable</h4>
64                    <p>Your data is protected with enterprise-grade security.</p>
65                </div>
66                <div class="feature">
67                    <h4>24/7 Support</h4>
68                    <p>Round-the-clock customer support whenever you need help.</p>
69                </div>
70            </section>
71            
72            <section id="contact">
73                <h3>Contact Us</h3>
74                <form>
75                    <label for="name">Your Name:</label>
76                    <input type="text" id="name" name="name" placeholder="Enter your name" required>
77                    
78                    <label for="email">Email Address:</label>
79                    <input type="email" id="email" name="email" placeholder="Enter your email" required>
80                    
81                    <label for="message">Message:</label>
82                    <textarea id="message" name="message" placeholder="Tell us how we can help you" required></textarea>
83                    
84                    <button type="submit">Send Message</button>
85                </form>
86            </section>
87        </main>
88        
89        <footer>
90            <p>&copy; 2024 Our Company. All rights reserved.</p>
91            <img src="logo.png" alt="Company Logo" title="Our company logo">
92        </footer>
93        
94        <script>
95            // This JavaScript code should not be translated
96            console.log('Page loaded successfully');
97        </script>
98    </body>
99    </html>
100    "##, "#", "#", "#");
101    
102    println!("\n原始HTML内容长度: {} 字符", sample_html.len());
103    
104    // 执行翻译
105    println!("\n🔄 开始翻译...");
106    let start_time = std::time::Instant::now();
107    
108    let translated_html = translator.translate_html(&sample_html).await?;
109    
110    let duration = start_time.elapsed();
111    println!("✅ 翻译完成!耗时: {:?}", duration);
112    
113    // 显示翻译统计
114    let stats = translator.get_stats();
115    println!("\n📊 翻译统计:");
116    println!("   - 收集文本数量: {}", stats.texts_collected);
117    println!("   - 过滤后文本数量: {}", stats.texts_filtered);
118    println!("   - 缓存命中: {}", stats.cache_hits);
119    println!("   - 缓存未命中: {}", stats.cache_misses);
120    println!("   - 缓存命中率: {:.1}%", stats.cache_hit_rate() * 100.0);
121    println!("   - 创建批次数量: {}", stats.batches_created);
122    println!("   - 处理时间: {:?}", stats.processing_time);
123    
124    // 保存翻译结果
125    std::fs::write("translated_example.html", &translated_html)?;
126    println!("\n💾 翻译结果已保存到: translated_example.html");
127    
128    // 显示部分翻译结果预览
129    let preview_length = 500;
130    let preview = if translated_html.len() > preview_length {
131        format!("{}...", &translated_html[..preview_length])
132    } else {
133        translated_html.clone()
134    };
135    
136    println!("\n📝 翻译结果预览:");
137    println!("{}", "=".repeat(60));
138    println!("{}", preview);
139    println!("{}", "=".repeat(60));
140    
141    // 对比原文和译文长度
142    println!("\n📏 长度对比:");
143    println!("   原文: {} 字符", sample_html.len());
144    println!("   译文: {} 字符", translated_html.len());
145    println!("   变化: {:.1}%", 
146             (translated_html.len() as f32 / sample_html.len() as f32 - 1.0) * 100.0);
147    
148    // 演示文件翻译
149    println!("\n🔄 演示文件翻译功能...");
150    std::fs::write("sample_input.html", &sample_html)?;
151    
152    translator.translate_file("sample_input.html", "sample_output.html").await?;
153    println!("✅ 文件翻译完成: sample_input.html → sample_output.html");
154    
155    println!("\n🎉 示例演示完成!");
156    
157    Ok(())
158}
159
160/// 辅助函数:显示库信息
161#[allow(dead_code)]
162fn show_library_info() {
163    let info = html_translation_lib::get_library_info();
164    println!("📚 库信息:");
165    println!("   名称: {}", info.name);
166    println!("   版本: {}", info.version);
167    println!("   启用特性: {:?}", info.features);
168}