swarmauri_evaluatorpool_accessibility 0.3.0.dev8__tar.gz → 0.3.0.dev14__tar.gz
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.
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/PKG-INFO +1 -1
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/pyproject.toml +1 -1
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/swarmauri_evaluatorpool_accessibility/AccessibilityEvaluatorPool.py +119 -3
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/swarmauri_evaluatorpool_accessibility/AutomatedReadabilityIndexEvaluator.py +41 -15
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/swarmauri_evaluatorpool_accessibility/ColemanLiauIndexEvaluator.py +29 -4
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/swarmauri_evaluatorpool_accessibility/FleschKincaidGradeEvaluator.py +15 -1
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/swarmauri_evaluatorpool_accessibility/FleschReadingEaseEvaluator.py +18 -10
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/swarmauri_evaluatorpool_accessibility/GunningFogEvaluator.py +8 -1
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/LICENSE +0 -0
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/README.md +0 -0
- {swarmauri_evaluatorpool_accessibility-0.3.0.dev8 → swarmauri_evaluatorpool_accessibility-0.3.0.dev14}/swarmauri_evaluatorpool_accessibility/__init__.py +0 -0
|
@@ -6,6 +6,7 @@ from typing import Any, Dict, List, Literal, Sequence
|
|
|
6
6
|
from swarmauri_base.ComponentBase import ComponentBase
|
|
7
7
|
from swarmauri_base.evaluator_pools.EvaluatorPoolBase import EvaluatorPoolBase
|
|
8
8
|
from swarmauri_core.evaluators.IEvaluate import IEvaluate
|
|
9
|
+
from swarmauri_standard.programs.Program import Program
|
|
9
10
|
|
|
10
11
|
# ─────────────────────────────────────────────────────────────────────────────
|
|
11
12
|
# bring the default evaluators into scope
|
|
@@ -35,6 +36,12 @@ class AccessibilityEvaluatorPool(EvaluatorPoolBase):
|
|
|
35
36
|
|
|
36
37
|
type: Literal["AccessibilityEvaluatorPool"] = "AccessibilityEvaluatorPool"
|
|
37
38
|
|
|
39
|
+
class _EvaluatorRegistry(dict):
|
|
40
|
+
"""Dict-like registry that iterates over values for legacy callers."""
|
|
41
|
+
|
|
42
|
+
def __iter__(self):
|
|
43
|
+
return iter(self.values())
|
|
44
|
+
|
|
38
45
|
# ------------------------------------------------------------------ #
|
|
39
46
|
# construction
|
|
40
47
|
# ------------------------------------------------------------------ #
|
|
@@ -45,6 +52,8 @@ class AccessibilityEvaluatorPool(EvaluatorPoolBase):
|
|
|
45
52
|
**kwargs: Any,
|
|
46
53
|
) -> None:
|
|
47
54
|
super().__init__(**kwargs)
|
|
55
|
+
self.evaluators = self._EvaluatorRegistry()
|
|
56
|
+
self._allow_add = True
|
|
48
57
|
|
|
49
58
|
# The pool’s registry is a Dict[str, IEvaluate] coming from the base-class
|
|
50
59
|
self.weights: Dict[str, float] = weights or {}
|
|
@@ -53,14 +62,15 @@ class AccessibilityEvaluatorPool(EvaluatorPoolBase):
|
|
|
53
62
|
# 1) caller supplied evaluators → honoured as-is
|
|
54
63
|
# 2) no evaluators supplied (None / empty) → register built-ins
|
|
55
64
|
# ------------------------------------------------------------------ #
|
|
56
|
-
if evaluators:
|
|
65
|
+
if evaluators is not None:
|
|
57
66
|
for ev in evaluators:
|
|
58
|
-
self.
|
|
67
|
+
self._register_evaluator_internal(ev, ev.__class__.__name__)
|
|
59
68
|
else:
|
|
60
69
|
self._register_builtin_evaluators()
|
|
61
70
|
|
|
62
71
|
# custom aggregation that flips “lower-is-better” metrics
|
|
63
72
|
self.set_aggregation_function(self._accessibility_aggregation)
|
|
73
|
+
self._allow_add = False
|
|
64
74
|
|
|
65
75
|
if self.logger:
|
|
66
76
|
self.logger.info(
|
|
@@ -83,13 +93,119 @@ class AccessibilityEvaluatorPool(EvaluatorPoolBase):
|
|
|
83
93
|
for cls in self._BUILTINS:
|
|
84
94
|
try:
|
|
85
95
|
inst = cls()
|
|
86
|
-
self.
|
|
96
|
+
self._register_evaluator_internal(inst, cls.__name__)
|
|
87
97
|
# default weight = 1 unless already provided
|
|
88
98
|
self.weights.setdefault(cls.__name__, 1.0)
|
|
89
99
|
except Exception as exc: # pragma: no cover
|
|
90
100
|
if self.logger:
|
|
91
101
|
self.logger.error("Failed to instantiate %s: %s", cls.__name__, exc)
|
|
92
102
|
|
|
103
|
+
def _register_evaluator_internal(self, evaluator: IEvaluate, name: str) -> None:
|
|
104
|
+
super().add_evaluator(evaluator, name)
|
|
105
|
+
|
|
106
|
+
def add_evaluator(self, evaluator: IEvaluate, name: Any = None) -> str: # type: ignore[override]
|
|
107
|
+
"""Legacy behavior: disallow runtime add after initialization."""
|
|
108
|
+
if not self._allow_add:
|
|
109
|
+
raise RuntimeError(
|
|
110
|
+
"AccessibilityEvaluatorPool manages evaluator registration internally"
|
|
111
|
+
)
|
|
112
|
+
if not isinstance(name, str) and name is not None:
|
|
113
|
+
name = evaluator.__class__.__name__
|
|
114
|
+
return super().add_evaluator(evaluator, name)
|
|
115
|
+
|
|
116
|
+
def remove_evaluator(self, name: str) -> bool:
|
|
117
|
+
removed = super().remove_evaluator(name)
|
|
118
|
+
if removed:
|
|
119
|
+
self.weights.pop(name, None)
|
|
120
|
+
return removed
|
|
121
|
+
|
|
122
|
+
def reset(self) -> None:
|
|
123
|
+
for evaluator in self.evaluators.values():
|
|
124
|
+
if hasattr(evaluator, "reset"):
|
|
125
|
+
evaluator.reset()
|
|
126
|
+
|
|
127
|
+
def configure(self, config: Dict[str, Any]) -> None:
|
|
128
|
+
if "weights" in config and isinstance(config["weights"], dict):
|
|
129
|
+
self.weights = dict(config["weights"])
|
|
130
|
+
|
|
131
|
+
def _should_evaluate_file(self, file_path: str, content: Any) -> bool:
|
|
132
|
+
if not content:
|
|
133
|
+
return False
|
|
134
|
+
ext = file_path.rsplit(".", 1)[-1].lower() if "." in file_path else ""
|
|
135
|
+
return ext in {"py", "txt", "md", "html", "htm", "rst"}
|
|
136
|
+
|
|
137
|
+
def _evaluate_file(self, file_path: str, file_content: Any) -> float:
|
|
138
|
+
if not self._should_evaluate_file(file_path, file_content):
|
|
139
|
+
return 0.0
|
|
140
|
+
scores: list[float] = []
|
|
141
|
+
for evaluator in self.evaluators.values():
|
|
142
|
+
evaluate_file = getattr(evaluator, "evaluate_file", None)
|
|
143
|
+
if not callable(evaluate_file):
|
|
144
|
+
continue
|
|
145
|
+
try:
|
|
146
|
+
result = evaluate_file(file_path, file_content)
|
|
147
|
+
if isinstance(result, dict):
|
|
148
|
+
scores.append(float(result.get("score", 0.0)))
|
|
149
|
+
else:
|
|
150
|
+
scores.append(float(result))
|
|
151
|
+
except Exception:
|
|
152
|
+
scores.append(0.0)
|
|
153
|
+
return sum(scores) / len(scores) if scores else 0.0
|
|
154
|
+
|
|
155
|
+
def _calculate_overall_score(self, scores: Dict[str, float]) -> float:
|
|
156
|
+
if not scores:
|
|
157
|
+
return 0.0
|
|
158
|
+
total, total_weight = 0.0, 0.0
|
|
159
|
+
for name, score in scores.items():
|
|
160
|
+
score_f = float(score)
|
|
161
|
+
if name == "FleschReadingEaseEvaluator":
|
|
162
|
+
norm = max(0.0, min(1.0, score_f / 100.0))
|
|
163
|
+
else:
|
|
164
|
+
norm = max(0.0, min(1.0, 1.0 - score_f))
|
|
165
|
+
weight = float(self.weights.get(name, 1.0))
|
|
166
|
+
total += norm * weight
|
|
167
|
+
total_weight += weight
|
|
168
|
+
return 0.0 if total_weight == 0.0 else total / total_weight
|
|
169
|
+
|
|
170
|
+
def _legacy_evaluate(self, program: Program) -> Dict[str, Any]:
|
|
171
|
+
source_files = (
|
|
172
|
+
program.get_source_files() if hasattr(program, "get_source_files") else {}
|
|
173
|
+
)
|
|
174
|
+
file_scores = {
|
|
175
|
+
path: self._evaluate_file(path, content)
|
|
176
|
+
for path, content in source_files.items()
|
|
177
|
+
if self._should_evaluate_file(path, content)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
evaluator_scores: Dict[str, float] = {}
|
|
181
|
+
for name, evaluator in self.evaluators.items():
|
|
182
|
+
agg = getattr(evaluator, "aggregate_results", None)
|
|
183
|
+
if callable(agg):
|
|
184
|
+
try:
|
|
185
|
+
result = agg(file_scores)
|
|
186
|
+
evaluator_scores[name] = float(result.get("score", 0.0))
|
|
187
|
+
except Exception:
|
|
188
|
+
evaluator_scores[name] = 0.0
|
|
189
|
+
else:
|
|
190
|
+
evaluator_scores[name] = 0.0
|
|
191
|
+
|
|
192
|
+
overall = (
|
|
193
|
+
sum(evaluator_scores.values()) / len(evaluator_scores)
|
|
194
|
+
if evaluator_scores
|
|
195
|
+
else 0.0
|
|
196
|
+
)
|
|
197
|
+
return {
|
|
198
|
+
"overall_score": overall,
|
|
199
|
+
"evaluator_scores": evaluator_scores,
|
|
200
|
+
"file_scores": file_scores,
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
def evaluate(self, programs: Any, **kwargs: Any) -> Any: # type: ignore[override]
|
|
204
|
+
# Backward-compatible single-program mode used in unit tests.
|
|
205
|
+
if not isinstance(programs, Sequence) or isinstance(programs, (str, bytes)):
|
|
206
|
+
return self._legacy_evaluate(programs)
|
|
207
|
+
return super().evaluate(programs, **kwargs)
|
|
208
|
+
|
|
93
209
|
# ------------------------------------------------------------------ #
|
|
94
210
|
# evaluation – we just rely on the base-class dispatcher
|
|
95
211
|
# ------------------------------------------------------------------ #
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
# File: peagen/evaluators/AutomatedReadabilityIndexEvaluator.py
|
|
2
2
|
|
|
3
|
+
import os
|
|
3
4
|
import re
|
|
4
5
|
from pathlib import Path
|
|
5
6
|
from typing import Any, Dict, List, Literal, Tuple
|
|
@@ -43,14 +44,16 @@ class AutomatedReadabilityIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
|
43
44
|
expected by EvaluatorPoolBase.
|
|
44
45
|
"""
|
|
45
46
|
|
|
46
|
-
text = self.
|
|
47
|
+
text = self._extract_text_from_program(program)
|
|
47
48
|
|
|
48
49
|
if not text.strip():
|
|
49
|
-
return 0.0, {"error": "no_text"}
|
|
50
|
+
return 0.0, {"error": "no_text", "chars": 0, "words": 0, "sentences": 0}
|
|
50
51
|
|
|
51
52
|
chars = len(text)
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
words_list = self._count_words(text)
|
|
54
|
+
sentences_list = self._count_sentences(text)
|
|
55
|
+
words = len(words_list)
|
|
56
|
+
sents = len(sentences_list)
|
|
54
57
|
|
|
55
58
|
if words == 0 or sents == 0:
|
|
56
59
|
return 0.0, {
|
|
@@ -68,20 +71,41 @@ class AutomatedReadabilityIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
|
68
71
|
# -------------------------------------------------------------------
|
|
69
72
|
# helpers
|
|
70
73
|
# -------------------------------------------------------------------
|
|
71
|
-
def
|
|
74
|
+
def _extract_text_from_program(self, program: Program) -> str:
|
|
72
75
|
"""
|
|
73
|
-
|
|
74
|
-
Supports .txt, .md, .html and any text-like files present
|
|
75
|
-
in program.get_source_files() or program.content.
|
|
76
|
+
Extract text from a program's artifacts or source-files.
|
|
76
77
|
"""
|
|
78
|
+
if hasattr(program, "get_artifacts"):
|
|
79
|
+
segments: List[str] = []
|
|
80
|
+
for artifact in program.get_artifacts() or []:
|
|
81
|
+
path = artifact.get_path()
|
|
82
|
+
if not os.path.exists(path):
|
|
83
|
+
continue
|
|
84
|
+
ext = Path(path).suffix.lower()
|
|
85
|
+
try:
|
|
86
|
+
with open(path, encoding="utf-8") as f:
|
|
87
|
+
raw = f.read()
|
|
88
|
+
if ext in (".md", ".markdown"):
|
|
89
|
+
html = markdown.markdown(raw)
|
|
90
|
+
segments.append(BeautifulSoup(html, "html.parser").get_text())
|
|
91
|
+
elif ext in (".html", ".htm"):
|
|
92
|
+
segments.append(BeautifulSoup(raw, "html.parser").get_text())
|
|
93
|
+
else:
|
|
94
|
+
segments.append(raw)
|
|
95
|
+
except Exception as exc:
|
|
96
|
+
if self.logger:
|
|
97
|
+
self.logger.error("Error parsing %s: %s", path, exc)
|
|
98
|
+
return " ".join(segments)
|
|
99
|
+
|
|
77
100
|
files = (
|
|
78
101
|
program.get_source_files()
|
|
79
102
|
if hasattr(program, "get_source_files")
|
|
80
|
-
else program
|
|
103
|
+
else getattr(program, "content", {})
|
|
81
104
|
)
|
|
82
|
-
|
|
83
105
|
segments: List[str] = []
|
|
84
106
|
for rel_path, data in files.items():
|
|
107
|
+
if not isinstance(data, str):
|
|
108
|
+
continue
|
|
85
109
|
ext = Path(rel_path).suffix.lower()
|
|
86
110
|
try:
|
|
87
111
|
if ext in (".md", ".markdown"):
|
|
@@ -89,19 +113,21 @@ class AutomatedReadabilityIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
|
89
113
|
segments.append(BeautifulSoup(html, "html.parser").get_text())
|
|
90
114
|
elif ext in (".html", ".htm"):
|
|
91
115
|
segments.append(BeautifulSoup(data, "html.parser").get_text())
|
|
92
|
-
else:
|
|
116
|
+
else:
|
|
93
117
|
segments.append(data)
|
|
94
118
|
except Exception as exc:
|
|
95
119
|
if self.logger:
|
|
96
120
|
self.logger.error("Error parsing %s: %s", rel_path, exc)
|
|
97
|
-
|
|
98
121
|
return " ".join(segments)
|
|
99
122
|
|
|
100
123
|
@staticmethod
|
|
101
|
-
def
|
|
124
|
+
def _count_words(text: str) -> List[str]:
|
|
102
125
|
return re.findall(r"\b\w+\b", text.lower())
|
|
103
126
|
|
|
104
127
|
@staticmethod
|
|
105
|
-
def
|
|
128
|
+
def _count_sentences(text: str) -> List[str]:
|
|
129
|
+
if not text.strip():
|
|
130
|
+
return []
|
|
106
131
|
sents = re.split(r"(?<=[.!?])\s+", text)
|
|
107
|
-
|
|
132
|
+
filtered = [s for s in sents if s.strip()]
|
|
133
|
+
return filtered if filtered else [text.strip()]
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import logging
|
|
1
2
|
import re
|
|
2
3
|
from typing import Any, Dict, Literal, Tuple
|
|
3
4
|
|
|
@@ -34,7 +35,7 @@ class ColemanLiauIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
|
34
35
|
# Core scoring logic
|
|
35
36
|
# ──────────────────────────────────────────────────────────────────────
|
|
36
37
|
def _compute_score(self, program: Program, **__) -> Tuple[float, Dict[str, Any]]:
|
|
37
|
-
text = self.
|
|
38
|
+
text = self._get_text_from_program(program)
|
|
38
39
|
|
|
39
40
|
if not text.strip():
|
|
40
41
|
return 0.0, {
|
|
@@ -64,11 +65,31 @@ class ColemanLiauIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
|
64
65
|
grade_level = max(1, round(raw_cli))
|
|
65
66
|
|
|
66
67
|
score = (
|
|
67
|
-
self.
|
|
68
|
+
self._calculate_score(grade_level)
|
|
68
69
|
if self.normalize_scores
|
|
69
70
|
else float(grade_level)
|
|
70
71
|
)
|
|
71
72
|
|
|
73
|
+
if self.logger:
|
|
74
|
+
self.logger.debug(
|
|
75
|
+
"Text analysis: letters=%s words=%s sentences=%s",
|
|
76
|
+
letters,
|
|
77
|
+
words,
|
|
78
|
+
sentences,
|
|
79
|
+
)
|
|
80
|
+
self.logger.debug(
|
|
81
|
+
"Coleman-Liau Index: %.3f (grade=%s)", raw_cli, grade_level
|
|
82
|
+
)
|
|
83
|
+
logging.getLogger(__name__).debug(
|
|
84
|
+
"Text analysis: letters=%s words=%s sentences=%s",
|
|
85
|
+
letters,
|
|
86
|
+
words,
|
|
87
|
+
sentences,
|
|
88
|
+
)
|
|
89
|
+
logging.getLogger(__name__).debug(
|
|
90
|
+
"Coleman-Liau Index: %.3f (grade=%s)", raw_cli, grade_level
|
|
91
|
+
)
|
|
92
|
+
|
|
72
93
|
return score, {
|
|
73
94
|
"grade_level": grade_level,
|
|
74
95
|
"raw_index": raw_cli,
|
|
@@ -83,7 +104,7 @@ class ColemanLiauIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
|
83
104
|
# ──────────────────────────────────────────────────────────────────────
|
|
84
105
|
# Helpers
|
|
85
106
|
# ──────────────────────────────────────────────────────────────────────
|
|
86
|
-
def
|
|
107
|
+
def _get_text_from_program(self, program: Program) -> str:
|
|
87
108
|
for attr in ("output", "source", "content"):
|
|
88
109
|
val = getattr(program, attr, None)
|
|
89
110
|
if isinstance(val, str):
|
|
@@ -112,10 +133,14 @@ class ColemanLiauIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
|
112
133
|
|
|
113
134
|
@staticmethod
|
|
114
135
|
def _count_sentences(text: str) -> int:
|
|
136
|
+
if not text.strip():
|
|
137
|
+
return 0
|
|
115
138
|
hits = re.findall(r"[.!?]+", text)
|
|
116
139
|
return len(hits) if hits else 1
|
|
117
140
|
|
|
118
|
-
def
|
|
141
|
+
def _calculate_score(self, grade_level: int) -> float:
|
|
142
|
+
if not self.normalize_scores:
|
|
143
|
+
return float(grade_level)
|
|
119
144
|
if grade_level == self.target_grade_level:
|
|
120
145
|
return 1.0
|
|
121
146
|
if grade_level <= 1 or grade_level >= self.max_grade_level:
|
|
@@ -128,12 +128,26 @@ class FleschKincaidGradeEvaluator(EvaluatorBase, ComponentBase):
|
|
|
128
128
|
try:
|
|
129
129
|
source_files = program.get_source_files()
|
|
130
130
|
if isinstance(source_files, dict):
|
|
131
|
-
return "
|
|
131
|
+
return " ".join(self._stringify_value(v) for v in source_files.values())
|
|
132
132
|
except Exception as exc:
|
|
133
133
|
if self.logger:
|
|
134
134
|
self.logger.debug(f"Failed to obtain program text: {exc}")
|
|
135
135
|
return ""
|
|
136
136
|
|
|
137
|
+
@staticmethod
|
|
138
|
+
def _stringify_value(value: Any) -> str:
|
|
139
|
+
if isinstance(value, str):
|
|
140
|
+
return value
|
|
141
|
+
if isinstance(value, dict):
|
|
142
|
+
if isinstance(value.get("text"), str):
|
|
143
|
+
return value["text"]
|
|
144
|
+
if isinstance(value.get("content"), str):
|
|
145
|
+
return value["content"]
|
|
146
|
+
return " ".join(str(v) for v in value.values())
|
|
147
|
+
if isinstance(value, list):
|
|
148
|
+
return " ".join(str(v) for v in value)
|
|
149
|
+
return str(value)
|
|
150
|
+
|
|
137
151
|
def _count_sentences(self, text: str) -> int:
|
|
138
152
|
"""
|
|
139
153
|
Count the number of sentences in the text.
|
|
@@ -6,7 +6,6 @@ from pydantic import PrivateAttr
|
|
|
6
6
|
|
|
7
7
|
import nltk
|
|
8
8
|
from nltk.corpus import cmudict
|
|
9
|
-
from nltk.tokenize import sent_tokenize, word_tokenize
|
|
10
9
|
from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
|
|
11
10
|
from swarmauri_base.ComponentBase import ComponentBase
|
|
12
11
|
from swarmauri_standard.programs.Program import Program
|
|
@@ -49,11 +48,12 @@ class FleschReadingEaseEvaluator(EvaluatorBase, ComponentBase):
|
|
|
49
48
|
super().__init__(**kwargs)
|
|
50
49
|
# Download necessary NLTK resources if not already present
|
|
51
50
|
try:
|
|
52
|
-
nltk.data.find("tokenizers/
|
|
51
|
+
nltk.data.find("tokenizers/punkt_tab/english")
|
|
53
52
|
except LookupError:
|
|
54
53
|
if self.logger:
|
|
55
|
-
self.logger.info("Downloading NLTK punkt tokenizer")
|
|
54
|
+
self.logger.info("Downloading NLTK punkt tokenizer resources")
|
|
56
55
|
nltk.download("punkt", quiet=True, download_dir=NLTK_DATA_DIR)
|
|
56
|
+
nltk.download("punkt_tab", quiet=True, download_dir=NLTK_DATA_DIR)
|
|
57
57
|
|
|
58
58
|
try:
|
|
59
59
|
nltk.data.find("corpora/cmudict")
|
|
@@ -98,12 +98,9 @@ class FleschReadingEaseEvaluator(EvaluatorBase, ComponentBase):
|
|
|
98
98
|
# Clean the text (remove extra whitespace, etc.)
|
|
99
99
|
text = self._clean_text(text)
|
|
100
100
|
|
|
101
|
-
# Tokenize
|
|
102
|
-
sentences =
|
|
103
|
-
words =
|
|
104
|
-
|
|
105
|
-
# Filter out punctuation from words
|
|
106
|
-
words = [word for word in words if re.match(r"\w+", word)]
|
|
101
|
+
# Tokenize locally to avoid runtime dependence on punkt resources.
|
|
102
|
+
sentences = self._split_sentences(text)
|
|
103
|
+
words = self._split_words(text)
|
|
107
104
|
|
|
108
105
|
# Count sentences, words, and syllables
|
|
109
106
|
sentence_count = len(sentences)
|
|
@@ -151,12 +148,23 @@ class FleschReadingEaseEvaluator(EvaluatorBase, ComponentBase):
|
|
|
151
148
|
try:
|
|
152
149
|
source_files = program.get_source_files()
|
|
153
150
|
if isinstance(source_files, dict):
|
|
154
|
-
return "
|
|
151
|
+
return " ".join(v for v in source_files.values() if isinstance(v, str))
|
|
155
152
|
except Exception as exc:
|
|
156
153
|
if self.logger:
|
|
157
154
|
self.logger.debug(f"Failed to obtain program text: {exc}")
|
|
158
155
|
return ""
|
|
159
156
|
|
|
157
|
+
@staticmethod
|
|
158
|
+
def _split_sentences(text: str) -> list[str]:
|
|
159
|
+
if not text.strip():
|
|
160
|
+
return []
|
|
161
|
+
parts = re.split(r"(?<=[.!?])\s+", text)
|
|
162
|
+
return [p for p in parts if p.strip()] or [text.strip()]
|
|
163
|
+
|
|
164
|
+
@staticmethod
|
|
165
|
+
def _split_words(text: str) -> list[str]:
|
|
166
|
+
return re.findall(r"\b\w+\b", text)
|
|
167
|
+
|
|
160
168
|
def _clean_text(self, text: str) -> str:
|
|
161
169
|
"""
|
|
162
170
|
Clean text by removing extra whitespace and normalizing.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import re
|
|
2
2
|
import string
|
|
3
|
+
import logging
|
|
3
4
|
from typing import Any, Dict, Literal, Tuple
|
|
4
5
|
|
|
5
6
|
from swarmauri_base.ComponentBase import ComponentBase
|
|
@@ -51,6 +52,7 @@ class GunningFogEvaluator(EvaluatorBase, ComponentBase):
|
|
|
51
52
|
if not text or not isinstance(text, str):
|
|
52
53
|
if self.logger:
|
|
53
54
|
self.logger.warning("Program text is empty or not a string")
|
|
55
|
+
logging.getLogger(__name__).warning("Program text is empty or not a string")
|
|
54
56
|
return 0.0, {"error": "No valid text to analyze"}
|
|
55
57
|
|
|
56
58
|
# Count sentences, words, and complex words
|
|
@@ -91,6 +93,9 @@ class GunningFogEvaluator(EvaluatorBase, ComponentBase):
|
|
|
91
93
|
|
|
92
94
|
if self.logger:
|
|
93
95
|
self.logger.debug(f"Computed Gunning Fog Index: {gunning_fog_index:.2f}")
|
|
96
|
+
logging.getLogger(__name__).debug(
|
|
97
|
+
"Computed Gunning Fog Index: %.2f", gunning_fog_index
|
|
98
|
+
)
|
|
94
99
|
return normalized_score, metadata
|
|
95
100
|
|
|
96
101
|
def _get_program_text(self, program: Program) -> str:
|
|
@@ -98,7 +103,9 @@ class GunningFogEvaluator(EvaluatorBase, ComponentBase):
|
|
|
98
103
|
try:
|
|
99
104
|
source_files = program.get_source_files()
|
|
100
105
|
if isinstance(source_files, dict):
|
|
101
|
-
return " \n".join(
|
|
106
|
+
return " \n".join(
|
|
107
|
+
v for v in source_files.values() if isinstance(v, str)
|
|
108
|
+
)
|
|
102
109
|
except Exception as exc:
|
|
103
110
|
if self.logger:
|
|
104
111
|
self.logger.debug(f"Failed to obtain program text: {exc}")
|
|
File without changes
|
|
File without changes
|