auditmysite 0.26.0

Resource-efficient WCAG 2.1 Accessibility Checker in Rust
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Content Chunk Optimizer
//!
//! Analyzes page content structure for optimal chunking in RAG/embedding
//! pipelines. Evaluates heading-based segmentation, section lengths,
//! and semantic coherence heuristics.

use serde::{Deserialize, Serialize};

use super::{build_dimension, AiSignal, DimensionScore};

/// Content chunk analysis result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkAnalysis {
    /// Dimension score (0–100) with individual signals
    pub dimension: DimensionScore,
    /// Detected content sections with their properties
    pub sections: Vec<ContentSection>,
    /// Recommended chunk strategy
    pub recommendation: String,
}

/// A detected content section
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentSection {
    /// Section heading (or "Einleitung" for content before first heading)
    pub heading: String,
    /// Heading level (1-6, 0 for intro)
    pub level: u32,
    /// Estimated word count
    pub word_count: u32,
    /// Quality assessment
    pub quality: ChunkQuality,
}

/// Quality of a content section as a chunk
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChunkQuality {
    /// Optimal size (100–800 words)
    Optimal,
    /// Too short for meaningful embedding (< 100 words)
    TooShort,
    /// Too long, should be split (> 800 words)
    TooLong,
    /// Acceptable but not ideal
    Acceptable,
}

impl std::fmt::Display for ChunkQuality {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChunkQuality::Optimal => write!(f, "Optimal"),
            ChunkQuality::TooShort => write!(f, "Zu kurz"),
            ChunkQuality::TooLong => write!(f, "Zu lang"),
            ChunkQuality::Acceptable => write!(f, "Akzeptabel"),
        }
    }
}

/// Input data for chunk analysis
pub(crate) struct ChunkInput {
    pub headings: Vec<HeadingInfo>,
    pub total_word_count: u32,
    pub has_semantic_html: bool,
    pub has_article_tag: bool,
    pub has_section_tags: bool,
}

/// A heading found in the content
pub(crate) struct HeadingInfo {
    pub text: String,
    pub level: u32,
    pub word_count_after: u32,
}

pub(crate) fn analyze_chunks(input: &ChunkInput) -> ChunkAnalysis {
    // Build sections from headings
    let sections = build_sections(input);
    let section_count = sections.len();

    let optimal_count = sections
        .iter()
        .filter(|s| s.quality == ChunkQuality::Optimal)
        .count();
    let too_long_count = sections
        .iter()
        .filter(|s| s.quality == ChunkQuality::TooLong)
        .count();
    let too_short_count = sections
        .iter()
        .filter(|s| s.quality == ChunkQuality::TooShort)
        .count();

    let mut signals = Vec::new();

    // 1. Section count — enough sections for meaningful chunks
    let good_section_count = (3..=30).contains(&section_count);
    signals.push(AiSignal {
        name: "Abschnittszahl".into(),
        present: good_section_count,
        weight: 0.15,
        detail: if section_count < 3 {
            format!(
                "Nur {} Abschnitte — zu wenig für granulare Chunk-Bildung",
                section_count
            )
        } else if section_count > 30 {
            format!(
                "{} Abschnitte — sehr fragmentiert, kann Kontext verteilen",
                section_count
            )
        } else {
            format!(
                "{} Abschnitte — gute Granularität für Chunks",
                section_count
            )
        },
    });

    // 2. Optimal chunk ratio
    let optimal_ratio = if section_count > 0 {
        optimal_count as f32 / section_count as f32
    } else {
        0.0
    };
    signals.push(AiSignal {
        name: "Heuristik: Abschnittslänge".into(),
        present: optimal_ratio >= 0.5,
        weight: 0.20,
        detail: format!(
            "Heuristik: {} von {} Abschnitten liegen im Bereich 100–800 Wörter ({:.0}%). \
             Richtwert, keine standardisierte Metrik.",
            optimal_count,
            section_count,
            optimal_ratio * 100.0
        ),
    });

    // 3. No oversized sections
    let no_oversized = too_long_count == 0;
    signals.push(AiSignal {
        name: "Keine Übergroßen Abschnitte".into(),
        present: no_oversized,
        weight: 0.15,
        detail: if no_oversized {
            "Kein Abschnitt über 800 Wörter — gut für Token-Limits".into()
        } else {
            format!(
                "{} Abschnitte über 800 Wörter — sollten aufgeteilt werden",
                too_long_count
            )
        },
    });

    // 4. Minimal fragment ratio
    let low_fragment = too_short_count as f32 / (section_count.max(1) as f32) < 0.3;
    signals.push(AiSignal {
        name: "Wenig Fragmente".into(),
        present: low_fragment,
        weight: 0.10,
        detail: if low_fragment {
            format!(
                "Nur {} Kurzabschnitte (<100 Wörter) — wenig Informationsverlust",
                too_short_count
            )
        } else {
            format!(
                "{} Kurzabschnitte — viele Fragmente können Kontext verlieren",
                too_short_count
            )
        },
    });

    // 5. Heading hierarchy — clean hierarchy enables tree-based chunking
    let has_hierarchy =
        input.headings.iter().any(|h| h.level >= 2) && input.headings.iter().any(|h| h.level >= 3);
    signals.push(AiSignal {
        name: "Hierarchische Gliederung".into(),
        present: has_hierarchy,
        weight: 0.10,
        detail: if has_hierarchy {
            "Mehrstufige Heading-Hierarchie — rekursive Chunk-Strategien möglich".into()
        } else {
            "Flache Heading-Struktur — nur sequenzielles Chunking möglich".into()
        },
    });

    // 6. Semantic HTML usage
    signals.push(AiSignal {
        name: "Semantisches HTML".into(),
        present: input.has_semantic_html,
        weight: 0.10,
        detail: if input.has_semantic_html {
            "Semantische Elemente (article, section, nav) — erleichtert Bereichs-Erkennung".into()
        } else {
            "Kaum semantisches HTML — Chunks nur heading-basiert möglich".into()
        },
    });

    // 7. Content/word density per section
    let avg_words = if section_count > 0 {
        input.total_word_count / section_count as u32
    } else {
        input.total_word_count
    };
    let good_density = (100..=500).contains(&avg_words);
    signals.push(AiSignal {
        name: "Abschnittsdichte".into(),
        present: good_density,
        weight: 0.10,
        detail: format!(
            "Ø {} Wörter/Abschnitt — {}",
            avg_words,
            if good_density {
                "optimaler Bereich für Embeddings"
            } else if avg_words < 100 {
                "zu dünn für gehaltvolle Embeddings"
            } else {
                "zu dicht, Split empfohlen"
            }
        ),
    });

    // 8. Article/section tags
    let has_article = input.has_article_tag || input.has_section_tags;
    signals.push(AiSignal {
        name: "Content-Begrenzung".into(),
        present: has_article,
        weight: 0.10,
        detail: if has_article {
            "article/section-Tags vorhanden — Hauptinhalt abgrenzbar".into()
        } else {
            "Kein article/section — Hauptinhalt nicht klar abgegrenzt".into()
        },
    });

    // Build recommendation
    let recommendation = if optimal_ratio >= 0.7 && no_oversized {
        "Content ist gut für RAG/Embedding-Pipelines geeignet. Heading-basiertes Chunking empfohlen."
            .to_string()
    } else if too_long_count > 0 && has_hierarchy {
        format!(
            "{} übergroße Abschnitte sollten an H3/H4-Grenzen aufgeteilt werden. \
             Rekursives Splitting nach Heading-Level empfohlen.",
            too_long_count
        )
    } else if section_count < 3 {
        "Zu wenig Gliederung für effektives Chunking. \
         Zusätzliche Zwischenüberschriften würden die Extrahierbarkeit verbessern."
            .to_string()
    } else {
        format!(
            "Gemischte Inhaltsstruktur: {} Abschnitte optimal, {} zu kurz, {} zu lang. \
             Mehr Zwischenüberschriften verbessern die Lesbarkeit für KI-Systeme.",
            optimal_count, too_short_count, too_long_count
        )
    };

    ChunkAnalysis {
        dimension: build_dimension("Technische KI-Lesbarkeit", &signals),
        sections,
        recommendation,
    }
}

fn build_sections(input: &ChunkInput) -> Vec<ContentSection> {
    let mut sections = Vec::new();

    if input.headings.is_empty() {
        // No headings: the entire content is one chunk
        sections.push(ContentSection {
            heading: "Gesamter Inhalt".into(),
            level: 0,
            word_count: input.total_word_count,
            quality: classify_chunk_size(input.total_word_count),
        });
        return sections;
    }

    // First heading might have content before it
    if let Some(first) = input.headings.first() {
        let intro_words = input.total_word_count.saturating_sub(
            input
                .headings
                .iter()
                .map(|h| h.word_count_after)
                .sum::<u32>(),
        );
        if intro_words > 20 {
            sections.push(ContentSection {
                heading: "Einleitung".into(),
                level: 0,
                word_count: intro_words,
                quality: classify_chunk_size(intro_words),
            });
        }

        // Each heading starts a section
        for h in &input.headings {
            sections.push(ContentSection {
                heading: if h.text.chars().count() > 80 {
                    format!("{}…", h.text.chars().take(77).collect::<String>())
                } else {
                    h.text.clone()
                },
                level: h.level,
                word_count: h.word_count_after,
                quality: classify_chunk_size(h.word_count_after),
            });
        }

        let _ = first; // suppress unused warning
    }

    sections
}

fn classify_chunk_size(words: u32) -> ChunkQuality {
    match words {
        0..=50 => ChunkQuality::TooShort,
        51..=99 => ChunkQuality::Acceptable,
        100..=800 => ChunkQuality::Optimal,
        801..=1200 => ChunkQuality::Acceptable,
        _ => ChunkQuality::TooLong,
    }
}

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

    fn rich_input() -> ChunkInput {
        ChunkInput {
            headings: vec![
                HeadingInfo {
                    text: "Introduction".into(),
                    level: 1,
                    word_count_after: 250,
                },
                HeadingInfo {
                    text: "Core Concepts".into(),
                    level: 2,
                    word_count_after: 400,
                },
                HeadingInfo {
                    text: "Deep Dive".into(),
                    level: 3,
                    word_count_after: 300,
                },
                HeadingInfo {
                    text: "Conclusion".into(),
                    level: 2,
                    word_count_after: 150,
                },
            ],
            total_word_count: 1100,
            has_semantic_html: true,
            has_article_tag: true,
            has_section_tags: true,
        }
    }

    fn minimal_input() -> ChunkInput {
        ChunkInput {
            headings: vec![],
            total_word_count: 0,
            has_semantic_html: false,
            has_article_tag: false,
            has_section_tags: false,
        }
    }

    #[test]
    fn rich_input_produces_high_score() {
        let result = analyze_chunks(&rich_input());
        assert!(result.dimension.score >= 60);
        assert_eq!(result.dimension.name, "Technische KI-Lesbarkeit");
        assert!(!result.sections.is_empty());
    }

    #[test]
    fn minimal_input_produces_single_section_low_score() {
        let result = analyze_chunks(&minimal_input());
        // No headings → one section covering all 0 words
        assert_eq!(result.sections.len(), 1);
        assert_eq!(result.sections[0].heading, "Gesamter Inhalt");
        assert_eq!(result.sections[0].quality, ChunkQuality::TooShort);
        assert!(result.dimension.score <= 30);
    }

    #[test]
    fn oversized_section_penalizes_score() {
        let small_input = ChunkInput {
            headings: vec![
                HeadingInfo {
                    text: "Intro".into(),
                    level: 1,
                    word_count_after: 300,
                },
                HeadingInfo {
                    text: "Body".into(),
                    level: 2,
                    word_count_after: 300,
                },
                HeadingInfo {
                    text: "End".into(),
                    level: 2,
                    word_count_after: 300,
                },
            ],
            total_word_count: 900,
            has_semantic_html: true,
            has_article_tag: true,
            has_section_tags: true,
        };
        let large_input = ChunkInput {
            headings: vec![
                HeadingInfo {
                    text: "Intro".into(),
                    level: 1,
                    word_count_after: 2000,
                },
                HeadingInfo {
                    text: "Body".into(),
                    level: 2,
                    word_count_after: 300,
                },
                HeadingInfo {
                    text: "End".into(),
                    level: 2,
                    word_count_after: 300,
                },
            ],
            total_word_count: 2600,
            has_semantic_html: true,
            has_article_tag: true,
            has_section_tags: true,
        };
        let small_score = analyze_chunks(&small_input).dimension.score;
        let large_score = analyze_chunks(&large_input).dimension.score;
        assert!(small_score > large_score);
    }

    #[test]
    fn classify_chunk_size_boundaries() {
        assert_eq!(classify_chunk_size(0), ChunkQuality::TooShort);
        assert_eq!(classify_chunk_size(50), ChunkQuality::TooShort);
        assert_eq!(classify_chunk_size(51), ChunkQuality::Acceptable);
        assert_eq!(classify_chunk_size(100), ChunkQuality::Optimal);
        assert_eq!(classify_chunk_size(800), ChunkQuality::Optimal);
        assert_eq!(classify_chunk_size(801), ChunkQuality::Acceptable);
        assert_eq!(classify_chunk_size(1200), ChunkQuality::Acceptable);
        assert_eq!(classify_chunk_size(1201), ChunkQuality::TooLong);
    }

    #[test]
    fn hierarchy_requires_both_h2_and_h3() {
        let flat_input = ChunkInput {
            headings: vec![
                HeadingInfo {
                    text: "A".into(),
                    level: 2,
                    word_count_after: 200,
                },
                HeadingInfo {
                    text: "B".into(),
                    level: 2,
                    word_count_after: 200,
                },
                HeadingInfo {
                    text: "C".into(),
                    level: 2,
                    word_count_after: 200,
                },
            ],
            total_word_count: 600,
            has_semantic_html: false,
            has_article_tag: false,
            has_section_tags: false,
        };
        let result = analyze_chunks(&flat_input);
        let hier_signal = result
            .dimension
            .signals
            .iter()
            .find(|s| s.name == "Hierarchische Gliederung")
            .expect("signal must exist");
        // Only H2, no H3 → flat
        assert!(!hier_signal.present);
    }
}