Spaces:
Sleeping
Sleeping
File size: 10,477 Bytes
d4ba4cb ad24416 d4ba4cb ad24416 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 ad24416 78a7720 ad24416 78a7720 ad24416 82845cf 78a7720 ad24416 4c0c68a ad24416 78a7720 ad24416 78a7720 ad24416 78a7720 d4ba4cb 78a7720 fd51df0 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 d4ba4cb 78a7720 5c214fc ad24416 bcc0f8a 4c0c68a ad24416 78a7720 ad24416 d4ba4cb 4c0c68a 78a7720 d4ba4cb 4c0c68a 78a7720 d4ba4cb ad24416 78a7720 82845cf 4c0c68a ad24416 82845cf ad24416 78a7720 ad24416 78a7720 bcc0f8a | 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 | import gradio as gr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os, math
APP_TITLE = "π§Ή Smart Data Cleaning & Analysis Agent"
df_global = None # Global dataset
# --------------------
# Load dataset
# --------------------
def load_dataset(file):
global df_global
if file is None:
return "β Please upload a dataset!", [], None
try:
ext = os.path.splitext(file.name)[1].lower()
if ext == ".csv":
df_global = pd.read_csv(file.name)
elif ext == ".xlsx":
df_global = pd.read_excel(file.name)
elif ext == ".json":
df_global = pd.read_json(file.name)
else:
return f"β Unsupported file format: {ext}", [], None
return "β
Dataset loaded successfully!", df_global.columns.tolist(), df_global.head()
except Exception as e:
return f"β Error: {str(e)}", [], None
# --------------------
# Column-level cleaning / imputation
# --------------------
def clean_column(column, null_action, case_action, fill_value):
global df_global
if df_global is None:
return "β Please upload a dataset first!", None
if column not in df_global.columns:
return f"β Column '{column}' not found!", None
# Null handling / imputation
if null_action == "Fill with Mean":
if pd.api.types.is_numeric_dtype(df_global[column]):
df_global[column].fillna(df_global[column].mean(), inplace=True)
elif null_action == "Fill with Median":
if pd.api.types.is_numeric_dtype(df_global[column]):
df_global[column].fillna(df_global[column].median(), inplace=True)
elif null_action == "Fill with Mode":
mode_val = df_global[column].mode()
if not mode_val.empty:
df_global[column].fillna(mode_val[0], inplace=True)
elif null_action == "Fill with Constant":
if fill_value is not None and fill_value != "":
try:
val = float(fill_value) if pd.api.types.is_numeric_dtype(df_global[column]) else fill_value
df_global[column].fillna(val, inplace=True)
except:
df_global[column].fillna(fill_value, inplace=True)
elif null_action == "Forward Fill (ffill)":
df_global[column].fillna(method="ffill", inplace=True)
elif null_action == "Backward Fill (bfill)":
df_global[column].fillna(method="bfill", inplace=True)
if null_action == "Remove Nulls":
df_global = df_global[df_global[column].notna()]
# Case conversion
if pd.api.types.is_string_dtype(df_global[column]):
if case_action == "Lowercase":
df_global[column] = df_global[column].str.lower()
elif case_action == "Uppercase":
df_global[column] = df_global[column].str.upper()
return f"β
Cleaning applied to column '{column}'", df_global.head()
# --------------------
# Full dataset cleaning
# --------------------
def full_clean(file, trim_spaces, normalize_case, convert_dtypes, parse_dates, date_cols_hint,
dup_strategy, dup_subset, outliers, z_thresh, iqr_factor):
global df_global
if df_global is None or file is None:
return None, "β Please upload a dataset first!"
if trim_spaces:
obj_cols = df_global.select_dtypes(include=["object", "string"]).columns
for c in obj_cols:
df_global[c] = df_global[c].astype(str).str.strip()
if normalize_case != "Keep case":
obj_cols = df_global.select_dtypes(include=["object", "string"]).columns
if normalize_case == "lower()":
df_global[obj_cols] = df_global[obj_cols].apply(lambda c: c.astype(str).str.lower())
elif normalize_case == "UPPER()":
df_global[obj_cols] = df_global[obj_cols].apply(lambda c: c.astype(str).str.upper())
elif normalize_case == "Title Case":
df_global[obj_cols] = df_global[obj_cols].apply(lambda c: c.astype(str).str.title())
if convert_dtypes:
df_global = df_global.convert_dtypes()
if parse_dates:
hinted = [c.strip() for c in date_cols_hint.split(",") if c.strip()]
target_cols = hinted if hinted else df_global.columns.tolist()
for c in target_cols:
try:
df_global[c] = pd.to_datetime(df_global[c], errors="ignore", infer_datetime_format=True)
except:
pass
subset_cols = [c.strip() for c in dup_subset.split(",") if c.strip()] or None
if dup_strategy == "Drop exact duplicates":
df_global.drop_duplicates(subset=subset_cols, keep="first", inplace=True)
elif dup_strategy == "Drop duplicates (keep last)":
df_global.drop_duplicates(subset=subset_cols, keep="last", inplace=True)
num_cols = df_global.select_dtypes(include=[np.number]).columns
if outliers == "Clip by z-score (|z| > threshold)" and len(num_cols) > 0:
thr = int(z_thresh)
for c in num_cols:
col = df_global[c].astype(float)
mu, sd = col.mean(), col.std(ddof=0)
if sd and not np.isnan(sd):
z = (col - mu) / sd
mask = z.abs() > thr
col_clipped = col.clip(lower=mu - thr*sd, upper=mu + thr*sd)
df_global[c] = col.where(~mask, col_clipped)
elif outliers == "Clip by IQR (1.5ΓIQR fences)" and len(num_cols) > 0:
factor = float(iqr_factor)
for c in num_cols:
q1, q3 = df_global[c].quantile(0.25), df_global[c].quantile(0.75)
iqr = q3 - q1
if pd.notna(iqr) and iqr > 0:
low = q1 - 1.5 * iqr * factor
high = q3 + 1.5 * iqr * factor
df_global[c] = df_global[c].clip(lower=low, upper=high)
return df_global.head(), "β
Full cleaning applied!"
# --------------------
# Data visualization
# --------------------
def plot_column(column, plot_type):
global df_global
if df_global is None or column not in df_global.columns:
return None, "β Column not found or dataset not loaded!"
plt.figure(figsize=(6,4))
data = df_global[column].dropna()
numeric = pd.api.types.is_numeric_dtype(data)
try:
if plot_type == "Histogram":
if numeric:
sns.histplot(data, kde=True)
else:
sns.countplot(x=data)
elif plot_type == "Boxplot":
if numeric:
sns.boxplot(x=data)
else:
return None, "β Boxplot only works with numeric data"
elif plot_type == "Bar Plot":
if numeric:
sns.barplot(x=df_global.index, y=data)
else:
sns.countplot(x=data)
elif plot_type == "Scatter Plot":
num_cols = df_global.select_dtypes(include=[np.number]).columns
if len(num_cols) >= 2:
sns.scatterplot(x=df_global[num_cols[0]], y=df_global[num_cols[1]])
else:
return None, "β Not enough numeric columns for scatter plot"
except Exception as e:
return None, f"β Error plotting column: {str(e)}"
plt.tight_layout()
plt.savefig("temp_plot.png")
plt.close()
return "temp_plot.png", f"β
{plot_type} generated for column '{column}'"
# --------------------
# Gradio UI
# --------------------
with gr.Blocks(title=APP_TITLE) as demo:
gr.Markdown(f"# {APP_TITLE}")
gr.Markdown("Upload your dataset, clean it, and visualize columns dynamically.")
# File input
with gr.Row():
file_input = gr.File(label="π Upload Dataset", file_types=[".csv", ".xlsx", ".json"])
status = gr.Textbox(label="Status", interactive=False)
# Full cleaning options
with gr.Row():
trim_spaces = gr.Checkbox(label="Trim whitespace", value=False)
normalize_case = gr.Dropdown(["Keep case", "lower()", "UPPER()", "Title Case"], value="Keep case")
convert_dtypes = gr.Checkbox(label="Auto convert dtypes", value=False)
parse_dates = gr.Checkbox(label="Try parse dates", value=False)
date_cols_hint = gr.Textbox(label="Date Columns Hint (comma separated)")
dup_strategy = gr.Dropdown(["Do nothing", "Drop exact duplicates", "Drop duplicates (keep last)"], value="Do nothing")
dup_subset = gr.Textbox(label="Subset Columns for Duplicates (comma separated)")
outliers = gr.Dropdown(["No outlier handling", "Clip by z-score (|z| > threshold)", "Clip by IQR (1.5ΓIQR fences)"], value="No outlier handling")
z_thresh = gr.Slider(1, 10, value=3, step=1)
iqr_factor = gr.Slider(1, 10, value=2, step=1)
full_clean_btn = gr.Button("β¨ Apply Full Cleaning")
# Column-level cleaning
column_dropdown = gr.Dropdown(label="π Select Column", choices=[], interactive=True, allow_custom_value=True)
null_action = gr.Dropdown(["Remove Nulls", "Fill with Mean", "Fill with Median", "Fill with Mode",
"Fill with Constant", "Forward Fill (ffill)", "Backward Fill (bfill)"],
label="Handle Null Values")
fill_value = gr.Textbox(label="Constant Value (if 'Fill with Constant')", placeholder="Enter value here")
case_action = gr.Radio(["None", "Lowercase", "Uppercase"], label="Case Conversion", value="None")
clean_column_btn = gr.Button("β¨ Clean Selected Column")
# Data visualization
plot_type = gr.Dropdown(["Histogram", "Boxplot", "Bar Plot", "Scatter Plot"], label="Plot Type")
plot_btn = gr.Button("π Generate Plot")
plot_output = gr.Image(label="Plot Output")
output_table = gr.Dataframe(label="Preview Data (After Cleaning)", interactive=False)
# Events
file_input.change(load_dataset, inputs=file_input, outputs=[status, column_dropdown, output_table])
full_clean_btn.click(full_clean, inputs=[file_input, trim_spaces, normalize_case, convert_dtypes,
parse_dates, date_cols_hint, dup_strategy, dup_subset,
outliers, z_thresh, iqr_factor], outputs=[output_table, status])
clean_column_btn.click(clean_column, inputs=[column_dropdown, null_action, case_action, fill_value], outputs=[status, output_table])
plot_btn.click(plot_column, inputs=[column_dropdown, plot_type], outputs=[plot_output, status])
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|