Spaces:
Sleeping
Sleeping
Commit ·
3d61cb9
1
Parent(s): db9343f
add use-case area recommender, explore drill-in, and name resolution
Browse files- new Recommend Areas tab: free-text use case -> ranked top-N via LLM function calling + min-max weighted composite score
- new AreaRankingService with metric-kind tagging (prefer rate over count) so results aren't just the biggest counties
- Explore button on each result opens per-area chat
- FIPS names via AHRF lookup, ZCTAs via pgeocode (new dep)
- removed flaky city/state search and 50-state map; ZIP-only entry
- polish: live ZIP validation, mid-chat ZIP switch, short-msg bypass, batched column descriptions, magic numbers -> constants
- cleanup: dead _build_area_context helper, word-bounded column matching
- requirements.txt +2 -1
- src/components/area_insights_interface.py +391 -301
- src/services/area_ranking_service.py +638 -0
- src/services/zip_resolution_service.py +0 -173
requirements.txt
CHANGED
|
@@ -4,4 +4,5 @@ openai>=1.12.0
|
|
| 4 |
PyPDF2>=3.0.0
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
requests>=2.31.0
|
| 7 |
-
openpyxl>=3.1.0
|
|
|
|
|
|
| 4 |
PyPDF2>=3.0.0
|
| 5 |
python-dotenv>=1.0.0
|
| 6 |
requests>=2.31.0
|
| 7 |
+
openpyxl>=3.1.0
|
| 8 |
+
pgeocode>=0.5.0
|
src/components/area_insights_interface.py
CHANGED
|
@@ -6,15 +6,24 @@ combining ZIP code resolution, offline dataset querying, and LLM responses.
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import logging
|
|
|
|
| 9 |
import streamlit as st
|
| 10 |
-
from typing import Dict, List, Optional
|
| 11 |
from services.azure_openai_service import AzureOpenAIService
|
| 12 |
from services.zip_resolution_service import ZipResolutionService
|
| 13 |
from services.offline_dataset_service import OfflineDatasetService
|
| 14 |
from services.retrieval_service import RetrievalService
|
|
|
|
| 15 |
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# Specialized system prompt for area insights
|
| 19 |
AREA_INSIGHTS_SYSTEM_PROMPT = """You are a geographical data analyst assistant providing insights about specific US areas.
|
| 20 |
|
|
@@ -68,136 +77,238 @@ class AreaInsightsInterface:
|
|
| 68 |
self.retrieval_service = retrieval_service
|
| 69 |
self.zip_service = zip_service
|
| 70 |
self.dataset_service = dataset_service
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
# Initialize session state for area insights
|
| 73 |
if 'area_chat_history' not in st.session_state:
|
| 74 |
st.session_state.area_chat_history = []
|
| 75 |
-
|
| 76 |
if 'area_current_zip' not in st.session_state:
|
| 77 |
st.session_state.area_current_zip = None
|
| 78 |
-
|
| 79 |
if 'area_current_name' not in st.session_state:
|
| 80 |
st.session_state.area_current_name = None
|
| 81 |
-
|
| 82 |
if 'area_chat_started' not in st.session_state:
|
| 83 |
st.session_state.area_chat_started = False
|
| 84 |
-
|
| 85 |
if 'area_no_data_warning' not in st.session_state:
|
| 86 |
st.session_state.area_no_data_warning = False
|
| 87 |
-
|
| 88 |
if 'area_column_descriptions' not in st.session_state:
|
| 89 |
st.session_state.area_column_descriptions = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
def display(self):
|
| 92 |
"""Display the area insights interface."""
|
| 93 |
st.subheader("🗺️ Area Insights Chatbot")
|
| 94 |
-
|
| 95 |
# Check if OpenAI service is configured
|
| 96 |
if not self.openai_service:
|
| 97 |
st.error("Azure OpenAI is not configured. Please set up your credentials.")
|
| 98 |
return
|
| 99 |
-
|
| 100 |
-
#
|
| 101 |
-
if
|
| 102 |
-
self._display_area_entry()
|
| 103 |
-
else:
|
| 104 |
self._display_chat()
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
def _display_area_entry(self):
|
| 107 |
-
"""
|
| 108 |
-
st.
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
- "Manhattan, NY" or "Manhattan, New York"
|
| 114 |
-
- "Austin, TX"
|
| 115 |
-
- Direct ZIP code: "01001" or "94102"
|
| 116 |
-
|
| 117 |
-
💡 **Tip:** Use city name with state abbreviation (e.g., "Boston, MA") for best results.
|
| 118 |
-
""")
|
| 119 |
-
|
| 120 |
-
# Tabs for area name or direct ZIP entry
|
| 121 |
-
tab1, tab2 = st.tabs(["🔍 Search by City/Area", "📍 Enter ZIP Code Directly"])
|
| 122 |
-
|
| 123 |
with tab1:
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
"Enter city and state:",
|
| 127 |
-
placeholder="e.g., Springfield, MA",
|
| 128 |
-
key="area_name_input",
|
| 129 |
-
help="Enter city name with state (full name or abbreviation)"
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
start_button = st.button("🚀 Start Chat", type="primary", disabled=not area_input, key="start_by_name")
|
| 133 |
-
|
| 134 |
-
if start_button and area_input:
|
| 135 |
-
with st.spinner("Resolving location..."):
|
| 136 |
-
self._resolve_and_start_chat(area_input)
|
| 137 |
-
# Stop execution here to prevent dual rendering
|
| 138 |
-
st.stop()
|
| 139 |
-
|
| 140 |
with tab2:
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
)
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
return
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
st.
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
def _start_chat_with_zip(self, resolution_result: Dict):
|
| 203 |
"""
|
|
@@ -262,16 +373,38 @@ class AreaInsightsInterface:
|
|
| 262 |
with st.sidebar:
|
| 263 |
st.divider()
|
| 264 |
st.subheader("Area Chat Controls")
|
| 265 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
if st.button("🔄 Start New Area Chat", help="Reset and choose a different area"):
|
| 267 |
self._reset_area_chat()
|
| 268 |
st.rerun()
|
| 269 |
-
|
| 270 |
if st.button("🗑️ Clear Chat History", help="Clear messages but keep current area"):
|
| 271 |
st.session_state.area_chat_history = []
|
| 272 |
st.session_state.area_column_descriptions = {}
|
| 273 |
st.rerun()
|
| 274 |
-
|
| 275 |
# Show dataset info
|
| 276 |
st.divider()
|
| 277 |
st.caption("**Available Datasets**")
|
|
@@ -347,6 +480,23 @@ class AreaInsightsInterface:
|
|
| 347 |
zip_code=zip_code
|
| 348 |
)
|
| 349 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
# Step 1: Define the data extraction tool for Azure OpenAI function calling
|
| 351 |
# This tells the model what "functions" it can call
|
| 352 |
tools = [
|
|
@@ -505,93 +655,91 @@ Provide a helpful response. You can use general knowledge about this area."""
|
|
| 505 |
|
| 506 |
def _get_relevant_columns(self, user_message: str, dataset_results: Dict) -> Dict[str, List[str]]:
|
| 507 |
"""
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
"""
|
| 517 |
-
relevant_columns = {}
|
| 518 |
-
|
| 519 |
-
# Get active dictionaries for search context
|
| 520 |
all_dicts = self.data_dictionary_service.get_all_dictionaries()
|
| 521 |
active_dicts = [d['name'] for d in all_dicts if d.get('active', True)]
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
# Map
|
| 525 |
-
|
| 526 |
-
logger.info(f"Datasets with data: {dataset_names_loaded}")
|
| 527 |
-
|
| 528 |
-
# Filter active dictionaries to only those matching loaded datasets
|
| 529 |
-
filtered_dicts = []
|
| 530 |
for dict_name in active_dicts:
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
# Check if dictionary name contains or matches dataset name
|
| 538 |
-
if (dataset_name_lower in dict_name_lower or
|
| 539 |
-
dict_name_lower in dataset_name_lower or
|
| 540 |
-
dict_name_lower.startswith(dataset_name_lower.split('_')[0])):
|
| 541 |
-
filtered_dicts.append(dict_name)
|
| 542 |
-
matches_dataset = True
|
| 543 |
-
logger.info(f"Matched dictionary '{dict_name}' to dataset '{dataset_name}'")
|
| 544 |
break
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
logger.info(f"Skipping dictionary '{dict_name}' (no matching dataset with data)")
|
| 548 |
-
|
| 549 |
-
logger.info(f"Searching {len(filtered_dicts)} relevant data dictionaries for columns matching: '{user_message}'")
|
| 550 |
-
|
| 551 |
if not filtered_dicts:
|
| 552 |
logger.warning("No dictionaries match the loaded datasets")
|
| 553 |
-
return
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
|
|
|
|
|
|
| 557 |
search_results = self.retrieval_service.search(
|
| 558 |
user_message,
|
| 559 |
-
filtered_dicts,
|
| 560 |
-
top_k=
|
| 561 |
-
disable_embeddings=False
|
| 562 |
)
|
| 563 |
-
|
| 564 |
if not search_results:
|
| 565 |
logger.info("No relevant columns found in data dictionaries")
|
| 566 |
-
return
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
for result in search_results:
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 595 |
return relevant_columns
|
| 596 |
|
| 597 |
def _build_smart_context(self, dataset_results: Dict, relevant_columns: Dict[str, List[str]], user_message: str) -> str:
|
|
@@ -680,130 +828,66 @@ Provide a helpful response. You can use general knowledge about this area."""
|
|
| 680 |
|
| 681 |
return result
|
| 682 |
|
| 683 |
-
def _build_area_context(self, dataset_results: Dict, user_message: str) -> str:
|
| 684 |
-
"""
|
| 685 |
-
Build context string combining dataset values and column descriptions.
|
| 686 |
-
|
| 687 |
-
Args:
|
| 688 |
-
dataset_results: Results from offline dataset query
|
| 689 |
-
user_message: User's message (for relevance filtering)
|
| 690 |
-
|
| 691 |
-
Returns:
|
| 692 |
-
Formatted context string
|
| 693 |
-
"""
|
| 694 |
-
if not dataset_results:
|
| 695 |
-
return ""
|
| 696 |
-
|
| 697 |
-
context_parts = []
|
| 698 |
-
context_parts.append("**Available Data for this Area:**\n")
|
| 699 |
-
|
| 700 |
-
# Collect only columns that will be displayed (first 10 per dataset)
|
| 701 |
-
displayed_columns = set()
|
| 702 |
-
for dataset_name, data in dataset_results.items():
|
| 703 |
-
for i, col in enumerate(data['columns']):
|
| 704 |
-
if i < 10: # Only first 10 columns per dataset
|
| 705 |
-
displayed_columns.add(col)
|
| 706 |
-
|
| 707 |
-
logger.info(f"Getting descriptions for {len(displayed_columns)} displayed columns (out of total columns across datasets)")
|
| 708 |
-
|
| 709 |
-
# Get column descriptions via embedding search (cached) - only for displayed columns
|
| 710 |
-
column_descriptions = self._get_column_descriptions(list(displayed_columns))
|
| 711 |
-
|
| 712 |
-
# Build formatted context
|
| 713 |
-
for dataset_name, data in dataset_results.items():
|
| 714 |
-
df = data['rows']
|
| 715 |
-
context_parts.append(f"\n**Dataset: {dataset_name}** ({data['row_count']} record(s))")
|
| 716 |
-
|
| 717 |
-
# Show up to 10 columns per dataset
|
| 718 |
-
displayed_cols = 0
|
| 719 |
-
for col in data['columns']:
|
| 720 |
-
if displayed_cols >= 10:
|
| 721 |
-
context_parts.append(f" ... and {len(data['columns']) - displayed_cols} more columns")
|
| 722 |
-
break
|
| 723 |
-
|
| 724 |
-
# Get first non-null value
|
| 725 |
-
values = df[col].dropna().unique()
|
| 726 |
-
if len(values) > 0:
|
| 727 |
-
value = values[0]
|
| 728 |
-
|
| 729 |
-
# Format value
|
| 730 |
-
if len(values) > 1:
|
| 731 |
-
value_str = f"{value} (+ {len(values)-1} other values)"
|
| 732 |
-
else:
|
| 733 |
-
value_str = str(value)
|
| 734 |
-
|
| 735 |
-
# Add description if available
|
| 736 |
-
desc = column_descriptions.get(col, "")
|
| 737 |
-
if desc:
|
| 738 |
-
context_parts.append(f" - **{col}**: {value_str}\n ℹ️ {desc}")
|
| 739 |
-
else:
|
| 740 |
-
context_parts.append(f" - **{col}**: {value_str}")
|
| 741 |
-
|
| 742 |
-
displayed_cols += 1
|
| 743 |
-
|
| 744 |
-
return "\n".join(context_parts)
|
| 745 |
-
|
| 746 |
def _get_column_descriptions(self, columns: List[str]) -> Dict[str, str]:
|
| 747 |
"""
|
| 748 |
-
Get descriptions for columns using
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
Returns:
|
| 754 |
-
Dictionary mapping column names to descriptions
|
| 755 |
"""
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
if not active_dicts:
|
| 770 |
logger.warning("No active data dictionaries for column description lookup")
|
| 771 |
-
return
|
| 772 |
-
|
| 773 |
-
#
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
query
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
|
|
|
|
|
|
| 807 |
|
| 808 |
def _show_debug_info(self, dataset_results: Dict, context: str, relevant_columns: Dict[str, List[str]] = None):
|
| 809 |
"""
|
|
@@ -828,7 +912,11 @@ Provide a helpful response. You can use general knowledge about this area."""
|
|
| 828 |
st.caption(f" {ds_name}: {', '.join(cols)}")
|
| 829 |
|
| 830 |
st.caption("**Context sent to LLM:**")
|
| 831 |
-
st.code(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 832 |
|
| 833 |
st.caption("**Cached Column Descriptions:**")
|
| 834 |
st.json(st.session_state.area_column_descriptions)
|
|
@@ -841,6 +929,8 @@ Provide a helpful response. You can use general knowledge about this area."""
|
|
| 841 |
st.session_state.area_chat_started = False
|
| 842 |
st.session_state.area_no_data_warning = False
|
| 843 |
st.session_state.area_column_descriptions = {}
|
|
|
|
|
|
|
| 844 |
if 'area_nearby_zips' in st.session_state:
|
| 845 |
del st.session_state.area_nearby_zips
|
| 846 |
logger.info("Area chat reset")
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import logging
|
| 9 |
+
import re
|
| 10 |
import streamlit as st
|
| 11 |
+
from typing import Dict, List, Optional, Set, Tuple
|
| 12 |
from services.azure_openai_service import AzureOpenAIService
|
| 13 |
from services.zip_resolution_service import ZipResolutionService
|
| 14 |
from services.offline_dataset_service import OfflineDatasetService
|
| 15 |
from services.retrieval_service import RetrievalService
|
| 16 |
+
from services.area_ranking_service import AreaRankingService
|
| 17 |
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
| 20 |
+
# Tunables
|
| 21 |
+
COLUMN_SEARCH_TOP_K = 20 # how many chunks to retrieve when matching user query to columns
|
| 22 |
+
MAX_RELEVANT_COLS_PER_DATASET = 10 # cap relevant columns included per dataset in LLM context
|
| 23 |
+
DESCRIPTION_MAX_CHARS = 200 # truncation cap for column descriptions
|
| 24 |
+
SHORT_MESSAGE_WORD_THRESHOLD = 3 # messages at/under this word count skip the decision LLM call
|
| 25 |
+
CONTEXT_PREVIEW_CHARS = 2000 # debug-panel context preview size
|
| 26 |
+
|
| 27 |
# Specialized system prompt for area insights
|
| 28 |
AREA_INSIGHTS_SYSTEM_PROMPT = """You are a geographical data analyst assistant providing insights about specific US areas.
|
| 29 |
|
|
|
|
| 77 |
self.retrieval_service = retrieval_service
|
| 78 |
self.zip_service = zip_service
|
| 79 |
self.dataset_service = dataset_service
|
| 80 |
+
|
| 81 |
+
# Ranking service (use-case → top areas). Built here so its lifetime matches the component.
|
| 82 |
+
self.ranking_service = (
|
| 83 |
+
AreaRankingService(
|
| 84 |
+
openai_service=self.openai_service,
|
| 85 |
+
retrieval_service=self.retrieval_service,
|
| 86 |
+
data_dictionary_service=self.data_dictionary_service,
|
| 87 |
+
dataset_service=self.dataset_service,
|
| 88 |
+
)
|
| 89 |
+
if self.openai_service else None
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
# Initialize session state for area insights
|
| 93 |
if 'area_chat_history' not in st.session_state:
|
| 94 |
st.session_state.area_chat_history = []
|
| 95 |
+
|
| 96 |
if 'area_current_zip' not in st.session_state:
|
| 97 |
st.session_state.area_current_zip = None
|
| 98 |
+
|
| 99 |
if 'area_current_name' not in st.session_state:
|
| 100 |
st.session_state.area_current_name = None
|
| 101 |
+
|
| 102 |
if 'area_chat_started' not in st.session_state:
|
| 103 |
st.session_state.area_chat_started = False
|
| 104 |
+
|
| 105 |
if 'area_no_data_warning' not in st.session_state:
|
| 106 |
st.session_state.area_no_data_warning = False
|
| 107 |
+
|
| 108 |
if 'area_column_descriptions' not in st.session_state:
|
| 109 |
st.session_state.area_column_descriptions = {}
|
| 110 |
+
|
| 111 |
+
# Recommendation-mode state
|
| 112 |
+
if 'area_show_recommendations' not in st.session_state:
|
| 113 |
+
st.session_state.area_show_recommendations = False
|
| 114 |
+
|
| 115 |
+
if 'area_recommendations' not in st.session_state:
|
| 116 |
+
st.session_state.area_recommendations = None
|
| 117 |
|
| 118 |
def display(self):
|
| 119 |
"""Display the area insights interface."""
|
| 120 |
st.subheader("🗺️ Area Insights Chatbot")
|
| 121 |
+
|
| 122 |
# Check if OpenAI service is configured
|
| 123 |
if not self.openai_service:
|
| 124 |
st.error("Azure OpenAI is not configured. Please set up your credentials.")
|
| 125 |
return
|
| 126 |
+
|
| 127 |
+
# State machine: chat > recommendations > entry
|
| 128 |
+
if st.session_state.area_chat_started:
|
|
|
|
|
|
|
| 129 |
self._display_chat()
|
| 130 |
+
elif st.session_state.area_show_recommendations:
|
| 131 |
+
self._display_recommendations()
|
| 132 |
+
else:
|
| 133 |
+
self._display_area_entry()
|
| 134 |
+
|
| 135 |
def _display_area_entry(self):
|
| 136 |
+
"""Entry screen with two modes: use-case-based recommendations or direct ZIP lookup."""
|
| 137 |
+
tab1, tab2 = st.tabs([
|
| 138 |
+
"🎯 Recommend areas for my use case",
|
| 139 |
+
"📍 Look up a specific ZIP",
|
| 140 |
+
])
|
| 141 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
with tab1:
|
| 143 |
+
self._display_use_case_entry()
|
| 144 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
with tab2:
|
| 146 |
+
self._display_zip_entry()
|
| 147 |
+
|
| 148 |
+
def _display_use_case_entry(self):
|
| 149 |
+
"""Describe-your-use-case form → ranked list of recommended areas."""
|
| 150 |
+
st.markdown(
|
| 151 |
+
"Describe what you're looking for — the system scans your loaded datasets and "
|
| 152 |
+
"ranks the areas that best match."
|
| 153 |
+
)
|
| 154 |
+
with st.expander("💡 Example use cases"):
|
| 155 |
+
st.markdown(
|
| 156 |
+
"- *I'm running a Phase 2 diabetes medication trial and need counties with "
|
| 157 |
+
"high adult diabetes prevalence.*\n"
|
| 158 |
+
"- *Looking for counties with high poverty and limited healthcare access for "
|
| 159 |
+
"a community health outreach study.*\n"
|
| 160 |
+
"- *Need areas with high cardiovascular disease risk and large populations "
|
| 161 |
+
"for a cardiac device trial.*"
|
| 162 |
)
|
| 163 |
+
|
| 164 |
+
use_case = st.text_area(
|
| 165 |
+
"Your use case:",
|
| 166 |
+
placeholder="e.g. I'm recruiting for a Phase 2 diabetes trial and need areas with high diabetes prevalence and at least 20,000 residents.",
|
| 167 |
+
height=120,
|
| 168 |
+
key="use_case_input",
|
| 169 |
+
)
|
| 170 |
+
top_n = st.slider("How many areas to recommend?", 5, 20, 10, key="recommend_top_n")
|
| 171 |
+
|
| 172 |
+
submitted = st.button(
|
| 173 |
+
"🎯 Find Matching Areas",
|
| 174 |
+
type="primary",
|
| 175 |
+
disabled=not (use_case or "").strip(),
|
| 176 |
+
key="find_areas_btn",
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
if submitted and (use_case or "").strip():
|
| 180 |
+
with st.spinner("Analysing data dictionaries and ranking areas..."):
|
| 181 |
+
try:
|
| 182 |
+
rec = self.ranking_service.rank_areas_for_use_case(use_case.strip(), top_n=top_n)
|
| 183 |
+
st.session_state.area_recommendations = rec
|
| 184 |
+
st.session_state.area_show_recommendations = True
|
| 185 |
+
logger.info(
|
| 186 |
+
f"Ranking complete: {len(rec.get('top_areas', []))} areas on dataset "
|
| 187 |
+
f"{rec.get('primary_dataset')}"
|
| 188 |
+
)
|
| 189 |
+
st.rerun()
|
| 190 |
+
except Exception as e:
|
| 191 |
+
logger.error(f"Area ranking failed: {e}")
|
| 192 |
+
st.error(f"Ranking failed: {e}")
|
| 193 |
+
|
| 194 |
+
def _display_zip_entry(self):
|
| 195 |
+
"""Direct 5-digit ZIP entry (existing flow)."""
|
| 196 |
+
st.markdown(
|
| 197 |
+
"Enter a 5-digit US ZIP code to jump straight into insights for that area.\n\n"
|
| 198 |
+
"**Examples:** `01001` · `10001` · `94102`"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
zip_input = st.text_input(
|
| 202 |
+
"Enter 5-digit ZIP code:",
|
| 203 |
+
placeholder="e.g., 01001",
|
| 204 |
+
max_chars=5,
|
| 205 |
+
key="direct_zip_input",
|
| 206 |
+
help="Enter a valid 5-digit US ZIP code",
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
zip_value = (zip_input or "").strip()
|
| 210 |
+
is_valid_zip = zip_value.isdigit() and len(zip_value) == 5
|
| 211 |
+
|
| 212 |
+
if zip_value and not is_valid_zip:
|
| 213 |
+
st.caption("⚠️ ZIP must be exactly 5 digits.")
|
| 214 |
+
|
| 215 |
+
start_zip_button = st.button(
|
| 216 |
+
"🚀 Start Chat",
|
| 217 |
+
type="primary",
|
| 218 |
+
disabled=not is_valid_zip,
|
| 219 |
+
key="start_by_zip",
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
if start_zip_button and is_valid_zip:
|
| 223 |
+
with st.spinner("Loading data for ZIP code..."):
|
| 224 |
+
result = self.zip_service.manual_zip_entry(zip_value)
|
| 225 |
+
if not result['error']:
|
| 226 |
+
self._start_chat_with_zip(result)
|
| 227 |
+
st.rerun()
|
| 228 |
+
else:
|
| 229 |
+
st.error(result['error'])
|
| 230 |
+
|
| 231 |
+
def _display_recommendations(self):
|
| 232 |
+
"""Render the ranked list of recommended areas."""
|
| 233 |
+
rec = st.session_state.area_recommendations or {}
|
| 234 |
+
use_case = rec.get('use_case', '')
|
| 235 |
+
criteria = rec.get('criteria', [])
|
| 236 |
+
top_areas = rec.get('top_areas', [])
|
| 237 |
+
primary_dataset = rec.get('primary_dataset')
|
| 238 |
+
warning = rec.get('warning')
|
| 239 |
+
narrative = rec.get('narrative', '')
|
| 240 |
+
|
| 241 |
+
# Header row with "new search" escape hatch
|
| 242 |
+
col_hdr, col_btn = st.columns([5, 1])
|
| 243 |
+
with col_hdr:
|
| 244 |
+
st.markdown(f"**Use case:** {use_case}")
|
| 245 |
+
with col_btn:
|
| 246 |
+
if st.button("🔙 New search", key="rec_back_btn"):
|
| 247 |
+
st.session_state.area_show_recommendations = False
|
| 248 |
+
st.session_state.area_recommendations = None
|
| 249 |
+
st.rerun()
|
| 250 |
+
|
| 251 |
+
if warning:
|
| 252 |
+
st.warning(warning)
|
| 253 |
+
|
| 254 |
+
if not top_areas:
|
| 255 |
+
if not warning:
|
| 256 |
+
st.info("No areas could be ranked. Try rewording your use case.")
|
| 257 |
return
|
| 258 |
+
|
| 259 |
+
# Show criteria used
|
| 260 |
+
if criteria:
|
| 261 |
+
with st.expander(f"📐 Ranking criteria (dataset: **{primary_dataset}**)", expanded=True):
|
| 262 |
+
for c in criteria:
|
| 263 |
+
arrow = "↑" if c['direction'] == 'high' else "↓"
|
| 264 |
+
st.markdown(
|
| 265 |
+
f"- **{c['column']}** {arrow} (weight {c['weight']:.1f}) — {c.get('reason', '')}"
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
# Narrative summary
|
| 269 |
+
if narrative:
|
| 270 |
+
st.markdown("### 📊 Analysis")
|
| 271 |
+
st.markdown(narrative)
|
| 272 |
+
|
| 273 |
+
# Ranked list
|
| 274 |
+
st.markdown(f"### 🏆 Top {len(top_areas)} Matching Areas")
|
| 275 |
+
for rank, area in enumerate(top_areas, start=1):
|
| 276 |
+
area_id = area.get('area_id') or "(unknown)"
|
| 277 |
+
display_name = area.get('display_name')
|
| 278 |
+
score = area.get('composite_score', 0.0)
|
| 279 |
+
with st.container():
|
| 280 |
+
col_info, col_action = st.columns([5, 1])
|
| 281 |
+
with col_info:
|
| 282 |
+
if display_name:
|
| 283 |
+
st.markdown(
|
| 284 |
+
f"**#{rank} · {display_name}** "
|
| 285 |
+
f"<span style='color:#888;font-size:0.85em'>(FIPS {area_id})</span> — "
|
| 286 |
+
f"composite score **{score:.3f}**",
|
| 287 |
+
unsafe_allow_html=True,
|
| 288 |
+
)
|
| 289 |
+
else:
|
| 290 |
+
st.markdown(f"**#{rank} · Area `{area_id}`** — composite score **{score:.3f}**")
|
| 291 |
+
metric_bits = []
|
| 292 |
+
for col, m in area.get('metrics', {}).items():
|
| 293 |
+
val = m.get('value')
|
| 294 |
+
arrow = "↑" if m.get('direction') == 'high' else "↓"
|
| 295 |
+
metric_bits.append(f"{col} {arrow} {val:,.2f}")
|
| 296 |
+
if metric_bits:
|
| 297 |
+
st.caption(" · ".join(metric_bits))
|
| 298 |
+
with col_action:
|
| 299 |
+
drill_key = f"drill_{rank}_{area_id}"
|
| 300 |
+
if st.button(
|
| 301 |
+
"🔍 Explore",
|
| 302 |
+
key=drill_key,
|
| 303 |
+
help="Open a focused chat about this area — ask follow-up questions like 'what's the physician density?' or 'how does poverty compare to state average?'",
|
| 304 |
+
):
|
| 305 |
+
self._start_chat_with_zip({
|
| 306 |
+
'zip_code': area_id,
|
| 307 |
+
'display_name': display_name or f"Area {area_id}",
|
| 308 |
+
})
|
| 309 |
+
st.session_state.area_show_recommendations = False
|
| 310 |
+
st.rerun()
|
| 311 |
+
st.divider()
|
| 312 |
|
| 313 |
def _start_chat_with_zip(self, resolution_result: Dict):
|
| 314 |
"""
|
|
|
|
| 373 |
with st.sidebar:
|
| 374 |
st.divider()
|
| 375 |
st.subheader("Area Chat Controls")
|
| 376 |
+
|
| 377 |
+
# Quick ZIP switch — lets users compare areas without losing context
|
| 378 |
+
with st.form("area_switch_form", clear_on_submit=True):
|
| 379 |
+
new_zip = st.text_input(
|
| 380 |
+
"Switch to ZIP:",
|
| 381 |
+
placeholder="e.g., 94102",
|
| 382 |
+
max_chars=5,
|
| 383 |
+
key="switch_zip_input",
|
| 384 |
+
help="Enter a new 5-digit ZIP to switch area (clears chat history)"
|
| 385 |
+
)
|
| 386 |
+
switch_submitted = st.form_submit_button("🔀 Switch Area")
|
| 387 |
+
if switch_submitted:
|
| 388 |
+
candidate = (new_zip or "").strip()
|
| 389 |
+
if candidate.isdigit() and len(candidate) == 5:
|
| 390 |
+
result = self.zip_service.manual_zip_entry(candidate)
|
| 391 |
+
if not result['error']:
|
| 392 |
+
self._start_chat_with_zip(result)
|
| 393 |
+
st.rerun()
|
| 394 |
+
else:
|
| 395 |
+
st.error(result['error'])
|
| 396 |
+
else:
|
| 397 |
+
st.error("ZIP must be exactly 5 digits.")
|
| 398 |
+
|
| 399 |
if st.button("🔄 Start New Area Chat", help="Reset and choose a different area"):
|
| 400 |
self._reset_area_chat()
|
| 401 |
st.rerun()
|
| 402 |
+
|
| 403 |
if st.button("🗑️ Clear Chat History", help="Clear messages but keep current area"):
|
| 404 |
st.session_state.area_chat_history = []
|
| 405 |
st.session_state.area_column_descriptions = {}
|
| 406 |
st.rerun()
|
| 407 |
+
|
| 408 |
# Show dataset info
|
| 409 |
st.divider()
|
| 410 |
st.caption("**Available Datasets**")
|
|
|
|
| 480 |
zip_code=zip_code
|
| 481 |
)
|
| 482 |
|
| 483 |
+
# Short-message fast path: skip the decision LLM call for trivial inputs
|
| 484 |
+
# (greetings, acknowledgements) — they never need data extraction.
|
| 485 |
+
if len(user_message.split()) <= SHORT_MESSAGE_WORD_THRESHOLD:
|
| 486 |
+
logger.info(f"Short-message bypass: '{user_message}' -> skipping decision call")
|
| 487 |
+
final_prompt = f"""Area: {area_name} (ZIP: {zip_code})
|
| 488 |
+
|
| 489 |
+
User Question: {user_message}
|
| 490 |
+
|
| 491 |
+
Provide a brief, friendly response. You can use general knowledge about this area."""
|
| 492 |
+
final_response = self.openai_service.generate_response(
|
| 493 |
+
final_prompt,
|
| 494 |
+
st.session_state.area_chat_history,
|
| 495 |
+
system_prompt=system_prompt,
|
| 496 |
+
tools=None
|
| 497 |
+
)
|
| 498 |
+
return self.openai_service.get_message_content(final_response)
|
| 499 |
+
|
| 500 |
# Step 1: Define the data extraction tool for Azure OpenAI function calling
|
| 501 |
# This tells the model what "functions" it can call
|
| 502 |
tools = [
|
|
|
|
| 655 |
|
| 656 |
def _get_relevant_columns(self, user_message: str, dataset_results: Dict) -> Dict[str, List[str]]:
|
| 657 |
"""
|
| 658 |
+
Map the user's query to relevant columns in the loaded datasets.
|
| 659 |
+
|
| 660 |
+
Each retrieved chunk comes from exactly one dictionary (via its `dataset`
|
| 661 |
+
field). We map that dictionary back to a loaded dataset, then match the
|
| 662 |
+
chunk text against that dataset's columns using word-bounded regexes.
|
| 663 |
+
This avoids the cross-dataset false-positives caused by naive substring
|
| 664 |
+
matching against every dataset's columns, and preserves retrieval rank
|
| 665 |
+
order so the most relevant columns appear first.
|
| 666 |
"""
|
|
|
|
|
|
|
|
|
|
| 667 |
all_dicts = self.data_dictionary_service.get_all_dictionaries()
|
| 668 |
active_dicts = [d['name'] for d in all_dicts if d.get('active', True)]
|
| 669 |
+
loaded_datasets = set(dataset_results.keys())
|
| 670 |
+
|
| 671 |
+
# Map each active dictionary -> its corresponding loaded dataset (if any)
|
| 672 |
+
dict_to_dataset: Dict[str, str] = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 673 |
for dict_name in active_dicts:
|
| 674 |
+
dict_lower = dict_name.lower()
|
| 675 |
+
for dataset_name in loaded_datasets:
|
| 676 |
+
ds_lower = dataset_name.lower()
|
| 677 |
+
if (ds_lower in dict_lower or dict_lower in ds_lower or
|
| 678 |
+
dict_lower.startswith(ds_lower.split('_')[0])):
|
| 679 |
+
dict_to_dataset[dict_name] = dataset_name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 680 |
break
|
| 681 |
+
|
| 682 |
+
filtered_dicts = list(dict_to_dataset.keys())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 683 |
if not filtered_dicts:
|
| 684 |
logger.warning("No dictionaries match the loaded datasets")
|
| 685 |
+
return {}
|
| 686 |
+
|
| 687 |
+
logger.info(
|
| 688 |
+
f"Searching {len(filtered_dicts)} dictionaries for columns matching: '{user_message}'"
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
search_results = self.retrieval_service.search(
|
| 692 |
user_message,
|
| 693 |
+
filtered_dicts,
|
| 694 |
+
top_k=COLUMN_SEARCH_TOP_K,
|
| 695 |
+
disable_embeddings=False,
|
| 696 |
)
|
|
|
|
| 697 |
if not search_results:
|
| 698 |
logger.info("No relevant columns found in data dictionaries")
|
| 699 |
+
return {}
|
| 700 |
+
|
| 701 |
+
# Precompile word-bounded patterns per dataset column (supports underscore<->space variants).
|
| 702 |
+
# Short names (<=2 chars) are skipped to avoid noise from abbreviations.
|
| 703 |
+
dataset_col_patterns: Dict[str, List[Tuple[str, "re.Pattern[str]"]]] = {}
|
| 704 |
+
for ds_name, ds_data in dataset_results.items():
|
| 705 |
+
patterns: List[Tuple[str, "re.Pattern[str]"]] = []
|
| 706 |
+
for col in ds_data['columns']:
|
| 707 |
+
if len(col) <= 2:
|
| 708 |
+
continue
|
| 709 |
+
variants = {re.escape(col), re.escape(col.replace('_', ' '))}
|
| 710 |
+
patterns.append((col, re.compile(r'(?i)\b(?:' + '|'.join(variants) + r')\b')))
|
| 711 |
+
dataset_col_patterns[ds_name] = patterns
|
| 712 |
+
|
| 713 |
+
# Walk chunks in retrieval-rank order; each chunk contributes to at most
|
| 714 |
+
# one dataset (the one its source dictionary maps to).
|
| 715 |
+
relevant_columns: Dict[str, List[str]] = {}
|
| 716 |
+
seen: Set[Tuple[str, str]] = set()
|
| 717 |
for result in search_results:
|
| 718 |
+
chunk_dict = result.get('dataset')
|
| 719 |
+
chunk_text = result.get('text', '')
|
| 720 |
+
if not chunk_dict or not chunk_text:
|
| 721 |
+
continue
|
| 722 |
+
dataset_name = dict_to_dataset.get(chunk_dict)
|
| 723 |
+
if not dataset_name:
|
| 724 |
+
continue
|
| 725 |
+
|
| 726 |
+
for col, pat in dataset_col_patterns.get(dataset_name, []):
|
| 727 |
+
key = (dataset_name, col)
|
| 728 |
+
if key in seen:
|
| 729 |
+
continue
|
| 730 |
+
if pat.search(chunk_text):
|
| 731 |
+
seen.add(key)
|
| 732 |
+
relevant_columns.setdefault(dataset_name, []).append(col)
|
| 733 |
+
|
| 734 |
+
# Cap per dataset while preserving retrieval rank
|
| 735 |
+
for ds_name in relevant_columns:
|
| 736 |
+
relevant_columns[ds_name] = relevant_columns[ds_name][:MAX_RELEVANT_COLS_PER_DATASET]
|
| 737 |
+
|
| 738 |
+
total = sum(len(cols) for cols in relevant_columns.values())
|
| 739 |
+
logger.info(
|
| 740 |
+
f"Selected {total} relevant columns across {len(relevant_columns)} datasets "
|
| 741 |
+
f"from {len(search_results)} chunks"
|
| 742 |
+
)
|
| 743 |
return relevant_columns
|
| 744 |
|
| 745 |
def _build_smart_context(self, dataset_results: Dict, relevant_columns: Dict[str, List[str]], user_message: str) -> str:
|
|
|
|
| 828 |
|
| 829 |
return result
|
| 830 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 831 |
def _get_column_descriptions(self, columns: List[str]) -> Dict[str, str]:
|
| 832 |
"""
|
| 833 |
+
Get descriptions for columns using a single batched semantic search.
|
| 834 |
+
|
| 835 |
+
One retrieval call is made per invocation (not per column), then results
|
| 836 |
+
are matched back to the requested columns by substring lookup. Results
|
| 837 |
+
are memoised in `st.session_state.area_column_descriptions`.
|
|
|
|
|
|
|
| 838 |
"""
|
| 839 |
+
cached = st.session_state.area_column_descriptions
|
| 840 |
+
uncached = [col for col in columns if col not in cached]
|
| 841 |
+
|
| 842 |
+
# Fast path: everything cached
|
| 843 |
+
if not uncached:
|
| 844 |
+
return {col: cached.get(col, "") for col in columns}
|
| 845 |
+
|
| 846 |
+
active_dicts = [
|
| 847 |
+
d['name']
|
| 848 |
+
for d in self.data_dictionary_service.get_all_dictionaries()
|
| 849 |
+
if d.get('active', True)
|
| 850 |
+
]
|
|
|
|
| 851 |
if not active_dicts:
|
| 852 |
logger.warning("No active data dictionaries for column description lookup")
|
| 853 |
+
return {col: "" for col in columns}
|
| 854 |
+
|
| 855 |
+
# One batched search covering every uncached column name
|
| 856 |
+
query = "column definitions: " + ", ".join(uncached)
|
| 857 |
+
try:
|
| 858 |
+
results = self.retrieval_service.search(
|
| 859 |
+
query,
|
| 860 |
+
active_dicts,
|
| 861 |
+
top_k=min(max(len(uncached) * 3, 10), 60),
|
| 862 |
+
disable_embeddings=False,
|
| 863 |
+
)
|
| 864 |
+
except Exception as e:
|
| 865 |
+
logger.error(f"Batched column description search failed: {e}")
|
| 866 |
+
results = []
|
| 867 |
+
|
| 868 |
+
logger.info(
|
| 869 |
+
f"Batched description search: {len(uncached)} columns, "
|
| 870 |
+
f"{len(results)} chunks returned"
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
# Match each column to the highest-ranked chunk that mentions it
|
| 874 |
+
for col in uncached:
|
| 875 |
+
col_lower = col.lower()
|
| 876 |
+
col_spaces = col.replace('_', ' ').lower()
|
| 877 |
+
matched_text = ""
|
| 878 |
+
for r in results:
|
| 879 |
+
text = r.get('text', '')
|
| 880 |
+
text_lower = text.lower()
|
| 881 |
+
if col_lower in text_lower or col_spaces in text_lower:
|
| 882 |
+
matched_text = text.strip()
|
| 883 |
+
break
|
| 884 |
+
|
| 885 |
+
if matched_text and len(matched_text) > DESCRIPTION_MAX_CHARS:
|
| 886 |
+
matched_text = matched_text[: DESCRIPTION_MAX_CHARS - 3] + "..."
|
| 887 |
+
cached[col] = matched_text
|
| 888 |
+
|
| 889 |
+
st.session_state.area_column_descriptions = cached
|
| 890 |
+
return {col: cached.get(col, "") for col in columns}
|
| 891 |
|
| 892 |
def _show_debug_info(self, dataset_results: Dict, context: str, relevant_columns: Dict[str, List[str]] = None):
|
| 893 |
"""
|
|
|
|
| 912 |
st.caption(f" {ds_name}: {', '.join(cols)}")
|
| 913 |
|
| 914 |
st.caption("**Context sent to LLM:**")
|
| 915 |
+
st.code(
|
| 916 |
+
context[:CONTEXT_PREVIEW_CHARS]
|
| 917 |
+
+ ("...[truncated]" if len(context) > CONTEXT_PREVIEW_CHARS else ""),
|
| 918 |
+
language="markdown",
|
| 919 |
+
)
|
| 920 |
|
| 921 |
st.caption("**Cached Column Descriptions:**")
|
| 922 |
st.json(st.session_state.area_column_descriptions)
|
|
|
|
| 929 |
st.session_state.area_chat_started = False
|
| 930 |
st.session_state.area_no_data_warning = False
|
| 931 |
st.session_state.area_column_descriptions = {}
|
| 932 |
+
st.session_state.area_show_recommendations = False
|
| 933 |
+
st.session_state.area_recommendations = None
|
| 934 |
if 'area_nearby_zips' in st.session_state:
|
| 935 |
del st.session_state.area_nearby_zips
|
| 936 |
logger.info("Area chat reset")
|
src/services/area_ranking_service.py
ADDED
|
@@ -0,0 +1,638 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Area Ranking Service.
|
| 3 |
+
|
| 4 |
+
Given a free-text use case (e.g. "I want to run a Phase 2 diabetes trial"),
|
| 5 |
+
recommend the areas (rows in the loaded offline datasets) that best match it.
|
| 6 |
+
|
| 7 |
+
Pipeline:
|
| 8 |
+
1. Retrieve candidate columns from the active data dictionaries using the
|
| 9 |
+
use case as the query.
|
| 10 |
+
2. Ask the LLM (via function calling) to pick 2-5 of those columns as
|
| 11 |
+
scoring criteria, assigning a direction ("high"/"low") and weight.
|
| 12 |
+
3. Pick the dataset with the most criteria as the "primary" dataset, min-max
|
| 13 |
+
normalise each criterion column across its rows, compute a weighted
|
| 14 |
+
composite score, return the top N rows.
|
| 15 |
+
|
| 16 |
+
Scoring across datasets with different granularity (tract vs. county FIPS) is
|
| 17 |
+
not attempted in v1 — we score on a single primary dataset and mention which.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import logging
|
| 24 |
+
import re
|
| 25 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 26 |
+
|
| 27 |
+
import pandas as pd
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# Tunables
|
| 32 |
+
CANDIDATE_SEARCH_TOP_K = 50 # chunks to retrieve for candidate-column extraction
|
| 33 |
+
MAX_CANDIDATE_COLUMNS = 30 # cap candidates fed to the LLM
|
| 34 |
+
MAX_CRITERIA = 5 # cap scoring criteria the LLM may select
|
| 35 |
+
MIN_CRITERIA = 1 # minimum criteria required to score
|
| 36 |
+
DESCRIPTION_MAX_CHARS = 180
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class AreaRankingService:
|
| 40 |
+
"""Recommend areas for a free-text use case by scoring loaded datasets."""
|
| 41 |
+
|
| 42 |
+
def __init__(self, openai_service, retrieval_service, data_dictionary_service, dataset_service):
|
| 43 |
+
self.openai_service = openai_service
|
| 44 |
+
self.retrieval_service = retrieval_service
|
| 45 |
+
self.data_dictionary_service = data_dictionary_service
|
| 46 |
+
self.dataset_service = dataset_service
|
| 47 |
+
# Lazy-built FIPS -> human-readable name lookup (populated from AHRF on first call)
|
| 48 |
+
self._fips_name_lookup: Optional[Dict[str, str]] = None
|
| 49 |
+
# Lazy-built ZIP (ZCTA) -> "City, ST" lookup via pgeocode (handles SVI_2022 ZCTA keys)
|
| 50 |
+
self._zip_resolver = None # pgeocode.Nominatim or False once probed
|
| 51 |
+
|
| 52 |
+
# ------------------------------------------------------------------ public
|
| 53 |
+
|
| 54 |
+
def rank_areas_for_use_case(self, use_case: str, top_n: int = 10) -> Dict[str, Any]:
|
| 55 |
+
"""
|
| 56 |
+
Rank areas for the given use case.
|
| 57 |
+
|
| 58 |
+
Returns a dict:
|
| 59 |
+
{
|
| 60 |
+
'use_case': str,
|
| 61 |
+
'candidates': [{dataset, column, description}, ...],
|
| 62 |
+
'criteria': [{dataset, column, direction, weight, reason}, ...],
|
| 63 |
+
'primary_dataset': str,
|
| 64 |
+
'top_areas': [{area_id, composite_score, metrics: {...}}, ...],
|
| 65 |
+
'warning': Optional[str],
|
| 66 |
+
}
|
| 67 |
+
"""
|
| 68 |
+
result: Dict[str, Any] = {
|
| 69 |
+
'use_case': use_case,
|
| 70 |
+
'candidates': [],
|
| 71 |
+
'criteria': [],
|
| 72 |
+
'primary_dataset': None,
|
| 73 |
+
'top_areas': [],
|
| 74 |
+
'warning': None,
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
loaded = self._loaded_datasets()
|
| 78 |
+
if not loaded:
|
| 79 |
+
result['warning'] = "No offline datasets are loaded, so no areas can be ranked."
|
| 80 |
+
return result
|
| 81 |
+
|
| 82 |
+
# 1. Candidate columns from data dictionaries
|
| 83 |
+
candidates = self._retrieve_candidate_columns(use_case, loaded)
|
| 84 |
+
result['candidates'] = candidates
|
| 85 |
+
if not candidates:
|
| 86 |
+
result['warning'] = (
|
| 87 |
+
"Couldn't find any candidate columns in the loaded data dictionaries "
|
| 88 |
+
"matching your use case. Try rewording it with more specific terms."
|
| 89 |
+
)
|
| 90 |
+
return result
|
| 91 |
+
|
| 92 |
+
# 2. LLM picks scoring criteria (function calling)
|
| 93 |
+
criteria = self._extract_scoring_criteria(use_case, candidates)
|
| 94 |
+
if len(criteria) < MIN_CRITERIA:
|
| 95 |
+
result['warning'] = (
|
| 96 |
+
"The model didn't return any valid scoring criteria for this use case. "
|
| 97 |
+
"Try rewording your use case with clearer metrics."
|
| 98 |
+
)
|
| 99 |
+
return result
|
| 100 |
+
result['criteria'] = criteria
|
| 101 |
+
|
| 102 |
+
# 3. Pick primary dataset + score
|
| 103 |
+
primary_dataset = self._pick_primary_dataset(criteria, loaded)
|
| 104 |
+
result['primary_dataset'] = primary_dataset
|
| 105 |
+
primary_criteria = [c for c in criteria if c['dataset'] == primary_dataset]
|
| 106 |
+
dropped = [c for c in criteria if c['dataset'] != primary_dataset]
|
| 107 |
+
if dropped:
|
| 108 |
+
result['warning'] = (
|
| 109 |
+
f"Scoring uses dataset '{primary_dataset}' (most criteria). "
|
| 110 |
+
f"Dropped criteria from other datasets to avoid cross-granularity joins: "
|
| 111 |
+
+ ", ".join(f"{c['dataset']}.{c['column']}" for c in dropped)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
df = loaded[primary_dataset]['df']
|
| 115 |
+
top_areas = self._score_and_rank(df, loaded[primary_dataset]['id_col'], primary_criteria, top_n)
|
| 116 |
+
result['top_areas'] = top_areas
|
| 117 |
+
|
| 118 |
+
# Short narrative explaining the top picks
|
| 119 |
+
result['narrative'] = self._generate_narrative(use_case, primary_criteria, top_areas, primary_dataset)
|
| 120 |
+
return result
|
| 121 |
+
|
| 122 |
+
# --------------------------------------------------------------- internals
|
| 123 |
+
|
| 124 |
+
def _loaded_datasets(self) -> Dict[str, Dict[str, Any]]:
|
| 125 |
+
"""
|
| 126 |
+
Return loaded datasets as {name: {df, id_col, columns}}.
|
| 127 |
+
|
| 128 |
+
Uses the offline dataset service's private _datasets / _zip_columns
|
| 129 |
+
attributes because there is no public accessor for the DataFrame.
|
| 130 |
+
"""
|
| 131 |
+
datasets_attr = getattr(self.dataset_service, '_datasets', {}) or {}
|
| 132 |
+
id_columns = getattr(self.dataset_service, '_zip_columns', {}) or {}
|
| 133 |
+
out: Dict[str, Dict[str, Any]] = {}
|
| 134 |
+
for name, df in datasets_attr.items():
|
| 135 |
+
if df is None or df.empty:
|
| 136 |
+
continue
|
| 137 |
+
id_col = id_columns.get(name)
|
| 138 |
+
out[name] = {
|
| 139 |
+
'df': df,
|
| 140 |
+
'id_col': id_col,
|
| 141 |
+
'columns': list(df.columns),
|
| 142 |
+
}
|
| 143 |
+
return out
|
| 144 |
+
|
| 145 |
+
@staticmethod
|
| 146 |
+
def _classify_metric_kind(col: str) -> str:
|
| 147 |
+
"""
|
| 148 |
+
Heuristic tag for a column: 'rate' | 'count' | 'flag' | 'unknown'.
|
| 149 |
+
|
| 150 |
+
Recognises the SVI/EJI conventions (`E_`, `EP_`, `EPL_`, `MP_`, `F_`)
|
| 151 |
+
and generic suffixes like `_pct`, `_per_cap`, `_rate`, `_est`, etc.
|
| 152 |
+
Deliberately conservative — anything ambiguous returns 'unknown' so
|
| 153 |
+
the LLM can decide.
|
| 154 |
+
"""
|
| 155 |
+
if not col:
|
| 156 |
+
return 'unknown'
|
| 157 |
+
c = col.lower()
|
| 158 |
+
# SVI/EJI prefixes (most common in our loaded datasets)
|
| 159 |
+
if col.startswith(('EP_', 'EPL_', 'MP_')):
|
| 160 |
+
return 'rate'
|
| 161 |
+
if col.startswith('F_'):
|
| 162 |
+
return 'flag'
|
| 163 |
+
if col.startswith(('E_', 'M_')):
|
| 164 |
+
return 'count'
|
| 165 |
+
# Generic rate markers — check before count markers so that
|
| 166 |
+
# `popn_est_ge65_pct_21` is treated as a rate, not a count.
|
| 167 |
+
rate_markers = (
|
| 168 |
+
'_pct', 'pct_', '_pc_', '_per_cap', 'per_cap_',
|
| 169 |
+
'_rate', '_ratio', '_prcnt', '_percent', 'percentage', 'percentile',
|
| 170 |
+
)
|
| 171 |
+
if any(m in c for m in rate_markers):
|
| 172 |
+
return 'rate'
|
| 173 |
+
count_markers = ('_est', '_count', '_cnt', '_num', '_tot', 'popn', 'popul')
|
| 174 |
+
if any(m in c for m in count_markers):
|
| 175 |
+
return 'count'
|
| 176 |
+
return 'unknown'
|
| 177 |
+
|
| 178 |
+
def _retrieve_candidate_columns(
|
| 179 |
+
self, use_case: str, loaded: Dict[str, Dict[str, Any]]
|
| 180 |
+
) -> List[Dict[str, str]]:
|
| 181 |
+
"""
|
| 182 |
+
Retrieve chunks matching the use case, attribute each to a loaded dataset
|
| 183 |
+
via the chunk's `dataset` field, and extract a single column name per
|
| 184 |
+
chunk by word-bounded regex match.
|
| 185 |
+
"""
|
| 186 |
+
all_dicts = self.data_dictionary_service.get_all_dictionaries()
|
| 187 |
+
active_dicts = [d['name'] for d in all_dicts if d.get('active', True)]
|
| 188 |
+
if not active_dicts:
|
| 189 |
+
return []
|
| 190 |
+
|
| 191 |
+
# Map each active dictionary to a loaded dataset (same heuristic used in
|
| 192 |
+
# area_insights_interface._get_relevant_columns).
|
| 193 |
+
dict_to_dataset: Dict[str, str] = {}
|
| 194 |
+
loaded_names = set(loaded.keys())
|
| 195 |
+
for dict_name in active_dicts:
|
| 196 |
+
dict_lower = dict_name.lower()
|
| 197 |
+
for ds_name in loaded_names:
|
| 198 |
+
ds_lower = ds_name.lower()
|
| 199 |
+
if (ds_lower in dict_lower or dict_lower in ds_lower or
|
| 200 |
+
dict_lower.startswith(ds_lower.split('_')[0])):
|
| 201 |
+
dict_to_dataset[dict_name] = ds_name
|
| 202 |
+
break
|
| 203 |
+
|
| 204 |
+
filtered_dicts = list(dict_to_dataset.keys())
|
| 205 |
+
if not filtered_dicts:
|
| 206 |
+
logger.warning("No active dictionary matches any loaded dataset")
|
| 207 |
+
return []
|
| 208 |
+
|
| 209 |
+
try:
|
| 210 |
+
chunks = self.retrieval_service.search(
|
| 211 |
+
use_case, filtered_dicts, top_k=CANDIDATE_SEARCH_TOP_K, disable_embeddings=False
|
| 212 |
+
)
|
| 213 |
+
except Exception as e:
|
| 214 |
+
logger.error(f"Retrieval for candidate columns failed: {e}")
|
| 215 |
+
return []
|
| 216 |
+
|
| 217 |
+
# Precompile column-name patterns per dataset
|
| 218 |
+
col_patterns: Dict[str, List[Tuple[str, "re.Pattern[str]"]]] = {}
|
| 219 |
+
for ds_name, meta in loaded.items():
|
| 220 |
+
patterns: List[Tuple[str, "re.Pattern[str]"]] = []
|
| 221 |
+
for col in meta['columns']:
|
| 222 |
+
if len(col) <= 2 or col == meta['id_col']:
|
| 223 |
+
continue
|
| 224 |
+
variants = {re.escape(col), re.escape(col.replace('_', ' '))}
|
| 225 |
+
patterns.append((col, re.compile(r'(?i)\b(?:' + '|'.join(variants) + r')\b')))
|
| 226 |
+
col_patterns[ds_name] = patterns
|
| 227 |
+
|
| 228 |
+
# Extract one best column match per chunk
|
| 229 |
+
candidates: List[Dict[str, str]] = []
|
| 230 |
+
seen: set = set()
|
| 231 |
+
for chunk in chunks:
|
| 232 |
+
chunk_dict = chunk.get('dataset')
|
| 233 |
+
text = chunk.get('text', '')
|
| 234 |
+
if not chunk_dict or not text:
|
| 235 |
+
continue
|
| 236 |
+
ds_name = dict_to_dataset.get(chunk_dict)
|
| 237 |
+
if not ds_name:
|
| 238 |
+
continue
|
| 239 |
+
for col, pat in col_patterns.get(ds_name, []):
|
| 240 |
+
key = (ds_name, col)
|
| 241 |
+
if key in seen:
|
| 242 |
+
continue
|
| 243 |
+
if pat.search(text):
|
| 244 |
+
seen.add(key)
|
| 245 |
+
desc = text.strip()
|
| 246 |
+
if len(desc) > DESCRIPTION_MAX_CHARS:
|
| 247 |
+
desc = desc[: DESCRIPTION_MAX_CHARS - 3] + "..."
|
| 248 |
+
candidates.append({
|
| 249 |
+
'dataset': ds_name,
|
| 250 |
+
'column': col,
|
| 251 |
+
'description': desc,
|
| 252 |
+
'metric_kind': self._classify_metric_kind(col),
|
| 253 |
+
})
|
| 254 |
+
break # one column per chunk to preserve ranking granularity
|
| 255 |
+
if len(candidates) >= MAX_CANDIDATE_COLUMNS:
|
| 256 |
+
break
|
| 257 |
+
|
| 258 |
+
logger.info(
|
| 259 |
+
f"Candidate columns for use case: {len(candidates)} across "
|
| 260 |
+
f"{len({c['dataset'] for c in candidates})} dataset(s)"
|
| 261 |
+
)
|
| 262 |
+
return candidates
|
| 263 |
+
|
| 264 |
+
def _extract_scoring_criteria(
|
| 265 |
+
self, use_case: str, candidates: List[Dict[str, str]]
|
| 266 |
+
) -> List[Dict[str, Any]]:
|
| 267 |
+
"""
|
| 268 |
+
Use Azure OpenAI function calling to convert the use case + candidate
|
| 269 |
+
columns into a list of scoring criteria. Validates that every returned
|
| 270 |
+
(dataset, column) pair came from the candidate list.
|
| 271 |
+
"""
|
| 272 |
+
candidate_lines = [
|
| 273 |
+
f"{i + 1}. Dataset: {c['dataset']} | Column: {c['column']} [{c.get('metric_kind', 'unknown')}] | {c['description']}"
|
| 274 |
+
for i, c in enumerate(candidates)
|
| 275 |
+
]
|
| 276 |
+
# Check whether the use case explicitly asks for volume (cohort size, at least N, etc.)
|
| 277 |
+
volume_cues = ('at least', 'minimum', 'cohort size', 'market size', 'total popul', 'population of', 'large popul')
|
| 278 |
+
use_case_wants_volume = any(cue in use_case.lower() for cue in volume_cues)
|
| 279 |
+
|
| 280 |
+
prompt = (
|
| 281 |
+
f"Use case: {use_case}\n\n"
|
| 282 |
+
"Candidate columns from the loaded datasets (each tagged with its metric kind "
|
| 283 |
+
"in square brackets):\n"
|
| 284 |
+
" [rate] — percentage, percentile, per-capita, or ratio. Measures prevalence or density.\n"
|
| 285 |
+
" [count] — raw estimate of people/entities. Grows with area size.\n"
|
| 286 |
+
" [flag] — binary 0/1 indicator (e.g. 'high-risk flag').\n"
|
| 287 |
+
" [unknown] — could be either; judge from the description.\n\n"
|
| 288 |
+
+ "\n".join(candidate_lines)
|
| 289 |
+
+ "\n\n"
|
| 290 |
+
"SCORING GUIDANCE (follow carefully):\n"
|
| 291 |
+
"1. STRONGLY PREFER [rate] metrics over [count] metrics when the use case is about "
|
| 292 |
+
"targeting, prevalence, density, or identifying high-risk areas. Rate metrics measure "
|
| 293 |
+
"'how concentrated X is here'; count metrics just reward bigger areas and bias results "
|
| 294 |
+
"toward Los Angeles / Cook / Harris / Maricopa every time.\n"
|
| 295 |
+
"2. If both rate and count versions of the same underlying concept exist (e.g. "
|
| 296 |
+
"E_DIABETES [count] vs EP_DIABETES [rate]), pick the rate.\n"
|
| 297 |
+
f"3. {'Use counts ONLY for the specific volume constraint the use case mentions.' if use_case_wants_volume else 'Avoid [count] metrics unless the use case explicitly asks for volume/size.'}\n"
|
| 298 |
+
"4. Avoid [flag] metrics for primary scoring — they collapse to 0/1 and lose information. "
|
| 299 |
+
"Only use them if nothing better measures the concept.\n"
|
| 300 |
+
"5. Don't pick multiple near-duplicate columns (e.g. the same concept across year variants).\n\n"
|
| 301 |
+
f"Pick {MIN_CRITERIA}-{MAX_CRITERIA} columns. For each:\n"
|
| 302 |
+
"- direction: 'high' if higher values are better for the use case, 'low' if lower is better\n"
|
| 303 |
+
"- weight: relative importance (1.0 = baseline, 2.0 = twice as important)\n"
|
| 304 |
+
"- reason: one short sentence on why it matters\n\n"
|
| 305 |
+
"Return criteria by calling set_scoring_criteria."
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
tool = {
|
| 309 |
+
"type": "function",
|
| 310 |
+
"function": {
|
| 311 |
+
"name": "set_scoring_criteria",
|
| 312 |
+
"description": "Define weighted criteria for ranking areas for the given use case.",
|
| 313 |
+
"parameters": {
|
| 314 |
+
"type": "object",
|
| 315 |
+
"properties": {
|
| 316 |
+
"criteria": {
|
| 317 |
+
"type": "array",
|
| 318 |
+
"maxItems": MAX_CRITERIA,
|
| 319 |
+
"items": {
|
| 320 |
+
"type": "object",
|
| 321 |
+
"properties": {
|
| 322 |
+
"dataset": {"type": "string"},
|
| 323 |
+
"column": {"type": "string"},
|
| 324 |
+
"direction": {"type": "string", "enum": ["high", "low"]},
|
| 325 |
+
"weight": {"type": "number"},
|
| 326 |
+
"reason": {"type": "string"},
|
| 327 |
+
},
|
| 328 |
+
"required": ["dataset", "column", "direction", "weight", "reason"],
|
| 329 |
+
},
|
| 330 |
+
},
|
| 331 |
+
},
|
| 332 |
+
"required": ["criteria"],
|
| 333 |
+
},
|
| 334 |
+
},
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
try:
|
| 338 |
+
response = self.openai_service.generate_response(
|
| 339 |
+
prompt,
|
| 340 |
+
chat_history=[],
|
| 341 |
+
system_prompt=(
|
| 342 |
+
"You are an analytics assistant that maps a free-text use case to "
|
| 343 |
+
"weighted scoring criteria over a fixed list of columns. You must "
|
| 344 |
+
"call set_scoring_criteria; never answer in prose."
|
| 345 |
+
),
|
| 346 |
+
tools=[tool],
|
| 347 |
+
)
|
| 348 |
+
except Exception as e:
|
| 349 |
+
logger.error(f"Criteria extraction API call failed: {e}")
|
| 350 |
+
return []
|
| 351 |
+
|
| 352 |
+
if not self.openai_service.has_tool_calls(response):
|
| 353 |
+
logger.warning("Model did not call set_scoring_criteria tool")
|
| 354 |
+
return []
|
| 355 |
+
|
| 356 |
+
tool_calls = self.openai_service.get_tool_calls(response)
|
| 357 |
+
raw_criteria: List[Dict[str, Any]] = []
|
| 358 |
+
for tc in tool_calls:
|
| 359 |
+
if tc["function"]["name"] != "set_scoring_criteria":
|
| 360 |
+
continue
|
| 361 |
+
try:
|
| 362 |
+
args = json.loads(tc["function"]["arguments"])
|
| 363 |
+
except json.JSONDecodeError as e:
|
| 364 |
+
logger.warning(f"Failed to parse tool arguments: {e}")
|
| 365 |
+
continue
|
| 366 |
+
for c in args.get("criteria", []):
|
| 367 |
+
raw_criteria.append(c)
|
| 368 |
+
|
| 369 |
+
valid_pairs = {(c['dataset'], c['column']) for c in candidates}
|
| 370 |
+
validated: List[Dict[str, Any]] = []
|
| 371 |
+
for c in raw_criteria:
|
| 372 |
+
ds = c.get('dataset')
|
| 373 |
+
col = c.get('column')
|
| 374 |
+
direction = c.get('direction')
|
| 375 |
+
weight = c.get('weight')
|
| 376 |
+
reason = c.get('reason', '')
|
| 377 |
+
if (ds, col) not in valid_pairs:
|
| 378 |
+
logger.warning(f"LLM chose unknown pair ({ds}, {col}); dropping")
|
| 379 |
+
continue
|
| 380 |
+
if direction not in ('high', 'low'):
|
| 381 |
+
logger.warning(f"Invalid direction '{direction}' for ({ds}, {col}); dropping")
|
| 382 |
+
continue
|
| 383 |
+
try:
|
| 384 |
+
weight_f = float(weight)
|
| 385 |
+
if weight_f <= 0:
|
| 386 |
+
raise ValueError
|
| 387 |
+
except (TypeError, ValueError):
|
| 388 |
+
logger.warning(f"Invalid weight {weight!r} for ({ds}, {col}); defaulting to 1.0")
|
| 389 |
+
weight_f = 1.0
|
| 390 |
+
validated.append({
|
| 391 |
+
'dataset': ds,
|
| 392 |
+
'column': col,
|
| 393 |
+
'direction': direction,
|
| 394 |
+
'weight': weight_f,
|
| 395 |
+
'reason': reason,
|
| 396 |
+
})
|
| 397 |
+
|
| 398 |
+
logger.info(
|
| 399 |
+
f"Validated {len(validated)}/{len(raw_criteria)} criteria from LLM"
|
| 400 |
+
)
|
| 401 |
+
return validated[:MAX_CRITERIA]
|
| 402 |
+
|
| 403 |
+
def _pick_primary_dataset(
|
| 404 |
+
self, criteria: List[Dict[str, Any]], loaded: Dict[str, Dict[str, Any]]
|
| 405 |
+
) -> str:
|
| 406 |
+
"""Pick the dataset with the most criteria; break ties by total weight, then by name."""
|
| 407 |
+
counts: Dict[str, float] = {}
|
| 408 |
+
weights: Dict[str, float] = {}
|
| 409 |
+
for c in criteria:
|
| 410 |
+
if c['dataset'] not in loaded:
|
| 411 |
+
continue
|
| 412 |
+
counts[c['dataset']] = counts.get(c['dataset'], 0) + 1
|
| 413 |
+
weights[c['dataset']] = weights.get(c['dataset'], 0.0) + c['weight']
|
| 414 |
+
if not counts:
|
| 415 |
+
# Fall back to the first loaded dataset
|
| 416 |
+
return next(iter(loaded.keys()))
|
| 417 |
+
return max(
|
| 418 |
+
counts.keys(),
|
| 419 |
+
key=lambda d: (counts[d], weights[d], -ord(d[0]) if d else 0),
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
def _score_and_rank(
|
| 423 |
+
self,
|
| 424 |
+
df: pd.DataFrame,
|
| 425 |
+
id_col: Optional[str],
|
| 426 |
+
criteria: List[Dict[str, Any]],
|
| 427 |
+
top_n: int,
|
| 428 |
+
) -> List[Dict[str, Any]]:
|
| 429 |
+
"""
|
| 430 |
+
Min-max normalise each criterion column across df rows, apply weight
|
| 431 |
+
and direction, compute composite score, return top N.
|
| 432 |
+
"""
|
| 433 |
+
if df is None or df.empty or not criteria:
|
| 434 |
+
return []
|
| 435 |
+
|
| 436 |
+
cols_present = [c for c in criteria if c['column'] in df.columns]
|
| 437 |
+
if not cols_present:
|
| 438 |
+
logger.warning("None of the criterion columns exist in the primary dataset")
|
| 439 |
+
return []
|
| 440 |
+
|
| 441 |
+
work = df.copy()
|
| 442 |
+
|
| 443 |
+
# Coerce each criterion column to numeric; rows with NaN in any criterion are dropped
|
| 444 |
+
for c in cols_present:
|
| 445 |
+
col = c['column']
|
| 446 |
+
work[col] = pd.to_numeric(work[col], errors='coerce')
|
| 447 |
+
work = work.dropna(subset=[c['column'] for c in cols_present])
|
| 448 |
+
if work.empty:
|
| 449 |
+
logger.warning("After dropping NaN rows, no rows remain to score")
|
| 450 |
+
return []
|
| 451 |
+
|
| 452 |
+
# Normalise per column, apply direction + weight
|
| 453 |
+
score_components: Dict[str, pd.Series] = {}
|
| 454 |
+
for c in cols_present:
|
| 455 |
+
col = c['column']
|
| 456 |
+
series = work[col].astype(float)
|
| 457 |
+
lo, hi = series.min(), series.max()
|
| 458 |
+
if hi == lo:
|
| 459 |
+
norm = pd.Series(0.0, index=series.index)
|
| 460 |
+
else:
|
| 461 |
+
norm = (series - lo) / (hi - lo)
|
| 462 |
+
if c['direction'] == 'low':
|
| 463 |
+
norm = 1.0 - norm
|
| 464 |
+
score_components[col] = norm * c['weight']
|
| 465 |
+
|
| 466 |
+
score_df = pd.DataFrame(score_components)
|
| 467 |
+
total_weight = sum(c['weight'] for c in cols_present)
|
| 468 |
+
work['_composite_score'] = score_df.sum(axis=1) / (total_weight or 1.0)
|
| 469 |
+
|
| 470 |
+
# Top N rows
|
| 471 |
+
top = work.sort_values('_composite_score', ascending=False).head(top_n)
|
| 472 |
+
|
| 473 |
+
# Assemble response
|
| 474 |
+
out: List[Dict[str, Any]] = []
|
| 475 |
+
for _, row in top.iterrows():
|
| 476 |
+
area_id = str(row[id_col]).strip() if id_col and id_col in row else None
|
| 477 |
+
metrics = {}
|
| 478 |
+
for c in cols_present:
|
| 479 |
+
col = c['column']
|
| 480 |
+
raw = row[col]
|
| 481 |
+
metrics[col] = {
|
| 482 |
+
'value': float(raw),
|
| 483 |
+
'direction': c['direction'],
|
| 484 |
+
'weight': c['weight'],
|
| 485 |
+
'reason': c.get('reason', ''),
|
| 486 |
+
}
|
| 487 |
+
out.append({
|
| 488 |
+
'area_id': area_id,
|
| 489 |
+
'display_name': self._resolve_area_name(area_id),
|
| 490 |
+
'composite_score': round(float(row['_composite_score']), 4),
|
| 491 |
+
'metrics': metrics,
|
| 492 |
+
})
|
| 493 |
+
return out
|
| 494 |
+
|
| 495 |
+
def _build_fips_lookup(self) -> Dict[str, str]:
|
| 496 |
+
"""
|
| 497 |
+
Build a FIPS -> 'County, ST' lookup from the AHRF dataset's own name columns.
|
| 498 |
+
|
| 499 |
+
AHRF ships with `fips_st_cnty` (county FIPS as int) and
|
| 500 |
+
`cnty_name_st_abbrev` (e.g. 'Autauga, AL'), so we re-use that rather
|
| 501 |
+
than calling an external geocoder.
|
| 502 |
+
"""
|
| 503 |
+
datasets = getattr(self.dataset_service, '_datasets', {}) or {}
|
| 504 |
+
ahrf = None
|
| 505 |
+
for name, df in datasets.items():
|
| 506 |
+
if 'ahrf' in name.lower() and df is not None and not df.empty:
|
| 507 |
+
ahrf = df
|
| 508 |
+
break
|
| 509 |
+
if ahrf is None or 'fips_st_cnty' not in ahrf.columns or 'cnty_name_st_abbrev' not in ahrf.columns:
|
| 510 |
+
logger.warning("AHRF with fips/cnty_name_st_abbrev columns not found; FIPS names disabled")
|
| 511 |
+
return {}
|
| 512 |
+
|
| 513 |
+
lookup: Dict[str, str] = {}
|
| 514 |
+
for fips, name in zip(ahrf['fips_st_cnty'], ahrf['cnty_name_st_abbrev']):
|
| 515 |
+
if pd.isna(fips) or pd.isna(name):
|
| 516 |
+
continue
|
| 517 |
+
try:
|
| 518 |
+
fips_int = int(fips)
|
| 519 |
+
except (TypeError, ValueError):
|
| 520 |
+
continue
|
| 521 |
+
# Store both zero-padded and un-padded forms so either string comparison hits
|
| 522 |
+
padded = f"{fips_int:05d}"
|
| 523 |
+
lookup[padded] = str(name).strip()
|
| 524 |
+
lookup[str(fips_int)] = str(name).strip()
|
| 525 |
+
logger.info(f"Built FIPS->name lookup from AHRF: {len(lookup)} entries")
|
| 526 |
+
return lookup
|
| 527 |
+
|
| 528 |
+
def _resolve_area_name(self, area_id: Optional[str]) -> Optional[str]:
|
| 529 |
+
"""
|
| 530 |
+
Resolve an area identifier to a human-readable name.
|
| 531 |
+
|
| 532 |
+
Handles three key shapes:
|
| 533 |
+
- 5-digit county FIPS (e.g. '06037' -> 'Los Angeles, CA') via AHRF
|
| 534 |
+
- 5-digit ZCTA / ZIP (e.g. '32162' -> 'The Villages, FL') via pgeocode
|
| 535 |
+
- 11-digit tract FIPS -> 'Tract in {County, ST}'
|
| 536 |
+
|
| 537 |
+
Tries AHRF first (no network), then falls back to pgeocode for ZIPs.
|
| 538 |
+
"""
|
| 539 |
+
if not area_id:
|
| 540 |
+
return None
|
| 541 |
+
if self._fips_name_lookup is None:
|
| 542 |
+
self._fips_name_lookup = self._build_fips_lookup()
|
| 543 |
+
|
| 544 |
+
key = str(area_id).strip()
|
| 545 |
+
|
| 546 |
+
# 1) Direct AHRF county-FIPS hit (most common for ahrf primary dataset)
|
| 547 |
+
if self._fips_name_lookup and key in self._fips_name_lookup:
|
| 548 |
+
return self._fips_name_lookup[key]
|
| 549 |
+
|
| 550 |
+
# 2) Tract-level FIPS (11 digits): first 5 digits = state+county
|
| 551 |
+
if key.isdigit() and len(key) == 11:
|
| 552 |
+
county_part = key[:5]
|
| 553 |
+
name = (
|
| 554 |
+
self._fips_name_lookup.get(county_part)
|
| 555 |
+
if self._fips_name_lookup else None
|
| 556 |
+
) or (
|
| 557 |
+
self._fips_name_lookup.get(str(int(county_part)))
|
| 558 |
+
if self._fips_name_lookup else None
|
| 559 |
+
)
|
| 560 |
+
if name:
|
| 561 |
+
return f"Tract in {name}"
|
| 562 |
+
|
| 563 |
+
# 3) ZCTA / ZIP (5 digits, not in AHRF county map): pgeocode
|
| 564 |
+
if key.isdigit() and len(key) == 5:
|
| 565 |
+
zip_name = self._lookup_zip_name(key)
|
| 566 |
+
if zip_name:
|
| 567 |
+
return zip_name
|
| 568 |
+
|
| 569 |
+
return None
|
| 570 |
+
|
| 571 |
+
def _lookup_zip_name(self, zip_code: str) -> Optional[str]:
|
| 572 |
+
"""Return 'City, ST' for a US ZIP code via pgeocode, lazily initialised."""
|
| 573 |
+
if self._zip_resolver is False:
|
| 574 |
+
return None
|
| 575 |
+
if self._zip_resolver is None:
|
| 576 |
+
try:
|
| 577 |
+
import pgeocode # Deferred import so the service works even without it installed
|
| 578 |
+
self._zip_resolver = pgeocode.Nominatim('us')
|
| 579 |
+
logger.info("pgeocode ZIP resolver initialised")
|
| 580 |
+
except Exception as e:
|
| 581 |
+
logger.warning(f"pgeocode unavailable; ZIP names disabled: {e}")
|
| 582 |
+
self._zip_resolver = False
|
| 583 |
+
return None
|
| 584 |
+
try:
|
| 585 |
+
row = self._zip_resolver.query_postal_code(zip_code)
|
| 586 |
+
place = row.get('place_name') if hasattr(row, 'get') else row['place_name']
|
| 587 |
+
state = row.get('state_code') if hasattr(row, 'get') else row['state_code']
|
| 588 |
+
if place and state and str(place) != 'nan' and str(state) != 'nan':
|
| 589 |
+
return f"{place}, {state}"
|
| 590 |
+
except Exception as e:
|
| 591 |
+
logger.debug(f"pgeocode query failed for {zip_code}: {e}")
|
| 592 |
+
return None
|
| 593 |
+
|
| 594 |
+
def _generate_narrative(
|
| 595 |
+
self,
|
| 596 |
+
use_case: str,
|
| 597 |
+
criteria: List[Dict[str, Any]],
|
| 598 |
+
top_areas: List[Dict[str, Any]],
|
| 599 |
+
primary_dataset: str,
|
| 600 |
+
) -> str:
|
| 601 |
+
"""Short LLM-written summary of the top picks with specific numbers cited."""
|
| 602 |
+
if not top_areas:
|
| 603 |
+
return ""
|
| 604 |
+
|
| 605 |
+
criteria_desc = "\n".join(
|
| 606 |
+
f"- {c['dataset']}.{c['column']} ({c['direction']}er is better, weight {c['weight']:.1f}): {c['reason']}"
|
| 607 |
+
for c in criteria
|
| 608 |
+
)
|
| 609 |
+
def _fmt_area(a: Dict[str, Any]) -> str:
|
| 610 |
+
name = a.get('display_name') or f"FIPS {a['area_id']}"
|
| 611 |
+
metrics_str = ", ".join(f"{col}={m['value']:.2f}" for col, m in a['metrics'].items())
|
| 612 |
+
return f"- {name} (FIPS {a['area_id']}, score {a['composite_score']:.2f}): {metrics_str}"
|
| 613 |
+
|
| 614 |
+
top_summary = "\n".join(_fmt_area(a) for a in top_areas[: min(5, len(top_areas))])
|
| 615 |
+
prompt = (
|
| 616 |
+
f"Use case: {use_case}\n\n"
|
| 617 |
+
f"Ranking criteria (all from dataset '{primary_dataset}'):\n{criteria_desc}\n\n"
|
| 618 |
+
f"Top matching areas:\n{top_summary}\n\n"
|
| 619 |
+
"Write 2-3 short paragraphs:\n"
|
| 620 |
+
"1. The overall pattern across the top results (e.g. 'these areas share high X and moderate Y').\n"
|
| 621 |
+
"2. Call out the #1 area specifically with its key metric values.\n"
|
| 622 |
+
"3. Brief caveats about data limitations where relevant.\n\n"
|
| 623 |
+
"Cite specific numbers. Be factual, avoid speculation, and do not repeat the criteria list verbatim."
|
| 624 |
+
)
|
| 625 |
+
try:
|
| 626 |
+
response = self.openai_service.generate_response(
|
| 627 |
+
prompt,
|
| 628 |
+
chat_history=[],
|
| 629 |
+
system_prompt=(
|
| 630 |
+
"You are a data analyst summarising area rankings for a decision-maker. "
|
| 631 |
+
"Keep it concise and ground every claim in the numbers provided."
|
| 632 |
+
),
|
| 633 |
+
tools=None,
|
| 634 |
+
)
|
| 635 |
+
return self.openai_service.get_message_content(response) or ""
|
| 636 |
+
except Exception as e:
|
| 637 |
+
logger.warning(f"Narrative generation failed: {e}")
|
| 638 |
+
return ""
|
src/services/zip_resolution_service.py
CHANGED
|
@@ -67,179 +67,6 @@ class ZipResolutionService:
|
|
| 67 |
return zip_match.group(0)
|
| 68 |
return None
|
| 69 |
|
| 70 |
-
def resolve_to_zip(self, area_name: str) -> Dict[str, Optional[str]]:
|
| 71 |
-
"""
|
| 72 |
-
Resolve an area name to a US ZIP code using Nominatim API.
|
| 73 |
-
|
| 74 |
-
Args:
|
| 75 |
-
area_name: Name of the area (city, locality, or region)
|
| 76 |
-
|
| 77 |
-
Returns:
|
| 78 |
-
Dictionary with keys:
|
| 79 |
-
- 'zip_code': 5-digit ZIP code (or None if not found)
|
| 80 |
-
- 'normalized_address': Full formatted address
|
| 81 |
-
- 'error': Error message if resolution failed
|
| 82 |
-
- 'display_name': Human-readable location name
|
| 83 |
-
"""
|
| 84 |
-
# Check cache first
|
| 85 |
-
cache_key = area_name.lower().strip()
|
| 86 |
-
if cache_key in self._cache:
|
| 87 |
-
logger.info(f"Using cached ZIP for '{area_name}'")
|
| 88 |
-
return self._cache[cache_key]
|
| 89 |
-
|
| 90 |
-
# Try multiple query variations
|
| 91 |
-
query_variations = [
|
| 92 |
-
area_name, # Original query
|
| 93 |
-
]
|
| 94 |
-
|
| 95 |
-
# Add variation with state abbreviation if full state name is used
|
| 96 |
-
state_mapping = {
|
| 97 |
-
'massachusetts': 'MA', 'new york': 'NY', 'california': 'CA',
|
| 98 |
-
'texas': 'TX', 'florida': 'FL', 'pennsylvania': 'PA',
|
| 99 |
-
'illinois': 'IL', 'ohio': 'OH', 'georgia': 'GA', 'michigan': 'MI',
|
| 100 |
-
'north carolina': 'NC', 'new jersey': 'NJ', 'virginia': 'VA',
|
| 101 |
-
'washington': 'WA', 'arizona': 'AZ', 'tennessee': 'TN',
|
| 102 |
-
'indiana': 'IN', 'missouri': 'MO', 'maryland': 'MD',
|
| 103 |
-
'wisconsin': 'WI', 'colorado': 'CO', 'minnesota': 'MN',
|
| 104 |
-
'south carolina': 'SC', 'alabama': 'AL', 'louisiana': 'LA',
|
| 105 |
-
'kentucky': 'KY', 'oregon': 'OR', 'oklahoma': 'OK',
|
| 106 |
-
'connecticut': 'CT', 'utah': 'UT', 'iowa': 'IA',
|
| 107 |
-
'nevada': 'NV', 'arkansas': 'AR', 'mississippi': 'MS',
|
| 108 |
-
'kansas': 'KS', 'new mexico': 'NM', 'nebraska': 'NE',
|
| 109 |
-
'west virginia': 'WV', 'idaho': 'ID', 'hawaii': 'HI',
|
| 110 |
-
'new hampshire': 'NH', 'maine': 'ME', 'montana': 'MT',
|
| 111 |
-
'rhode island': 'RI', 'delaware': 'DE', 'south dakota': 'SD',
|
| 112 |
-
'north dakota': 'ND', 'alaska': 'AK', 'vermont': 'VT',
|
| 113 |
-
'wyoming': 'WY'
|
| 114 |
-
}
|
| 115 |
-
|
| 116 |
-
area_lower = area_name.lower()
|
| 117 |
-
for state_full, state_abbr in state_mapping.items():
|
| 118 |
-
if state_full in area_lower:
|
| 119 |
-
# Add variation with abbreviation
|
| 120 |
-
variation = area_name.lower().replace(state_full, state_abbr).title()
|
| 121 |
-
if variation not in query_variations:
|
| 122 |
-
query_variations.append(variation)
|
| 123 |
-
break
|
| 124 |
-
|
| 125 |
-
# Try each query variation
|
| 126 |
-
for query in query_variations:
|
| 127 |
-
result = self._try_resolve(query, is_retry=(query != area_name))
|
| 128 |
-
if result['zip_code']:
|
| 129 |
-
# Cache with original area name
|
| 130 |
-
self._cache[cache_key] = result
|
| 131 |
-
return result
|
| 132 |
-
|
| 133 |
-
# If all variations failed, return the last result (with error)
|
| 134 |
-
if not result['zip_code']:
|
| 135 |
-
area_root = area_name.split(',')[0]
|
| 136 |
-
county_hint = ""
|
| 137 |
-
# If the query or resolved display name looks like a county, make the guidance explicit
|
| 138 |
-
if "county" in area_name.lower() or "county" in str(result.get('display_name', '')).lower():
|
| 139 |
-
county_hint = "\n• County names typically do not have ZIP codes. Please enter a city or ZIP within the county (e.g., 'City, ST 12345')."
|
| 140 |
-
|
| 141 |
-
# Keep prior error context (e.g., network/timeout) if it exists
|
| 142 |
-
base_error = result.get('error') or f"Could not find ZIP code for '{area_name}'. Location found: {result.get('display_name', 'N/A')}."
|
| 143 |
-
|
| 144 |
-
# Enhance error message with suggestions
|
| 145 |
-
result['error'] = (
|
| 146 |
-
f"{base_error}\n\n💡 Try:\n"
|
| 147 |
-
f"• Adding more specific details (e.g., '{area_root}, ST 12345')\n"
|
| 148 |
-
f"• Using just the city name with state abbreviation (e.g., 'Springfield, IL')\n"
|
| 149 |
-
f"• Entering a ZIP code directly (e.g., '10001', '30301', '94105') in the field below"
|
| 150 |
-
f"{county_hint}"
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
self._cache[cache_key] = result
|
| 154 |
-
return result
|
| 155 |
-
|
| 156 |
-
def _try_resolve(self, query: str, is_retry: bool = False) -> Dict[str, Optional[str]]:
|
| 157 |
-
"""
|
| 158 |
-
Attempt to resolve a single query to a ZIP code.
|
| 159 |
-
|
| 160 |
-
Args:
|
| 161 |
-
query: Search query string
|
| 162 |
-
is_retry: Whether this is a retry with modified query
|
| 163 |
-
|
| 164 |
-
Returns:
|
| 165 |
-
Dictionary with resolution result
|
| 166 |
-
"""
|
| 167 |
-
result = {
|
| 168 |
-
'zip_code': None,
|
| 169 |
-
'normalized_address': None,
|
| 170 |
-
'error': None,
|
| 171 |
-
'display_name': None
|
| 172 |
-
}
|
| 173 |
-
|
| 174 |
-
try:
|
| 175 |
-
# Respect rate limiting
|
| 176 |
-
self._wait_for_rate_limit()
|
| 177 |
-
|
| 178 |
-
if is_retry:
|
| 179 |
-
logger.info(f"Trying alternate query: '{query}'")
|
| 180 |
-
|
| 181 |
-
# Make API request with multiple result limit for better matching
|
| 182 |
-
params = {
|
| 183 |
-
'q': query,
|
| 184 |
-
'format': 'json',
|
| 185 |
-
'addressdetails': 1,
|
| 186 |
-
'countrycodes': 'us',
|
| 187 |
-
'limit': 3 # Get top 3 results to find one with postal code
|
| 188 |
-
}
|
| 189 |
-
|
| 190 |
-
headers = {
|
| 191 |
-
'User-Agent': self.user_agent
|
| 192 |
-
}
|
| 193 |
-
|
| 194 |
-
response = requests.get(
|
| 195 |
-
f"{self.base_url}/search",
|
| 196 |
-
params=params,
|
| 197 |
-
headers=headers,
|
| 198 |
-
timeout=10
|
| 199 |
-
)
|
| 200 |
-
response.raise_for_status()
|
| 201 |
-
|
| 202 |
-
data = response.json()
|
| 203 |
-
|
| 204 |
-
if not data or len(data) == 0:
|
| 205 |
-
result['error'] = f"No location found for '{query}'"
|
| 206 |
-
logger.warning(f"No results from Nominatim for '{query}'")
|
| 207 |
-
return result
|
| 208 |
-
|
| 209 |
-
# Try each result to find one with a postal code
|
| 210 |
-
for location in data:
|
| 211 |
-
result['display_name'] = location.get('display_name', query)
|
| 212 |
-
|
| 213 |
-
# Try to extract ZIP code from address details
|
| 214 |
-
address = location.get('address', {})
|
| 215 |
-
zip_code = address.get('postcode')
|
| 216 |
-
|
| 217 |
-
if zip_code:
|
| 218 |
-
normalized_zip = self._normalize_zip(zip_code)
|
| 219 |
-
if normalized_zip and self._validate_zip(normalized_zip):
|
| 220 |
-
result['zip_code'] = normalized_zip
|
| 221 |
-
result['normalized_address'] = result['display_name']
|
| 222 |
-
result['error'] = None
|
| 223 |
-
logger.info(f"✓ Resolved '{query}' to ZIP {normalized_zip}")
|
| 224 |
-
return result
|
| 225 |
-
|
| 226 |
-
# If we get here, location was found but no valid ZIP in any result
|
| 227 |
-
county_hint = "" if "county" not in query.lower() else " County-level names rarely include ZIP codes; please provide a city or ZIP within the county."
|
| 228 |
-
result['error'] = f"Location found but no ZIP code available.{county_hint}"
|
| 229 |
-
logger.warning(f"No ZIP code in any Nominatim results for '{query}'")
|
| 230 |
-
|
| 231 |
-
except requests.Timeout:
|
| 232 |
-
result['error'] = "Request timed out. Please try again."
|
| 233 |
-
logger.error(f"Timeout resolving '{query}'")
|
| 234 |
-
except requests.RequestException as e:
|
| 235 |
-
result['error'] = f"Network error: {str(e)}"
|
| 236 |
-
logger.error(f"Request error resolving '{query}': {e}")
|
| 237 |
-
except Exception as e:
|
| 238 |
-
result['error'] = f"Unexpected error: {str(e)}"
|
| 239 |
-
logger.error(f"Unexpected error resolving '{query}': {e}")
|
| 240 |
-
|
| 241 |
-
return result
|
| 242 |
-
|
| 243 |
def get_nearby_zips(self, zip_code: str, available_zips: set, radius_miles: float = 10) -> List[str]:
|
| 244 |
"""
|
| 245 |
Get nearby ZIP codes that have data available.
|
|
|
|
| 67 |
return zip_match.group(0)
|
| 68 |
return None
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
def get_nearby_zips(self, zip_code: str, available_zips: set, radius_miles: float = 10) -> List[str]:
|
| 71 |
"""
|
| 72 |
Get nearby ZIP codes that have data available.
|