webpage_quality_analyzer 1.0.2

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

use webpage_quality_analyzer::Analyzer;

#[path = "common/macros.rs"]
mod macros;
use macros::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    print_section!("🚀", "Advanced Features Examples");

    // Example 1: NLP Features (requires nlp feature flag)
    print_section!("🧠", "Example 1: NLP Features");

    let nlp_analyzer: Analyzer = Analyzer::builder()
        .with_profile_name("content_article")?
        .enable_nlp(true) // Enable Natural Language Processing
        .build()?;

    let multilingual_html = r##"
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>The Future of Artificial Intelligence</title>
            <meta name="description" content="An in-depth analysis of AI developments and their impact on society.">
        </head>
        <body>
            <article>
                <h1>The Future of Artificial Intelligence</h1>
                
                <p>Artificial intelligence represents one of the most significant technological 
                advances of our time. The rapid development of machine learning algorithms, 
                neural networks, and deep learning systems has transformed industries and 
                created new possibilities for solving complex problems.</p>
                
                <h2>Current Applications</h2>
                <p>Today's AI systems excel in pattern recognition, natural language processing, 
                and predictive analytics. Companies across various sectors leverage these 
                capabilities to enhance decision-making processes and automate routine tasks.</p>
                
                <h2>Future Implications</h2>
                <p>The trajectory of AI development suggests continued integration into daily life. 
                Autonomous vehicles, personalized medicine, and intelligent automation represent 
                just the beginning of AI's transformative potential.</p>
                
                <h3>Challenges and Considerations</h3>
                <p>However, this technological revolution brings important considerations regarding 
                privacy, employment, and ethical implementation. Society must carefully navigate 
                these challenges to ensure AI benefits humanity broadly.</p>
                
                <p>The complexity of these systems requires sophisticated understanding and 
                careful regulation. Policymakers, technologists, and citizens must collaborate 
                to establish frameworks that promote innovation while protecting fundamental values.</p>
            </article>
        </body>
        </html>
    "##;

    match nlp_analyzer
        .run(
            "https://ai-blog.example.com/future-ai",
            Some(multilingual_html),
        )
        .await
    {
        Ok(report) => {
            println!("✅ NLP Analysis completed!");
            println!("   Overall Score: {:.1}/100", report.score);

            // Language and readability metrics
            let content = &report.metrics.html_analysis.content;
            println!("   Content Analysis:");
            println!("     Word Count: {}", content.word_count);
            println!("     Sentence Count: {}", content.sentence_count);
            println!(
                "     Average Sentence Length: {:.1} words",
                content.avg_sentence_len
            );

            if let Some(readability) = content.readability_fk {
                println!("     Flesch-Kincaid Score: {:.1}", readability);
                let reading_level = match readability {
                    r if r < 6.0 => "Elementary School",
                    r if r < 9.0 => "Middle School",
                    r if r < 13.0 => "High School",
                    r if r < 16.0 => "College",
                    _ => "Graduate",
                };
                println!("     Reading Level: {}", reading_level);
            }

            println!(
                "     Unique Word Ratio: {:.1}%",
                content.unique_word_ratio * 100.0
            );
            println!(
                "     Reading Time: {:.1} minutes",
                content.reading_time_minutes
            );

            // Language detection if available
            let lang_metrics = &report.metrics.html_analysis.language;
            if let Some(confidence) = lang_metrics.language_confidence {
                println!("     Language Confidence: {:.1}%", confidence * 100.0);
            }
        }
        Err(e) => println!("❌ NLP analysis failed: {}", e),
    }

    println!();

    // Example 2: Link Checking Features
    println!("🔗 Example 2: Link Checking");
    println!("---------------------------");

    let linkcheck_analyzer: Analyzer = Analyzer::builder()
        .with_profile_name("news")?
        .enable_linkcheck(true)
        .linkcheck_sample(10) // Check up to 10 links for demo
        .build()?;

    let link_rich_html = r##"
        <!DOCTYPE html>
        <html>
        <head>
            <title>Web Development Resources</title>
        </head>
        <body>
            <h1>Essential Web Development Resources</h1>
            
            <h2>Documentation</h2>
            <p>The best places to learn web development:</p>
            <ul>
                <li><a href="https://developer.mozilla.org">MDN Web Docs</a> - Comprehensive web documentation</li>
                <li><a href="https://www.w3schools.com">W3Schools</a> - Tutorials and references</li>
                <li><a href="https://stackoverflow.com">Stack Overflow</a> - Community Q&A</li>
                <li><a href="/internal-page">Internal Documentation</a></li>
            </ul>
            
            <h2>Tools and Frameworks</h2>
            <p>Popular development tools:</p>
            <ul>
                <li><a href="https://github.com">GitHub</a> - Version control</li>
                <li><a href="https://code.visualstudio.com">VS Code</a> - Code editor</li>
                <li><a href="https://nodejs.org">Node.js</a> - Runtime environment</li>
                <li><a href="#top">Back to top</a></li>
            </ul>
            
            <p>For more information, <a href="mailto:contact@example.com">contact us</a>.</p>
        </body>
        </html>
    "##;

    match linkcheck_analyzer
        .run("https://resources.example.com", Some(link_rich_html))
        .await
    {
        Ok(report) => {
            println!("✅ Link analysis completed!");

            let links = &report.metrics.html_analysis.links;
            println!("   Link Analysis:");
            println!("     Total Links: {}", links.total_links);
            println!("     Internal Links: {}", links.internal_links);
            println!("     External Links: {}", links.external_links);
            println!(
                "     Anchor Text Diversity: {:.1}%",
                links.anchor_text_diversity
            );
            println!("     NoFollow Links: {}", links.nofollow_links);

            if let Some(broken_rate) = links.broken_link_rate {
                println!("     Broken Link Rate: {:.1}%", broken_rate * 100.0);
            } else {
                println!(
                    "     Broken Link Rate: Not checked (feature disabled or no external links)"
                );
            }

            // Show rel attribute distribution
            if !links.rel_attribute_counts.is_empty() {
                println!("     Rel Attributes:");
                for (rel, count) in &links.rel_attribute_counts {
                    println!("       {}: {}", rel, count);
                }
            }
        }
        Err(e) => println!("❌ Link analysis failed: {}", e),
    }

    println!();

    // Example 3: Error Handling and Edge Cases
    println!("⚠️  Example 3: Error Handling & Edge Cases");
    println!("------------------------------------------");

    let edge_cases = vec![
        ("Empty HTML", ""),
        ("Minimal HTML", "<html><head><title>Test</title></head><body></body></html>"),
        ("No Title", "<html><body><p>Content without title</p></body></html>"),
        ("Very Short Content", "<html><head><title>Short</title></head><body><p>Hi</p></body></html>"),
        ("Malformed HTML", "<html><head><title>Test</head><body><p>Unclosed tags<body></html>"),
        ("Unicode Content", "<html><head><title>测试页面</title></head><body><p>这是中文内容测试。</p></body></html>"),
        ("Script Heavy", r#"<html><head><title>JS Heavy</title><script>console.log("lots"); console.log("of"); console.log("javascript");</script></head><body><p>Content</p></body></html>"#),
    ];

    let edge_case_analyzer: Analyzer = Analyzer::builder().build()?;

    for (case_name, html) in edge_cases {
        print!("   Testing {}: ", case_name);

        match edge_case_analyzer
            .run("https://test.example.com", Some(html))
            .await
        {
            Ok(report) => {
                println!("✅ Score: {:.1}/100 ({})", report.score, report.verdict);
            }
            Err(e) => {
                println!("❌ Error: {}", e);
            }
        }
    }

    println!();

    // Example 4: Performance and Batch Analysis
    println!("⚡ Example 4: Performance & Batch Analysis");
    println!("------------------------------------------");

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

    // Create a lightweight analyzer for batch processing
    let batch_analyzer: Analyzer = Analyzer::builder()
        .with_profile_name("blog")?
        .enable_linkcheck(false) // Disable for speed
        .enable_nlp(false) // Disable for speed
        .add_report(false) // Minimal report for speed
        .build()?;

    let test_pages = vec![
        ("Blog Post", "<html><head><title>Blog</title></head><body><h1>Blog Post</h1><p>Content here.</p></body></html>"),
        ("News Article", "<html><head><title>News</title></head><body><h1>Breaking News</h1><p>News content.</p></body></html>"),
        ("Product Page", "<html><head><title>Product</title></head><body><h1>Amazing Product</h1><p>Buy now!</p></body></html>"),
        ("Documentation", "<html><head><title>Docs</title></head><body><h1>API Docs</h1><p>Technical documentation.</p></body></html>"),
        ("About Page", "<html><head><title>About</title></head><body><h1>About Us</h1><p>Company information.</p></body></html>"),
    ];

    let mut results = Vec::new();

    for (page_type, html) in test_pages {
        let url = format!(
            "https://example.com/{}",
            page_type.to_lowercase().replace(" ", "-")
        );

        match batch_analyzer.run(&url, Some(html)).await {
            Ok(report) => {
                results.push((page_type, report.score, report.verdict));
            }
            Err(e) => {
                println!("   ❌ Failed to analyze {}: {}", page_type, e);
            }
        }
    }

    let elapsed = start_time.elapsed();

    println!("✅ Batch analysis completed in {:.2?}", elapsed);
    println!("   Results:");

    for (page_type, score, verdict) in results {
        println!("     {}: {:.1}/100 ({})", page_type, score, verdict);
    }

    println!();

    // Example 5: Detailed Report Analysis
    println!("📊 Example 5: Detailed Report Analysis");
    println!("--------------------------------------");

    let detailed_analyzer: Analyzer = Analyzer::builder()
        .with_profile_name("content_article")?
        .enable_nlp(true)
        .enable_linkcheck(true)
        .linkcheck_sample(5)
        .add_report(true) // Full detailed report
        .build()?;

    let comprehensive_html = r##"
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Complete Guide to Rust Programming</title>
            <meta name="description" content="Learn Rust programming from basics to advanced concepts with practical examples and best practices.">
            <meta name="author" content="Rust Expert">
            <link rel="canonical" href="https://example.com/rust-guide">
            <meta property="og:title" content="Complete Guide to Rust Programming">
            <meta property="og:description" content="Comprehensive Rust tutorial">
        </head>
        <body>
            <header>
                <h1>Complete Guide to Rust Programming</h1>
                <nav>
                    <a href="#basics">Basics</a>
                    <a href="#advanced">Advanced</a>
                    <a href="#examples">Examples</a>
                </nav>
            </header>
            
            <main>
                <section id="basics">
                    <h2>Rust Basics</h2>
                    <p>Rust is a systems programming language focused on safety, speed, and concurrency. 
                    It prevents common programming errors through its ownership system and type safety.</p>
                    
                    <h3>Memory Safety</h3>
                    <p>Rust eliminates entire classes of bugs at compile time. No null pointer dereferences, 
                    buffer overflows, or memory leaks in safe Rust code.</p>
                    
                    <img src="rust-memory.png" alt="Rust memory management diagram">
                </section>
                
                <section id="advanced">
                    <h2>Advanced Features</h2>
                    <p>Advanced Rust includes traits, generics, lifetimes, and async programming. 
                    These features enable powerful abstractions while maintaining zero-cost guarantees.</p>
                    
                    <h3>Ownership and Borrowing</h3>
                    <p>The ownership system is Rust's unique approach to memory management. 
                    It ensures memory safety without garbage collection overhead.</p>
                </section>
                
                <section id="examples">
                    <h2>Practical Examples</h2>
                    <p>Here are some practical examples demonstrating Rust's capabilities in real-world scenarios.</p>
                    
                    <ul>
                        <li><a href="https://github.com/rust-lang/rust">Rust Source Code</a></li>
                        <li><a href="https://doc.rust-lang.org">Official Documentation</a></li>
                        <li><a href="https://play.rust-lang.org">Rust Playground</a></li>
                    </ul>
                </section>
            </main>
            
            <footer>
                <p>© 2024 Rust Programming Guide. All rights reserved.</p>
            </footer>
        </body>
        </html>
    "##;

    match detailed_analyzer
        .run("https://example.com/rust-guide", Some(comprehensive_html))
        .await
    {
        Ok(report) => {
            println!("✅ Comprehensive analysis completed!");
            println!();
            println!("📈 Overall Results:");
            println!("   Score: {:.1}/100", report.score);
            println!("   Verdict: {}", report.verdict);
            println!("   Version: {}", report.version);
            println!();

            // Metadata
            println!("📋 Page Metadata:");
            println!("   Title: {}", report.metadata.title);
            if let Some(desc) = &report.metadata.meta_description {
                println!("   Description: {}", desc);
            }
            if let Some(author) = &report.metadata.author {
                println!("   Author: {}", author);
            }
            println!(
                "   Language: {}",
                report
                    .metadata
                    .language
                    .as_ref()
                    .unwrap_or(&"not specified".to_string())
            );
            println!(
                "   Charset: {}",
                report
                    .metadata
                    .charset
                    .as_ref()
                    .unwrap_or(&"not specified".to_string())
            );
            println!();

            // Detailed metrics breakdown
            let metrics = &report.metrics.html_analysis;

            println!("📊 Metrics Breakdown:");
            println!("   Content ({:.1}%):", metrics.content.word_count);
            println!(
                "     Words: {}, Sentences: {}, Paragraphs: {}",
                metrics.content.word_count,
                metrics.content.sentence_count,
                metrics.structure.paragraph_count
            );

            println!("   Structure:");
            println!(
                "     Headings: {} (depth: {})",
                metrics.structure.headings_count, metrics.structure.heading_depth
            );

            println!("   SEO:");
            println!("     Title: {} chars", metrics.seo.title_len);
            println!(
                "     Meta desc: {}",
                if metrics.seo.meta_desc_len.is_some() {
                    "present"
                } else {
                    "missing"
                }
            );
            println!("     OG tags: {}", metrics.seo.og_tags);

            println!("   Technical:");
            println!("     HTML size: {} bytes", metrics.technical.html_bytes);
            println!(
                "     Tech score: {:.1}/100",
                metrics.technical.technical_score
            );

            // Analysis notes
            if !report.notes.is_empty() {
                println!();
                println!("💡 Analysis Notes:");
                for (i, note) in report.notes.iter().take(5).enumerate() {
                    println!("   {}. {}", i + 1, note);
                }
                if report.notes.len() > 5 {
                    println!("   ... and {} more notes", report.notes.len() - 5);
                }
            }
        }
        Err(e) => println!("❌ Comprehensive analysis failed: {}", e),
    }

    println!();
    println!("🎉 Advanced Features examples completed!");
    println!();
    println!("💡 Key Takeaways:");
    println!("   • Enable NLP features for advanced content analysis");
    println!("   • Use link checking to validate external references");
    println!("   • Handle edge cases gracefully with proper error handling");
    println!("   • Optimize analyzer settings for batch processing performance");
    println!("   • Access comprehensive metrics and metadata from detailed reports");

    Ok(())
}