"""Prepare all civic intelligence data for HuggingFace Hub upload. Usage: python scripts/data/prepare_huggingface_upload.py """ from __future__ import annotations import json import csv from datetime import datetime, timezone from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parents[2] DATA_DIR = PROJECT_ROOT / 'data' / 'civic_intel' def _human_size(size_bytes: int) -> str: if size_bytes < 1024: return f'{size_bytes} B' elif size_bytes < 1024 * 1024: return f'{size_bytes / 1024:.1f} KB' else: return f'{size_bytes / (1024 * 1024):.1f} MB' def count_records(filepath: Path) -> int: """Count records in a data file.""" try: if filepath.suffix == '.json': data = json.loads(filepath.read_text(encoding='utf-8')) if isinstance(data, list): return len(data) elif isinstance(data, dict): if 'features' in data: return len(data['features']) return len(data) elif filepath.suffix == '.csv': with open(filepath, 'r', encoding='utf-8') as f: return sum(1 for _ in csv.reader(f)) - 1 elif filepath.suffix == '.geojson': data = json.loads(filepath.read_text(encoding='utf-8')) return len(data.get('features', [])) except Exception: pass return 0 def main(): print('\n' + '=' * 60) print(' SafeVixAI Civic Intelligence - HuggingFace Prep') print('=' * 60) if not DATA_DIR.exists(): print(f' ERROR: {DATA_DIR} not found') return # Build file manifest manifest = { 'name': 'SafeVixAI Civic Intelligence Dataset', 'version': '1.0.0', 'description': 'Comprehensive Indian civic infrastructure and municipal data for AI-powered road safety and citizen grievance systems.', 'license': 'MIT', 'exported_at': datetime.now(timezone.utc).isoformat(), 'source': 'SafeVixAI Project (IIT Madras Road Safety Hackathon 2026)', 'categories': {}, 'files': {}, 'totals': { 'total_files': 0, 'total_records': 0, 'total_size_bytes': 0, } } # Walk directory categories = { 'boundaries': 'GeoJSON administrative boundaries (states, districts)', 'osm_features': 'OpenStreetMap civic infrastructure features', 'seed_data': 'Static reference datasets (LGD, road categories, grievances)', 'municipalities': 'Municipal corporation directory', } manifest['categories'] = categories for filepath in sorted(DATA_DIR.rglob('*')): if filepath.is_dir(): continue rel = str(filepath.relative_to(DATA_DIR)).replace('\\', '/') size = filepath.stat().st_size records = count_records(filepath) manifest['files'][rel] = { 'size_bytes': size, 'size_human': _human_size(size), 'records': records, 'format': filepath.suffix.lstrip('.'), } manifest['totals']['total_files'] += 1 manifest['totals']['total_records'] += records manifest['totals']['total_size_bytes'] += size manifest['totals']['total_size_human'] = _human_size(manifest['totals']['total_size_bytes']) # Save manifest manifest_file = DATA_DIR / 'metadata.json' manifest_file.write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding='utf-8') # Generate README.md dataset card readme = f"""--- license: mit language: - en - hi - ta - te - kn - ml - mr - bn - gu - pa tags: - india - civic - geospatial - road-safety - municipal - gis - hackathon size_categories: - 10K3} files {stats["records"]:>8,} records {_human_size(stats["size"]):>10s}') print(f'\n Generated:') print(f' {manifest_file}') print(f' {readme_file}') print(f'\n Upload to HuggingFace:') print(f' huggingface-cli upload SafeVixHub/civic-intel-india \\') print(f' {DATA_DIR} .') print() if __name__ == '__main__': main()