Spaces:
Sleeping

Digitalytics / src /services /zip_resolution_service.py
faseehsandhu's picture
add use-case area recommender, explore drill-in, and name resolution
3d61cb9
Raw History Blame Contribute Delete
6.04 kB
"""
ZIP Resolution Service for Area Insights
This module provides functionality to convert area names (city, locality, region)
to US ZIP codes using the Nominatim geocoding API from OpenStreetMap.
"""
import re
import time
import requests
import logging
from typing import Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
class ZipResolutionService:
"""Service for resolving area names to US ZIP codes using Nominatim API."""
def __init__(self):
"""Initialize the ZIP resolution service with Nominatim API configuration."""
self.base_url = "https://nominatim.openstreetmap.org"
self.user_agent = "StreamlitDataDictBot/1.0"
self.last_request_time = 0
self.min_delay = 1.0 # Nominatim requires 1 second between requests
self._cache = {} # Cache resolved ZIP codes
def _wait_for_rate_limit(self):
"""Ensure at least 1 second has passed since the last API request."""
current_time = time.time()
time_since_last = current_time - self.last_request_time
if time_since_last < self.min_delay:
time.sleep(self.min_delay - time_since_last)
self.last_request_time = time.time()
def _validate_zip(self, zip_code: str) -> bool:
"""
Validate that ZIP code is a 5-digit US format.
Args:
zip_code: ZIP code string to validate
Returns:
True if valid 5-digit ZIP, False otherwise
"""
if not zip_code:
return False
zip_pattern = re.compile(r'^\d{5}$')
return bool(zip_pattern.match(zip_code.strip()))
def _normalize_zip(self, zip_code: str) -> Optional[str]:
"""
Normalize ZIP code to 5-digit format.
Args:
zip_code: ZIP code string (may include ZIP+4 format)
Returns:
5-digit ZIP code or None if invalid
"""
if not zip_code:
return None
# Extract first 5 digits
zip_match = re.search(r'\d{5}', str(zip_code))
if zip_match:
return zip_match.group(0)
return None
def get_nearby_zips(self, zip_code: str, available_zips: set, radius_miles: float = 10) -> List[str]:
"""
Get nearby ZIP codes that have data available.
Args:
zip_code: The ZIP code to search around
available_zips: Set of ZIP codes that have data in datasets
radius_miles: Search radius in miles (default: 10)
Returns:
List of nearby ZIP codes (limited to 5 suggestions)
"""
if not self._validate_zip(zip_code):
logger.warning(f"Invalid ZIP code for nearby search: {zip_code}")
return []
# If the ZIP itself has data, return empty (no suggestions needed)
if zip_code in available_zips:
return []
suggestions = []
try:
# Respect rate limiting
self._wait_for_rate_limit()
# Get coordinates for the ZIP code
params = {
'postalcode': zip_code,
'country': 'us',
'format': 'json',
'limit': 1
}
headers = {
'User-Agent': self.user_agent
}
response = requests.get(
f"{self.base_url}/search",
params=params,
headers=headers,
timeout=10
)
response.raise_for_status()
data = response.json()
if not data:
logger.warning(f"No coordinates found for ZIP {zip_code}")
return []
lat = float(data[0]['lat'])
lon = float(data[0]['lon'])
# Calculate approximate lat/lon box (1 degree ≈ 69 miles)
degree_offset = radius_miles / 69.0
# For simplicity, find ZIP codes with similar prefixes
# (Real geographic distance calculation would require all ZIP coordinates)
zip_prefix = zip_code[:3]
for available_zip in available_zips:
if available_zip.startswith(zip_prefix):
suggestions.append(available_zip)
if len(suggestions) >= 5:
break
logger.info(f"Found {len(suggestions)} nearby ZIPs for {zip_code}")
except Exception as e:
logger.error(f"Error finding nearby ZIPs for {zip_code}: {e}")
return suggestions[:5] # Limit to 5 suggestions
def manual_zip_entry(self, zip_code: str) -> Dict[str, Optional[str]]:
"""
Validate and process a manually entered ZIP code.
Args:
zip_code: User-provided ZIP code string
Returns:
Dictionary with validation result and normalized ZIP
"""
result = {
'zip_code': None,
'normalized_address': None,
'error': None,
'display_name': None
}
normalized = self._normalize_zip(zip_code)
if normalized and self._validate_zip(normalized):
result['zip_code'] = normalized
result['display_name'] = f"ZIP Code: {normalized}"
result['normalized_address'] = f"US ZIP {normalized}"
logger.info(f"Manual ZIP entry validated: {normalized}")
else:
result['error'] = f"Invalid ZIP code format: '{zip_code}'. Please enter a 5-digit US ZIP code."
logger.warning(f"Invalid manual ZIP entry: {zip_code}")
return result
def clear_cache(self):
"""Clear the resolution cache."""
self._cache.clear()
logger.info("ZIP resolution cache cleared")