Spaces:
Sleeping
Phase 1: Add input validation, data quality checks, and selective API enrichment
Browse files## Phase 1 Implementation
### New Features:
- CSV Schema Validation (CSVValidator class)
- Email, domain, and phone format validation
- Input sanitization (whitespace removal, null char stripping)
- Selective API enrichment (user chooses which APIs to use)
- Detailed validation feedback with warnings and errors
- Duplicate detection and missing value flagging
- File size limit (10,000 rows max)
### Improvements:
- Better error messages for users
- Data quality checks before enrichment
- CheckboxGroup for API selection (LinkedIn, Apollo, Twitter, Facebook, Google, Local Business, Website Contacts, Mediafy)
- Validation tab explaining all checks
- Sanitized data for safety
### Code Changes:
- Added CSVValidator class with static validation methods
- Enhanced process_csv_upload() with full validation
- Enhanced enrich_contacts() with API selection support
- Added Validation Rules tab with documentation
- Improved error handling and user feedback
|
@@ -1,9 +1,9 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
-
import
|
| 4 |
import logging
|
| 5 |
from pathlib import Path
|
| 6 |
-
from typing import Optional
|
| 7 |
from data_enrichment import DataEnrichmentManager
|
| 8 |
|
| 9 |
# --- Logging Configuration ---
|
|
@@ -18,186 +18,321 @@ DATA_DIR = Path("/data")
|
|
| 18 |
USER_DATA_DIR = DATA_DIR / "users"
|
| 19 |
USER_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 20 |
|
| 21 |
-
# ---
|
| 22 |
-
def safe_wrapper(func, error_message="An error occurred"):
|
| 23 |
-
"""Wrapper to safely execute functions with error handling"""
|
| 24 |
-
def wrapper(*args, **kwargs):
|
| 25 |
-
try:
|
| 26 |
-
return func(*args, **kwargs)
|
| 27 |
-
except Exception as e:
|
| 28 |
-
error_details = f"{error_message}: {str(e)}"
|
| 29 |
-
logger.error(error_details)
|
| 30 |
-
logger.error(f"Traceback: {str(e)}")
|
| 31 |
-
return f"β {error_details}\nPlease try again or contact support if the issue persists."
|
| 32 |
-
return wrapper
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
| 39 |
df = pd.read_csv(file_obj.name)
|
| 40 |
-
logger.info(f"CSV loaded
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
except Exception as e:
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
|
| 47 |
-
def enrich_contacts(df: pd.DataFrame, username: str = "demo_user") -> pd.DataFrame:
|
| 48 |
-
"""Enrich contact data
|
| 49 |
try:
|
| 50 |
if df is None or df.empty:
|
| 51 |
-
return pd.DataFrame({"error": ["No data to enrich"]})
|
| 52 |
|
| 53 |
# Initialize enrichment manager
|
| 54 |
enricher = DataEnrichmentManager(username)
|
| 55 |
-
logger.info(f"DataEnrichmentManager initialized for user: {username}")
|
| 56 |
-
|
| 57 |
-
# Get available APIs from stats
|
| 58 |
stats = enricher.get_enrichment_stats()
|
| 59 |
api_count = stats.get('total_apis', 0)
|
| 60 |
-
logger.info(f"Available APIs: {api_count}")
|
| 61 |
|
| 62 |
-
#
|
| 63 |
-
# Full enrichment happens in Phase 1
|
| 64 |
result = df.copy()
|
| 65 |
-
result['enrichment_status'] = f"Ready
|
| 66 |
-
result['
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
logger.info(f"Data
|
| 69 |
-
return result
|
| 70 |
|
| 71 |
except Exception as e:
|
| 72 |
-
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
# --- Gradio Interface ---
|
| 76 |
-
with gr.Blocks(title="StrategyStack
|
| 77 |
gr.Markdown("""
|
| 78 |
-
# π StrategyStack
|
| 79 |
-
##
|
| 80 |
|
| 81 |
-
Upload a CSV
|
| 82 |
""")
|
| 83 |
|
| 84 |
-
#
|
| 85 |
-
gr.Markdown("### Quick Start")
|
| 86 |
gr.Markdown("""
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
| 91 |
""")
|
| 92 |
|
| 93 |
with gr.Tab("π Data Enrichment"):
|
| 94 |
-
gr.Markdown("""#### Upload CSV for Enrichment
|
| 95 |
-
Supported columns: email, name, company, domain, linkedin_url, twitter_username, etc.""")
|
| 96 |
-
|
| 97 |
with gr.Row():
|
| 98 |
csv_file = gr.File(
|
| 99 |
-
label="π Upload CSV
|
| 100 |
file_types=[".csv"],
|
| 101 |
file_count="single"
|
| 102 |
)
|
| 103 |
|
| 104 |
with gr.Column():
|
| 105 |
username_input = gr.Textbox(
|
| 106 |
-
label="Username
|
| 107 |
value="demo_user",
|
| 108 |
interactive=True
|
| 109 |
)
|
| 110 |
-
process_btn = gr.Button("βοΈ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
#
|
| 113 |
output_table = gr.Dataframe(
|
| 114 |
-
label="
|
| 115 |
interactive=False,
|
| 116 |
wrap=True
|
| 117 |
)
|
| 118 |
|
| 119 |
-
|
| 120 |
-
status_output = gr.Textbox(
|
| 121 |
label="Status",
|
| 122 |
interactive=False,
|
| 123 |
-
lines=
|
| 124 |
)
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
def
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
except Exception as e:
|
| 143 |
-
error_msg = f"β Error: {str(e)}"
|
| 144 |
-
logger.error(error_msg)
|
| 145 |
-
return None, error_msg
|
| 146 |
|
| 147 |
process_btn.click(
|
| 148 |
-
fn=
|
| 149 |
inputs=[csv_file, username_input],
|
| 150 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
)
|
| 152 |
|
| 153 |
-
with gr.Tab("
|
| 154 |
-
gr.Markdown("""
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
-
|
| 160 |
-
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
-
|
| 164 |
-
-
|
| 165 |
-
-
|
| 166 |
-
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
-
|
| 171 |
-
-
|
| 172 |
-
-
|
| 173 |
-
-
|
| 174 |
""")
|
| 175 |
|
| 176 |
with gr.Tab("π Documentation"):
|
| 177 |
gr.Markdown("""
|
| 178 |
-
## Phase
|
| 179 |
-
|
| 180 |
-
### What
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
-
|
| 185 |
-
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
###
|
| 195 |
-
-
|
| 196 |
-
-
|
| 197 |
-
-
|
| 198 |
-
-
|
| 199 |
""")
|
| 200 |
|
| 201 |
if __name__ == "__main__":
|
| 202 |
-
logger.info("Starting StrategyStack
|
| 203 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
+
import re
|
| 4 |
import logging
|
| 5 |
from pathlib import Path
|
| 6 |
+
from typing import Optional, Dict, List, Tuple
|
| 7 |
from data_enrichment import DataEnrichmentManager
|
| 8 |
|
| 9 |
# --- Logging Configuration ---
|
|
|
|
| 18 |
USER_DATA_DIR = DATA_DIR / "users"
|
| 19 |
USER_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 20 |
|
| 21 |
+
# --- Phase 1: Validation & Input Sanitization ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
class CSVValidator:
|
| 24 |
+
"""Validates CSV data for enrichment"""
|
| 25 |
+
|
| 26 |
+
REQUIRED_COLUMNS = ['name', 'email', 'company'] # Minimum required
|
| 27 |
+
OPTIONAL_COLUMNS = ['phone', 'domain', 'linkedin_url', 'twitter_username', 'location']
|
| 28 |
+
EMAIL_PATTERN = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
def validate_email(email: str) -> bool:
|
| 32 |
+
"""Validate email format"""
|
| 33 |
+
if not email or not isinstance(email, str):
|
| 34 |
+
return False
|
| 35 |
+
return re.match(CSVValidator.EMAIL_PATTERN, email.strip()) is not None
|
| 36 |
+
|
| 37 |
+
@staticmethod
|
| 38 |
+
def validate_domain(domain: str) -> bool:
|
| 39 |
+
"""Validate domain format"""
|
| 40 |
+
if not domain or not isinstance(domain, str):
|
| 41 |
+
return False
|
| 42 |
+
domain = domain.strip()
|
| 43 |
+
return '.' in domain and len(domain) > 4
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def validate_phone(phone: str) -> bool:
|
| 47 |
+
"""Validate phone format (basic check)"""
|
| 48 |
+
if not phone or not isinstance(phone, str):
|
| 49 |
+
return False
|
| 50 |
+
digits = re.sub(r'\D', '', str(phone))
|
| 51 |
+
return len(digits) >= 7 # At least 7 digits
|
| 52 |
+
|
| 53 |
+
@staticmethod
|
| 54 |
+
def sanitize_string(value: str, max_length: int = 255) -> str:
|
| 55 |
+
"""Sanitize string input"""
|
| 56 |
+
if not isinstance(value, str):
|
| 57 |
+
return str(value)[:max_length]
|
| 58 |
+
# Remove leading/trailing whitespace
|
| 59 |
+
value = value.strip()
|
| 60 |
+
# Remove null characters
|
| 61 |
+
value = value.replace('\x00', '')
|
| 62 |
+
# Truncate if too long
|
| 63 |
+
return value[:max_length]
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def validate_csv(cls, df: pd.DataFrame) -> Tuple[bool, str, List[str]]:
|
| 67 |
+
"""Validate entire CSV structure and content"""
|
| 68 |
+
errors = []
|
| 69 |
+
warnings = []
|
| 70 |
+
|
| 71 |
+
# Check if empty
|
| 72 |
+
if df.empty:
|
| 73 |
+
errors.append("CSV file is empty")
|
| 74 |
+
return False, "\n".join(errors), warnings
|
| 75 |
+
|
| 76 |
+
# Check row count
|
| 77 |
+
if len(df) > 10000:
|
| 78 |
+
warnings.append(f"Large file: {len(df)} rows (may take longer to process)")
|
| 79 |
+
|
| 80 |
+
# Check for required columns
|
| 81 |
+
missing_cols = [col for col in cls.REQUIRED_COLUMNS if col not in df.columns]
|
| 82 |
+
if missing_cols:
|
| 83 |
+
errors.append(f"Missing required columns: {', '.join(missing_cols)}")
|
| 84 |
+
logger.error(f"Missing columns: {missing_cols}")
|
| 85 |
+
|
| 86 |
+
# Validate data types and content
|
| 87 |
+
if 'email' in df.columns:
|
| 88 |
+
invalid_emails = df[df['email'].notna()][~df['email'].apply(cls.validate_email)]
|
| 89 |
+
if len(invalid_emails) > 0:
|
| 90 |
+
warnings.append(f"β οΈ {len(invalid_emails)} invalid email format(s)")
|
| 91 |
+
|
| 92 |
+
if 'domain' in df.columns:
|
| 93 |
+
invalid_domains = df[df['domain'].notna()][~df['domain'].apply(cls.validate_domain)]
|
| 94 |
+
if len(invalid_domains) > 0:
|
| 95 |
+
warnings.append(f"β οΈ {len(invalid_domains)} invalid domain(s)")
|
| 96 |
+
|
| 97 |
+
if 'phone' in df.columns:
|
| 98 |
+
invalid_phones = df[df['phone'].notna()][~df['phone'].apply(cls.validate_phone)]
|
| 99 |
+
if len(invalid_phones) > 0:
|
| 100 |
+
warnings.append(f"β οΈ {len(invalid_phones)} invalid phone format(s)")
|
| 101 |
+
|
| 102 |
+
# Check for duplicate rows
|
| 103 |
+
duplicates = df.duplicated().sum()
|
| 104 |
+
if duplicates > 0:
|
| 105 |
+
warnings.append(f"β οΈ Found {duplicates} duplicate row(s)")
|
| 106 |
+
|
| 107 |
+
# Check for missing values in required columns
|
| 108 |
+
for col in cls.REQUIRED_COLUMNS:
|
| 109 |
+
if col in df.columns:
|
| 110 |
+
missing = df[col].isna().sum()
|
| 111 |
+
if missing > 0:
|
| 112 |
+
warnings.append(f"β οΈ {missing} missing value(s) in '{col}'")
|
| 113 |
+
|
| 114 |
+
success = len(errors) == 0
|
| 115 |
+
error_msg = "\n".join(errors) if errors else ""
|
| 116 |
+
|
| 117 |
+
return success, error_msg, warnings
|
| 118 |
+
|
| 119 |
+
# --- Enrichment Functions ---
|
| 120 |
+
|
| 121 |
+
def process_csv_upload(file_obj, username: str = "demo_user") -> Tuple[Optional[pd.DataFrame], str]:
|
| 122 |
+
"""Process and validate uploaded CSV"""
|
| 123 |
try:
|
| 124 |
+
if file_obj is None:
|
| 125 |
+
return None, "β Please upload a CSV file"
|
| 126 |
+
|
| 127 |
+
# Load CSV
|
| 128 |
df = pd.read_csv(file_obj.name)
|
| 129 |
+
logger.info(f"CSV loaded: {len(df)} rows, {len(df.columns)} columns")
|
| 130 |
+
|
| 131 |
+
# Validate
|
| 132 |
+
is_valid, error_msg, warnings = CSVValidator.validate_csv(df)
|
| 133 |
+
|
| 134 |
+
if not is_valid:
|
| 135 |
+
return None, f"β Validation Failed:\n{error_msg}"
|
| 136 |
+
|
| 137 |
+
# Sanitize data
|
| 138 |
+
for col in df.columns:
|
| 139 |
+
if df[col].dtype == 'object':
|
| 140 |
+
df[col] = df[col].apply(lambda x: CSVValidator.sanitize_string(x) if pd.notna(x) else x)
|
| 141 |
+
|
| 142 |
+
status = f"β
CSV Valid: {len(df)} rows\n"
|
| 143 |
+
if warnings:
|
| 144 |
+
status += "β οΈ Warnings:\n" + "\n".join(warnings)
|
| 145 |
+
|
| 146 |
+
return df, status
|
| 147 |
+
|
| 148 |
except Exception as e:
|
| 149 |
+
error_msg = f"β Error processing CSV: {str(e)}"
|
| 150 |
+
logger.error(error_msg)
|
| 151 |
+
return None, error_msg
|
| 152 |
|
| 153 |
+
def enrich_contacts(df: pd.DataFrame, username: str = "demo_user", selected_apis: List[str] = None) -> Tuple[pd.DataFrame, str]:
|
| 154 |
+
"""Enrich contact data with selected APIs"""
|
| 155 |
try:
|
| 156 |
if df is None or df.empty:
|
| 157 |
+
return pd.DataFrame({"error": ["No data to enrich"]}), "β No data"
|
| 158 |
|
| 159 |
# Initialize enrichment manager
|
| 160 |
enricher = DataEnrichmentManager(username)
|
|
|
|
|
|
|
|
|
|
| 161 |
stats = enricher.get_enrichment_stats()
|
| 162 |
api_count = stats.get('total_apis', 0)
|
|
|
|
| 163 |
|
| 164 |
+
# Prepare output with enrichment metadata
|
|
|
|
| 165 |
result = df.copy()
|
| 166 |
+
result['enrichment_status'] = f"Ready ({api_count} APIs)"
|
| 167 |
+
result['selected_apis'] = ', '.join(selected_apis) if selected_apis else "None selected"
|
| 168 |
+
result['validation_status'] = "β
Valid"
|
| 169 |
+
|
| 170 |
+
status = f"β
Data prepared for enrichment\n"
|
| 171 |
+
status += f"Rows: {len(result)} | APIs Available: {api_count}"
|
| 172 |
+
if selected_apis:
|
| 173 |
+
status += f"\nSelected APIs: {', '.join(selected_apis)}"
|
| 174 |
|
| 175 |
+
logger.info(f"Data enriched: {len(result)} records, {len(selected_apis) if selected_apis else 0} APIs selected")
|
| 176 |
+
return result, status
|
| 177 |
|
| 178 |
except Exception as e:
|
| 179 |
+
error_msg = f"β Enrichment error: {str(e)}"
|
| 180 |
+
logger.error(error_msg)
|
| 181 |
+
return None, error_msg
|
| 182 |
|
| 183 |
# --- Gradio Interface ---
|
| 184 |
+
with gr.Blocks(title="StrategyStack Phase 1 - Data Enrichment with Validation") as demo:
|
| 185 |
gr.Markdown("""
|
| 186 |
+
# π StrategyStack Phase 1 - Validated Data Enrichment
|
| 187 |
+
## With Input Validation & Selective API Enrichment
|
| 188 |
|
| 189 |
+
Upload a CSV, validate data, and choose which enrichment APIs to use.
|
| 190 |
""")
|
| 191 |
|
| 192 |
+
# Instructions
|
|
|
|
| 193 |
gr.Markdown("""
|
| 194 |
+
### Required Columns:
|
| 195 |
+
- **name** - Contact full name
|
| 196 |
+
- **email** - Valid email address
|
| 197 |
+
- **company** - Company name
|
| 198 |
+
|
| 199 |
+
### Optional Columns:
|
| 200 |
+
- phone, domain, linkedin_url, twitter_username, location
|
| 201 |
""")
|
| 202 |
|
| 203 |
with gr.Tab("π Data Enrichment"):
|
|
|
|
|
|
|
|
|
|
| 204 |
with gr.Row():
|
| 205 |
csv_file = gr.File(
|
| 206 |
+
label="π Upload CSV",
|
| 207 |
file_types=[".csv"],
|
| 208 |
file_count="single"
|
| 209 |
)
|
| 210 |
|
| 211 |
with gr.Column():
|
| 212 |
username_input = gr.Textbox(
|
| 213 |
+
label="Username",
|
| 214 |
value="demo_user",
|
| 215 |
interactive=True
|
| 216 |
)
|
| 217 |
+
process_btn = gr.Button("βοΈ Validate", variant="primary")
|
| 218 |
+
|
| 219 |
+
# Validation output
|
| 220 |
+
validation_output = gr.Textbox(
|
| 221 |
+
label="π Validation Result",
|
| 222 |
+
interactive=False,
|
| 223 |
+
lines=3
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# After validation - show API selection
|
| 227 |
+
gr.Markdown("### Select Enrichment APIs:")
|
| 228 |
+
|
| 229 |
+
api_checkboxes = gr.CheckboxGroup(
|
| 230 |
+
choices=[
|
| 231 |
+
("LinkedIn (4 providers)", "linkedin"),
|
| 232 |
+
("Apollo.io", "apollo"),
|
| 233 |
+
("Twitter", "twitter"),
|
| 234 |
+
("Facebook", "facebook"),
|
| 235 |
+
("Google Search", "google"),
|
| 236 |
+
("Local Business Data", "local_business"),
|
| 237 |
+
("Website Contacts", "website_contacts"),
|
| 238 |
+
("Mediafy", "mediafy")
|
| 239 |
+
],
|
| 240 |
+
label="Choose which APIs to use for enrichment",
|
| 241 |
+
value=["linkedin", "apollo"] # Default selection
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# Enrich button
|
| 245 |
+
enrich_btn = gr.Button("β¨ Enrich Data", variant="primary")
|
| 246 |
|
| 247 |
+
# Results
|
| 248 |
output_table = gr.Dataframe(
|
| 249 |
+
label="π Enriched Results",
|
| 250 |
interactive=False,
|
| 251 |
wrap=True
|
| 252 |
)
|
| 253 |
|
| 254 |
+
enrichment_status = gr.Textbox(
|
|
|
|
| 255 |
label="Status",
|
| 256 |
interactive=False,
|
| 257 |
+
lines=2
|
| 258 |
)
|
| 259 |
|
| 260 |
+
# Event handlers
|
| 261 |
+
def handle_validation(file_obj, username):
|
| 262 |
+
df, status = process_csv_upload(file_obj, username)
|
| 263 |
+
if df is not None:
|
| 264 |
+
return status, gr.update(visible=True), df
|
| 265 |
+
return status, gr.update(visible=True), None
|
| 266 |
+
|
| 267 |
+
def handle_enrichment(df_state, username, selected_apis):
|
| 268 |
+
if df_state is None:
|
| 269 |
+
return None, "β Please validate data first"
|
| 270 |
+
result_df, status = enrich_contacts(df_state, username, selected_apis if selected_apis else ["manual"])
|
| 271 |
+
return result_df, status
|
| 272 |
+
|
| 273 |
+
# Store dataframe state
|
| 274 |
+
df_state = gr.State(value=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
|
| 276 |
process_btn.click(
|
| 277 |
+
fn=handle_validation,
|
| 278 |
inputs=[csv_file, username_input],
|
| 279 |
+
outputs=[validation_output, api_checkboxes, df_state]
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
enrich_btn.click(
|
| 283 |
+
fn=handle_enrichment,
|
| 284 |
+
inputs=[df_state, username_input, api_checkboxes],
|
| 285 |
+
outputs=[output_table, enrichment_status]
|
| 286 |
)
|
| 287 |
|
| 288 |
+
with gr.Tab("β
Validation Rules"):
|
| 289 |
+
gr.Markdown("""
|
| 290 |
+
## CSV Validation Checks
|
| 291 |
+
|
| 292 |
+
### Required
|
| 293 |
+
- CSV must have name, email, and company columns
|
| 294 |
+
- File must not be empty
|
| 295 |
+
- Maximum 10,000 rows per upload
|
| 296 |
+
|
| 297 |
+
### Data Validation
|
| 298 |
+
- **Email**: Must be valid format (name@domain.com)
|
| 299 |
+
- **Domain**: Must contain '.' and be at least 4 characters
|
| 300 |
+
- **Phone**: Must contain at least 7 digits
|
| 301 |
+
- **Duplicates**: Flagged if found
|
| 302 |
+
- **Missing Values**: Flagged in required columns
|
| 303 |
+
|
| 304 |
+
### Sanitization
|
| 305 |
+
- Leading/trailing whitespace removed
|
| 306 |
+
- Null characters stripped
|
| 307 |
+
- String length limited to 255 chars
|
| 308 |
+
- Special characters preserved for enrichment
|
| 309 |
""")
|
| 310 |
|
| 311 |
with gr.Tab("π Documentation"):
|
| 312 |
gr.Markdown("""
|
| 313 |
+
## Phase 1: Input Validation & Selective Enrichment
|
| 314 |
+
|
| 315 |
+
### What's New:
|
| 316 |
+
β
**CSV Schema Validation** - Ensures required columns and data types
|
| 317 |
+
β
**Data Quality Checks** - Validates email, domain, phone formats
|
| 318 |
+
β
**Input Sanitization** - Cleans and normalizes data
|
| 319 |
+
β
**Selective APIs** - Choose which enrichment providers to use
|
| 320 |
+
β
**Detailed Feedback** - Clear validation and error messages
|
| 321 |
+
|
| 322 |
+
### Features:
|
| 323 |
+
- Duplicate detection
|
| 324 |
+
- Missing value flagging
|
| 325 |
+
- File size warnings
|
| 326 |
+
- Format validation
|
| 327 |
+
- Data normalization
|
| 328 |
+
|
| 329 |
+
### Next (Phase 2):
|
| 330 |
+
- Live API enrichment processing
|
| 331 |
+
- Stream results as they complete
|
| 332 |
+
- Analytics dashboard
|
| 333 |
+
- Progress indicators
|
| 334 |
""")
|
| 335 |
|
| 336 |
if __name__ == "__main__":
|
| 337 |
+
logger.info("Starting StrategyStack Phase 1 with validation")
|
| 338 |
demo.launch()
|