Spaces:
Sleeping
Sleeping
| """ | |
| Google Services Integration Module | |
| Provides Google Translate, Google Calendar link generation, | |
| and Google Maps polling station lookup functionality. | |
| """ | |
| import os | |
| import urllib.parse | |
| from datetime import datetime, timedelta | |
| from typing import Optional | |
| def get_google_maps_api_key() -> Optional[str]: | |
| """Return the Maps API key if configured, else None.""" | |
| key = os.getenv('GOOGLE_MAPS_API_KEY', '') | |
| if key and key != 'your-google-maps-api-key-here': | |
| return key | |
| return None | |
| def is_translate_enabled() -> bool: | |
| """Check whether Google Translate widget is enabled.""" | |
| return os.getenv('GOOGLE_TRANSLATE_ENABLED', 'true').lower() == 'true' | |
| def build_calendar_url( | |
| title: str, | |
| start_date: datetime, | |
| description: str = '', | |
| location: str = 'India', | |
| duration_hours: int = 24, | |
| ) -> str: | |
| """ | |
| Build a Google Calendar event creation URL. | |
| Args: | |
| title: Event title (e.g. "Phase 1 — Polling Day") | |
| start_date: datetime of event start | |
| description: Event description | |
| location: Event location string | |
| duration_hours: Duration of the event in hours | |
| Returns: | |
| Google Calendar URL that opens the "create event" form pre-filled. | |
| """ | |
| end_date = start_date + timedelta(hours=duration_hours) | |
| # Google Calendar expects dates in compact ISO format | |
| fmt = '%Y%m%dT%H%M%SZ' | |
| dates = f"{start_date.strftime(fmt)}/{end_date.strftime(fmt)}" | |
| params = { | |
| 'action': 'TEMPLATE', | |
| 'text': title, | |
| 'dates': dates, | |
| 'details': description, | |
| 'location': location, | |
| 'sf': 'true', | |
| 'output': 'xml', | |
| } | |
| return 'https://calendar.google.com/calendar/render?' + urllib.parse.urlencode(params) | |
| def build_maps_embed_url(query: str = 'Election Commission Office near me') -> Optional[str]: | |
| """ | |
| Build a Google Maps Embed API URL for polling station lookup. | |
| Args: | |
| query: Search query for the map embed | |
| Returns: | |
| Embed URL string, or None if API key is not configured. | |
| """ | |
| api_key = get_google_maps_api_key() | |
| if not api_key: | |
| return None | |
| params = { | |
| 'key': api_key, | |
| 'q': query, | |
| 'zoom': '12', | |
| } | |
| return 'https://www.google.com/maps/embed/v1/search?' + urllib.parse.urlencode(params) | |
| def get_google_config() -> dict: | |
| """ | |
| Return safe public Google configuration for frontend use. | |
| Never exposes full API keys — only presence flags. | |
| """ | |
| return { | |
| 'translate_enabled': is_translate_enabled(), | |
| 'maps_available': get_google_maps_api_key() is not None, | |
| 'maps_key': get_google_maps_api_key(), # Embed API key is public by design | |
| 'calendar_supported': True, | |
| } | |