Commit
·
2736dc6
1
Parent(s):
a8c8925
Update features/linguistic_analyzer.py
Browse filesAdding Enhanced Feature Engineering Pipeline
- features/linguistic_analyzer.py +658 -489
features/linguistic_analyzer.py
CHANGED
|
@@ -1,534 +1,703 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
|
| 4 |
-
import numpy as np
|
| 5 |
import pandas as pd
|
| 6 |
-
import
|
|
|
|
| 7 |
import logging
|
| 8 |
-
|
| 9 |
-
from
|
| 10 |
-
from
|
| 11 |
-
import
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
Analyzes syntactic patterns, discourse markers, and linguistic anomalies.
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
-
def __init__(self):
|
| 24 |
-
self.discourse_markers = self._load_discourse_markers()
|
| 25 |
-
self.linguistic_patterns = self._load_linguistic_patterns()
|
| 26 |
-
self.pos_patterns = self._load_pos_patterns()
|
| 27 |
-
self.is_fitted_ = False
|
| 28 |
-
|
| 29 |
-
def _load_discourse_markers(self):
|
| 30 |
-
"""Load discourse markers for coherence analysis"""
|
| 31 |
-
markers = {
|
| 32 |
-
'addition': {'also', 'furthermore', 'moreover', 'additionally', 'besides', 'plus', 'and'},
|
| 33 |
-
'contrast': {'however', 'but', 'nevertheless', 'nonetheless', 'yet', 'still', 'although', 'though'},
|
| 34 |
-
'cause_effect': {'therefore', 'thus', 'consequently', 'as a result', 'because', 'since', 'so'},
|
| 35 |
-
'temporal': {'then', 'next', 'afterwards', 'meanwhile', 'subsequently', 'finally', 'first', 'second'},
|
| 36 |
-
'emphasis': {'indeed', 'certainly', 'obviously', 'clearly', 'definitely', 'absolutely', 'surely'},
|
| 37 |
-
'concession': {'admittedly', 'granted', 'to be sure', 'of course', 'naturally', 'undoubtedly'},
|
| 38 |
-
'exemplification': {'for example', 'for instance', 'such as', 'namely', 'specifically', 'particularly'},
|
| 39 |
-
'summary': {'in conclusion', 'to summarize', 'in summary', 'overall', 'in general', 'basically'}
|
| 40 |
-
}
|
| 41 |
-
return markers
|
| 42 |
-
|
| 43 |
-
def _load_linguistic_patterns(self):
|
| 44 |
-
"""Load patterns for linguistic analysis"""
|
| 45 |
-
patterns = {
|
| 46 |
-
'modal_verbs': {'can', 'could', 'may', 'might', 'must', 'shall', 'should', 'will', 'would'},
|
| 47 |
-
'hedge_words': {'probably', 'possibly', 'perhaps', 'maybe', 'likely', 'apparently', 'seemingly', 'supposedly'},
|
| 48 |
-
'boosters': {'very', 'extremely', 'highly', 'completely', 'totally', 'absolutely', 'definitely', 'certainly'},
|
| 49 |
-
'negation': {'not', 'no', 'never', 'nothing', 'nobody', 'nowhere', 'neither', 'nor'},
|
| 50 |
-
'intensifiers': {'so', 'such', 'quite', 'rather', 'pretty', 'fairly', 'really', 'truly', 'deeply'},
|
| 51 |
-
'questioning': {'why', 'how', 'what', 'when', 'where', 'who', 'which', 'whose'},
|
| 52 |
-
'personal_pronouns': {'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her', 'us', 'them'},
|
| 53 |
-
'demonstratives': {'this', 'that', 'these', 'those', 'here', 'there'},
|
| 54 |
-
'quantifiers': {'all', 'every', 'each', 'some', 'any', 'many', 'few', 'several', 'most', 'much'}
|
| 55 |
-
}
|
| 56 |
-
return patterns
|
| 57 |
-
|
| 58 |
-
def _load_pos_patterns(self):
|
| 59 |
-
"""Load part-of-speech patterns (simplified without NLTK)"""
|
| 60 |
-
# Simple heuristics for POS detection
|
| 61 |
-
patterns = {
|
| 62 |
-
'verb_endings': {'ed', 'ing', 'en', 's', 'es'},
|
| 63 |
-
'noun_endings': {'tion', 'sion', 'ment', 'ness', 'ity', 'er', 'or', 'ist', 'ism'},
|
| 64 |
-
'adjective_endings': {'able', 'ible', 'ful', 'less', 'ous', 'eous', 'ious', 'ive', 'ic', 'al'},
|
| 65 |
-
'adverb_endings': {'ly', 'ward', 'wise'}
|
| 66 |
-
}
|
| 67 |
-
return patterns
|
| 68 |
-
|
| 69 |
-
def fit(self, X, y=None):
|
| 70 |
-
"""Fit the linguistic analyzer"""
|
| 71 |
-
self.is_fitted_ = True
|
| 72 |
-
return self
|
| 73 |
|
| 74 |
-
def
|
| 75 |
-
|
| 76 |
-
if not self.is_fitted_:
|
| 77 |
-
raise ValueError("LinguisticAnalyzer must be fitted before transform")
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
if
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
|
| 85 |
-
|
|
|
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
def
|
| 94 |
-
"""
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
-
def
|
| 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 |
-
def
|
| 128 |
-
"""
|
| 129 |
-
|
| 130 |
-
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
marker_count = 0
|
| 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 |
-
def
|
| 163 |
-
"""
|
| 164 |
-
|
|
|
|
| 165 |
|
| 166 |
-
#
|
| 167 |
-
|
| 168 |
-
avg_sentence_length = len(words) / len(sentences)
|
| 169 |
-
else:
|
| 170 |
-
avg_sentence_length = 0
|
| 171 |
-
features.append(avg_sentence_length)
|
| 172 |
-
|
| 173 |
-
# Sentence length variance
|
| 174 |
-
if len(sentences) > 1:
|
| 175 |
-
sentence_lengths = [len(sentence.split()) for sentence in sentences]
|
| 176 |
-
mean_length = sum(sentence_lengths) / len(sentence_lengths)
|
| 177 |
-
variance = sum((length - mean_length) ** 2 for length in sentence_lengths) / len(sentence_lengths)
|
| 178 |
-
else:
|
| 179 |
-
variance = 0
|
| 180 |
-
features.append(variance)
|
| 181 |
-
|
| 182 |
-
# Complex sentence indicators
|
| 183 |
-
complex_indicators = self._count_complex_sentence_indicators(text)
|
| 184 |
-
features.extend(complex_indicators)
|
| 185 |
-
|
| 186 |
-
return features
|
| 187 |
-
|
| 188 |
-
def _count_complex_sentence_indicators(self, text):
|
| 189 |
-
"""Count indicators of complex sentence structure"""
|
| 190 |
-
indicators = []
|
| 191 |
-
|
| 192 |
-
# Subordinating conjunctions
|
| 193 |
-
subordinating = ['although', 'because', 'since', 'while', 'whereas', 'if', 'unless', 'when', 'where']
|
| 194 |
-
sub_count = sum(text.lower().count(f' {conj} ') for conj in subordinating)
|
| 195 |
-
indicators.append(sub_count / len(text) * 1000 if text else 0)
|
| 196 |
-
|
| 197 |
-
# Relative pronouns
|
| 198 |
-
relative_pronouns = ['that', 'which', 'who', 'whom', 'whose', 'where', 'when']
|
| 199 |
-
rel_count = sum(text.lower().count(f' {pron} ') for pron in relative_pronouns)
|
| 200 |
-
indicators.append(rel_count / len(text) * 1000 if text else 0)
|
| 201 |
-
|
| 202 |
-
# Passive voice indicators (simplified)
|
| 203 |
-
passive_indicators = ['was', 'were', 'been', 'being']
|
| 204 |
-
passive_count = sum(text.lower().count(f' {ind} ') for ind in passive_indicators)
|
| 205 |
-
indicators.append(passive_count / len(text) * 1000 if text else 0)
|
| 206 |
-
|
| 207 |
-
return indicators
|
| 208 |
-
|
| 209 |
-
def _extract_coherence_features(self, text, sentences):
|
| 210 |
-
"""Extract text coherence and flow features"""
|
| 211 |
-
features = []
|
| 212 |
|
| 213 |
-
#
|
| 214 |
-
|
| 215 |
-
paragraphs = [p.strip() for p in paragraphs if p.strip()]
|
| 216 |
|
| 217 |
-
#
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
avg_paragraph_length = 0
|
| 222 |
-
features.append(avg_paragraph_length)
|
| 223 |
|
| 224 |
-
#
|
| 225 |
-
|
| 226 |
-
features.append(coherence_score)
|
| 227 |
|
| 228 |
-
#
|
| 229 |
-
|
| 230 |
-
features.append(transition_density)
|
| 231 |
|
| 232 |
-
return
|
| 233 |
|
| 234 |
-
def
|
| 235 |
-
"""
|
| 236 |
-
if
|
| 237 |
-
return
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
words1 = set(re.findall(r'\b\w+\b', sentences[i].lower()))
|
| 243 |
-
words2 = set(re.findall(r'\b\w+\b', sentences[i + 1].lower()))
|
| 244 |
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
-
def
|
| 259 |
-
"""
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
else:
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
-
def
|
| 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 |
-
def
|
| 310 |
-
"""
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
'text_length': len(text),
|
| 322 |
-
'word_count': len(words),
|
| 323 |
-
'sentence_count': len(sentences),
|
| 324 |
-
'avg_words_per_sentence': len(words) / len(sentences) if sentences else 0
|
| 325 |
},
|
| 326 |
-
'
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
}
|
| 331 |
|
| 332 |
-
#
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
for marker in markers:
|
| 341 |
-
if ' ' in marker and marker in text_lower:
|
| 342 |
-
found_markers.extend([marker] * text_lower.count(marker))
|
| 343 |
-
|
| 344 |
-
analysis['discourse_markers'][marker_type] = {
|
| 345 |
-
'count': len(found_markers),
|
| 346 |
-
'ratio': len(found_markers) / len(words) if words else 0,
|
| 347 |
-
'markers_found': list(set(found_markers))[:5] # Top 5 unique markers
|
| 348 |
}
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
'
|
| 355 |
-
'
|
| 356 |
-
'patterns_found': list(set(found_patterns))[:5]
|
| 357 |
}
|
| 358 |
|
| 359 |
-
#
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
'complexity_score': sum(complex_indicators) / len(complex_indicators)
|
| 367 |
-
}
|
| 368 |
-
|
| 369 |
-
# Analyze coherence
|
| 370 |
-
analysis['coherence_analysis'] = {
|
| 371 |
-
'lexical_coherence': self._calculate_lexical_coherence(sentences),
|
| 372 |
-
'transition_density': self._calculate_transition_density(text),
|
| 373 |
-
'paragraph_structure': len(text.split('\n\n')),
|
| 374 |
-
'overall_coherence_score': (self._calculate_lexical_coherence(sentences) +
|
| 375 |
-
min(1.0, self._calculate_transition_density(text) / 10)) / 2
|
| 376 |
-
}
|
| 377 |
-
|
| 378 |
-
# Overall assessment
|
| 379 |
-
analysis['overall_assessment'] = {
|
| 380 |
-
'linguistic_sophistication': self._assess_sophistication(analysis),
|
| 381 |
-
'discourse_quality': self._assess_discourse_quality(analysis),
|
| 382 |
-
'potential_anomalies': self._detect_linguistic_anomalies(analysis)
|
| 383 |
-
}
|
| 384 |
|
| 385 |
-
return
|
| 386 |
|
| 387 |
-
def
|
| 388 |
-
"""
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
#
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
|
| 410 |
-
def
|
| 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 |
else:
|
| 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 |
-
'examples': analysis['linguistic_patterns']['questioning']['patterns_found']
|
| 482 |
-
})
|
| 483 |
-
|
| 484 |
-
return anomalies
|
| 485 |
-
|
| 486 |
-
def get_manipulation_indicators(self, text):
|
| 487 |
-
"""Get specific linguistic manipulation indicators"""
|
| 488 |
-
analysis = self.analyze_text_linguistics(text)
|
| 489 |
-
|
| 490 |
-
indicators = {
|
| 491 |
-
'linguistic_manipulation_score': 0.0,
|
| 492 |
-
'specific_indicators': [],
|
| 493 |
-
'overall_risk': 'low'
|
| 494 |
}
|
| 495 |
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# File: data/prepare_datasets.py (ENHANCED)
|
| 2 |
+
# Enhanced version with feature engineering integration and advanced validation
|
| 3 |
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
from pathlib import Path
|
| 7 |
import logging
|
| 8 |
+
import re
|
| 9 |
+
from typing import Optional, Tuple, Dict, Any
|
| 10 |
+
from sklearn.model_selection import train_test_split
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
from data.data_validator import DataValidationPipeline
|
| 15 |
+
from data.validation_schemas import ValidationLevel, DataSource
|
| 16 |
+
from typing import Tuple, Dict
|
| 17 |
+
|
| 18 |
+
# Import enhanced feature engineering components
|
| 19 |
+
try:
|
| 20 |
+
from features.feature_engineer import AdvancedFeatureEngineer
|
| 21 |
+
from features.sentiment_analyzer import SentimentAnalyzer
|
| 22 |
+
from features.readability_analyzer import ReadabilityAnalyzer
|
| 23 |
+
from features.entity_analyzer import EntityAnalyzer
|
| 24 |
+
from features.linguistic_analyzer import LinguisticAnalyzer
|
| 25 |
+
ENHANCED_FEATURES_AVAILABLE = True
|
| 26 |
+
except ImportError as e:
|
| 27 |
+
ENHANCED_FEATURES_AVAILABLE = False
|
| 28 |
+
logging.warning(f"Enhanced features not available in prepare_datasets.py: {e}")
|
| 29 |
|
| 30 |
+
# Configure logging
|
| 31 |
+
logging.basicConfig(
|
| 32 |
+
level=logging.INFO,
|
| 33 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 34 |
+
handlers=[
|
| 35 |
+
logging.FileHandler('/tmp/data_preparation.log'),
|
| 36 |
+
logging.StreamHandler()
|
| 37 |
+
]
|
| 38 |
+
)
|
| 39 |
logger = logging.getLogger(__name__)
|
| 40 |
|
| 41 |
+
# Log enhanced feature availability
|
| 42 |
+
if ENHANCED_FEATURES_AVAILABLE:
|
| 43 |
+
logger.info("Enhanced feature engineering components loaded for data preparation")
|
| 44 |
+
else:
|
| 45 |
+
logger.warning("Enhanced features not available - standard validation only")
|
| 46 |
|
| 47 |
+
|
| 48 |
+
class EnhancedDatasetPreparer:
|
| 49 |
+
"""Enhanced dataset preparation with feature engineering integration and comprehensive validation"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
def __init__(self, base_dir: Path = None, enable_feature_analysis: bool = None):
|
| 52 |
+
self.base_dir = base_dir or Path(__file__).resolve().parent
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
# Auto-detect enhanced features if not specified
|
| 55 |
+
if enable_feature_analysis is None:
|
| 56 |
+
self.enable_feature_analysis = ENHANCED_FEATURES_AVAILABLE
|
| 57 |
+
else:
|
| 58 |
+
self.enable_feature_analysis = enable_feature_analysis and ENHANCED_FEATURES_AVAILABLE
|
| 59 |
|
| 60 |
+
self.setup_paths()
|
| 61 |
+
self.setup_feature_analyzers()
|
| 62 |
|
| 63 |
+
logger.info(f"Enhanced dataset preparer initialized with feature analysis: {self.enable_feature_analysis}")
|
| 64 |
+
|
| 65 |
+
def setup_paths(self):
|
| 66 |
+
"""Setup all necessary paths"""
|
| 67 |
+
# Input paths
|
| 68 |
+
self.kaggle_fake = self.base_dir / "kaggle" / "Fake.csv"
|
| 69 |
+
self.kaggle_real = self.base_dir / "kaggle" / "True.csv"
|
| 70 |
+
self.liar_paths = [
|
| 71 |
+
self.base_dir / "liar" / "train.tsv",
|
| 72 |
+
self.base_dir / "liar" / "test.tsv",
|
| 73 |
+
self.base_dir / "liar" / "valid.tsv"
|
| 74 |
+
]
|
| 75 |
|
| 76 |
+
# Output paths
|
| 77 |
+
self.output_dir = Path("/tmp/data")
|
| 78 |
+
self.output_dir.mkdir(parents=True, exist_ok=True)
|
| 79 |
+
self.output_path = self.output_dir / "combined_dataset.csv"
|
| 80 |
+
self.metadata_path = self.output_dir / "dataset_metadata.json"
|
| 81 |
+
|
| 82 |
+
# Enhanced feature paths
|
| 83 |
+
self.feature_analysis_dir = self.output_dir / "feature_analysis"
|
| 84 |
+
self.feature_analysis_dir.mkdir(parents=True, exist_ok=True)
|
| 85 |
+
self.feature_quality_path = self.feature_analysis_dir / "feature_quality_report.json"
|
| 86 |
+
self.feature_samples_path = self.feature_analysis_dir / "feature_samples.json"
|
| 87 |
|
| 88 |
+
def setup_feature_analyzers(self):
|
| 89 |
+
"""Setup feature analyzers if enhanced features are enabled"""
|
| 90 |
+
self.feature_analyzers = {}
|
| 91 |
+
|
| 92 |
+
if self.enable_feature_analysis:
|
| 93 |
+
try:
|
| 94 |
+
self.feature_analyzers = {
|
| 95 |
+
'sentiment': SentimentAnalyzer(),
|
| 96 |
+
'readability': ReadabilityAnalyzer(),
|
| 97 |
+
'entity': EntityAnalyzer(),
|
| 98 |
+
'linguistic': LinguisticAnalyzer()
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
# Fit analyzers (they're stateless but need fit() call for API consistency)
|
| 102 |
+
for analyzer in self.feature_analyzers.values():
|
| 103 |
+
analyzer.fit([])
|
| 104 |
+
|
| 105 |
+
logger.info("Enhanced feature analyzers initialized successfully")
|
| 106 |
+
|
| 107 |
+
except Exception as e:
|
| 108 |
+
logger.warning(f"Failed to initialize feature analyzers: {e}")
|
| 109 |
+
self.enable_feature_analysis = False
|
| 110 |
+
self.feature_analyzers = {}
|
| 111 |
|
| 112 |
+
def validate_text_quality(self, text: str) -> bool:
|
| 113 |
+
"""Enhanced text quality validation with feature analysis"""
|
| 114 |
+
if not isinstance(text, str):
|
| 115 |
+
return False
|
| 116 |
+
|
| 117 |
+
text = text.strip()
|
| 118 |
+
|
| 119 |
+
# Basic length check
|
| 120 |
+
if len(text) < 10:
|
| 121 |
+
return False
|
| 122 |
+
|
| 123 |
+
# Check for meaningful content
|
| 124 |
+
if not any(c.isalpha() for c in text):
|
| 125 |
+
return False
|
| 126 |
+
|
| 127 |
+
# Check for sentence structure
|
| 128 |
+
if not any(punct in text for punct in '.!?'):
|
| 129 |
+
return False
|
| 130 |
+
|
| 131 |
+
# Check for excessive repetition
|
| 132 |
+
words = text.lower().split()
|
| 133 |
+
if len(words) > 0:
|
| 134 |
+
most_common_word_count = max(words.count(word) for word in set(words))
|
| 135 |
+
if most_common_word_count > len(words) * 0.5: # More than 50% repetition
|
| 136 |
+
return False
|
| 137 |
+
|
| 138 |
+
# Check for excessive special characters
|
| 139 |
+
special_char_ratio = sum(1 for c in text if not c.isalnum() and not c.isspace()) / len(text)
|
| 140 |
+
if special_char_ratio > 0.3: # More than 30% special characters
|
| 141 |
+
return False
|
| 142 |
+
|
| 143 |
+
# Enhanced feature-based quality checks
|
| 144 |
+
if self.enable_feature_analysis:
|
| 145 |
+
try:
|
| 146 |
+
quality_score = self.assess_text_feature_quality(text)
|
| 147 |
+
if quality_score < 0.3: # Minimum quality threshold
|
| 148 |
+
return False
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.warning(f"Feature quality check failed for text: {e}")
|
| 151 |
+
|
| 152 |
+
return True
|
| 153 |
|
| 154 |
+
def assess_text_feature_quality(self, text: str) -> float:
|
| 155 |
+
"""Assess text quality using enhanced features"""
|
| 156 |
+
if not self.enable_feature_analysis:
|
| 157 |
+
return 1.0 # Default to high quality if features not available
|
| 158 |
|
| 159 |
+
try:
|
| 160 |
+
quality_scores = []
|
|
|
|
| 161 |
|
| 162 |
+
# Sentiment analysis quality
|
| 163 |
+
if 'sentiment' in self.feature_analyzers:
|
| 164 |
+
sentiment_analysis = self.feature_analyzers['sentiment'].analyze_text_sentiment(text)
|
| 165 |
+
# Good quality text should have reasonable emotional balance
|
| 166 |
+
emotional_balance = 1 - abs(sentiment_analysis.get('emotional_intensity', 0))
|
| 167 |
+
quality_scores.append(max(0.1, emotional_balance))
|
| 168 |
|
| 169 |
+
# Readability quality
|
| 170 |
+
if 'readability' in self.feature_analyzers:
|
| 171 |
+
readability_analysis = self.feature_analyzers['readability'].analyze_text_readability(text)
|
| 172 |
+
if 'interpretation' in readability_analysis:
|
| 173 |
+
readability_level = readability_analysis['interpretation'].get('readability_level', 'standard')
|
| 174 |
+
# Moderate readability levels indicate higher quality
|
| 175 |
+
readability_score = {
|
| 176 |
+
'very_easy': 0.7, 'easy': 0.8, 'fairly_easy': 0.9, 'standard': 1.0,
|
| 177 |
+
'fairly_difficult': 0.9, 'difficult': 0.7, 'very_difficult': 0.5
|
| 178 |
+
}.get(readability_level, 0.5)
|
| 179 |
+
quality_scores.append(readability_score)
|
| 180 |
|
| 181 |
+
# Entity analysis quality
|
| 182 |
+
if 'entity' in self.feature_analyzers:
|
| 183 |
+
entity_analysis = self.feature_analyzers['entity'].analyze_text_entities(text)
|
| 184 |
+
# Quality text should have reasonable entity density
|
| 185 |
+
entity_density = entity_analysis.get('summary', {}).get('total_entities_found', 0)
|
| 186 |
+
normalized_density = min(1.0, entity_density / max(1, len(text.split()) * 0.1))
|
| 187 |
+
quality_scores.append(0.5 + normalized_density * 0.5)
|
| 188 |
+
|
| 189 |
+
# Linguistic analysis quality
|
| 190 |
+
if 'linguistic' in self.feature_analyzers:
|
| 191 |
+
linguistic_analysis = self.feature_analyzers['linguistic'].analyze_text_linguistics(text)
|
| 192 |
+
discourse_quality = linguistic_analysis.get('overall_assessment', {}).get('discourse_quality', 'fair')
|
| 193 |
+
discourse_score = {
|
| 194 |
+
'poor': 0.3, 'fair': 0.6, 'good': 0.8, 'excellent': 1.0
|
| 195 |
+
}.get(discourse_quality, 0.5)
|
| 196 |
+
quality_scores.append(discourse_score)
|
| 197 |
+
|
| 198 |
+
# Calculate overall quality score
|
| 199 |
+
if quality_scores:
|
| 200 |
+
overall_quality = sum(quality_scores) / len(quality_scores)
|
| 201 |
+
else:
|
| 202 |
+
overall_quality = 1.0 # Default if no analyzers available
|
| 203 |
+
|
| 204 |
+
return overall_quality
|
| 205 |
+
|
| 206 |
+
except Exception as e:
|
| 207 |
+
logger.warning(f"Feature quality assessment failed: {e}")
|
| 208 |
+
return 0.5 # Default middle-ground quality
|
| 209 |
|
| 210 |
+
def clean_text(self, text: str) -> str:
|
| 211 |
+
"""Enhanced text cleaning with feature preservation"""
|
| 212 |
+
if not isinstance(text, str):
|
| 213 |
+
return ""
|
| 214 |
|
| 215 |
+
# Remove excessive whitespace
|
| 216 |
+
text = re.sub(r'\s+', ' ', text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
+
# Remove URLs but preserve text structure
|
| 219 |
+
text = re.sub(r'http\S+|www\S+|https\S+', '[URL]', text)
|
|
|
|
| 220 |
|
| 221 |
+
# Remove excessive punctuation while preserving meaning
|
| 222 |
+
text = re.sub(r'[!]{3,}', '!!', text)
|
| 223 |
+
text = re.sub(r'[?]{3,}', '??', text)
|
| 224 |
+
text = re.sub(r'[.]{4,}', '...', text)
|
|
|
|
|
|
|
| 225 |
|
| 226 |
+
# Remove non-printable characters
|
| 227 |
+
text = ''.join(char for char in text if ord(char) >= 32)
|
|
|
|
| 228 |
|
| 229 |
+
# Preserve important features for analysis
|
| 230 |
+
# Don't over-clean as it might remove important linguistic patterns
|
|
|
|
| 231 |
|
| 232 |
+
return text.strip()
|
| 233 |
|
| 234 |
+
def extract_text_features_sample(self, texts: list, sample_size: int = 100) -> Dict:
|
| 235 |
+
"""Extract feature samples for quality analysis"""
|
| 236 |
+
if not self.enable_feature_analysis or not texts:
|
| 237 |
+
return {}
|
| 238 |
+
|
| 239 |
+
try:
|
| 240 |
+
# Sample texts for feature analysis
|
| 241 |
+
sample_texts = texts[:sample_size] if len(texts) > sample_size else texts
|
|
|
|
|
|
|
| 242 |
|
| 243 |
+
feature_samples = {
|
| 244 |
+
'sample_size': len(sample_texts),
|
| 245 |
+
'total_texts': len(texts),
|
| 246 |
+
'feature_analysis': {},
|
| 247 |
+
'quality_metrics': {},
|
| 248 |
+
'timestamp': datetime.now().isoformat()
|
| 249 |
+
}
|
| 250 |
|
| 251 |
+
# Analyze features for sample texts
|
| 252 |
+
for analyzer_name, analyzer in self.feature_analyzers.items():
|
| 253 |
+
try:
|
| 254 |
+
analyzer_samples = []
|
| 255 |
+
|
| 256 |
+
for i, text in enumerate(sample_texts[:10]): # Analyze first 10 for detailed samples
|
| 257 |
+
if analyzer_name == 'sentiment':
|
| 258 |
+
analysis = analyzer.analyze_text_sentiment(text)
|
| 259 |
+
elif analyzer_name == 'readability':
|
| 260 |
+
analysis = analyzer.analyze_text_readability(text)
|
| 261 |
+
elif analyzer_name == 'entity':
|
| 262 |
+
analysis = analyzer.analyze_text_entities(text)
|
| 263 |
+
elif analyzer_name == 'linguistic':
|
| 264 |
+
analysis = analyzer.analyze_text_linguistics(text)
|
| 265 |
+
else:
|
| 266 |
+
continue
|
| 267 |
+
|
| 268 |
+
analyzer_samples.append({
|
| 269 |
+
'text_index': i,
|
| 270 |
+
'text_preview': text[:100] + "..." if len(text) > 100 else text,
|
| 271 |
+
'analysis': analysis
|
| 272 |
+
})
|
| 273 |
+
|
| 274 |
+
feature_samples['feature_analysis'][analyzer_name] = analyzer_samples
|
| 275 |
+
|
| 276 |
+
except Exception as e:
|
| 277 |
+
logger.warning(f"Feature analysis failed for {analyzer_name}: {e}")
|
| 278 |
+
feature_samples['feature_analysis'][analyzer_name] = {'error': str(e)}
|
| 279 |
+
|
| 280 |
+
# Calculate overall quality metrics
|
| 281 |
+
quality_scores = []
|
| 282 |
+
for text in sample_texts:
|
| 283 |
+
quality_score = self.assess_text_feature_quality(text)
|
| 284 |
+
quality_scores.append(quality_score)
|
| 285 |
+
|
| 286 |
+
feature_samples['quality_metrics'] = {
|
| 287 |
+
'mean_quality': float(np.mean(quality_scores)),
|
| 288 |
+
'std_quality': float(np.std(quality_scores)),
|
| 289 |
+
'min_quality': float(np.min(quality_scores)),
|
| 290 |
+
'max_quality': float(np.max(quality_scores)),
|
| 291 |
+
'quality_distribution': {
|
| 292 |
+
'high_quality': sum(1 for q in quality_scores if q > 0.7),
|
| 293 |
+
'medium_quality': sum(1 for q in quality_scores if 0.4 <= q <= 0.7),
|
| 294 |
+
'low_quality': sum(1 for q in quality_scores if q < 0.4)
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
return feature_samples
|
| 299 |
+
|
| 300 |
+
except Exception as e:
|
| 301 |
+
logger.error(f"Feature sample extraction failed: {e}")
|
| 302 |
+
return {'error': str(e)}
|
| 303 |
|
| 304 |
+
def load_kaggle_dataset(self) -> Optional[pd.DataFrame]:
|
| 305 |
+
"""Load and process Kaggle dataset with enhanced validation"""
|
| 306 |
+
try:
|
| 307 |
+
logger.info("Loading Kaggle dataset with enhanced validation...")
|
| 308 |
+
|
| 309 |
+
# Check if files exist
|
| 310 |
+
if not self.kaggle_fake.exists() or not self.kaggle_real.exists():
|
| 311 |
+
logger.warning("Kaggle dataset files not found")
|
| 312 |
+
return None
|
| 313 |
+
|
| 314 |
+
# Load datasets
|
| 315 |
+
df_fake = pd.read_csv(self.kaggle_fake)
|
| 316 |
+
df_real = pd.read_csv(self.kaggle_real)
|
| 317 |
+
|
| 318 |
+
logger.info(f"Loaded {len(df_fake)} fake and {len(df_real)} real articles from Kaggle")
|
| 319 |
+
|
| 320 |
+
# Process fake news
|
| 321 |
+
df_fake['label'] = 1
|
| 322 |
+
df_fake['text'] = df_fake['title'].fillna('') + ". " + df_fake['text'].fillna('')
|
| 323 |
+
df_fake['source'] = 'kaggle_fake'
|
| 324 |
+
df_fake['original_source'] = 'kaggle'
|
| 325 |
+
|
| 326 |
+
# Process real news
|
| 327 |
+
df_real['label'] = 0
|
| 328 |
+
df_real['text'] = df_real['title'].fillna('') + ". " + df_real['text'].fillna('')
|
| 329 |
+
df_real['source'] = 'kaggle_real'
|
| 330 |
+
df_real['original_source'] = 'kaggle'
|
| 331 |
+
|
| 332 |
+
# Combine datasets
|
| 333 |
+
df_combined = pd.concat([
|
| 334 |
+
df_fake[['text', 'label', 'source', 'original_source']],
|
| 335 |
+
df_real[['text', 'label', 'source', 'original_source']]
|
| 336 |
+
], ignore_index=True)
|
| 337 |
+
|
| 338 |
+
logger.info(f"Combined Kaggle dataset: {len(df_combined)} samples")
|
| 339 |
+
|
| 340 |
+
# Enhanced validation with feature analysis
|
| 341 |
+
validated_df, validation_report = self.validate_dataset_with_enhanced_features(
|
| 342 |
+
df_combined, 'kaggle_combined'
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
return validated_df, validation_report
|
| 346 |
+
|
| 347 |
+
except Exception as e:
|
| 348 |
+
logger.error(f"Error loading Kaggle dataset: {e}")
|
| 349 |
+
return None
|
| 350 |
+
|
| 351 |
+
def load_liar_dataset(self) -> Optional[pd.DataFrame]:
|
| 352 |
+
"""Load and process LIAR dataset with enhanced validation"""
|
| 353 |
+
try:
|
| 354 |
+
logger.info("Loading LIAR dataset with enhanced validation...")
|
| 355 |
+
|
| 356 |
+
liar_dfs = []
|
| 357 |
+
total_processed = 0
|
| 358 |
+
|
| 359 |
+
for path in self.liar_paths:
|
| 360 |
+
if not path.exists():
|
| 361 |
+
logger.warning(f"LIAR file not found: {path}")
|
| 362 |
+
continue
|
| 363 |
+
|
| 364 |
+
try:
|
| 365 |
+
# Read TSV with flexible parameters
|
| 366 |
+
df = pd.read_csv(
|
| 367 |
+
path,
|
| 368 |
+
sep='\t',
|
| 369 |
+
header=None,
|
| 370 |
+
quoting=3,
|
| 371 |
+
on_bad_lines='skip',
|
| 372 |
+
low_memory=False
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# Expected columns for LIAR dataset
|
| 376 |
+
expected_columns = [
|
| 377 |
+
'id', 'label_text', 'statement', 'subject', 'speaker', 'job',
|
| 378 |
+
'state', 'party', 'barely_true', 'false', 'half_true',
|
| 379 |
+
'mostly_true', 'pants_on_fire', 'context'
|
| 380 |
+
]
|
| 381 |
+
|
| 382 |
+
# Handle different column counts
|
| 383 |
+
if len(df.columns) >= 3:
|
| 384 |
+
df.columns = expected_columns[:len(df.columns)]
|
| 385 |
+
|
| 386 |
+
# Map labels to binary classification
|
| 387 |
+
if 'label_text' in df.columns:
|
| 388 |
+
df['label'] = df['label_text'].apply(
|
| 389 |
+
lambda x: 1 if str(x).lower() in ['false', 'pants-fire', 'barely-true'] else 0
|
| 390 |
+
)
|
| 391 |
+
else:
|
| 392 |
+
continue
|
| 393 |
+
|
| 394 |
+
# Extract text
|
| 395 |
+
if 'statement' in df.columns:
|
| 396 |
+
df['text'] = df['statement'].astype(str)
|
| 397 |
+
else:
|
| 398 |
+
continue
|
| 399 |
+
|
| 400 |
+
df['source'] = f'liar_{path.stem}'
|
| 401 |
+
df['original_source'] = 'liar'
|
| 402 |
+
|
| 403 |
+
processed_df = df[['text', 'label', 'source', 'original_source']].copy()
|
| 404 |
+
liar_dfs.append(processed_df)
|
| 405 |
+
total_processed += len(processed_df)
|
| 406 |
+
|
| 407 |
+
logger.info(f"Processed {len(processed_df)} samples from {path.name}")
|
| 408 |
+
|
| 409 |
+
except Exception as e:
|
| 410 |
+
logger.error(f"Error processing LIAR file {path}: {e}")
|
| 411 |
+
continue
|
| 412 |
+
|
| 413 |
+
if liar_dfs:
|
| 414 |
+
combined_liar = pd.concat(liar_dfs, ignore_index=True)
|
| 415 |
+
logger.info(f"Combined LIAR dataset: {len(combined_liar)} samples")
|
| 416 |
+
|
| 417 |
+
# Enhanced validation with feature analysis
|
| 418 |
+
validated_df, validation_report = self.validate_dataset_with_enhanced_features(
|
| 419 |
+
combined_liar, 'liar_combined'
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
return validated_df, validation_report
|
| 423 |
else:
|
| 424 |
+
logger.warning("No LIAR data could be processed")
|
| 425 |
+
return None
|
| 426 |
+
|
| 427 |
+
except Exception as e:
|
| 428 |
+
logger.error(f"Error loading LIAR dataset: {e}")
|
| 429 |
+
return None
|
| 430 |
|
| 431 |
+
def validate_dataset(self, df: pd.DataFrame) -> pd.DataFrame:
|
| 432 |
+
"""Comprehensive dataset validation with enhanced feature analysis"""
|
| 433 |
+
logger.info("Starting enhanced dataset validation...")
|
| 434 |
+
|
| 435 |
+
initial_count = len(df)
|
| 436 |
+
|
| 437 |
+
# Remove null texts
|
| 438 |
+
df = df.dropna(subset=['text'])
|
| 439 |
+
logger.info(f"Removed {initial_count - len(df)} null text entries")
|
| 440 |
+
|
| 441 |
+
# Clean text with feature preservation
|
| 442 |
+
df['text'] = df['text'].apply(self.clean_text)
|
| 443 |
+
|
| 444 |
+
# Enhanced text quality validation
|
| 445 |
+
if self.enable_feature_analysis:
|
| 446 |
+
logger.info("Performing feature-based quality validation...")
|
| 447 |
+
quality_mask = df['text'].apply(self.validate_text_quality)
|
| 448 |
+
quality_removed = len(df) - quality_mask.sum()
|
| 449 |
+
df = df[quality_mask]
|
| 450 |
+
logger.info(f"Removed {quality_removed} low-quality texts using enhanced validation")
|
| 451 |
+
else:
|
| 452 |
+
# Standard validation
|
| 453 |
+
valid_mask = df['text'].apply(self.validate_text_quality)
|
| 454 |
+
df = df[valid_mask]
|
| 455 |
+
logger.info(f"Removed {initial_count - valid_mask.sum()} low-quality texts")
|
| 456 |
+
|
| 457 |
+
# Remove duplicates
|
| 458 |
+
before_dedup = len(df)
|
| 459 |
+
df = df.drop_duplicates(subset=['text'])
|
| 460 |
+
logger.info(f"Removed {before_dedup - len(df)} duplicate texts")
|
| 461 |
+
|
| 462 |
+
# Validate label distribution
|
| 463 |
+
label_counts = df['label'].value_counts()
|
| 464 |
+
logger.info(f"Label distribution: {label_counts.to_dict()}")
|
| 465 |
+
|
| 466 |
+
# Check for balance
|
| 467 |
+
if len(label_counts) > 1:
|
| 468 |
+
balance_ratio = label_counts.min() / label_counts.max()
|
| 469 |
+
if balance_ratio < 0.3:
|
| 470 |
+
logger.warning(f"Dataset is imbalanced (ratio: {balance_ratio:.2f})")
|
| 471 |
+
|
| 472 |
+
# Add enhanced metadata
|
| 473 |
+
df['text_length'] = df['text'].str.len()
|
| 474 |
+
df['word_count'] = df['text'].str.split().str.len()
|
| 475 |
+
df['processed_timestamp'] = datetime.now().isoformat()
|
| 476 |
+
|
| 477 |
+
# Add feature quality scores if enhanced features are available
|
| 478 |
+
if self.enable_feature_analysis:
|
| 479 |
+
logger.info("Adding feature quality scores...")
|
| 480 |
+
try:
|
| 481 |
+
df['feature_quality_score'] = df['text'].apply(self.assess_text_feature_quality)
|
| 482 |
+
quality_stats = df['feature_quality_score'].describe()
|
| 483 |
+
logger.info(f"Feature quality statistics: mean={quality_stats['mean']:.3f}, std={quality_stats['std']:.3f}")
|
| 484 |
+
except Exception as e:
|
| 485 |
+
logger.warning(f"Failed to add feature quality scores: {e}")
|
| 486 |
+
|
| 487 |
+
return df
|
| 488 |
|
| 489 |
+
def generate_dataset_metadata(self, df: pd.DataFrame, feature_samples: Dict = None) -> dict:
|
| 490 |
+
"""Generate comprehensive dataset metadata with feature analysis"""
|
| 491 |
+
metadata = {
|
| 492 |
+
'total_samples': len(df),
|
| 493 |
+
'label_distribution': df['label'].value_counts().to_dict(),
|
| 494 |
+
'source_distribution': df['source'].value_counts().to_dict() if 'source' in df.columns else {},
|
| 495 |
+
'text_length_stats': {
|
| 496 |
+
'mean': float(df['text_length'].mean()),
|
| 497 |
+
'std': float(df['text_length'].std()),
|
| 498 |
+
'min': int(df['text_length'].min()),
|
| 499 |
+
'max': int(df['text_length'].max()),
|
| 500 |
+
'median': float(df['text_length'].median())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 501 |
},
|
| 502 |
+
'word_count_stats': {
|
| 503 |
+
'mean': float(df['word_count'].mean()),
|
| 504 |
+
'std': float(df['word_count'].std()),
|
| 505 |
+
'min': int(df['word_count'].min()),
|
| 506 |
+
'max': int(df['word_count'].max()),
|
| 507 |
+
'median': float(df['word_count'].median())
|
| 508 |
+
},
|
| 509 |
+
'data_hash': hashlib.md5(df['text'].str.cat().encode()).hexdigest(),
|
| 510 |
+
'creation_timestamp': datetime.now().isoformat(),
|
| 511 |
+
'quality_score': self.calculate_quality_score(df),
|
| 512 |
+
'enhanced_features': {
|
| 513 |
+
'feature_analysis_enabled': self.enable_feature_analysis,
|
| 514 |
+
'enhanced_features_available': ENHANCED_FEATURES_AVAILABLE
|
| 515 |
+
}
|
| 516 |
}
|
| 517 |
|
| 518 |
+
# Add feature quality statistics if available
|
| 519 |
+
if self.enable_feature_analysis and 'feature_quality_score' in df.columns:
|
| 520 |
+
metadata['feature_quality_stats'] = {
|
| 521 |
+
'mean': float(df['feature_quality_score'].mean()),
|
| 522 |
+
'std': float(df['feature_quality_score'].std()),
|
| 523 |
+
'min': float(df['feature_quality_score'].min()),
|
| 524 |
+
'max': float(df['feature_quality_score'].max()),
|
| 525 |
+
'median': float(df['feature_quality_score'].median())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
}
|
| 527 |
+
|
| 528 |
+
# Quality distribution
|
| 529 |
+
quality_scores = df['feature_quality_score']
|
| 530 |
+
metadata['feature_quality_distribution'] = {
|
| 531 |
+
'high_quality': int(sum(quality_scores > 0.7)),
|
| 532 |
+
'medium_quality': int(sum((quality_scores >= 0.4) & (quality_scores <= 0.7))),
|
| 533 |
+
'low_quality': int(sum(quality_scores < 0.4))
|
|
|
|
| 534 |
}
|
| 535 |
|
| 536 |
+
# Add feature samples if provided
|
| 537 |
+
if feature_samples:
|
| 538 |
+
metadata['feature_analysis_summary'] = {
|
| 539 |
+
'sample_analyzed': feature_samples.get('sample_size', 0),
|
| 540 |
+
'quality_metrics': feature_samples.get('quality_metrics', {}),
|
| 541 |
+
'analyzers_used': list(feature_samples.get('feature_analysis', {}).keys())
|
| 542 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
|
| 544 |
+
return metadata
|
| 545 |
|
| 546 |
+
def calculate_quality_score(self, df: pd.DataFrame) -> float:
|
| 547 |
+
"""Calculate overall dataset quality score with feature consideration"""
|
| 548 |
+
scores = []
|
| 549 |
+
|
| 550 |
+
# Balance score
|
| 551 |
+
label_counts = df['label'].value_counts()
|
| 552 |
+
if len(label_counts) > 1:
|
| 553 |
+
balance_score = label_counts.min() / label_counts.max()
|
| 554 |
+
scores.append(balance_score)
|
| 555 |
+
|
| 556 |
+
# Diversity score (based on unique text ratio)
|
| 557 |
+
diversity_score = df['text'].nunique() / len(df)
|
| 558 |
+
scores.append(diversity_score)
|
| 559 |
+
|
| 560 |
+
# Length consistency score
|
| 561 |
+
text_lengths = df['text_length']
|
| 562 |
+
length_cv = text_lengths.std() / text_lengths.mean() # Coefficient of variation
|
| 563 |
+
length_score = max(0, 1 - length_cv / 2) # Normalize to 0-1
|
| 564 |
+
scores.append(length_score)
|
| 565 |
+
|
| 566 |
+
# Feature quality score if available
|
| 567 |
+
if self.enable_feature_analysis and 'feature_quality_score' in df.columns:
|
| 568 |
+
feature_quality_mean = df['feature_quality_score'].mean()
|
| 569 |
+
scores.append(feature_quality_mean)
|
| 570 |
+
|
| 571 |
+
return float(np.mean(scores))
|
| 572 |
|
| 573 |
+
def validate_dataset_with_enhanced_features(self, df: pd.DataFrame, source_name: str) -> Tuple[pd.DataFrame, Dict]:
|
| 574 |
+
"""Validate dataset using both standard and enhanced feature validation"""
|
| 575 |
+
logger.info(f"Starting enhanced validation for {source_name}...")
|
| 576 |
+
|
| 577 |
+
# Standard validation using existing schemas
|
| 578 |
+
validator = DataValidationPipeline()
|
| 579 |
+
|
| 580 |
+
# Convert DataFrame to validation format
|
| 581 |
+
articles_data = []
|
| 582 |
+
for _, row in df.iterrows():
|
| 583 |
+
article_data = {
|
| 584 |
+
'text': str(row.get('text', '')),
|
| 585 |
+
'label': int(row.get('label', 0)),
|
| 586 |
+
'source': source_name
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
if 'title' in row and pd.notna(row['title']):
|
| 590 |
+
article_data['title'] = str(row['title'])
|
| 591 |
+
if 'url' in row and pd.notna(row['url']):
|
| 592 |
+
article_data['url'] = str(row['url'])
|
| 593 |
+
|
| 594 |
+
articles_data.append(article_data)
|
| 595 |
+
|
| 596 |
+
# Perform batch validation
|
| 597 |
+
validation_result = validator.validate_batch(
|
| 598 |
+
articles_data,
|
| 599 |
+
batch_id=f"{source_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
|
| 600 |
+
validation_level=ValidationLevel.MODERATE
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
# Filter valid articles and add quality scores
|
| 604 |
+
valid_indices = [i for i, result in enumerate(validation_result.validation_results) if result.is_valid]
|
| 605 |
+
|
| 606 |
+
if valid_indices:
|
| 607 |
+
valid_df = df.iloc[valid_indices].copy()
|
| 608 |
+
quality_scores = [validation_result.validation_results[i].quality_metrics.get('overall_quality_score', 0.0)
|
| 609 |
+
for i in valid_indices]
|
| 610 |
+
valid_df['validation_quality_score'] = quality_scores
|
| 611 |
+
valid_df['validation_timestamp'] = datetime.now().isoformat()
|
| 612 |
else:
|
| 613 |
+
valid_df = pd.DataFrame(columns=df.columns)
|
| 614 |
+
|
| 615 |
+
# Enhanced feature-based validation
|
| 616 |
+
feature_quality_summary = {}
|
| 617 |
+
if self.enable_feature_analysis and not valid_df.empty:
|
| 618 |
+
logger.info(f"Performing enhanced feature analysis for {source_name}...")
|
| 619 |
+
try:
|
| 620 |
+
# Extract feature samples for analysis
|
| 621 |
+
feature_samples = self.extract_text_features_sample(valid_df['text'].tolist())
|
| 622 |
+
|
| 623 |
+
# Add feature quality scores
|
| 624 |
+
valid_df['enhanced_quality_score'] = valid_df['text'].apply(self.assess_text_feature_quality)
|
| 625 |
+
|
| 626 |
+
# Create feature quality summary
|
| 627 |
+
feature_quality_summary = {
|
| 628 |
+
'enhanced_analysis_performed': True,
|
| 629 |
+
'feature_samples': feature_samples,
|
| 630 |
+
'enhanced_quality_stats': {
|
| 631 |
+
'mean': float(valid_df['enhanced_quality_score'].mean()),
|
| 632 |
+
'std': float(valid_df['enhanced_quality_score'].std()),
|
| 633 |
+
'min': float(valid_df['enhanced_quality_score'].min()),
|
| 634 |
+
'max': float(valid_df['enhanced_quality_score'].max())
|
| 635 |
+
}
|
| 636 |
+
}
|
| 637 |
+
|
| 638 |
+
# Save feature samples for reference
|
| 639 |
+
if feature_samples:
|
| 640 |
+
sample_file = self.feature_analysis_dir / f"{source_name}_samples.json"
|
| 641 |
+
with open(sample_file, 'w') as f:
|
| 642 |
+
json.dump(feature_samples, f, indent=2)
|
| 643 |
+
logger.info(f"Feature samples saved to {sample_file}")
|
| 644 |
+
|
| 645 |
+
except Exception as e:
|
| 646 |
+
logger.warning(f"Enhanced feature analysis failed for {source_name}: {e}")
|
| 647 |
+
feature_quality_summary = {'enhanced_analysis_performed': False, 'error': str(e)}
|
| 648 |
+
|
| 649 |
+
# Combine validation results
|
| 650 |
+
validation_summary = {
|
| 651 |
+
'source': source_name,
|
| 652 |
+
'original_count': len(df),
|
| 653 |
+
'valid_count': len(valid_df),
|
| 654 |
+
'success_rate': validation_result.success_rate,
|
| 655 |
+
'overall_quality_score': validation_result.overall_quality_score,
|
| 656 |
+
'validation_timestamp': datetime.now().isoformat(),
|
| 657 |
+
'enhanced_features': feature_quality_summary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 658 |
}
|
| 659 |
|
| 660 |
+
return valid_df, validation_summary
|
| 661 |
+
|
| 662 |
+
def prepare_datasets(self) -> Tuple[bool, str]:
|
| 663 |
+
"""Main method to prepare all datasets with enhanced feature analysis"""
|
| 664 |
+
logger.info("Starting enhanced dataset preparation with feature analysis...")
|
| 665 |
+
|
| 666 |
+
try:
|
| 667 |
+
# Load and validate datasets with enhanced features
|
| 668 |
+
kaggle_result = self.load_kaggle_dataset()
|
| 669 |
+
liar_result = self.load_liar_dataset()
|
| 670 |
+
|
| 671 |
+
# Handle None returns gracefully
|
| 672 |
+
if kaggle_result is None:
|
| 673 |
+
logger.warning("Kaggle dataset loading failed")
|
| 674 |
+
kaggle_df, kaggle_validation = pd.DataFrame(), {
|
| 675 |
+
'source': 'kaggle_combined', 'original_count': 0, 'valid_count': 0,
|
| 676 |
+
'success_rate': 0, 'overall_quality_score': 0, 'validation_timestamp': datetime.now().isoformat(),
|
| 677 |
+
'enhanced_features': {'enhanced_analysis_performed': False}
|
| 678 |
+
}
|
| 679 |
+
else:
|
| 680 |
+
kaggle_df, kaggle_validation = kaggle_result
|
| 681 |
+
|
| 682 |
+
if liar_result is None:
|
| 683 |
+
logger.warning("LIAR dataset loading failed")
|
| 684 |
+
liar_df, liar_validation = pd.DataFrame(), {
|
| 685 |
+
'source': 'liar_combined', 'original_count': 0, 'valid_count': 0,
|
| 686 |
+
'success_rate': 0, 'overall_quality_score': 0, 'validation_timestamp': datetime.now().isoformat(),
|
| 687 |
+
'enhanced_features': {'enhanced_analysis_performed': False}
|
| 688 |
+
}
|
| 689 |
+
else:
|
| 690 |
+
liar_df, liar_validation = liar_result
|
| 691 |
+
|
| 692 |
+
# Combine datasets
|
| 693 |
+
datasets_to_combine = [df for df in [kaggle_df, liar_df] if not df.empty]
|
| 694 |
+
|
| 695 |
+
if not datasets_to_combine:
|
| 696 |
+
return False, "No datasets could be loaded and validated"
|
| 697 |
+
|
| 698 |
+
combined_df = pd.concat(datasets_to_combine, ignore_index=True)
|
| 699 |
+
|
| 700 |
+
# Final enhanced validation and feature analysis
|
| 701 |
+
if self.enable_feature_analysis:
|
| 702 |
+
logger.info("Performing final enhanced validation on combined dataset...")
|
| 703 |
+
combined_df = self.validate_dataset(combined_df)
|