Repository navigation
Expand file tree
/
Copy pathpreprocess.py
More file actions
898 lines (727 loc) · 35.9 KB
/
Copy pathpreprocess.py
File metadata and controls
898 lines (727 loc) · 35.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
128
129
130
131
132
133
134
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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
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
482
483
484
485
486
487
488
489
490
491
492
493
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
#!/usr/bin/env python3
"""
UNIVERSAL DATA PREPROCESSING SYSTEM
====================================
A generic, reusable Python program to automatically inspect, clean, transform,
and validate any tabular CSV dataset for Machine Learning workflows.
Author: Antigravity Data Science & ML Engineering Team
"""
import os
import sys
import re
import argparse
import warnings
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg') # Non-interactive backend for server environments
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
warnings.filterwarnings('ignore')
# ==========================================
# 22. CONFIGURATION DEFAULTS
# ==========================================
DATA_PATH = "dataset.csv"
OUTPUT_DIR = "processed_data"
HANDLE_OUTLIERS = False
EXTRACT_DATE_FEATURES = True
EXCLUDE_IDENTIFIERS = True
EXCLUDE_FREE_TEXT = True
SCALE_NUMERICAL = True
MISSING_REPRESENTATIONS = [
'nan', 'nan', 'none', 'null', 'n/a', 'na', '?', '-', '', ' ', ' ', 'none', 'null', '<na>'
]
# ==========================================
# 23. COMMAND-LINE SUPPORT
# ==========================================
def parse_arguments():
parser = argparse.ArgumentParser(
description="Universal Data Preprocessing System — works with CSV and Excel files."
)
parser.add_argument("--input", "-i", type=str, default=DATA_PATH, help="Path to input CSV or Excel file")
parser.add_argument("--output", "-o", type=str, default=OUTPUT_DIR, help="Output directory for processed files")
parser.add_argument("--sheet", "-s", type=str, default="0", help="Excel sheet name or 0-based index (default: first sheet). Ignored for CSV files.")
parser.add_argument("--handle-outliers", action="store_true", default=HANDLE_OUTLIERS, help="Cap numerical outliers using IQR method")
parser.add_argument("--no-scaling", action="store_false", dest="scale_numerical", default=SCALE_NUMERICAL, help="Disable StandardScaler for numerical features")
parser.add_argument("--no-date-features", action="store_false", dest="extract_dates", default=EXTRACT_DATE_FEATURES, help="Disable date feature extraction")
parser.add_argument("--include-identifiers",action="store_false", dest="exclude_identifiers",default=EXCLUDE_IDENTIFIERS, help="Include identifier columns in ML-ready matrix")
parser.add_argument("--include-free-text", action="store_false", dest="exclude_free_text", default=EXCLUDE_FREE_TEXT, help="Include free-form text in ML-ready matrix")
return parser.parse_args()
# ==========================================
# 1. LOAD DATASET
# ==========================================
def load_dataset(file_path, sheet_name=0):
"""
Load a CSV or Excel dataset safely.
- CSV: Tries multiple encodings automatically.
- Excel (.xlsx / .xls): Reads the first sheet by default.
Pass sheet_name='Sheet2' (or index) to choose another.
"""
if not os.path.exists(file_path):
raise FileNotFoundError(f"Input file not found at path: {file_path}")
ext = os.path.splitext(file_path)[1].lower()
# ---- Excel branch ----
if ext in ('.xlsx', '.xls', '.xlsm', '.xlsb'):
try:
# Show available sheets to the user
xl = pd.ExcelFile(file_path)
if len(xl.sheet_names) > 1:
print(f"[i] Excel file contains {len(xl.sheet_names)} sheets: {xl.sheet_names}")
print(f"[i] Loading sheet: '{xl.sheet_names[sheet_name] if isinstance(sheet_name, int) else sheet_name}'")
print(f"[i] To load a different sheet use: --sheet 'SheetName'")
df = pd.read_excel(file_path, sheet_name=sheet_name, engine=None)
print(f"[+] Loaded Excel file '{file_path}' successfully.")
except ImportError as e:
raise ImportError(
f"Missing Excel engine. Install it with:\n"
f" pip install openpyxl (for .xlsx)\n"
f" pip install xlrd (for legacy .xls)\n"
f"Original error: {e}"
)
except Exception as e:
raise ValueError(f"Could not read Excel file '{file_path}': {e}")
# ---- CSV branch ----
elif ext in ('.csv', '.tsv', '.txt', ''):
encodings = ['utf-8', 'latin1', 'cp1252', 'iso-8859-1']
sep = '\t' if ext == '.tsv' else ','
df = None
for enc in encodings:
try:
df = pd.read_csv(file_path, encoding=enc, sep=sep)
print(f"[+] Loaded '{file_path}' successfully with encoding: {enc}")
break
except (UnicodeDecodeError, pd.errors.ParserError):
continue
if df is None:
raise ValueError(f"Unable to parse file '{file_path}' with supported encodings.")
else:
raise ValueError(
f"Unsupported file extension '{ext}'.\n"
f"Supported formats: .csv, .tsv, .xlsx, .xls, .xlsm"
)
if df.empty:
raise ValueError(f"The loaded dataset '{file_path}' is completely empty.")
return df
# ==========================================
# 4. CLEAN COLUMN NAMES
# ==========================================
def clean_column_names(df):
"""Standardize column names to lowercase_with_underscores and handle duplicates."""
cleaned_cols = []
seen = {}
for col in df.columns:
# Strip whitespace, convert to lowercase
name = str(col).strip().lower()
# Remove special characters except alphanumeric and spaces/underscores
name = re.sub(r'[^\w\s]', '_', name)
# Replace spaces/hyphens with single underscore
name = re.sub(r'[\s\-]+', '_', name)
# Collapse multiple underscores
name = re.sub(r'_+', '_', name).strip('_')
if not name:
name = "unnamed_column"
# Handle duplicates
if name in seen:
seen[name] += 1
name = f"{name}_{seen[name]}"
else:
seen[name] = 0
cleaned_cols.append(name)
df.columns = cleaned_cols
return df
# ==========================================
# 6. STANDARDIZE MISSING VALUES
# ==========================================
def standardize_missing_values(df):
"""Convert custom missing representations (N/A, ?, NULL, empty strings) into np.nan."""
df_clean = df.copy()
for col in df_clean.columns:
if df_clean[col].dtype == object or isinstance(df_clean[col].dtype, pd.StringDtype):
# Strip string values first
s = df_clean[col].astype(str).str.strip()
# Check against missing representations (case-insensitive)
is_missing = s.str.lower().isin(MISSING_REPRESENTATIONS) | (s == '')
df_clean.loc[is_missing, col] = np.nan
return df_clean
# ==========================================
# 3. AUTOMATIC COLUMN TYPE DETECTION
# ==========================================
def detect_column_types(df):
"""
Classify columns into: numerical, categorical, datetime, boolean, text, identifier.
Uses value-based inspection rather than relying solely on pandas dtypes.
"""
col_types = {}
for col in df.columns:
series = df[col].dropna()
if len(series) == 0:
col_types[col] = "categorical"
continue
col_name_lower = str(col).lower()
unique_vals = series.unique()
n_unique = len(unique_vals)
uniqueness_ratio = n_unique / max(len(series), 1)
# First, test if strings can be converted to numerical ($75,000, 50%, "29", etc.)
is_numeric_convertible = False
parsed_numeric = None
if pd.api.types.is_numeric_dtype(series):
is_numeric_convertible = True
parsed_numeric = series
elif series.dtype == object or isinstance(series.dtype, pd.StringDtype):
clean_str = series.astype(str).str.replace(r'[\$,%]', '', regex=True).str.strip()
num_parsed = pd.to_numeric(clean_str, errors='coerce')
if num_parsed.notna().sum() / len(series) >= 0.8:
is_numeric_convertible = True
parsed_numeric = num_parsed
# 1. Identifier Check (Name contains id/email/uuid/phone/name OR string patterns like email/UUID)
id_keywords = ['_id', 'id_', 'uuid', 'email', 'phone', 'ssn', 'account', 'customer_code', 'emp_', 'name', 'code']
is_id_name = any(kw in col_name_lower for kw in id_keywords) or col_name_lower == 'id'
# Check string patterns (e.g. email or uuid or emp code format like EMP001)
str_sample = series.astype(str).iloc[:min(20, len(series))]
is_email = str_sample.str.contains(r'^[\w\.-]+@[\w\.-]+\.\w+$', regex=True).mean() > 0.5
is_code = str_sample.str.contains(r'^[A-Za-z]+\d+$', regex=True).mean() > 0.5
if is_id_name or is_email or is_code:
if n_unique > 2:
col_types[col] = "identifier"
continue
# 2. Boolean Check
str_vals = set(series.astype(str).str.strip().str.lower().unique())
bool_tokens = {'true', 'false', 'yes', 'no', 'y', 'n', '1', '0', '1.0', '0.0', 't', 'f'}
if str_vals.issubset(bool_tokens):
col_types[col] = "boolean"
continue
# 3. Datetime Check
if pd.api.types.is_datetime64_any_dtype(series):
col_types[col] = "datetime"
continue
elif series.dtype == object or isinstance(series.dtype, pd.StringDtype):
if not is_numeric_convertible:
sample = series.iloc[:min(100, len(series))]
try:
parsed_dt = pd.to_datetime(sample, errors='coerce', format='mixed')
if parsed_dt.notna().sum() / len(sample) >= 0.7:
col_types[col] = "datetime"
continue
except Exception:
pass
# 4. Numerical Check
if is_numeric_convertible:
# Check if integer sequence identifier (e.g. 1001, 1002, 1003...) with ID name
if is_id_name and uniqueness_ratio > 0.9:
col_types[col] = "identifier"
else:
col_types[col] = "numerical"
continue
# 5. Free-Form Text vs Categorical
if series.dtype == object or isinstance(series.dtype, pd.StringDtype):
avg_word_count = series.astype(str).apply(lambda x: len(x.split())).mean()
avg_char_len = series.astype(str).apply(len).mean()
if avg_word_count > 3 or avg_char_len > 40:
col_types[col] = "text"
else:
col_types[col] = "categorical"
continue
col_types[col] = "categorical"
return col_types
# ==========================================
# 2. DATASET PROFILING
# ==========================================
def profile_dataset(df, col_types):
"""Generate profiling DataFrame with statistics for each column."""
profile_data = []
for col in df.columns:
dtype = df[col].dtype
missing_cnt = df[col].isna().sum()
missing_pct = (missing_cnt / len(df)) * 100
n_unique = df[col].nunique(dropna=True)
detected = col_types.get(col, "unknown")
profile_data.append({
"Column": col,
"Dtype": str(dtype),
"Missing": missing_cnt,
"Missing %": round(missing_pct, 2),
"Unique": n_unique,
"Detected Type": detected
})
profile_df = pd.DataFrame(profile_data)
return profile_df
# ==========================================
# 5. DUPLICATE HANDLING
# ==========================================
def handle_duplicates(df):
"""Detect and remove exact duplicate rows."""
dup_before = df.duplicated().sum()
df_cleaned = df.drop_duplicates().reset_index(drop=drop) if False else df.drop_duplicates()
dup_after = df_cleaned.duplicated().sum()
dup_removed = dup_before - dup_after
print("\n--- DUPLICATE HANDLING ---")
print(f"Duplicates before: {dup_before}")
print(f"Duplicates removed: {dup_removed}")
print(f"Rows after: {len(df_cleaned)}")
return df_cleaned, dup_before, dup_removed
# ==========================================
# 7. TEXT CLEANING
# ==========================================
def clean_text_columns(df, col_types):
"""Strip whitespace, normalize spaces, and unify category casing."""
df_clean = df.copy()
for col, ctype in col_types.items():
if ctype in ['categorical', 'text', 'identifier'] and col in df_clean.columns:
if df_clean[col].dtype == object or isinstance(df_clean[col].dtype, pd.StringDtype):
# Strip leading/trailing whitespace & collapse multiple spaces
s = df_clean[col].astype(str)
s = s.str.strip().str.replace(r'\s+', ' ', regex=True)
# Restore NaNs
s = s.replace(['nan', 'NaN', 'None'], np.nan)
if ctype == 'categorical':
# Normalize category casing when unambiguous (e.g. Male, male -> male)
non_nulls = s.dropna()
lower_map = {}
for val in non_nulls.unique():
lval = val.lower()
if lval not in lower_map:
lower_map[lval] = val
# Map to the most frequent casing or lowercase if standardized
# Here we title-case or standardize clean strings
s_clean = s.apply(lambda x: x.title() if isinstance(x, str) and not x.isupper() else x)
df_clean[col] = s_clean
else:
df_clean[col] = s
return df_clean
# ==========================================
# 8. NUMERICAL DATA CLEANING
# ==========================================
def process_numerical_columns(df, col_types):
"""Convert numeric string representations ($1,000, 50%) to floats/ints and clean values."""
df_clean = df.copy()
for col, ctype in col_types.items():
if ctype == 'numerical' and col in df_clean.columns:
s = df_clean[col]
if s.dtype == object or isinstance(s.dtype, pd.StringDtype):
# Remove $, %, commas
s_clean = s.astype(str).str.replace(r'[\$,%]', '', regex=True).str.strip()
df_clean[col] = pd.to_numeric(s_clean, errors='coerce')
else:
df_clean[col] = pd.to_numeric(df_clean[col], errors='coerce')
# Replace Inf/-Inf with NaN
df_clean[col] = df_clean[col].replace([np.inf, -np.inf], np.nan)
return df_clean
# ==========================================
# 9. OUTLIER DETECTION (IQR METHOD)
# ==========================================
def detect_outliers(df, col_types, handle_outliers=False):
"""Detect numerical outliers using IQR method. Optionally cap extreme values."""
df_clean = df.copy()
outlier_report = []
num_cols = [col for col, ctype in col_types.items() if ctype == 'numerical' and col in df.columns]
for col in num_cols:
series = df_clean[col].dropna()
if len(series) == 0:
continue
q1 = series.quantile(0.25)
q3 = series.quantile(0.75)
iqr = q3 - q1
lower_bound = q1 - 1.5 * iqr
upper_bound = q3 + 1.5 * iqr
outliers = series[(series < lower_bound) | (series > upper_bound)]
outlier_cnt = len(outliers)
outlier_report.append({
"Column": col,
"Q1": round(q1, 2),
"Q3": round(q3, 2),
"IQR": round(iqr, 2),
"Lower Bound": round(lower_bound, 2),
"Upper Bound": round(upper_bound, 2),
"Outlier Count": outlier_cnt
})
if handle_outliers and outlier_cnt > 0:
df_clean[col] = df_clean[col].clip(lower=lower_bound, upper=upper_bound)
outlier_df = pd.DataFrame(outlier_report)
return df_clean, outlier_df
# ==========================================
# 10. DATETIME PROCESSING
# ==========================================
def process_datetime_columns(df, col_types, extract_features=True):
"""Convert dates to pandas datetime and extract year, month, day, day_of_week, quarter."""
df_clean = df.copy()
extracted_cols = []
date_cols = [col for col, ctype in col_types.items() if ctype == 'datetime' and col in df.columns]
for col in date_cols:
df_clean[col] = pd.to_datetime(df_clean[col], errors='coerce', format='mixed')
if extract_features:
df_clean[f"{col}_year"] = df_clean[col].dt.year
df_clean[f"{col}_month"] = df_clean[col].dt.month
df_clean[f"{col}_day"] = df_clean[col].dt.day
df_clean[f"{col}_day_of_week"] = df_clean[col].dt.dayofweek
df_clean[f"{col}_quarter"] = df_clean[col].dt.quarter
extracted_cols.extend([
f"{col}_year", f"{col}_month", f"{col}_day",
f"{col}_day_of_week", f"{col}_quarter"
])
return df_clean, extracted_cols
# ==========================================
# 11. BOOLEAN PROCESSING
# ==========================================
def process_boolean_columns(df, col_types):
"""Normalize Boolean-like values to 0 / 1."""
df_clean = df.copy()
bool_cols = [col for col, ctype in col_types.items() if ctype == 'boolean' and col in df.columns]
true_set = {'true', 'yes', 'y', '1', '1.0', 't'}
for col in bool_cols:
def map_bool(val):
if pd.isna(val):
return np.nan
sval = str(val).strip().lower()
if sval in true_set:
return 1.0
return 0.0
df_clean[col] = df_clean[col].apply(map_bool)
return df_clean
# ==========================================
# 14. IDENTIFIER DETECTION REPORT
# ==========================================
def detect_identifiers(df, col_types):
"""Generate diagnostic report for identified identifier columns."""
id_report = []
for col, ctype in col_types.items():
if col in df.columns:
n_unique = df[col].nunique(dropna=True)
ratio = n_unique / max(len(df), 1)
if ctype == 'identifier':
id_report.append({
"Column": col,
"Identifier Probability": 0.95 if ratio > 0.8 else 0.85,
"Reason": f"High uniqueness ratio ({ratio:.2f}) / ID name pattern",
"Action": "Keep in Cleaned CSV; Exclude from ML Matrix by default"
})
elif ctype == 'text':
id_report.append({
"Column": col,
"Identifier Probability": 0.10,
"Reason": "Free-form text column",
"Action": "Keep in Cleaned CSV; Exclude from ML Matrix by default"
})
return pd.DataFrame(id_report)
# ==========================================
# 16. BUILD PREPROCESSING PIPELINE
# ==========================================
def build_preprocessing_pipeline(num_cols, cat_cols, scale_numerical=True):
"""Build Scikit-Learn ColumnTransformer pipeline for ML data preparation."""
transformers = []
if num_cols:
num_steps = [('imputer', SimpleImputer(strategy='median'))]
if scale_numerical:
num_steps.append(('scaler', StandardScaler()))
num_pipeline = Pipeline(num_steps)
transformers.append(('num', num_pipeline, num_cols))
if cat_cols:
cat_pipeline = Pipeline([
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
])
transformers.append(('cat', cat_pipeline, cat_cols))
preprocessor = ColumnTransformer(transformers=transformers, remainder='drop')
return preprocessor
# ==========================================
# 17. CREATE CLEANED & ML-READY DATASETS
# ==========================================
def create_cleaned_dataset(df, col_types, extracted_date_cols):
"""Create human-readable cleaned dataset preserving useful columns."""
df_cleaned = df.copy()
# Impute missing values for cleaned dataset in a human-readable way
for col in df_cleaned.columns:
ctype = col_types.get(col, 'categorical')
if df_cleaned[col].isna().sum() > 0:
if ctype == 'numerical' or col in extracted_date_cols:
median_val = df_cleaned[col].median()
df_cleaned[col] = df_cleaned[col].fillna(median_val)
elif ctype in ['categorical', 'boolean']:
mode_vals = df_cleaned[col].mode()
fill_val = mode_vals[0] if len(mode_vals) > 0 else 'Unknown'
df_cleaned[col] = df_cleaned[col].fillna(fill_val)
elif ctype == 'datetime':
df_cleaned[col] = df_cleaned[col].ffill().bfill()
elif ctype in ['identifier', 'text']:
df_cleaned[col] = df_cleaned[col].fillna('Missing')
return df_cleaned
def create_ml_ready_dataset(df_processed, col_types, extracted_date_cols,
exclude_ids=True, exclude_text=True, scale_num=True):
"""Create numerical machine-learning ready matrix using Scikit-Learn pipeline."""
# Determine feature lists
num_cols = [col for col, ctype in col_types.items() if ctype in ['numerical', 'boolean'] and col in df_processed.columns]
num_cols.extend([col for col in extracted_date_cols if col in df_processed.columns])
cat_cols = [col for col, ctype in col_types.items() if ctype == 'categorical' and col in df_processed.columns]
# Filter out excluded types if requested
if exclude_ids:
num_cols = [c for c in num_cols if col_types.get(c) != 'identifier']
cat_cols = [c for c in cat_cols if col_types.get(c) != 'identifier']
if exclude_text:
num_cols = [c for c in num_cols if col_types.get(c) != 'text']
cat_cols = [c for c in cat_cols if col_types.get(c) != 'text']
pipeline = build_preprocessing_pipeline(num_cols, cat_cols, scale_numerical=scale_num)
feature_data = df_processed[num_cols + cat_cols].copy()
ml_array = pipeline.fit_transform(feature_data)
# Reconstruct feature column names
feature_names = list(num_cols)
if cat_cols and hasattr(pipeline.named_transformers_['cat'].named_steps['onehot'], 'get_feature_names_out'):
onehot_cols = pipeline.named_transformers_['cat'].named_steps['onehot'].get_feature_names_out(cat_cols)
feature_names.extend(onehot_cols)
ml_df = pd.DataFrame(ml_array, columns=feature_names)
return ml_df, pipeline, num_cols, cat_cols
# ==========================================
# 18. PREPROCESSING REPORT & SUMMARY
# ==========================================
def generate_reports(df_orig, df_clean, df_ml, col_types, extracted_date_cols, outlier_df, id_df, dup_info):
"""Generate preprocessing_report.csv and preprocessing_summary.txt."""
report_rows = []
ml_cols = set(df_ml.columns)
for col in df_orig.columns:
orig_type = str(df_orig[col].dtype)
detected_type = col_types.get(col, 'unknown')
missing_before = df_orig[col].isna().sum()
missing_after = df_clean[col].isna().sum() if col in df_clean.columns else 0
# Check transformation notes
trans = []
if detected_type == 'numerical':
trans.append('Median Imputed; StandardScaled' if 'scaler' in sys.argv else 'Median Imputed')
elif detected_type == 'categorical':
trans.append('Mode Imputed; OneHotEncoded')
elif detected_type == 'boolean':
trans.append('Normalized to 0/1; Imputed')
elif detected_type == 'datetime':
trans.append('Extracted Date Features (Year, Month, Day, etc.)')
elif detected_type == 'identifier':
trans.append('Retained in Cleaned CSV; Excluded from ML Matrix')
elif detected_type == 'text':
trans.append('Whitespace Trimmed; Excluded from standard ML Matrix')
inc_ml = "Yes" if any(col in mc for mc in ml_cols) or detected_type in ['numerical', 'categorical', 'boolean'] else "No"
report_rows.append({
"Column": col,
"Original Type": orig_type,
"Detected Type": detected_type,
"Missing Before": int(missing_before),
"Missing After": int(missing_after),
"Transformation": "; ".join(trans),
"Included in ML": inc_ml
})
report_df = pd.DataFrame(report_rows)
# Build detailed text summary
dup_before, dup_removed, rows_after = dup_info
summary_text = []
summary_text.append("==========================================================")
summary_text.append("UNIVERSAL DATA PREPROCESSING AUTOMATED SUMMARY REPORT")
summary_text.append("==========================================================")
summary_text.append(f"Original Rows: {len(df_orig)}")
summary_text.append(f"Original Columns: {len(df_orig.columns)}")
summary_text.append(f"Cleaned Rows: {len(df_clean)}")
summary_text.append(f"ML Feature Matrix Shape: {df_ml.shape}")
summary_text.append("----------------------------------------------------------")
summary_text.append(f"Duplicates Before: {dup_before}")
summary_text.append(f"Duplicates Removed: {dup_removed}")
summary_text.append(f"Rows Retained: {rows_after}")
summary_text.append("----------------------------------------------------------")
summary_text.append("COLUMN TYPES DETECTED:")
for ctype, count in pd.Series(col_types).value_counts().items():
summary_text.append(f" - {ctype.capitalize()}: {count}")
summary_text.append("----------------------------------------------------------")
summary_text.append("OUTLIER DETECTION (IQR METHOD):")
if not outlier_df.empty:
summary_text.append(outlier_df.to_string(index=False))
else:
summary_text.append(" No numerical columns for outlier analysis.")
summary_text.append("----------------------------------------------------------")
summary_text.append("IDENTIFIER DETECTION REPORT:")
if not id_df.empty:
summary_text.append(id_df.to_string(index=False))
else:
summary_text.append(" No identifier or text columns detected.")
summary_text.append("==========================================================")
return report_df, "\n".join(summary_text)
# ==========================================
# 19. VALIDATION ENGINE
# ==========================================
def validate_outputs(df_orig, df_clean, df_ml, dup_info):
"""Comprehensive post-processing validation assertions and report."""
dup_before, dup_removed, rows_after = dup_info
missing_before = df_orig.isna().sum().sum()
missing_after_clean = df_clean.isna().sum().sum()
missing_after_ml = df_ml.isna().sum().sum()
inf_count = np.isinf(df_ml.values).sum() if not df_ml.empty else 0
invalid_count = df_ml.isna().sum().sum()
dup_after = df_clean.duplicated().sum()
status = "PASS" if (missing_after_ml == 0 and inf_count == 0 and dup_after == 0) else "FAIL"
print("\n========== VALIDATION ==========")
print(f"Rows before: {len(df_orig)}")
print(f"Rows after: {len(df_clean)}")
print("")
print(f"Duplicates before: {dup_before}")
print(f"Duplicates after: {dup_after}")
print("")
print(f"Missing values before: {missing_before}")
print(f"Missing values (Clean): {missing_after_clean}")
print(f"Missing values (ML): {missing_after_ml}")
print("")
print(f"Infinite values: {inf_count}")
print(f"Invalid values: {invalid_count}")
print("")
print(f"Validation status: {status}")
print("================================\n")
return status
# ==========================================
# 20. VISUALIZATIONS
# ==========================================
def generate_visualizations(df_orig, df_clean, col_types, output_dir):
"""Generate diagnostic plots and save to reports/figures/."""
figures_dir = os.path.join(output_dir, "reports", "figures")
os.makedirs(figures_dir, exist_ok=True)
# 1. Missing Values Before vs After
try:
plt.figure(figsize=(10, 5))
missing_before = df_orig.isna().sum()
missing_after = df_clean.isna().sum()
comp_df = pd.DataFrame({"Before": missing_before, "After": missing_after})
comp_df = comp_df[comp_df["Before"] > 0]
if not comp_df.empty:
comp_df.plot(kind="bar", color=["#e74c3c", "#2ecc71"], figsize=(10, 5))
plt.title("Missing Values Before vs After Preprocessing")
plt.ylabel("Missing Count")
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.savefig(os.path.join(figures_dir, "missing_values.png"), dpi=300)
plt.close()
except Exception as e:
print(f"[-] Visualization note (missing values): {e}")
# 2. Numerical Distributions
try:
num_cols = [c for c, t in col_types.items() if t == 'numerical' and c in df_clean.columns]
if num_cols:
n_num = len(num_cols)
fig, axes = plt.subplots(nrows=(n_num + 1) // 2, ncols=min(2, n_num), figsize=(12, 4 * ((n_num + 1) // 2)))
axes = np.array(axes).reshape(-1)
for idx, col in enumerate(num_cols):
sns.histplot(df_clean[col], kde=True, ax=axes[idx], color="#3498db")
axes[idx].set_title(f"Distribution of {col}")
for j in range(idx + 1, len(axes)):
fig.delaxes(axes[j])
plt.tight_layout()
plt.savefig(os.path.join(figures_dir, "numerical_distributions.png"), dpi=300)
plt.close()
except Exception as e:
print(f"[-] Visualization note (distributions): {e}")
# 3. Boxplots for Outliers
try:
num_cols = [c for c, t in col_types.items() if t == 'numerical' and c in df_clean.columns]
if num_cols:
plt.figure(figsize=(10, 6))
sns.boxplot(data=df_clean[num_cols], palette="Set2")
plt.title("Numerical Columns Boxplots (Outlier Diagnostic)")
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.savefig(os.path.join(figures_dir, "numerical_boxplots.png"), dpi=300)
plt.close()
except Exception as e:
print(f"[-] Visualization note (boxplots): {e}")
# 4. Correlation Heatmap
try:
num_cols = [c for c, t in col_types.items() if t == 'numerical' and c in df_clean.columns]
if len(num_cols) > 1:
plt.figure(figsize=(8, 6))
corr = df_clean[num_cols].corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", fmt=".2f", linewidths=0.5)
plt.title("Numerical Feature Correlation Heatmap")
plt.tight_layout()
plt.savefig(os.path.join(figures_dir, "correlation_heatmap.png"), dpi=300)
plt.close()
except Exception as e:
print(f"[-] Visualization note (correlation): {e}")
print(f"[+] Visualizations saved successfully in '{figures_dir}'")
# ==========================================
# 21. MAIN ORCHESTRATION FUNCTION
# ==========================================
def main():
args = parse_arguments()
print("=================================================================")
print(" UNIVERSAL AUTOMATED DATA PREPROCESSING PIPELINE ")
print("=================================================================")
print(f"Input Dataset: {args.input}")
print(f"Output Directory: {args.output}")
print(f"Handle Outliers (IQR): {args.handle_outliers}")
print(f"Scale Numerical Features: {args.scale_numerical}")
print(f"Extract Date Features: {args.extract_dates}")
print("=================================================================\n")
os.makedirs(args.output, exist_ok=True)
# Step 1: Load Dataset (CSV or Excel)
# Convert --sheet arg: numeric string → int, otherwise keep as sheet name string
sheet = int(args.sheet) if args.sheet.isdigit() else args.sheet
df_raw = load_dataset(args.input, sheet_name=sheet)
# Step 2: Clean Column Names
df = clean_column_names(df_raw)
# Step 3: Standardize Missing Values
df_standardized = standardize_missing_values(df)
df = df_standardized.copy()
# Step 4: Duplicate Handling
df, dup_before, dup_removed = handle_duplicates(df)
dup_info = (dup_before, dup_removed, len(df))
# Step 5: Column Type Detection
col_types = detect_column_types(df)
# Step 6: Dataset Profiling
profile_df = profile_dataset(df, col_types)
print("\n--- DATASET PROFILING TABLE ---")
print(profile_df.to_string(index=False))
# Step 7: Text Cleaning
df = clean_text_columns(df, col_types)
# Step 8: Process Numerical Columns
df = process_numerical_columns(df, col_types)
# Step 9: Process Boolean Columns
df = process_boolean_columns(df, col_types)
# Step 10: Datetime Processing
df, extracted_date_cols = process_datetime_columns(df, col_types, extract_features=args.extract_dates)
# Step 11: Outlier Detection & Handling
df, outlier_df = detect_outliers(df, col_types, handle_outliers=args.handle_outliers)
# Step 12: Identifier Detection
id_df = detect_identifiers(df, col_types)
# Step 13: Create Cleaned Dataset
df_clean = create_cleaned_dataset(df, col_types, extracted_date_cols)
# Step 14: Create ML-Ready Dataset
df_ml, pipeline, num_cols, cat_cols = create_ml_ready_dataset(
df, col_types, extracted_date_cols,
exclude_ids=args.exclude_identifiers,
exclude_text=args.exclude_free_text,
scale_num=args.scale_numerical
)
# Step 15: Generate Reports & Summaries
report_df, summary_txt = generate_reports(
df_standardized, df_clean, df_ml, col_types, extracted_date_cols, outlier_df, id_df, dup_info
)
# Step 16: Save All Outputs
clean_csv_path = os.path.join(args.output, "cleaned_dataset.csv")
ml_csv_path = os.path.join(args.output, "ml_ready_dataset.csv")
report_csv_path = os.path.join(args.output, "preprocessing_report.csv")
summary_txt_path = os.path.join(args.output, "preprocessing_summary.txt")
# Also save to current directory if required by root output spec
df_clean.to_csv("cleaned_dataset.csv", index=False)
df_clean.to_csv(clean_csv_path, index=False)
df_ml.to_csv("ml_ready_dataset.csv", index=False)
df_ml.to_csv(ml_csv_path, index=False)
report_df.to_csv("preprocessing_report.csv", index=False)
report_df.to_csv(report_csv_path, index=False)
with open("preprocessing_summary.txt", "w", encoding="utf-8") as f:
f.write(summary_txt)
with open(summary_txt_path, "w", encoding="utf-8") as f:
f.write(summary_txt)
print(f"\n[+] Saved cleaned dataset to: 'cleaned_dataset.csv' & '{clean_csv_path}'")
print(f"[+] Saved ML-ready dataset to: 'ml_ready_dataset.csv' & '{ml_csv_path}'")
print(f"[+] Saved preprocessing report to: 'preprocessing_report.csv' & '{report_csv_path}'")
print(f"[+] Saved summary text report to: 'preprocessing_summary.txt' & '{summary_txt_path}'")
# Step 17: Visualizations
generate_visualizations(df_raw, df_clean, col_types, args.output)
# Step 18: Validation
validation_status = validate_outputs(df_raw, df_clean, df_ml, dup_info)
if validation_status == "FAIL":
sys.exit(1)
if __name__ == "__main__":
main()