sujithrajaR commited on
Commit
d4ba4cb
·
verified ·
1 Parent(s): 85d1df3

Create app.py

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