Ahmedik95316 commited on
Commit
2736dc6
·
1 Parent(s): a8c8925

Update features/linguistic_analyzer.py

Browse files

Adding Enhanced Feature Engineering Pipeline

Files changed (1) hide show
  1. features/linguistic_analyzer.py +658 -489
features/linguistic_analyzer.py CHANGED
@@ -1,534 +1,703 @@
1
- # features/linguistic_analyzer.py
2
- # Advanced Linguistic Analysis Component for Enhanced Feature Engineering
3
 
4
- import numpy as np
5
  import pandas as pd
6
- import re
 
7
  import logging
8
- from typing import List, Dict, Any, Tuple
9
- from sklearn.base import BaseEstimator, TransformerMixin
10
- from collections import Counter, defaultdict
11
- import warnings
12
- warnings.filterwarnings('ignore')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
 
 
 
 
 
 
 
 
 
14
  logger = logging.getLogger(__name__)
15
 
 
 
 
 
 
16
 
17
- class LinguisticAnalyzer(BaseEstimator, TransformerMixin):
18
- """
19
- Advanced linguistic analysis for fake news detection.
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 transform(self, X):
75
- """Extract linguistic features"""
76
- if not self.is_fitted_:
77
- raise ValueError("LinguisticAnalyzer must be fitted before transform")
78
 
79
- # Convert input to array if needed
80
- if isinstance(X, pd.Series):
81
- X = X.values
82
- elif isinstance(X, list):
83
- X = np.array(X)
84
 
85
- features = []
 
86
 
87
- for text in X:
88
- text_features = self._extract_linguistic_features(str(text))
89
- features.append(text_features)
 
 
 
 
 
 
 
 
 
90
 
91
- return np.array(features)
 
 
 
 
 
 
 
 
 
 
92
 
93
- def fit_transform(self, X, y=None):
94
- """Fit and transform in one step"""
95
- return self.fit(X, y).transform(X)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- def _extract_linguistic_features(self, text):
98
- """Extract comprehensive linguistic features"""
99
- text_lower = text.lower()
100
- words = re.findall(r'\b\w+\b', text_lower)
101
- sentences = re.split(r'[.!?]+', text)
102
- sentences = [s.strip() for s in sentences if s.strip()]
103
-
104
- if len(words) == 0:
105
- return [0.0] * 25 # Return zeros for empty text
106
-
107
- features = []
108
-
109
- # Discourse marker features
110
- discourse_features = self._extract_discourse_features(text_lower, words)
111
- features.extend(discourse_features)
112
-
113
- # Linguistic pattern features
114
- pattern_features = self._extract_pattern_features(text_lower, words)
115
- features.extend(pattern_features)
116
-
117
- # Syntactic complexity features
118
- syntax_features = self._extract_syntax_features(text, sentences, words)
119
- features.extend(syntax_features)
120
-
121
- # Coherence and flow features
122
- coherence_features = self._extract_coherence_features(text, sentences)
123
- features.extend(coherence_features)
124
-
125
- return features
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
- def _extract_discourse_features(self, text_lower, words):
128
- """Extract discourse marker features"""
129
- features = []
130
- total_words = len(words)
131
 
132
- # Count discourse markers by category
133
- for marker_type, markers in self.discourse_markers.items():
134
- marker_count = 0
135
 
136
- # Single word markers
137
- marker_count += sum(1 for word in words if word in markers)
 
 
 
 
138
 
139
- # Multi-word markers
140
- for marker in markers:
141
- if ' ' in marker:
142
- marker_count += text_lower.count(marker)
 
 
 
 
 
 
 
143
 
144
- marker_ratio = marker_count / total_words if total_words > 0 else 0
145
- features.append(marker_ratio)
146
-
147
- return features
148
-
149
- def _extract_pattern_features(self, text_lower, words):
150
- """Extract linguistic pattern features"""
151
- features = []
152
- total_words = len(words)
153
-
154
- # Count linguistic patterns
155
- for pattern_type, pattern_words in self.linguistic_patterns.items():
156
- pattern_count = sum(1 for word in words if word in pattern_words)
157
- pattern_ratio = pattern_count / total_words if total_words > 0 else 0
158
- features.append(pattern_ratio)
159
-
160
- return features
 
 
 
 
 
 
 
 
 
 
 
161
 
162
- def _extract_syntax_features(self, text, sentences, words):
163
- """Extract syntactic complexity features"""
164
- features = []
 
165
 
166
- # Average sentence length
167
- if sentences:
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
- # Paragraph structure (approximate)
214
- paragraphs = text.split('\n\n')
215
- paragraphs = [p.strip() for p in paragraphs if p.strip()]
216
 
217
- # Average paragraph length
218
- if paragraphs:
219
- avg_paragraph_length = sum(len(p.split()) for p in paragraphs) / len(paragraphs)
220
- else:
221
- avg_paragraph_length = 0
222
- features.append(avg_paragraph_length)
223
 
224
- # Topic coherence (simplified using word repetition)
225
- coherence_score = self._calculate_lexical_coherence(sentences)
226
- features.append(coherence_score)
227
 
228
- # Transition density
229
- transition_density = self._calculate_transition_density(text)
230
- features.append(transition_density)
231
 
232
- return features
233
 
234
- def _calculate_lexical_coherence(self, sentences):
235
- """Calculate lexical coherence between sentences"""
236
- if len(sentences) < 2:
237
- return 0
238
-
239
- coherence_scores = []
240
-
241
- for i in range(len(sentences) - 1):
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
- # Remove very common words
246
- common_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by'}
247
- words1 = words1 - common_words
248
- words2 = words2 - common_words
 
 
 
249
 
250
- if words1 and words2:
251
- overlap = len(words1.intersection(words2))
252
- union = len(words1.union(words2))
253
- coherence = overlap / union if union > 0 else 0
254
- coherence_scores.append(coherence)
255
-
256
- return sum(coherence_scores) / len(coherence_scores) if coherence_scores else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
- def _calculate_transition_density(self, text):
259
- """Calculate density of transition words"""
260
- transition_words = {
261
- 'however', 'therefore', 'furthermore', 'moreover', 'consequently',
262
- 'nevertheless', 'nonetheless', 'meanwhile', 'additionally', 'similarly',
263
- 'likewise', 'in contrast', 'on the other hand', 'for example', 'for instance'
264
- }
265
-
266
- text_lower = text.lower()
267
- transition_count = 0
268
-
269
- for transition in transition_words:
270
- if ' ' in transition:
271
- transition_count += text_lower.count(transition)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  else:
273
- transition_count += len(re.findall(rf'\b{transition}\b', text_lower))
274
-
275
- return transition_count / len(text) * 1000 if text else 0
 
 
 
276
 
277
- def get_feature_names(self):
278
- """Get names of extracted features"""
279
- feature_names = []
280
-
281
- # Discourse marker features
282
- for marker_type in self.discourse_markers.keys():
283
- feature_names.append(f'linguistic_{marker_type}_markers_ratio')
284
-
285
- # Linguistic pattern features
286
- for pattern_type in self.linguistic_patterns.keys():
287
- feature_names.append(f'linguistic_{pattern_type}_ratio')
288
-
289
- # Syntax features
290
- syntax_features = [
291
- 'linguistic_avg_sentence_length',
292
- 'linguistic_sentence_length_variance',
293
- 'linguistic_subordinating_density',
294
- 'linguistic_relative_pronouns_density',
295
- 'linguistic_passive_voice_density'
296
- ]
297
- feature_names.extend(syntax_features)
298
-
299
- # Coherence features
300
- coherence_features = [
301
- 'linguistic_avg_paragraph_length',
302
- 'linguistic_lexical_coherence',
303
- 'linguistic_transition_density'
304
- ]
305
- feature_names.extend(coherence_features)
306
-
307
- return feature_names
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
 
309
- def analyze_text_linguistics(self, text):
310
- """Detailed linguistic analysis of a single text"""
311
- if not self.is_fitted_:
312
- raise ValueError("LinguisticAnalyzer must be fitted before analysis")
313
-
314
- text_lower = text.lower()
315
- words = re.findall(r'\b\w+\b', text_lower)
316
- sentences = re.split(r'[.!?]+', text)
317
- sentences = [s.strip() for s in sentences if s.strip()]
318
-
319
- analysis = {
320
- 'basic_stats': {
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
- 'discourse_markers': {},
327
- 'linguistic_patterns': {},
328
- 'syntactic_complexity': {},
329
- 'coherence_analysis': {}
 
 
 
 
 
 
 
 
 
 
330
  }
331
 
332
- # Analyze discourse markers
333
- for marker_type, markers in self.discourse_markers.items():
334
- found_markers = []
335
- for word in words:
336
- if word in markers:
337
- found_markers.append(word)
338
-
339
- # Check multi-word markers
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
- # Analyze linguistic patterns
351
- for pattern_type, pattern_words in self.linguistic_patterns.items():
352
- found_patterns = [word for word in words if word in pattern_words]
353
- analysis['linguistic_patterns'][pattern_type] = {
354
- 'count': len(found_patterns),
355
- 'ratio': len(found_patterns) / len(words) if words else 0,
356
- 'patterns_found': list(set(found_patterns))[:5]
357
  }
358
 
359
- # Analyze syntactic complexity
360
- complex_indicators = self._count_complex_sentence_indicators(text)
361
- analysis['syntactic_complexity'] = {
362
- 'subordinating_conjunctions_density': complex_indicators[0],
363
- 'relative_pronouns_density': complex_indicators[1],
364
- 'passive_voice_density': complex_indicators[2],
365
- 'sentence_length_variance': self._extract_syntax_features(text, sentences, words)[1],
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 analysis
386
 
387
- def _assess_sophistication(self, analysis):
388
- """Assess overall linguistic sophistication"""
389
- sophistication_score = 0
390
-
391
- # Discourse marker variety
392
- marker_variety = len([mt for mt, data in analysis['discourse_markers'].items() if data['count'] > 0])
393
- sophistication_score += marker_variety / len(self.discourse_markers) * 0.3
394
-
395
- # Complex syntax usage
396
- syntax_score = analysis['syntactic_complexity']['complexity_score']
397
- sophistication_score += min(syntax_score, 0.02) / 0.02 * 0.3 # Cap and normalize
398
-
399
- # Coherence quality
400
- coherence_score = analysis['coherence_analysis']['overall_coherence_score']
401
- sophistication_score += coherence_score * 0.4
402
-
403
- if sophistication_score > 0.7:
404
- return 'high'
405
- elif sophistication_score > 0.4:
406
- return 'medium'
407
- else:
408
- return 'low'
 
 
 
 
409
 
410
- def _assess_discourse_quality(self, analysis):
411
- """Assess discourse quality and organization"""
412
- quality_indicators = []
413
-
414
- # Balanced use of discourse markers
415
- marker_counts = [data['count'] for data in analysis['discourse_markers'].values()]
416
- if marker_counts:
417
- marker_balance = 1 - (max(marker_counts) - min(marker_counts)) / (sum(marker_counts) + 1)
418
- quality_indicators.append(marker_balance)
419
-
420
- # Coherence score
421
- quality_indicators.append(analysis['coherence_analysis']['overall_coherence_score'])
422
-
423
- # Transition usage
424
- transition_score = min(1.0, analysis['coherence_analysis']['transition_density'] / 5)
425
- quality_indicators.append(transition_score)
426
-
427
- avg_quality = sum(quality_indicators) / len(quality_indicators) if quality_indicators else 0
428
-
429
- if avg_quality > 0.7:
430
- return 'excellent'
431
- elif avg_quality > 0.5:
432
- return 'good'
433
- elif avg_quality > 0.3:
434
- return 'fair'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435
  else:
436
- return 'poor'
437
-
438
- def _detect_linguistic_anomalies(self, analysis):
439
- """Detect potential linguistic anomalies that might indicate manipulation"""
440
- anomalies = []
441
-
442
- # Excessive use of boosters/intensifiers
443
- booster_ratio = analysis['linguistic_patterns']['boosters']['ratio']
444
- if booster_ratio > 0.05: # More than 5% boosters
445
- anomalies.append({
446
- 'type': 'excessive_boosters',
447
- 'severity': 'medium',
448
- 'description': f'High use of intensifying language ({booster_ratio:.1%})',
449
- 'examples': analysis['linguistic_patterns']['boosters']['patterns_found']
450
- })
451
-
452
- # Unusual negation patterns
453
- negation_ratio = analysis['linguistic_patterns']['negation']['ratio']
454
- if negation_ratio > 0.08: # More than 8% negation
455
- anomalies.append({
456
- 'type': 'excessive_negation',
457
- 'severity': 'low',
458
- 'description': f'High use of negative language ({negation_ratio:.1%})',
459
- 'examples': analysis['linguistic_patterns']['negation']['patterns_found']
460
- })
461
-
462
- # Low coherence with high complexity (potential obfuscation)
463
- coherence = analysis['coherence_analysis']['overall_coherence_score']
464
- complexity = analysis['syntactic_complexity']['complexity_score']
465
- if complexity > 0.01 and coherence < 0.3:
466
- anomalies.append({
467
- 'type': 'complexity_without_coherence',
468
- 'severity': 'high',
469
- 'description': 'Complex language structure with poor coherence (potential obfuscation)',
470
- 'coherence_score': coherence,
471
- 'complexity_score': complexity
472
- })
473
-
474
- # Unusual question density
475
- question_ratio = analysis['linguistic_patterns']['questioning']['ratio']
476
- if question_ratio > 0.06: # More than 6% question words
477
- anomalies.append({
478
- 'type': 'excessive_questioning',
479
- 'severity': 'medium',
480
- 'description': f'High density of questioning language ({question_ratio:.1%})',
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
- # Check for manipulation patterns
497
- manipulation_score = 0
498
-
499
- # Excessive emphasis/boosters
500
- if analysis['linguistic_patterns']['boosters']['ratio'] > 0.05:
501
- manipulation_score += 0.3
502
- indicators['specific_indicators'].append('excessive_emphasis')
503
-
504
- # Lack of hedging (overconfidence)
505
- if analysis['linguistic_patterns']['hedge_words']['ratio'] < 0.01:
506
- manipulation_score += 0.2
507
- indicators['specific_indicators'].append('overconfident_language')
508
-
509
- # Poor coherence (confusion tactics)
510
- if analysis['coherence_analysis']['overall_coherence_score'] < 0.3:
511
- manipulation_score += 0.4
512
- indicators['specific_indicators'].append('poor_coherence')
513
-
514
- # Excessive questioning (doubt seeding)
515
- if analysis['linguistic_patterns']['questioning']['ratio'] > 0.06:
516
- manipulation_score += 0.3
517
- indicators['specific_indicators'].append('excessive_questioning')
518
-
519
- # High personal pronoun usage (false intimacy)
520
- if analysis['linguistic_patterns']['personal_pronouns']['ratio'] > 0.15:
521
- manipulation_score += 0.2
522
- indicators['specific_indicators'].append('false_intimacy')
523
-
524
- indicators['linguistic_manipulation_score'] = min(1.0, manipulation_score)
525
-
526
- # Overall risk assessment
527
- if manipulation_score > 0.7:
528
- indicators['overall_risk'] = 'high'
529
- elif manipulation_score > 0.4:
530
- indicators['overall_risk'] = 'medium'
531
- else:
532
- indicators['overall_risk'] = 'low'
533
-
534
- return indicators
 
 
 
 
 
 
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)