Spaces:
Sleeping

faseehsandhu commited on
Commit
31b5ed7
·
0 Parent(s):
.env.example ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
2
+ AZURE_OPENAI_API_KEY=your-api-key
3
+ AZURE_OPENAI_DEPLOYMENT=gpt-4
4
+ AZURE_OPENAI_API_VERSION=2024-02-15-preview
5
+
6
+ # Add any other environment variables needed for your application here.
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.xlsx filter=lfs diff=lfs merge=lfs -text
2
+ *.pdf filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual Environment
24
+ .venv/
25
+ venv/
26
+ ENV/
27
+ env/
28
+
29
+ # IDE
30
+ .vscode/
31
+ .idea/
32
+ *.swp
33
+ *.swo
34
+ *~
35
+
36
+ # Environment variables
37
+ .env
38
+
39
+ # Data files
40
+ data/user_uploads/*
41
+ !data/user_uploads/.gitkeep
42
+
43
+ # OS
44
+ .DS_Store
45
+ Thumbs.db
46
+
47
+ # Streamlit
48
+ .streamlit/secrets.toml
README.md ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Streamlit Data Dictionary Chatbot
2
+
3
+ An AI-powered intelligent assistant that helps data scientists and analysts quickly discover relevant columns and datasets for machine learning projects. Instead of manually searching through multiple data dictionaries, users can describe their use case in natural language and receive intelligent, cited recommendations powered by Azure OpenAI.
4
+
5
+ ## Executive Summary
6
+
7
+ This Streamlit web application combines conversational AI with smart retrieval technology (RAG - Retrieval-Augmented Generation) to make data dictionary exploration effortless. It supports multiple file formats, maintains conversation context, and uses advanced semantic search to find the most relevant columns for any data science use case.
8
+
9
+ ## Key Features
10
+
11
+ ### 🤖 AI-Powered Conversational Interface
12
+ - **Natural Language Queries**: Ask questions in plain English (e.g., "Which columns help predict diabetes risk?")
13
+ - **Context-Aware Responses**: Remembers last 10 conversation exchanges for meaningful follow-ups
14
+ - **Deep-Dive Analysis**: Ask detailed questions about specific columns, definitions, and relationships
15
+ - **Smart Clarifications**: AI asks clarifying questions when queries are ambiguous
16
+ - **Mandatory Dataset Citation**: Every column recommendation explicitly states its source dataset
17
+
18
+ ### 📊 Multi-Source Data Dictionary Management
19
+ - **Default Dictionaries**: Pre-loaded data dictionaries available immediately on startup
20
+ - **User Uploads**: Upload custom data dictionaries at runtime
21
+ - **Multiple Format Support**: CSV (.csv), Excel (.xlsx, .xls), and PDF (.pdf) files
22
+ - **Dictionary Controls**: Toggle dictionaries on/off, view metadata, delete user uploads
23
+ - **Real-Time Metrics**: Live dashboard showing loaded dictionaries and cache status
24
+
25
+ ### 🎯 Smart Retrieval System (RAG)
26
+ - **Two-Stage Retrieval**: Combines fast keyword matching with AI semantic search
27
+ - **Massive Token Reduction**: Reduces context from 160,000+ to 5,000-10,000 tokens (97% reduction)
28
+ - **Cost Savings**: ~95% reduction in Azure OpenAI API costs
29
+ - **Speed Optimized**: First query ~2-3 seconds, subsequent queries <1 second (cached)
30
+ - **Intelligent Behavior**: Skips retrieval for simple greetings, auto-detects dictionary changes
31
+ - **Configurable Precision**: Adjustable top-k results (5-50) via sidebar slider
32
+
33
+ ### 💾 Advanced Caching System
34
+ - **Persistent Disk Cache**: Survives application restarts (`.cache/` directory)
35
+ - **Instant Startup**: Subsequent launches skip indexing (<500ms load time)
36
+ - **Automatic Invalidation**: Rebuilds cache when dictionaries change
37
+ - **Manual Controls**: "Clear Cache" and "Force Reindex" buttons
38
+ - **Embedding Cache**: Prevents redundant API calls for previously seen queries
39
+
40
+ ### 🎨 User Interface Components
41
+ - **Main Chat View**: Message history, input box, index status badge, debug expander
42
+ - **Sidebar Controls**: Navigation, retrieval settings, cache management, metrics dashboard
43
+ - **Upload Management**: Drag-and-drop uploader with file list and delete functionality
44
+ - **Retrieval Dashboard**: Live metrics for chunks indexed, embeddings cached, corpus signature
45
+
46
+ ### ⚙️ Advanced Configuration
47
+ - **Top-k Slider**: Adjust precision vs recall (5-50 results)
48
+ - **Embeddings Toggle**: Switch between semantic and keyword-only search
49
+ - **Debug Mode**: View retrieved snippets, source, and settings used
50
+ - **Environment Variables**: Flexible Azure OpenAI configuration
51
+
52
+ ## Project Structure
53
+
54
+ ```
55
+ streamlit-data-dictionary-chatbot
56
+ ├── src
57
+ │ ├── app.py # Main entry point of the Streamlit application
58
+ │ ├── components # UI components for the application
59
+ │ │ ├── chat_interface.py # Chatbot interface implementation
60
+ │ │ ├── file_uploader.py # File upload functionality
61
+ │ │ └── sidebar.py # Sidebar layout for navigation
62
+ │ ├── services # Services for data handling and API interactions
63
+ │ │ ├── azure_openai_service.py # Azure OpenAI API interactions
64
+ │ │ ├── data_dictionary_service.py # Management of data dictionaries
65
+ │ │ └── file_parser_service.py # File parsing logic
66
+ │ ├── utils # Utility functions and session management
67
+ │ │ ├── session_state.py # Session state management
68
+ │ │ └── validators.py # Input validation functions
69
+ │ └── config.py # Configuration settings
70
+ ├── data
71
+ │ ├── default_dictionaries # Directory for default data dictionaries
72
+ │ │ └── .gitkeep # Keeps the directory in version control
73
+ │ └── user_uploads # Directory for user-uploaded data dictionaries
74
+ │ └── .gitkeep # Keeps the directory in version control
75
+ ├── tests # Unit tests for the application
76
+ │ ├── test_services.py # Tests for service logic
77
+ │ └── test_utils.py # Tests for utility functions
78
+ ├── .env.example # Example environment variable configuration
79
+ ├── .gitignore # Files and directories to ignore in version control
80
+ ├── requirements.txt # Project dependencies
81
+ ├── README.md # Project documentation
82
+ └── setup.py # Packaging configuration
83
+ ```
84
+
85
+ ## Key Benefits
86
+
87
+ ✅ **Time Savings**: Find relevant columns in seconds vs hours of manual searching
88
+ ✅ **Cost Efficiency**: 95% reduction in API costs through smart retrieval
89
+ ✅ **Accuracy**: AI semantic search finds contextually relevant matches, not just keywords
90
+ ✅ **Scalability**: Handles unlimited data dictionaries without context limit errors
91
+ ✅ **Flexibility**: Works with CSV, Excel, and PDF data dictionaries
92
+ ✅ **Transparency**: Debug tools and citation enforcement ensure trustworthy recommendations
93
+ ✅ **User Control**: Adjustable precision, cache management, dictionary selection
94
+ ✅ **Conversational**: Natural follow-up questions and clarifications supported
95
+ ✅ **Persistent**: Cache system ensures instant subsequent uses
96
+ ✅ **Production-Ready**: Error handling, logging, graceful degradation built-in
97
+
98
+ ## Use Case Example
99
+
100
+ **User Query:** *"I'm building a diabetes risk prediction model. Which columns should I use?"*
101
+
102
+ **Application Process:**
103
+ 1. Indexes all available data dictionaries into searchable chunks (if not cached)
104
+ 2. Searches for "diabetes risk prediction" using two-stage retrieval
105
+ 3. Finds 25 most relevant entries across all dictionaries
106
+ 4. Sends only these 25 entries + query + chat history to AI
107
+ 5. AI responds with specific column recommendations, each citing the source dataset
108
+ 6. User follows up: *"Tell me more about the HbA1c column"*
109
+ 7. System retrieves detailed information about that specific column
110
+
111
+ **Result:** Precise, cited recommendations in <3 seconds with context-aware assistance.
112
+
113
+ ## Installation
114
+
115
+ 1. Clone the repository:
116
+ ```
117
+ git clone https://github.com/yourusername/streamlit-data-dictionary-chatbot.git
118
+ cd streamlit-data-dictionary-chatbot
119
+ ```
120
+
121
+ 2. Install the required packages:
122
+ ```
123
+ pip install -r requirements.txt
124
+ ```
125
+
126
+ 3. Set up your environment variables by copying `.env.example` to `.env` and filling in the necessary values:
127
+
128
+ **Required for chat:**
129
+ ```env
130
+ AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
131
+ AZURE_OPENAI_API_KEY=your-api-key
132
+ AZURE_OPENAI_DEPLOYMENT=gpt-4o-mini # or your chat model deployment name
133
+ AZURE_OPENAI_API_VERSION=2024-12-01-preview
134
+ ```
135
+
136
+ **Optional for enhanced retrieval (recommended):**
137
+ ```env
138
+ AZURE_OPENAI_EMBEDDING_ENDPOINT=https://your-resource.openai.azure.com/
139
+ AZURE_OPENAI_EMBEDDING_DEPLOYMENT=text-embedding-3-large # or your embedding deployment name
140
+ AZURE_OPENAI_EMBEDDING_API_VERSION=2024-02-01
141
+ ```
142
+
143
+ If embedding variables are not set, the app will fall back to lexical search (still functional, but less accurate).
144
+
145
+ ## How It Works
146
+
147
+ ### Retrieval-Augmented Generation (RAG)
148
+
149
+ **The Problem:**
150
+ Large data dictionaries can contain 100,000+ tokens, but Azure OpenAI's GPT-4o-mini has a 128,000 token context limit. Sending complete dictionaries causes:
151
+ - ❌ API errors (context_length_exceeded)
152
+ - ❌ High costs (~$0.50+ per query)
153
+ - ❌ Slow response times (5-10 seconds)
154
+ - ❌ Information overload for the AI
155
+
156
+ **The Solution:**
157
+ Two-stage intelligent retrieval system that selects only the 1-2% most relevant data:
158
+
159
+ #### Stage 1: Lexical Pre-Filtering (Keyword-Based)
160
+ - Quickly scans all indexed chunks (lines from data dictionaries)
161
+ - Uses token overlap (60%) + fuzzy matching (40%) to score relevance
162
+ - Selects top 300 potentially relevant entries
163
+ - Speed: <100ms for thousands of chunks
164
+
165
+ #### Stage 2: Semantic Re-Ranking (AI-Based)
166
+ - Converts user query and top 300 candidates into embeddings (vector representations)
167
+ - Uses Azure OpenAI `text-embedding-3-large` model (3,072 dimensions)
168
+ - Computes cosine similarity for semantic relevance
169
+ - Returns top-k results (configurable 5-50, default 25)
170
+ - Caches embeddings to avoid redundant API calls
171
+
172
+ **Complete Flow:**
173
+ 1. **Indexes dictionaries** into chunks with metadata (dataset name, line number)
174
+ 2. **At query time**, runs two-stage retrieval (lexical → semantic)
175
+ 3. **Sends only 25 relevant snippets** to the LLM with query and chat history
176
+ 4. **LLM responds** with grounded answers, citing specific datasets and columns
177
+ 5. **Caches embeddings** for instant subsequent queries
178
+
179
+ **Performance Metrics:**
180
+ - Token Reduction: 160,000 → 5,000-10,000 tokens (97% reduction)
181
+ - Cost Reduction: ~95% savings on API calls
182
+ - Speed: First query ~2-3s, cached queries <1s
183
+ - Accuracy: Retrieves only contextually relevant data
184
+
185
+ **Intelligent Optimizations:**
186
+ - Short messages (≤3 words like "hi", "thanks") skip retrieval entirely
187
+ - Automatic cache invalidation when dictionaries change
188
+ - Batch embedding API calls for efficiency
189
+ - Graceful fallback to keyword-only mode if embeddings unavailable
190
+
191
+ ## Usage
192
+
193
+ To run the application, execute the following command:
194
+ ```
195
+ streamlit run src/app.py
196
+ ```
197
+
198
+ Open your web browser and navigate to `http://localhost:8501` to access the application.
199
+
200
+ ## Technical Architecture
201
+
202
+ **Frontend:** Streamlit (Python web framework)
203
+ **Backend:** Python 3.x
204
+ **AI Services:**
205
+ - Azure OpenAI GPT-4o-mini (chat completions)
206
+ - Azure OpenAI text-embedding-3-large (semantic search)
207
+
208
+ **Data Processing:** Pandas, PyPDF2
209
+ **Storage:** File system (dictionaries + cache)
210
+ **Search Algorithm:** Hybrid lexical + semantic retrieval
211
+
212
+ **Cache Structure:**
213
+ ```
214
+ .cache/
215
+ ├── chunks.json # Indexed dictionary entries
216
+ ├── embeddings.json # Cached embedding vectors
217
+ └── corpus_sig.txt # Dictionary change detection hash
218
+ ```
219
+
220
+ ## Configuration Reference
221
+
222
+ ### Required Environment Variables (Chat)
223
+ ```env
224
+ AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
225
+ AZURE_OPENAI_API_KEY=your-api-key
226
+ AZURE_OPENAI_DEPLOYMENT=gpt-4o-mini
227
+ AZURE_OPENAI_API_VERSION=2024-12-01-preview
228
+ ```
229
+
230
+ ### Optional Environment Variables (Enhanced Retrieval)
231
+ ```env
232
+ AZURE_OPENAI_EMBEDDING_ENDPOINT=https://your-resource.openai.azure.com/
233
+ AZURE_OPENAI_EMBEDDING_DEPLOYMENT=text-embedding-3-large
234
+ AZURE_OPENAI_EMBEDDING_API_VERSION=2024-02-01
235
+ ```
236
+
237
+ **Note:** Without embedding variables, the app falls back to lexical search (functional but less accurate).
238
+
239
+ ### Runtime Controls (Sidebar)
240
+ - **Top-k Slider**: Adjust number of retrieved results (5-50)
241
+ - **Embeddings Toggle**: Disable semantic search for faster keyword-only mode
242
+ - **Clear Cache**: Wipe all cached data and embeddings
243
+ - **Force Reindex**: Rebuild index from current dictionaries
244
+
245
+ ## Troubleshooting
246
+
247
+ **Issue:** Slow first query
248
+ **Solution:** First query builds embeddings cache. Subsequent queries are instant.
249
+
250
+ **Issue:** "Context length exceeded" error
251
+ **Solution:** Reduce top-k slider value or verify retrieval service is enabled.
252
+
253
+ **Issue:** Embeddings not working
254
+ **Solution:** Verify `AZURE_OPENAI_EMBEDDING_DEPLOYMENT` is set correctly. App falls back to lexical search.
255
+
256
+ **Issue:** Cache not persisting
257
+ **Solution:** Check write permissions for `.cache/` directory.
258
+
259
+ **Issue:** Inaccurate results
260
+ **Solution:** Increase top-k value or enable embeddings if disabled.
261
+
262
+ ## Contributing
263
+
264
+ Contributions are welcome! Please feel free to submit a pull request or open an issue for any enhancements or bug fixes.
265
+
266
+ ## License
267
+
268
+ This project is licensed under the MIT License. See the LICENSE file for more details.
data/default_dictionaries/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file is intentionally left blank.
data/default_dictionaries/AHRF Data Dictionary.xlsx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:470f31391f3708f3719d234119e1d8fd7eb3a2dcd3a1a6de682ef363df379d5e
3
+ size 163372
data/default_dictionaries/CHR Data Dictionary.xlsx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7910eb3c331221b1cfda0e75db4838ada56a51f520fb019b1223e881346b4813
3
+ size 17150
data/default_dictionaries/EJI_DATADICTIONARY.csv ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2024 VARIABLE NAME,2024 VARIABLE DESCRIPTION,2024 TABLE FIELD CALCULATION,NOTES
2
+ STATEFP,State Federal Information Processing Series (FIPS) code,No Value,No Value
3
+ COUNTYFP,County FIPS code,No Value,No Value
4
+ TRACTCE,Census tract geographic code, No Value,No Value
5
+ AFFGEOID,"Census tract identifier; a concatenation of current state Federal Information Processing Series (FIPS) code, county FIPS code, and census tract code",No Value,No Value
6
+ GEOID,"11-digit census tract identifier, which is a concatenation of the 2-digit state FIPS code, 3-digit county FIPS code, and 6-digit census tract geographic code for 2020, with Connecticut tracts using updated 2022 County FIPS Codes.","2020 State FIPS + 2020 County FIPS + 2020 Census Tract Code (All States, except Connecticut)
7
+ For Connecticut tracts: 2020 State FIPS + 2022 County FIPS + 2020 Census Tract Code",Connecticut tracts are using updated 2022 County FIPS codes. All other tracts are using 2020 FIPS codes.
8
+ GEOID_2020,"11-digit census tract identifier, which is a concatenation of the 2-digit state FIPS code, 3-digit county FIPS code, and 6-digit census tract geographic code for 2020.",2020 State FIPS + 2020 County FIPS + 2020 Census Tract Code (All States),Connecticut tracts are using 2020 County FIPS codes. All other tracts are using 2020 FIPS codes as well.
9
+ COUNTY,County names,No Value,No Value
10
+ StateAbbr,State abbreviations,No Value,No Value
11
+ StateDesc,Full state name,No Value,No Value
12
+ Location,"Text description of tract, county, state",No Value,No Value
13
+ E_TOTPOP,"Population estimate, 2018-2022 ACS",S0601_C01_001E,No Value
14
+ M_TOTPOP,"Population estimate MOE, 2018-2022 ACS",S0601_C01_001M,No Value
15
+ E_DAYPOP,"Adjunct variable - Estimated daytime population, LandScan 2021",No Value,No Value
16
+ SPL_EJI,"Summation of the EBM, HVM, and SVM percentile ranks",RPL_EBM + RPL_HVM + RPL_SVM,Tract with null values were not included in the sum.
17
+ RPL_EJI,Percentile ranks of SPL_EJI,In Excel: PERCENTRANK.INC on SPL_EJI array with 4 significant digits,Null values removed before calculating output rank.
18
+ SPL_SER,Summation of the EBM and SVM percentile ranks,RPL_EBM + RPL_SVM,Tract with null values were not included in the sum.
19
+ RPL_SER,Percentile ranks of SPL_SER,In Excel: PERCENTRANK.INC on SPL_SER array with 4 significant digits,Null values removed before calculating output rank.
20
+ SPL_EJI_CBM,"Summation of the EBM, HVM, SVM, and CBM percentile ranks",RPL_EBM + RPL_HVM + RPL_SVM + RPL_CBM,Tract with null values were not included in the sum.
21
+ RPL_EJI_CBM,Percentile ranks of SPL_EJI_CBM,In Excel: PERCENTRANK.INC on SPL_EJI_CBM array with 4 significant digits,Null values removed before calculating output rank.
22
+ E_MINRTY,"Percentage of persons who identify as Hispanic or Latino (of any race); Black and African American, Not Hispanic or Latino; American Indian and Alaska Native, Not Hispanic or Latino; Asian, Not Hispanic or Latino; Native Hawaiian and Other Pacific Islander, Not Hispanic or Latino; Two or More Races, Not Hispanic or Latino; Other Races, Not Hispanic or Latino",100.0 - DP05_0079PE,No Value
23
+ EPL_MINRTY,"Percentile rank of percentage of persons who identify as Hispanic or Latino (of any race); Black and African American, Not Hispanic or Latino; American Indian and Alaska Native, Not Hispanic or Latino; Asian, Not Hispanic or Latino; Native Hawaiian and Other Pacific Islander, Not Hispanic or Latino; Two or More Races, Not Hispanic or Latino; Other Races, Not Hispanic or Latino",In Excel: PERCENTRANK.INC on E_MINRTY array with 4 significant digits,Null values removed before calculating output rank.
24
+ SPL_SVM_DOM1,"Domain consisting of the percentage of persons who identify as Hispanic or Latino (of any race); Black and African American, Not Hispanic or Latino; American Indian and Alaska Native, Not Hispanic or Latino; Asian, Not Hispanic or Latino; Native Hawaiian and Other Pacific Islander, Not Hispanic or Latino; Two or More Races, Not Hispanic or Latino; Other Races, Not Hispanic or Latino",EPL_MINRTY,Tract with null values were not included in the sum.
25
+ RPL_SVM_DOM1,"Percentile rank of domain consisting of the percentage of persons who identify as Hispanic or Latino (of any race); Black and African American, Not Hispanic or Latino; American Indian and Alaska Native, Not Hispanic or Latino; Asian, Not Hispanic or Latino; Native Hawaiian and Other Pacific Islander, Not Hispanic or Latino; Two or More Races, Not Hispanic or Latino; Other Races, Not Hispanic or Latino",In Excel: PERCENTRANK.INC on SPL_SVM_DOM1 array with 4 significant digits,Null values removed before calculating output rank.
26
+ E_POV200,Percentage of persons with income below 200% of the federal poverty level,(S1701_C01_042E / S1701_C01_001E) * 100,No Value
27
+ EPL_POV200,Percentile rank of the percentage of persons with income below 200% of federal poverty level,In Excel: PERCENTRANK.INC on E_POV200 array with 4 significant digits,Null values removed before calculating output rank.
28
+ E_NOHSDP,Percentage of persons with no high school diploma (age 25+) ,S0601_C01_033E,No Value
29
+ EPL_NOHSDP,Percentile rank of percentage of persons with no high school diploma (age 25+),In Excel: PERCENTRANK.INC on E_NOHSDP array with 4 significant digits,Null values removed before calculating output rank.
30
+ E_UNEMP,Percentage of persons who are unemployed,DP03_0009PE,No Value
31
+ EPL_UNEMP,Percentile rank of the percentage of persons who are unemployed,In Excel: PERCENTRANK.INC on E_UNEMP array with 4 significant digits,Null values removed before calculating output rank.
32
+ E_RENTER,Percentage of housing units that are renter occupied,S1101_C01_019E,No Value
33
+ EPL_RENTER,Percentile rank of the percentage of housing units that are renter occupied,In Excel: PERCENTRANK.INC on E_RENTER array with 4 significant digits,Null values removed before calculating output rank.
34
+ E_HOUBDN,"Percentage of households that make less than 75,000 who are considered burdened by housing costs (i.e., pay greater than 30% of monthly income on housing expenses) ",((S2503_C01_028E + S2503_C01_032E + S2503_C01_036E + S2503_C01_040E) / S2503_C01_001E) * 100,No Value
35
+ EPL_HOUBDN,"Percentile rank of the percentage of households that make less than 75,000 who are considered burdened by housing costs (i.e., pay greater than 30% of monthly income on housing expenses) ",In Excel: PERCENTRANK.INC on E_HOUBDN array with 4 significant digits,Null values removed before calculating output rank.
36
+ E_UNINSUR,"Percentage of persons who are uninsured (i.e., have no health insurance)",S2701_C05_001E,No Value
37
+ EPL_UNINSUR,Percentile rank of the percentage of persons who are uninsured,In Excel: PERCENTRANK.INC on E_UNINSUR array with 4 significant digits,Null values removed before calculating output rank.
38
+ E_NOINT,Percentage of persons without internet,S2801_C02_019E,No Value
39
+ EPL_NOINT,Percentile rank of the percentage of persons without internet,In Excel: PERCENTRANK.INC on E_NOINT array with 4 significant digits,Null values removed before calculating output rank.
40
+ SPL_SVM_DOM2,"Domain consisting of persons below 200% of the federal poverty level, with no high school diploma, unemployed, renters, high housing cost, no health insurance, and no internet",EPL_POV200 + EPL_NOHSDP + EPL_UNEMP + EPL_RENTER + EPL_HOUBDN + EPL_UNINSUR + EPL_NOINT,Tract with null values were not included in the sum.
41
+ RPL_SVM_DOM2,"Percentile rank of the domain consisting of persons below 200% of the federal poverty level, with no high school diploma, unemployed, renters, high housing cost, no health insurance, and no internet",In Excel: PERCENTRANK.INC on SPL_SVM_DOM2 array with 4 significant digits,Null values removed before calculating output rank.
42
+ E_AGE65,Persons aged 65 and older,S0101_C02_030E,No Value
43
+ EPL_AGE65,Percentile rank of the percentage of persons aged 65 and older ,In Excel: PERCENTRANK.INC on E_AGE65 array with 4 significant digits,Null values removed before calculating output rank.
44
+ E_AGE17,Persons aged 17 and younger,DP05_0019PE,No Value
45
+ EPL_AGE17,Percentile rank of the percentage of persons aged 17 and younger estimate,In Excel: PERCENTRANK.INC on E_AGE17 array with 4 significant digits,Null values removed before calculating output rank.
46
+ E_DISABL,Percentage of civilian noninstitutionalized persons with a disability,DP02_0072PE,No Value
47
+ EPL_DISABL,Percentile rank of the percentage of civilian noninstitutionalized population with a disability,In Excel: PERCENTRANK.INC on E_DISABL array with 4 significant digits,Null values removed before calculating output rank.
48
+ E_LIMENG,"Percentage of persons (age 5+) who speak English ""less than well""",((B16005_007E + B16005_008E + B16005_012E + B16005_013E + B16005_017E + B16005_018E + B16005_022E + B16005_023E + B16005_029E + B16005_030E + B16005_034E + B16005_035E + B16005_039E + B16005_040E + B16005_044E + B16005_045E) / B16005_001E) * 100,No Value
49
+ EPL_LIMENG,"Percentile rank of the percentage of persons (age 5+) who speak English ""less than well"" ",In Excel: PERCENTRANK.INC on E_LIMENG array with 4 significant digits,Null values removed before calculating output rank.
50
+ SPL_SVM_DOM3,"Domain consisting of English language proficiency, aged 65 or older, aged 17 or younger, and civilian with a disability",EPL_AGE65 + EPL_AGE17 + EPL_DISABL + EPL_LIMENG,Tract with null values were not included in the sum.
51
+ RPL_SVM_DOM3,"Percentile rank of the domain consisting of English language proficiency, aged 65 or older, aged 17 or younger, and civilian with a disability",In Excel: PERCENTRANK.INC on SPL_SVM_DOM3 array with 4 significant digits,Null values removed before calculating output rank.
52
+ E_MOBILE,Percentage of housing units designated as mobile homes,DP04_0014PE,No Value
53
+ EPL_MOBILE,Percentile rank of the percentage of housing units designated as mobile homes estimate,In Excel: PERCENTRANK.INC on E_MOBILE array with 4 significant digits,Null values removed before calculating output rank.
54
+ E_GROUPQ,Percentage of persons living in group quarters,(B26001_001E / E_TOTPOP) * 100,No Value
55
+ EPL_GROUPQ,Percentile rank of the percentage of persons living in group quarters ,In Excel: PERCENTRANK.INC on E_MOBILE array with 4 significant digits,Null values removed before calculating output rank.
56
+ SPL_SVM_DOM4,Domain consisting of mobile homes and housing with group quarters,EPL_MOBILE + EPL_GROUPQ,Tract with null values were not included in the sum.
57
+ RPL_SVM_DOM4,Percentile rank of the domain consisting of mobile homes and housing with group quarters,In Excel: PERCENTRANK.INC on SPL_SVM_DOM4 array with 4 significant digits,Null values removed before calculating output rank.
58
+ SPL_SVM,Summation of the Social Vulnerability Module percentile ranks,EPL_MINRTY + EPL_RENTER + EPL_HOUBDN + EPL_UNINSUR EPL_NOINT + EPL_AGE65 + EPL_AGE17 + EPL_DISABL + EPL_LIMENG + EPL_MOBILE + EPL_GROUPQ,Tract with null values were not included in the sum.
59
+ RPL_SVM,Percentile ranks of Social Vulnerability Module,In Excel: PERCENTRANK.INC on SPL_SVM array with 4 significant digits,Null values removed before calculating output rank.
60
+ E_OZONE,"The annual mean number of days above the regulatory standard for Ozone (O3), averaged over 3-years ",No Value,No Value
61
+ EPL_OZONE,Percentile rank of annual mean days above O3 regulatory standard - 3-year average,In Excel: PERCENTRANK.INC on E_OZONE array with 4 significant digits,Null values removed before calculating output rank.
62
+ E_PM,"The annual mean number of days above the regulatory standard for Particulate Matter 2.5 (PM2.5), averaged over 3-years ",No Value,No Value
63
+ EPL_PM,Percentile rank of annual mean days above PM2.5 regulatory standard - 3-year average,In Excel: PERCENTRANK.INC on E_PM array with 4 significant digits,Null values removed before calculating output rank.
64
+ E_DSLPM,Ambient concentrations of diesel particulate matter ,No Value,No Value
65
+ EPL_DSLPM,Percentile rank of ambient concentrations of diesel PM/m3,In Excel: PERCENTRANK.INC on E_DSLPM array with 4 significant digits,Null values removed before calculating output rank.
66
+ E_TOTCR,"The likelihood of developing cancer from air toxics over the course of a lifetime, assuming continuous exposure ",No Value,No Value
67
+ EPL_TOTCR,"Percentile rank of the probability of contracting cancer over the course of a lifetime, assuming continuous exposure",In Excel: PERCENTRANK.INC on E_TOTCR array with 4 significant digits,Null values removed before calculating output rank.
68
+ SPL_EBM_DOM1,"Domain consisting of ozone, PM2.5, air toxics cancer risk, and diesel particulate matter.",EPL_OZONE + EPL_PM + EPL_DSLPM + EPL_TOTCR,Tract with null values were not included in the sum.
69
+ RPL_EBM_DOM1,"Percentile rank of domain consisting of ozone, PM2.5, air toxics cancer risk, and diesel particulate matter.",In Excel: PERCENTRANK.INC on SPL_EBM_THEME1 array with 4 significant digits,Null values removed before calculating output rank.
70
+ E_NPL,"
71
+ The proportion of the census tract that is within a 1-mile buffer of an EPA National Priority List (NPL) Site
72
+ ",No Value,No Value
73
+ EPL_NPL,Percentile rank of the proportion of tract's area within 1-mi buffer of EPA National Priority List site,In Excel: PERCENTRANK.INC on E_NPL array with 4 significant digits,Null values removed before calculating output rank.
74
+ E_TRI,The proportion of the census tract that is within a 1-mi buffer of an EPA Toxic Release Inventory (TRI) Site ,No Value,No Value
75
+ EPL_TRI,Percentile rank of the proportion of tract's area within 1-mi buffer of EPA Toxic Release Inventory site,In Excel: PERCENTRANK.INC on E_TRI array with 4 significant digits,Null values removed before calculating output rank.
76
+ E_TSD,"The proportion of the census tract that is within a 1-mile buffer of an EPA Treatment, Storage, and Disposal Facility (TSDF) ",No Value,No Value
77
+ EPL_TSD,"Percentile rank of the proportion of tract's area within 1-mi buffer of EPA Treatment, Storage, and Disposal site",In Excel: PERCENTRANK.INC on E_TSD array with 4 significant digits,Null values removed before calculating output rank.
78
+ E_RMP,The proportion of the census tract that is within a 1-mile buffer of an EPA Risk Management Plan (RMP) site ,No Value,No Value
79
+ EPL_RMP,Percentile rank of the proportion of tract's area within 1-mi buffer of EPA risk management plan site,In Excel: PERCENTRANK.INC on E_RMP array with 4 significant digits,Null values removed before calculating output rank.
80
+ E_COAL,The proportion of the census tract that is within a 1-mile buffer of a coal mine ,No Value,No Value
81
+ EPL_COAL,Percentile rank of the proportion of tract's area within 1-mi buffer of coal mines,In Excel: PERCENTRANK.INC on E_COAL array with 4 significant digits,Null values removed before calculating output rank.
82
+ E_LEAD,The proportion of the census tract that is within a 1-mile buffer of a lead mine ,No Value,No Value
83
+ EPL_LEAD,Percentile rank of the proportion of tract's area within 1-mi buffer of lead mines,In Excel: PERCENTRANK.INC on E_LEAD array with 4 significant digits,Null values removed before calculating output rank.
84
+ SPL_EBM_DOM2,"Domain consisting of proximity to National Priority List sites, Toxic Release Inventory sites, Treatment, Storage, and Disposal sites, Risk Management Plan sites, coal mines, and lead mines",EPL_NPL + EPL_TRI + EPL_TSD + EPL_RMP + EPL_COAL + EPL_LEAD,Tract with null values were not included in the sum.
85
+ RPL_EBM_DOM2,"Percentile rank of the domain consisting of proximity to National Priority List sites, Toxic Release Inventory sites, Treatment, Storage, and Disposal sites, Risk Management Plan sites, coal mines, and lead mines",In Excel: PERCENTRANK.INC on SPL_EBM_THEME2 array with 4 significant digits,Null values removed before calculating output rank.
86
+ E_PARK,The proportion the census tract that is within a 1-mi buffer of a park or greenspace ,No Value,No Value
87
+ EPL_PARK,"The inverse of the percentile rank of the proportion of tract's area within 1-mi buffer of green space, to represent tracts that are not within 1-mi of a park or greenspace",In Excel: PERCENTRANK.INC on E_PARK array with 4 significant digits,Null values removed before calculating output rank.
88
+ E_HOUAGE,"The percentage of houses built before 1980, to estimate potential exposure to lead ",No Value,No Value
89
+ EPL_HOUAGE,Percentile rank of the percentage of houses built pre- 1980 (lead exposure),In Excel: PERCENTRANK.INC on E_HOUSAGE array with 4 significant digits,Null values removed before calculating output rank.
90
+ E_WLKIND,"The National Walkability Index (NWI) rank, which ranks block groups according to their relative walkability, aggregated to the census tract level ",No Value,No Value
91
+ EPL_WLKIND,The inverse of the percentile rank of the National Walkability Index (NWI) estimate,In Excel: PERCENTRANK.INC on E_WLKIND array with 4 significant digits,Null values removed before calculating output rank.
92
+ SPL_EBM_DOM3,"Domain consisting of proximity to recreational parks, houses built pre-1980 (lead exposure), and the NWI",EPL_PARK + EPL_HOUAGE + EPL_WLKIND,Tract with null values were not included in the sum.
93
+ RPL_EBM_DOM3,"Percentile rank of domain consisting of proximity to recreational parks, houses built pre- 1980 (lead exposure), and the NWI",In Excel: PERCENTRANK.INC on SPL_EBM_THEME3 array with 4 significant digits,Null values removed before calculating output rank.
94
+ E_RAIL,The proportion of the census tract within a 1-mi buffer of a railway ,No Value,No Value
95
+ EPL_RAIL,Percentile rank of the proportion of tract's area within 1-mi buffer of railway,In Excel: PERCENTRANK.INC on E_RAIL array with 4 significant digits,Null values removed before calculating output rank.
96
+ E_ROAD,The proportion of the census tract that is within a 1-mi buffer of a high volume roadway or highway ,No Value,No Value
97
+ EPL_ROAD,Percentile rank of the proportion of tract's area within 1-mi buffer of high volume road or highway,In Excel: PERCENTRANK.INC on E_ROAD array with 4 significant digits,Null values removed before calculating output rank.
98
+ E_AIRPRT,The proportion of the census tract that is within a 1-mi buffer of an airport ,No Value,No Value
99
+ EPL_AIRPRT,Percentile rank of the proportion of tract's area within 1-mi buffer of airport,In Excel: PERCENTRANK.INC on E_AIRPRT array with 4 significant digits,Null values removed before calculating output rank.
100
+ SPL_EBM_DOM4,"Domain consisting of proximity to high volume roads, railways, and airports",EPL_RAIL + EPL_ROAD + EPL_AIRPRT,Tract with null values were not included in the sum.
101
+ RPL_EBM_DOM4,"Percentile rank of the domain consisting of proximity to high volume roads, railways, and airports",In Excel: PERCENTRANK.INC on SPL_EBM_THEME4 array with 4 significant digits,Null values removed before calculating output rank.
102
+ E_IMPWTR,The percentage of the census tract that intersects an impaired or impacted watershed at the HUC-12 level ,No Value,No Value
103
+ EPL_IMPWTR,Percentile rank of the percentage of the tract that intersects an impaired/impacted watershed at the HUC12 level,In Excel: PERCENTRANK.INC on E_IMPWTR array with 4 significant digits,Null values removed before calculating output rank.
104
+ F_IMPWTR,Flag field to denote which census tracts have no data versus a true value of 0 as the proportion of impaired water. ,"If E_IMPWTR IS NOT NULL, then F_IMPWTR = 0 to denote a non-null value;
105
+ If E_IMPWTR IS NULL, then F_IMPWTR = 1 to denote where missing data has been updated to zero.","If E_IMPWTR has no data (IS NULL), F_IMPWTR = 1. "
106
+ SPL_EBM_DOM5,Domain consisting of impaired water bodies,EPL_IMPWTR,Tract with null values were not included in the sum.
107
+ RPL_EBM_DOM5,Percentile rank of the domain consisting of impaired water bodies,In Excel: PERCENTRANK.INC on SPL_EBM_THEME5 array with 4 significant digits,Null values removed before calculating output rank.
108
+ SPL_EBM,Summation of the Environmental Burden Module percentile ranks,EPL_OZONE + EPL_PM + EPL_DSLPM + EPL_TOTCR + EPL_NPL + EPL_TRI + EPL_TSD + EPL_RMP + EPL_COAL + EPL_LEAD + EPL_PARK + EPL_HOUAGE + EPL_WLKIND + EPL_RAIL + EPL_ROAD + EPL_AIRPRT + EPL_IMPWTR,Tract with null values were not included in the sum.
109
+ RPL_EBM,Percentile ranks of Environmental Burden Module,In Excel: PERCENTRANK.INC on SPL_EBM array with 4 significant digits,Null values removed before calculating output rank.
110
+ E_ASTHMA,Percentage of individuals with asthma,No Value,No Value
111
+ EPL_ASTHMA,Percentile rank of the percentage of individuals with asthma,In Excel: PERCENTRANK.INC on EP_ASTHMA array with 4 significant digits,Null values removed before calculating output rank.
112
+ F_ASTHMA,Flag indicating tracts greater than 0.6666 percentile rank with asthma,EPL_ASTHMA > 0.6666,No Value
113
+ E_CANCER,Percentage of individuals with cancer,No Value,No Value
114
+ EPL_CANCER,Percentile rank of percentage of persons with cancer,In Excel: PERCENTRANK.INC on EP_CANCER array with 4 significant digits,Null values removed before calculating output rank.
115
+ F_CANCER,Flag indicating tracts greater than 0.6666 percentile rank with cancer,EPL_CANCER > 0.6666,No Value
116
+ E_CHD,Percentage of individuals with coronary heart disease,No Value,No Value
117
+ EPL_CHD,Percentile rank of percentage of individuals with coronary heart disease,In Excel: PERCENTRANK.INC on EP_CHD array with 4 significant digits,Null values removed before calculating output rank.
118
+ F_CHD,Flag indicating tracts greater than 0.6666 percentile rank with coronary heart disease,EPL_BPHIGH > 0.6666,No Value
119
+ E_MHLTH,Percentage of individuals reporting not good mental health,No Value,No Value
120
+ EPL_MHLTH,Percentage of individuals reporting not good mental health percentile rank,In Excel: PERCENTRANK.INC on EP_MHLTH array with 4 significant digits,Null values removed before calculating output rank.
121
+ F_MHLTH,Flag indicating tracts greater than 0.6666 percentile rank with not good mental health,EPL_MHLTH > 0.6666,No Value
122
+ E_DIABETES,Percentage of individuals with diabetes,No Value,No Value
123
+ EPL_DIABETES,Percentile rank of percentage of individuals with diabetes,In Excel: PERCENTRANK.INC on EP_DIABETES array with 4 significant digits,Null values removed before calculating output rank.
124
+ F_DIABETES,Flag indicating tracts greater than 0.6666 percentile rank with diabetes,EPL_DIABETES > 0.6666,No Value
125
+ F_HVM,Total number of tertile flags (>0.6666),F_BPHIGH + F_ASTHMA + F_CANCER + F_MHLTH + F_DIABETES,Tract with null values were not included in the sum.
126
+ RPL_HVM,Normalized (0-1) flag score for HVM tertile flags,F_HVM * 0.2,No Value
127
+ E_NEHD,Number of extreme heat days (days where maximum temperature exceeds 95th percentile of historical maximum temperatures for that tract),No Value,No Value
128
+ EPL_NEHD,Percentile rank of the number of extreme heat days,In Excel: PERCENTRANK.INC on E_NEHD array with 4 significant digits,Null values removed before calculating output rank.
129
+ SPL_CBM_DOM1,Domain consisting of the number of extreme heat days,EPL_NEHD,No Value
130
+ RPL_CBM_DOM1,Percentile rank of the domain consisting of number of extreme heat days,In Excel: PERCENTRANK.INC on SPL_CBM_DOM1 array with 4 significant digits,No Value
131
+ E_SMOKE,Average annualized frequency of smoky days from wildfire smoke,No Value,No Value
132
+ EPL_SMOKE,Percentile rank of average annualized frequency of smoky days from wildfire smoke,In Excel: PERCENTRANK.INC on E_SMOKE array with 4 significant digits,Null values removed before calculating output rank.
133
+ E_BURN,Average annualized burned area from wildfires,No Value,No Value
134
+ EPL_BURN,Percentile rank of average annualized burned area from wildfires,In Excel: PERCENTRANK.INC on E_BURN array with 4 significant digits,Null values removed before calculating output rank.
135
+ SPL_CBM_DOM2,Domain consisting of wildifire smoke frequency and burned area from wildfires,EPL_BURN + EPL_SMOKE,No Value
136
+ RPL_CBM_DOM2,Percentile rank of the domain consisting of wildifire smoke frequency and burned area from wildfires,In Excel: PERCENTRANK.INC on SPL_CBM_DOM2 array with 4 significant digits,Null values removed before calculating output rank.
137
+ E_CFLD,Average annualized frequency of coastal flooding events,No Value,No Value
138
+ EPL_CFLD,Percentile rank of average annualized frequency of coastal flooding events,In Excel: PERCENTRANK.INC on E_CFLD array with 4 significant digits,Null values removed before calculating output rank.
139
+ F_CFLD,Flag to denote true values and null values in Coastal Flooding Frequency,"If E_CFLD = 0, then F_CFLD = 0 to denote true zeros;
140
+ If E_CFLD IS NULL, F_CFLD = 1 to denote where missing data has been updated to zero;
141
+ If E_CFLD > 0 and EPL_CFLD = 0, then F_CFLD = 2 to denote non-zero values
142
+ with a percentile rank of zero;
143
+ All others receive a flag of 9.",No Value
144
+ E_DRGT,Average annualized frequency of drought events,No Value,No Value
145
+ EPL_DRGT,Percentile rank of average annualized frequency of drought events,In Excel: PERCENTRANK.INC on E_DRGT array with 4 significant digits,Null values removed before calculating output rank.
146
+ F_DRGT,Flag to denote true values and null values in Drought Frequency,"If E_DRGT = 0, then F_DRGT = 0 to denote true zeros;
147
+ If E_DRGT IS NULL, F_DRGT = 1 to denote where missing data has been updated to zero;
148
+ If E_DRGT > 0 and EPL_DRGT = 0, then F_DRGT = 2 to denote non-zero values
149
+ with a percentile rank of zero;
150
+ All others receive a flag of 9.",No Value
151
+ E_HRCN,Average annualized frequency of hurricane events,No Value,No Value
152
+ EPL_HRCN,Percentile rank of average annualized frequency of hurricane events,In Excel: PERCENTRANK.INC on E_HRCN array with 4 significant digits,Null values removed before calculating output rank.
153
+ F_HRCN,Flag to denote true values and null values in Hurricane Frequency,"If E_HRCN = 0, then F_HRCN = 0 to denote true zeros;
154
+ If E_HRCN IS NULL, F_HRCN = 1 to denote where missing data has been updated to zero;
155
+ If E_HRCN > 0 and EPL_HRCN = 0, then F_HRCN = 2 to denote non-zero values
156
+ with a percentile rank of zero;
157
+ All others receive a flag of 9.",No Value
158
+ E_RFLD,Average annualized frequency of riverine flooding events,No Value,No Value
159
+ EPL_RFLD,Percentile rank of average annualized frequency of riverine flooding events,In Excel: PERCENTRANK.INC on E_RFLD array with 4 significant digits,Null values removed before calculating output rank.
160
+ F_RFLD,Flag to denote true values and null values in Riverine Flooding Frequency,"If E_RFLD = 0, then F_RFLD = 0 to denote true zeros;
161
+ If E_RFLD IS NULL, F_RFLD = 1 to denote where missing data has been updated to zero;
162
+ If E_RFLD > 0 and EPL_RFLD = 0, then F_RFLD = 2 to denote non-zero values
163
+ with a percentile rank of zero;
164
+ All others receive a flag of 9.",No Value
165
+ E_SWND,Average annualized frequency of strong wind events,No Value,No Value
166
+ EPL_SWND,Percentile rank of average annualized frequency of strong wind events,In Excel: PERCENTRANK.INC on E_SWND array with 4 significant digits,Null values removed before calculating output rank.
167
+ F_SWND,Flag to denote true values and null values in Strong Wind Frequency,"If E_SWND = 0, then F_SWND = 0 to denote true zeros;
168
+ If E_SWND IS NULL, F_SWND = 1 to denote where missing data has been updated to zero;
169
+ If E_SWND > 0 and EPL_SWND = 0, then F_SWND = 2 to denote non-zero values with a percentile rank of zero;
170
+ All others receive a flag of 9.",No Value
171
+ E_TRND,Average annualized frequency of tornado events,No Value,No Value
172
+ EPL_TRND,Percentile rank of average annualized frequency of tornado events,In Excel: PERCENTRANK.INC on E_TRND array with 4 significant digits,Null values removed before calculating output rank.
173
+ F_TRND,Flag to denote true values and null values in Tornado Frequency,"If E_TRND = 0, then F_TRND = 0 to denote true zeros;
174
+ If E_TRND IS NULL, F_TRND = 1 to denote where missing data has been updated to zero;
175
+ If E_TRND > 0 and EPL_TRND = 0, then F_TRND = 2 to denote non-zero values
176
+ with a percentile rank of zero;
177
+ All others receive a flag of 9.",No Value
178
+ SPL_CBM_DOM3,"Domain consisting of Coastal Flooding Frequency, Drought Frequency, Hurricane Frequency, Riverine Flooding Frequency, Strong Wind Frequency, and Tornado Frequency",EPL_CFLD + EPL_DRGT + EPL_HRCN + EPL_RFLD + EPL_SWND + EPL_TRND,Tract with null values were not included in the sum.
179
+ RPL_CBM_DOM3,"Percentile rank of domain consisting of Coastal Flooding Frequency, Drought Frequency, Hurricane Frequency, Riverine Flooding Frequency, Strong Wind Frequency, and Tornado Frequency",In Excel: PERCENTRANK.INC on SPL_CBM_DOM3 array with 4 significant digits,Null values removed before calculating output rank.
180
+ SPL_CBM,Summation of the Climate Burden Module percentile ranks,EPL_NEHD + EPL_BURN + EPL_SMOKE + EPL_CFLD + EPL_DRGT + EPL_HRCN + EPL_RFLD + EPL_SWND + EPL_TRND,Tract with null values were not included in the sum.
181
+ RPL_CBM,Percentile ranks of the Climate Burden Module,In Excel: PERCENTRANK.INC on SPL_CBM array with 4 significant digits,Null values removed before calculating output rank.
182
+ AFAM,"Adjunct variable - Black and African American, Not Hispanic or Latino persons estimate",DP05_0080E,No Value
183
+ E_AFAM,"Adjunct variable - Percentage of Black and African American, Not Hispanic or Latino persons estimate",DP05_0080PE,No Value
184
+ AIAN,"Adjunct variable - American Indian and Alaska Native, Not Hispanic or Latino Persons estimate",DP05_0081E,No Value
185
+ E_AIAN,"Adjunct variable - Percentage of American Indian and Alaska Native, Not Hispanic or Latino Persons estimate",DP05_0081PE,No Value
186
+ ASIAN,"Adjunct variable - Asian, Not Hispanic or Latino Persons estimate",DP05_0082E,No Value
187
+ E_ASIAN,"Adjunct variable - Percentage of Asian, Not Hispanic or Latino Persons estimate",DP05_0082PE,No Value
188
+ HISP,Adjunct variable - Hispanic or Latino (of any race) Persons estimate,DP05_0073E,No Value
189
+ E_HISP,Adjunct variable - Percentage of Hispanic or Latino (of any race) Persons estimate,DP05_0073PE,No Value
190
+ NHPI,"Adjunct variable - Native Hawaiian and Other Pacific Islander, Not Hispanic or Latino Persons estimate",DP05_0083E,No Value
191
+ E_NHPI,"Adjunct variable - Percentage of Native Hawaiian and Other Pacific Islander, Not Hispanic or Latino Persons estimate",DP05_0083PE,No Value
192
+ OTHERRACE,"Adjunct variable - Other Races, Not Hispanic or Latino Persons estimate",DP05_0084E,No Value
193
+ E_OTHERRACE,"Adjunct variable - Percentage of Other Races, Not Hispanic or Latino Persons estimate",DP05_0084PE,No Value
194
+ TWOMORE,"Adjunct variable - Two or More Races, Not Hispanic or Latino Persons estimate",DP05_0085E,No Value
195
+ E_TWOMORE,"Adjunct variable - Percentage of Two or More Races, Not Hispanic or Latino Persons estimate",DP05_0085PE,No Value
196
+ Tribe_PCT_Tract,Percent of census tract that intersects with Tribal land,No Value,"Sum of the geographical intersections of Tribal land per census tract.
197
+ All Tribal lands are used in caluclation (including non-federally recognized tribal lands)."
198
+ Tribe_Names,Concatenation of Tribal land names that intersect with the census tract,No Value,No Value
199
+ Tribe_Flag,Flag to denote if Tribal Lands belong to Federally Recognized Tribes,"
200
+ If AINNHR = F and MTFCC =! G2160, then Tribal_Flag = 1 to denote Tribal Lands are federally recognized.
201
+ All others receive a flag of 0.","If the sum of Tribal lands for a tract includes at least 1 federally recognized Tribe, the tract will receive a flag of 1, even if there are also non-federally regognized Tribes in the tract as well."
data/default_dictionaries/SVI2022Documentation.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4cf98150bb26f993d10857b4891ea280380f43515956d66579b61956424c1d5
3
+ size 542662
data/user_uploads/.gitkeep ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file is intentionally left blank.
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ openai
4
+ PyPDF2
5
+ python-dotenv
6
+ streamlit-chat
7
+ requests
8
+ openpyxl
setup.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="streamlit-data-dictionary-chatbot",
5
+ version="0.1.0",
6
+ author="Your Name",
7
+ author_email="your.email@example.com",
8
+ description="A Streamlit application for analyzing data dictionaries with a chatbot interface.",
9
+ packages=find_packages(where="src"),
10
+ package_dir={"": "src"},
11
+ install_requires=[
12
+ "streamlit",
13
+ "pandas",
14
+ "PyPDF2",
15
+ "openai",
16
+ "python-dotenv"
17
+ ],
18
+ entry_points={
19
+ "console_scripts": [
20
+ "run-app=app:main",
21
+ ],
22
+ },
23
+ classifiers=[
24
+ "Programming Language :: Python :: 3",
25
+ "Framework :: Streamlit",
26
+ "License :: OSI Approved :: MIT License",
27
+ "Operating System :: OS Independent",
28
+ ],
29
+ python_requires='>=3.6',
30
+ )
src/app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from components.chat_interface import ChatInterface
3
+ from components.file_uploader import FileUploader
4
+ from components.sidebar import Sidebar
5
+ from services.data_dictionary_service import DataDictionaryService
6
+
7
+ def main():
8
+ st.set_page_config(page_title="Data Dictionary Chatbot", layout="wide")
9
+
10
+ # Initialize session state
11
+ if 'current_view' not in st.session_state:
12
+ st.session_state.current_view = "Chat"
13
+
14
+ # Initialize services
15
+ data_service = DataDictionaryService()
16
+
17
+ # Auto-load default dictionaries on startup
18
+ if 'dictionaries_loaded' not in st.session_state:
19
+ with st.spinner("Loading default data dictionaries..."):
20
+ default_count = data_service.load_default_dictionaries()
21
+ user_count = data_service.load_user_dictionaries()
22
+ st.session_state.dictionaries_loaded = True
23
+ st.session_state.data_service = data_service
24
+
25
+ # Show success message
26
+ total = default_count + user_count
27
+ if total > 0:
28
+ st.success(f"✅ Successfully loaded {total} data dictionar{'y' if total == 1 else 'ies'} ({default_count} default, {user_count} user-uploaded)")
29
+ else:
30
+ st.info("ℹ️ No data dictionaries found. You can upload your own using the uploader below.")
31
+ else:
32
+ data_service = st.session_state.data_service
33
+
34
+ # Sidebar for navigation
35
+ sidebar = Sidebar(data_service)
36
+ current_view = sidebar.display()
37
+
38
+ # Main content area
39
+ st.title("Data Dictionary Chatbot")
40
+
41
+ # Display content based on current view
42
+ if current_view == "Chat":
43
+ # Chat interface component
44
+ chat_interface = ChatInterface(data_service)
45
+ chat_interface.display()
46
+
47
+ elif current_view == "Manage Dictionaries":
48
+ st.header("Manage Data Dictionaries")
49
+ # File uploader component
50
+ file_uploader = FileUploader(data_service)
51
+ file_uploader.display()
52
+
53
+ # Display existing dictionaries
54
+ st.subheader("Existing Dictionaries")
55
+ dictionaries = data_service.get_all_dictionaries()
56
+
57
+ if dictionaries:
58
+ for dict_info in dictionaries:
59
+ with st.expander(f"📄 {dict_info['name']}"):
60
+ st.write(f"Type: {dict_info.get('type', 'Unknown')}")
61
+ st.write(f"Status: {'Active' if dict_info.get('active', True) else 'Inactive'}")
62
+ if dict_info.get('type') == 'user':
63
+ if st.button("Delete", key=f"del_{dict_info['name']}"):
64
+ data_service.delete_dictionary(dict_info['name'])
65
+ st.rerun()
66
+ else:
67
+ st.info("No dictionaries available. Upload some using the form above.")
68
+
69
+ else: # About view
70
+ st.header("About This Application")
71
+ st.markdown("""
72
+ This chatbot application helps you analyze data dictionaries and find relevant columns
73
+ for your machine learning use cases.
74
+
75
+ ### Features
76
+ - Upload and manage data dictionaries (PDF, Excel, CSV)
77
+ - AI-powered column suggestions
78
+ - Interactive chat interface
79
+ - Support for multiple dictionaries
80
+
81
+ ### How to Use
82
+ 1. Upload your data dictionaries using the 'Manage Dictionaries' view
83
+ 2. Switch to the 'Chat' view
84
+ 3. Describe your use case to get relevant column suggestions
85
+ 4. Use the sidebar to enable/disable specific dictionaries
86
+
87
+ ### Supported File Types
88
+ - PDF (.pdf)
89
+ - Excel (.xlsx, .xls)
90
+ - CSV (.csv)
91
+ """)
92
+
93
+ if __name__ == "__main__":
94
+ main()
src/components/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file is intentionally left blank.
src/components/chat_interface.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ # Configure logger for chat interface
4
+ logger = logging.getLogger("chat_interface")
5
+ if not logger.hasHandlers():
6
+ logging.basicConfig(level=logging.INFO)
7
+ logger.setLevel(logging.INFO)
8
+ import streamlit as st
9
+ from services.azure_openai_service import AzureOpenAIService
10
+ from services.data_dictionary_service import DataDictionaryService
11
+ from services.retrieval_service import RetrievalService, format_retrieved_chunks
12
+
13
+ class ChatInterface:
14
+ def __init__(self, data_dictionary_service=None):
15
+ try:
16
+ self.openai_service = AzureOpenAIService()
17
+ except ValueError as e:
18
+ st.error(f"Configuration Error: {str(e)}")
19
+ st.info("Please check your .env file and ensure all Azure OpenAI credentials are set correctly.")
20
+ self.openai_service = None
21
+
22
+ self.data_dictionary_service = data_dictionary_service or DataDictionaryService()
23
+ # Reuse retrieval service across reruns via session_state to avoid reloading cache repeatedly
24
+ if 'retrieval_service' not in st.session_state:
25
+ st.session_state.retrieval_service = RetrievalService(self.data_dictionary_service)
26
+ self.retrieval_service = st.session_state.retrieval_service
27
+
28
+ # Initialize session state for chat history if not exists
29
+ if 'chat_history' not in st.session_state:
30
+ st.session_state.chat_history = []
31
+
32
+ def display(self):
33
+ # Check if OpenAI service is configured
34
+ if not self.openai_service:
35
+ st.error("Azure OpenAI is not configured. Please set up your credentials in the sidebar.")
36
+ return
37
+
38
+ # Display active dictionaries info
39
+ active_dicts = [d for d in self.data_dictionary_service.get_all_dictionaries()
40
+ if d.get('active', True)]
41
+
42
+ if not active_dicts:
43
+ st.warning("No active data dictionaries. Please enable at least one dictionary in the sidebar.")
44
+ return
45
+
46
+ # Display chat interface
47
+ st.subheader("Chat with your Data Dictionaries")
48
+ st.markdown("Describe your use case or ask questions about the data dictionaries.")
49
+
50
+ st.write("Ask me anything about the data dictionaries!")
51
+ # Badge: Index ready indicator
52
+ try:
53
+ status = self.retrieval_service.get_cache_status()
54
+ ready_badge = "✅ Index ready" if status.get('chunks_indexed', 0) > 0 else "⌛ Building index on demand"
55
+ st.caption(ready_badge)
56
+ except Exception:
57
+ pass
58
+
59
+ # Check if OpenAI service is available
60
+ if self.openai_service is None:
61
+ st.error("⚠️ Azure OpenAI service is not configured. Please check your environment variables.")
62
+ return
63
+
64
+ # Display chat history from session state
65
+ for user_msg, bot_msg in st.session_state.chat_history:
66
+ with st.chat_message("user"):
67
+ st.write(user_msg)
68
+ with st.chat_message("assistant"):
69
+ st.write(bot_msg)
70
+
71
+ # User input
72
+ user_input = st.chat_input("Type your message here...")
73
+ if user_input:
74
+ logger.info(f"[ChatInterface] User input: {user_input}")
75
+ # Display user message immediately
76
+ with st.chat_message("user"):
77
+ st.write(user_input)
78
+ with st.chat_message("assistant"):
79
+ with st.spinner("Thinking..."):
80
+ try:
81
+ active_dicts = [d['name'] for d in self.data_dictionary_service.get_all_dictionaries() if d.get('active', True)]
82
+ # Do not force indexing here; retrieval_service.search() will decide
83
+ logger.info(f"[ChatInterface] Calling retrieval_service.search() with active_dicts: {active_dicts}")
84
+ # Use user-configured retrieval settings
85
+ top_k = st.session_state.get('retrieval_top_k', 25)
86
+ disable_embeddings = st.session_state.get('retrieval_disable_embeddings', False)
87
+ try:
88
+ k = int(top_k)
89
+ except Exception:
90
+ k = 25
91
+ retrieved = self.retrieval_service.search(user_input, active_dicts, top_k=k, disable_embeddings=disable_embeddings)
92
+ context = format_retrieved_chunks(retrieved)
93
+ if not context:
94
+ logger.info("[ChatInterface] Retrieval returned no context, falling back to _build_context_from_dictionaries.")
95
+ context = self._build_context_from_dictionaries()
96
+ self._show_trim_warning()
97
+ else:
98
+ logger.info(f"[ChatInterface] Retrieved context length: {len(context)}")
99
+ if context:
100
+ enhanced_prompt = f"""Available Data Dictionaries:\n\n{context}\n\nUser: {user_input}"""
101
+ else:
102
+ enhanced_prompt = user_input
103
+ logger.info(f"[ChatInterface] Sending prompt to OpenAI (length: {len(enhanced_prompt)})")
104
+ response = self.openai_service.generate_response(enhanced_prompt, st.session_state.chat_history)
105
+ bot_response = self.openai_service.parse_response(response)
106
+ logger.info(f"[ChatInterface] Received response from OpenAI (length: {len(bot_response)})")
107
+ st.write(bot_response)
108
+
109
+ # Optional debug: show retrieved snippets/context passed to the model
110
+ try:
111
+ context_source = "retrieval" if retrieved else "fallback"
112
+ with st.expander("Show retrieved snippets (debug)"):
113
+ st.caption(f"Source: {context_source} | top_k: {k} | embeddings: {'enabled' if not disable_embeddings else 'disabled'}")
114
+ st.code(context[:4000] + ("\n...[truncated]" if len(context) > 4000 else ""), language="markdown")
115
+ except Exception:
116
+ pass
117
+ st.session_state.chat_history.append((user_input, bot_response))
118
+ except Exception as e:
119
+ error_message = f"❌ Error: {str(e)}"
120
+ logger.error(f"[ChatInterface] Exception: {error_message}")
121
+ st.error(error_message)
122
+ st.session_state.chat_history.append((user_input, error_message))
123
+
124
+ def _build_context_from_dictionaries(self) -> str:
125
+ """Build context string from loaded data dictionaries.
126
+
127
+ Returns:
128
+ A formatted string containing dictionary information.
129
+ """
130
+ if not self.data_dictionary_service.data_dictionaries:
131
+ return ""
132
+
133
+ # Adaptive token budgeting: aim to stay below ~110k tokens for dictionaries
134
+ # leaving room for system prompt, chat history, and user message (model max ~128k)
135
+ TOKEN_BUDGET = 110_000
136
+ APPROX_CHAR_PER_TOKEN = 4 # rough heuristic
137
+ remaining_budget = TOKEN_BUDGET
138
+ assembled = []
139
+ trimmed_any = False
140
+
141
+ # Sort dictionaries by size (small first) to maximize inclusion
142
+ dict_items = sorted(self.data_dictionary_service.data_dictionaries.items(), key=lambda kv: len(kv[1]))
143
+ for dict_name, dict_content in dict_items:
144
+ dict_tokens_est = len(dict_content) / APPROX_CHAR_PER_TOKEN
145
+ header = f"\n### {dict_name}\n"
146
+ header_tokens_est = len(header) / APPROX_CHAR_PER_TOKEN
147
+ total_needed = dict_tokens_est + header_tokens_est
148
+ if total_needed <= remaining_budget:
149
+ assembled.append(f"{header}{dict_content}")
150
+ remaining_budget -= total_needed
151
+ else:
152
+ # Need to trim this dictionary's content to fit remaining budget if any left
153
+ if remaining_budget > header_tokens_est + 50: # ensure at least some content
154
+ allowed_tokens = remaining_budget - header_tokens_est
155
+ allowed_chars = int(allowed_tokens * APPROX_CHAR_PER_TOKEN)
156
+ trimmed_content = dict_content[:allowed_chars]
157
+ assembled.append(f"{header}{trimmed_content}\n...[TRIMMED due to context budget]\n")
158
+ remaining_budget = 0
159
+ trimmed_any = True
160
+ else:
161
+ trimmed_any = True
162
+ break # no more room for additional dictionaries
163
+
164
+ context_str = "".join(assembled)
165
+ if trimmed_any:
166
+ # Store a flag in session to optionally show a warning in UI layer
167
+ st.session_state['_dict_trimmed'] = True
168
+ else:
169
+ st.session_state['_dict_trimmed'] = False
170
+ return context_str
171
+
172
+ def _show_trim_warning(self):
173
+ if st.session_state.get('_dict_trimmed'):
174
+ st.warning("Some data dictionaries were partially included due to model context limits. Consider enabling fewer dictionaries or implementing retrieval for more precise results.")
175
+
176
+ def reset_chat(self):
177
+ if st.button("Reset Chat"):
178
+ st.session_state.chat_history = []
179
+ st.rerun()
src/components/file_uploader.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+
4
+ class FileUploader:
5
+ def __init__(self, data_service=None):
6
+ self.data_service = data_service
7
+
8
+ def display(self):
9
+ st.header("Upload Your Data Dictionary")
10
+
11
+ uploaded_file = st.file_uploader("Choose a file", type=["pdf", "xlsx", "xls", "csv"])
12
+
13
+ if uploaded_file is not None:
14
+ # Save the uploaded file to the user_uploads directory
15
+ user_uploads_dir = "data/user_uploads"
16
+ os.makedirs(user_uploads_dir, exist_ok=True)
17
+ file_path = os.path.join(user_uploads_dir, uploaded_file.name)
18
+
19
+ with open(file_path, "wb") as f:
20
+ f.write(uploaded_file.getbuffer())
21
+
22
+ st.success(f"✅ File '{uploaded_file.name}' uploaded successfully!")
23
+
24
+ # Reload user dictionaries if data_service is available
25
+ if self.data_service:
26
+ with st.spinner("Processing uploaded file..."):
27
+ loaded = self.data_service.load_user_dictionaries()
28
+ st.info(f"📚 Reloaded {loaded} user-uploaded dictionar{'y' if loaded == 1 else 'ies'}")
29
+ # Update session state to trigger UI refresh
30
+ if 'data_service' in st.session_state:
31
+ st.session_state.data_service = self.data_service
32
+
33
+ st.info("📁 Supported formats: PDF, Excel (XLSX, XLS), CSV")
src/components/sidebar.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ class Sidebar:
4
+ def __init__(self, data_service=None):
5
+ self.data_service = data_service
6
+
7
+ def display(self):
8
+ st.sidebar.title("Data Dictionary Chatbot")
9
+
10
+ # Show loaded dictionaries
11
+ if self.data_service:
12
+ num_dicts = len(self.data_service.data_dictionaries)
13
+ st.sidebar.metric("Loaded Dictionaries", num_dicts)
14
+
15
+ if num_dicts > 0:
16
+ st.sidebar.subheader("Available Dictionaries")
17
+ for dict_name in self.data_service.data_dictionaries.keys():
18
+ st.sidebar.text(f"📄 {dict_name}")
19
+
20
+ st.sidebar.header("Navigation")
21
+
22
+ # Define navigation options that map to actual views
23
+ nav_options = {
24
+ "💬 Chat": "Chat",
25
+ "📤 Upload Data Dictionary": "Manage Dictionaries",
26
+ "ℹ️ About": "About"
27
+ }
28
+
29
+ # Get current view or default to Chat
30
+ current_view = st.session_state.get('current_view', 'Chat')
31
+
32
+ # Find the current option label based on the view
33
+ current_option = None
34
+ for label, view in nav_options.items():
35
+ if view == current_view:
36
+ current_option = label
37
+ break
38
+
39
+ # Create radio buttons with proper default
40
+ option_labels = list(nav_options.keys())
41
+ default_index = option_labels.index(current_option) if current_option else 0
42
+
43
+ selected_option = st.sidebar.radio(
44
+ "Select an option:",
45
+ option_labels,
46
+ index=default_index
47
+ )
48
+
49
+ # Update the session state based on selection
50
+ selected_view = nav_options[selected_option]
51
+ if st.session_state.get('current_view') != selected_view:
52
+ st.session_state.current_view = selected_view
53
+ st.rerun()
54
+
55
+ # Retrieval / Cache Status Section
56
+ retrieval = st.session_state.get('retrieval_service')
57
+ st.sidebar.markdown("---")
58
+ st.sidebar.subheader("Retrieval / Cache Status")
59
+ if retrieval:
60
+ status = retrieval.get_cache_status()
61
+ col1, col2 = st.sidebar.columns(2)
62
+ col1.metric("Chunks", status['chunks_indexed'])
63
+ col2.metric("Embeddings", status['embeddings_cached'])
64
+ st.sidebar.caption(f"Embeddings Enabled: {'✅' if status['embeddings_enabled'] else '❌'}")
65
+ st.sidebar.caption(f"Corpus Sig: `{status['corpus_sig']}`")
66
+ # Controls
67
+ st.sidebar.subheader("Retrieval Settings")
68
+ top_k = st.sidebar.slider("Top-k retrieved", min_value=5, max_value=50, value=25, step=5, help="How many relevant snippets to retrieve")
69
+ disable_embeddings = st.sidebar.checkbox("Disable embeddings (lexical only)", value=False, help="Speeds up retrieval, less semantic accuracy")
70
+ st.session_state['retrieval_top_k'] = top_k
71
+ st.session_state['retrieval_disable_embeddings'] = disable_embeddings
72
+ if st.sidebar.button("Clear Retrieval Cache"):
73
+ retrieval.clear_cache()
74
+ st.sidebar.info("Cache cleared. It will rebuild on next data query.")
75
+ st.rerun()
76
+ if st.sidebar.button("Force Reindex"):
77
+ retrieval.index()
78
+ st.sidebar.success("Reindex complete.")
79
+ st.rerun()
80
+ else:
81
+ st.sidebar.caption("Retrieval service not initialized yet.")
82
+
83
+ return selected_view
src/config.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ class Config:
4
+ """Configuration settings for the Streamlit Data Dictionary Chatbot application."""
5
+
6
+ # Azure OpenAI configuration
7
+ AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT", "https://your-resource.openai.azure.com/")
8
+ AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY", "your-api-key")
9
+ AZURE_OPENAI_DEPLOYMENT = os.getenv("AZURE_OPENAI_DEPLOYMENT", "gpt-4")
10
+ API_VERSION = os.getenv("AZURE_OPENAI_API_VERSION", "2024-02-15-preview")
11
+
12
+ # File upload settings
13
+ ALLOWED_FILE_TYPES = {'pdf', 'xlsx', 'xls', 'csv'}
14
+
15
+ # Default data dictionary path
16
+ DEFAULT_DICTIONARY_PATH = os.path.join("data", "default_dictionaries")
17
+
18
+ # User uploads path
19
+ USER_UPLOADS_PATH = os.path.join("data", "user_uploads")
src/services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file is intentionally left blank.
src/services/azure_openai_service.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Azure OpenAI Service for Streamlit Data Dictionary Chatbot
3
+
4
+ This module contains the logic for interacting with the Azure OpenAI API,
5
+ including sending requests and receiving responses for the chatbot functionality.
6
+ """
7
+
8
+ import os
9
+ import json
10
+ import requests
11
+ from dotenv import load_dotenv
12
+
13
+ # Load environment variables
14
+ load_dotenv()
15
+
16
+ class AzureOpenAIService:
17
+ def __init__(self):
18
+ self.endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
19
+ self.api_key = os.getenv("AZURE_OPENAI_API_KEY")
20
+ self.deployment_name = os.getenv("AZURE_OPENAI_DEPLOYMENT")
21
+ self.api_version = os.getenv("AZURE_OPENAI_API_VERSION", "2024-02-15-preview")
22
+
23
+ # Validate required environment variables
24
+ if not self.endpoint:
25
+ raise ValueError("AZURE_OPENAI_ENDPOINT is not set in environment variables")
26
+ if not self.api_key:
27
+ raise ValueError("AZURE_OPENAI_API_KEY is not set in environment variables")
28
+ if not self.deployment_name:
29
+ raise ValueError("AZURE_OPENAI_DEPLOYMENT is not set in environment variables")
30
+
31
+ # Remove trailing slash from endpoint if present
32
+ self.endpoint = self.endpoint.rstrip('/')
33
+
34
+ def generate_response(self, prompt: str, chat_history: list = None) -> dict:
35
+ """Generate a response from Azure OpenAI API.
36
+
37
+ Args:
38
+ prompt: The user's input prompt
39
+ chat_history: List of tuples containing (user_message, assistant_message) from previous conversation
40
+
41
+ Returns:
42
+ The API response as a dictionary
43
+ """
44
+ if not prompt or not prompt.strip():
45
+ raise ValueError("Prompt cannot be empty")
46
+
47
+ headers = {
48
+ "Content-Type": "application/json",
49
+ "api-key": self.api_key
50
+ }
51
+
52
+ # Build messages array with chat history
53
+ messages = [
54
+ {"role": "system", "content": """You are a friendly and helpful data science assistant with expertise in data dictionaries, health data analysis, and machine learning.
55
+
56
+ Your role is to:
57
+ - Have natural, conversational interactions with users
58
+ - Answer questions about data dictionaries in a helpful, approachable manner
59
+ - Provide detailed column recommendations when asked about specific use cases
60
+ - Answer deep-dive questions about specific columns (data types, examples, usage, relationships)
61
+ - Respond warmly to greetings, thanks, and casual conversation
62
+ - Be flexible in your responses - sometimes users need structured analysis, sometimes just a quick answer
63
+ - Use a professional yet friendly tone
64
+ - Ask clarifying questions when the user's request is ambiguous or could benefit from more context
65
+
66
+ When users ask for dataset/column recommendations:
67
+ - ALWAYS cite the dataset source for each column (e.g., "Dataset: EJI_DATADICTIONARY")
68
+ - Group recommendations by dataset when multiple datasets are referenced
69
+ - Format as: **Column Name** (Dataset: DatasetName) - description and relevance
70
+ - Include column names, descriptions, relevance reasons, and priority levels
71
+ - Format clearly with headers and bullet points
72
+ - Never mention a column without specifying which dataset it comes from
73
+
74
+ When users ask about a specific column in detail:
75
+ - Provide comprehensive information from the data dictionary
76
+ - Include: full description, data type, valid values/ranges, units, notes
77
+ - Explain common use cases and how it relates to other columns
78
+ - Suggest related columns that might be useful
79
+ - ALWAYS specify which dataset the column comes from
80
+
81
+ When users ask vague or broad questions:
82
+ - Ask for clarification (e.g., "Which dataset are you interested in?" or "Are you looking for demographic, environmental, or health-related columns?")
83
+ - Offer to narrow down the scope
84
+ - Suggest categories or themes they might explore
85
+
86
+ When users engage casually (greetings, thanks, follow-ups):
87
+ - Respond naturally and warmly
88
+ - Keep it brief and friendly
89
+ - Stay helpful and ready to assist further
90
+
91
+ Be adaptive, conversational, and proactive in helping users find exactly what they need."""}
92
+ ]
93
+
94
+ # Add chat history if provided (keep last 10 exchanges to avoid token limits)
95
+ if chat_history:
96
+ # Limit to last 10 exchanges to manage token usage
97
+ recent_history = chat_history[-10:] if len(chat_history) > 10 else chat_history
98
+ for user_msg, assistant_msg in recent_history:
99
+ messages.append({"role": "user", "content": user_msg})
100
+ messages.append({"role": "assistant", "content": assistant_msg})
101
+
102
+ # Add current prompt
103
+ messages.append({"role": "user", "content": prompt})
104
+
105
+ data = {
106
+ "messages": messages,
107
+ "temperature": 0.5,
108
+ "max_tokens": 8000
109
+ }
110
+
111
+ # Correct Azure OpenAI endpoint format
112
+ url = f"{self.endpoint}/openai/deployments/{self.deployment_name}/chat/completions?api-version={self.api_version}"
113
+
114
+ try:
115
+ response = requests.post(url, headers=headers, json=data, timeout=30)
116
+
117
+ if response.status_code == 200:
118
+ return response.json()
119
+ else:
120
+ error_msg = f"Azure OpenAI API Error {response.status_code}: {response.text}"
121
+ raise Exception(error_msg)
122
+ except requests.exceptions.Timeout:
123
+ raise Exception("Request timed out. Please try again.")
124
+ except requests.exceptions.RequestException as e:
125
+ raise Exception(f"Request failed: {str(e)}")
126
+
127
+ def parse_response(self, response: dict) -> str:
128
+ if "choices" in response and len(response["choices"]) > 0:
129
+ return response["choices"][0]["message"]["content"]
130
+ return "No response from the model."
src/services/cache_service.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """cache_service.py
2
+ Simple JSON-based cache utilities for retrieval index and embeddings.
3
+ """
4
+ from __future__ import annotations
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any, Optional
8
+
9
+ DEFAULT_CACHE_DIR = ".cache"
10
+
11
+ def ensure_cache_dir(cache_dir: str = DEFAULT_CACHE_DIR) -> Path:
12
+ p = Path(cache_dir)
13
+ p.mkdir(parents=True, exist_ok=True)
14
+ return p
15
+
16
+ def load_json(path: Path) -> Optional[Any]:
17
+ try:
18
+ if path.exists():
19
+ with path.open("r", encoding="utf-8") as f:
20
+ return json.load(f)
21
+ except Exception:
22
+ return None
23
+ return None
24
+
25
+ def save_json(path: Path, data: Any) -> bool:
26
+ try:
27
+ path.parent.mkdir(parents=True, exist_ok=True)
28
+ with path.open("w", encoding="utf-8") as f:
29
+ json.dump(data, f)
30
+ return True
31
+ except Exception:
32
+ return False
src/services/data_dictionary_service.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ data_dictionary_service.py
3
+
4
+ This file manages the loading and processing of both default and user-uploaded data dictionaries,
5
+ providing methods to retrieve and analyze the data.
6
+ """
7
+
8
+ import os
9
+ import json
10
+ from pathlib import Path
11
+ import pandas as pd
12
+ import PyPDF2
13
+
14
+ class DataDictionaryService:
15
+ """Service for managing data dictionaries."""
16
+
17
+ def __init__(self, default_dict_path: str = "data/default_dictionaries", user_upload_path: str = "data/user_uploads"):
18
+ """
19
+ Initialize the DataDictionaryService with paths for default and user-uploaded dictionaries.
20
+
21
+ Args:
22
+ default_dict_path: Path to the default data dictionaries directory.
23
+ user_upload_path: Path to the user-uploaded data dictionaries directory.
24
+ """
25
+ self.default_dict_path = Path(default_dict_path)
26
+ self.user_upload_path = Path(user_upload_path)
27
+ self.data_dictionaries = {}
28
+ self.active_status = {} # Track which dictionaries are active
29
+
30
+ # Create directories if they don't exist
31
+ self.default_dict_path.mkdir(parents=True, exist_ok=True)
32
+ self.user_upload_path.mkdir(parents=True, exist_ok=True)
33
+
34
+ # Load dictionaries on initialization
35
+ self.load_all_dictionaries()
36
+
37
+ def load_all_dictionaries(self):
38
+ """Load both default and user dictionaries."""
39
+ self.load_default_dictionaries()
40
+ self.load_user_dictionaries()
41
+
42
+ def get_all_dictionaries(self):
43
+ """
44
+ Get information about all available dictionaries.
45
+
46
+ Returns:
47
+ List of dictionaries with information about each data dictionary
48
+ """
49
+ all_dicts = []
50
+
51
+ # Add default dictionaries
52
+ for name, content in self.data_dictionaries.items():
53
+ dict_info = {
54
+ 'name': name,
55
+ 'type': 'default' if Path(name).parent == self.default_dict_path else 'user',
56
+ 'active': self.active_status.get(name, True),
57
+ 'size': len(content) if content else 0
58
+ }
59
+ all_dicts.append(dict_info)
60
+
61
+ return all_dicts
62
+
63
+ def set_dictionary_active(self, dict_name: str, active: bool):
64
+ """
65
+ Set whether a dictionary is active or not.
66
+
67
+ Args:
68
+ dict_name: Name of the dictionary
69
+ active: Whether the dictionary should be active
70
+ """
71
+ self.active_status[dict_name] = active
72
+
73
+ def get_active_dictionaries(self):
74
+ """
75
+ Get only the active dictionaries.
76
+
77
+ Returns:
78
+ Dictionary containing only active data dictionaries
79
+ """
80
+ return {name: content for name, content in self.data_dictionaries.items()
81
+ if self.active_status.get(name, True)}
82
+
83
+ def load_default_dictionaries(self):
84
+ """
85
+ Load dictionaries from the default directory.
86
+
87
+ Returns:
88
+ Number of dictionaries loaded
89
+ """
90
+ count = 0
91
+ for file_path in self.default_dict_path.glob("*.*"):
92
+ if file_path.suffix.lower() in ['.pdf', '.xlsx', '.xls', '.csv']:
93
+ content = self._load_file(file_path)
94
+ if content:
95
+ self.data_dictionaries[str(file_path)] = content
96
+ self.active_status[str(file_path)] = True
97
+ count += 1
98
+ return count
99
+
100
+ def load_user_dictionaries(self):
101
+ """
102
+ Load dictionaries from the user uploads directory.
103
+
104
+ Returns:
105
+ Number of dictionaries loaded
106
+ """
107
+ count = 0
108
+ for file_path in self.user_upload_path.glob("*.*"):
109
+ if file_path.suffix.lower() in ['.pdf', '.xlsx', '.xls', '.csv']:
110
+ content = self._load_file(file_path)
111
+ if content:
112
+ self.data_dictionaries[str(file_path)] = content
113
+ self.active_status[str(file_path)] = True
114
+ count += 1
115
+ return count
116
+
117
+ def _load_file(self, file_path: Path) -> str:
118
+ """
119
+ Load content from a file based on its type.
120
+
121
+ Args:
122
+ file_path: Path to the file
123
+
124
+ Returns:
125
+ String content of the file
126
+ """
127
+ try:
128
+ if file_path.suffix.lower() == '.pdf':
129
+ return self._load_pdf(file_path)
130
+ elif file_path.suffix.lower() in ['.xlsx', '.xls']:
131
+ return self._load_excel(file_path)
132
+ elif file_path.suffix.lower() == '.csv':
133
+ return self._load_csv(file_path)
134
+ except Exception as e:
135
+ print(f"Error loading {file_path}: {str(e)}")
136
+ return None
137
+
138
+ def _load_pdf(self, file_path: Path) -> str:
139
+ """Load content from a PDF file."""
140
+ with open(file_path, 'rb') as file:
141
+ reader = PyPDF2.PdfReader(file)
142
+ text = ""
143
+ for page in reader.pages:
144
+ text += page.extract_text() + "\n"
145
+ return text
146
+
147
+ def _load_excel(self, file_path: Path) -> str:
148
+ """Load content from an Excel file."""
149
+ df = pd.read_excel(file_path)
150
+ return df.to_string()
151
+
152
+ def _load_csv(self, file_path: Path) -> str:
153
+ """Load content from a CSV file."""
154
+ df = pd.read_csv(file_path)
155
+ return df.to_string()
156
+
157
+ def save_uploaded_file(self, uploaded_file) -> dict:
158
+ """
159
+ Save an uploaded file and load it into the service.
160
+
161
+ Args:
162
+ uploaded_file: Streamlit UploadedFile object
163
+
164
+ Returns:
165
+ Dictionary with status information
166
+ """
167
+ try:
168
+ # Create save path
169
+ save_path = self.user_upload_path / uploaded_file.name
170
+
171
+ # Save file
172
+ with open(save_path, "wb") as f:
173
+ f.write(uploaded_file.getbuffer())
174
+
175
+ # Load the file into the service
176
+ content = self._load_file(save_path)
177
+ if content:
178
+ self.data_dictionaries[str(save_path)] = content
179
+ self.active_status[str(save_path)] = True
180
+ return {
181
+ "success": True,
182
+ "message": f"Successfully uploaded and loaded {uploaded_file.name}"
183
+ }
184
+ else:
185
+ return {
186
+ "success": False,
187
+ "message": f"Failed to load {uploaded_file.name}"
188
+ }
189
+
190
+ except Exception as e:
191
+ return {
192
+ "success": False,
193
+ "message": f"Error saving file: {str(e)}"
194
+ }
195
+
196
+ def delete_dictionary(self, dict_name: str) -> dict:
197
+ """
198
+ Delete a dictionary file and remove it from the service.
199
+
200
+ Args:
201
+ dict_name: Name of the dictionary to delete
202
+
203
+ Returns:
204
+ Dictionary with status information
205
+ """
206
+ try:
207
+ # Find the full path
208
+ full_path = None
209
+ for path in self.data_dictionaries.keys():
210
+ if dict_name in path:
211
+ full_path = Path(path)
212
+ break
213
+
214
+ if not full_path:
215
+ return {
216
+ "success": False,
217
+ "message": f"Dictionary {dict_name} not found"
218
+ }
219
+
220
+ # Only allow deleting user uploads
221
+ if self.user_upload_path not in full_path.parents:
222
+ return {
223
+ "success": False,
224
+ "message": "Can only delete user-uploaded dictionaries"
225
+ }
226
+
227
+ # Delete file
228
+ if full_path.exists():
229
+ full_path.unlink()
230
+
231
+ # Remove from service
232
+ if str(full_path) in self.data_dictionaries:
233
+ del self.data_dictionaries[str(full_path)]
234
+ if str(full_path) in self.active_status:
235
+ del self.active_status[str(full_path)]
236
+
237
+ return {
238
+ "success": True,
239
+ "message": f"Successfully deleted {dict_name}"
240
+ }
241
+
242
+ except Exception as e:
243
+ return {
244
+ "success": False,
245
+ "message": f"Error deleting dictionary: {str(e)}"
246
+ }
247
+ self.user_upload_path.mkdir(parents=True, exist_ok=True)
248
+
249
+ def load_default_dictionaries(self):
250
+ """Load default data dictionaries from the specified directory."""
251
+ loaded_count = 0
252
+ for file in self.default_dict_path.glob('*'):
253
+ if file.suffix in ['.pdf', '.xlsx', '.xls', '.csv']:
254
+ content = self.extract_data(file)
255
+ if content:
256
+ self.data_dictionaries[file.stem] = content
257
+ loaded_count += 1
258
+ return loaded_count
259
+
260
+ def load_user_dictionaries(self):
261
+ """Load user-uploaded data dictionaries from the specified directory."""
262
+ loaded_count = 0
263
+ for file in self.user_upload_path.glob('*'):
264
+ if file.suffix in ['.pdf', '.xlsx', '.xls', '.csv']:
265
+ content = self.extract_data(file)
266
+ if content:
267
+ self.data_dictionaries[file.stem] = content
268
+ loaded_count += 1
269
+ return loaded_count
270
+
271
+ def extract_data(self, file_path: Path) -> str:
272
+ """Extract data from a given file based on its type.
273
+
274
+ Args:
275
+ file_path: Path to the file to extract data from.
276
+
277
+ Returns:
278
+ Extracted data as a string.
279
+ """
280
+ if file_path.suffix == '.pdf':
281
+ return self.extract_text_from_pdf(file_path)
282
+ elif file_path.suffix in ['.xlsx', '.xls']:
283
+ return self.extract_data_from_excel(file_path)
284
+ elif file_path.suffix == '.csv':
285
+ return self.extract_data_from_csv(file_path)
286
+ return ""
287
+
288
+ def extract_text_from_pdf(self, pdf_path: Path) -> str:
289
+ """Extract text content from a PDF file.
290
+
291
+ Args:
292
+ pdf_path: Path to the PDF file.
293
+
294
+ Returns:
295
+ Extracted text content.
296
+ """
297
+ text = ""
298
+ try:
299
+ with open(pdf_path, 'rb') as file:
300
+ pdf_reader = PyPDF2.PdfReader(file)
301
+ for page in pdf_reader.pages:
302
+ text += page.extract_text() + "\n"
303
+ return text
304
+ except Exception as e:
305
+ print(f"Error reading PDF {pdf_path}: {str(e)}")
306
+ return ""
307
+
308
+ def extract_data_from_excel(self, excel_path: Path) -> str:
309
+ """Extract data from an Excel file.
310
+
311
+ Args:
312
+ excel_path: Path to the Excel file.
313
+
314
+ Returns:
315
+ Text representation of the Excel data.
316
+ """
317
+ text = ""
318
+ try:
319
+ excel_file = pd.ExcelFile(excel_path)
320
+ for sheet_name in excel_file.sheet_names:
321
+ df = pd.read_excel(excel_path, sheet_name=sheet_name)
322
+ text += f"\n--- Sheet: {sheet_name} ---\n"
323
+ text += df.to_string(index=False) + "\n"
324
+ return text
325
+ except Exception as e:
326
+ print(f"Error reading Excel {excel_path}: {str(e)}")
327
+ return ""
328
+
329
+ def extract_data_from_csv(self, csv_path: Path) -> str:
330
+ """Extract data from a CSV file.
331
+
332
+ Args:
333
+ csv_path: Path to the CSV file.
334
+
335
+ Returns:
336
+ Text representation of the CSV data.
337
+ """
338
+ try:
339
+ df = pd.read_csv(csv_path)
340
+ return df.to_string(index=False)
341
+ except Exception as e:
342
+ print(f"Error reading CSV {csv_path}: {str(e)}")
343
+ return ""
344
+
345
+ def get_data_dictionaries(self) -> dict:
346
+ """Return the loaded data dictionaries.
347
+
348
+ Returns:
349
+ A dictionary containing all loaded data dictionaries.
350
+ """
351
+ return self.data_dictionaries
src/services/file_parser_service.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File Parser Service for Streamlit Data Dictionary Chatbot
3
+
4
+ This service handles the parsing of uploaded files, extracting relevant information
5
+ from various formats (e.g., PDF, Excel) to be used in the application.
6
+ """
7
+
8
+ import os
9
+ import pandas as pd
10
+ import PyPDF2
11
+ from typing import Union, Dict, Any
12
+
13
+ class FileParserService:
14
+ """Service for parsing uploaded data dictionary files."""
15
+
16
+ @staticmethod
17
+ def extract_text_from_pdf(pdf_path: str) -> str:
18
+ """Extract text content from a PDF file."""
19
+ text = ""
20
+ try:
21
+ with open(pdf_path, 'rb') as file:
22
+ pdf_reader = PyPDF2.PdfReader(file)
23
+ for page in pdf_reader.pages:
24
+ text += page.extract_text() + "\n"
25
+ return text
26
+ except Exception as e:
27
+ raise ValueError(f"Error reading PDF {pdf_path}: {str(e)}")
28
+
29
+ @staticmethod
30
+ def extract_data_from_excel(excel_path: str) -> Dict[str, Any]:
31
+ """Extract data from an Excel file and return as a dictionary."""
32
+ data = {}
33
+ try:
34
+ excel_file = pd.ExcelFile(excel_path)
35
+ for sheet_name in excel_file.sheet_names:
36
+ df = pd.read_excel(excel_path, sheet_name=sheet_name)
37
+ data[sheet_name] = df.to_dict(orient='records')
38
+ return data
39
+ except Exception as e:
40
+ raise ValueError(f"Error reading Excel {excel_path}: {str(e)}")
41
+
42
+ @staticmethod
43
+ def parse_file(file_path: str) -> Union[str, Dict[str, Any]]:
44
+ """Parse the uploaded file based on its extension."""
45
+ _, file_extension = os.path.splitext(file_path)
46
+ file_extension = file_extension.lower()
47
+
48
+ if file_extension == '.pdf':
49
+ return FileParserService.extract_text_from_pdf(file_path)
50
+ elif file_extension in ['.xlsx', '.xls']:
51
+ return FileParserService.extract_data_from_excel(file_path)
52
+ else:
53
+ raise ValueError(f"Unsupported file format: {file_extension}")
src/services/retrieval_service.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import logging
3
+
4
+ # Configure logger for retrieval service
5
+ logger = logging.getLogger("retrieval_service")
6
+ if not logger.hasHandlers():
7
+ logging.basicConfig(level=logging.INFO)
8
+ logger.setLevel(logging.INFO)
9
+ """retrieval_service.py
10
+
11
+ Lightweight retrieval (RAG) helper for the data dictionary chatbot.
12
+
13
+ Goals:
14
+ - Avoid passing entire dictionaries to the LLM by selecting only relevant chunks.
15
+ - Provide drill-down capability for individual columns or lines.
16
+ - Be resilient when embeddings are not configured (fallback to keyword scoring).
17
+
18
+ Design:
19
+ - Chunks are simple dicts: {"id", "text", "dataset", "score", "meta"}
20
+ - Build chunks by splitting dictionary content into non-empty lines; future improvement: structured CSV parsing.
21
+ - Search uses one of:
22
+ 1. Embeddings (if AZURE_OPENAI_EMBEDDING_DEPLOYMENT is set) -> cosine similarity
23
+ 2. Fallback lexical scoring: token overlap + SequenceMatcher ratio.
24
+
25
+ This avoids adding heavy external dependencies (FAISS/Chroma). Can be swapped out later.
26
+ """
27
+
28
+ import os
29
+ import math
30
+ import json
31
+ import re
32
+ from typing import List, Dict, Any, Tuple
33
+ from pathlib import Path
34
+ import hashlib
35
+ from services.cache_service import ensure_cache_dir, load_json, save_json
36
+ from difflib import SequenceMatcher
37
+ import requests
38
+
39
+ # Heuristic: limit total chunks returned to keep prompt small
40
+ DEFAULT_TOP_K = 25
41
+ LEXICAL_PREFILTER_K = 300 # limit how many chunks we embed per query
42
+ MAX_CHUNK_CHARS = 1200 # prevent single giant lines blowing up context
43
+
44
+ class RetrievalService:
45
+ def __init__(self, data_dictionary_service):
46
+ self.data_service = data_dictionary_service
47
+ self.chunks: List[Dict[str, Any]] = []
48
+ # Support separate embedding endpoint if configured, otherwise use main endpoint
49
+ self._embedding_endpoint = os.getenv("AZURE_OPENAI_EMBEDDING_ENDPOINT") or os.getenv("AZURE_OPENAI_ENDPOINT", "")
50
+ self._embedding_endpoint = self._embedding_endpoint.rstrip("/")
51
+ self._embedding_key = os.getenv("AZURE_OPENAI_API_KEY")
52
+ self._embedding_deployment = os.getenv("AZURE_OPENAI_EMBEDDING_DEPLOYMENT") # user must set
53
+ self._api_version = os.getenv("AZURE_OPENAI_EMBEDDING_API_VERSION") or os.getenv("AZURE_OPENAI_API_VERSION", "2024-02-15-preview")
54
+ self._embeddings_cache: Dict[str, List[float]] = {}
55
+ # Cache paths
56
+ self._cache_dir = ensure_cache_dir()
57
+ self._chunks_path = Path(self._cache_dir) / "chunks.json"
58
+ self._embeds_path = Path(self._cache_dir) / "embeddings.json"
59
+ self._sig_path = Path(self._cache_dir) / "corpus_sig.txt"
60
+
61
+ # Preload cached index/embeddings if signatures match
62
+ self._corpus_sig = self._compute_corpus_signature()
63
+ self._load_cached_index()
64
+ self._load_cached_embeddings()
65
+
66
+ # -------------------- Public API -------------------- #
67
+ def index(self) -> int:
68
+ """(Re)build chunk list from current data dictionaries.
69
+ Returns number of chunks indexed."""
70
+ logger.info("[RetrievalService] Indexing all data dictionaries...")
71
+ self.chunks = []
72
+ for name, content in self.data_service.data_dictionaries.items():
73
+ dataset = name
74
+ for i, line in enumerate(content.splitlines()):
75
+ line = line.strip()
76
+ if not line or len(line) < 3:
77
+ continue
78
+ truncated = line[:MAX_CHUNK_CHARS]
79
+ chunk = {
80
+ "id": f"{dataset}:{i}",
81
+ "dataset": dataset,
82
+ "text": truncated,
83
+ "meta": {"line_number": i}
84
+ }
85
+ self.chunks.append(chunk)
86
+ logger.info(f"[RetrievalService] Indexed {len(self.chunks)} chunks from {len(self.data_service.data_dictionaries)} dictionaries.")
87
+ # Save index and signature
88
+ save_json(self._chunks_path, self.chunks)
89
+ try:
90
+ self._sig_path.write_text(self._corpus_sig, encoding="utf-8")
91
+ except Exception:
92
+ pass
93
+ return len(self.chunks)
94
+
95
+ def ensure_index(self):
96
+ if not self.chunks:
97
+ self.index()
98
+
99
+ # -------------------- Cache Status & Maintenance -------------------- #
100
+ def get_cache_status(self) -> Dict[str, Any]:
101
+ """Return lightweight cache/index status for UI display."""
102
+ return {
103
+ "chunks_indexed": len(self.chunks),
104
+ "embeddings_cached": len(self._embeddings_cache),
105
+ "embeddings_enabled": self._embedding_ready(),
106
+ "cache_dir": str(self._cache_dir),
107
+ "corpus_sig": (self._corpus_sig[:12] + "…") if getattr(self, "_corpus_sig", None) else "",
108
+ }
109
+
110
+ def clear_cache(self) -> None:
111
+ """Clear on-disk caches and in-memory caches."""
112
+ logger.info("[RetrievalService] Clearing caches (index + embeddings).")
113
+ # Clear disk files
114
+ for p in [self._chunks_path, self._embeds_path, self._sig_path]:
115
+ try:
116
+ if p.exists():
117
+ p.unlink()
118
+ except Exception:
119
+ pass
120
+ # Clear memory
121
+ self.chunks = []
122
+ self._embeddings_cache = {}
123
+
124
+ def search(self, query: str, active_datasets: List[str], top_k: int = DEFAULT_TOP_K, disable_embeddings: bool = False) -> List[Dict[str, Any]]:
125
+ logger.info(f"[RetrievalService] search() called with query: '{query}' and active_datasets: {active_datasets}")
126
+ # Skip retrieval for very short conversational messages (greetings, acknowledgments)
127
+ if len(query.strip().split()) <= 3 and not any(kw in query.lower() for kw in ['column', 'data', 'dataset', 'show', 'recommend', 'suggest']):
128
+ logger.info("[RetrievalService] Skipping retrieval for short conversational message.")
129
+ return [] # Let chat history handle short conversational exchanges
130
+ # If corpus has changed (e.g., new upload), refresh index
131
+ current_sig = self._compute_corpus_signature()
132
+ if current_sig != self._corpus_sig:
133
+ logger.info("[RetrievalService] Corpus changed; rebuilding index and refreshing cache.")
134
+ self._corpus_sig = current_sig
135
+ self.index()
136
+ self.ensure_index()
137
+ filtered = [c for c in self.chunks if c["dataset"] in active_datasets]
138
+ logger.info(f"[RetrievalService] {len(filtered)} chunks after filtering by active datasets.")
139
+ if not filtered:
140
+ logger.info("[RetrievalService] No chunks found for active datasets.")
141
+ return []
142
+ # Always do a quick lexical prefilter first to keep embedding calls bounded
143
+ q_tokens = tokenize(query)
144
+ for c in filtered:
145
+ c_tokens = tokenize(c["text"])
146
+ overlap = len(q_tokens & c_tokens) / (len(q_tokens) + 1e-9)
147
+ seq_ratio = SequenceMatcher(None, query.lower(), c["text"].lower()).ratio()
148
+ c["_lex"] = (overlap * 0.6) + (seq_ratio * 0.4)
149
+
150
+ prefiltered = sorted(filtered, key=lambda x: x["_lex"], reverse=True)[:min(LEXICAL_PREFILTER_K, len(filtered))]
151
+ logger.info(f"[RetrievalService] Lexical prefilter reduced to {len(prefiltered)} chunks.")
152
+
153
+ # If embeddings are ready, re-rank the prefiltered set with semantic similarity
154
+ if self._embedding_ready() and not disable_embeddings:
155
+ logger.info("[RetrievalService] Using embedding-based rerank on prefiltered set.")
156
+ query_vec = self._get_embedding(query)
157
+ if query_vec and any(v != 0.0 for v in query_vec):
158
+ # Batch-embed any prefiltered texts not in cache
159
+ texts_to_embed = []
160
+ idx_map = [] # indices of prefiltered needing embeddings
161
+ for idx, c in enumerate(prefiltered):
162
+ if c["text"] not in self._embeddings_cache:
163
+ texts_to_embed.append(c["text"])
164
+ idx_map.append(idx)
165
+ if texts_to_embed:
166
+ logger.info(f"[RetrievalService] Batch embedding {len(texts_to_embed)} prefiltered chunks...")
167
+ batch_vecs = self._embed_batch(texts_to_embed)
168
+ for i, vec in zip(idx_map, batch_vecs):
169
+ self._embeddings_cache[prefiltered[i]["text"]] = vec
170
+ # Compute cosine similarity using cached (or newly embedded) vectors
171
+ for c in prefiltered:
172
+ vec = self._embeddings_cache.get(c["text"], [])
173
+ c["score"] = cosine_similarity(query_vec, vec)
174
+ ranked = sorted(prefiltered, key=lambda x: x["score"], reverse=True)[:top_k]
175
+ logger.info(f"[RetrievalService] Returning top {len(ranked)} chunks (embedding rerank).")
176
+ return ranked
177
+ else:
178
+ logger.warning("[RetrievalService] Embedding unavailable, using lexical scores only.")
179
+
180
+ # No embeddings: use lexical scores
181
+ ranked = sorted(prefiltered, key=lambda x: x["_lex"], reverse=True)[:top_k]
182
+ logger.info(f"[RetrievalService] Returning top {len(ranked)} chunks (lexical only).")
183
+ return ranked
184
+
185
+ # -------------------- Embeddings Helpers -------------------- #
186
+ def _embedding_ready(self) -> bool:
187
+ return all([self._embedding_endpoint, self._embedding_key, self._embedding_deployment])
188
+
189
+ def _get_embedding(self, text: str) -> List[float]:
190
+ if text in self._embeddings_cache:
191
+ return self._embeddings_cache[text]
192
+ url = f"{self._embedding_endpoint}/openai/deployments/{self._embedding_deployment}/embeddings?api-version={self._api_version}"
193
+ headers = {"Content-Type": "application/json", "api-key": self._embedding_key}
194
+ data = {"input": text}
195
+ try:
196
+ logger.info(f"[RetrievalService] Requesting embedding for text (len={len(text)} chars)...")
197
+ resp = requests.post(url, headers=headers, json=data, timeout=10)
198
+ resp.raise_for_status()
199
+ vec = resp.json()["data"][0]["embedding"]
200
+ self._embeddings_cache[text] = vec
201
+ logger.info(f"[RetrievalService] Received embedding vector of length {len(vec)}.")
202
+ # Persist embeddings cache opportunistically
203
+ save_json(self._embeds_path, self._embeddings_cache)
204
+ return vec
205
+ except Exception as e:
206
+ logger.error(f"[RetrievalService] Embedding API call failed: {e}")
207
+ # On any failure, return empty vector to trigger lexical fallback
208
+ return []
209
+
210
+ def _embed_batch(self, texts: List[str]) -> List[List[float]]:
211
+ """Embed multiple texts in a single request (or minimal number of requests).
212
+ Returns vectors in the same order as input texts. On failure, returns empty vectors.
213
+ """
214
+ if not texts:
215
+ return []
216
+ url = f"{self._embedding_endpoint}/openai/deployments/{self._embedding_deployment}/embeddings?api-version={self._api_version}"
217
+ headers = {"Content-Type": "application/json", "api-key": self._embedding_key}
218
+ try:
219
+ logger.info(f"[RetrievalService] Batch embedding {len(texts)} texts...")
220
+ resp = requests.post(url, headers=headers, json={"input": texts}, timeout=20)
221
+ resp.raise_for_status()
222
+ data = resp.json().get("data", [])
223
+ # Azure returns embeddings in the same order as inputs
224
+ vectors = [item.get("embedding", []) for item in data]
225
+ if len(vectors) != len(texts):
226
+ logger.warning("[RetrievalService] Mismatch in batch embeddings count; falling back to empty vectors for missing entries.")
227
+ # pad to expected length
228
+ while len(vectors) < len(texts):
229
+ vectors.append([])
230
+ # Update cache and persist
231
+ for txt, vec in zip(texts, vectors):
232
+ self._embeddings_cache[txt] = vec
233
+ save_json(self._embeds_path, self._embeddings_cache)
234
+ return vectors
235
+ except Exception as e:
236
+ logger.error(f"[RetrievalService] Batch embedding failed: {e}")
237
+ return [[] for _ in texts]
238
+
239
+ # -------------------- Cache Helpers -------------------- #
240
+ def _compute_corpus_signature(self) -> str:
241
+ hasher = hashlib.sha256()
242
+ # Use names + sizes + head/tail slices for a stable signature
243
+ for name in sorted(self.data_service.data_dictionaries.keys()):
244
+ content = self.data_service.data_dictionaries.get(name, "")
245
+ head = content[:1024]
246
+ tail = content[-1024:]
247
+ hasher.update(name.encode("utf-8", errors="ignore"))
248
+ hasher.update(str(len(content)).encode("utf-8"))
249
+ hasher.update(head.encode("utf-8", errors="ignore"))
250
+ hasher.update(tail.encode("utf-8", errors="ignore"))
251
+ return hasher.hexdigest()
252
+
253
+ def _load_cached_index(self):
254
+ try:
255
+ sig = self._sig_path.read_text(encoding="utf-8") if self._sig_path.exists() else ""
256
+ if sig and sig == self._corpus_sig:
257
+ cached = load_json(self._chunks_path)
258
+ if isinstance(cached, list):
259
+ self.chunks = cached
260
+ logger.info(f"[RetrievalService] Loaded {len(self.chunks)} chunks from cache.")
261
+ except Exception:
262
+ pass
263
+
264
+ def _load_cached_embeddings(self):
265
+ try:
266
+ cached = load_json(self._embeds_path)
267
+ if isinstance(cached, dict):
268
+ self._embeddings_cache = cached
269
+ logger.info(f"[RetrievalService] Loaded {len(self._embeddings_cache)} embeddings from cache.")
270
+ except Exception:
271
+ pass
272
+
273
+ # -------------------- Utility Functions -------------------- #
274
+
275
+ def tokenize(text: str) -> set:
276
+ return set(re.findall(r"[a-zA-Z0-9_]+", text.lower()))
277
+
278
+ def cosine_similarity(a: List[float], b: List[float]) -> float:
279
+ if not a or not b or len(a) != len(b):
280
+ return 0.0
281
+ dot = sum(x * y for x, y in zip(a, b))
282
+ na = math.sqrt(sum(x * x for x in a))
283
+ nb = math.sqrt(sum(y * y for y in b))
284
+ if na == 0 or nb == 0:
285
+ return 0.0
286
+ return dot / (na * nb)
287
+
288
+ # -------------------- Prompt Assembly Helper -------------------- #
289
+
290
+ def format_retrieved_chunks(chunks: List[Dict[str, Any]]) -> str:
291
+ if not chunks:
292
+ return ""
293
+ parts = ["### Retrieved Relevant Entries (Always cite the Dataset name when recommending columns)"]
294
+ for i, c in enumerate(chunks, start=1):
295
+ parts.append(f"{i}. **Dataset: {c['dataset']}** | {c['text']}")
296
+ return "\n".join(parts)
297
+
298
+ if __name__ == "__main__":
299
+ # Simple manual test (requires data service mock)
300
+ class DummyDataService:
301
+ def __init__(self):
302
+ self.data_dictionaries = {"TEST_DICT": "COLUMN_A Description of A\nCOLUMN_B Description about B and health\nCOLUMN_C Irrelevant line"}
303
+ ds = DummyDataService()
304
+ rs = RetrievalService(ds)
305
+ rs.index()
306
+ results = rs.search("health columns", ["TEST_DICT"], top_k=5)
307
+ print(format_retrieved_chunks(results))
src/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file is intentionally left blank.
src/utils/session_state.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ def get_session_state():
4
+ """Get the current session state or create a new one if it doesn't exist."""
5
+ if 'data_dictionaries' not in st.session_state:
6
+ st.session_state.data_dictionaries = []
7
+ if 'user_uploads' not in st.session_state:
8
+ st.session_state.user_uploads = []
9
+ if 'chat_history' not in st.session_state:
10
+ st.session_state.chat_history = []
11
+ return st.session_state
12
+
13
+ def clear_session_state():
14
+ """Clear the session state for a fresh start."""
15
+ st.session_state.data_dictionaries.clear()
16
+ st.session_state.user_uploads.clear()
17
+ st.session_state.chat_history.clear()
src/utils/validators.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def validate_file_format(file_name: str, allowed_extensions: list = None) -> bool:
2
+ """
3
+ Validate that the file has an allowed format.
4
+
5
+ Args:
6
+ file_name (str): The name of the file.
7
+ allowed_extensions (list): Optional list of allowed extensions.
8
+ If None, defaults to ['pdf', 'xlsx', 'xls', 'csv']
9
+
10
+ Returns:
11
+ bool: True if the file format is allowed, False otherwise.
12
+ """
13
+ if allowed_extensions is None:
14
+ allowed_extensions = ['.pdf', '.xlsx', '.xls', '.csv']
15
+
16
+ return any(file_name.lower().endswith(ext) for ext in allowed_extensions)
17
+
18
+
19
+ def validate_file_extension(file_name: str, allowed_extensions: list) -> bool:
20
+ """
21
+ Validate that the uploaded file has an allowed extension.
22
+
23
+ Args:
24
+ file_name (str): The name of the uploaded file.
25
+ allowed_extensions (list): A list of allowed file extensions.
26
+
27
+ Returns:
28
+ bool: True if the file extension is allowed, False otherwise.
29
+ """
30
+ return any(file_name.endswith(ext) for ext in allowed_extensions)
31
+
32
+
33
+ def validate_file_size(file_size: int, max_size_mb: int) -> bool:
34
+ """
35
+ Validate that the uploaded file size does not exceed the maximum allowed size.
36
+
37
+ Args:
38
+ file_size (int): The size of the uploaded file in bytes.
39
+ max_size_mb (int): The maximum allowed file size in megabytes.
40
+
41
+ Returns:
42
+ bool: True if the file size is within the limit, False otherwise.
43
+ """
44
+ max_size_bytes = max_size_mb * 1024 * 1024
45
+ return file_size <= max_size_bytes
46
+
47
+
48
+ def validate_uploaded_file(file_name: str, file_size: int, allowed_extensions: list, max_size_mb: int) -> str:
49
+ """
50
+ Validate the uploaded file based on its name and size.
51
+
52
+ Args:
53
+ file_name (str): The name of the uploaded file.
54
+ file_size (int): The size of the uploaded file in bytes.
55
+ allowed_extensions (list): A list of allowed file extensions.
56
+ max_size_mb (int): The maximum allowed file size in megabytes.
57
+
58
+ Returns:
59
+ str: A message indicating the validation result.
60
+ """
61
+ if not validate_file_extension(file_name, allowed_extensions):
62
+ return f"Invalid file type. Allowed types are: {', '.join(allowed_extensions)}."
63
+
64
+ if not validate_file_size(file_size, max_size_mb):
65
+ return f"File size exceeds the maximum limit of {max_size_mb} MB."
66
+
67
+ return "File is valid."
68
+
69
+
70
+ def validate_data_dictionary(data_dict: dict) -> bool:
71
+ """
72
+ Validate that a data dictionary has consistent structure.
73
+
74
+ Args:
75
+ data_dict (dict): Dictionary containing 'columns' and 'data' keys.
76
+
77
+ Returns:
78
+ bool: True if the data dictionary is valid, False otherwise.
79
+ """
80
+ if not isinstance(data_dict, dict):
81
+ return False
82
+
83
+ if 'columns' not in data_dict or 'data' not in data_dict:
84
+ return False
85
+
86
+ columns = data_dict['columns']
87
+ data = data_dict['data']
88
+
89
+ if not isinstance(columns, list) or not isinstance(data, list):
90
+ return False
91
+
92
+ # Check that all rows have the same number of columns
93
+ num_columns = len(columns)
94
+ for row in data:
95
+ if not isinstance(row, list) or len(row) != num_columns:
96
+ return False
97
+
98
+ return True
tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file is intentionally left blank.
tests/test_services.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from src.services.data_dictionary_service import DataDictionaryService
3
+ from src.services.file_parser_service import FileParserService
4
+
5
+ # Sample test data
6
+ sample_pdf_path = "data/user_uploads/sample_data_dictionary.pdf"
7
+ sample_excel_path = "data/user_uploads/sample_data_dictionary.xlsx"
8
+
9
+ @pytest.fixture
10
+ def data_dictionary_service():
11
+ return DataDictionaryService()
12
+
13
+ def test_load_default_dictionaries(data_dictionary_service):
14
+ # Assuming there are default dictionaries in the data/default_dictionaries directory
15
+ default_dictionaries = data_dictionary_service.load_default_dictionaries()
16
+ assert isinstance(default_dictionaries, dict)
17
+ assert len(default_dictionaries) > 0 # Ensure there are default dictionaries loaded
18
+
19
+ def test_load_user_uploaded_dictionary(data_dictionary_service):
20
+ # Test loading a user-uploaded PDF dictionary
21
+ pdf_content = data_dictionary_service.load_user_uploaded_dictionary(sample_pdf_path)
22
+ assert pdf_content is not None
23
+ assert isinstance(pdf_content, str) # Ensure content is a string
24
+
25
+ # Test loading a user-uploaded Excel dictionary
26
+ excel_content = data_dictionary_service.load_user_uploaded_dictionary(sample_excel_path)
27
+ assert excel_content is not None
28
+ assert isinstance(excel_content, str) # Ensure content is a string
29
+
30
+ def test_parse_file_service():
31
+ parser_service = FileParserService()
32
+
33
+ # Test parsing a PDF file
34
+ pdf_text = parser_service.extract_text_from_pdf(sample_pdf_path)
35
+ assert pdf_text is not None
36
+ assert isinstance(pdf_text, str) # Ensure text is extracted as a string
37
+
38
+ # Test parsing an Excel file
39
+ excel_text = parser_service.extract_data_from_excel(sample_excel_path)
40
+ assert excel_text is not None
41
+ assert isinstance(excel_text, str) # Ensure text is extracted as a string
42
+
43
+ def test_invalid_file_upload(data_dictionary_service):
44
+ # Test loading an invalid file type
45
+ invalid_file_path = "data/user_uploads/invalid_file.txt"
46
+ result = data_dictionary_service.load_user_uploaded_dictionary(invalid_file_path)
47
+ assert result is None # Ensure that invalid file returns None or appropriate error handling
tests/test_utils.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from src.utils.validators import validate_file_format, validate_data_dictionary
3
+
4
+ def test_validate_file_format():
5
+ assert validate_file_format("data.xlsx") == True
6
+ assert validate_file_format("data.pdf") == True
7
+ assert validate_file_format("data.txt") == False
8
+ assert validate_file_format("data.csv") == True
9
+
10
+ def test_validate_data_dictionary():
11
+ valid_dict = {
12
+ "columns": ["age", "gender", "income"],
13
+ "data": [[25, "M", 50000], [30, "F", 60000]]
14
+ }
15
+ invalid_dict = {
16
+ "columns": ["age", "gender"],
17
+ "data": [[25, "M"], [30, "F", 60000]]
18
+ }
19
+
20
+ assert validate_data_dictionary(valid_dict) == True
21
+ assert validate_data_dictionary(invalid_dict) == False