swarmauri_evaluatorpool_accessibility 0.1.2.dev1__tar.gz → 0.3.0.dev2__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.1.2.dev1 → swarmauri_evaluatorpool_accessibility-0.3.0.dev2}/PKG-INFO +1 -1
- {swarmauri_evaluatorpool_accessibility-0.1.2.dev1 → swarmauri_evaluatorpool_accessibility-0.3.0.dev2}/pyproject.toml +1 -1
- swarmauri_evaluatorpool_accessibility-0.3.0.dev2/swarmauri_evaluatorpool_accessibility/AccessibilityEvaluatorPool.py +129 -0
- swarmauri_evaluatorpool_accessibility-0.3.0.dev2/swarmauri_evaluatorpool_accessibility/AutomatedReadabilityIndexEvaluator.py +107 -0
- swarmauri_evaluatorpool_accessibility-0.3.0.dev2/swarmauri_evaluatorpool_accessibility/ColemanLiauIndexEvaluator.py +129 -0
- {swarmauri_evaluatorpool_accessibility-0.1.2.dev1 → swarmauri_evaluatorpool_accessibility-0.3.0.dev2}/swarmauri_evaluatorpool_accessibility/FleschKincaidGradeEvaluator.py +28 -29
- {swarmauri_evaluatorpool_accessibility-0.1.2.dev1 → swarmauri_evaluatorpool_accessibility-0.3.0.dev2}/swarmauri_evaluatorpool_accessibility/FleschReadingEaseEvaluator.py +32 -10
- {swarmauri_evaluatorpool_accessibility-0.1.2.dev1 → swarmauri_evaluatorpool_accessibility-0.3.0.dev2}/swarmauri_evaluatorpool_accessibility/GunningFogEvaluator.py +26 -7
- swarmauri_evaluatorpool_accessibility-0.1.2.dev1/swarmauri_evaluatorpool_accessibility/AccessibilityEvaluatorPool.py +0 -350
- swarmauri_evaluatorpool_accessibility-0.1.2.dev1/swarmauri_evaluatorpool_accessibility/AutomatedReadabilityIndexEvaluator.py +0 -198
- swarmauri_evaluatorpool_accessibility-0.1.2.dev1/swarmauri_evaluatorpool_accessibility/ColemanLiauIndexEvaluator.py +0 -245
- {swarmauri_evaluatorpool_accessibility-0.1.2.dev1 → swarmauri_evaluatorpool_accessibility-0.3.0.dev2}/LICENSE +0 -0
- {swarmauri_evaluatorpool_accessibility-0.1.2.dev1 → swarmauri_evaluatorpool_accessibility-0.3.0.dev2}/README.md +0 -0
- {swarmauri_evaluatorpool_accessibility-0.1.2.dev1 → swarmauri_evaluatorpool_accessibility-0.3.0.dev2}/swarmauri_evaluatorpool_accessibility/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: swarmauri_evaluatorpool_accessibility
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0.dev2
|
|
4
4
|
Summary: A package providing accessibility and readability evaluators for SwarmAuri
|
|
5
5
|
License: Apache-2.0
|
|
6
6
|
Keywords: accessibility,readability,evaluator,swarmauri,flesch-kincaid,gunning-fog,coleman-liau,automated-readability-index,flesch-reading-ease,text-analysis,nlp
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# File: swarmauri_standard/evaluator_pools/AccessibilityEvaluatorPool.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Dict, List, Literal, Sequence
|
|
5
|
+
|
|
6
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
7
|
+
from swarmauri_base.evaluator_pools.EvaluatorPoolBase import EvaluatorPoolBase
|
|
8
|
+
from swarmauri_core.evaluators.IEvaluate import IEvaluate
|
|
9
|
+
|
|
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
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@ComponentBase.register_type(EvaluatorPoolBase, "AccessibilityEvaluatorPool")
|
|
24
|
+
class AccessibilityEvaluatorPool(EvaluatorPoolBase):
|
|
25
|
+
"""
|
|
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
|
|
31
|
+
|
|
32
|
+
The pool itself follows the contracts defined by `EvaluatorPoolBase`
|
|
33
|
+
(thread-safe registry, concurrent dispatch, aggregation hook, etc.).
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
type: Literal["AccessibilityEvaluatorPool"] = "AccessibilityEvaluatorPool"
|
|
37
|
+
|
|
38
|
+
# ------------------------------------------------------------------ #
|
|
39
|
+
# construction
|
|
40
|
+
# ------------------------------------------------------------------ #
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
evaluators: Sequence[IEvaluate] | None = None,
|
|
44
|
+
weights: Dict[str, float] | None = None,
|
|
45
|
+
**kwargs: Any,
|
|
46
|
+
) -> None:
|
|
47
|
+
super().__init__(**kwargs)
|
|
48
|
+
|
|
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(),
|
|
69
|
+
)
|
|
70
|
+
|
|
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:
|
|
84
|
+
try:
|
|
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:
|
|
116
|
+
return 0.0
|
|
117
|
+
|
|
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
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# File: peagen/evaluators/AutomatedReadabilityIndexEvaluator.py
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List, Literal, Tuple
|
|
6
|
+
|
|
7
|
+
import markdown
|
|
8
|
+
from bs4 import BeautifulSoup
|
|
9
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
10
|
+
from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
|
|
11
|
+
from swarmauri_standard.programs.Program import Program
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@ComponentBase.register_type(EvaluatorBase, "AutomatedReadabilityIndexEvaluator")
|
|
15
|
+
class AutomatedReadabilityIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
16
|
+
"""
|
|
17
|
+
Computes the Automated Readability Index (ARI) for a Program’s textual sources.
|
|
18
|
+
|
|
19
|
+
Conforms to the IEvaluate interface by returning a dict:
|
|
20
|
+
{ "score": <float>, "metadata": <dict> }
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
type: Literal["AutomatedReadabilityIndexEvaluator"] = (
|
|
24
|
+
"AutomatedReadabilityIndexEvaluator"
|
|
25
|
+
)
|
|
26
|
+
model_config = {"arbitrary_types_allowed": True, "exclude": {"logger"}}
|
|
27
|
+
|
|
28
|
+
# ────────────────────────────────────────────────────────────────────
|
|
29
|
+
# public IEvaluate API
|
|
30
|
+
# ────────────────────────────────────────────────────────────────────
|
|
31
|
+
def evaluate(self, program: Program, **kwargs) -> Dict[str, Any]: # IEvaluate
|
|
32
|
+
score, meta = self._compute_score(program, **kwargs)
|
|
33
|
+
return {"score": score, "metadata": meta}
|
|
34
|
+
|
|
35
|
+
# ────────────────────────────────────────────────────────────────────
|
|
36
|
+
# internals
|
|
37
|
+
# ────────────────────────────────────────────────────────────────────
|
|
38
|
+
def _compute_score(
|
|
39
|
+
self, program: Program, **kwargs
|
|
40
|
+
) -> Tuple[float, Dict[str, Any]]:
|
|
41
|
+
"""
|
|
42
|
+
Return (score, metadata) tuple; wrapper packs it into the dict
|
|
43
|
+
expected by EvaluatorPoolBase.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
text = self._collect_text(program)
|
|
47
|
+
|
|
48
|
+
if not text.strip():
|
|
49
|
+
return 0.0, {"error": "no_text"}
|
|
50
|
+
|
|
51
|
+
chars = len(text)
|
|
52
|
+
words = len(self._tokenize_words(text))
|
|
53
|
+
sents = len(self._tokenize_sentences(text))
|
|
54
|
+
|
|
55
|
+
if words == 0 or sents == 0:
|
|
56
|
+
return 0.0, {
|
|
57
|
+
"error": "division_by_zero",
|
|
58
|
+
"chars": chars,
|
|
59
|
+
"words": words,
|
|
60
|
+
"sentences": sents,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
ari = 4.71 * (chars / words) + 0.5 * (words / sents) - 21.43
|
|
64
|
+
ari = max(0.0, ari)
|
|
65
|
+
|
|
66
|
+
return ari, {"chars": chars, "words": words, "sentences": sents}
|
|
67
|
+
|
|
68
|
+
# -------------------------------------------------------------------
|
|
69
|
+
# helpers
|
|
70
|
+
# -------------------------------------------------------------------
|
|
71
|
+
def _collect_text(self, program: Program) -> str:
|
|
72
|
+
"""
|
|
73
|
+
Aggregate plain text from all source files in the program.
|
|
74
|
+
Supports .txt, .md, .html and any text-like files present
|
|
75
|
+
in program.get_source_files() or program.content.
|
|
76
|
+
"""
|
|
77
|
+
files = (
|
|
78
|
+
program.get_source_files()
|
|
79
|
+
if hasattr(program, "get_source_files")
|
|
80
|
+
else program.content
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
segments: List[str] = []
|
|
84
|
+
for rel_path, data in files.items():
|
|
85
|
+
ext = Path(rel_path).suffix.lower()
|
|
86
|
+
try:
|
|
87
|
+
if ext in (".md", ".markdown"):
|
|
88
|
+
html = markdown.markdown(data)
|
|
89
|
+
segments.append(BeautifulSoup(html, "html.parser").get_text())
|
|
90
|
+
elif ext in (".html", ".htm"):
|
|
91
|
+
segments.append(BeautifulSoup(data, "html.parser").get_text())
|
|
92
|
+
else: # plain text
|
|
93
|
+
segments.append(data)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
if self.logger:
|
|
96
|
+
self.logger.error("Error parsing %s: %s", rel_path, exc)
|
|
97
|
+
|
|
98
|
+
return " ".join(segments)
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def _tokenize_words(text: str) -> List[str]:
|
|
102
|
+
return re.findall(r"\b\w+\b", text.lower())
|
|
103
|
+
|
|
104
|
+
@staticmethod
|
|
105
|
+
def _tokenize_sentences(text: str) -> List[str]:
|
|
106
|
+
sents = re.split(r"(?<=[.!?])\s+", text)
|
|
107
|
+
return [s for s in sents if s.strip()] or [text.strip()]
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from typing import Any, Dict, Literal, Tuple
|
|
3
|
+
|
|
4
|
+
from pydantic import Field
|
|
5
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
6
|
+
from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
|
|
7
|
+
from swarmauri_standard.programs.Program import Program
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@ComponentBase.register_type(EvaluatorBase, "ColemanLiauIndexEvaluator")
|
|
11
|
+
class ColemanLiauIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
12
|
+
"""
|
|
13
|
+
Coleman–Liau Index evaluator compliant with the Program/Evaluator contracts.
|
|
14
|
+
|
|
15
|
+
• ``evaluate()`` returns ``{"score": float, "metadata": dict}``.
|
|
16
|
+
• ``_compute_score()`` returns ``Tuple[float, Dict[str, Any]]`` for internal use.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
type: Literal["ColemanLiauIndexEvaluator"] = "ColemanLiauIndexEvaluator"
|
|
20
|
+
|
|
21
|
+
normalize_scores: bool = Field(default=True)
|
|
22
|
+
target_grade_level: int = Field(default=8, ge=1)
|
|
23
|
+
max_grade_level: int = Field(default=16, ge=1)
|
|
24
|
+
|
|
25
|
+
# ──────────────────────────────────────────────────────────────────────
|
|
26
|
+
# Public API – called by the pool / runner
|
|
27
|
+
# ──────────────────────────────────────────────────────────────────────
|
|
28
|
+
def evaluate(self, program: Program, **kwargs) -> Dict[str, Any]:
|
|
29
|
+
"""Return ``{"score": float, "metadata": dict}`` for the given program."""
|
|
30
|
+
score, meta = self._compute_score(program, **kwargs)
|
|
31
|
+
return {"score": score, "metadata": meta}
|
|
32
|
+
|
|
33
|
+
# ──────────────────────────────────────────────────────────────────────
|
|
34
|
+
# Core scoring logic
|
|
35
|
+
# ──────────────────────────────────────────────────────────────────────
|
|
36
|
+
def _compute_score(self, program: Program, **__) -> Tuple[float, Dict[str, Any]]:
|
|
37
|
+
text = self._extract_text(program)
|
|
38
|
+
|
|
39
|
+
if not text.strip():
|
|
40
|
+
return 0.0, {
|
|
41
|
+
"error": "Empty text",
|
|
42
|
+
"grade_level": 0,
|
|
43
|
+
"letters": 0,
|
|
44
|
+
"words": 0,
|
|
45
|
+
"sentences": 0,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
letters = self._count_letters(text)
|
|
49
|
+
words = self._count_words(text)
|
|
50
|
+
sentences = self._count_sentences(text)
|
|
51
|
+
|
|
52
|
+
if words == 0:
|
|
53
|
+
return 0.0, {
|
|
54
|
+
"error": "No words found",
|
|
55
|
+
"grade_level": 0,
|
|
56
|
+
"letters": letters,
|
|
57
|
+
"words": words,
|
|
58
|
+
"sentences": sentences,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
L = (letters / words) * 100
|
|
62
|
+
S = (sentences / words) * 100
|
|
63
|
+
raw_cli = 0.0588 * L - 0.296 * S - 15.8
|
|
64
|
+
grade_level = max(1, round(raw_cli))
|
|
65
|
+
|
|
66
|
+
score = (
|
|
67
|
+
self._normalise(grade_level)
|
|
68
|
+
if self.normalize_scores
|
|
69
|
+
else float(grade_level)
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
return score, {
|
|
73
|
+
"grade_level": grade_level,
|
|
74
|
+
"raw_index": raw_cli,
|
|
75
|
+
"letters": letters,
|
|
76
|
+
"words": words,
|
|
77
|
+
"sentences": sentences,
|
|
78
|
+
"letters_per_100_words": L,
|
|
79
|
+
"sentences_per_100_words": S,
|
|
80
|
+
"target_grade_level": self.target_grade_level,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
# ──────────────────────────────────────────────────────────────────────
|
|
84
|
+
# Helpers
|
|
85
|
+
# ──────────────────────────────────────────────────────────────────────
|
|
86
|
+
def _extract_text(self, program: Program) -> str:
|
|
87
|
+
for attr in ("output", "source", "content"):
|
|
88
|
+
val = getattr(program, attr, None)
|
|
89
|
+
if isinstance(val, str):
|
|
90
|
+
return val
|
|
91
|
+
if isinstance(val, dict):
|
|
92
|
+
joined = "\n".join(v for v in val.values() if isinstance(v, str))
|
|
93
|
+
if joined.strip():
|
|
94
|
+
return joined
|
|
95
|
+
|
|
96
|
+
if hasattr(program, "get_source_files"):
|
|
97
|
+
files = program.get_source_files()
|
|
98
|
+
if isinstance(files, dict):
|
|
99
|
+
joined = "\n".join(v for v in files.values() if isinstance(v, str))
|
|
100
|
+
if joined.strip():
|
|
101
|
+
return joined
|
|
102
|
+
|
|
103
|
+
return str(program)
|
|
104
|
+
|
|
105
|
+
@staticmethod
|
|
106
|
+
def _count_letters(text: str) -> int:
|
|
107
|
+
return sum(1 for ch in text if ch.isalpha())
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def _count_words(text: str) -> int:
|
|
111
|
+
return len([w for w in re.split(r"\s+", text) if re.search(r"\w", w)])
|
|
112
|
+
|
|
113
|
+
@staticmethod
|
|
114
|
+
def _count_sentences(text: str) -> int:
|
|
115
|
+
hits = re.findall(r"[.!?]+", text)
|
|
116
|
+
return len(hits) if hits else 1
|
|
117
|
+
|
|
118
|
+
def _normalise(self, grade_level: int) -> float:
|
|
119
|
+
if grade_level == self.target_grade_level:
|
|
120
|
+
return 1.0
|
|
121
|
+
if grade_level <= 1 or grade_level >= self.max_grade_level:
|
|
122
|
+
return 0.0
|
|
123
|
+
|
|
124
|
+
distance = abs(grade_level - self.target_grade_level)
|
|
125
|
+
max_distance = max(
|
|
126
|
+
abs(self.target_grade_level - 1),
|
|
127
|
+
abs(self.target_grade_level - self.max_grade_level),
|
|
128
|
+
)
|
|
129
|
+
return max(0.0, 1.0 - distance / max_distance)
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import logging
|
|
2
1
|
import re
|
|
3
2
|
import string
|
|
4
3
|
from typing import Any, Dict, Literal, Tuple
|
|
@@ -7,8 +6,6 @@ from swarmauri_base.ComponentBase import ComponentBase
|
|
|
7
6
|
from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
|
|
8
7
|
from swarmauri_standard.programs.Program import Program
|
|
9
8
|
|
|
10
|
-
logger = logging.getLogger(__name__)
|
|
11
|
-
|
|
12
9
|
|
|
13
10
|
@ComponentBase.register_type(EvaluatorBase, "FleschKincaidGradeEvaluator")
|
|
14
11
|
class FleschKincaidGradeEvaluator(EvaluatorBase, ComponentBase):
|
|
@@ -28,6 +25,14 @@ class FleschKincaidGradeEvaluator(EvaluatorBase, ComponentBase):
|
|
|
28
25
|
|
|
29
26
|
type: Literal["FleschKincaidGradeEvaluator"] = "FleschKincaidGradeEvaluator"
|
|
30
27
|
|
|
28
|
+
# ------------------------------------------------------------------
|
|
29
|
+
# public API
|
|
30
|
+
# ------------------------------------------------------------------
|
|
31
|
+
def evaluate(self, program: Program, **kwargs) -> Dict[str, Any]:
|
|
32
|
+
"""Return ``{"score": float, "metadata": dict}`` for the given program."""
|
|
33
|
+
score, meta = self._compute_score(program, **kwargs)
|
|
34
|
+
return {"score": score, "metadata": meta}
|
|
35
|
+
|
|
31
36
|
def _compute_score(
|
|
32
37
|
self, program: Program, **kwargs
|
|
33
38
|
) -> Tuple[float, Dict[str, Any]]:
|
|
@@ -54,7 +59,8 @@ class FleschKincaidGradeEvaluator(EvaluatorBase, ComponentBase):
|
|
|
54
59
|
text = self._get_program_text(program)
|
|
55
60
|
|
|
56
61
|
if not text:
|
|
57
|
-
logger
|
|
62
|
+
if self.logger:
|
|
63
|
+
self.logger.warning("No text found in program output")
|
|
58
64
|
return 0.0, {"error": "No text to evaluate"}
|
|
59
65
|
|
|
60
66
|
# Count sentences, words, and syllables
|
|
@@ -62,13 +68,17 @@ class FleschKincaidGradeEvaluator(EvaluatorBase, ComponentBase):
|
|
|
62
68
|
words = self._count_words(text)
|
|
63
69
|
syllables = self._count_syllables(text)
|
|
64
70
|
|
|
65
|
-
logger
|
|
66
|
-
|
|
67
|
-
|
|
71
|
+
if self.logger:
|
|
72
|
+
self.logger.debug(
|
|
73
|
+
f"Text analysis: {sentences} sentences, {words} words, {syllables} syllables"
|
|
74
|
+
)
|
|
68
75
|
|
|
69
76
|
# Calculate the Flesch-Kincaid Grade Level
|
|
70
77
|
if sentences == 0 or words == 0:
|
|
71
|
-
logger
|
|
78
|
+
if self.logger:
|
|
79
|
+
self.logger.warning(
|
|
80
|
+
"Text lacks sufficient content for FKGL calculation"
|
|
81
|
+
)
|
|
72
82
|
return 0.0, {
|
|
73
83
|
"error": "Text lacks sufficient content for analysis",
|
|
74
84
|
"sentences": sentences,
|
|
@@ -101,7 +111,8 @@ class FleschKincaidGradeEvaluator(EvaluatorBase, ComponentBase):
|
|
|
101
111
|
},
|
|
102
112
|
}
|
|
103
113
|
|
|
104
|
-
logger
|
|
114
|
+
if self.logger:
|
|
115
|
+
self.logger.info(f"Calculated FKGL score: {fkgl_score:.2f}")
|
|
105
116
|
return fkgl_score, metadata
|
|
106
117
|
|
|
107
118
|
def _get_program_text(self, program: Program) -> str:
|
|
@@ -114,26 +125,14 @@ class FleschKincaidGradeEvaluator(EvaluatorBase, ComponentBase):
|
|
|
114
125
|
Returns:
|
|
115
126
|
The extracted text as a string
|
|
116
127
|
"""
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
if isinstance(output, dict):
|
|
126
|
-
if "text" in output:
|
|
127
|
-
return str(output["text"])
|
|
128
|
-
if "content" in output:
|
|
129
|
-
return str(output["content"])
|
|
130
|
-
|
|
131
|
-
# If output is a list, join elements as strings
|
|
132
|
-
if isinstance(output, list):
|
|
133
|
-
return " ".join(str(item) for item in output)
|
|
134
|
-
|
|
135
|
-
# Fall back to string representation
|
|
136
|
-
return str(output)
|
|
128
|
+
try:
|
|
129
|
+
source_files = program.get_source_files()
|
|
130
|
+
if isinstance(source_files, dict):
|
|
131
|
+
return " \n".join(str(v) for v in source_files.values())
|
|
132
|
+
except Exception as exc:
|
|
133
|
+
if self.logger:
|
|
134
|
+
self.logger.debug(f"Failed to obtain program text: {exc}")
|
|
135
|
+
return ""
|
|
137
136
|
|
|
138
137
|
def _count_sentences(self, text: str) -> int:
|
|
139
138
|
"""
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import logging
|
|
2
1
|
import os
|
|
3
2
|
import re
|
|
4
3
|
from typing import Any, Dict, Literal, Tuple
|
|
@@ -12,7 +11,6 @@ from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
|
|
|
12
11
|
from swarmauri_base.ComponentBase import ComponentBase
|
|
13
12
|
from swarmauri_standard.programs.Program import Program
|
|
14
13
|
|
|
15
|
-
logger = logging.getLogger(__name__)
|
|
16
14
|
|
|
17
15
|
# Custom download dir for environments like CI
|
|
18
16
|
NLTK_DATA_DIR = os.getenv("NLTK_DATA_DIR", "/tmp/nltk_data")
|
|
@@ -38,6 +36,14 @@ class FleschReadingEaseEvaluator(EvaluatorBase, ComponentBase):
|
|
|
38
36
|
type: Literal["FleschReadingEaseEvaluator"] = "FleschReadingEaseEvaluator"
|
|
39
37
|
_cmu_dict = PrivateAttr(default=None)
|
|
40
38
|
|
|
39
|
+
# ------------------------------------------------------------------
|
|
40
|
+
# public API
|
|
41
|
+
# ------------------------------------------------------------------
|
|
42
|
+
def evaluate(self, program: Program, **kwargs) -> Dict[str, Any]:
|
|
43
|
+
"""Return ``{"score": float, "metadata": dict}`` for the given program."""
|
|
44
|
+
score, meta = self._compute_score(program, **kwargs)
|
|
45
|
+
return {"score": score, "metadata": meta}
|
|
46
|
+
|
|
41
47
|
def __init__(self, **kwargs):
|
|
42
48
|
"""Initialize the Flesch Reading Ease evaluator."""
|
|
43
49
|
super().__init__(**kwargs)
|
|
@@ -45,13 +51,15 @@ class FleschReadingEaseEvaluator(EvaluatorBase, ComponentBase):
|
|
|
45
51
|
try:
|
|
46
52
|
nltk.data.find("tokenizers/punkt")
|
|
47
53
|
except LookupError:
|
|
48
|
-
logger
|
|
54
|
+
if self.logger:
|
|
55
|
+
self.logger.info("Downloading NLTK punkt tokenizer")
|
|
49
56
|
nltk.download("punkt", quiet=True, download_dir=NLTK_DATA_DIR)
|
|
50
57
|
|
|
51
58
|
try:
|
|
52
59
|
nltk.data.find("corpora/cmudict")
|
|
53
60
|
except LookupError:
|
|
54
|
-
logger
|
|
61
|
+
if self.logger:
|
|
62
|
+
self.logger.info("Downloading CMU Pronouncing Dictionary")
|
|
55
63
|
nltk.download("cmudict", quiet=True, download_dir=NLTK_DATA_DIR)
|
|
56
64
|
|
|
57
65
|
# Load the CMU dictionary for syllable counting
|
|
@@ -81,9 +89,10 @@ class FleschReadingEaseEvaluator(EvaluatorBase, ComponentBase):
|
|
|
81
89
|
ValueError: If the text cannot be processed
|
|
82
90
|
"""
|
|
83
91
|
# Extract text from the program
|
|
84
|
-
text =
|
|
92
|
+
text = self._get_program_text(program)
|
|
85
93
|
if not text or not isinstance(text, str):
|
|
86
|
-
logger
|
|
94
|
+
if self.logger:
|
|
95
|
+
self.logger.warning("Program content is empty or not a string")
|
|
87
96
|
return 0.0, {"error": "No valid text content found"}
|
|
88
97
|
|
|
89
98
|
# Clean the text (remove extra whitespace, etc.)
|
|
@@ -101,7 +110,8 @@ class FleschReadingEaseEvaluator(EvaluatorBase, ComponentBase):
|
|
|
101
110
|
word_count = len(words)
|
|
102
111
|
|
|
103
112
|
if sentence_count == 0 or word_count == 0:
|
|
104
|
-
logger
|
|
113
|
+
if self.logger:
|
|
114
|
+
self.logger.warning("Text contains no sentences or words")
|
|
105
115
|
return 0.0, {"error": "Text contains no sentences or words"}
|
|
106
116
|
|
|
107
117
|
# Count syllables in each word
|
|
@@ -130,11 +140,23 @@ class FleschReadingEaseEvaluator(EvaluatorBase, ComponentBase):
|
|
|
130
140
|
"readability_interpretation": self._interpret_score(fre_score),
|
|
131
141
|
}
|
|
132
142
|
|
|
133
|
-
logger
|
|
134
|
-
|
|
135
|
-
|
|
143
|
+
if self.logger:
|
|
144
|
+
self.logger.info(
|
|
145
|
+
f"Flesch Reading Ease score: {fre_score:.2f} ({metadata['readability_interpretation']})"
|
|
146
|
+
)
|
|
136
147
|
return fre_score, metadata
|
|
137
148
|
|
|
149
|
+
def _get_program_text(self, program: Program) -> str:
|
|
150
|
+
"""Return program text by joining its source files."""
|
|
151
|
+
try:
|
|
152
|
+
source_files = program.get_source_files()
|
|
153
|
+
if isinstance(source_files, dict):
|
|
154
|
+
return " \n".join(str(v) for v in source_files.values())
|
|
155
|
+
except Exception as exc:
|
|
156
|
+
if self.logger:
|
|
157
|
+
self.logger.debug(f"Failed to obtain program text: {exc}")
|
|
158
|
+
return ""
|
|
159
|
+
|
|
138
160
|
def _clean_text(self, text: str) -> str:
|
|
139
161
|
"""
|
|
140
162
|
Clean text by removing extra whitespace and normalizing.
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import logging
|
|
2
1
|
import re
|
|
3
2
|
import string
|
|
4
3
|
from typing import Any, Dict, Literal, Tuple
|
|
@@ -7,8 +6,6 @@ from swarmauri_base.ComponentBase import ComponentBase
|
|
|
7
6
|
from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
|
|
8
7
|
from swarmauri_standard.programs.Program import Program
|
|
9
8
|
|
|
10
|
-
logger = logging.getLogger(__name__)
|
|
11
|
-
|
|
12
9
|
|
|
13
10
|
@ComponentBase.register_type(EvaluatorBase, "GunningFogEvaluator")
|
|
14
11
|
class GunningFogEvaluator(EvaluatorBase, ComponentBase):
|
|
@@ -27,6 +24,14 @@ class GunningFogEvaluator(EvaluatorBase, ComponentBase):
|
|
|
27
24
|
|
|
28
25
|
type: Literal["GunningFogEvaluator"] = "GunningFogEvaluator"
|
|
29
26
|
|
|
27
|
+
# ------------------------------------------------------------------
|
|
28
|
+
# public API
|
|
29
|
+
# ------------------------------------------------------------------
|
|
30
|
+
def evaluate(self, program: Program, **kwargs) -> Dict[str, Any]:
|
|
31
|
+
"""Return ``{"score": float, "metadata": dict}`` for the given program."""
|
|
32
|
+
score, meta = self._compute_score(program, **kwargs)
|
|
33
|
+
return {"score": score, "metadata": meta}
|
|
34
|
+
|
|
30
35
|
def _compute_score(
|
|
31
36
|
self, program: Program, **kwargs
|
|
32
37
|
) -> Tuple[float, Dict[str, Any]]:
|
|
@@ -42,9 +47,10 @@ class GunningFogEvaluator(EvaluatorBase, ComponentBase):
|
|
|
42
47
|
- float: The Gunning Fog Index score (lower is better for readability)
|
|
43
48
|
- Dict[str, Any]: Metadata including sentence count, word count, and complex word count
|
|
44
49
|
"""
|
|
45
|
-
text =
|
|
50
|
+
text = self._get_program_text(program)
|
|
46
51
|
if not text or not isinstance(text, str):
|
|
47
|
-
logger
|
|
52
|
+
if self.logger:
|
|
53
|
+
self.logger.warning("Program text is empty or not a string")
|
|
48
54
|
return 0.0, {"error": "No valid text to analyze"}
|
|
49
55
|
|
|
50
56
|
# Count sentences, words, and complex words
|
|
@@ -54,7 +60,8 @@ class GunningFogEvaluator(EvaluatorBase, ComponentBase):
|
|
|
54
60
|
|
|
55
61
|
# Avoid division by zero
|
|
56
62
|
if sentences == 0 or words == 0:
|
|
57
|
-
logger
|
|
63
|
+
if self.logger:
|
|
64
|
+
self.logger.warning("Text has no sentences or words")
|
|
58
65
|
return 0.0, {
|
|
59
66
|
"sentences": sentences,
|
|
60
67
|
"words": words,
|
|
@@ -82,9 +89,21 @@ class GunningFogEvaluator(EvaluatorBase, ComponentBase):
|
|
|
82
89
|
"percent_complex_words": percent_complex_words,
|
|
83
90
|
}
|
|
84
91
|
|
|
85
|
-
logger
|
|
92
|
+
if self.logger:
|
|
93
|
+
self.logger.debug(f"Computed Gunning Fog Index: {gunning_fog_index:.2f}")
|
|
86
94
|
return normalized_score, metadata
|
|
87
95
|
|
|
96
|
+
def _get_program_text(self, program: Program) -> str:
|
|
97
|
+
"""Return a concatenated text representation of the program."""
|
|
98
|
+
try:
|
|
99
|
+
source_files = program.get_source_files()
|
|
100
|
+
if isinstance(source_files, dict):
|
|
101
|
+
return " \n".join(str(v) for v in source_files.values())
|
|
102
|
+
except Exception as exc:
|
|
103
|
+
if self.logger:
|
|
104
|
+
self.logger.debug(f"Failed to obtain program text: {exc}")
|
|
105
|
+
return ""
|
|
106
|
+
|
|
88
107
|
def _count_sentences(self, text: str) -> int:
|
|
89
108
|
"""
|
|
90
109
|
Count the number of sentences in the text.
|