Skip to main content

TranslationConfig

Struct TranslationConfig 

Source
pub struct TranslationConfig {
Show 17 fields pub source_language: String, pub target_language: String, pub api_url: String, pub enable_cache: bool, pub cache_ttl: Duration, pub max_cache_entries: usize, pub batch_size: usize, pub max_retries: usize, pub retry_delay_ms: u64, pub timeout_seconds: u64, pub use_indexing: bool, pub min_text_length: usize, pub skip_links: bool, pub skip_code_blocks: bool, pub custom_filters: Vec<String>, pub api_key: Option<String>, pub user_agent: String,
}
Expand description

翻译配置结构体

Fields§

§source_language: String

源语言代码 (ISO 639-1)

§target_language: String

目标语言代码 (ISO 639-1)

§api_url: String

翻译API的URL地址

§enable_cache: bool

是否启用缓存

§cache_ttl: Duration

缓存TTL (生存时间)

§max_cache_entries: usize

缓存最大条目数

§batch_size: usize

批处理大小

§max_retries: usize

最大重试次数

§retry_delay_ms: u64

重试延迟 (毫秒)

§timeout_seconds: u64

请求超时时间 (秒)

§use_indexing: bool

是否启用索引标记

§min_text_length: usize

最小翻译文本长度

§skip_links: bool

是否跳过链接文本

§skip_code_blocks: bool

是否跳过代码块

§custom_filters: Vec<String>

自定义过滤规则 (正则表达式)

§api_key: Option<String>

API认证密钥

§user_agent: String

用户代理字符串

Implementations§

Source§

impl TranslationConfig

Source

pub fn new() -> Self

创建新的配置实例

Examples found in repository?
examples/performance_test.rs (line 112)
51async fn main() -> Result<(), Box<dyn std::error::Error>> {
52    println!("🚀 HTML翻译库性能测试\n");
53    
54    let large_html = generate_large_html();
55    let dom = parse_html(&large_html);
56    
57    println!("📊 测试数据:");
58    println!("  - HTML大小: {} KB", large_html.len() / 1024);
59    println!("  - 包含 ~5000 个文本元素\n");
60    
61    // 1. DOM遍历性能测试
62    println!("🔍 DOM遍历性能对比:");
63    
64    // 原始递归收集器
65    let start = Instant::now();
66    let original_collector = TextCollector::new();
67    let original_items = original_collector.collect_from_dom(&dom)?;
68    let original_time = start.elapsed();
69    println!("  - 原始递归收集器: {}ms, 收集到 {} 项", 
70             original_time.as_millis(), original_items.len());
71    
72    // 优化的迭代收集器
73    let start = Instant::now();
74    let mut optimized_collector = OptimizedTextCollector::new();
75    let optimized_items = optimized_collector.collect_from_dom_optimized(&dom)?;
76    let optimized_time = start.elapsed();
77    println!("  - 优化迭代收集器: {}ms, 收集到 {} 项", 
78             optimized_time.as_millis(), optimized_items.len());
79    
80    let speedup = original_time.as_millis() as f64 / optimized_time.as_millis() as f64;
81    println!("  ✨ 性能提升: {:.2}x 倍速\n", speedup);
82    
83    // 2. 内存管理测试
84    println!("💾 内存管理优化:");
85    let memory_manager = Arc::new(GlobalMemoryManager::new());
86    
87    // 测试字符串池效率
88    let start = Instant::now();
89    let mut test_strings = Vec::new();
90    for i in 0..1000 {
91        let s = memory_manager.acquire_string(50);
92        test_strings.push(format!("Test string {}", i));
93    }
94    
95    for s in test_strings {
96        memory_manager.release_string(s);
97    }
98    let pool_time = start.elapsed();
99    
100    // 获取内存统计
101    let (pool_stats, _) = memory_manager.get_pool_stats();
102    println!("  - 字符串池操作: {}ms", pool_time.as_millis());
103    println!("  - 池大小: 小型={}, 大型={}, 总容量={}KB", 
104             pool_stats.small_pool_size,
105             pool_stats.large_pool_size, 
106             pool_stats.total_capacity / 1024);
107    
108    // 3. 智能缓存测试
109    println!("\n🧠 智能缓存性能:");
110    use html_translation_lib::config::TranslationConfig;
111    
112    let config = TranslationConfig::new()
113        .target_language("zh")
114        .api_url("http://example.com/translate");
115    
116    let mut cache_manager = SmartCacheManager::new(&config).await?;
117    
118    let start = Instant::now();
119    
120    // 模拟缓存操作
121    for i in 0..500 {
122        let key = format!("text_{}", i % 100); // 重复键以测试缓存命中
123        let value = format!("translation_{}", i);
124        cache_manager.set(&key, value).await?;
125    }
126    
127    // 测试缓存命中
128    let mut hits = 0;
129    for i in 0..100 {
130        let key = format!("text_{}", i);
131        if cache_manager.get(&key).await?.is_some() {
132            hits += 1;
133        }
134    }
135    
136    let cache_time = start.elapsed();
137    let cache_stats = cache_manager.stats();
138    
139    println!("  - 缓存操作时间: {}ms", cache_time.as_millis());
140    println!("  - 缓存命中数: {} / 100", hits);
141    println!("  - L1命中率: {:.1}%", cache_stats.l1_hit_rate() * 100.0);
142    println!("  - 总命中率: {:.1}%", cache_stats.hit_rate() * 100.0);
143    
144    // 4. 并发批处理测试
145    println!("\n⚡ 并发批处理性能:");
146    let batch_config = BatchConfig {
147        batch_size: 20,
148        max_concurrency: 4,
149        timeout_duration: std::time::Duration::from_secs(10),
150        ..Default::default()
151    };
152    
153    let batch_processor = ConcurrentBatchProcessor::new(
154        batch_config, 
155        Arc::clone(&memory_manager)
156    );
157    
158    // 准备测试文本
159    let test_texts: Vec<String> = (0..200)
160        .map(|i| format!("Test text number {}", i))
161        .collect();
162    
163    let start = Instant::now();
164    
165    // 提交批处理任务
166    let mut task_ids = Vec::new();
167    for chunk in test_texts.chunks(50) {
168        let task_id = batch_processor.submit_batch(
169            chunk.to_vec(), 
170            Priority::Normal
171        ).await?;
172        task_ids.push(task_id);
173    }
174    
175    // 模拟翻译函数
176    async fn mock_translate(texts: Vec<String>) -> html_translation_lib::error::TranslationResult<Vec<String>> {
177        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
178        Ok(texts.into_iter().map(|t| format!("翻译_{}", t)).collect())
179    }
180    
181    // 处理队列
182    let _results = batch_processor.process_queue(mock_translate).await?;
183    let batch_time = start.elapsed();
184    
185    let batch_stats = batch_processor.get_stats().await;
186    let queue_status = batch_processor.get_queue_status();
187    
188    println!("  - 批处理总时间: {}ms", batch_time.as_millis());
189    println!("  - 处理成功率: {:.1}%", batch_stats.success_rate() * 100.0);
190    println!("  - 平均处理时间: {}ms", batch_stats.average_processing_time().as_millis());
191    println!("  - 吞吐量: {:.1} 任务/秒", batch_stats.throughput());
192    println!("  - 队列剩余: {} 任务", queue_status.total_tasks);
193    
194    // 5. 总结
195    println!("\n📈 性能优化总结:");
196    println!("  ✅ DOM遍历优化: {:.1}x 性能提升", speedup);
197    println!("  ✅ 内存池管理: 减少 GC 压力");
198    println!("  ✅ 智能缓存: {:.1}% 命中率", cache_stats.hit_rate() * 100.0);
199    println!("  ✅ 并发批处理: {:.1}% 成功率", batch_stats.success_rate() * 100.0);
200    println!("\n🎉 所有性能优化测试完成!");
201    
202    Ok(())
203}
More examples
Hide additional examples
examples/basic_translation.rs (line 16)
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}
examples/monolith_integration.rs (line 104)
11async fn main() -> TranslationResult<()> {
12    tracing_subscriber::fmt::init();
13    
14    println!("HTML翻译库 - Monolith集成示例");
15    println!("{}", "=".repeat(50));
16    
17    // 模拟从网络获取的HTML内容 - 避免前缀标识符冲突
18    let html_content = format!(r##"
19    <!DOCTYPE html>
20    <html lang="en">
21    <head>
22        <meta charset="UTF-8">
23        <title>Product Documentation</title>
24        <link rel="stylesheet" href="styles.css">
25    </head>
26    <body>
27        <header>
28            <h1>Product Documentation</h1>
29            <p>Comprehensive guide for our product</p>
30        </header>
31        
32        <nav>
33            <ul>
34                <li><a href="{}getting-started">Getting Started</a></li>
35                <li><a href="{}features">Features</a></li>
36                <li><a href="{}api-reference">API Reference</a></li>
37                <li><a href="{}troubleshooting">Troubleshooting</a></li>
38            </ul>
39        </nav>
40        
41        <main>
42            <section id="getting-started">
43                <h2>Getting Started</h2>
44                <p>Follow these simple steps to begin using our product:</p>
45                <ol>
46                    <li>Download the latest version from our website</li>
47                    <li>Install the software on your system</li>
48                    <li>Run the initial configuration wizard</li>
49                    <li>Start exploring the features</li>
50                </ol>
51            </section>
52            
53            <section id="features">
54                <h2>Key Features</h2>
55                <div class="feature-grid">
56                    <div class="feature-card">
57                        <h3>Easy to Use</h3>
58                        <p>Intuitive interface designed for users of all skill levels.</p>
59                    </div>
60                    <div class="feature-card">
61                        <h3>High Performance</h3>
62                        <p>Optimized algorithms ensure fast processing times.</p>
63                    </div>
64                    <div class="feature-card">
65                        <h3>Extensible</h3>
66                        <p>Plugin architecture allows for custom functionality.</p>
67                    </div>
68                </div>
69            </section>
70            
71            <section id="api-reference">
72                <h2>API Reference</h2>
73                <p>Complete documentation of all available functions and methods.</p>
74                <code>
75                function processData(input) {{
76                    // Example function
77                    return input.map(item => item * 2);
78                }}
79                </code>
80            </section>
81        </main>
82        
83        <footer>
84            <p>© 2024 Company Name. All rights reserved.</p>
85        </footer>
86        
87        <script src="script.js"></script>
88    </body>
89    </html>
90    "##, "#", "#", "#", "#");
91    
92    println!("📄 原始HTML内容长度: {} 字符", html_content.len());
93    
94    // 步骤1: 解析HTML为DOM
95    println!("\n🔍 步骤1: 解析HTML为DOM...");
96    let dom = parse_document(RcDom::default(), Default::default())
97        .from_utf8()
98        .read_from(&mut html_content.as_bytes())?;
99    
100    println!("✅ HTML解析完成");
101    
102    // 步骤2: 配置翻译参数
103    println!("\n⚙️  步骤2: 配置翻译参数...");
104    let translation_config = TranslationConfig::new()
105        .target_language("zh")
106        .api_url("http://localhost:1188/translate")
107        .enable_cache(true)
108        .batch_size(15)
109        .max_retries(3);
110    
111    println!("✅ 翻译配置完成");
112    
113    // 步骤3: 在合并资源前翻译内容
114    println!("\n🔄 步骤3: 翻译DOM内容...");
115    let start_time = std::time::Instant::now();
116    
117    let translated_dom = translate_before_merge(dom, translation_config).await?;
118    
119    let translation_time = start_time.elapsed();
120    println!("✅ 翻译完成!耗时: {:?}", translation_time);
121    
122    // 步骤4: 将翻译后的DOM序列化为HTML
123    println!("\n📝 步骤4: 序列化翻译后的DOM...");
124    let translated_html = serialize_dom(&translated_dom)?;
125    
126    println!("✅ DOM序列化完成");
127    
128    // 步骤5: 保存翻译后的HTML(在实际使用中,这里会传给Monolith)
129    println!("\n💾 步骤5: 保存翻译结果...");
130    std::fs::write("translated_monolith_input.html", &translated_html)?;
131    println!("✅ 翻译后的HTML已保存到: translated_monolith_input.html");
132    
133    // 现在这个文件可以作为Monolith的输入
134    println!("\n🔧 集成说明:");
135    println!("   1. 翻译后的HTML文件: translated_monolith_input.html");
136    println!("   2. 现在可以使用Monolith处理此文件:");
137    println!("      monolith translated_monolith_input.html > final_output.html");
138    println!("   3. 最终输出将是翻译好的单文件HTML");
139    
140    // 显示处理统计
141    println!("\n📊 处理统计:");
142    println!("   - 原始内容长度: {} 字符", html_content.len());
143    println!("   - 翻译后长度: {} 字符", translated_html.len());
144    println!("   - 翻译用时: {:?}", translation_time);
145    println!("   - 长度变化: {:.1}%", 
146             (translated_html.len() as f32 / html_content.len() as f32 - 1.0) * 100.0);
147    
148    // 显示部分翻译结果预览
149    let preview_length = 800;
150    let preview = if translated_html.len() > preview_length {
151        format!("{}...", &translated_html[..preview_length])
152    } else {
153        translated_html.clone()
154    };
155    
156    println!("\n📝 翻译结果预览:");
157    println!("{}", "=".repeat(60));
158    println!("{}", preview);
159    println!("{}", "=".repeat(60));
160    
161    println!("\n🎉 Monolith集成示例完成!");
162    println!("   翻译后的文件现在可以用作Monolith的输入。");
163    
164    Ok(())
165}
Source

pub fn target_language(self, lang: &str) -> Self

设置目标语言

Examples found in repository?
examples/performance_test.rs (line 113)
51async fn main() -> Result<(), Box<dyn std::error::Error>> {
52    println!("🚀 HTML翻译库性能测试\n");
53    
54    let large_html = generate_large_html();
55    let dom = parse_html(&large_html);
56    
57    println!("📊 测试数据:");
58    println!("  - HTML大小: {} KB", large_html.len() / 1024);
59    println!("  - 包含 ~5000 个文本元素\n");
60    
61    // 1. DOM遍历性能测试
62    println!("🔍 DOM遍历性能对比:");
63    
64    // 原始递归收集器
65    let start = Instant::now();
66    let original_collector = TextCollector::new();
67    let original_items = original_collector.collect_from_dom(&dom)?;
68    let original_time = start.elapsed();
69    println!("  - 原始递归收集器: {}ms, 收集到 {} 项", 
70             original_time.as_millis(), original_items.len());
71    
72    // 优化的迭代收集器
73    let start = Instant::now();
74    let mut optimized_collector = OptimizedTextCollector::new();
75    let optimized_items = optimized_collector.collect_from_dom_optimized(&dom)?;
76    let optimized_time = start.elapsed();
77    println!("  - 优化迭代收集器: {}ms, 收集到 {} 项", 
78             optimized_time.as_millis(), optimized_items.len());
79    
80    let speedup = original_time.as_millis() as f64 / optimized_time.as_millis() as f64;
81    println!("  ✨ 性能提升: {:.2}x 倍速\n", speedup);
82    
83    // 2. 内存管理测试
84    println!("💾 内存管理优化:");
85    let memory_manager = Arc::new(GlobalMemoryManager::new());
86    
87    // 测试字符串池效率
88    let start = Instant::now();
89    let mut test_strings = Vec::new();
90    for i in 0..1000 {
91        let s = memory_manager.acquire_string(50);
92        test_strings.push(format!("Test string {}", i));
93    }
94    
95    for s in test_strings {
96        memory_manager.release_string(s);
97    }
98    let pool_time = start.elapsed();
99    
100    // 获取内存统计
101    let (pool_stats, _) = memory_manager.get_pool_stats();
102    println!("  - 字符串池操作: {}ms", pool_time.as_millis());
103    println!("  - 池大小: 小型={}, 大型={}, 总容量={}KB", 
104             pool_stats.small_pool_size,
105             pool_stats.large_pool_size, 
106             pool_stats.total_capacity / 1024);
107    
108    // 3. 智能缓存测试
109    println!("\n🧠 智能缓存性能:");
110    use html_translation_lib::config::TranslationConfig;
111    
112    let config = TranslationConfig::new()
113        .target_language("zh")
114        .api_url("http://example.com/translate");
115    
116    let mut cache_manager = SmartCacheManager::new(&config).await?;
117    
118    let start = Instant::now();
119    
120    // 模拟缓存操作
121    for i in 0..500 {
122        let key = format!("text_{}", i % 100); // 重复键以测试缓存命中
123        let value = format!("translation_{}", i);
124        cache_manager.set(&key, value).await?;
125    }
126    
127    // 测试缓存命中
128    let mut hits = 0;
129    for i in 0..100 {
130        let key = format!("text_{}", i);
131        if cache_manager.get(&key).await?.is_some() {
132            hits += 1;
133        }
134    }
135    
136    let cache_time = start.elapsed();
137    let cache_stats = cache_manager.stats();
138    
139    println!("  - 缓存操作时间: {}ms", cache_time.as_millis());
140    println!("  - 缓存命中数: {} / 100", hits);
141    println!("  - L1命中率: {:.1}%", cache_stats.l1_hit_rate() * 100.0);
142    println!("  - 总命中率: {:.1}%", cache_stats.hit_rate() * 100.0);
143    
144    // 4. 并发批处理测试
145    println!("\n⚡ 并发批处理性能:");
146    let batch_config = BatchConfig {
147        batch_size: 20,
148        max_concurrency: 4,
149        timeout_duration: std::time::Duration::from_secs(10),
150        ..Default::default()
151    };
152    
153    let batch_processor = ConcurrentBatchProcessor::new(
154        batch_config, 
155        Arc::clone(&memory_manager)
156    );
157    
158    // 准备测试文本
159    let test_texts: Vec<String> = (0..200)
160        .map(|i| format!("Test text number {}", i))
161        .collect();
162    
163    let start = Instant::now();
164    
165    // 提交批处理任务
166    let mut task_ids = Vec::new();
167    for chunk in test_texts.chunks(50) {
168        let task_id = batch_processor.submit_batch(
169            chunk.to_vec(), 
170            Priority::Normal
171        ).await?;
172        task_ids.push(task_id);
173    }
174    
175    // 模拟翻译函数
176    async fn mock_translate(texts: Vec<String>) -> html_translation_lib::error::TranslationResult<Vec<String>> {
177        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
178        Ok(texts.into_iter().map(|t| format!("翻译_{}", t)).collect())
179    }
180    
181    // 处理队列
182    let _results = batch_processor.process_queue(mock_translate).await?;
183    let batch_time = start.elapsed();
184    
185    let batch_stats = batch_processor.get_stats().await;
186    let queue_status = batch_processor.get_queue_status();
187    
188    println!("  - 批处理总时间: {}ms", batch_time.as_millis());
189    println!("  - 处理成功率: {:.1}%", batch_stats.success_rate() * 100.0);
190    println!("  - 平均处理时间: {}ms", batch_stats.average_processing_time().as_millis());
191    println!("  - 吞吐量: {:.1} 任务/秒", batch_stats.throughput());
192    println!("  - 队列剩余: {} 任务", queue_status.total_tasks);
193    
194    // 5. 总结
195    println!("\n📈 性能优化总结:");
196    println!("  ✅ DOM遍历优化: {:.1}x 性能提升", speedup);
197    println!("  ✅ 内存池管理: 减少 GC 压力");
198    println!("  ✅ 智能缓存: {:.1}% 命中率", cache_stats.hit_rate() * 100.0);
199    println!("  ✅ 并发批处理: {:.1}% 成功率", batch_stats.success_rate() * 100.0);
200    println!("\n🎉 所有性能优化测试完成!");
201    
202    Ok(())
203}
More examples
Hide additional examples
examples/basic_translation.rs (line 17)
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}
examples/monolith_integration.rs (line 105)
11async fn main() -> TranslationResult<()> {
12    tracing_subscriber::fmt::init();
13    
14    println!("HTML翻译库 - Monolith集成示例");
15    println!("{}", "=".repeat(50));
16    
17    // 模拟从网络获取的HTML内容 - 避免前缀标识符冲突
18    let html_content = format!(r##"
19    <!DOCTYPE html>
20    <html lang="en">
21    <head>
22        <meta charset="UTF-8">
23        <title>Product Documentation</title>
24        <link rel="stylesheet" href="styles.css">
25    </head>
26    <body>
27        <header>
28            <h1>Product Documentation</h1>
29            <p>Comprehensive guide for our product</p>
30        </header>
31        
32        <nav>
33            <ul>
34                <li><a href="{}getting-started">Getting Started</a></li>
35                <li><a href="{}features">Features</a></li>
36                <li><a href="{}api-reference">API Reference</a></li>
37                <li><a href="{}troubleshooting">Troubleshooting</a></li>
38            </ul>
39        </nav>
40        
41        <main>
42            <section id="getting-started">
43                <h2>Getting Started</h2>
44                <p>Follow these simple steps to begin using our product:</p>
45                <ol>
46                    <li>Download the latest version from our website</li>
47                    <li>Install the software on your system</li>
48                    <li>Run the initial configuration wizard</li>
49                    <li>Start exploring the features</li>
50                </ol>
51            </section>
52            
53            <section id="features">
54                <h2>Key Features</h2>
55                <div class="feature-grid">
56                    <div class="feature-card">
57                        <h3>Easy to Use</h3>
58                        <p>Intuitive interface designed for users of all skill levels.</p>
59                    </div>
60                    <div class="feature-card">
61                        <h3>High Performance</h3>
62                        <p>Optimized algorithms ensure fast processing times.</p>
63                    </div>
64                    <div class="feature-card">
65                        <h3>Extensible</h3>
66                        <p>Plugin architecture allows for custom functionality.</p>
67                    </div>
68                </div>
69            </section>
70            
71            <section id="api-reference">
72                <h2>API Reference</h2>
73                <p>Complete documentation of all available functions and methods.</p>
74                <code>
75                function processData(input) {{
76                    // Example function
77                    return input.map(item => item * 2);
78                }}
79                </code>
80            </section>
81        </main>
82        
83        <footer>
84            <p>© 2024 Company Name. All rights reserved.</p>
85        </footer>
86        
87        <script src="script.js"></script>
88    </body>
89    </html>
90    "##, "#", "#", "#", "#");
91    
92    println!("📄 原始HTML内容长度: {} 字符", html_content.len());
93    
94    // 步骤1: 解析HTML为DOM
95    println!("\n🔍 步骤1: 解析HTML为DOM...");
96    let dom = parse_document(RcDom::default(), Default::default())
97        .from_utf8()
98        .read_from(&mut html_content.as_bytes())?;
99    
100    println!("✅ HTML解析完成");
101    
102    // 步骤2: 配置翻译参数
103    println!("\n⚙️  步骤2: 配置翻译参数...");
104    let translation_config = TranslationConfig::new()
105        .target_language("zh")
106        .api_url("http://localhost:1188/translate")
107        .enable_cache(true)
108        .batch_size(15)
109        .max_retries(3);
110    
111    println!("✅ 翻译配置完成");
112    
113    // 步骤3: 在合并资源前翻译内容
114    println!("\n🔄 步骤3: 翻译DOM内容...");
115    let start_time = std::time::Instant::now();
116    
117    let translated_dom = translate_before_merge(dom, translation_config).await?;
118    
119    let translation_time = start_time.elapsed();
120    println!("✅ 翻译完成!耗时: {:?}", translation_time);
121    
122    // 步骤4: 将翻译后的DOM序列化为HTML
123    println!("\n📝 步骤4: 序列化翻译后的DOM...");
124    let translated_html = serialize_dom(&translated_dom)?;
125    
126    println!("✅ DOM序列化完成");
127    
128    // 步骤5: 保存翻译后的HTML(在实际使用中,这里会传给Monolith)
129    println!("\n💾 步骤5: 保存翻译结果...");
130    std::fs::write("translated_monolith_input.html", &translated_html)?;
131    println!("✅ 翻译后的HTML已保存到: translated_monolith_input.html");
132    
133    // 现在这个文件可以作为Monolith的输入
134    println!("\n🔧 集成说明:");
135    println!("   1. 翻译后的HTML文件: translated_monolith_input.html");
136    println!("   2. 现在可以使用Monolith处理此文件:");
137    println!("      monolith translated_monolith_input.html > final_output.html");
138    println!("   3. 最终输出将是翻译好的单文件HTML");
139    
140    // 显示处理统计
141    println!("\n📊 处理统计:");
142    println!("   - 原始内容长度: {} 字符", html_content.len());
143    println!("   - 翻译后长度: {} 字符", translated_html.len());
144    println!("   - 翻译用时: {:?}", translation_time);
145    println!("   - 长度变化: {:.1}%", 
146             (translated_html.len() as f32 / html_content.len() as f32 - 1.0) * 100.0);
147    
148    // 显示部分翻译结果预览
149    let preview_length = 800;
150    let preview = if translated_html.len() > preview_length {
151        format!("{}...", &translated_html[..preview_length])
152    } else {
153        translated_html.clone()
154    };
155    
156    println!("\n📝 翻译结果预览:");
157    println!("{}", "=".repeat(60));
158    println!("{}", preview);
159    println!("{}", "=".repeat(60));
160    
161    println!("\n🎉 Monolith集成示例完成!");
162    println!("   翻译后的文件现在可以用作Monolith的输入。");
163    
164    Ok(())
165}
Source

pub fn source_language(self, lang: &str) -> Self

设置源语言

Source

pub fn api_url(self, url: &str) -> Self

设置API URL

Examples found in repository?
examples/performance_test.rs (line 114)
51async fn main() -> Result<(), Box<dyn std::error::Error>> {
52    println!("🚀 HTML翻译库性能测试\n");
53    
54    let large_html = generate_large_html();
55    let dom = parse_html(&large_html);
56    
57    println!("📊 测试数据:");
58    println!("  - HTML大小: {} KB", large_html.len() / 1024);
59    println!("  - 包含 ~5000 个文本元素\n");
60    
61    // 1. DOM遍历性能测试
62    println!("🔍 DOM遍历性能对比:");
63    
64    // 原始递归收集器
65    let start = Instant::now();
66    let original_collector = TextCollector::new();
67    let original_items = original_collector.collect_from_dom(&dom)?;
68    let original_time = start.elapsed();
69    println!("  - 原始递归收集器: {}ms, 收集到 {} 项", 
70             original_time.as_millis(), original_items.len());
71    
72    // 优化的迭代收集器
73    let start = Instant::now();
74    let mut optimized_collector = OptimizedTextCollector::new();
75    let optimized_items = optimized_collector.collect_from_dom_optimized(&dom)?;
76    let optimized_time = start.elapsed();
77    println!("  - 优化迭代收集器: {}ms, 收集到 {} 项", 
78             optimized_time.as_millis(), optimized_items.len());
79    
80    let speedup = original_time.as_millis() as f64 / optimized_time.as_millis() as f64;
81    println!("  ✨ 性能提升: {:.2}x 倍速\n", speedup);
82    
83    // 2. 内存管理测试
84    println!("💾 内存管理优化:");
85    let memory_manager = Arc::new(GlobalMemoryManager::new());
86    
87    // 测试字符串池效率
88    let start = Instant::now();
89    let mut test_strings = Vec::new();
90    for i in 0..1000 {
91        let s = memory_manager.acquire_string(50);
92        test_strings.push(format!("Test string {}", i));
93    }
94    
95    for s in test_strings {
96        memory_manager.release_string(s);
97    }
98    let pool_time = start.elapsed();
99    
100    // 获取内存统计
101    let (pool_stats, _) = memory_manager.get_pool_stats();
102    println!("  - 字符串池操作: {}ms", pool_time.as_millis());
103    println!("  - 池大小: 小型={}, 大型={}, 总容量={}KB", 
104             pool_stats.small_pool_size,
105             pool_stats.large_pool_size, 
106             pool_stats.total_capacity / 1024);
107    
108    // 3. 智能缓存测试
109    println!("\n🧠 智能缓存性能:");
110    use html_translation_lib::config::TranslationConfig;
111    
112    let config = TranslationConfig::new()
113        .target_language("zh")
114        .api_url("http://example.com/translate");
115    
116    let mut cache_manager = SmartCacheManager::new(&config).await?;
117    
118    let start = Instant::now();
119    
120    // 模拟缓存操作
121    for i in 0..500 {
122        let key = format!("text_{}", i % 100); // 重复键以测试缓存命中
123        let value = format!("translation_{}", i);
124        cache_manager.set(&key, value).await?;
125    }
126    
127    // 测试缓存命中
128    let mut hits = 0;
129    for i in 0..100 {
130        let key = format!("text_{}", i);
131        if cache_manager.get(&key).await?.is_some() {
132            hits += 1;
133        }
134    }
135    
136    let cache_time = start.elapsed();
137    let cache_stats = cache_manager.stats();
138    
139    println!("  - 缓存操作时间: {}ms", cache_time.as_millis());
140    println!("  - 缓存命中数: {} / 100", hits);
141    println!("  - L1命中率: {:.1}%", cache_stats.l1_hit_rate() * 100.0);
142    println!("  - 总命中率: {:.1}%", cache_stats.hit_rate() * 100.0);
143    
144    // 4. 并发批处理测试
145    println!("\n⚡ 并发批处理性能:");
146    let batch_config = BatchConfig {
147        batch_size: 20,
148        max_concurrency: 4,
149        timeout_duration: std::time::Duration::from_secs(10),
150        ..Default::default()
151    };
152    
153    let batch_processor = ConcurrentBatchProcessor::new(
154        batch_config, 
155        Arc::clone(&memory_manager)
156    );
157    
158    // 准备测试文本
159    let test_texts: Vec<String> = (0..200)
160        .map(|i| format!("Test text number {}", i))
161        .collect();
162    
163    let start = Instant::now();
164    
165    // 提交批处理任务
166    let mut task_ids = Vec::new();
167    for chunk in test_texts.chunks(50) {
168        let task_id = batch_processor.submit_batch(
169            chunk.to_vec(), 
170            Priority::Normal
171        ).await?;
172        task_ids.push(task_id);
173    }
174    
175    // 模拟翻译函数
176    async fn mock_translate(texts: Vec<String>) -> html_translation_lib::error::TranslationResult<Vec<String>> {
177        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
178        Ok(texts.into_iter().map(|t| format!("翻译_{}", t)).collect())
179    }
180    
181    // 处理队列
182    let _results = batch_processor.process_queue(mock_translate).await?;
183    let batch_time = start.elapsed();
184    
185    let batch_stats = batch_processor.get_stats().await;
186    let queue_status = batch_processor.get_queue_status();
187    
188    println!("  - 批处理总时间: {}ms", batch_time.as_millis());
189    println!("  - 处理成功率: {:.1}%", batch_stats.success_rate() * 100.0);
190    println!("  - 平均处理时间: {}ms", batch_stats.average_processing_time().as_millis());
191    println!("  - 吞吐量: {:.1} 任务/秒", batch_stats.throughput());
192    println!("  - 队列剩余: {} 任务", queue_status.total_tasks);
193    
194    // 5. 总结
195    println!("\n📈 性能优化总结:");
196    println!("  ✅ DOM遍历优化: {:.1}x 性能提升", speedup);
197    println!("  ✅ 内存池管理: 减少 GC 压力");
198    println!("  ✅ 智能缓存: {:.1}% 命中率", cache_stats.hit_rate() * 100.0);
199    println!("  ✅ 并发批处理: {:.1}% 成功率", batch_stats.success_rate() * 100.0);
200    println!("\n🎉 所有性能优化测试完成!");
201    
202    Ok(())
203}
More examples
Hide additional examples
examples/basic_translation.rs (line 18)
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}
examples/monolith_integration.rs (line 106)
11async fn main() -> TranslationResult<()> {
12    tracing_subscriber::fmt::init();
13    
14    println!("HTML翻译库 - Monolith集成示例");
15    println!("{}", "=".repeat(50));
16    
17    // 模拟从网络获取的HTML内容 - 避免前缀标识符冲突
18    let html_content = format!(r##"
19    <!DOCTYPE html>
20    <html lang="en">
21    <head>
22        <meta charset="UTF-8">
23        <title>Product Documentation</title>
24        <link rel="stylesheet" href="styles.css">
25    </head>
26    <body>
27        <header>
28            <h1>Product Documentation</h1>
29            <p>Comprehensive guide for our product</p>
30        </header>
31        
32        <nav>
33            <ul>
34                <li><a href="{}getting-started">Getting Started</a></li>
35                <li><a href="{}features">Features</a></li>
36                <li><a href="{}api-reference">API Reference</a></li>
37                <li><a href="{}troubleshooting">Troubleshooting</a></li>
38            </ul>
39        </nav>
40        
41        <main>
42            <section id="getting-started">
43                <h2>Getting Started</h2>
44                <p>Follow these simple steps to begin using our product:</p>
45                <ol>
46                    <li>Download the latest version from our website</li>
47                    <li>Install the software on your system</li>
48                    <li>Run the initial configuration wizard</li>
49                    <li>Start exploring the features</li>
50                </ol>
51            </section>
52            
53            <section id="features">
54                <h2>Key Features</h2>
55                <div class="feature-grid">
56                    <div class="feature-card">
57                        <h3>Easy to Use</h3>
58                        <p>Intuitive interface designed for users of all skill levels.</p>
59                    </div>
60                    <div class="feature-card">
61                        <h3>High Performance</h3>
62                        <p>Optimized algorithms ensure fast processing times.</p>
63                    </div>
64                    <div class="feature-card">
65                        <h3>Extensible</h3>
66                        <p>Plugin architecture allows for custom functionality.</p>
67                    </div>
68                </div>
69            </section>
70            
71            <section id="api-reference">
72                <h2>API Reference</h2>
73                <p>Complete documentation of all available functions and methods.</p>
74                <code>
75                function processData(input) {{
76                    // Example function
77                    return input.map(item => item * 2);
78                }}
79                </code>
80            </section>
81        </main>
82        
83        <footer>
84            <p>© 2024 Company Name. All rights reserved.</p>
85        </footer>
86        
87        <script src="script.js"></script>
88    </body>
89    </html>
90    "##, "#", "#", "#", "#");
91    
92    println!("📄 原始HTML内容长度: {} 字符", html_content.len());
93    
94    // 步骤1: 解析HTML为DOM
95    println!("\n🔍 步骤1: 解析HTML为DOM...");
96    let dom = parse_document(RcDom::default(), Default::default())
97        .from_utf8()
98        .read_from(&mut html_content.as_bytes())?;
99    
100    println!("✅ HTML解析完成");
101    
102    // 步骤2: 配置翻译参数
103    println!("\n⚙️  步骤2: 配置翻译参数...");
104    let translation_config = TranslationConfig::new()
105        .target_language("zh")
106        .api_url("http://localhost:1188/translate")
107        .enable_cache(true)
108        .batch_size(15)
109        .max_retries(3);
110    
111    println!("✅ 翻译配置完成");
112    
113    // 步骤3: 在合并资源前翻译内容
114    println!("\n🔄 步骤3: 翻译DOM内容...");
115    let start_time = std::time::Instant::now();
116    
117    let translated_dom = translate_before_merge(dom, translation_config).await?;
118    
119    let translation_time = start_time.elapsed();
120    println!("✅ 翻译完成!耗时: {:?}", translation_time);
121    
122    // 步骤4: 将翻译后的DOM序列化为HTML
123    println!("\n📝 步骤4: 序列化翻译后的DOM...");
124    let translated_html = serialize_dom(&translated_dom)?;
125    
126    println!("✅ DOM序列化完成");
127    
128    // 步骤5: 保存翻译后的HTML(在实际使用中,这里会传给Monolith)
129    println!("\n💾 步骤5: 保存翻译结果...");
130    std::fs::write("translated_monolith_input.html", &translated_html)?;
131    println!("✅ 翻译后的HTML已保存到: translated_monolith_input.html");
132    
133    // 现在这个文件可以作为Monolith的输入
134    println!("\n🔧 集成说明:");
135    println!("   1. 翻译后的HTML文件: translated_monolith_input.html");
136    println!("   2. 现在可以使用Monolith处理此文件:");
137    println!("      monolith translated_monolith_input.html > final_output.html");
138    println!("   3. 最终输出将是翻译好的单文件HTML");
139    
140    // 显示处理统计
141    println!("\n📊 处理统计:");
142    println!("   - 原始内容长度: {} 字符", html_content.len());
143    println!("   - 翻译后长度: {} 字符", translated_html.len());
144    println!("   - 翻译用时: {:?}", translation_time);
145    println!("   - 长度变化: {:.1}%", 
146             (translated_html.len() as f32 / html_content.len() as f32 - 1.0) * 100.0);
147    
148    // 显示部分翻译结果预览
149    let preview_length = 800;
150    let preview = if translated_html.len() > preview_length {
151        format!("{}...", &translated_html[..preview_length])
152    } else {
153        translated_html.clone()
154    };
155    
156    println!("\n📝 翻译结果预览:");
157    println!("{}", "=".repeat(60));
158    println!("{}", preview);
159    println!("{}", "=".repeat(60));
160    
161    println!("\n🎉 Monolith集成示例完成!");
162    println!("   翻译后的文件现在可以用作Monolith的输入。");
163    
164    Ok(())
165}
Source

pub fn enable_cache(self, enabled: bool) -> Self

启用或禁用缓存

Examples found in repository?
examples/basic_translation.rs (line 19)
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}
More examples
Hide additional examples
examples/monolith_integration.rs (line 107)
11async fn main() -> TranslationResult<()> {
12    tracing_subscriber::fmt::init();
13    
14    println!("HTML翻译库 - Monolith集成示例");
15    println!("{}", "=".repeat(50));
16    
17    // 模拟从网络获取的HTML内容 - 避免前缀标识符冲突
18    let html_content = format!(r##"
19    <!DOCTYPE html>
20    <html lang="en">
21    <head>
22        <meta charset="UTF-8">
23        <title>Product Documentation</title>
24        <link rel="stylesheet" href="styles.css">
25    </head>
26    <body>
27        <header>
28            <h1>Product Documentation</h1>
29            <p>Comprehensive guide for our product</p>
30        </header>
31        
32        <nav>
33            <ul>
34                <li><a href="{}getting-started">Getting Started</a></li>
35                <li><a href="{}features">Features</a></li>
36                <li><a href="{}api-reference">API Reference</a></li>
37                <li><a href="{}troubleshooting">Troubleshooting</a></li>
38            </ul>
39        </nav>
40        
41        <main>
42            <section id="getting-started">
43                <h2>Getting Started</h2>
44                <p>Follow these simple steps to begin using our product:</p>
45                <ol>
46                    <li>Download the latest version from our website</li>
47                    <li>Install the software on your system</li>
48                    <li>Run the initial configuration wizard</li>
49                    <li>Start exploring the features</li>
50                </ol>
51            </section>
52            
53            <section id="features">
54                <h2>Key Features</h2>
55                <div class="feature-grid">
56                    <div class="feature-card">
57                        <h3>Easy to Use</h3>
58                        <p>Intuitive interface designed for users of all skill levels.</p>
59                    </div>
60                    <div class="feature-card">
61                        <h3>High Performance</h3>
62                        <p>Optimized algorithms ensure fast processing times.</p>
63                    </div>
64                    <div class="feature-card">
65                        <h3>Extensible</h3>
66                        <p>Plugin architecture allows for custom functionality.</p>
67                    </div>
68                </div>
69            </section>
70            
71            <section id="api-reference">
72                <h2>API Reference</h2>
73                <p>Complete documentation of all available functions and methods.</p>
74                <code>
75                function processData(input) {{
76                    // Example function
77                    return input.map(item => item * 2);
78                }}
79                </code>
80            </section>
81        </main>
82        
83        <footer>
84            <p>© 2024 Company Name. All rights reserved.</p>
85        </footer>
86        
87        <script src="script.js"></script>
88    </body>
89    </html>
90    "##, "#", "#", "#", "#");
91    
92    println!("📄 原始HTML内容长度: {} 字符", html_content.len());
93    
94    // 步骤1: 解析HTML为DOM
95    println!("\n🔍 步骤1: 解析HTML为DOM...");
96    let dom = parse_document(RcDom::default(), Default::default())
97        .from_utf8()
98        .read_from(&mut html_content.as_bytes())?;
99    
100    println!("✅ HTML解析完成");
101    
102    // 步骤2: 配置翻译参数
103    println!("\n⚙️  步骤2: 配置翻译参数...");
104    let translation_config = TranslationConfig::new()
105        .target_language("zh")
106        .api_url("http://localhost:1188/translate")
107        .enable_cache(true)
108        .batch_size(15)
109        .max_retries(3);
110    
111    println!("✅ 翻译配置完成");
112    
113    // 步骤3: 在合并资源前翻译内容
114    println!("\n🔄 步骤3: 翻译DOM内容...");
115    let start_time = std::time::Instant::now();
116    
117    let translated_dom = translate_before_merge(dom, translation_config).await?;
118    
119    let translation_time = start_time.elapsed();
120    println!("✅ 翻译完成!耗时: {:?}", translation_time);
121    
122    // 步骤4: 将翻译后的DOM序列化为HTML
123    println!("\n📝 步骤4: 序列化翻译后的DOM...");
124    let translated_html = serialize_dom(&translated_dom)?;
125    
126    println!("✅ DOM序列化完成");
127    
128    // 步骤5: 保存翻译后的HTML(在实际使用中,这里会传给Monolith)
129    println!("\n💾 步骤5: 保存翻译结果...");
130    std::fs::write("translated_monolith_input.html", &translated_html)?;
131    println!("✅ 翻译后的HTML已保存到: translated_monolith_input.html");
132    
133    // 现在这个文件可以作为Monolith的输入
134    println!("\n🔧 集成说明:");
135    println!("   1. 翻译后的HTML文件: translated_monolith_input.html");
136    println!("   2. 现在可以使用Monolith处理此文件:");
137    println!("      monolith translated_monolith_input.html > final_output.html");
138    println!("   3. 最终输出将是翻译好的单文件HTML");
139    
140    // 显示处理统计
141    println!("\n📊 处理统计:");
142    println!("   - 原始内容长度: {} 字符", html_content.len());
143    println!("   - 翻译后长度: {} 字符", translated_html.len());
144    println!("   - 翻译用时: {:?}", translation_time);
145    println!("   - 长度变化: {:.1}%", 
146             (translated_html.len() as f32 / html_content.len() as f32 - 1.0) * 100.0);
147    
148    // 显示部分翻译结果预览
149    let preview_length = 800;
150    let preview = if translated_html.len() > preview_length {
151        format!("{}...", &translated_html[..preview_length])
152    } else {
153        translated_html.clone()
154    };
155    
156    println!("\n📝 翻译结果预览:");
157    println!("{}", "=".repeat(60));
158    println!("{}", preview);
159    println!("{}", "=".repeat(60));
160    
161    println!("\n🎉 Monolith集成示例完成!");
162    println!("   翻译后的文件现在可以用作Monolith的输入。");
163    
164    Ok(())
165}
Source

pub fn cache_ttl(self, ttl: Duration) -> Self

设置缓存TTL

Source

pub fn batch_size(self, size: usize) -> Self

设置批处理大小

Examples found in repository?
examples/basic_translation.rs (line 20)
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}
More examples
Hide additional examples
examples/monolith_integration.rs (line 108)
11async fn main() -> TranslationResult<()> {
12    tracing_subscriber::fmt::init();
13    
14    println!("HTML翻译库 - Monolith集成示例");
15    println!("{}", "=".repeat(50));
16    
17    // 模拟从网络获取的HTML内容 - 避免前缀标识符冲突
18    let html_content = format!(r##"
19    <!DOCTYPE html>
20    <html lang="en">
21    <head>
22        <meta charset="UTF-8">
23        <title>Product Documentation</title>
24        <link rel="stylesheet" href="styles.css">
25    </head>
26    <body>
27        <header>
28            <h1>Product Documentation</h1>
29            <p>Comprehensive guide for our product</p>
30        </header>
31        
32        <nav>
33            <ul>
34                <li><a href="{}getting-started">Getting Started</a></li>
35                <li><a href="{}features">Features</a></li>
36                <li><a href="{}api-reference">API Reference</a></li>
37                <li><a href="{}troubleshooting">Troubleshooting</a></li>
38            </ul>
39        </nav>
40        
41        <main>
42            <section id="getting-started">
43                <h2>Getting Started</h2>
44                <p>Follow these simple steps to begin using our product:</p>
45                <ol>
46                    <li>Download the latest version from our website</li>
47                    <li>Install the software on your system</li>
48                    <li>Run the initial configuration wizard</li>
49                    <li>Start exploring the features</li>
50                </ol>
51            </section>
52            
53            <section id="features">
54                <h2>Key Features</h2>
55                <div class="feature-grid">
56                    <div class="feature-card">
57                        <h3>Easy to Use</h3>
58                        <p>Intuitive interface designed for users of all skill levels.</p>
59                    </div>
60                    <div class="feature-card">
61                        <h3>High Performance</h3>
62                        <p>Optimized algorithms ensure fast processing times.</p>
63                    </div>
64                    <div class="feature-card">
65                        <h3>Extensible</h3>
66                        <p>Plugin architecture allows for custom functionality.</p>
67                    </div>
68                </div>
69            </section>
70            
71            <section id="api-reference">
72                <h2>API Reference</h2>
73                <p>Complete documentation of all available functions and methods.</p>
74                <code>
75                function processData(input) {{
76                    // Example function
77                    return input.map(item => item * 2);
78                }}
79                </code>
80            </section>
81        </main>
82        
83        <footer>
84            <p>© 2024 Company Name. All rights reserved.</p>
85        </footer>
86        
87        <script src="script.js"></script>
88    </body>
89    </html>
90    "##, "#", "#", "#", "#");
91    
92    println!("📄 原始HTML内容长度: {} 字符", html_content.len());
93    
94    // 步骤1: 解析HTML为DOM
95    println!("\n🔍 步骤1: 解析HTML为DOM...");
96    let dom = parse_document(RcDom::default(), Default::default())
97        .from_utf8()
98        .read_from(&mut html_content.as_bytes())?;
99    
100    println!("✅ HTML解析完成");
101    
102    // 步骤2: 配置翻译参数
103    println!("\n⚙️  步骤2: 配置翻译参数...");
104    let translation_config = TranslationConfig::new()
105        .target_language("zh")
106        .api_url("http://localhost:1188/translate")
107        .enable_cache(true)
108        .batch_size(15)
109        .max_retries(3);
110    
111    println!("✅ 翻译配置完成");
112    
113    // 步骤3: 在合并资源前翻译内容
114    println!("\n🔄 步骤3: 翻译DOM内容...");
115    let start_time = std::time::Instant::now();
116    
117    let translated_dom = translate_before_merge(dom, translation_config).await?;
118    
119    let translation_time = start_time.elapsed();
120    println!("✅ 翻译完成!耗时: {:?}", translation_time);
121    
122    // 步骤4: 将翻译后的DOM序列化为HTML
123    println!("\n📝 步骤4: 序列化翻译后的DOM...");
124    let translated_html = serialize_dom(&translated_dom)?;
125    
126    println!("✅ DOM序列化完成");
127    
128    // 步骤5: 保存翻译后的HTML(在实际使用中,这里会传给Monolith)
129    println!("\n💾 步骤5: 保存翻译结果...");
130    std::fs::write("translated_monolith_input.html", &translated_html)?;
131    println!("✅ 翻译后的HTML已保存到: translated_monolith_input.html");
132    
133    // 现在这个文件可以作为Monolith的输入
134    println!("\n🔧 集成说明:");
135    println!("   1. 翻译后的HTML文件: translated_monolith_input.html");
136    println!("   2. 现在可以使用Monolith处理此文件:");
137    println!("      monolith translated_monolith_input.html > final_output.html");
138    println!("   3. 最终输出将是翻译好的单文件HTML");
139    
140    // 显示处理统计
141    println!("\n📊 处理统计:");
142    println!("   - 原始内容长度: {} 字符", html_content.len());
143    println!("   - 翻译后长度: {} 字符", translated_html.len());
144    println!("   - 翻译用时: {:?}", translation_time);
145    println!("   - 长度变化: {:.1}%", 
146             (translated_html.len() as f32 / html_content.len() as f32 - 1.0) * 100.0);
147    
148    // 显示部分翻译结果预览
149    let preview_length = 800;
150    let preview = if translated_html.len() > preview_length {
151        format!("{}...", &translated_html[..preview_length])
152    } else {
153        translated_html.clone()
154    };
155    
156    println!("\n📝 翻译结果预览:");
157    println!("{}", "=".repeat(60));
158    println!("{}", preview);
159    println!("{}", "=".repeat(60));
160    
161    println!("\n🎉 Monolith集成示例完成!");
162    println!("   翻译后的文件现在可以用作Monolith的输入。");
163    
164    Ok(())
165}
Source

pub fn max_retries(self, retries: usize) -> Self

设置最大重试次数

Examples found in repository?
examples/basic_translation.rs (line 21)
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}
More examples
Hide additional examples
examples/monolith_integration.rs (line 109)
11async fn main() -> TranslationResult<()> {
12    tracing_subscriber::fmt::init();
13    
14    println!("HTML翻译库 - Monolith集成示例");
15    println!("{}", "=".repeat(50));
16    
17    // 模拟从网络获取的HTML内容 - 避免前缀标识符冲突
18    let html_content = format!(r##"
19    <!DOCTYPE html>
20    <html lang="en">
21    <head>
22        <meta charset="UTF-8">
23        <title>Product Documentation</title>
24        <link rel="stylesheet" href="styles.css">
25    </head>
26    <body>
27        <header>
28            <h1>Product Documentation</h1>
29            <p>Comprehensive guide for our product</p>
30        </header>
31        
32        <nav>
33            <ul>
34                <li><a href="{}getting-started">Getting Started</a></li>
35                <li><a href="{}features">Features</a></li>
36                <li><a href="{}api-reference">API Reference</a></li>
37                <li><a href="{}troubleshooting">Troubleshooting</a></li>
38            </ul>
39        </nav>
40        
41        <main>
42            <section id="getting-started">
43                <h2>Getting Started</h2>
44                <p>Follow these simple steps to begin using our product:</p>
45                <ol>
46                    <li>Download the latest version from our website</li>
47                    <li>Install the software on your system</li>
48                    <li>Run the initial configuration wizard</li>
49                    <li>Start exploring the features</li>
50                </ol>
51            </section>
52            
53            <section id="features">
54                <h2>Key Features</h2>
55                <div class="feature-grid">
56                    <div class="feature-card">
57                        <h3>Easy to Use</h3>
58                        <p>Intuitive interface designed for users of all skill levels.</p>
59                    </div>
60                    <div class="feature-card">
61                        <h3>High Performance</h3>
62                        <p>Optimized algorithms ensure fast processing times.</p>
63                    </div>
64                    <div class="feature-card">
65                        <h3>Extensible</h3>
66                        <p>Plugin architecture allows for custom functionality.</p>
67                    </div>
68                </div>
69            </section>
70            
71            <section id="api-reference">
72                <h2>API Reference</h2>
73                <p>Complete documentation of all available functions and methods.</p>
74                <code>
75                function processData(input) {{
76                    // Example function
77                    return input.map(item => item * 2);
78                }}
79                </code>
80            </section>
81        </main>
82        
83        <footer>
84            <p>© 2024 Company Name. All rights reserved.</p>
85        </footer>
86        
87        <script src="script.js"></script>
88    </body>
89    </html>
90    "##, "#", "#", "#", "#");
91    
92    println!("📄 原始HTML内容长度: {} 字符", html_content.len());
93    
94    // 步骤1: 解析HTML为DOM
95    println!("\n🔍 步骤1: 解析HTML为DOM...");
96    let dom = parse_document(RcDom::default(), Default::default())
97        .from_utf8()
98        .read_from(&mut html_content.as_bytes())?;
99    
100    println!("✅ HTML解析完成");
101    
102    // 步骤2: 配置翻译参数
103    println!("\n⚙️  步骤2: 配置翻译参数...");
104    let translation_config = TranslationConfig::new()
105        .target_language("zh")
106        .api_url("http://localhost:1188/translate")
107        .enable_cache(true)
108        .batch_size(15)
109        .max_retries(3);
110    
111    println!("✅ 翻译配置完成");
112    
113    // 步骤3: 在合并资源前翻译内容
114    println!("\n🔄 步骤3: 翻译DOM内容...");
115    let start_time = std::time::Instant::now();
116    
117    let translated_dom = translate_before_merge(dom, translation_config).await?;
118    
119    let translation_time = start_time.elapsed();
120    println!("✅ 翻译完成!耗时: {:?}", translation_time);
121    
122    // 步骤4: 将翻译后的DOM序列化为HTML
123    println!("\n📝 步骤4: 序列化翻译后的DOM...");
124    let translated_html = serialize_dom(&translated_dom)?;
125    
126    println!("✅ DOM序列化完成");
127    
128    // 步骤5: 保存翻译后的HTML(在实际使用中,这里会传给Monolith)
129    println!("\n💾 步骤5: 保存翻译结果...");
130    std::fs::write("translated_monolith_input.html", &translated_html)?;
131    println!("✅ 翻译后的HTML已保存到: translated_monolith_input.html");
132    
133    // 现在这个文件可以作为Monolith的输入
134    println!("\n🔧 集成说明:");
135    println!("   1. 翻译后的HTML文件: translated_monolith_input.html");
136    println!("   2. 现在可以使用Monolith处理此文件:");
137    println!("      monolith translated_monolith_input.html > final_output.html");
138    println!("   3. 最终输出将是翻译好的单文件HTML");
139    
140    // 显示处理统计
141    println!("\n📊 处理统计:");
142    println!("   - 原始内容长度: {} 字符", html_content.len());
143    println!("   - 翻译后长度: {} 字符", translated_html.len());
144    println!("   - 翻译用时: {:?}", translation_time);
145    println!("   - 长度变化: {:.1}%", 
146             (translated_html.len() as f32 / html_content.len() as f32 - 1.0) * 100.0);
147    
148    // 显示部分翻译结果预览
149    let preview_length = 800;
150    let preview = if translated_html.len() > preview_length {
151        format!("{}...", &translated_html[..preview_length])
152    } else {
153        translated_html.clone()
154    };
155    
156    println!("\n📝 翻译结果预览:");
157    println!("{}", "=".repeat(60));
158    println!("{}", preview);
159    println!("{}", "=".repeat(60));
160    
161    println!("\n🎉 Monolith集成示例完成!");
162    println!("   翻译后的文件现在可以用作Monolith的输入。");
163    
164    Ok(())
165}
Source

pub fn timeout(self, seconds: u64) -> Self

设置请求超时时间

Source

pub fn api_key(self, key: Option<String>) -> Self

设置API密钥

Source

pub fn use_indexing(self, enabled: bool) -> Self

启用或禁用索引标记

Source

pub fn min_text_length(self, length: usize) -> Self

设置最小翻译文本长度

Source

pub fn add_filter(self, pattern: &str) -> Self

添加自定义过滤规则

Source

pub fn from_file<P: AsRef<Path>>(path: P) -> TranslationResult<Self>

从文件加载配置

Source

pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> TranslationResult<()>

保存配置到文件

Source

pub fn from_env() -> Self

从环境变量加载配置

Source

pub fn validate(&self) -> TranslationResult<()>

验证配置的有效性

Source

pub fn http_timeout(&self) -> Duration

获取HTTP客户端超时时间

Source

pub fn retry_delay(&self) -> Duration

获取重试延迟时间

Trait Implementations§

Source§

impl Clone for TranslationConfig

Source§

fn clone(&self) -> TranslationConfig

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TranslationConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for TranslationConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for TranslationConfig

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for TranslationConfig

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more