swarmauri_evaluatorpool_accessibility 0.1.1__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.
- swarmauri_evaluatorpool_accessibility/AccessibilityEvaluatorPool.py +350 -0
- swarmauri_evaluatorpool_accessibility/AutomatedReadabilityIndexEvaluator.py +198 -0
- swarmauri_evaluatorpool_accessibility/ColemanLiauIndexEvaluator.py +245 -0
- swarmauri_evaluatorpool_accessibility/FleschKincaidGradeEvaluator.py +268 -0
- swarmauri_evaluatorpool_accessibility/FleschReadingEaseEvaluator.py +227 -0
- swarmauri_evaluatorpool_accessibility/GunningFogEvaluator.py +177 -0
- swarmauri_evaluatorpool_accessibility/__init__.py +28 -0
- swarmauri_evaluatorpool_accessibility-0.1.1.dist-info/LICENSE +201 -0
- swarmauri_evaluatorpool_accessibility-0.1.1.dist-info/METADATA +28 -0
- swarmauri_evaluatorpool_accessibility-0.1.1.dist-info/RECORD +12 -0
- swarmauri_evaluatorpool_accessibility-0.1.1.dist-info/WHEEL +4 -0
- swarmauri_evaluatorpool_accessibility-0.1.1.dist-info/entry_points.txt +10 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import importlib
|
|
3
|
+
import inspect
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List, Literal, Optional
|
|
6
|
+
|
|
7
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
8
|
+
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
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@ComponentBase.register_type(EvaluatorPoolBase, "AccessibilityEvaluatorPool")
|
|
17
|
+
class AccessibilityEvaluatorPool(EvaluatorPoolBase):
|
|
18
|
+
"""
|
|
19
|
+
Evaluator pool that runs a suite of accessibility and readability evaluators
|
|
20
|
+
across a Program.
|
|
21
|
+
|
|
22
|
+
This pool iterates through all files in a Program and invokes each of the
|
|
23
|
+
Accessibility & Readability evaluators, then aggregates a combined score.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
type: Literal["AccessibilityEvaluatorPool"] = "AccessibilityEvaluatorPool"
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
evaluators: Optional[List[EvaluatorBase]] = None,
|
|
31
|
+
weights: Optional[Dict[str, float]] = None,
|
|
32
|
+
**kwargs: Any,
|
|
33
|
+
) -> 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
|
+
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
|
+
|
|
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"
|
|
159
|
+
)
|
|
160
|
+
return 0.0
|
|
161
|
+
|
|
162
|
+
file_scores = []
|
|
163
|
+
|
|
164
|
+
# Run each evaluator on this file
|
|
165
|
+
for evaluator in self.evaluators:
|
|
166
|
+
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:
|
|
261
|
+
return 0.0
|
|
262
|
+
|
|
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()
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
from typing import Any, Dict, List, Literal, Tuple
|
|
5
|
+
|
|
6
|
+
import markdown
|
|
7
|
+
from bs4 import BeautifulSoup
|
|
8
|
+
from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
|
|
9
|
+
from swarmauri_base.ComponentBase import ComponentBase
|
|
10
|
+
from swarmauri_standard.programs.Program import Program
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@ComponentBase.register_type(EvaluatorBase, "AutomatedReadabilityIndexEvaluator")
|
|
16
|
+
class AutomatedReadabilityIndexEvaluator(EvaluatorBase, ComponentBase):
|
|
17
|
+
"""
|
|
18
|
+
Evaluator that computes the Automated Readability Index (ARI) score for text content.
|
|
19
|
+
|
|
20
|
+
This evaluator parses text from various file formats (.txt, .md, .html),
|
|
21
|
+
counts characters, words, and sentences, and applies the ARI formula to estimate
|
|
22
|
+
the U.S. grade level readability of the content.
|
|
23
|
+
|
|
24
|
+
The ARI formula is: 4.71*(characters/words) + 0.5*(words/sentences) - 21.43
|
|
25
|
+
|
|
26
|
+
Attributes:
|
|
27
|
+
type: The type identifier for this evaluator
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
type: Literal["AutomatedReadabilityIndexEvaluator"] = (
|
|
31
|
+
"AutomatedReadabilityIndexEvaluator"
|
|
32
|
+
)
|
|
33
|
+
model_config = {"arbitrary_types_allowed": True, "exclude": {"logger"}}
|
|
34
|
+
|
|
35
|
+
def _compute_score(
|
|
36
|
+
self, program: Program, **kwargs
|
|
37
|
+
) -> Tuple[float, Dict[str, Any]]:
|
|
38
|
+
"""
|
|
39
|
+
Compute the Automated Readability Index (ARI) score for a program's text content.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
program: The program to evaluate
|
|
43
|
+
**kwargs: Additional parameters for the evaluation process
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
A tuple containing:
|
|
47
|
+
- float: The ARI score (higher means more complex text)
|
|
48
|
+
- Dict[str, Any]: Metadata including character, word, and sentence counts
|
|
49
|
+
|
|
50
|
+
Raises:
|
|
51
|
+
ValueError: If no text content could be extracted from the program
|
|
52
|
+
"""
|
|
53
|
+
logger.info(f"Computing ARI score for program: {program.name}")
|
|
54
|
+
|
|
55
|
+
# Extract text content from program artifacts
|
|
56
|
+
text_content = self._extract_text_from_program(program)
|
|
57
|
+
|
|
58
|
+
if not text_content:
|
|
59
|
+
logger.warning("No text content found in program artifacts")
|
|
60
|
+
return 0.0, {
|
|
61
|
+
"error": "No text content found",
|
|
62
|
+
"chars": 0,
|
|
63
|
+
"words": 0,
|
|
64
|
+
"sentences": 0,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# Count characters, words, and sentences
|
|
68
|
+
char_count = len(text_content)
|
|
69
|
+
word_count = len(self._count_words(text_content))
|
|
70
|
+
sentence_count = len(self._count_sentences(text_content))
|
|
71
|
+
|
|
72
|
+
logger.debug(
|
|
73
|
+
f"Text statistics: {char_count} chars, {word_count} words, {sentence_count} sentences"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
# Handle edge cases to avoid division by zero
|
|
77
|
+
if word_count == 0 or sentence_count == 0:
|
|
78
|
+
logger.warning(
|
|
79
|
+
"Cannot compute ARI: division by zero (no words or sentences)"
|
|
80
|
+
)
|
|
81
|
+
return 0.0, {
|
|
82
|
+
"error": "Cannot compute ARI: no words or sentences",
|
|
83
|
+
"chars": char_count,
|
|
84
|
+
"words": word_count,
|
|
85
|
+
"sentences": sentence_count,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
# Calculate ARI score
|
|
89
|
+
# ARI = 4.71*(characters/words) + 0.5*(words/sentences) - 21.43
|
|
90
|
+
ari_score = (
|
|
91
|
+
4.71 * (char_count / word_count)
|
|
92
|
+
+ 0.5 * (word_count / sentence_count)
|
|
93
|
+
- 21.43
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# Ensure score is non-negative (ARI can theoretically go below 0 for very simple text)
|
|
97
|
+
ari_score = max(0.0, ari_score)
|
|
98
|
+
|
|
99
|
+
logger.info(f"Computed ARI score: {ari_score:.2f}")
|
|
100
|
+
|
|
101
|
+
return ari_score, {
|
|
102
|
+
"chars": char_count,
|
|
103
|
+
"words": word_count,
|
|
104
|
+
"sentences": sentence_count,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
def _extract_text_from_program(self, program: Program) -> str:
|
|
108
|
+
"""
|
|
109
|
+
Extract text content from program artifacts.
|
|
110
|
+
|
|
111
|
+
Handles different file types (.txt, .md, .html) and extracts plain text.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
program: The program containing artifacts to extract text from
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
A string containing all the extracted text content
|
|
118
|
+
"""
|
|
119
|
+
text_content = []
|
|
120
|
+
|
|
121
|
+
# Get all artifacts from the program
|
|
122
|
+
artifacts = program.get_artifacts()
|
|
123
|
+
|
|
124
|
+
for artifact in artifacts:
|
|
125
|
+
file_path = artifact.get_path()
|
|
126
|
+
if not file_path or not os.path.exists(file_path):
|
|
127
|
+
logger.debug(f"Skipping non-existent artifact: {file_path}")
|
|
128
|
+
continue
|
|
129
|
+
|
|
130
|
+
# Process based on file extension
|
|
131
|
+
_, ext = os.path.splitext(file_path)
|
|
132
|
+
ext = ext.lower()
|
|
133
|
+
|
|
134
|
+
try:
|
|
135
|
+
if ext in [".txt"]:
|
|
136
|
+
# Plain text files
|
|
137
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
138
|
+
text_content.append(f.read())
|
|
139
|
+
|
|
140
|
+
elif ext in [".md", ".markdown"]:
|
|
141
|
+
# Markdown files - convert to HTML then extract text
|
|
142
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
143
|
+
md_content = f.read()
|
|
144
|
+
html_content = markdown.markdown(md_content)
|
|
145
|
+
soup = BeautifulSoup(html_content, "html.parser")
|
|
146
|
+
text_content.append(soup.get_text())
|
|
147
|
+
|
|
148
|
+
elif ext in [".html", ".htm"]:
|
|
149
|
+
# HTML files
|
|
150
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
151
|
+
html_content = f.read()
|
|
152
|
+
soup = BeautifulSoup(html_content, "html.parser")
|
|
153
|
+
text_content.append(soup.get_text())
|
|
154
|
+
|
|
155
|
+
except Exception as e:
|
|
156
|
+
logger.error(f"Error extracting text from {file_path}: {str(e)}")
|
|
157
|
+
|
|
158
|
+
return " ".join(text_content)
|
|
159
|
+
|
|
160
|
+
def _count_words(self, text: str) -> List[str]:
|
|
161
|
+
"""
|
|
162
|
+
Count words in the given text.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
text: The text to analyze
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
A list of words found in the text
|
|
169
|
+
"""
|
|
170
|
+
# Split by whitespace and filter out empty strings
|
|
171
|
+
words = [word for word in re.findall(r"\b\w+\b", text.lower()) if word]
|
|
172
|
+
return words
|
|
173
|
+
|
|
174
|
+
def _count_sentences(self, text: str) -> List[str]:
|
|
175
|
+
"""
|
|
176
|
+
Count sentences in the given text.
|
|
177
|
+
|
|
178
|
+
Uses regular expressions to identify sentence boundaries based on
|
|
179
|
+
common punctuation patterns.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
text: The text to analyze
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
A list of sentences found in the text
|
|
186
|
+
"""
|
|
187
|
+
# Handle common sentence terminators and edge cases
|
|
188
|
+
# This regex looks for sentence-ending punctuation followed by space or end of string
|
|
189
|
+
sentences = re.split(r"(?<=[.!?])\s+", text)
|
|
190
|
+
|
|
191
|
+
# Filter out empty sentences
|
|
192
|
+
sentences = [s for s in sentences if s.strip()]
|
|
193
|
+
|
|
194
|
+
# If no sentences were found but there is text, count it as one sentence
|
|
195
|
+
if not sentences and text.strip():
|
|
196
|
+
return [text]
|
|
197
|
+
|
|
198
|
+
return sentences
|