swarmauri_evaluatorpool_accessibility 0.1.2.dev1__py3-none-any.whl → 0.3.0.dev2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,350 +1,129 @@
1
- import logging
2
- import importlib
3
- import inspect
4
- from pathlib import Path
5
- from typing import Any, Dict, List, Literal, Optional
1
+ # File: swarmauri_standard/evaluator_pools/AccessibilityEvaluatorPool.py
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Dict, List, Literal, Sequence
6
5
 
7
6
  from swarmauri_base.ComponentBase import ComponentBase
8
7
  from swarmauri_base.evaluator_pools.EvaluatorPoolBase import EvaluatorPoolBase
9
- from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
10
-
11
- from swarmauri_standard.programs.Program import Program
8
+ from swarmauri_core.evaluators.IEvaluate import IEvaluate
12
9
 
13
- logger = logging.getLogger(__name__)
10
+ # ─────────────────────────────────────────────────────────────────────────────
11
+ # bring the default evaluators into scope
12
+ # adjust the import paths if your project lays them out differently
13
+ # ─────────────────────────────────────────────────────────────────────────────
14
+ from . import ( # noqa: E402
15
+ AutomatedReadabilityIndexEvaluator,
16
+ ColemanLiauIndexEvaluator,
17
+ FleschKincaidGradeEvaluator,
18
+ FleschReadingEaseEvaluator,
19
+ GunningFogEvaluator,
20
+ )
14
21
 
15
22
 
16
23
  @ComponentBase.register_type(EvaluatorPoolBase, "AccessibilityEvaluatorPool")
17
24
  class AccessibilityEvaluatorPool(EvaluatorPoolBase):
18
25
  """
19
- Evaluator pool that runs a suite of accessibility and readability evaluators
20
- across a Program.
26
+ Pool that aggregates classic readability / accessibility metrics.
27
+
28
+ Every contained evaluator **must** satisfy the `IEvaluate` interface:
29
+ • evaluate(program: IProgram, **kw) -> tuple[float, dict]
30
+ • reset() -> None
21
31
 
22
- This pool iterates through all files in a Program and invokes each of the
23
- Accessibility & Readability evaluators, then aggregates a combined score.
32
+ The pool itself follows the contracts defined by `EvaluatorPoolBase`
33
+ (thread-safe registry, concurrent dispatch, aggregation hook, etc.).
24
34
  """
25
35
 
26
36
  type: Literal["AccessibilityEvaluatorPool"] = "AccessibilityEvaluatorPool"
27
37
 
38
+ # ------------------------------------------------------------------ #
39
+ # construction
40
+ # ------------------------------------------------------------------ #
28
41
  def __init__(
29
42
  self,
30
- evaluators: Optional[List[EvaluatorBase]] = None,
31
- weights: Optional[Dict[str, float]] = None,
43
+ evaluators: Sequence[IEvaluate] | None = None,
44
+ weights: Dict[str, float] | None = None,
32
45
  **kwargs: Any,
33
46
  ) -> None:
34
- """
35
- Initialize the AccessibilityEvaluatorPool.
36
-
37
- Parameters
38
- ----------
39
- evaluators : Optional[List[EvaluatorBase]]
40
- List of accessibility and readability evaluators to use
41
- weights : Optional[Dict[str, float]]
42
- Dictionary mapping evaluator names to their weights for score aggregation
43
- **kwargs : Any
44
- Additional keyword arguments
45
- """
46
47
  super().__init__(**kwargs)
47
- self.evaluators = evaluators if evaluators is not None else []
48
- self.weights = weights or {}
49
-
50
- if evaluators is None and not self.evaluators:
51
- self._auto_register_evaluators()
52
-
53
- # Validate that all evaluators are properly initialized
54
- for evaluator in self.evaluators:
55
- if not isinstance(evaluator, EvaluatorBase):
56
- raise TypeError(
57
- f"Expected EvaluatorBase instance, got {type(evaluator)}"
58
- )
59
-
60
- logger.info(
61
- f"Initialized AccessibilityEvaluatorPool with {len(self.evaluators)} evaluators"
62
- )
63
-
64
- def _auto_register_evaluators(self) -> None:
65
- """Instantiate and register all evaluators defined in this package."""
66
- try:
67
- package = importlib.import_module(__package__)
68
- for name in getattr(package, "__all__", []):
69
- if name == "AccessibilityEvaluatorPool":
70
- continue
71
- obj = getattr(package, name, None)
72
- if inspect.isclass(obj) and issubclass(obj, EvaluatorBase):
73
- try:
74
- evaluator = obj()
75
- self.evaluators.append(evaluator)
76
- self.weights.setdefault(obj.__name__, 1.0)
77
- except Exception as e: # pragma: no cover - best effort
78
- logger.warning(f"Failed to instantiate evaluator {name}: {e}")
79
- except Exception as e: # pragma: no cover - best effort
80
- logger.warning(f"Failed automatic evaluator registration: {e}")
81
-
82
- def evaluate(self, program: Program) -> Dict[str, Any]:
83
- """
84
- Evaluate accessibility and readability across all files in a program.
85
-
86
- Parameters
87
- ----------
88
- program : Program
89
- The program to evaluate
90
-
91
- Returns
92
- -------
93
- Dict[str, Any]
94
- Evaluation results containing:
95
- - overall_score: float between 0 and 1
96
- - evaluator_scores: Dict mapping evaluator names to their individual scores
97
- - file_scores: Dict mapping file paths to their individual scores
98
- """
99
- logger.info("Starting accessibility evaluation on program")
100
-
101
- if not self.evaluators:
102
- logger.warning("No evaluators configured, returning empty result")
103
- return {"overall_score": 0.0, "evaluator_scores": {}, "file_scores": {}}
104
-
105
- # Track scores by evaluator and by file
106
- evaluator_scores: Dict[str, float] = {}
107
- file_scores: Dict[str, float] = {}
108
-
109
- # Get all source files from the program
110
- source_files = program.get_source_files()
111
48
 
112
- # Process each file in the program
113
- for file_path, file_content in source_files.items():
114
- file_score = self._evaluate_file(file_path, file_content)
115
- file_scores[str(file_path)] = file_score
116
-
117
- # Calculate scores for each evaluator across all files
118
- for evaluator in self.evaluators:
119
- evaluator_name = evaluator.__class__.__name__
120
- evaluator_result = evaluator.aggregate_results()
121
- evaluator_scores[evaluator_name] = evaluator_result.get("score", 0.0)
122
-
123
- # Calculate overall weighted score
124
- overall_score = self._calculate_overall_score(evaluator_scores)
125
-
126
- result = {
127
- "overall_score": overall_score,
128
- "evaluator_scores": evaluator_scores,
129
- "file_scores": file_scores,
130
- }
131
-
132
- logger.info(
133
- f"Completed accessibility evaluation with overall score: {overall_score:.2f}"
134
- )
135
- return result
136
-
137
- def _evaluate_file(self, file_path: str, file_content: str) -> float:
138
- """
139
- Evaluate a single file using all configured evaluators.
140
-
141
- Parameters
142
- ----------
143
- file_path : str
144
- Path to the file to evaluate
145
- file_content : str
146
- Content of the file to evaluate
147
-
148
- Returns
149
- -------
150
- float
151
- The average score for this file across all evaluators
152
- """
153
- logger.debug(f"Evaluating accessibility for file: {file_path}")
154
-
155
- # Skip files that shouldn't be evaluated for accessibility
156
- if not self._should_evaluate_file(file_path, file_content):
157
- logger.debug(
158
- f"Skipping file {file_path} as it's not suitable for accessibility evaluation"
49
+ # The pool’s registry is a Dict[str, IEvaluate] coming from the base-class
50
+ self.weights: Dict[str, float] = weights or {}
51
+
52
+ # ------------------------------------------------------------------ #
53
+ # 1) caller supplied evaluators → honoured as-is
54
+ # 2) no evaluators supplied (None / empty) → register built-ins
55
+ # ------------------------------------------------------------------ #
56
+ if evaluators:
57
+ for ev in evaluators:
58
+ self.add_evaluator(ev, ev.__class__.__name__)
59
+ else:
60
+ self._register_builtin_evaluators()
61
+
62
+ # custom aggregation that flips “lower-is-better” metrics
63
+ self.set_aggregation_function(self._accessibility_aggregation)
64
+
65
+ if self.logger:
66
+ self.logger.info(
67
+ "AccessibilityEvaluatorPool initialised with %d evaluators",
68
+ self.get_evaluator_count(),
159
69
  )
160
- return 0.0
161
-
162
- file_scores = []
163
70
 
164
- # Run each evaluator on this file
165
- for evaluator in self.evaluators:
71
+ # ------------------------------------------------------------------ #
72
+ # built-in evaluator registration
73
+ # ------------------------------------------------------------------ #
74
+ _BUILTINS: List[type[IEvaluate]] = [
75
+ AutomatedReadabilityIndexEvaluator,
76
+ ColemanLiauIndexEvaluator,
77
+ FleschKincaidGradeEvaluator,
78
+ FleschReadingEaseEvaluator,
79
+ GunningFogEvaluator,
80
+ ]
81
+
82
+ def _register_builtin_evaluators(self) -> None:
83
+ for cls in self._BUILTINS:
166
84
  try:
167
- # Update evaluate_file call to use file_path and file_content
168
- result = evaluator.evaluate_file(file_path, file_content)
169
- score = result.get("score", 0.0)
170
- file_scores.append(score)
171
- logger.debug(
172
- f"Evaluator {evaluator.__class__.__name__} gave score {score:.2f} for {file_path}"
173
- )
174
- except Exception as e:
175
- logger.error(
176
- f"Error evaluating {file_path} with {evaluator.__class__.__name__}: {str(e)}"
177
- )
178
- file_scores.append(0.0)
179
-
180
- # Calculate average score for this file
181
- if file_scores:
182
- avg_score = sum(file_scores) / len(file_scores)
183
- logger.debug(
184
- f"Average accessibility score for {file_path}: {avg_score:.2f}"
185
- )
186
- return avg_score
187
- return 0.0
188
-
189
- def _should_evaluate_file(self, file_path: str, file_content: str) -> bool:
190
- """
191
- Determine if a file should be evaluated for accessibility.
192
-
193
- Parameters
194
- ----------
195
- file_path : str
196
- Path to the file to check
197
- file_content : str
198
- Content of the file to check
199
-
200
- Returns
201
- -------
202
- bool
203
- True if the file should be evaluated, False otherwise
204
- """
205
- # Skip empty files
206
- if not file_content:
207
- return False
208
-
209
- # Skip files that are too large (might cause performance issues)
210
- if len(file_content) > 1_000_000: # 1MB limit
211
- logger.warning(
212
- f"File {file_path} exceeds size limit for accessibility evaluation"
213
- )
214
- return False
215
-
216
- # Skip file types that don't make sense for accessibility evaluation
217
- excluded_extensions = {
218
- ".bin",
219
- ".pyc",
220
- ".pyo",
221
- ".so",
222
- ".dll",
223
- ".exe",
224
- ".png",
225
- ".jpg",
226
- ".jpeg",
227
- ".gif",
228
- ".svg",
229
- ".ico",
230
- ".mp3",
231
- ".mp4",
232
- ".avi",
233
- ".mov",
234
- ".zip",
235
- ".tar",
236
- ".gz",
237
- ".rar",
238
- }
239
-
240
- file_ext = Path(file_path).suffix.lower()
241
- if file_ext in excluded_extensions:
242
- return False
243
-
244
- return True
245
-
246
- def _calculate_overall_score(self, evaluator_scores: Dict[str, float]) -> float:
247
- """
248
- Calculate the overall weighted score based on individual evaluator scores.
249
-
250
- Parameters
251
- ----------
252
- evaluator_scores : Dict[str, float]
253
- Dictionary mapping evaluator names to their scores
254
-
255
- Returns
256
- -------
257
- float
258
- The overall weighted score between 0 and 1
259
- """
260
- if not evaluator_scores:
85
+ inst = cls()
86
+ self.add_evaluator(inst, cls.__name__)
87
+ # default weight = 1 unless already provided
88
+ self.weights.setdefault(cls.__name__, 1.0)
89
+ except Exception as exc: # pragma: no cover
90
+ if self.logger:
91
+ self.logger.error("Failed to instantiate %s: %s", cls.__name__, exc)
92
+
93
+ # ------------------------------------------------------------------ #
94
+ # evaluation – we just rely on the base-class dispatcher
95
+ # ------------------------------------------------------------------ #
96
+ # Nothing to override here; EvaluatorPoolBase will:
97
+ # • spin up a ThreadPoolExecutor
98
+ # • fan-out evaluate() calls
99
+ # • gather (score, metadata) tuples
100
+ # • call self.aggregate() on the individual scores
101
+ # • wrap the result in an `EvalResultBase` instance
102
+
103
+ # ------------------------------------------------------------------ #
104
+ # aggregation helper – unify score direction, apply weights
105
+ # ------------------------------------------------------------------ #
106
+ def _accessibility_aggregation(self, raw_scores: Sequence[float]) -> float:
107
+ """
108
+ Convert individual evaluator scores to a 0–1 scale where “higher is
109
+ better” and return a weighted mean.
110
+
111
+ * FleschReadingEase already gives “higher == easier” → scale to 0-1.
112
+ * All other metrics are “grade-level” indices (lower == easier) → invert.
113
+ """
114
+ names = self.get_evaluator_names()
115
+ if not names:
261
116
  return 0.0
262
117
 
263
- total_weight = 0.0
264
- weighted_sum = 0.0
265
-
266
- for evaluator_name, score in evaluator_scores.items():
267
- # Get weight for this evaluator, default to 1.0 if not specified
268
- weight = self.weights.get(evaluator_name, 1.0)
269
- weighted_sum += score * weight
270
- total_weight += weight
271
-
272
- # Avoid division by zero
273
- if total_weight == 0.0:
274
- return 0.0
275
-
276
- # Ensure the result is between 0 and 1
277
- overall_score = min(1.0, max(0.0, weighted_sum / total_weight))
278
- return overall_score
279
-
280
- def configure(self, config: Dict[str, Any]) -> None:
281
- """
282
- Configure the evaluator pool with the provided configuration.
283
-
284
- Parameters
285
- ----------
286
- config : Dict[str, Any]
287
- Configuration dictionary which may include:
288
- - evaluators: List of evaluator configurations
289
- - weights: Dictionary mapping evaluator names to their weights
290
- """
291
- logger.info("Configuring AccessibilityEvaluatorPool")
292
-
293
- if "weights" in config:
294
- self.weights = config["weights"]
295
- logger.debug(f"Updated evaluator weights: {self.weights}")
296
-
297
- # Other configuration options can be added here
298
-
299
- def add_evaluator(self, evaluator: EvaluatorBase, weight: float = 1.0) -> None:
300
- """
301
- Add an evaluator to the pool with an optional weight.
302
-
303
- Parameters
304
- ----------
305
- evaluator : EvaluatorBase
306
- The evaluator to add
307
- weight : float, default=1.0
308
- The weight to assign to this evaluator
309
- """
310
- if not isinstance(evaluator, EvaluatorBase):
311
- raise TypeError(f"Expected EvaluatorBase instance, got {type(evaluator)}")
312
-
313
- self.evaluators.append(evaluator)
314
- evaluator_name = evaluator.__class__.__name__
315
- self.weights[evaluator_name] = weight
316
- logger.info(f"Added evaluator {evaluator_name} with weight {weight}")
317
-
318
- def remove_evaluator(self, evaluator_name: str) -> bool:
319
- """
320
- Remove an evaluator from the pool by name.
321
-
322
- Parameters
323
- ----------
324
- evaluator_name : str
325
- The name of the evaluator class to remove
326
-
327
- Returns
328
- -------
329
- bool
330
- True if an evaluator was removed, False otherwise
331
- """
332
- for i, evaluator in enumerate(self.evaluators):
333
- if evaluator.__class__.__name__ == evaluator_name:
334
- self.evaluators.pop(i)
335
- self.weights.pop(evaluator_name, None)
336
- logger.info(f"Removed evaluator {evaluator_name}")
337
- return True
338
-
339
- logger.warning(f"No evaluator found with name {evaluator_name}")
340
- return False
341
-
342
- def reset(self) -> None:
343
- """
344
- Reset the evaluator pool, clearing any cached results.
345
- """
346
- logger.info("Resetting AccessibilityEvaluatorPool")
347
-
348
- # Reset each evaluator
349
- for evaluator in self.evaluators:
350
- evaluator.reset()
118
+ total, total_weight = 0.0, 0.0
119
+ for name, score in zip(names, raw_scores):
120
+ # normalise & clamp
121
+ if name == "FleschReadingEaseEvaluator":
122
+ norm = max(0.0, min(1.0, score / 100.0))
123
+ else:
124
+ norm = max(0.0, min(1.0, 1.0 - (score / 20.0))) # 0-20 -> 1-0
125
+ w = self.weights.get(name, 1.0)
126
+ total += norm * w
127
+ total_weight += w
128
+
129
+ return 0.0 if total_weight == 0 else total / total_weight