File size: 7,859 Bytes
4851501 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
# Data Ingestion Scripts
Documentation for scripts that download and process geographic datasets.
---
## Overview
Data ingestion scripts in `backend/scripts/` automate downloading and processing of various data sources:
- OpenStreetMap via Geofabrik
- Humanitarian Data Exchange (HDX)
- World Bank Open Data
- STRI GIS Portal
- Kontur Population
- Global datasets
---
##Scripts Reference
### 1. download_geofabrik.py
Downloads OpenStreetMap data for Panama from Geofabrik.
**Usage**:
```bash
cd backend
python scripts/download_geofabrik.py
```
**What it downloads**:
- Roads network
- Buildings
- POI (points of interest)
- Natural features
**Output**: GeoJSON files in `backend/data/osm/`
**Schedule**: Run monthly for updates
---
### 2. download_hdx_panama.py
Downloads administrative boundaries from Humanitarian Data Exchange.
**Usage**:
```bash
python scripts/download_hdx_panama.py
```
**Downloads**:
- Level 1: Provinces (10 features)
- Level 2: Districts (81 features)
- Level 3: Corregimientos (679 features)
**Output**: `backend/data/hdx/pan_admin{1,2,3}_2021.geojson`
**Schedule**: Annual updates
---
### 3. download_worldbank.py
Downloads World Bank development indicators.
**Usage**:
```bash
python scripts/download_worldbank.py
```
**Indicators**:
- GDP per capita
- Life expectancy
- Access to electricity
- Internet usage
- And more...
**Output**: `backend/data/worldbank/indicators.geojson`
**Processing**: Joins indicator data with country geometries
---
### 4. download_stri_data.py
Downloads datasets from STRI GIS Portal.
**Usage**:
```bash
python scripts/download_stri_data.py
```
**Downloads**:
- Protected areas
- Forest cover
- Environmental datasets
**Output**: `backend/data/stri/*.geojson`
**Note**: Uses ArcGIS REST API
---
### 5. stri_catalog_scraper.py
Discovers and catalogs all available STRI datasets.
**Usage**:
```bash
python scripts/stri_catalog_scraper.py
```
**Output**: JSON catalog of 100+ STRI datasets with metadata
**Features**:
- Priority scoring
- Temporal dataset detection
- REST endpoint generation
---
### 6. create_province_layer.py
Creates province-level socioeconomic data layer.
**Usage**:
```bash
python scripts/create_province_layer.py
```
**Combines**:
- INEC Census data
- MPI (poverty index)
- Administrative geometries
**Output**: `backend/data/socioeconomic/province_socioeconomic.geojson`
---
### 7. download_global_datasets.py
Downloads global reference datasets.
**Usage**:
```bash
python scripts/download_global_datasets.py
```
**Downloads**:
- Natural Earth country boundaries
- Global admin boundaries
- Reference layers
**Output**: `backend/data/global/*.geojson`
---
### 8. register_global_datasets.py
Registers global datasets in catalog.json.
**Usage**:
```bash
python scripts/register_global_datasets.py
```
**Action**: Adds dataset entries to `backend/data/catalog.json`
---
## Adding New Data Sources
### Step-by-Step Guide
#### 1. Create Download Script
Create `backend/scripts/download_mycustom_data.py`:
```python
import geopandas as gpd
import requests
from pathlib import Path
def download_custom_data():
"""Download custom dataset."""
# Define output path
output_dir = Path(__file__).parent.parent / "data" / "custom"
output_dir.mkdir(parents=True, exist_ok=True)
# Download data
url = "https://example.com/data.geojson"
response = requests.get(url)
# Save as GeoJSON
output_file = output_dir / "custom_data.geojson"
with open(output_file, 'w') as f:
f.write(response.text)
print(f"Downloaded to {output_file}")
if __name__ == "__main__":
download_custom_data()
```
#### 2. Update Catalog
Add entry to `backend/data/catalog.json`:
```json
{
"custom_data": {
"path": "custom/custom_data.geojson",
"description": "Short description for display",
"semantic_description": "Detailed description mentioning key concepts that help AI discovery. Include what data represents, coverage area, and typical use cases.",
"categories": ["infrastructure"],
"tags": ["roads", "transport", "panama"],
"schema": {
"columns": ["name", "type", "length_km", "geom"],
"geometry_type": "LineString"
}
}
}
```
**Key Fields**:
- `path`: Relative path from `backend/data/`
- `description`: Human-readable short description
- `semantic_description`: Detailed description for AI semantic search
- `categories`: Classify dataset
- `tags`: Keywords for filtering
- `schema`: Optional column and geometry info
#### 3. Regenerate Embeddings
```bash
cd backend
rm data/embeddings.npy
python -c "from backend.core.semantic_search import get_semantic_search; get_semantic_search()"
```
This generates vector embeddings for the new dataset description.
#### 4. Test Discovery
```bash
# Start backend
uvicorn backend.main:app --reload
# Test query
curl -X POST http://localhost:8000/api/chat \
-H "Content-Type: application/json" \
-d '{"message":"show me [your new data]","history":[]}'
```
Verify the AI can discover and query your dataset.
---
## Script Templates
### Basic Download Template
```python
#!/usr/bin/env python3
"""
Download script for [DATA SOURCE NAME]
"""
import geopandas as gpd
import requests
from pathlib import Path
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Constants
DATA_URL = "https://example.com/data.geojson"
OUTPUT_DIR = Path(__file__).parent.parent / "data" / "category"
def download_data():
"""Download and process data."""
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
logger.info(f"Downloading from {DATA_URL}")
# Download
gdf = gpd.read_file(DATA_URL)
# Process (example: project to WGS84)
if gdf.crs and gdf.crs != "EPSG:4326":
gdf = gdf.to_crs("EPSG:4326")
# Save
output_file = OUTPUT_DIR / "data.geojson"
gdf.to_file(output_file, driver="GeoJSON")
logger.info(f"Saved {len(gdf)} features to {output_file}")
if __name__ == "__main__":
download_data()
```
### API Download Template
```python
import requests
import json
def download_from_api():
"""Download from REST API."""
# Query API
params = {
"where": "country='Panama'",
"outFields": "*",
"f": "geojson"
}
response = requests.get(API_URL, params=params)
response.raise_for_status()
# Parse and save
geojson = response.json()
with open(output_file, 'w') as f:
json.dump(geojson, f)
```
---
## Data Processing Best Practices
### 1. Coordinate System
Always save in WGS84 (EPSG:4326):
```python
if gdf.crs != "EPSG:4326":
gdf = gdf.to_crs("EPSG:4326")
```
### 2. Column Naming
Use lowercase with underscores:
```python
gdf.columns = gdf.columns.str.lower().str.replace(' ', '_')
```
### 3. Null Handling
Remove or fill nulls:
```python
gdf['name'] = gdf['name'].fillna('Unknown')
gdf = gdf.dropna(subset=['geom'])
```
### 4. Simplify Geometry (if needed)
For large datasets:
```python
gdf['geom'] = gdf['geom'].simplify(tolerance=0.001)
```
### 5. Validate GeoJSON
```python
import json
# Check valid JSON
with open(output_file) as f:
data = json.load(f)
assert data['type'] == 'FeatureCollection'
assert 'features' in data
```
---
## Data Sources Reference
| Source | Script | Frequency | Size |
|--------|--------|-----------|------|
| Geofabrik (OSM) | `download_geofabrik.py` | Monthly | ~100MB |
| HDX | `download_hdx_panama.py` | Annual | ~5MB |
| World Bank | `download_worldbank.py` | Annual | ~1MB |
| STRI | `download_stri_data.py` | As updated | ~50MB |
| Kontur | Manual | Quarterly | ~200MB |
---
## Next Steps
- **Dataset Sources**: [../data/DATASET_SOURCES.md](../data/DATASET_SOURCES.md)
- **Core Services**: [CORE_SERVICES.md](CORE_SERVICES.md)
|