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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/// Scoring function implementations for profile-aware metrics
/// This module provides concrete implementations of different scoring algorithms
use crate::metrics::definitions::{
    BonusCondition, BonusConditionType, LinearScorer, MetricScorer, MetricValue,
    ProfileMetricConfig, ScoringFunction, ValidationRule,
};

#[derive(Debug, thiserror::Error)]
pub enum ScoringError {
    #[error("Invalid metric value: {0}")]
    InvalidValue(String),

    #[error("Validation failed: {0}")]
    ValidationError(String),

    #[error("Unknown scoring function: {0}")]
    UnknownFunction(String),
}

/// Scoring context provides additional information for complex scoring decisions
pub struct ScoringContext {
    pub profile_name: String,
    pub content_type: String,
    pub page_metrics: Option<crate::models::models::PageMetrics>,
}

/// Enhanced metric scorer that can use context for complex scoring decisions
pub trait EnhancedMetricScorer: MetricScorer {
    fn score_with_context(
        &self,
        value: MetricValue,
        config: &ProfileMetricConfig,
        _context: &ScoringContext,
    ) -> f32 {
        // Default implementation falls back to standard scoring
        self.score_metric(value, config)
    }
}

/// Word count scorer with profile-aware content expectations
pub struct WordCountScorer;

impl MetricScorer for WordCountScorer {
    fn score_metric(&self, value: MetricValue, config: &ProfileMetricConfig) -> f32 {
        let word_count = value.as_f32();
        let thresholds = &config.thresholds;

        // Use exponential scoring for content-heavy profiles
        let base_score = if word_count == 0.0 {
            0.0
        } else if word_count >= thresholds.excellent {
            // ✅ FIX: Reward excellence beyond threshold (up to 105 for exceptional content)
            // Instead of capping at 100, continue rewarding up to 2x excellent threshold
            let excellence_multiplier = (word_count / thresholds.excellent).min(2.0);
            (100.0 + (excellence_multiplier - 1.0) * 5.0).min(105.0)
        } else if word_count >= thresholds.good {
            let range = thresholds.excellent - thresholds.good;
            let position = (word_count - thresholds.good) / range;
            80.0 + (position * 20.0)
        } else if word_count >= thresholds.fair {
            let range = thresholds.good - thresholds.fair;
            let position = (word_count - thresholds.fair) / range;
            60.0 + (position * 20.0)
        } else if word_count >= thresholds.poor {
            let range = thresholds.fair - thresholds.poor;
            let position = (word_count - thresholds.poor) / range;
            30.0 + (position * 30.0)
        } else {
            // Heavy penalty for very low word counts
            (word_count / thresholds.poor) * 30.0
        };

        // Apply profile-specific penalty multiplier for severe deficiencies
        if word_count < thresholds.poor * 0.5 {
            let penalty_factor = 1.0 / config.penalty_multiplier.max(1.0);
            (base_score * penalty_factor).clamp(0.0, 30.0)
        } else {
            base_score.clamp(0.0, 105.0)  // ✅ INCREASED from 100.0 to 105.0
        }
    }

    fn apply_bonuses(
        &self,
        base_score: f32,
        value: MetricValue,
        conditions: &[BonusCondition],
    ) -> f32 {
        let mut final_score = base_score;
        let numeric_value = value.as_f32();

        for condition in conditions {
            let bonus_applies = match &condition.condition_type {
                BonusConditionType::ValueBetween { min, max } => {
                    numeric_value >= *min && numeric_value <= *max
                }
                BonusConditionType::ValueAbove { threshold } => numeric_value > *threshold,
                BonusConditionType::ValueBelow { threshold } => numeric_value < *threshold,
                BonusConditionType::ValueEquals { target } => (numeric_value - target).abs() < 0.01,
            };

            if bonus_applies {
                final_score += condition.bonus_points;
            }
        }

        // ✅ Allow up to 110 for WordCountScorer to reward exceptional content
        final_score.clamp(0.0, 110.0)
    }

    fn validate_metric_value(
        &self,
        value: &MetricValue,
        rules: &[ValidationRule],
    ) -> Result<(), String> {
        let linear_scorer = LinearScorer {
            min_value: 0.0,
            max_value: 5000.0,
            reverse_scoring: false,
        };
        linear_scorer.validate_metric_value(value, rules)
    }
}

impl EnhancedMetricScorer for WordCountScorer {
    fn score_with_context(
        &self,
        value: MetricValue,
        config: &ProfileMetricConfig,
        context: &ScoringContext,
    ) -> f32 {
        let word_count = value.as_f32();
        let mut base_score = self.score_metric(value.clone(), config);

        // Apply context-specific adjustments
        match context.profile_name.as_str() {
            "content_article" => {
                // Bonus for content articles with substantial word count
                if word_count > 2000.0 {
                    base_score += 5.0;
                }
            }
            "news" => {
                // News articles shouldn't be too long
                if word_count > 1200.0 {
                    base_score *= 0.9; // Small penalty for overly long news
                }
            }
            "product" => {
                let word_count = value.as_f32();
                // Product pages prefer concise content
                if word_count > 500.0 {
                    base_score *= 0.85; // Penalty for verbose product descriptions
                }
            }
            _ => {}
        }

        base_score.clamp(0.0, 100.0)
    }
}

/// Readability scorer that considers profile-specific reading levels
pub struct ReadabilityScorer;

impl MetricScorer for ReadabilityScorer {
    fn score_metric(&self, value: MetricValue, config: &ProfileMetricConfig) -> f32 {
        let fk_score = match value {
            MetricValue::OptionF32(Some(score)) => score,
            MetricValue::F32(score) => score,
            _ => return 50.0, // Default score for missing readability
        };

        let thresholds = &config.thresholds;

        // Reverse scoring: lower FK score = better readability = higher score
        let base_score = if fk_score <= thresholds.excellent {
            100.0
        } else if fk_score <= thresholds.good {
            let range = thresholds.good - thresholds.excellent;
            let position = (fk_score - thresholds.excellent) / range;
            100.0 - (position * 20.0)
        } else if fk_score <= thresholds.fair {
            let range = thresholds.fair - thresholds.good;
            let position = (fk_score - thresholds.good) / range;
            80.0 - (position * 20.0)
        } else if fk_score <= thresholds.poor {
            let range = thresholds.poor - thresholds.fair;
            let position = (fk_score - thresholds.fair) / range;
            60.0 - (position * 30.0)
        } else {
            // Very difficult text
            30.0 - ((fk_score - thresholds.poor) * 2.0).min(25.0)
        };

        base_score.clamp(0.0, 100.0)
    }

    fn apply_bonuses(
        &self,
        base_score: f32,
        value: MetricValue,
        conditions: &[BonusCondition],
    ) -> f32 {
        let fk_score = value.as_f32();
        let mut final_score = base_score;

        for condition in conditions {
            let bonus_applies = match &condition.condition_type {
                BonusConditionType::ValueBetween { min, max } => {
                    fk_score >= *min && fk_score <= *max
                }
                BonusConditionType::ValueBelow { threshold } => fk_score < *threshold,
                _ => false,
            };

            if bonus_applies {
                final_score += condition.bonus_points;
            }
        }

        final_score.clamp(0.0, 100.0)
    }

    fn validate_metric_value(
        &self,
        value: &MetricValue,
        _rules: &[ValidationRule],
    ) -> Result<(), String> {
        match value {
            MetricValue::OptionF32(Some(score)) | MetricValue::F32(score) => {
                if score.is_nan() || score.is_infinite() {
                    return Err("Readability score must be a valid number".to_string());
                }
                if *score < 0.0 || *score > 30.0 {
                    return Err("Readability score should be between 0 and 30".to_string());
                }
            }
            MetricValue::OptionF32(None) => {} // None is acceptable
            _ => return Err("Invalid readability value type".to_string()),
        }
        Ok(())
    }
}

impl EnhancedMetricScorer for ReadabilityScorer {
    fn score_with_context(
        &self,
        value: MetricValue,
        config: &ProfileMetricConfig,
        context: &ScoringContext,
    ) -> f32 {
        let fk_score = value.as_f32();
        let mut base_score = self.score_metric(value.clone(), config);

        // Profile-specific readability adjustments
        match context.profile_name.as_str() {
            "content_article" => {
                // Academic/professional content can have higher complexity
                if fk_score > 15.0 {
                    base_score += 5.0; // Bonus for sophisticated language
                }
            }
            "news" => {
                // News should be very readable
                if fk_score > 12.0 {
                    base_score -= 10.0; // Penalty for complex news
                }
            }
            "general" => {
                // Standard web content should be accessible
                if fk_score > 14.0 {
                    base_score -= 5.0;
                }
            }
            _ => {}
        }

        base_score.clamp(0.0, 100.0)
    }
}

/// Image count scorer with profile-specific visual expectations
pub struct ImageCountScorer;

impl MetricScorer for ImageCountScorer {
    fn score_metric(&self, value: MetricValue, config: &ProfileMetricConfig) -> f32 {
        let image_count = value.as_f32();
        let thresholds = &config.thresholds;

        let base_score = if image_count >= thresholds.excellent {
            100.0
        } else if image_count >= thresholds.good {
            let range = (thresholds.excellent - thresholds.good).max(0.001);
            let position = ((image_count - thresholds.good) / range).clamp(0.0, 1.0);
            80.0 + (position * 20.0)
        } else if image_count >= thresholds.fair {
            let range = (thresholds.good - thresholds.fair).max(0.001);
            let position = ((image_count - thresholds.fair) / range).clamp(0.0, 1.0);
            60.0 + (position * 20.0)
        } else if image_count >= thresholds.poor {
            let range = (thresholds.fair - thresholds.poor).max(0.001);
            let position = ((image_count - thresholds.poor) / range).clamp(0.0, 1.0);
            30.0 + (position * 30.0)
        } else if image_count == 0.0 {
            // No penalty for zero images in some profiles
            if thresholds.poor == 0.0 {
                70.0
            } else {
                0.0
            }
        } else {
            (image_count / thresholds.poor) * 30.0
        };

        base_score.clamp(0.0, 100.0)
    }

    fn apply_bonuses(
        &self,
        base_score: f32,
        value: MetricValue,
        conditions: &[BonusCondition],
    ) -> f32 {
        let linear_scorer = LinearScorer {
            min_value: 0.0,
            max_value: 50.0,
            reverse_scoring: false,
        };
        linear_scorer.apply_bonuses(base_score, value, conditions)
    }

    fn validate_metric_value(
        &self,
        value: &MetricValue,
        rules: &[ValidationRule],
    ) -> Result<(), String> {
        let linear_scorer = LinearScorer {
            min_value: 0.0,
            max_value: 50.0,
            reverse_scoring: false,
        };
        linear_scorer.validate_metric_value(value, rules)
    }
}

impl EnhancedMetricScorer for ImageCountScorer {
    fn score_with_context(
        &self,
        value: MetricValue,
        config: &ProfileMetricConfig,
        context: &ScoringContext,
    ) -> f32 {
        let image_count = value.as_f32();
        let mut base_score = self.score_metric(value.clone(), config);

        // Profile-specific adjustments
        match context.profile_name.as_str() {
            "product" => {
                // Product pages heavily benefit from multiple images
                if image_count >= 5.0 {
                    base_score += 10.0; // Significant bonus for rich visual content
                }
            }
            "portfolio" => {
                // Portfolio sites are expected to be image-heavy
                if image_count >= 8.0 {
                    base_score += 8.0;
                }
            }
            "content_article" => {
                // Articles benefit from some images but not too many
                if image_count > 10.0 {
                    base_score *= 0.9; // Small penalty for too many images
                }
            }
            _ => {}
        }

        base_score.clamp(0.0, 100.0)
    }
}

/// Factory function to create enhanced scorers
pub fn create_enhanced_scorer(
    scoring_function: &ScoringFunction,
    metric_name: &str,
) -> Box<dyn EnhancedMetricScorer> {
    match metric_name {
        "word_count" => Box::new(WordCountScorer),
        "readability_fk" => Box::new(ReadabilityScorer),
        "images_count" => Box::new(ImageCountScorer),
        _ => {
            // For other metrics, wrap the standard scorer
            let standard_scorer =
                crate::metrics::definitions::create_metric_scorer(scoring_function);
            Box::new(StandardScorerWrapper {
                scorer: standard_scorer,
            })
        }
    }
}

/// Wrapper to make standard scorers compatible with enhanced interface
struct StandardScorerWrapper {
    scorer: Box<dyn MetricScorer>,
}

impl MetricScorer for StandardScorerWrapper {
    fn score_metric(&self, value: MetricValue, config: &ProfileMetricConfig) -> f32 {
        self.scorer.score_metric(value, config)
    }

    fn apply_bonuses(
        &self,
        base_score: f32,
        value: MetricValue,
        conditions: &[BonusCondition],
    ) -> f32 {
        self.scorer.apply_bonuses(base_score, value, conditions)
    }

    fn validate_metric_value(
        &self,
        value: &MetricValue,
        rules: &[ValidationRule],
    ) -> Result<(), String> {
        self.scorer.validate_metric_value(value, rules)
    }
}

impl EnhancedMetricScorer for StandardScorerWrapper {
    fn score_with_context(
        &self,
        value: MetricValue,
        config: &ProfileMetricConfig,
        _context: &ScoringContext,
    ) -> f32 {
        // Standard wrapper just uses the base scorer
        self.score_metric(value, config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metrics::definitions::{ProfileMetricConfig, ThresholdSet};

    #[test]
    fn test_word_count_scorer() {
        let scorer = WordCountScorer;
        let config = ProfileMetricConfig {
            weight: 0.25,
            enabled: true,
            thresholds: ThresholdSet {
                excellent: 1500.0,
                good: 800.0,
                fair: 400.0,
                poor: 100.0,
            },
            penalty_multiplier: 2.0,
            bonus_conditions: Vec::new(),
            scoring_function_override: None,
        };

        // Test excellent score
        let score = scorer.score_metric(MetricValue::Usize(1600), &config);
        assert!(score >= 95.0);

        // Test poor score with penalty
        let score = scorer.score_metric(MetricValue::Usize(50), &config); // Below poor threshold
        assert!(score <= 25.0); // Should be heavily penalized

        // Test zero word count
        let score = scorer.score_metric(MetricValue::Usize(0), &config);
        assert_eq!(score, 0.0);
    }

    #[test]
    fn test_readability_scorer() {
        let scorer = ReadabilityScorer;
        let config = ProfileMetricConfig {
            weight: 0.20,
            enabled: true,
            thresholds: ThresholdSet {
                excellent: 8.0,
                good: 12.0,
                fair: 16.0,
                poor: 20.0,
            },
            penalty_multiplier: 1.5,
            bonus_conditions: Vec::new(),
            scoring_function_override: None,
        };

        // Test excellent readability (low FK score)
        let score = scorer.score_metric(MetricValue::OptionF32(Some(6.0)), &config);
        assert!(score >= 95.0);

        // Test poor readability (high FK score)
        let score = scorer.score_metric(MetricValue::OptionF32(Some(25.0)), &config);
        assert!(score <= 30.0);

        // Test missing readability
        let score = scorer.score_metric(MetricValue::OptionF32(None), &config);
        assert_eq!(score, 50.0);
    }
}