Spaces:
Sleeping
Sleeping
Download app.py from sujithrajaR/Datacleaning_agent: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/sujithrajaR/Datacleaning_agent/resolve/main/app.py
- Command line
-
hf download hf://spaces/sujithrajaR/Datacleaning_agent/app.py
-
curl -L -o app.py https://huggingface.co/spaces/sujithrajaR/Datacleaning_agent/resolve/main/app.py
10.5 kB
| 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) | |