Download app/csv_importer.py from awolter/gelpredict: direct link, hf CLI and curl.
- Browser
- Download file 9.56 kB
-
https://huggingface.co/datasets/awolter/gelpredict/resolve/main/app/csv_importer.py
- Command line
-
hf download hf://datasets/awolter/gelpredict/app/csv_importer.py
-
curl -L -o csv_importer.py https://huggingface.co/datasets/awolter/gelpredict/resolve/main/app/csv_importer.py
9.56 kB
| """ | |
| CSV Importer for GelPredict | |
| Validates data against FIELD_SPEC before committing to database. | |
| Provides preview, column mapping, and row-level error reporting. | |
| """ | |
| import pandas as pd | |
| import streamlit as st | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple | |
| import io | |
| # Import from data_entry_gui | |
| from data_entry_gui import ( | |
| FIELD_SPEC, validate_against_spec, tx, new_record_id, | |
| create_well, add_reagent, ensure_default_plate_if_unset, | |
| sanitize_and_enrich_well_payload, coerce_payload, load_codebook | |
| ) | |
| def detect_column_mapping(csv_columns: List[str], table: str) -> Dict[str, str]: | |
| """ | |
| Auto-detect column mapping from CSV headers to FIELD_SPEC fields. | |
| Args: | |
| csv_columns: List of column names from CSV | |
| table: Target table name | |
| Returns: | |
| Dictionary mapping CSV column → FIELD_SPEC field | |
| """ | |
| if table not in FIELD_SPEC: | |
| return {} | |
| spec_fields = list(FIELD_SPEC[table].keys()) | |
| mapping = {} | |
| for csv_col in csv_columns: | |
| # Normalize: lowercase, strip whitespace | |
| csv_col_norm = csv_col.lower().strip() | |
| # Try exact match | |
| if csv_col in spec_fields: | |
| mapping[csv_col] = csv_col | |
| continue | |
| # Try case-insensitive match | |
| for spec_field in spec_fields: | |
| if csv_col_norm == spec_field.lower(): | |
| mapping[csv_col] = spec_field | |
| break | |
| # Try partial match (e.g., "Operator" → "operator_id") | |
| if csv_col not in mapping: | |
| for spec_field in spec_fields: | |
| if csv_col_norm in spec_field.lower() or spec_field.lower() in csv_col_norm: | |
| mapping[csv_col] = spec_field | |
| break | |
| return mapping | |
| def validate_csv_rows(df: pd.DataFrame, column_mapping: Dict[str, str], table: str) -> List[Dict]: | |
| """ | |
| Validate all rows in DataFrame against FIELD_SPEC. | |
| Args: | |
| df: DataFrame to validate | |
| column_mapping: Mapping of CSV columns → FIELD_SPEC fields | |
| table: Target table name | |
| Returns: | |
| List of error dictionaries (empty if all valid) | |
| Each error: {"row": int, "field": str, "error": str} | |
| """ | |
| errors = [] | |
| codebook = load_codebook() | |
| for idx, row in df.iterrows(): | |
| # Build payload from mapped columns | |
| payload = {} | |
| for csv_col, spec_field in column_mapping.items(): | |
| if csv_col in row: | |
| val = None if pd.isna(row[csv_col]) else row[csv_col] | |
| payload[spec_field] = val | |
| # Coerce then validate | |
| payload = coerce_payload(table, payload, codebook) | |
| row_errors = validate_against_spec(table, FIELD_SPEC, payload) | |
| for error in row_errors: | |
| errors.append({ | |
| "row": int(idx) + 1, # 1-indexed for user display | |
| "field": error.split()[0] if error else "unknown", | |
| "error": error | |
| }) | |
| return errors | |
| def import_wells_csv(df: pd.DataFrame, column_mapping: Dict[str, str]) -> Tuple[int, List[str]]: | |
| """ | |
| Import wells from CSV into database (with transaction). | |
| Args: | |
| df: DataFrame with well data | |
| column_mapping: Mapping of CSV columns → FIELD_SPEC fields | |
| Returns: | |
| Tuple of (success_count, error_messages) | |
| """ | |
| success_count = 0 | |
| errors = [] | |
| codebook = load_codebook() | |
| for idx, row in df.iterrows(): | |
| try: | |
| # Build payload | |
| payload = {"record_id": new_record_id()} | |
| for csv_col, spec_field in column_mapping.items(): | |
| if csv_col in row and not pd.isna(row[csv_col]): | |
| payload[spec_field] = row[csv_col] | |
| # Coerce types for consistent typing | |
| payload = coerce_payload("wells_master_v4", payload, codebook) | |
| # Ensure plate geometry registered | |
| if payload.get("plate_id"): | |
| ensure_default_plate_if_unset(str(payload["plate_id"])) | |
| # Sanitize and enrich (correct signature: returns tuple) | |
| payload, _ = sanitize_and_enrich_well_payload(payload, []) | |
| # Create well (no reagents in basic CSV import) | |
| create_well(payload, reagents_list=[]) | |
| success_count += 1 | |
| except Exception as e: | |
| errors.append(f"Row {int(idx)+1}: {str(e)}") | |
| return success_count, errors | |
| def show_csv_importer(): | |
| """ | |
| Streamlit UI for CSV import wizard. | |
| """ | |
| st.header("📂 CSV Import Wizard") | |
| st.caption("Import wells from CSV with validation before commit") | |
| # Step 1: Upload CSV | |
| st.subheader("1️⃣ Upload CSV") | |
| uploaded_file = st.file_uploader( | |
| "Choose a CSV file", | |
| type=["csv"], | |
| help="CSV must contain well metadata columns" | |
| ) | |
| if not uploaded_file: | |
| st.info("👆 Upload a CSV file to begin") | |
| return | |
| # Load CSV | |
| try: | |
| df = pd.read_csv(uploaded_file) | |
| st.success(f"✅ Loaded {len(df)} rows, {len(df.columns)} columns") | |
| except Exception as e: | |
| st.error(f"❌ Failed to load CSV: {e}") | |
| return | |
| # Preview | |
| with st.expander("📊 Preview Data", expanded=True): | |
| st.dataframe(df.head(20), use_container_width=True) | |
| # Step 2: Column Mapping | |
| st.subheader("2️⃣ Map Columns") | |
| st.caption("Map CSV columns to database fields") | |
| # Auto-detect mapping | |
| auto_mapping = detect_column_mapping(df.columns.tolist(), "wells_master_v4") | |
| # Manual override | |
| st.markdown("**Column Mapping:**") | |
| col1, col2 = st.columns(2) | |
| mapping = {} | |
| spec_fields = ["(skip)"] + list(FIELD_SPEC["wells_master_v4"].keys()) | |
| for i, csv_col in enumerate(df.columns): | |
| # Default to auto-detected or skip | |
| default_idx = 0 | |
| if csv_col in auto_mapping: | |
| try: | |
| default_idx = spec_fields.index(auto_mapping[csv_col]) | |
| except: | |
| pass | |
| # Show mapping selector | |
| with col1 if i % 2 == 0 else col2: | |
| mapped_field = st.selectbox( | |
| f"CSV: `{csv_col}`", | |
| spec_fields, | |
| index=default_idx, | |
| key=f"map_{csv_col}" | |
| ) | |
| if mapped_field != "(skip)": | |
| mapping[csv_col] = mapped_field | |
| if not mapping: | |
| st.warning("⚠️ No columns mapped. Map at least one column to proceed.") | |
| return | |
| st.success(f"✅ Mapped {len(mapping)} columns") | |
| # Step 3: Validation | |
| st.subheader("3️⃣ Validate Data") | |
| if st.button("🔍 Validate All Rows", type="primary"): | |
| with st.spinner("Validating..."): | |
| errors = validate_csv_rows(df, mapping, "wells_master_v4") | |
| if not errors: | |
| st.success(f"✅ All {len(df)} rows passed validation!") | |
| st.session_state["csv_validation_passed"] = True | |
| st.session_state["csv_df"] = df | |
| st.session_state["csv_mapping"] = mapping | |
| else: | |
| st.error(f"❌ Found {len(errors)} validation errors") | |
| st.session_state["csv_validation_passed"] = False | |
| # Show errors | |
| with st.expander("View Errors", expanded=True): | |
| error_df = pd.DataFrame(errors) | |
| st.dataframe(error_df, use_container_width=True) | |
| # Download errors | |
| error_csv = error_df.to_csv(index=False) | |
| st.download_button( | |
| "⬇️ Download Errors (CSV)", | |
| error_csv, | |
| file_name="validation_errors.csv", | |
| mime="text/csv" | |
| ) | |
| # Step 4: Import | |
| if st.session_state.get("csv_validation_passed"): | |
| st.markdown("---") | |
| st.subheader("4️⃣ Import to Database") | |
| st.warning("⚠️ This will create new well records. Proceed with caution!") | |
| col_a, col_b, col_c = st.columns([1, 1, 2]) | |
| with col_a: | |
| confirm = st.checkbox("I confirm import") | |
| with col_b: | |
| if st.button("💾 Import Now", type="primary", disabled=not confirm): | |
| with st.spinner("Importing..."): | |
| success_count, import_errors = import_wells_csv( | |
| st.session_state["csv_df"], | |
| st.session_state["csv_mapping"] | |
| ) | |
| if not import_errors: | |
| st.success(f"🎉 Successfully imported {success_count} wells!") | |
| st.balloons() | |
| # Clear session state | |
| st.session_state["csv_validation_passed"] = False | |
| else: | |
| st.error(f"⚠️ Imported {success_count} wells, but {len(import_errors)} failed") | |
| with st.expander("View Import Errors"): | |
| for err in import_errors: | |
| st.text(err) | |
| with col_c: | |
| st.caption("Imports are atomic per row (if one field fails, entire row is skipped)") | |
| if __name__ == "__main__": | |
| # For testing standalone | |
| st.set_page_config(page_title="CSV Importer", page_icon="📂") | |
| show_csv_importer() | |