sujithrajaR commited on
Commit
78a7720
·
verified ·
1 Parent(s): d981336

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -171
app.py CHANGED
@@ -5,219 +5,174 @@ import os, math
5
 
6
  APP_TITLE = "🧹 Smart Data Cleaning Agent"
7
 
8
- def clean_data(file, null_strategy, custom_fill, dup_strategy, dup_subset,
9
- trim_spaces, normalize_case, convert_dtypes, parse_dates, date_cols_hint,
10
- outliers, z_thresh, iqr_factor,
11
- split_column, split_sep):
12
 
 
 
 
 
 
13
  if file is None:
14
- return None, "❌ Please upload a dataset."
15
-
16
- # Load file
17
- ext = os.path.splitext(file.name)[1].lower()
18
- if ext == ".csv":
19
- df = pd.read_csv(file.name)
20
- elif ext == ".xlsx":
21
- df = pd.read_excel(file.name)
22
- elif ext == ".json":
23
- df = pd.read_json(file.name)
24
- else:
25
- return None, f"❌ Unsupported file format: {ext}"
26
-
27
- report_lines = []
28
- before_rows = len(df)
29
- before_nulls = int(df.isna().sum().sum())
30
- before_dups = int(df.duplicated().sum())
31
-
32
- # === Cleaning ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  if trim_spaces:
34
- obj_cols = df.select_dtypes(include=["object", "string"]).columns
35
  for c in obj_cols:
36
- df[c] = df[c].astype(str).str.strip()
37
- report_lines.append(f"Trimmed whitespace in {len(obj_cols)} text cols.")
38
 
 
39
  if normalize_case != "Keep case":
40
- obj_cols = df.select_dtypes(include=["object", "string"]).columns
41
  if normalize_case == "lower()":
42
- df[obj_cols] = df[obj_cols].apply(lambda c: c.astype(str).str.lower())
43
  elif normalize_case == "UPPER()":
44
- df[obj_cols] = df[obj_cols].apply(lambda c: c.astype(str).str.upper())
45
  elif normalize_case == "Title Case":
46
- df[obj_cols] = df[obj_cols].apply(lambda c: c.astype(str).str.title())
47
- report_lines.append(f"Normalized text case: {normalize_case} on {len(obj_cols)} cols.")
48
 
 
49
  if convert_dtypes:
50
- df = df.convert_dtypes()
51
- report_lines.append("Auto converted dtypes.")
52
 
 
53
  if parse_dates:
54
  hinted = [c.strip() for c in date_cols_hint.split(",") if c.strip()]
55
- target_cols = hinted if hinted else df.columns.tolist()
56
- parsed_cnt = 0
57
  for c in target_cols:
58
  try:
59
- df[c] = pd.to_datetime(df[c], errors="ignore", infer_datetime_format=True)
60
- if np.issubdtype(df[c].dtype, np.datetime64):
61
- parsed_cnt += 1
62
- except Exception:
63
- pass
64
- if parsed_cnt:
65
- report_lines.append(f"Parsed {parsed_cnt} date columns.")
66
-
67
- # Nulls
68
- if null_strategy == "Drop rows with any nulls":
69
- df = df.dropna(how="any")
70
- report_lines.append("Dropped rows with any nulls.")
71
- elif null_strategy == "Drop rows with all nulls":
72
- df = df.dropna(how="all")
73
- report_lines.append("Dropped rows entirely null.")
74
- elif null_strategy == "Fill nulls: Mean (numeric)":
75
- num_cols = df.select_dtypes(include=[np.number]).columns
76
- df[num_cols] = df[num_cols].fillna(df[num_cols].mean())
77
- report_lines.append("Filled numeric nulls with column mean.")
78
- elif null_strategy == "Fill nulls: Median (numeric)":
79
- num_cols = df.select_dtypes(include=[np.number]).columns
80
- df[num_cols] = df[num_cols].fillna(df[num_cols].median())
81
- report_lines.append("Filled numeric nulls with column median.")
82
- elif null_strategy == "Fill nulls: Mode (per column)":
83
- for col in df.columns:
84
- try:
85
- mode_val = df[col].mode(dropna=True)
86
- if not mode_val.empty:
87
- df[col] = df[col].fillna(mode_val[0])
88
- except Exception:
89
  pass
90
- report_lines.append("Filled nulls with per-column mode.")
91
- elif null_strategy.startswith("Fill nulls: Custom value"):
92
- df = df.fillna(custom_fill)
93
- report_lines.append(f"Filled nulls with custom value: {repr(custom_fill)}.")
94
 
95
- # Duplicates
96
  subset_cols = [c.strip() for c in dup_subset.split(",") if c.strip()] or None
97
  if dup_strategy == "Drop exact duplicates":
98
- df = df.drop_duplicates(subset=subset_cols, keep="first")
99
- report_lines.append("Dropped duplicates (keep first).")
100
  elif dup_strategy == "Drop duplicates (keep last)":
101
- df = df.drop_duplicates(subset=subset_cols, keep="last")
102
- report_lines.append("Dropped duplicates (keep last).")
103
 
104
  # Outliers
105
- num_cols = df.select_dtypes(include=[np.number]).columns
106
  if outliers == "Clip by z-score (|z| > threshold)" and len(num_cols) > 0:
107
  thr = int(z_thresh)
108
  for c in num_cols:
109
- col = df[c].astype(float)
110
  mu, sd = col.mean(), col.std(ddof=0)
111
  if sd and not np.isnan(sd):
112
  z = (col - mu) / sd
113
  mask = z.abs() > thr
114
  col_clipped = col.clip(lower=mu - thr*sd, upper=mu + thr*sd)
115
- df[c] = col.where(~mask, col_clipped)
116
- report_lines.append(f"Outliers clipped by z-score (±{thr}).")
117
  elif outliers == "Clip by IQR (1.5×IQR fences)" and len(num_cols) > 0:
118
  factor = float(iqr_factor)
119
  for c in num_cols:
120
- q1, q3 = df[c].quantile(0.25), df[c].quantile(0.75)
121
  iqr = q3 - q1
122
  if pd.notna(iqr) and iqr > 0:
123
  low = q1 - 1.5 * iqr * factor
124
  high = q3 + 1.5 * iqr * factor
125
- df[c] = df[c].clip(lower=low, upper=high)
126
- report_lines.append(f"Outliers clipped by IQR.")
127
 
128
- # Split Column
129
- if split_column and split_column in df.columns:
130
- sep = split_sep if split_sep else ","
131
- new_cols = df[split_column].astype(str).str.split(sep, expand=True)
132
- for i, col_name in enumerate(new_cols.columns):
133
- df[f"{split_column}_part{i+1}"] = new_cols[col_name]
134
- report_lines.append(f"Split column '{split_column}' into {len(new_cols.columns)} parts using separator '{sep}'.")
135
 
136
- # After stats
137
- after_rows = len(df)
138
- after_nulls = int(df.isna().sum().sum())
139
- after_dups = int(df.duplicated().sum())
 
 
140
 
141
- report_lines.insert(0, f"Rows: {before_rows} → {after_rows}")
142
- report_lines.insert(1, f"Null cells: {before_nulls} → {after_nulls}")
143
- report_lines.insert(2, f"Duplicates: {before_dups} → {after_dups}")
144
 
145
- return df.head(100), "\n".join(report_lines)
 
 
 
 
 
 
146
 
147
- # === Gradio Interface ===
148
- with gr.Blocks(title=APP_TITLE) as demo:
149
- gr.Markdown(f"# {APP_TITLE}\nUpload a dataset and apply cleaning options.")
 
 
 
150
 
151
  with gr.Row():
152
- with gr.Column(scale=1):
153
- file = gr.File(label="Upload Dataset", file_types=[".csv", ".xlsx", ".json"])
154
-
155
- null_strategy = gr.Dropdown(
156
- ["Do nothing","Drop rows with any nulls","Drop rows with all nulls",
157
- "Fill nulls: Mean (numeric)","Fill nulls: Median (numeric)",
158
- "Fill nulls: Mode (per column)","Fill nulls: Custom value →"],
159
- value="Do nothing", label="Null Handling"
160
- )
161
- custom_fill = gr.Textbox(label="Custom Fill Value", placeholder="0, Unknown, etc.")
162
-
163
- dup_strategy = gr.Dropdown(
164
- ["Do nothing","Drop exact duplicates","Drop duplicates (keep last)"],
165
- value="Do nothing", label="Duplicate Handling"
166
- )
167
- dup_subset = gr.Textbox(label="Subset Columns for Duplicates (comma separated)")
168
-
169
- trim_spaces = gr.Checkbox(label="Trim whitespace", value=False)
170
- normalize_case = gr.Dropdown(["Keep case","lower()","UPPER()","Title Case"], value="Keep case")
171
-
172
- convert_dtypes = gr.Checkbox(label="Auto convert dtypes", value=False)
173
- parse_dates = gr.Checkbox(label="Try parse dates", value=False)
174
- date_cols_hint = gr.Textbox(label="Date Columns Hint (comma separated)")
175
-
176
- outliers = gr.Dropdown(
177
- ["No outlier handling","Clip by z-score (|z| > threshold)","Clip by IQR (1.5×IQR fences)"],
178
- value="No outlier handling", label="Outlier Handling"
179
- )
180
- z_thresh = gr.Slider(1, 10, value=3, step=1, label="Z-score threshold")
181
- iqr_factor = gr.Slider(1, 10, value=2, step=1, label="IQR factor")
182
-
183
- # Dynamic Split Column dropdown
184
- split_column = gr.Dropdown(choices=[], label="Column to Split", interactive=True)
185
- split_sep = gr.Textbox(label="Split Separator", placeholder=", (comma) by default")
186
-
187
- run_btn = gr.Button("🧼 Run Cleaning")
188
-
189
- with gr.Column(scale=2):
190
- out_df = gr.DataFrame(label="Cleaned Data Preview", interactive=False)
191
- report = gr.Textbox(label="Cleaning Report", lines=20)
192
-
193
- # Function to populate split column dropdown dynamically after file upload
194
- def update_split_columns(file):
195
- if file is None:
196
- return []
197
- ext = os.path.splitext(file.name)[1].lower()
198
- try:
199
- if ext == ".csv":
200
- df = pd.read_csv(file.name, nrows=5)
201
- elif ext == ".xlsx":
202
- df = pd.read_excel(file.name, nrows=5)
203
- elif ext == ".json":
204
- df = pd.read_json(file.name)
205
- else:
206
- return []
207
- return df.columns.tolist()
208
- except Exception:
209
- return []
210
-
211
- file.change(update_split_columns, inputs=[file], outputs=[split_column])
212
-
213
- run_btn.click(
214
- clean_data,
215
- inputs=[file, null_strategy, custom_fill, dup_strategy, dup_subset,
216
- trim_spaces, normalize_case, convert_dtypes, parse_dates, date_cols_hint,
217
- outliers, z_thresh, iqr_factor,
218
- split_column, split_sep],
219
- outputs=[out_df, report]
220
- )
221
-
222
- if __name__ == "__main__":
223
- demo.launch()
 
5
 
6
  APP_TITLE = "🧹 Smart Data Cleaning Agent"
7
 
8
+ df_global = None # Global dataset
 
 
 
9
 
10
+ # --------------------
11
+ # Load dataset
12
+ # --------------------
13
+ def load_dataset(file):
14
+ global df_global
15
  if file is None:
16
+ return "❌ Please upload a dataset!", [], None
17
+ try:
18
+ ext = os.path.splitext(file.name)[1].lower()
19
+ if ext == ".csv":
20
+ df_global = pd.read_csv(file.name)
21
+ elif ext == ".xlsx":
22
+ df_global = pd.read_excel(file.name)
23
+ elif ext == ".json":
24
+ df_global = pd.read_json(file.name)
25
+ else:
26
+ return f"❌ Unsupported file format: {ext}", [], None
27
+ return "✅ Dataset loaded successfully!", df_global.columns.tolist(), df_global.head()
28
+ except Exception as e:
29
+ return f"❌ Error: {str(e)}", [], None
30
+
31
+ # --------------------
32
+ # Cleaning operations on a selected column
33
+ # --------------------
34
+ def clean_column(column, null_action, case_action):
35
+ global df_global
36
+ if df_global is None:
37
+ return "❌ Please upload a dataset first!", None
38
+ if column not in df_global.columns:
39
+ return f"❌ Column '{column}' not found!", None
40
+
41
+ # Null handling
42
+ if null_action == "Remove Nulls":
43
+ df_global[column] = df_global[column].dropna()
44
+ elif null_action == "Fill with Mean":
45
+ if pd.api.types.is_numeric_dtype(df_global[column]):
46
+ df_global[column].fillna(df_global[column].mean(), inplace=True)
47
+ elif null_action == "Fill with Median":
48
+ if pd.api.types.is_numeric_dtype(df_global[column]):
49
+ df_global[column].fillna(df_global[column].median(), inplace=True)
50
+ elif null_action == "Fill with Mode":
51
+ mode_val = df_global[column].mode()
52
+ if not mode_val.empty:
53
+ df_global[column].fillna(mode_val[0], inplace=True)
54
+
55
+ # Case conversion
56
+ if case_action == "Lowercase":
57
+ df_global[column] = df_global[column].astype(str).str.lower()
58
+ elif case_action == "Uppercase":
59
+ df_global[column] = df_global[column].astype(str).str.upper()
60
+
61
+ return f"✅ Cleaning applied to column '{column}'", df_global.head()
62
+
63
+ # --------------------
64
+ # Global cleaning options
65
+ # --------------------
66
+ def full_clean(file, trim_spaces, normalize_case, convert_dtypes, parse_dates, date_cols_hint,
67
+ dup_strategy, dup_subset, outliers, z_thresh, iqr_factor):
68
+ global df_global
69
+ if df_global is None or file is None:
70
+ return None, "❌ Please upload a dataset first!"
71
+
72
+ # Trim whitespace
73
  if trim_spaces:
74
+ obj_cols = df_global.select_dtypes(include=["object", "string"]).columns
75
  for c in obj_cols:
76
+ df_global[c] = df_global[c].astype(str).str.strip()
 
77
 
78
+ # Normalize case
79
  if normalize_case != "Keep case":
80
+ obj_cols = df_global.select_dtypes(include=["object", "string"]).columns
81
  if normalize_case == "lower()":
82
+ df_global[obj_cols] = df_global[obj_cols].apply(lambda c: c.astype(str).str.lower())
83
  elif normalize_case == "UPPER()":
84
+ df_global[obj_cols] = df_global[obj_cols].apply(lambda c: c.astype(str).str.upper())
85
  elif normalize_case == "Title Case":
86
+ df_global[obj_cols] = df_global[obj_cols].apply(lambda c: c.astype(str).str.title())
 
87
 
88
+ # Convert dtypes
89
  if convert_dtypes:
90
+ df_global = df_global.convert_dtypes()
 
91
 
92
+ # Parse dates
93
  if parse_dates:
94
  hinted = [c.strip() for c in date_cols_hint.split(",") if c.strip()]
95
+ target_cols = hinted if hinted else df_global.columns.tolist()
 
96
  for c in target_cols:
97
  try:
98
+ df_global[c] = pd.to_datetime(df_global[c], errors="ignore", infer_datetime_format=True)
99
+ except:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  pass
 
 
 
 
101
 
102
+ # Remove duplicates
103
  subset_cols = [c.strip() for c in dup_subset.split(",") if c.strip()] or None
104
  if dup_strategy == "Drop exact duplicates":
105
+ df_global.drop_duplicates(subset=subset_cols, keep="first", inplace=True)
 
106
  elif dup_strategy == "Drop duplicates (keep last)":
107
+ df_global.drop_duplicates(subset=subset_cols, keep="last", inplace=True)
 
108
 
109
  # Outliers
110
+ num_cols = df_global.select_dtypes(include=[np.number]).columns
111
  if outliers == "Clip by z-score (|z| > threshold)" and len(num_cols) > 0:
112
  thr = int(z_thresh)
113
  for c in num_cols:
114
+ col = df_global[c].astype(float)
115
  mu, sd = col.mean(), col.std(ddof=0)
116
  if sd and not np.isnan(sd):
117
  z = (col - mu) / sd
118
  mask = z.abs() > thr
119
  col_clipped = col.clip(lower=mu - thr*sd, upper=mu + thr*sd)
120
+ df_global[c] = col.where(~mask, col_clipped)
 
121
  elif outliers == "Clip by IQR (1.5×IQR fences)" and len(num_cols) > 0:
122
  factor = float(iqr_factor)
123
  for c in num_cols:
124
+ q1, q3 = df_global[c].quantile(0.25), df_global[c].quantile(0.75)
125
  iqr = q3 - q1
126
  if pd.notna(iqr) and iqr > 0:
127
  low = q1 - 1.5 * iqr * factor
128
  high = q3 + 1.5 * iqr * factor
129
+ df_global[c] = df_global[c].clip(lower=low, upper=high)
 
130
 
131
+ return df_global.head(), "✅ Full cleaning applied!"
 
 
 
 
 
 
132
 
133
+ # --------------------
134
+ # Gradio UI
135
+ # --------------------
136
+ with gr.Blocks(title=APP_TITLE) as demo:
137
+ gr.Markdown(f"# {APP_TITLE}")
138
+ gr.Markdown("Upload your dataset, apply global cleaning, or clean specific columns dynamically.")
139
 
140
+ with gr.Row():
141
+ file_input = gr.File(label="📂 Upload Dataset", file_types=[".csv", ".xlsx", ".json"])
142
+ status = gr.Textbox(label="Status", interactive=False)
143
 
144
+ with gr.Row():
145
+ # Global cleaning options
146
+ trim_spaces = gr.Checkbox(label="Trim whitespace", value=False)
147
+ normalize_case = gr.Dropdown(["Keep case", "lower()", "UPPER()", "Title Case"], value="Keep case")
148
+ convert_dtypes = gr.Checkbox(label="Auto convert dtypes", value=False)
149
+ parse_dates = gr.Checkbox(label="Try parse dates", value=False)
150
+ date_cols_hint = gr.Textbox(label="Date Columns Hint (comma separated)")
151
 
152
+ dup_strategy = gr.Dropdown(["Do nothing", "Drop exact duplicates", "Drop duplicates (keep last)"], value="Do nothing")
153
+ dup_subset = gr.Textbox(label="Subset Columns for Duplicates (comma separated)")
154
+
155
+ outliers = gr.Dropdown(["No outlier handling", "Clip by z-score (|z| > threshold)", "Clip by IQR (1.5×IQR fences)"], value="No outlier handling")
156
+ z_thresh = gr.Slider(1, 10, value=3, step=1)
157
+ iqr_factor = gr.Slider(1, 10, value=2, step=1)
158
 
159
  with gr.Row():
160
+ full_clean_btn = gr.Button("✨ Apply Full Cleaning")
161
+
162
+ with gr.Row():
163
+ # Column-level cleaning
164
+ column_dropdown = gr.Dropdown(label="📊 Select Column", choices=[], interactive=True)
165
+ null_action = gr.Radio(["Remove Nulls", "Fill with Mean", "Fill with Median", "Fill with Mode"], label="Handle Null Values")
166
+ case_action = gr.Radio(["None", "Lowercase", "Uppercase"], label="Case Conversion", value="None")
167
+ clean_column_btn = gr.Button("✨ Clean Selected Column")
168
+
169
+ output_table = gr.Dataframe(label="Preview Data (After Cleaning)", interactive=False)
170
+
171
+ # Events
172
+ file_input.change(load_dataset, inputs=file_input, outputs=[status, column_dropdown, output_table])
173
+ full_clean_btn.click(full_clean, inputs=[file_input, trim_spaces, normalize_case, convert_dtypes,
174
+ parse_dates, date_cols_hint, dup_strategy, dup_subset,
175
+ outliers, z_thresh, iqr_factor], outputs=[output_table, status])
176
+ clean_column_btn.click(clean_column, inputs=[column_dropdown, null_action, case_action], outputs=[status, output_table])
177
+
178
+ demo.launch()