datategrity / app.py
colesr
Claude Opus 4.7 (1M context)
Copilot: show billing-specific hint on HF Inference 402
4e85bc2
Raw History Blame Contribute Delete
101 kB
import gradio as gr import pandas as pd import numpy as np from huggingface_hub import InferenceClient import io import json import html import uuid from datetime import datetime import re # --------------------------------------------------------------------------- # UI theme + styling. Visual only — does not affect any application logic. # --------------------------------------------------------------------------- DATATEGRITY_THEME = gr.themes.Soft( primary_hue=gr.themes.Color( c50="#f8fafc", c100="#f1f5f9", c200="#e2e8f0", c300="#cbd5e1", c400="#94a3b8", c500="#64748b", c600="#475569", c700="#334155", c800="#1e293b", c900="#0f172a", c950="#020617", ), secondary_hue="slate", neutral_hue="slate", radius_size=gr.themes.sizes.radius_md, spacing_size=gr.themes.sizes.spacing_md, text_size=gr.themes.sizes.text_md, font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"], font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "Menlo", "monospace"], ).set( body_background_fill="#fafafa", body_background_fill_dark="#0a0a0a", background_fill_primary="#ffffff", background_fill_primary_dark="#111113", background_fill_secondary="#fafafa", background_fill_secondary_dark="#0d0d0f", border_color_primary="rgba(15, 23, 42, 0.08)", border_color_primary_dark="rgba(241, 245, 249, 0.08)", block_border_width="1px", block_shadow="none", block_radius="14px", block_label_background_fill="transparent", block_label_background_fill_dark="transparent", block_label_text_weight="500", block_title_text_weight="600", block_title_text_size="*text_md", button_large_radius="10px", button_small_radius="8px", button_primary_background_fill="#0f172a", button_primary_background_fill_hover="#1e293b", button_primary_background_fill_dark="#f8fafc", button_primary_background_fill_hover_dark="#e2e8f0", button_primary_text_color="#ffffff", button_primary_text_color_dark="#0f172a", button_primary_border_color="transparent", button_primary_border_color_dark="transparent", button_secondary_background_fill="#ffffff", button_secondary_background_fill_hover="#f8fafc", button_secondary_background_fill_dark="#1a1a1d", button_secondary_background_fill_hover_dark="#222227", button_secondary_text_color="#0f172a", button_secondary_text_color_dark="#f1f5f9", button_secondary_border_color="rgba(15, 23, 42, 0.08)", button_secondary_border_color_dark="rgba(241, 245, 249, 0.08)", input_background_fill="#ffffff", input_background_fill_dark="#141417", input_border_color="rgba(15, 23, 42, 0.08)", input_border_color_dark="rgba(241, 245, 249, 0.08)", input_border_color_focus="rgba(15, 23, 42, 0.3)", input_border_color_focus_dark="rgba(241, 245, 249, 0.3)", input_radius="10px", slider_color="#0f172a", slider_color_dark="#f1f5f9", ) DATATEGRITY_CSS = """ /* --- Container & typography ------------------------------------------- */ .gradio-container { max-width: 1240px !important; animation: dg-page-in 0.55s cubic-bezier(0.16, 1, 0.3, 1); } .gradio-container * { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } @keyframes dg-page-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } } /* --- Hero header ------------------------------------------------------ */ #dg-hero { padding: 1.8rem 0 1.4rem 0; border: none !important; background: transparent !important; } #dg-hero .dg-eyebrow { display: inline-flex; align-items: center; gap: 0.55rem; font-size: 0.72rem; font-weight: 500; letter-spacing: 0.14em; text-transform: uppercase; color: var(--body-text-color-subdued); margin-bottom: 0.95rem; opacity: 0; animation: dg-fade-up 0.7s 0.05s cubic-bezier(0.16, 1, 0.3, 1) forwards; } #dg-hero .dg-title { font-size: 2.35rem; font-weight: 600; line-height: 1.05; letter-spacing: -0.028em; margin: 0; background: linear-gradient(180deg, var(--body-text-color) 0%, color-mix(in srgb, var(--body-text-color) 70%, transparent) 130%); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; opacity: 0; animation: dg-fade-up 0.8s 0.12s cubic-bezier(0.16, 1, 0.3, 1) forwards; } #dg-hero .dg-sub { color: var(--body-text-color-subdued); font-size: 1.02rem; line-height: 1.55; margin: 0.6rem 0 0 0; max-width: 36rem; opacity: 0; animation: dg-fade-up 0.8s 0.2s cubic-bezier(0.16, 1, 0.3, 1) forwards; } @keyframes dg-fade-up { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } } .dg-live-dot { position: relative; width: 6px; height: 6px; background: #10b981; border-radius: 999px; } .dg-live-dot::after { content: ""; position: absolute; inset: -3px; border-radius: 999px; background: #10b981; opacity: 0.4; animation: dg-live-pulse 2.4s ease-in-out infinite; } @keyframes dg-live-pulse { 0% { transform: scale(0.6); opacity: 0.45; } 70% { transform: scale(2.2); opacity: 0; } 100% { transform: scale(2.2); opacity: 0; } } #dg-divider { height: 1px; background: linear-gradient(to right, transparent, var(--border-color-primary) 18%, var(--border-color-primary) 82%, transparent); margin: 0.25rem 0 1.6rem 0; border: none !important; padding: 0 !important; } /* --- Tabs ------------------------------------------------------------- */ .tab-nav { border-bottom: 1px solid var(--border-color-primary) !important; gap: 0.25rem !important; margin-bottom: 1.4rem !important; background: transparent !important; } button.tab-nav-button, button[role="tab"] { background: transparent !important; border: none !important; border-radius: 8px 8px 0 0 !important; font-weight: 500 !important; font-size: 0.92rem !important; padding: 0.7rem 1rem !important; color: var(--body-text-color-subdued) !important; position: relative; transition: color 0.2s ease, background 0.2s ease !important; } button[role="tab"]:hover { color: var(--body-text-color) !important; background: color-mix(in srgb, var(--body-text-color) 4%, transparent) !important; } button[role="tab"][aria-selected="true"] { color: var(--body-text-color) !important; } button[role="tab"][aria-selected="true"]::after { content: ""; position: absolute; left: 12%; right: 12%; bottom: -1px; height: 2px; border-radius: 2px; background: var(--body-text-color); animation: dg-tab-underline 0.35s cubic-bezier(0.16, 1, 0.3, 1); } @keyframes dg-tab-underline { from { transform: scaleX(0); opacity: 0; } to { transform: scaleX(1); opacity: 1; } } /* --- Section eyebrow headings (### in Markdown) ----------------------- */ .gradio-container h3 { font-weight: 600 !important; font-size: 0.78rem !important; text-transform: uppercase !important; letter-spacing: 0.08em !important; color: var(--body-text-color-subdued) !important; margin: 0.4rem 0 0.85rem 0 !important; } .gradio-container h1, .gradio-container h2 { letter-spacing: -0.015em; } /* --- Buttons ---------------------------------------------------------- */ .gr-button, button.lg, button.sm, button.primary, button.secondary { transition: transform 0.18s cubic-bezier(0.16, 1, 0.3, 1), box-shadow 0.22s ease, background 0.18s ease, border-color 0.18s ease !important; font-weight: 500 !important; letter-spacing: -0.005em; } .gr-button:hover, button.primary:hover, button.secondary:hover { transform: translateY(-1px); box-shadow: 0 6px 18px -10px rgba(15, 23, 42, 0.4) !important; } .gr-button:active, button.primary:active, button.secondary:active { transform: translateY(0); transition-duration: 60ms !important; } /* --- Blocks / cards --------------------------------------------------- */ .block, .form, .gr-box { transition: border-color 0.25s ease, box-shadow 0.25s ease !important; } .block:focus-within { border-color: color-mix(in srgb, var(--body-text-color) 22%, transparent) !important; } /* --- Inputs ----------------------------------------------------------- */ input[type="text"], input[type="password"], input[type="number"], textarea, select { transition: border-color 0.18s ease, box-shadow 0.18s ease, background 0.18s ease !important; } input[type="text"]:focus, input[type="password"]:focus, input[type="number"]:focus, textarea:focus, select:focus { box-shadow: 0 0 0 4px color-mix(in srgb, var(--body-text-color) 6%, transparent) !important; } /* mono feel for the rule/operation textareas */ .dg-mono textarea { font-family: var(--font-mono) !important; font-size: 0.88rem !important; line-height: 1.55 !important; } /* --- Dataframe / JSON ------------------------------------------------- */ .gr-dataframe, .gr-json { transition: opacity 0.25s ease; } /* --- Accordion -------------------------------------------------------- */ .label-wrap { transition: background 0.2s ease, color 0.2s ease !important; border-radius: 8px !important; padding: 0.45rem 0.6rem !important; } .label-wrap:hover { background: color-mix(in srgb, var(--body-text-color) 4%, transparent) !important; } /* --- File upload dropzone -------------------------------------------- */ .file-preview, .upload-container, [data-testid="file"] { transition: border-color 0.22s ease, background 0.22s ease !important; } .file-preview:hover, .upload-container:hover { border-color: color-mix(in srgb, var(--body-text-color) 22%, transparent) !important; } /* --- Footer + misc ---------------------------------------------------- */ footer { opacity: 0.55; transition: opacity 0.2s ease; } footer:hover { opacity: 1; } /* Slight column lift on tab switch */ .tabitem { animation: dg-fade-up 0.45s cubic-bezier(0.16, 1, 0.3, 1); } /* --- Copilot proposal cards (Phase 2) -------------------------------- */ .dg-proposals { display: flex; flex-direction: column; gap: 0.7rem; } .dg-proposal-card { border: 1px solid var(--border-color-primary); border-radius: 12px; padding: 0.85rem 0.95rem; background: var(--background-fill-primary); transition: border-color 0.25s ease, box-shadow 0.25s ease, transform 0.2s ease; animation: dg-card-in 0.4s cubic-bezier(0.16, 1, 0.3, 1); } .dg-proposal-card:hover { border-color: color-mix(in srgb, var(--body-text-color) 22%, transparent); box-shadow: 0 8px 24px -16px rgba(15, 23, 42, 0.4); transform: translateY(-1px); } @keyframes dg-card-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } } .dg-proposal-card.is-cleaning { border-left: 3px solid #6366f1; } .dg-proposal-card.is-validation { border-left: 3px solid #10b981; } .dg-card-head { display: flex; justify-content: space-between; align-items: center; font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--body-text-color-subdued); margin-bottom: 0.55rem; font-weight: 500; } .dg-card-id { font-family: var(--font-mono); font-size: 0.68rem; opacity: 0.6; letter-spacing: 0; text-transform: none; } .dg-card-payload { font-family: var(--font-mono); font-size: 0.83rem; line-height: 1.5; background: color-mix(in srgb, var(--body-text-color) 5%, transparent); border-radius: 6px; padding: 0.5rem 0.65rem; margin-bottom: 0.55rem; word-break: break-word; white-space: pre-wrap; } .dg-card-rationale { color: var(--body-text-color-subdued); font-size: 0.87rem; line-height: 1.55; } .dg-proposal-empty { color: var(--body-text-color-subdued); font-size: 0.88rem; padding: 1.4rem 1rem; border: 1px dashed var(--border-color-primary); border-radius: 12px; text-align: center; background: color-mix(in srgb, var(--body-text-color) 2%, transparent); } /* Recipe timeline */ .dg-recipe { display: flex; flex-direction: column; gap: 0.55rem; } .dg-recipe-item { display: flex; align-items: flex-start; gap: 0.7rem; padding: 0.55rem 0.7rem; border-radius: 8px; background: color-mix(in srgb, var(--body-text-color) 3%, transparent); transition: background 0.2s ease; animation: dg-card-in 0.35s cubic-bezier(0.16, 1, 0.3, 1); } .dg-recipe-item:hover { background: color-mix(in srgb, var(--body-text-color) 5%, transparent); } .dg-recipe-icon { flex: 0 0 auto; width: 22px; height: 22px; border-radius: 999px; display: inline-flex; align-items: center; justify-content: center; font-size: 0.7rem; color: white; background: #6366f1; } .dg-recipe-icon.is-validation { background: #10b981; } .dg-recipe-body { flex: 1 1 auto; min-width: 0; } .dg-recipe-meta { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.08em; color: var(--body-text-color-subdued); margin-bottom: 0.15rem; } .dg-recipe-payload { font-family: var(--font-mono); font-size: 0.8rem; word-break: break-word; } .dg-recipe-empty { color: var(--body-text-color-subdued); font-size: 0.85rem; padding: 0.85rem; border: 1px dashed var(--border-color-primary); border-radius: 10px; text-align: center; } """ def analyze_data_quality(df, columns=None): """Comprehensive data quality analysis""" if df is None or df.empty: return {"error": "DataFrame is empty"} if columns is None: columns = df.columns.tolist() analysis = { "dataset_info": { "rows": len(df), "columns": len(df.columns), "memory_usage": round(df.memory_usage(deep=True).sum() / 1024**2, 2), # MB }, "column_analysis": {}, "missing_values": {}, "duplicate_rows": int(df.duplicated().sum()) } for col in columns: col_data = df[col] analysis["column_analysis"][col] = { "dtype": str(col_data.dtype), "non_null": int(col_data.count()), "null_count": int(col_data.isna().sum()), "null_percentage": round(col_data.isna().mean() * 100, 2), "unique_values": int(col_data.nunique()), } if pd.api.types.is_numeric_dtype(col_data): analysis["column_analysis"][col].update({ "min": float(col_data.min()), "max": float(col_data.max()), "mean": round(float(col_data.mean()), 2), "std": round(float(col_data.std()), 2), "skewness": round(float(col_data.skew()), 2) }) elif pd.api.types.is_string_dtype(col_data): analysis["column_analysis"][col]["sample_values"] = col_data.dropna().head(3).tolist() # Missing values matrix analysis["missing_values"]["total_missing"] = int(df.isna().sum().sum()) analysis["missing_values"]["missing_by_column"] = {k: int(v) for k, v in df.isna().sum().to_dict().items()} return analysis def detect_anomalies(df, column, method="zscore"): """Detect anomalies in numerical column""" if df is None or df.empty: return {"error": "No data loaded"} if column is None or column not in df.columns: return {"error": "Invalid column selected"} if not pd.api.types.is_numeric_dtype(df[column]): return {"error": "Column must be numeric"} data = df[column].dropna() if len(data) == 0: return {"error": "No valid data in column"} if method == "zscore": z_scores = np.abs((data - data.mean()) / data.std()) threshold = 3 anomalies = data[z_scores > threshold] elif method == "iqr": q1 = data.quantile(0.25) q3 = data.quantile(0.75) iqr = q3 - q1 anomalies = data[(data < q1 - 1.5 * iqr) | (data > q3 + 1.5 * iqr)] else: return {"error": "Invalid method"} return { "method": method, "total_anomalies": int(len(anomalies)), "anomaly_percentage": round(float(len(anomalies) / len(data)) * 100, 2) if len(data) > 0 else 0, "anomaly_indices": anomalies.index.tolist()[:10], # First 10 indices "anomaly_values": [float(x) for x in anomalies.values[:10]] # First 10 values } def generate_data_quality_report(df): """Generate comprehensive data quality report""" if df is None or df.empty: return "# Error: No data loaded" analysis = analyze_data_quality(df) report = f"""# Data Quality Report ## Dataset Overview - **Total Rows**: {analysis['dataset_info']['rows']} - **Total Columns**: {analysis['dataset_info']['columns']} - **Memory Usage**: {analysis['dataset_info']['memory_usage']:.2f} MB - **Duplicate Rows**: {analysis['duplicate_rows']} ## Missing Values Summary - **Total Missing Values**: {analysis['missing_values']['total_missing']} - **Missing by Column**: {json.dumps(analysis['missing_values']['missing_by_column'], indent=2)} ## Column Analysis """ for col, stats in analysis['column_analysis'].items(): report += f""" ### {col} - **Data Type**: {stats['dtype']} - **Non-null Values**: {stats['non_null']} ({100 - stats['null_percentage']}%) - **Null Values**: {stats['null_count']} ({stats['null_percentage']}%) - **Unique Values**: {stats['unique_values']} """ if 'min' in stats: report += f"- **Min**: {stats['min']}, **Max**: {stats['max']}, **Mean**: {stats['mean']}, **Std**: {stats['std']}\n" return report def chat_with_data(df, message, history, hf_token): """AI-powered data analysis assistant""" if df is None or df.empty: yield "Please upload data first." return try: if not hf_token or hf_token.strip() == "": yield "⚠️ Please provide a valid Hugging Face token in the Settings tab. Get one from https://huggingface.co/settings/tokens" return client = InferenceClient(token=hf_token.strip(), model="openai/gpt-oss-20b") # Create context from data data_context = f""" Dataset Information: - Rows: {len(df)} - Columns: {list(df.columns)} - Data types: {df.dtypes.to_dict()} Sample Data (first 5 rows): {df.head().to_string()} """ # Build conversation context messages = [ {"role": "system", "content": f"""You are an expert data analyst assistant. Use the following dataset information to answer questions about the data: {data_context} When asked about data quality, anomalies, or statistics, use the dataset context provided. Be concise and focus on actionable insights."""}, *history, {"role": "user", "content": message} ] response = "" for message_response in client.chat_completion( messages, max_tokens=1024, stream=True, temperature=0.7, top_p=0.95, ): choices = message_response.choices if len(choices) and choices[0].delta.content: response += choices[0].delta.content yield response except Exception as e: yield f"❌ Error: {str(e)}\n\n💡 Make sure your Hugging Face token is valid and has the necessary permissions." def validate_data_integrity(df, rules): """Validate data against business rules""" if df is None or df.empty: return pd.DataFrame([{"rule": "No data", "passed": False, "error": "Upload data first"}]) if not rules or not rules.strip(): return pd.DataFrame([{"rule": "No rules provided", "passed": True, "notes": "Please enter validation rules in format: column:type:param"}]) results = [] try: for rule in [r.strip() for r in rules.split(',') if r.strip()]: try: # Parse rule (simple format: "column:rule_type:parameter") if ':' in rule: parts = rule.split(':') if len(parts) == 3: column, rule_type, parameter = parts if column not in df.columns: results.append({ "rule": f"{column} (column not found)", "passed": False, "error": f"Column '{column}' not in dataset" }) continue if rule_type == "null": invalid = int(df[column].isna().sum()) total = len(df) results.append({ "rule": f"{column} must not be null", "passed": invalid == 0, "violations": invalid, "total_rows": total, "compliance_rate": round((total - invalid) / total * 100, 2) if total > 0 else 0 }) elif rule_type == "unique": duplicates = int(df.duplicated(subset=[column]).sum()) results.append({ "rule": f"{column} must be unique", "passed": duplicates == 0, "violations": duplicates, "total_rows": len(df), "compliance_rate": round((len(df) - duplicates) / len(df) * 100, 2) if len(df) > 0 else 0 }) elif rule_type == "range": min_val, max_val = map(float, parameter.split(',')) violations = int(((df[column] < min_val) | (df[column] > max_val)).sum()) results.append({ "rule": f"{column} must be in range [{min_val}, {max_val}]", "passed": violations == 0, "violations": violations, "total_rows": len(df), "compliance_rate": round((len(df) - violations) / len(df) * 100, 2) if len(df) > 0 else 0 }) else: results.append({ "rule": rule, "passed": False, "error": f"Unknown rule type: {rule_type}" }) else: results.append({ "rule": rule, "passed": False, "error": "Invalid rule format (expected: column:type:param)" }) else: results.append({ "rule": rule, "passed": False, "error": "Invalid rule format (expected: column:type:param)" }) except Exception as e: results.append({ "rule": rule, "passed": False, "error": str(e) }) except Exception as e: results.append({ "rule": "Batch validation", "passed": False, "error": f"Validation failed: {str(e)}" }) return pd.DataFrame(results) def clean_data(df, operations): """Apply data cleaning operations""" if df is None or df.empty: return pd.DataFrame([["No data", "Please upload data first"]], columns=["Column", "Action"]) if not operations or not operations.strip(): return df.head(10) cleaned_df = df.copy() results = [] try: for operation in [op.strip() for op in operations.split(',') if op.strip()]: try: if ':' in operation: parts = operation.split(':') if len(parts) == 2: column, op_type = parts if column not in cleaned_df.columns: results.append([column, f"Column not found"]) continue original_count = len(cleaned_df) if op_type == "drop_null": cleaned_df = cleaned_df.dropna(subset=[column]) results.append([column, f"Dropped {original_count - len(cleaned_df)} null rows"]) elif op_type == "fill_mean": if pd.api.types.is_numeric_dtype(cleaned_df[column]): mean_val = cleaned_df[column].mean() cleaned_df[column] = cleaned_df[column].fillna(mean_val) results.append([column, f"Filled nulls with mean: {round(mean_val, 2)}"]) else: results.append([column, "Cannot fill mean - column not numeric"]) elif op_type == "fill_median": if pd.api.types.is_numeric_dtype(cleaned_df[column]): median_val = cleaned_df[column].median() cleaned_df[column] = cleaned_df[column].fillna(median_val) results.append([column, f"Filled nulls with median: {round(median_val, 2)}"]) else: results.append([column, "Cannot fill median - column not numeric"]) elif op_type == "lowercase": cleaned_df[column] = cleaned_df[column].astype(str).str.lower() results.append([column, "Converted to lowercase"]) elif op_type == "trim": cleaned_df[column] = cleaned_df[column].astype(str).str.strip() results.append([column, "Trimmed whitespace"]) else: results.append([column, f"Unknown operation: {op_type}"]) else: results.append([operation, "Invalid operation format"]) except Exception as e: results.append([operation, f"Error: {str(e)}"]) except Exception as e: results.append(["Batch cleaning", f"Failed: {str(e)}"]) # Return cleaned preview if no specific results, otherwise return results if not results: return cleaned_df.head(10) return pd.DataFrame(results, columns=["Column", "Action"]).head(20) def get_completion_suggestions(text, columns, rule_types=["null", "unique", "range"]): """Generate real-time suggestions for business rules""" if not text or not columns: return [] # Parse the current text to get partial rule parts = text.split(':') current_part = parts[-1].strip() if parts else "" suggestions = [] # If we're at the beginning of a rule (before first colon) if len(parts) == 1 and current_part: # Suggest columns that start with the current text matching_columns = [col for col in columns if col.lower().startswith(current_part.lower())] suggestions = [f"{col}:" for col in matching_columns[:5]] # If we have column but no rule type (after first colon, before second) elif len(parts) == 2 and current_part: # Suggest rule types that start with current text matching_rules = [rule for rule in rule_types if rule.lower().startswith(current_part.lower())] if "range" in matching_rules: suggestions = [f"{rule}:" for rule in matching_rules[:4]] suggestions.append("range:0,1000") # Special case for range else: suggestions = [f"{rule}:" for rule in matching_rules[:4]] # If we have column and rule type but no parameter (after second colon) elif len(parts) >= 3 and current_part and parts[-2].strip() == "range": # For range rules, suggest common value patterns if current_part in ["", "0", "1"]: suggestions = ["0,100", "0,1000", "1,100", "-100,100"] else: # Try to parse current input and suggest completion try: current_vals = current_part.split(',') if len(current_vals) == 1: suggestions = [f"{current_vals[0]},100", f"{current_vals[0]},1000"] elif len(current_vals) == 2: suggestions = [f"{current_vals[0]},{current_vals[1]}"] except: pass return suggestions[:5] # Return up to 5 suggestions # --------------------------------------------------------------------------- # Phase 1 Copilot: a small agent loop on top of read-only tools that wrap the # existing handlers. No data mutation — surfacing only. Approval UX and # mutating tools land in Phase 2. # --------------------------------------------------------------------------- AGENT_DEFAULT_MODEL = "meta-llama/Llama-3.3-70B-Instruct" AGENT_FALLBACK_MODELS = [ "meta-llama/Llama-3.3-70B-Instruct", "Qwen/Qwen2.5-72B-Instruct", "meta-llama/Meta-Llama-3.1-70B-Instruct", ] AGENT_DEFAULT_MAX_STEPS = 6 AGENT_TOOLS = [ { "type": "function", "function": { "name": "profile_dataset", "description": ( "Compute a comprehensive data-quality profile of the currently loaded " "dataset: row/column counts, per-column dtypes, null counts, unique " "counts, and numeric summaries (min/max/mean/std/skew). Call this " "first to learn the schema before answering specific questions." ), "parameters": { "type": "object", "properties": { "columns": { "type": "array", "items": {"type": "string"}, "description": "Optional subset of columns. Omit to profile all columns.", } }, "required": [], }, }, }, { "type": "function", "function": { "name": "detect_anomalies", "description": ( "Detect anomalies in a single numeric column using z-score (default) " "or IQR. Returns count, percentage, and sample anomalous indices/values." ), "parameters": { "type": "object", "properties": { "column": {"type": "string", "description": "Numeric column to scan."}, "method": { "type": "string", "enum": ["zscore", "iqr"], "description": "Detection method. Defaults to zscore.", }, }, "required": ["column"], }, }, }, { "type": "function", "function": { "name": "dry_run_rules", "description": ( "Evaluate validation rules against the dataset WITHOUT modifying it. " "Rules use the Datategrity DSL: comma-separated entries of the form " "`column:rule_type:param`, where rule_type is `null`, `unique`, or " "`range`. Examples: `id:unique`, `price:range:0,1000`, `email:null`. " "Returns per-rule pass/fail and compliance rate." ), "parameters": { "type": "object", "properties": { "rules": { "type": "string", "description": "Comma-separated rules in `column:rule_type:param` format.", } }, "required": ["rules"], }, }, }, { "type": "function", "function": { "name": "propose_validation_rules", "description": ( "Queue one or more validation rules for the user to review and apply. " "Use after profiling to suggest checks for the user to approve. Rules " "use the Datategrity DSL: comma-separated `column:rule_type:param` " "(rule_type: `null`, `unique`, `range:min,max`). The user sees each " "proposal as a card and decides whether to apply." ), "parameters": { "type": "object", "properties": { "rules": { "type": "string", "description": "Comma-separated rules in DSL form.", }, "rationale": { "type": "string", "description": "Short justification — why these rules, what data signals motivated them.", }, }, "required": ["rules", "rationale"], }, }, }, { "type": "function", "function": { "name": "propose_cleaning_operations", "description": ( "Queue one or more cleaning operations for the user to review and " "apply. Applying a cleaning proposal MUTATES the dataset, so always " "explain the rationale clearly. Operations use the Datategrity DSL: " "comma-separated `column:operation` where operation is one of " "`drop_null`, `fill_mean`, `fill_median`, `lowercase`, `trim`." ), "parameters": { "type": "object", "properties": { "operations": { "type": "string", "description": "Comma-separated cleaning ops in DSL form.", }, "rationale": { "type": "string", "description": "Short justification — why these operations, supported by data signals.", }, }, "required": ["operations", "rationale"], }, }, }, ] AGENT_SYSTEM_PROMPT = """You are Datategrity Copilot — a data-quality analyst working alongside the user inside the Datategrity workbench. You have five tools that operate on the dataset the user has uploaded: Read-only (inspect without changing anything): - `profile_dataset` — overall quality profile (call this first to learn the schema) - `detect_anomalies` — anomaly scan on a single numeric column - `dry_run_rules` — evaluate validation rules without mutating data Staged proposals (queue an action for the user to review and approve — they appear as cards in the right panel): - `propose_validation_rules` — suggest checks for the user to approve. Applying re-evaluates them against the current data. - `propose_cleaning_operations` — suggest cleaning ops. Applying MUTATES the dataset. Use sparingly and always with a clear rationale. Working style: - Be concise. Lead with the finding, then the supporting evidence. - Always inspect via tools before answering specific factual questions. Do not guess column names or values. - Typical flow: profile → identify risks → propose rules → if violations exist, propose minimal, conservative cleaning ops to address them. - Use the Datategrity DSL for both rules (`column:rule_type:param`) and cleaning ops (`column:operation`). - When you queue a proposal, briefly tell the user what you proposed and why. Don't dump the full DSL into chat — the card already shows it. - If the user asks a general question (definitions, advice), answer directly without calling tools.""" def _truncate_profile(profile, max_columns=40): """Trim analyze_data_quality output so wide datasets fit the model context.""" if not isinstance(profile, dict) or "column_analysis" not in profile: return profile cols = profile["column_analysis"] if len(cols) <= max_columns: return profile trimmed = dict(list(cols.items())[:max_columns]) out = {**profile, "column_analysis": trimmed} out["_note"] = ( f"column_analysis truncated to first {max_columns} of {len(cols)} columns " f"to fit context. Re-call profile_dataset with `columns` set to inspect specific ones." ) return out def _make_proposal_id(): return f"prop_{uuid.uuid4().hex[:6]}" def _make_recipe_id(): return f"rec_{uuid.uuid4().hex[:6]}" def _run_cleaning_ops(df, operations): """Apply cleaning operations purely and return (cleaned_df, action_log). Mirrors the per-op logic in clean_data() but isolates it from clean_data's UI-shaped return value so the Copilot apply path can both mutate the dataframe AND surface a structured action log. """ action_log = [] if df is None or df.empty: return df, [{"column": "(none)", "action": "no data loaded"}] cleaned = df.copy() for raw in (operations or "").split(","): op = raw.strip() if not op: continue if ":" not in op: action_log.append({"column": op, "action": "invalid format"}) continue parts = op.split(":") if len(parts) != 2: action_log.append({"column": op, "action": "invalid format"}) continue column, op_type = parts[0].strip(), parts[1].strip() if column not in cleaned.columns: action_log.append({"column": column, "action": "column not found"}) continue try: before = len(cleaned) if op_type == "drop_null": cleaned = cleaned.dropna(subset=[column]) action_log.append({"column": column, "action": f"dropped {before - len(cleaned)} null rows"}) elif op_type == "fill_mean": if pd.api.types.is_numeric_dtype(cleaned[column]): mean_val = cleaned[column].mean() cleaned[column] = cleaned[column].fillna(mean_val) action_log.append({"column": column, "action": f"filled nulls with mean ({round(float(mean_val), 2)})"}) else: action_log.append({"column": column, "action": "skipped — not numeric"}) elif op_type == "fill_median": if pd.api.types.is_numeric_dtype(cleaned[column]): median_val = cleaned[column].median() cleaned[column] = cleaned[column].fillna(median_val) action_log.append({"column": column, "action": f"filled nulls with median ({round(float(median_val), 2)})"}) else: action_log.append({"column": column, "action": "skipped — not numeric"}) elif op_type == "lowercase": cleaned[column] = cleaned[column].astype(str).str.lower() action_log.append({"column": column, "action": "converted to lowercase"}) elif op_type == "trim": cleaned[column] = cleaned[column].astype(str).str.strip() action_log.append({"column": column, "action": "trimmed whitespace"}) else: action_log.append({"column": column, "action": f"unknown operation: {op_type}"}) except Exception as e: action_log.append({"column": column, "action": f"error: {type(e).__name__}: {e}"}) return cleaned, action_log def _render_proposals_html(proposals): """Render the pending-proposals panel as HTML cards.""" proposals = list(proposals or []) if not proposals: return ( "<div class='dg-proposal-empty'>No pending proposals yet — ask the " "Copilot to suggest validation rules or cleaning operations.</div>" ) cards = ["<div class='dg-proposals'>"] for p in proposals: kind = p.get("kind", "validation") if kind == "cleaning": kind_label = "Cleaning operations" kind_class = "is-cleaning" else: kind_label = "Validation rules" kind_class = "is-validation" payload = html.escape(p.get("payload", "")) rationale = html.escape(p.get("rationale", "")) prop_id = html.escape(p.get("id", "")) cards.append( f"<div class='dg-proposal-card {kind_class}'>" f"<div class='dg-card-head'><span>{kind_label}</span>" f"<span class='dg-card-id'>{prop_id}</span></div>" f"<div class='dg-card-payload'>{payload}</div>" f"<div class='dg-card-rationale'>{rationale}</div>" f"</div>" ) cards.append("</div>") return "\n".join(cards) def _proposal_choices(proposals): """Build the (label, value) list for the proposal selector radio.""" proposals = list(proposals or []) choices = [] for p in proposals: kind = p.get("kind", "validation") snippet = (p.get("payload", "") or "").strip() if len(snippet) > 48: snippet = snippet[:45] + "…" label = f"{p.get('id', '?')} · {kind} · {snippet}" choices.append((label, p.get("id", ""))) return choices def _render_recipe_md(recipe): """Render the recipe (applied actions) as an HTML timeline.""" recipe = list(recipe or []) if not recipe: return "<div class='dg-recipe-empty'>No actions applied yet.</div>" items = ["<div class='dg-recipe'>"] for entry in recipe: kind = entry.get("kind", "validation") icon_class = "is-validation" if kind == "validation" else "" icon_char = "✓" if kind == "validation" else "★" applied = html.escape(entry.get("applied_at", "")) payload = html.escape(entry.get("payload", "")) rec_id = html.escape(entry.get("id", "")) items.append( f"<div class='dg-recipe-item'>" f"<span class='dg-recipe-icon {icon_class}'>{icon_char}</span>" f"<div class='dg-recipe-body'>" f"<div class='dg-recipe-meta'>{kind} · {applied} · {rec_id}</div>" f"<div class='dg-recipe-payload'>{payload}</div>" f"</div></div>" ) items.append("</div>") return "\n".join(items) def _proposal_summary(proposal): """Short human-friendly description of a proposal for chat confirmation.""" payload = proposal.get("payload", "") if proposal.get("kind") == "cleaning": n = len([p for p in payload.split(",") if p.strip()]) return f"cleaning ({n} op{'s' if n != 1 else ''})" n = len([p for p in payload.split(",") if p.strip()]) return f"validation ({n} rule{'s' if n != 1 else ''})" def _dispatch_tool(name, args, df): """Execute one tool call. Returns (result_dict, optional_proposal_dict).""" if df is None or (hasattr(df, "empty") and df.empty): return {"error": "No dataset is loaded. Ask the user to upload a CSV/Excel file."}, None try: if name == "profile_dataset": cols = args.get("columns") or None return _truncate_profile(analyze_data_quality(df, cols)), None if name == "detect_anomalies": return detect_anomalies(df, args.get("column"), args.get("method", "zscore")), None if name == "dry_run_rules": result_df = validate_data_integrity(df, args.get("rules", "")) return {"results": result_df.to_dict(orient="records")}, None if name == "propose_validation_rules": rules = (args.get("rules") or "").strip() if not rules: return {"error": "No rules supplied."}, None proposal = { "id": _make_proposal_id(), "kind": "validation", "payload": rules, "rationale": (args.get("rationale") or "").strip(), "created_at": datetime.now().isoformat(timespec="seconds"), } return { "proposal_id": proposal["id"], "status": "queued for user approval", "summary": f"Queued {len(rules.split(','))} validation rule(s) for the user to review.", }, proposal if name == "propose_cleaning_operations": ops = (args.get("operations") or "").strip() if not ops: return {"error": "No operations supplied."}, None proposal = { "id": _make_proposal_id(), "kind": "cleaning", "payload": ops, "rationale": (args.get("rationale") or "").strip(), "created_at": datetime.now().isoformat(timespec="seconds"), } return { "proposal_id": proposal["id"], "status": "queued for user approval", "summary": ( f"Queued {len(ops.split(','))} cleaning operation(s). " "Applying will MUTATE the dataset." ), }, proposal return {"error": f"Unknown tool: {name}"}, None except Exception as e: return {"error": f"Tool '{name}' raised {type(e).__name__}: {e}"}, None def _dataset_hint(df): """A short hint about the loaded dataset appended to the system prompt.""" if df is None or (hasattr(df, "empty") and df.empty): return "\n\nNote: No dataset is currently loaded." try: cols = ", ".join(f"`{c}` ({d})" for c, d in df.dtypes.astype(str).items()) return ( f"\n\nDataset currently loaded: {len(df)} rows × {len(df.columns)} columns.\n" f"Schema: {cols}" ) except Exception: return "" def run_copilot_turn(user_message, chat_history, trace, proposals, df, hf_token, model_id, max_steps, profile: gr.OAuthProfile | None = None, oauth_token: gr.OAuthToken | None = None): """Run a single Copilot turn end-to-end. Returns: (chat_history, trace, proposals, proposals_html, proposal_selector_update). Proposals accumulate across turns until the user applies or rejects them. Prefers the OAuth token over the manual hf_token when both are present. """ chat_history = list(chat_history or []) trace = list(trace or []) proposals = list(proposals or []) def _outputs(history, trace_, props): return ( history, trace_, props, _render_proposals_html(props), gr.update(choices=_proposal_choices(props), value=None), ) if not user_message or not user_message.strip(): return _outputs(chat_history, trace, proposals) effective_token = (oauth_token.token if oauth_token else None) or (hf_token or "").strip() if not effective_token: chat_history.append({"role": "user", "content": user_message}) chat_history.append({ "role": "assistant", "content": "⚠️ Sign in with Hugging Face (Settings) or add a manual HF token to use the Copilot.", }) return _outputs(chat_history, trace, proposals) if df is None or (hasattr(df, "empty") and df.empty): chat_history.append({"role": "user", "content": user_message}) chat_history.append({ "role": "assistant", "content": "Please upload a dataset on the **Upload & Explore** tab first — the Copilot's tools operate on the loaded data.", }) return _outputs(chat_history, trace, proposals) # Build OpenAI-style message list from chat history + this turn messages = [{"role": "system", "content": AGENT_SYSTEM_PROMPT + _dataset_hint(df)}] for turn in chat_history: if turn.get("role") in ("user", "assistant") and turn.get("content"): messages.append({"role": turn["role"], "content": turn["content"]}) messages.append({"role": "user", "content": user_message}) chat_history.append({"role": "user", "content": user_message}) model = (model_id or AGENT_DEFAULT_MODEL).strip() or AGENT_DEFAULT_MODEL client = InferenceClient(token=effective_token, model=model) steps = int(max_steps) if max_steps else AGENT_DEFAULT_MAX_STEPS final_text = "" new_proposals_this_turn = [] hit_step_cap = True for _ in range(steps): try: response = client.chat_completion( messages=messages, tools=AGENT_TOOLS, tool_choice="auto", max_tokens=1024, temperature=0.3, ) except Exception as e: err_text = str(e) is_402 = "402" in err_text or "Payment Required" in err_text or "depleted" in err_text.lower() if is_402: hint = ( "💡 Your Hugging Face Inference credits are exhausted. " "Subscribe to HF PRO or add pre-paid credits at " "https://huggingface.co/settings/billing, then retry." ) else: hint = ( f"💡 Confirm your HF token is valid and that `{model}` supports tool calling. " f"Try one of: {', '.join(AGENT_FALLBACK_MODELS)}." ) final_text = f"❌ Copilot error: {type(e).__name__}: {e}\n\n{hint}" hit_step_cap = False break msg = response.choices[0].message tool_calls = getattr(msg, "tool_calls", None) or [] assistant_msg = {"role": "assistant", "content": msg.content or ""} if tool_calls: assistant_msg["tool_calls"] = [ { "id": tc.id, "type": "function", "function": { "name": tc.function.name, "arguments": tc.function.arguments, }, } for tc in tool_calls ] messages.append(assistant_msg) if not tool_calls: final_text = msg.content or "" hit_step_cap = False break for tc in tool_calls: try: args = json.loads(tc.function.arguments or "{}") except json.JSONDecodeError: args = {} result, new_proposal = _dispatch_tool(tc.function.name, args, df) if new_proposal: proposals.append(new_proposal) new_proposals_this_turn.append(new_proposal) trace.append({"tool": tc.function.name, "args": args, "result": result}) messages.append({ "role": "tool", "tool_call_id": tc.id, "name": tc.function.name, "content": json.dumps(result, default=str)[:6000], }) if hit_step_cap and not final_text: final_text = ( "(Hit the tool-call step limit before producing a final answer. " "Try rephrasing, or raise **Max tool-call steps** in Settings.)" ) # If the agent queued proposals but didn't narrate them, prepend a hint if new_proposals_this_turn and final_text and "propos" not in final_text.lower(): summary = ", ".join(p["id"] for p in new_proposals_this_turn) final_text = ( f"_Queued proposals for your review: {summary} — see the right panel._\n\n" f"{final_text}" ) chat_history.append({"role": "assistant", "content": final_text or "(empty response)"}) return _outputs(chat_history, trace, proposals) def apply_proposal(prop_id, df, proposals, recipe, chat_history, rules_input_value): """Apply the selected proposal. Mutates data_state for cleaning kind only. Returns: (df, proposals, recipe, proposals_html, selector_update, recipe_html, chat_history, rules_input_value) """ proposals = list(proposals or []) recipe = list(recipe or []) chat_history = list(chat_history or []) rules_input_value = rules_input_value or "" def _bundle(_df, _props, _recipe, _chat, _rules): return ( _df, _props, _recipe, _render_proposals_html(_props), gr.update(choices=_proposal_choices(_props), value=None), _render_recipe_md(_recipe), _chat, _rules, ) if not prop_id: chat_history.append({"role": "assistant", "content": "_Select a proposal first._"}) return _bundle(df, proposals, recipe, chat_history, rules_input_value) target = next((p for p in proposals if p.get("id") == prop_id), None) if target is None: chat_history.append({"role": "assistant", "content": f"_Could not find proposal `{prop_id}`._"}) return _bundle(df, proposals, recipe, chat_history, rules_input_value) if df is None or (hasattr(df, "empty") and df.empty): chat_history.append({"role": "assistant", "content": "_No dataset is loaded — upload one first._"}) return _bundle(df, proposals, recipe, chat_history, rules_input_value) timestamp = datetime.now().isoformat(timespec="seconds") kind = target.get("kind", "validation") payload = target.get("payload", "") if kind == "cleaning": cleaned, action_log = _run_cleaning_ops(df, payload) new_df = cleaned recipe_entry = { "id": _make_recipe_id(), "kind": "cleaning", "payload": payload, "rationale": target.get("rationale", ""), "applied_at": timestamp, "actions": action_log, "rows_before": int(len(df)), "rows_after": int(len(cleaned)), } action_lines = "\n".join(f"- `{a['column']}` → {a['action']}" for a in action_log) chat_msg = ( f"✓ Applied cleaning proposal `{target['id']}` — " f"dataset is now **{len(cleaned):,} × {len(cleaned.columns)}** " f"(was {len(df):,} × {len(df.columns)}).\n\n" f"{action_lines or '_(no per-op detail)_'}" ) elif kind == "validation": try: results_df = validate_data_integrity(df, payload) results_records = results_df.to_dict(orient="records") except Exception as e: results_records = [{"rule": "Error", "passed": False, "error": str(e)}] new_df = df recipe_entry = { "id": _make_recipe_id(), "kind": "validation", "payload": payload, "rationale": target.get("rationale", ""), "applied_at": timestamp, "results": results_records, } # Append to the existing rules_input so they live in the Validation tab too existing = (rules_input_value or "").strip() merged = f"{existing}, {payload}".strip(", ") if existing else payload rules_input_value = merged passed = sum(1 for r in results_records if r.get("passed")) failed = len(results_records) - passed chat_msg = ( f"✓ Applied validation proposal `{target['id']}` — " f"**{passed} passed**, **{failed} failed** across {len(results_records)} rule(s). " f"Rules also added to the Validation & Cleaning tab." ) else: chat_history.append({"role": "assistant", "content": f"_Unknown proposal kind: {kind}_"}) return _bundle(df, proposals, recipe, chat_history, rules_input_value) recipe.append(recipe_entry) proposals = [p for p in proposals if p.get("id") != prop_id] chat_history.append({"role": "assistant", "content": chat_msg}) return _bundle(new_df, proposals, recipe, chat_history, rules_input_value) def reject_proposal(prop_id, proposals, chat_history): """Drop the selected proposal from the queue.""" proposals = list(proposals or []) chat_history = list(chat_history or []) if not prop_id: return ( proposals, _render_proposals_html(proposals), gr.update(choices=_proposal_choices(proposals), value=None), chat_history, ) proposals = [p for p in proposals if p.get("id") != prop_id] chat_history.append({"role": "assistant", "content": f"_Rejected proposal `{prop_id}`._"}) return ( proposals, _render_proposals_html(proposals), gr.update(choices=_proposal_choices(proposals), value=None), chat_history, ) def reject_all_proposals(proposals, chat_history): """Drop all pending proposals.""" proposals = list(proposals or []) chat_history = list(chat_history or []) if proposals: chat_history.append({"role": "assistant", "content": f"_Rejected all {len(proposals)} pending proposal(s)._"}) return ( [], _render_proposals_html([]), gr.update(choices=[], value=None), chat_history, ) # --------------------------------------------------------------------------- # Phase 3: persistence via HF OAuth + per-user recipe storage in an HF Dataset. # Each logged-in user gets a private dataset `<username>/datategrity-recipes` # containing recipes.json. Reads and writes use the user's own OAuth token, so # the Space holds no central secrets and the user owns their data. # --------------------------------------------------------------------------- RECIPE_DATASET_FILENAME = "recipes.json" def _recipe_repo_id(profile): return f"{profile.username}/datategrity-recipes" def _load_saved_recipes(profile, token): """Return the recipes list for a logged-in user. [] on any failure.""" if profile is None or token is None: return [] try: from huggingface_hub import hf_hub_download path = hf_hub_download( repo_id=_recipe_repo_id(profile), filename=RECIPE_DATASET_FILENAME, repo_type="dataset", token=token.token, ) with open(path, "r", encoding="utf-8") as f: data = json.load(f) if isinstance(data, dict) and isinstance(data.get("recipes"), list): return data["recipes"] return [] except Exception: # Repo or file doesn't exist yet — that's fine, just treat as empty return [] def _persist_saved_recipes(profile, token, recipes): """Upload recipes.json to the user's private dataset. Creates repo if needed.""" from huggingface_hub import HfApi api = HfApi(token=token.token) repo_id = _recipe_repo_id(profile) api.create_repo(repo_id, repo_type="dataset", exist_ok=True, private=True) payload = json.dumps( { "version": 1, "updated_at": datetime.now().isoformat(timespec="seconds"), "recipes": recipes, }, indent=2, default=str, ).encode("utf-8") api.upload_file( path_or_fileobj=payload, path_in_repo=RECIPE_DATASET_FILENAME, repo_id=repo_id, repo_type="dataset", commit_message=f"Update recipes ({datetime.now().isoformat(timespec='seconds')})", ) def _saved_recipe_choices(saved_recipes): """Build the (label, value) list for the saved-recipes dropdown.""" out = [] for r in (saved_recipes or []): name = r.get("name") or "(unnamed)" steps = r.get("steps") or [] out.append((f"{name} · {len(steps)} step(s) · {r.get('id', '')[:14]}", r.get("id", ""))) return out def _render_saved_recipes_md(saved_recipes, profile): """Status line shown above the saved-recipes controls.""" if profile is None: return "_Log in with Hugging Face (Settings) to save and replay recipes across sessions._" if not saved_recipes: return ( f"_Logged in as **{profile.username}**. No saved recipes yet — apply some " f"proposals, then click **Save current**._" ) return ( f"_Logged in as **{profile.username}** · {len(saved_recipes)} saved recipe(s) " f"in `{_recipe_repo_id(profile)}` (private)._" ) def refresh_saved_recipes(profile: gr.OAuthProfile | None = None, token: gr.OAuthToken | None = None): """Load saved recipes from HF. Used by demo.load and the Refresh button.""" recipes = _load_saved_recipes(profile, token) return ( recipes, _render_saved_recipes_md(recipes, profile), gr.update(choices=_saved_recipe_choices(recipes), value=None), ) def save_current_recipe(name, current_recipe, saved_recipes, profile: gr.OAuthProfile | None = None, token: gr.OAuthToken | None = None): """Bundle the current copilot_recipe_state under a name and persist.""" saved_recipes = list(saved_recipes or []) if profile is None or token is None: return ( saved_recipes, _render_saved_recipes_md(saved_recipes, profile), gr.update(choices=_saved_recipe_choices(saved_recipes), value=None), "_Log in with Hugging Face to save recipes._", ) if not name or not name.strip(): return ( saved_recipes, _render_saved_recipes_md(saved_recipes, profile), gr.update(choices=_saved_recipe_choices(saved_recipes), value=None), "_Give the recipe a name first._", ) if not current_recipe: return ( saved_recipes, _render_saved_recipes_md(saved_recipes, profile), gr.update(choices=_saved_recipe_choices(saved_recipes), value=None), "_Apply at least one proposal before saving._", ) new_entry = { "id": f"saved_{uuid.uuid4().hex[:8]}", "name": name.strip(), "created_at": datetime.now().isoformat(timespec="seconds"), "steps": list(current_recipe), } candidate = saved_recipes + [new_entry] try: _persist_saved_recipes(profile, token, candidate) except Exception as e: return ( saved_recipes, _render_saved_recipes_md(saved_recipes, profile), gr.update(choices=_saved_recipe_choices(saved_recipes), value=None), f"❌ Save failed: {type(e).__name__}: {e}", ) return ( candidate, _render_saved_recipes_md(candidate, profile), gr.update(choices=_saved_recipe_choices(candidate), value=new_entry["id"]), f"✓ Saved **{new_entry['name']}** ({len(new_entry['steps'])} step(s)) — `{new_entry['id']}`", ) def replay_saved_recipe(saved_id, saved_recipes, df, chat_history, current_recipe, rules_input_value): """Apply each step of the selected saved recipe to the current dataset.""" chat_history = list(chat_history or []) current_recipe = list(current_recipe or []) rules_input_value = rules_input_value or "" if not saved_id: chat_history.append({"role": "assistant", "content": "_Select a saved recipe to replay._"}) return df, chat_history, current_recipe, _render_recipe_md(current_recipe), rules_input_value if df is None or (hasattr(df, "empty") and df.empty): chat_history.append({"role": "assistant", "content": "_Upload a dataset before replaying._"}) return df, chat_history, current_recipe, _render_recipe_md(current_recipe), rules_input_value target = next((r for r in (saved_recipes or []) if r.get("id") == saved_id), None) if target is None: chat_history.append({"role": "assistant", "content": f"_Saved recipe `{saved_id}` not found — try Refresh._"}) return df, chat_history, current_recipe, _render_recipe_md(current_recipe), rules_input_value name = target.get("name", "(unnamed)") steps = target.get("steps") or [] summary_lines = [] rows_at_start = int(len(df)) for step in steps: kind = step.get("kind") payload = step.get("payload", "") timestamp = datetime.now().isoformat(timespec="seconds") if kind == "cleaning": before_rows = int(len(df)) cleaned, action_log = _run_cleaning_ops(df, payload) df = cleaned current_recipe.append({ "id": _make_recipe_id(), "kind": "cleaning", "payload": payload, "rationale": f"(replayed from saved recipe '{name}')", "applied_at": timestamp, "actions": action_log, "rows_before": before_rows, "rows_after": int(len(cleaned)), }) summary_lines.append(f"- cleaning · `{payload}` → {len(action_log)} action(s)") elif kind == "validation": try: results_df = validate_data_integrity(df, payload) results_records = results_df.to_dict(orient="records") except Exception as e: results_records = [{"rule": "Error", "passed": False, "error": str(e)}] current_recipe.append({ "id": _make_recipe_id(), "kind": "validation", "payload": payload, "rationale": f"(replayed from saved recipe '{name}')", "applied_at": timestamp, "results": results_records, }) passed = sum(1 for r in results_records if r.get("passed")) failed = len(results_records) - passed summary_lines.append(f"- validation · `{payload}` → {passed} passed, {failed} failed") existing = (rules_input_value or "").strip() rules_input_value = f"{existing}, {payload}".strip(", ") if existing else payload else: summary_lines.append(f"- skipped unknown step kind: `{kind}`") chat_history.append({ "role": "assistant", "content": ( f"✓ Replayed **{name}** ({len(steps)} step(s)) — " f"dataset is now **{len(df):,} × {len(df.columns)}** " f"(was {rows_at_start:,} rows).\n\n" + "\n".join(summary_lines) ), }) return df, chat_history, current_recipe, _render_recipe_md(current_recipe), rules_input_value def delete_saved_recipe(saved_id, saved_recipes, profile: gr.OAuthProfile | None = None, token: gr.OAuthToken | None = None): """Remove a saved recipe by id.""" saved_recipes = list(saved_recipes or []) if profile is None or token is None: return ( saved_recipes, _render_saved_recipes_md(saved_recipes, profile), gr.update(choices=_saved_recipe_choices(saved_recipes), value=None), "_Log in to delete recipes._", ) if not saved_id: return ( saved_recipes, _render_saved_recipes_md(saved_recipes, profile), gr.update(choices=_saved_recipe_choices(saved_recipes), value=None), "_Select a recipe to delete._", ) candidate = [r for r in saved_recipes if r.get("id") != saved_id] try: _persist_saved_recipes(profile, token, candidate) except Exception as e: return ( saved_recipes, _render_saved_recipes_md(saved_recipes, profile), gr.update(choices=_saved_recipe_choices(saved_recipes), value=None), f"❌ Delete failed: {type(e).__name__}: {e}", ) return ( candidate, _render_saved_recipes_md(candidate, profile), gr.update(choices=_saved_recipe_choices(candidate), value=None), f"✓ Deleted `{saved_id}`", ) def create_demo(): """Create the main Gradio application""" with gr.Blocks(title="Datategrity", theme=DATATEGRITY_THEME, css=DATATEGRITY_CSS) as demo: gr.HTML( """ <div id="dg-hero"> <div class="dg-eyebrow"><span class="dg-live-dot"></span>Datategrity · AI-assisted workbench</div> <h1 class="dg-title">Data integrity, made effortless.</h1> <p class="dg-sub">A minimalist studio for exploring datasets, surfacing anomalies, validating rules, and cleaning data — all in one place.</p> </div> <div id="dg-divider"></div> """ ) # Store data globally data_state = gr.State(value=None) # Hugging Face token input with gr.Accordion("⚙️ Settings", open=False): gr.Markdown("### Authentication") gr.Markdown( "Sign in with Hugging Face to use the Copilot and to **save & replay " "recipes across sessions**. Your recipes live in a private dataset " "owned by *your* account — the Space never sees them." ) login_btn = gr.LoginButton() gr.Markdown("### Manual token (optional)") hf_token_input = gr.Textbox( label="Hugging Face Token", type="password", placeholder="hf_...", info="Used only if you don't sign in above. Get one at https://huggingface.co/settings/tokens", ) gr.Markdown("*Stored locally in your session. The signed-in OAuth token takes precedence if both are present.*") gr.Markdown("### Copilot Configuration") agent_model_input = gr.Dropdown( choices=AGENT_FALLBACK_MODELS, value=AGENT_DEFAULT_MODEL, allow_custom_value=True, label="Copilot model", info="HF Inference model the Copilot uses. Must support tool calling.", ) agent_max_steps = gr.Slider( minimum=1, maximum=10, value=AGENT_DEFAULT_MAX_STEPS, step=1, label="Max tool-call steps per turn", info="How many tool-call rounds the agent can take before answering.", ) with gr.Tabs(): # Upload & Explore Tab with gr.TabItem("📂 Upload & Explore"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Data Upload") file_input = gr.File( label="Upload CSV/Excel (.csv, .xlsx, .xls)", file_types=[".csv", ".xlsx", ".xls"] ) gr.Markdown("✅ Supported formats: CSV, Excel (.xlsx, .xls)") sample_size = gr.Slider( minimum=10, maximum=1000, value=100, step=10, label="Sample Size", info="Number of rows to display initially" ) load_btn = gr.Button("🚀 Load Data", variant="primary") gr.Markdown("### Quick Actions") explore_btn = gr.Button("📊 Quick Explore", variant="secondary") quality_btn = gr.Button("🔍 Quality Check", variant="secondary") with gr.Column(scale=2): data_info = gr.JSON(label="Dataset Information") sample_data = gr.Dataframe( label="Sample Data", interactive=False ) # Quality Analysis Tab with gr.TabItem("🔍 Quality Analysis"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Quality Metrics") quality_columns = gr.Dropdown( label="Select Columns", multiselect=True, info="Select columns to analyze (leave empty for all columns)" ) analyze_quality_btn = gr.Button("🎯 Analyze Quality", variant="primary") gr.Markdown("### Anomaly Detection") anomaly_column = gr.Dropdown( label="Select Column for Anomaly Detection", info="Select a numeric column to detect anomalies" ) anomaly_method = gr.Radio( ["zscore", "iqr"], value="zscore", label="Detection Method", info="zscore: Standard deviation method | iqr: Interquartile range method" ) detect_anomalies_btn = gr.Button("⚠️ Detect Anomalies") with gr.Column(scale=2): quality_report = gr.JSON(label="Quality Analysis") anomaly_results = gr.JSON(label="Anomaly Detection Results") # Copilot Tab (Phase 2: agentic, staged proposals + recipe) with gr.TabItem("✨ Copilot"): # State for proposals and the applied-recipe timeline copilot_proposals_state = gr.State(value=[]) copilot_recipe_state = gr.State(value=[]) with gr.Row(): with gr.Column(scale=2): gr.Markdown("### Datategrity Copilot") gr.Markdown( "Profile the data, scan for anomalies, dry-run rules. " "The Copilot can also **propose** validation rules and " "cleaning operations — review each card on the right, then " "Apply or Reject. Cleaning applies mutate the loaded dataset." ) copilot_chat = gr.Chatbot( label="Conversation", height=440, ) copilot_input = gr.Textbox( placeholder="e.g. Profile the data and propose validation rules for the obvious risks.", show_label=False, autofocus=True, lines=2, ) with gr.Row(): copilot_send = gr.Button("Send", variant="primary") copilot_clear = gr.Button("Clear", variant="secondary") with gr.Column(scale=1): gr.Markdown("### Pending proposals") copilot_proposals_html = gr.HTML( value=_render_proposals_html([]), ) copilot_proposal_selector = gr.Radio( choices=[], label="Select to act on", interactive=True, ) with gr.Row(): copilot_apply_btn = gr.Button("Apply", variant="primary", size="sm") copilot_reject_btn = gr.Button("Reject", variant="secondary", size="sm") copilot_reject_all_btn = gr.Button("Reject all", variant="secondary", size="sm") gr.Markdown("### Recipe") copilot_recipe_html = gr.HTML( value=_render_recipe_md([]), ) with gr.Accordion("📁 Saved recipes", open=False): copilot_saved_recipes_state = gr.State(value=[]) saved_recipes_status_md = gr.Markdown( value="_Sign in (Settings) to save and replay recipes across sessions._" ) saved_recipes_selector = gr.Dropdown( choices=[], label="Saved recipes", info="Pick one to replay or delete.", interactive=True, ) save_recipe_name = gr.Textbox( placeholder="Name this recipe — e.g. 'Q1 sales cleanup'", show_label=False, lines=1, ) with gr.Row(): save_recipe_btn = gr.Button("Save current", variant="primary", size="sm") replay_recipe_btn = gr.Button("Replay", variant="secondary", size="sm") delete_recipe_btn = gr.Button("Delete", variant="secondary", size="sm") refresh_recipes_btn = gr.Button("⟳", variant="secondary", size="sm") saved_recipes_action_md = gr.Markdown(value="") with gr.Accordion("Tool trace", open=False): copilot_trace = gr.JSON( label="Tool calls (this session)", value=[], ) # AI Assistant Tab with gr.TabItem("🤖 AI Assistant"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Data Assistant") ai_message = gr.Textbox( label="Ask about your data", placeholder="e.g., 'What are the top 5 rows by value?' or 'Find anomalies in column X'", info="Ask questions about your dataset using natural language" ) ai_history = gr.List( label="Chat History" ) ai_btn = gr.Button("💬 Ask AI", variant="primary") ai_clear_btn = gr.Button("🗑️ Clear Chat") with gr.Column(scale=2): ai_response = gr.Textbox( label="AI Response", lines=10 ) ai_insights = gr.Markdown(label="Insights") # Validation & Cleaning Tab with gr.TabItem("✅ Validation & Cleaning"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Business Rules Validation") gr.Markdown("💡 **Tip**: Type your rules with real-time suggestions. Format: `column:rule_type:param`") rules_input = gr.Textbox( label="Rules (format: column:rule_type:param)", placeholder="id:unique, price:range:0,1000, email:null", lines=8, info="Enter validation rules separated by commas. Use tab for autocomplete suggestions.", elem_classes=["dg-mono"], ) # Hidden component to store current column list for suggestions columns_state = gr.State(value=[]) # Create suggestion display with gr.Accordion("✅ Suggestions", open=False) as suggestions_accordion: with gr.Column() as suggestions_container: suggestions_list = gr.Radio( [], label="Select suggestion", value=None, interactive=True ) validate_btn = gr.Button("✅ Validate Data", variant="primary") gr.Markdown("### Data Cleaning Operations") cleaning_ops = gr.Textbox( label="Cleaning Operations (format: column:operation)", placeholder="name:lowercase, price:fill_mean, description:trim", lines=5, info="Enter cleaning operations separated by commas. Format: column:operation", elem_classes=["dg-mono"], ) clean_btn = gr.Button("🧹 Clean Data", variant="secondary") download_clean_btn = gr.Button("💾 Download Cleaned Data", variant="secondary") with gr.Column(scale=2): validation_results = gr.Dataframe( label="Validation Results" ) cleaning_preview = gr.Dataframe( label="Cleaned Data Preview" ) # Reporting Tab with gr.TabItem("📋 Reporting"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Generate Reports") report_type = gr.Radio( ["Quality Report", "Anomaly Summary", "Validation Summary"], label="Report Type", info="Select the type of report to generate" ) generate_report_btn = gr.Button("📄 Generate Report", variant="primary") download_report_btn = gr.Button("📥 Download Report", variant="secondary") with gr.Column(scale=2): report_output = gr.Markdown(label="Report") report_json = gr.JSON(label="Report JSON") # Event Handlers - Updated with real-time suggestions def update_quality_columns(file): if file is None: return gr.update(choices=[]) try: # Try to read the file if hasattr(file, 'name'): if file.name.endswith('.csv'): df = pd.read_csv(file.name) else: df = pd.read_excel(file.name) return gr.update(choices=df.columns.tolist()) else: return gr.update(choices=[]) except Exception as e: gr.Warning(f"Could not read file: {str(e)}") return gr.update(choices=[]) def update_anomaly_column(file): if file is None: return gr.update(choices=[]) try: if hasattr(file, 'name'): if file.name.endswith('.csv'): df = pd.read_csv(file.name) else: df = pd.read_excel(file.name) numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist() return gr.update(choices=numeric_cols) else: return gr.update(choices=[]) except Exception as e: gr.Warning(f"Could not read file: {str(e)}") return gr.update(choices=[]) def analyze_quality(df, columns): if df is None or df.empty: return {"error": "No data loaded. Please upload data first."} try: return analyze_data_quality(df, columns) except Exception as e: return {"error": f"Analysis failed: {str(e)}"} def detect_anomalies_handler(df, column, method): if df is None or df.empty: return {"error": "No data loaded. Please upload data first."} if column is None: return {"error": "Please select a column for anomaly detection."} try: return detect_anomalies(df, column, method) except Exception as e: return {"error": f"Anomaly detection failed: {str(e)}"} def chat_with_data_handler(message, history, hf_token): if data_state.value is None or data_state.value.empty: return "Please upload data first.", history response = "" full_history = history or [] try: for partial_response in chat_with_data(data_state.value, message, history or [], hf_token): response = partial_response # Update history as we stream current_history = full_history + [{"role": "user", "content": message}] if partial_response and not partial_response.startswith("❌") and not partial_response.startswith("⚠️"): current_history.append({"role": "assistant", "content": partial_response}) yield partial_response, current_history except Exception as e: error_response = f"❌ Error: {str(e)}" current_history = full_history + [{"role": "user", "content": message}] current_history.append({"role": "assistant", "content": error_response}) yield error_response, current_history def validate_data_handler(df, rules): try: return validate_data_integrity(df, rules) except Exception as e: return pd.DataFrame([{"rule": "Error", "passed": False, "error": str(e)}]) def clean_data_handler(df, operations): try: return clean_data(df, operations) except Exception as e: return pd.DataFrame([["Error", str(e)]], columns=["Column", "Action"]) def generate_report(df, report_type): if df is None or df.empty: return "# Error: No data loaded", {"error": "No data"} try: if report_type == "Quality Report": report_text = generate_data_quality_report(df) analysis = analyze_data_quality(df) return report_text, analysis elif report_type == "Anomaly Summary": numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist() anomalies = {} for col in numeric_cols[:5]: # Limit to first 5 numeric columns try: anomalies[col] = detect_anomalies(df, col) except: continue summary = f"# Anomaly Summary\n\nDetected anomalies in {len(anomalies)} numeric columns" return summary, anomalies elif report_type == "Validation Summary": return "# Validation Summary\n\nRun validation to see results", {"status": "Run validation first"} except Exception as e: return f"# Error: {str(e)}", {"error": str(e)} def load_data(file, sample_size): """Load data with comprehensive error handling""" if file is None: return None, {}, pd.DataFrame(), "No file uploaded" try: # Check if file has the expected attributes if not hasattr(file, 'name'): return None, {"error": "Invalid file object"}, pd.DataFrame(), "Invalid file format" filename = file.name if hasattr(file, 'name') else str(file) # Read the file based on extension if filename.endswith('.csv'): df = pd.read_csv(file.name) elif filename.endswith('.xlsx') or filename.endswith('.xls'): df = pd.read_excel(file.name) else: return None, {"error": "Unsupported file format. Please use CSV or Excel files."}, pd.DataFrame(), "Unsupported format" # Store full dataset data_state.value = df.copy() # Sample for display sample_size = int(sample_size) sample_df = df.head(sample_size) # Generate quick analysis quick_analysis = { "rows": len(df), "columns": len(df.columns), "memory_mb": round(df.memory_usage(deep=True).sum() / 1024**2, 2), "columns_list": df.columns.tolist(), "data_types": df.dtypes.astype(str).value_counts().to_dict() } status = f"✅ Successfully loaded {len(df)} rows and {len(df.columns)} columns" return df, quick_analysis, sample_df, status except pd.errors.EmptyDataError: return None, {"error": "File is empty"}, pd.DataFrame(), "Empty file" except pd.errors.ParserError as e: return None, {"error": f"CSV parsing error: {str(e)}"}, pd.DataFrame(), "Parse error" except Exception as e: return None, {"error": f"Error loading file: {str(e)}"}, pd.DataFrame(), f"Error: {str(e)}" def update_columns_state(file): """Update the columns state when file is uploaded""" if file is None: return [] try: if hasattr(file, 'name'): if file.name.endswith('.csv'): df = pd.read_csv(file.name) else: df = pd.read_excel(file.name) return df.columns.tolist() else: return [] except Exception: return [] def get_suggestions(text, columns): """Get completion suggestions for the rules input""" if not text or not columns: return [], False try: suggestions = get_completion_suggestions(text, columns) return suggestions, len(suggestions) > 0 except Exception: return [], False def select_suggestion(suggestion, current_text): """Handle suggestion selection""" if not suggestion: return current_text # If suggestion is a rule type, append it to current text parts = current_text.split(':') if len(parts) >= 2: # Reconstruct with suggestion base = ':'.join(parts[:-1]) if suggestion.endswith(':'): return f"{base}:{suggestion[:-1]}:" else: return f"{base}:{suggestion}" return current_text + (suggestion if not current_text.endswith(':') else suggestion[1:]) def toggle_suggestions_accordion(has_suggestions): """Toggle the accordion visibility based on suggestions""" return gr.update(visible=has_suggestions) # Connect events with real-time suggestions file_input.change( update_quality_columns, file_input, quality_columns ) file_input.change( update_anomaly_column, file_input, anomaly_column ) file_input.change( update_columns_state, file_input, columns_state ) # Update load button to show status load_state = gr.State(value="Ready") load_btn.click( load_data, [file_input, sample_size], [data_state, data_info, sample_data, load_state] ).then( lambda status: gr.Info(status) if "Error" not in status else None, load_state, None ) explore_btn.click( lambda df: (df.describe().to_dict() if df is not None and not df.empty else {}), data_state, data_info ) quality_btn.click( lambda df: analyze_data_quality(df) if df is not None and not df.empty else {"error": "No data loaded"}, data_state, quality_report ) analyze_quality_btn.click( analyze_quality, [data_state, quality_columns], quality_report ) detect_anomalies_btn.click( detect_anomalies_handler, [data_state, anomaly_column, anomaly_method], anomaly_results ) ai_btn.click( chat_with_data_handler, [ai_message, ai_history, hf_token_input], [ai_response, ai_history], api_visibility="public" ) ai_clear_btn.click( lambda: ("", []), None, [ai_response, ai_history] ) validate_btn.click( validate_data_handler, [data_state, rules_input], validation_results ) clean_btn.click( clean_data_handler, [data_state, cleaning_ops], cleaning_preview ) download_clean_btn.click( lambda df: df.to_csv(index=False) if df is not None and not df.empty else "", data_state, gr.File(label="Download Cleaned Data") ) generate_report_btn.click( generate_report, [data_state, report_type], [report_output, report_json] ) download_report_btn.click( lambda report: report, report_output, gr.File(label="Download Report") ) # Real-time suggestions for rules input - using change event (Gradio 6 compatible) rules_input.change( get_suggestions, [rules_input, columns_state], [suggestions_list, gr.Checkbox(visible=False)] # Use a dummy checkbox for the second output ).then( toggle_suggestions_accordion, gr.Checkbox(visible=False), suggestions_accordion ) suggestions_list.change( select_suggestion, [suggestions_list, rules_input], rules_input ) # ---- Copilot wiring (Phase 2) ----------------------------------- copilot_turn_inputs = [ copilot_input, copilot_chat, copilot_trace, copilot_proposals_state, data_state, hf_token_input, agent_model_input, agent_max_steps, ] copilot_turn_outputs = [ copilot_chat, copilot_trace, copilot_proposals_state, copilot_proposals_html, copilot_proposal_selector, ] copilot_send.click( run_copilot_turn, copilot_turn_inputs, copilot_turn_outputs ).then(lambda: "", None, copilot_input) copilot_input.submit( run_copilot_turn, copilot_turn_inputs, copilot_turn_outputs ).then(lambda: "", None, copilot_input) copilot_clear.click( lambda: ([], [], [], [], _render_proposals_html([]), gr.update(choices=[], value=None), _render_recipe_md([])), None, [ copilot_chat, copilot_trace, copilot_proposals_state, copilot_recipe_state, copilot_proposals_html, copilot_proposal_selector, copilot_recipe_html, ], ) copilot_apply_btn.click( apply_proposal, [ copilot_proposal_selector, data_state, copilot_proposals_state, copilot_recipe_state, copilot_chat, rules_input, ], [ data_state, copilot_proposals_state, copilot_recipe_state, copilot_proposals_html, copilot_proposal_selector, copilot_recipe_html, copilot_chat, rules_input, ], ) copilot_reject_btn.click( reject_proposal, [copilot_proposal_selector, copilot_proposals_state, copilot_chat], [ copilot_proposals_state, copilot_proposals_html, copilot_proposal_selector, copilot_chat, ], ) copilot_reject_all_btn.click( reject_all_proposals, [copilot_proposals_state, copilot_chat], [ copilot_proposals_state, copilot_proposals_html, copilot_proposal_selector, copilot_chat, ], ) # ---- Saved recipes (Phase 3) ------------------------------------ saved_recipe_refresh_outputs = [ copilot_saved_recipes_state, saved_recipes_status_md, saved_recipes_selector, ] # Fire on every page load — OAuthProfile/OAuthToken are auto-injected demo.load(refresh_saved_recipes, None, saved_recipe_refresh_outputs) refresh_recipes_btn.click( refresh_saved_recipes, None, saved_recipe_refresh_outputs ) save_recipe_btn.click( save_current_recipe, [save_recipe_name, copilot_recipe_state, copilot_saved_recipes_state], [ copilot_saved_recipes_state, saved_recipes_status_md, saved_recipes_selector, saved_recipes_action_md, ], ).then(lambda: "", None, save_recipe_name) replay_recipe_btn.click( replay_saved_recipe, [ saved_recipes_selector, copilot_saved_recipes_state, data_state, copilot_chat, copilot_recipe_state, rules_input, ], [ data_state, copilot_chat, copilot_recipe_state, copilot_recipe_html, rules_input, ], ) delete_recipe_btn.click( delete_saved_recipe, [saved_recipes_selector, copilot_saved_recipes_state], [ copilot_saved_recipes_state, saved_recipes_status_md, saved_recipes_selector, saved_recipes_action_md, ], ) return demo # Create and launch the application if __name__ == "__main__": demo = create_demo() demo.launch( ssr_mode=False, footer_links=[{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}], allowed_paths=["*"], )
import gradio as gr
import pandas as pd
import numpy as np
from huggingface_hub import InferenceClient
import io
import json
import html
import uuid
from datetime import datetime
import re
# ---------------------------------------------------------------------------
# UI theme + styling. Visual only — does not affect any application logic.
# ---------------------------------------------------------------------------
DATATEGRITY_THEME = gr.themes.Soft(
primary_hue=gr.themes.Color(
c50="#f8fafc", c100="#f1f5f9", c200="#e2e8f0", c300="#cbd5e1",
c400="#94a3b8", c500="#64748b", c600="#475569", c700="#334155",
c800="#1e293b", c900="#0f172a", c950="#020617",
),
secondary_hue="slate",
neutral_hue="slate",
radius_size=gr.themes.sizes.radius_md,
spacing_size=gr.themes.sizes.spacing_md,
text_size=gr.themes.sizes.text_md,
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "Menlo", "monospace"],
).set(
body_background_fill="#fafafa",
body_background_fill_dark="#0a0a0a",
background_fill_primary="#ffffff",
background_fill_primary_dark="#111113",
background_fill_secondary="#fafafa",
background_fill_secondary_dark="#0d0d0f",
border_color_primary="rgba(15, 23, 42, 0.08)",
border_color_primary_dark="rgba(241, 245, 249, 0.08)",
block_border_width="1px",
block_shadow="none",
block_radius="14px",
block_label_background_fill="transparent",
block_label_background_fill_dark="transparent",
block_label_text_weight="500",
block_title_text_weight="600",
block_title_text_size="*text_md",
button_large_radius="10px",
button_small_radius="8px",
button_primary_background_fill="#0f172a",
button_primary_background_fill_hover="#1e293b",
button_primary_background_fill_dark="#f8fafc",
button_primary_background_fill_hover_dark="#e2e8f0",
button_primary_text_color="#ffffff",
button_primary_text_color_dark="#0f172a",
button_primary_border_color="transparent",
button_primary_border_color_dark="transparent",
button_secondary_background_fill="#ffffff",
button_secondary_background_fill_hover="#f8fafc",
button_secondary_background_fill_dark="#1a1a1d",
button_secondary_background_fill_hover_dark="#222227",
button_secondary_text_color="#0f172a",
button_secondary_text_color_dark="#f1f5f9",
button_secondary_border_color="rgba(15, 23, 42, 0.08)",
button_secondary_border_color_dark="rgba(241, 245, 249, 0.08)",
input_background_fill="#ffffff",
input_background_fill_dark="#141417",
input_border_color="rgba(15, 23, 42, 0.08)",
input_border_color_dark="rgba(241, 245, 249, 0.08)",
input_border_color_focus="rgba(15, 23, 42, 0.3)",
input_border_color_focus_dark="rgba(241, 245, 249, 0.3)",
input_radius="10px",
slider_color="#0f172a",
slider_color_dark="#f1f5f9",
)
DATATEGRITY_CSS = """
/* --- Container & typography ------------------------------------------- */
.gradio-container {
max-width: 1240px !important;
animation: dg-page-in 0.55s cubic-bezier(0.16, 1, 0.3, 1);
}
.gradio-container * {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@keyframes dg-page-in {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
/* --- Hero header ------------------------------------------------------ */
#dg-hero {
padding: 1.8rem 0 1.4rem 0;
border: none !important;
background: transparent !important;
}
#dg-hero .dg-eyebrow {
display: inline-flex;
align-items: center;
gap: 0.55rem;