-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
2146 lines (1811 loc) · 82.6 KB
/
Copy pathagent.py
File metadata and controls
2146 lines (1811 loc) · 82.6 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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Data Preprocessing Multi-Agent System (Google ADK)
Architecture:
SequentialAgent (root orchestrator)
├── Agent 1: Dataset Analyzer — selects the best dataset
├── Agent 2: Preprocessing Strategist — creates a preprocessing plan
├── LoopAgent (max 5 iterations)
│ ├── Agent 3: Preprocessing Executor — runs preprocessing code
│ ├── Agent 4: Validation Agent — validates results
│ └── LoopEscalationChecker — escalates if PASS or max retries
└── Agent 5: Report Generator — writes A-to-Z preprocessing report
Data flow uses output_key → {state_key} templating between agents.
Agents also read/write pipeline_state.json for persistent cross-session state.
Report is saved to outputs/ folder as a detailed markdown file.
"""
import os
import sys
import json
import asyncio
from pathlib import Path
from typing import AsyncGenerator
from dotenv import load_dotenv
sys.path.append(str(Path(__file__).parent.parent))
from pipeline_state import load_state, save_state
load_dotenv()
# ============================================================
# CONSTANTS
# ============================================================
MODEL = "gemini-3.1-flash-lite-preview"
PROJECT_ROOT = Path(__file__).parent.parent
DATASETS_DIR = PROJECT_ROOT / "datasets"
MODIFIED_DATASETS_DIR = PROJECT_ROOT / "modified_datasets"
SUPPORTED_EXTENSIONS = {".csv", ".tsv", ".json", ".jsonl", ".txt", ".parquet", ".xlsx", ".xls"}
SKIP_EXTENSIONS = {
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".svg", ".ico",
".pkl", ".pickle", ".h5", ".hdf5", ".pt", ".pth", ".bin",
".zip", ".tar", ".gz", ".rar", ".7z",
".mp3", ".mp4", ".wav", ".avi",
".pdf", ".doc", ".docx",
".pyc", ".exe", ".dll", ".so",
".md", ".yml", ".yaml", ".cfg", ".ini", ".gitignore",
}
# ============================================================
# ================== AGENT 1 TOOLS =========================
# ============================================================
def get_project_context() -> str:
"""
Load the current pipeline state from pipeline_state.json and return
the user's project goal and report as a JSON string.
Use this to understand what the user wants to build so you can
select the most relevant dataset.
"""
state = load_state()
context = {
"user_goal": state.get("user_goal", ""),
"report": state.get("report", "")[:3000] if state.get("report") else "",
"status": state.get("status", ""),
}
return json.dumps(context, indent=2)
def scan_datasets_folder() -> str:
"""
Scan the 'datasets' folder in the project root.
For each subfolder, list all files and read a sample (first 5 rows)
of each supported data file (csv, tsv, json, jsonl, parquet, xlsx, txt).
Returns a JSON string with folder summaries, file metadata, column names,
dtypes, missing values, and a text preview of each file.
"""
import pandas as pd
if not DATASETS_DIR.exists():
return json.dumps({"error": f"Datasets folder not found: {DATASETS_DIR}"})
folder_summaries = []
for folder in sorted(DATASETS_DIR.iterdir()):
if not folder.is_dir():
continue
folder_info = {
"folder_name": folder.name,
"folder_path": str(folder),
"files": [],
"skipped_files": [],
}
for file_path in sorted(folder.rglob("*")):
if not file_path.is_file():
continue
ext = file_path.suffix.lower()
if ext in SKIP_EXTENSIONS or ext not in SUPPORTED_EXTENSIONS:
folder_info["skipped_files"].append(file_path.name)
continue
file_info = {
"file_name": file_path.name,
"file_path": str(file_path),
"file_type": ext,
"file_size_kb": round(file_path.stat().st_size / 1024, 2),
"success": False,
"preview": "",
"columns": [],
"num_columns": 0,
"num_rows_hint": "unknown",
}
try:
if ext == ".csv":
df = pd.read_csv(file_path, nrows=5)
with open(file_path, encoding="utf-8", errors="ignore") as row_f:
total_rows = sum(1 for _ in row_f) - 1
file_info["num_rows_hint"] = str(total_rows)
elif ext == ".tsv":
df = pd.read_csv(file_path, sep="\t", nrows=5)
with open(file_path, encoding="utf-8", errors="ignore") as row_f:
total_rows = sum(1 for _ in row_f) - 1
file_info["num_rows_hint"] = str(total_rows)
elif ext == ".jsonl":
df = pd.read_json(file_path, lines=True, nrows=5)
elif ext == ".json":
with open(file_path, "r", encoding="utf-8") as f:
raw = json.load(f)
if isinstance(raw, list):
df = pd.DataFrame(raw[:5])
else:
file_info["preview"] = json.dumps(raw, indent=2)[:2000]
file_info["success"] = True
folder_info["files"].append(file_info)
continue
elif ext == ".parquet":
df = pd.read_parquet(file_path).head(5)
total_rows = pd.read_parquet(file_path, columns=[]).shape[0]
file_info["num_rows_hint"] = str(total_rows)
elif ext in (".xlsx", ".xls"):
df = pd.read_excel(file_path, nrows=5)
elif ext == ".txt":
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
lines = [f.readline() for _ in range(5)]
file_info["preview"] = "".join(lines)
file_info["success"] = True
folder_info["files"].append(file_info)
continue
else:
continue
file_info["preview"] = df.to_string(index=False)
file_info["columns"] = list(df.columns)
file_info["num_columns"] = len(df.columns)
file_info["dtypes"] = {col: str(dtype) for col, dtype in df.dtypes.items()}
file_info["missing_values"] = df.isnull().sum().to_dict()
file_info["success"] = True
except Exception as e:
file_info["preview"] = f"[Error reading file: {str(e)}]"
folder_info["files"].append(file_info)
if folder_info["files"]:
folder_summaries.append(folder_info)
if not folder_summaries:
return json.dumps({"error": "No readable datasets found in any subfolder."})
return json.dumps(folder_summaries, indent=2)
def save_selected_dataset(
selected_folder: str,
selected_file: str,
selected_file_path: str,
reason: str,
columns: str,
num_rows: str,
potential_issues: str,
) -> str:
"""
Save the selected dataset info to pipeline_state.json so that
Agent 2 can read it. Call this AFTER you have analyzed all datasets
and decided which one is the best.
Args:
selected_folder: Name of the folder containing the best dataset.
selected_file: Name of the selected file (e.g. 'data.csv').
selected_file_path: Full absolute path to the selected file.
reason: Detailed reason why this dataset was selected.
columns: Comma-separated list of column names in the dataset.
num_rows: Approximate number of rows as a string.
potential_issues: Comma-separated list of potential data quality issues.
Returns:
Confirmation message.
"""
agent1_output = {
"selected_dataset": {
"selected_folder": selected_folder,
"selected_file": selected_file,
"selected_file_path": selected_file_path,
"reason": reason,
"columns": [c.strip() for c in columns.split(",") if c.strip()],
"num_rows": num_rows,
"potential_issues": [i.strip() for i in potential_issues.split(",") if i.strip()],
}
}
save_state({
"agent1_output": agent1_output,
"selected_dataset_path": selected_file_path,
"status": "agent1_done",
})
return f"Selected dataset saved: {selected_folder}/{selected_file}"
# ============================================================
# ================== AGENT 2 TOOLS =========================
# ============================================================
def load_dataset_profile() -> str:
"""
Load the selected dataset from pipeline_state.json (Agent 1's output),
then perform a deep statistical profile of the data.
Returns JSON with: shape, dtypes, missing values per column,
unique counts, basic stats (mean/median/std/min/max),
sample rows, and detected data quality issues.
"""
import pandas as pd
import numpy as np
state = load_state()
agent1_out = state.get("agent1_output", {})
selected = agent1_out.get("selected_dataset", {})
file_path = selected.get("selected_file_path", "")
if not file_path or not Path(file_path).exists():
return json.dumps({"error": f"Selected dataset not found: {file_path}"})
ext = Path(file_path).suffix.lower()
try:
if ext == ".csv":
df = pd.read_csv(file_path)
elif ext == ".tsv":
df = pd.read_csv(file_path, sep="\t")
elif ext == ".json":
df = pd.read_json(file_path)
elif ext == ".jsonl":
df = pd.read_json(file_path, lines=True)
elif ext == ".parquet":
df = pd.read_parquet(file_path)
elif ext in (".xlsx", ".xls"):
df = pd.read_excel(file_path)
else:
return json.dumps({"error": f"Unsupported file type: {ext}"})
except Exception as e:
return json.dumps({"error": f"Failed to read dataset: {str(e)}"})
profile = {
"file_path": file_path,
"shape": {"rows": df.shape[0], "columns": df.shape[1]},
"columns": list(df.columns),
"dtypes": {col: str(dtype) for col, dtype in df.dtypes.items()},
"missing_values": df.isnull().sum().to_dict(),
"missing_pct": (df.isnull().sum() / len(df) * 100).round(2).to_dict(),
"unique_counts": df.nunique().to_dict(),
"sample_rows": df.head(3).to_dict(orient="records"),
}
# Numeric stats
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
if numeric_cols:
profile["numeric_stats"] = df[numeric_cols].describe().round(4).to_dict()
# Outlier detection via IQR
outlier_cols = []
for col in numeric_cols:
q1, q3 = df[col].quantile(0.25), df[col].quantile(0.75)
iqr = q3 - q1
if iqr > 0:
outlier_count = int(((df[col] < q1 - 1.5 * iqr) | (df[col] > q3 + 1.5 * iqr)).sum())
if outlier_count > 0:
outlier_cols.append({"column": col, "outlier_count": outlier_count, "pct": round(outlier_count / len(df) * 100, 2)})
profile["potential_outliers"] = outlier_cols
# Highly correlated pairs (>0.9)
if len(numeric_cols) > 1:
corr = df[numeric_cols].corr().abs()
high_corr = []
for i in range(len(corr.columns)):
for j in range(i + 1, len(corr.columns)):
if corr.iloc[i, j] > 0.9:
high_corr.append({"col1": corr.columns[i], "col2": corr.columns[j], "correlation": round(float(corr.iloc[i, j]), 4)})
profile["high_correlations"] = high_corr
# Categorical stats
cat_cols = df.select_dtypes(include=["object", "category"]).columns.tolist()
if cat_cols:
cat_stats = {}
for col in cat_cols:
top_vals = df[col].value_counts().head(10).to_dict()
cat_stats[col] = {
"unique": int(df[col].nunique()),
"top_values": {str(k): int(v) for k, v in top_vals.items()},
"avg_length": round(float(df[col].dropna().astype(str).str.len().mean()), 1),
}
profile["categorical_stats"] = cat_stats
# Constant columns
near_constant = [col for col in df.columns if df[col].nunique() <= 1]
if near_constant:
profile["constant_columns"] = near_constant
# Duplicates
profile["duplicate_rows"] = int(df.duplicated().sum())
# Unparsed date columns
date_candidates = []
for col in cat_cols:
sample = df[col].dropna().head(20)
try:
pd.to_datetime(sample)
date_candidates.append(col)
except (ValueError, TypeError):
pass
if date_candidates:
profile["unparsed_date_columns"] = date_candidates
return json.dumps(profile, indent=2, default=str)
def get_user_requirements() -> str:
"""
Load the user's original goal, Q&A pairs, report, and Agent 1's
selection reason from pipeline_state.json. This gives full context
for creating a preprocessing plan aligned with the user's ML goal.
"""
state = load_state()
requirements = {
"user_goal": state.get("user_goal", ""),
"qa_pairs": state.get("qa_pairs", []),
"report_summary": state.get("report", "")[:4000] if state.get("report") else "",
"agent1_selection": state.get("agent1_output", {}).get("selected_dataset", {}),
}
return json.dumps(requirements, indent=2, default=str)
def save_preprocessing_plan(
plan_summary: str,
target_column: str,
columns_to_drop: str,
missing_value_strategy: str,
encoding_strategy: str,
scaling_strategy: str,
outlier_strategy: str,
feature_engineering: str,
text_processing: str,
datetime_processing: str,
duplicate_strategy: str,
final_validation_checks: str,
step_by_step_order: str,
) -> str:
"""
Save the complete preprocessing plan to pipeline_state.json.
Agent 3 will read this plan and execute each step.
Args:
plan_summary: A 2-3 sentence summary of the overall preprocessing approach.
target_column: The target/label column name for ML (or 'none' if unsupervised).
columns_to_drop: Comma-separated column names to drop and why (format: 'col:reason,col:reason').
missing_value_strategy: Detailed strategy per column (format: 'col:strategy,col:strategy').
Strategies: drop_rows, fill_mean, fill_median, fill_mode, fill_zero, fill_ffill, fill_custom.
encoding_strategy: How to encode categorical columns (format: 'col:method,col:method').
Methods: label_encode, onehot_encode, ordinal_encode, target_encode, frequency_encode, drop.
scaling_strategy: How to scale numeric columns (format: 'col:method,col:method' or 'all:method').
Methods: standard, minmax, robust, log_transform, none.
outlier_strategy: How to handle outliers (format: 'col:method,col:method').
Methods: clip_iqr, remove_iqr, clip_zscore, remove_zscore, log_transform, keep.
feature_engineering: New features to create (format: 'new_col:formula_or_description,...').
text_processing: How to handle text columns (format: 'col:method,...').
Methods: tfidf, countvec, length_feature, word_count, drop, keep.
datetime_processing: How to handle datetime columns (format: 'col:extractions,...').
Extractions: year, month, day, dayofweek, hour, is_weekend, time_since.
duplicate_strategy: How to handle duplicate rows: 'drop_all', 'drop_keep_first', 'drop_keep_last', 'keep'.
final_validation_checks: Comma-separated list of checks to run after preprocessing.
step_by_step_order: Ordered comma-separated list of steps (e.g., 'drop_columns,handle_missing,encode,...').
Returns:
Confirmation message.
"""
plan = {
"plan_summary": plan_summary,
"target_column": target_column,
"columns_to_drop": columns_to_drop,
"missing_value_strategy": missing_value_strategy,
"encoding_strategy": encoding_strategy,
"scaling_strategy": scaling_strategy,
"outlier_strategy": outlier_strategy,
"feature_engineering": feature_engineering,
"text_processing": text_processing,
"datetime_processing": datetime_processing,
"duplicate_strategy": duplicate_strategy,
"final_validation_checks": final_validation_checks,
"step_by_step_order": step_by_step_order,
}
save_state({
"agent2_output": {"preprocessing_plan": plan},
"status": "agent2_done",
})
return f"Preprocessing plan saved. Steps: {step_by_step_order}"
# ============================================================
# ================== AGENT 3 TOOLS =========================
# ============================================================
def _resolve_local_path(p: str) -> str:
"""
Defensive path translator for built-in (host-side) preprocessing tools.
The LLM sometimes hands a sandbox path like '/workspace/output/foo.csv'
to a built-in tool that runs on the host. Pandas would then crash with
[Errno 2] No such file or directory. This helper rewrites such paths to
the equivalent local file under modified_datasets/ if it exists, and
raises a CLEAR error otherwise so the LLM can recover instead of looping.
"""
if not p:
raise FileNotFoundError(
"Empty dataset_path. Built-in tools need an absolute LOCAL path."
)
# Sandbox path? Try to remap to local modified_datasets/<basename>
if p.startswith("/workspace/") or p.startswith("\\workspace\\"):
basename = os.path.basename(p.replace("\\", "/"))
candidate = MODIFIED_DATASETS_DIR / basename
if candidate.exists():
return str(candidate)
raise FileNotFoundError(
f"Path '{p}' is a SANDBOX path. Built-in tools run on the HOST and "
f"cannot read sandbox files. Either (1) call download_from_sandbox "
f"first to copy the file to '{MODIFIED_DATASETS_DIR / basename}', or "
f"(2) skip the sandbox entirely and use the local path returned by "
f"the previous built-in tool. Built-in tools never accept /workspace/... paths."
)
if not os.path.isabs(p):
# Resolve relative to project root
candidate = PROJECT_ROOT / p
if candidate.exists():
return str(candidate)
if not os.path.exists(p):
raise FileNotFoundError(
f"Local file not found: {p}. Use the path returned by the previous "
f"built-in tool, or the 'dataset_path' from get_preprocessing_context."
)
return p
def get_preprocessing_context() -> str:
"""
Load everything Agent 3 needs: user goal, Agent 1's dataset selection,
Agent 2's preprocessing plan, the dataset file path, and any previous
validation feedback from Agent 4 (for retry loops).
"""
state = load_state()
context = {
"user_goal": state.get("user_goal", ""),
"selected_dataset": state.get("agent1_output", {}).get("selected_dataset", {}),
"preprocessing_plan": state.get("agent2_output", {}).get("preprocessing_plan", {}),
"dataset_path": state.get("selected_dataset_path", ""),
"validation_feedback": state.get("agent4_feedback", ""),
"iteration": state.get("loop_iteration", 0),
}
return json.dumps(context, indent=2, default=str)
def handle_missing_values(
dataset_path: str,
strategy_json: str,
output_path: str,
) -> str:
"""
Handle missing values in the dataset using column-specific strategies.
Args:
dataset_path: Absolute path to the input CSV/Parquet file.
strategy_json: JSON string mapping column names to strategies.
Example: '{"age": "fill_median", "city": "fill_mode", "temp": "fill_mean", "id": "drop_rows"}'
Supported strategies: fill_mean, fill_median, fill_mode, fill_zero,
fill_ffill, fill_bfill, fill_interpolate, drop_rows, drop_column.
output_path: Absolute path to save the result CSV.
Returns:
JSON with before/after missing counts and rows affected.
"""
import pandas as pd
dataset_path = _resolve_local_path(dataset_path)
df = pd.read_csv(dataset_path)
before_missing = df.isnull().sum().to_dict()
before_rows = len(df)
strategies = json.loads(strategy_json)
for col, strategy in strategies.items():
if col not in df.columns:
continue
if strategy == "fill_mean":
df[col] = df[col].fillna(df[col].mean())
elif strategy == "fill_median":
df[col] = df[col].fillna(df[col].median())
elif strategy == "fill_mode":
mode_val = df[col].mode()
if len(mode_val) > 0:
df[col] = df[col].fillna(mode_val[0])
elif strategy == "fill_zero":
df[col] = df[col].fillna(0)
elif strategy == "fill_ffill":
df[col] = df[col].ffill()
elif strategy == "fill_bfill":
df[col] = df[col].bfill()
elif strategy == "fill_interpolate":
df[col] = df[col].interpolate(method="linear")
elif strategy == "drop_rows":
df = df.dropna(subset=[col])
elif strategy == "drop_column":
df = df.drop(columns=[col])
df.to_csv(output_path, index=False)
after_missing = df.isnull().sum().to_dict()
return json.dumps({
"status": "success",
"before_missing": {k: v for k, v in before_missing.items() if v > 0},
"after_missing": {k: v for k, v in after_missing.items() if v > 0},
"rows_before": before_rows,
"rows_after": len(df),
"output_path": output_path,
}, indent=2)
def remove_duplicates(
dataset_path: str,
strategy: str,
subset_columns: str,
output_path: str,
) -> str:
"""
Remove duplicate rows from the dataset.
Args:
dataset_path: Absolute path to the input CSV file.
strategy: One of 'keep_first', 'keep_last', 'drop_all'.
subset_columns: Comma-separated column names to check for duplicates,
or 'all' to check all columns.
output_path: Absolute path to save the result CSV.
Returns:
JSON with duplicate count before/after and rows removed.
"""
import pandas as pd
dataset_path = _resolve_local_path(dataset_path)
df = pd.read_csv(dataset_path)
subset = None if subset_columns == "all" else [c.strip() for c in subset_columns.split(",")]
before_dupes = int(df.duplicated(subset=subset).sum())
if strategy == "keep_first":
df = df.drop_duplicates(subset=subset, keep="first")
elif strategy == "keep_last":
df = df.drop_duplicates(subset=subset, keep="last")
elif strategy == "drop_all":
df = df.drop_duplicates(subset=subset, keep=False)
df.to_csv(output_path, index=False)
return json.dumps({
"status": "success",
"duplicates_found": before_dupes,
"duplicates_removed": before_dupes - int(df.duplicated(subset=subset).sum()),
"rows_after": len(df),
"output_path": output_path,
}, indent=2)
def drop_columns(
dataset_path: str,
columns_to_drop: str,
output_path: str,
) -> str:
"""
Drop specified columns from the dataset.
Args:
dataset_path: Absolute path to the input CSV file.
columns_to_drop: Comma-separated column names to drop.
output_path: Absolute path to save the result CSV.
Returns:
JSON with columns dropped and remaining columns.
"""
import pandas as pd
dataset_path = _resolve_local_path(dataset_path)
df = pd.read_csv(dataset_path)
cols = [c.strip() for c in columns_to_drop.split(",") if c.strip()]
existing = [c for c in cols if c in df.columns]
missing = [c for c in cols if c not in df.columns]
df = df.drop(columns=existing)
df.to_csv(output_path, index=False)
return json.dumps({
"status": "success",
"dropped": existing,
"not_found": missing,
"remaining_columns": list(df.columns),
"output_path": output_path,
}, indent=2)
def encode_categorical_columns(
dataset_path: str,
encoding_json: str,
output_path: str,
) -> str:
"""
Encode categorical columns using specified methods.
Args:
dataset_path: Absolute path to the input CSV file.
encoding_json: JSON string mapping column names to encoding methods.
Example: '{"city": "onehot", "grade": "label", "browser": "frequency", "size": "ordinal:S,M,L,XL"}'
Supported: 'label', 'onehot', 'frequency', 'ordinal:val1,val2,...' (ordered),
'binary' (for 2-class columns), 'target:target_col' (target/mean encoding).
output_path: Absolute path to save the result CSV.
Returns:
JSON with encoding details per column and new column list.
"""
import pandas as pd
from sklearn.preprocessing import LabelEncoder
dataset_path = _resolve_local_path(dataset_path)
df = pd.read_csv(dataset_path)
encodings = json.loads(encoding_json)
details = {}
for col, method in encodings.items():
if col not in df.columns:
details[col] = {"status": "skipped", "reason": "column not found"}
continue
if method == "label":
le = LabelEncoder()
df[col] = le.fit_transform(df[col].astype(str))
details[col] = {"method": "label", "classes": list(le.classes_)}
elif method == "onehot":
dummies = pd.get_dummies(df[col], prefix=col, drop_first=True)
df = pd.concat([df.drop(columns=[col]), dummies], axis=1)
details[col] = {"method": "onehot", "new_columns": list(dummies.columns)}
elif method == "frequency":
freq_map = df[col].value_counts(normalize=True).to_dict()
df[col] = df[col].map(freq_map)
details[col] = {"method": "frequency", "top_mappings": dict(list(freq_map.items())[:5])}
elif method.startswith("ordinal:"):
order = method.split(":", 1)[1].split(",")
mapping = {val.strip(): i for i, val in enumerate(order)}
df[col] = df[col].map(mapping)
details[col] = {"method": "ordinal", "mapping": mapping}
elif method == "binary":
unique_vals = df[col].dropna().unique()
if len(unique_vals) == 2:
df[col] = (df[col] == unique_vals[1]).astype(int)
details[col] = {"method": "binary", "mapping": {str(unique_vals[0]): 0, str(unique_vals[1]): 1}}
else:
details[col] = {"status": "skipped", "reason": f"not binary — has {len(unique_vals)} unique values"}
elif method.startswith("target:"):
target_col = method.split(":", 1)[1]
if target_col in df.columns:
means = df.groupby(col)[target_col].mean()
df[col] = df[col].map(means)
details[col] = {"method": "target_encoding", "target": target_col}
else:
details[col] = {"status": "skipped", "reason": f"target column '{target_col}' not found"}
df.to_csv(output_path, index=False)
return json.dumps({
"status": "success",
"encoding_details": details,
"final_columns": list(df.columns),
"output_path": output_path,
}, indent=2)
def scale_numeric_columns(
dataset_path: str,
scaling_json: str,
exclude_columns: str,
output_path: str,
) -> str:
"""
Scale/normalize numeric columns using specified methods.
Args:
dataset_path: Absolute path to the input CSV file.
scaling_json: JSON string mapping column names to scaling methods.
Use '__all_numeric__' as key to apply one method to all numeric columns.
Example: '{"__all_numeric__": "standard"}' or '{"price": "minmax", "age": "robust"}'
Supported: 'standard' (z-score), 'minmax' (0-1), 'robust' (IQR-based),
'log' (log1p transform), 'maxabs' (scale by max absolute value),
'power_yeo' (Yeo-Johnson power transform for skewed data).
exclude_columns: Comma-separated column names to NEVER scale (e.g., target column, IDs).
output_path: Absolute path to save the result CSV.
Returns:
JSON with scaling details per column.
"""
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler, MaxAbsScaler, PowerTransformer
dataset_path = _resolve_local_path(dataset_path)
df = pd.read_csv(dataset_path)
scalings = json.loads(scaling_json)
exclude = {c.strip() for c in exclude_columns.split(",") if c.strip()}
details = {}
numeric_cols = [c for c in df.select_dtypes(include=[np.number]).columns if c not in exclude]
if "__all_numeric__" in scalings:
method = scalings["__all_numeric__"]
col_methods = {col: method for col in numeric_cols}
else:
col_methods = {col: m for col, m in scalings.items() if col in numeric_cols and col not in exclude}
for col, method in col_methods.items():
if col not in df.columns:
continue
before_stats = {"mean": round(float(df[col].mean()), 4), "std": round(float(df[col].std()), 4)}
if method == "standard":
scaler = StandardScaler()
df[col] = scaler.fit_transform(df[[col]])
elif method == "minmax":
scaler = MinMaxScaler()
df[col] = scaler.fit_transform(df[[col]])
elif method == "robust":
scaler = RobustScaler()
df[col] = scaler.fit_transform(df[[col]])
elif method == "log":
df[col] = np.log1p(df[col].clip(lower=0))
elif method == "maxabs":
scaler = MaxAbsScaler()
df[col] = scaler.fit_transform(df[[col]])
elif method == "power_yeo":
pt = PowerTransformer(method="yeo-johnson")
df[col] = pt.fit_transform(df[[col]])
after_stats = {"mean": round(float(df[col].mean()), 4), "std": round(float(df[col].std()), 4)}
details[col] = {"method": method, "before": before_stats, "after": after_stats}
df.to_csv(output_path, index=False)
return json.dumps({
"status": "success",
"scaling_details": details,
"excluded": list(exclude),
"output_path": output_path,
}, indent=2)
def handle_outliers(
dataset_path: str,
outlier_json: str,
output_path: str,
) -> str:
"""
Detect and handle outliers in numeric columns.
Args:
dataset_path: Absolute path to the input CSV file.
outlier_json: JSON string mapping column names to outlier strategies.
Example: '{"price": "clip_iqr", "age": "remove_zscore:3", "salary": "winsorize:5,95"}'
Supported:
- 'clip_iqr' or 'clip_iqr:1.5' — clip values to [Q1-k*IQR, Q3+k*IQR]
- 'remove_iqr' or 'remove_iqr:1.5' — remove rows outside IQR bounds
- 'clip_zscore:3' — clip values beyond z-score threshold
- 'remove_zscore:3' — remove rows beyond z-score threshold
- 'winsorize:5,95' — clip to given percentiles
- 'log_transform' — apply log1p (compresses extreme values)
- 'keep' — do nothing
output_path: Absolute path to save the result CSV.
Returns:
JSON with outlier counts before/after per column.
"""
import pandas as pd
import numpy as np
dataset_path = _resolve_local_path(dataset_path)
df = pd.read_csv(dataset_path)
strategies = json.loads(outlier_json)
details = {}
before_rows = len(df)
for col, strategy in strategies.items():
if col not in df.columns or strategy == "keep":
continue
q1, q3 = df[col].quantile(0.25), df[col].quantile(0.75)
iqr = q3 - q1
before_outliers = int(((df[col] < q1 - 1.5 * iqr) | (df[col] > q3 + 1.5 * iqr)).sum()) if iqr > 0 else 0
if strategy.startswith("clip_iqr"):
k = float(strategy.split(":")[1]) if ":" in strategy else 1.5
lower, upper = q1 - k * iqr, q3 + k * iqr
df[col] = df[col].clip(lower=lower, upper=upper)
elif strategy.startswith("remove_iqr"):
k = float(strategy.split(":")[1]) if ":" in strategy else 1.5
lower, upper = q1 - k * iqr, q3 + k * iqr
df = df[(df[col] >= lower) & (df[col] <= upper)]
elif strategy.startswith("clip_zscore"):
threshold = float(strategy.split(":")[1]) if ":" in strategy else 3
mean, std = df[col].mean(), df[col].std()
if std > 0:
df[col] = df[col].clip(lower=mean - threshold * std, upper=mean + threshold * std)
elif strategy.startswith("remove_zscore"):
threshold = float(strategy.split(":")[1]) if ":" in strategy else 3
mean, std = df[col].mean(), df[col].std()
if std > 0:
df = df[((df[col] - mean) / std).abs() <= threshold]
elif strategy.startswith("winsorize"):
parts = strategy.split(":")[1].split(",") if ":" in strategy else ["5", "95"]
lower_p, upper_p = float(parts[0]), float(parts[1])
lower_val = df[col].quantile(lower_p / 100)
upper_val = df[col].quantile(upper_p / 100)
df[col] = df[col].clip(lower=lower_val, upper=upper_val)
elif strategy == "log_transform":
df[col] = np.log1p(df[col].clip(lower=0))
after_outliers = 0
if iqr > 0:
new_q1, new_q3 = df[col].quantile(0.25), df[col].quantile(0.75)
new_iqr = new_q3 - new_q1
if new_iqr > 0:
after_outliers = int(((df[col] < new_q1 - 1.5 * new_iqr) | (df[col] > new_q3 + 1.5 * new_iqr)).sum())
details[col] = {"strategy": strategy, "outliers_before": before_outliers, "outliers_after": after_outliers}
df.to_csv(output_path, index=False)
return json.dumps({
"status": "success",
"outlier_details": details,
"rows_before": before_rows,
"rows_after": len(df),
"output_path": output_path,
}, indent=2)
def parse_datetime_columns(
dataset_path: str,
datetime_json: str,
output_path: str,
) -> str:
"""
Parse datetime columns and extract useful time features.
Args:
dataset_path: Absolute path to the input CSV file.
datetime_json: JSON mapping column names to comma-separated features to extract.
Example: '{"publish_date": "year,month,day,dayofweek,hour,is_weekend", "trending_date": "year,month,dayofweek"}'
Supported extractions: year, month, day, dayofweek (0=Mon), hour, minute,
is_weekend (0/1), quarter, week_of_year, days_since_earliest, time_of_day (morning/afternoon/evening/night).
The original column will be dropped after extraction.
output_path: Absolute path to save the result CSV.
Returns:
JSON with new columns created per datetime column.
"""
import pandas as pd
dataset_path = _resolve_local_path(dataset_path)
df = pd.read_csv(dataset_path)
configs = json.loads(datetime_json)
details = {}
for col, features_str in configs.items():
if col not in df.columns:
details[col] = {"status": "skipped", "reason": "column not found"}
continue
try:
dt = pd.to_datetime(df[col], errors="coerce", infer_datetime_format=True)
except Exception as e:
details[col] = {"status": "error", "reason": str(e)}
continue
features = [f.strip() for f in features_str.split(",")]
new_cols = []
for feat in features:
new_col = f"{col}_{feat}"
if feat == "year":
df[new_col] = dt.dt.year
elif feat == "month":
df[new_col] = dt.dt.month
elif feat == "day":
df[new_col] = dt.dt.day
elif feat == "dayofweek":
df[new_col] = dt.dt.dayofweek
elif feat == "hour":
df[new_col] = dt.dt.hour
elif feat == "minute":
df[new_col] = dt.dt.minute
elif feat == "is_weekend":
df[new_col] = (dt.dt.dayofweek >= 5).astype(int)
elif feat == "quarter":
df[new_col] = dt.dt.quarter
elif feat == "week_of_year":
df[new_col] = dt.dt.isocalendar().week.astype(int)
elif feat == "days_since_earliest":
earliest = dt.min()
df[new_col] = (dt - earliest).dt.days
elif feat == "time_of_day":
df[new_col] = pd.cut(
dt.dt.hour,
bins=[-1, 6, 12, 18, 24],
labels=["night", "morning", "afternoon", "evening"],
)
new_cols.append(new_col)
df = df.drop(columns=[col])
details[col] = {"status": "success", "new_columns": new_cols, "null_dates": int(dt.isnull().sum())}
df.to_csv(output_path, index=False)
return json.dumps({
"status": "success",
"datetime_details": details,
"final_columns": list(df.columns),
"output_path": output_path,
}, indent=2)
def engineer_features(
dataset_path: str,
features_json: str,
output_path: str,
) -> str:
"""
Create new engineered features from existing columns.
Args:
dataset_path: Absolute path to the input CSV file.
features_json: JSON mapping new column names to feature definitions.
Example: '{
"engagement_rate": "formula:(likes + comments) / views",
"title_length": "str_len:title",
"title_word_count": "word_count:title",
"log_views": "log:views",
"views_per_day": "ratio:views,days_since_publish",
"is_popular": "threshold_above:likes,1000",
"category_group": "bin:views,5",
"interaction": "multiply:likes,comments"
}'
Supported operations:
- 'formula:<pandas_expression>' — evaluate a pandas expression
- 'str_len:<col>' — string length
- 'word_count:<col>' — word count
- 'log:<col>' — log1p transform
- 'ratio:<col1>,<col2>' — col1 / col2 (safe division)
- 'threshold_above:<col>,<value>' — binary: 1 if col > value
- 'threshold_below:<col>,<value>' — binary: 1 if col < value