""" Offline Dataset Service for Area Insights This module manages loading and querying of offline datasets stored locally. Supports CSV and Excel files with automatic ZIP code column detection. """ import re import logging from pathlib import Path from typing import Dict, List, Optional, Set import pandas as pd logger = logging.getLogger(__name__) class OfflineDatasetService: """Service for managing and querying offline datasets by ZIP code.""" def __init__(self, datasets_path: str = "data/offline_datasets", data_dictionary_service=None): """ Initialize the offline dataset service. Args: datasets_path: Path to the directory containing offline datasets data_dictionary_service: Optional data dictionary service for metadata hints """ self.datasets_path = Path(datasets_path) self.data_dictionary_service = data_dictionary_service self._datasets = {} # Dictionary of {filename: DataFrame} self._zip_columns = {} # Dictionary of {filename: zip_column_name} self._available_zips = set() # Set of all unique ZIP codes across datasets self._column_hints = {} # Dictionary of {filename: {column_name: description}} # Create directory if it doesn't exist self.datasets_path.mkdir(parents=True, exist_ok=True) # Parse data dictionaries for column hints self._parse_data_dictionaries() # Load datasets on initialization self._load_datasets() def _parse_data_dictionaries(self): """ Parse data dictionaries to find ZIP/FIPS column hints for each dataset. Looks for patterns like 'zip', 'fips', 'postal' in column names and descriptions. """ if not self.data_dictionary_service: logger.info("No data dictionary service provided, skipping column hints parsing") return logger.info("Parsing data dictionaries for column hints...") try: dictionaries = self.data_dictionary_service.get_all_dictionaries() if not dictionaries: logger.info("No dictionaries available to parse") return # Handle both dict and list return types dict_items = dictionaries.items() if isinstance(dictionaries, dict) else [(d.get('name', ''), d.get('content', '')) for d in dictionaries] for dict_name, dict_content in dict_items: # Extract dataset name from dictionary name (e.g., "SVI_2022_DICTIONARY" -> "SVI_2022") dataset_base = Path(dict_name).stem # Common patterns for dataset name matching dataset_patterns = [ dataset_base, dataset_base.replace('_DICTIONARY', ''), dataset_base.replace('_DATADICTIONARY', ''), dataset_base.replace('DICTIONARY', ''), dataset_base.split('_')[0], # First part (e.g., "SVI" from "SVI_2022") ] # Parse the dictionary content for column information # Look for lines containing column names and descriptions lines = dict_content.split('\n') zip_keywords = ['zip', 'zipcode', 'zip code', 'postal', 'fips', 'zcta', 'census tract', 'geographic identifier', 'geoid'] for line in lines: line_lower = line.lower() # Check if this line mentions a ZIP/FIPS column for keyword in zip_keywords: if keyword in line_lower: # Try to extract column name (usually first word or before a delimiter) # Common formats: "column_name | description" or "column_name: description" parts = re.split(r'[|:\t,]', line) if parts: potential_col = parts[0].strip() # Remove common prefixes potential_col = re.sub(r'^(column|field|variable)\s*[:\-]?\s*', '', potential_col, flags=re.IGNORECASE) potential_col = potential_col.strip('*"\'` ') if potential_col and len(potential_col) < 50: # Sanity check # Store hint for all matching dataset patterns for pattern in dataset_patterns: if pattern not in self._column_hints: self._column_hints[pattern] = set() self._column_hints[pattern].add(potential_col) logger.info(f"Found ZIP column hint '{potential_col}' for dataset pattern '{dataset_base}' (keyword: '{keyword}')") break logger.info(f"Parsed data dictionaries, found hints for {len(self._column_hints)} dataset patterns") except Exception as e: logger.error(f"Error parsing data dictionaries for column hints: {e}") def _get_column_hint(self, dataset_name: str) -> Optional[Set[str]]: """ Get column hints for a dataset based on its name. Args: dataset_name: Name of the dataset file (without extension) Returns: Set of potential column names, or None if no hints found """ # Try exact match first if dataset_name in self._column_hints: return self._column_hints[dataset_name] # Try partial matches for pattern, columns in self._column_hints.items(): if pattern.lower() in dataset_name.lower() or dataset_name.lower() in pattern.lower(): return columns return None def _detect_zip_column(self, df: pd.DataFrame, dataset_name: str = None) -> Optional[str]: """ Auto-detect ZIP code column in a DataFrame using data dictionary hints and pattern matching. Args: df: DataFrame to search for ZIP column dataset_name: Optional dataset name for looking up hints Returns: Name of the ZIP column, or None if not found """ # Priority 1: Check data dictionary hints if available if dataset_name: hints = self._get_column_hint(dataset_name) if hints: logger.info(f"Checking column hints for '{dataset_name}': {hints}") for hint in hints: # Try exact match (case-insensitive) for col in df.columns: if str(col).lower().strip() == hint.lower().strip(): # Validate this column contains ZIP-like data if self._validate_zip_column(df, col): logger.info(f"✓ Detected ZIP column from dictionary hint: '{col}'") return col # Try partial match for col in df.columns: col_lower = str(col).lower().strip() hint_lower = hint.lower().strip() if hint_lower in col_lower or col_lower in hint_lower: if self._validate_zip_column(df, col): logger.info(f"✓ Detected ZIP column from partial hint match: '{col}' (hint: '{hint}')") return col # Priority 2: Pattern matching on column names zip_patterns = [ # Exact matches (highest priority) r'^zip$', r'^zipcode$', r'^zip_code$', r'^postal$', r'^postal_code$', r'^postalcode$', r'^zcta$', # ZIP Code Tabulation Area r'^zcta5$', # 5-digit ZCTA r'^geoid$', # Geographic identifier (often ZIP) r'^fips$', # FIPS code (might be ZIP) r'fips.*cnty', # County FIPS (might contain ZIP) # Contains patterns r'zip', r'postal', r'zcta' ] for col in df.columns: col_lower = str(col).lower().strip() for pattern in zip_patterns: if re.search(pattern, col_lower): if self._validate_zip_column(df, col): logger.info(f"[OK] Detected ZIP column by pattern: '{col}'") return col # Priority 3: Check FIPS and LOCATION columns for ZIP-like data potential_cols = [] for col in df.columns: col_lower = str(col).lower().strip() if col_lower in ['fips', 'location', 'geoid', 'tract', 'area', 'region']: potential_cols.append(col) for col in potential_cols: if self._validate_zip_column(df, col): logger.info(f"[OK] Detected ZIP column by content validation: '{col}'") return col logger.warning(f"No ZIP column detected in dataset with columns: {df.columns.tolist()}") return None def _validate_zip_column(self, df: pd.DataFrame, col: str) -> bool: """ Validate if a column contains ZIP code data. Args: df: DataFrame containing the column col: Column name to validate Returns: True if column contains ZIP-like data, False otherwise """ try: # Sample first 100 non-null values sample = df[col].dropna().head(100) if len(sample) == 0: return False # Check if values look like ZIP codes (4 or 5 digits) zip_like_count = 0 for val in sample: # Convert to string and check format val_str = str(val).strip() # Remove decimal point if present if '.' in val_str: val_str = val_str.split('.')[0] # Check if it's a 4 or 5-digit number (handles leading zeros) if re.match(r'^\d{4,5}$', val_str): zip_like_count += 1 # Also check for ZIP codes stored as integers (without leading zeros) elif val_str.isdigit() and 3 <= len(val_str) <= 5: zip_like_count += 1 # If more than 70% of samples look like ZIP codes, accept this column threshold = 0.7 is_valid = (zip_like_count / len(sample)) > threshold if is_valid: logger.debug(f"Column '{col}' validated as ZIP column: {zip_like_count}/{len(sample)} ZIP-like values ({zip_like_count/len(sample)*100:.1f}%)") return is_valid except Exception as e: logger.error(f"Error validating column '{col}': {e}") return False def _normalize_zip(self, zip_value) -> Optional[str]: """ Normalize ZIP code value to 5-digit format. Args: zip_value: ZIP code value (may be string, int, or float) Returns: 5-digit ZIP code string, or None if invalid """ if pd.isna(zip_value): return None # Convert to string and strip whitespace zip_str = str(zip_value).strip() # Remove decimal point if present (from float conversion) if '.' in zip_str: zip_str = zip_str.split('.')[0] # Handle integers that might be missing leading zeros if zip_str.isdigit(): # If it's 4 digits or less, pad with leading zeros to make 5 digits if len(zip_str) <= 4: zip_str = zip_str.zfill(5) # If it's exactly 5 digits, use as is elif len(zip_str) == 5: return zip_str # If it's more than 5 digits, try to extract first 5 else: zip_match = re.search(r'\d{5}', zip_str) if zip_match: return zip_match.group(0) # Extract first 5 digits (handles ZIP+4 format and other variations) zip_match = re.search(r'\d{5}', zip_str) if zip_match: return zip_match.group(0) return None def _load_datasets(self): """Load all CSV and Excel files from the datasets directory.""" if not self.datasets_path.exists(): logger.warning(f"Datasets directory does not exist: {self.datasets_path}") return # Supported file extensions extensions = ['*.csv', '*.xlsx', '*.xls'] loaded_count = 0 for pattern in extensions: for file_path in self.datasets_path.glob(pattern): try: logger.info(f"Loading dataset: {file_path.name}") # Load based on file type if file_path.suffix.lower() == '.csv': # Try multiple encodings for CSV files df = None encodings = ['utf-8', 'latin-1', 'iso-8859-1', 'cp1252'] for encoding in encodings: try: df = pd.read_csv(file_path, dtype=str, low_memory=False, encoding=encoding) break except UnicodeDecodeError: continue if df is None: logger.error(f"Could not read CSV {file_path.name} with any supported encoding") continue else: # Excel files # For Excel files, try to find a sheet with ZIP data try: excel_file = pd.ExcelFile(file_path) df = None found_header_row = None # Try each sheet to find one with ZIP codes for sheet_name in excel_file.sheet_names: try: # First, read without header to check first 3 rows for column names temp_df = pd.read_excel(file_path, sheet_name=sheet_name, dtype=str, header=None) if temp_df.empty or len(temp_df) < 1: continue # Check rows 0, 1, 2 for ZIP column names header_row = None for row_idx in range(min(3, len(temp_df))): row_values = temp_df.iloc[row_idx].astype(str).values # Check if this row looks like headers (has ZIP-related keywords) row_text = ' '.join(str(v).lower() for v in row_values) if any(keyword in row_text for keyword in ['zip', 'fips', 'zcta', 'postal']): header_row = row_idx logger.info(f"Found potential header row {row_idx} in sheet '{sheet_name}': {row_values[:5]}...") break # If no header with ZIP keywords found, default to first row (0) if header_row is None: # Try loading with first row as header anyway header_row = 0 logger.debug(f"No ZIP keyword found in first 3 rows, trying row 0 as header") # Load with detected header row sheet_df = pd.read_excel(file_path, sheet_name=sheet_name, dtype=str, header=header_row) if not sheet_df.empty: # Check if this sheet has a ZIP column dataset_name = file_path.stem zip_col = self._detect_zip_column(sheet_df, dataset_name) if zip_col: df = sheet_df logger.info(f"Found ZIP column '{zip_col}' in sheet '{sheet_name}' (header row: {header_row}) of {file_path.name}") break else: logger.debug(f"Sheet '{sheet_name}' has no ZIP column") except Exception as e: logger.debug(f"Could not process sheet '{sheet_name}' from {file_path.name}: {e}") continue if df is None: logger.warning(f"No sheets with ZIP data found in {file_path.name}") continue except Exception as e: logger.error(f"Error reading Excel file {file_path.name}: {e}") continue if df.empty: logger.warning(f"Dataset is empty: {file_path.name}") continue # Get dataset name for hint lookup dataset_name = file_path.stem # Detect ZIP column (pass dataset name for hint lookup) zip_col = self._detect_zip_column(df, dataset_name) if zip_col: # Store dataset and ZIP column name self._datasets[dataset_name] = df self._zip_columns[dataset_name] = zip_col # Collect all unique ZIP codes zip_values = df[zip_col].apply(self._normalize_zip).dropna().unique() self._available_zips.update(zip_values) loaded_count += 1 logger.info(f"[SUCCESS] Loaded '{dataset_name}' with {len(df)} rows, {len(zip_values)} unique ZIPs, column: '{zip_col}'") else: logger.warning(f"[WARNING] Skipping '{file_path.name}' - no ZIP column detected") except Exception as e: logger.error(f"❌ Error loading dataset '{file_path.name}': {e}") logger.info(f"Loaded {loaded_count} datasets with {len(self._available_zips)} unique ZIP codes") def query_by_zip(self, zip_code: str) -> Dict[str, Dict]: """ Query all datasets for rows matching the given ZIP code. Args: zip_code: 5-digit US ZIP code to search for Returns: Dictionary with structure: { 'dataset_name': { 'rows': DataFrame with matching rows, 'columns': List of column names, 'row_count': Number of matching rows }, ... } """ results = {} # Normalize input ZIP normalized_zip = self._normalize_zip(zip_code) if not normalized_zip: logger.warning(f"Invalid ZIP code format: {zip_code}") return results logger.info(f"Querying datasets for ZIP: {normalized_zip}") for dataset_name, df in self._datasets.items(): try: zip_col = self._zip_columns[dataset_name] logger.info(f"\n=== Querying {dataset_name} ===") logger.info(f"ZIP column: {zip_col}") logger.info(f"Total rows in dataset: {len(df)}") # Normalize all ZIP values in the column for comparison df_copy = df.copy() df_copy['_normalized_zip'] = df_copy[zip_col].apply(self._normalize_zip) # Filter rows matching the ZIP code matching_rows = df_copy[df_copy['_normalized_zip'] == normalized_zip] # Remove the temporary normalized column matching_rows = matching_rows.drop(columns=['_normalized_zip']) if not matching_rows.empty: logger.info(f"Found {len(matching_rows)} matching rows for ZIP {normalized_zip}") # Log all values in the matching rows for verification logger.info(f"VALUES FROM {dataset_name} for ZIP {normalized_zip}:") for col in matching_rows.columns: values = matching_rows[col].values if len(values) > 0: val = values[0] logger.info(f" {col} = {repr(val)} (type: {type(val).__name__})") results[dataset_name] = { 'rows': matching_rows, 'columns': matching_rows.columns.tolist(), 'row_count': len(matching_rows) } else: logger.info(f"No matching rows found in '{dataset_name}' for ZIP {normalized_zip}") except Exception as e: logger.error(f"Error querying dataset '{dataset_name}' for ZIP {normalized_zip}: {e}") if not results: logger.info(f"No data found for ZIP {normalized_zip} in any dataset") else: logger.info(f"\nQuery Summary: Found data in {len(results)} datasets for ZIP {normalized_zip}") return results def get_available_zips(self) -> Set[str]: """ Get all unique ZIP codes available across all datasets. Returns: Set of ZIP code strings """ return self._available_zips.copy() def get_dataset_info(self) -> List[Dict]: """ Get information about all loaded datasets. Returns: List of dictionaries with dataset metadata """ info = [] for dataset_name, df in self._datasets.items(): info.append({ 'name': dataset_name, 'rows': len(df), 'columns': len(df.columns), 'zip_column': self._zip_columns.get(dataset_name), 'unique_zips': df[self._zip_columns[dataset_name]].apply(self._normalize_zip).nunique() }) return info def reload_datasets(self): """Reload all datasets from the directory.""" self._datasets.clear() self._zip_columns.clear() self._available_zips.clear() self._load_datasets() logger.info("Datasets reloaded") def has_data_for_zip(self, zip_code: str) -> bool: """ Check if any dataset contains data for the given ZIP code. Args: zip_code: ZIP code to check Returns: True if data exists, False otherwise """ normalized_zip = self._normalize_zip(zip_code) return normalized_zip in self._available_zips if normalized_zip else False def get_column_values(self, zip_code: str, column_name: str) -> List[tuple]: """ Get all values for a specific column across datasets for a ZIP code. Args: zip_code: ZIP code to filter by column_name: Column name to extract Returns: List of tuples: (dataset_name, value) """ results = [] query_results = self.query_by_zip(zip_code) for dataset_name, data in query_results.items(): df = data['rows'] if column_name in df.columns: for value in df[column_name].dropna().unique(): results.append((dataset_name, value)) return results