|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from datetime import datetime, timezone |
| 4 | +from urllib.error import HTTPError, URLError |
| 5 | +from urllib.request import Request, urlopen |
| 6 | +import json |
| 7 | +import os |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from base.querier import BaseQuerier |
| 11 | +from dtos import RawLocation |
| 12 | + |
| 13 | + |
| 14 | +GOOGLE_PLACES_ENDPOINT = "https://places.googleapis.com/v1/places:searchText" |
| 15 | + |
| 16 | + |
| 17 | +class GooglePlacesQuerier(BaseQuerier): |
| 18 | + def __init__(self, *, api_key: str | None = None, text_query: str, data_source: str): |
| 19 | + self.api_key = api_key or os.environ.get("GOOGLE_API_KEY") |
| 20 | + self.text_query = text_query |
| 21 | + self.data_source = data_source |
| 22 | + |
| 23 | + def fetch(self) -> list[RawLocation]: |
| 24 | + if not self.api_key: |
| 25 | + raise RuntimeError("GOOGLE_API_KEY is required") |
| 26 | + |
| 27 | + payload = self._request({"textQuery": self.text_query}) |
| 28 | + places = payload.get("places", []) |
| 29 | + fetched_at = datetime.now(timezone.utc) |
| 30 | + raw_locations: list[RawLocation] = [] |
| 31 | + for index, place in enumerate(places): |
| 32 | + raw_locations.append( |
| 33 | + RawLocation( |
| 34 | + data_source=self.data_source, |
| 35 | + data_source_id=place.get("id") or f"{self.data_source}-{index}", |
| 36 | + fetched_at=fetched_at, |
| 37 | + payload=place, |
| 38 | + ) |
| 39 | + ) |
| 40 | + return raw_locations |
| 41 | + |
| 42 | + def _request(self, body: dict[str, Any]) -> dict[str, Any]: |
| 43 | + request = Request( |
| 44 | + GOOGLE_PLACES_ENDPOINT, |
| 45 | + data=json.dumps(body).encode("utf-8"), |
| 46 | + headers={ |
| 47 | + "Content-Type": "application/json", |
| 48 | + "X-Goog-Api-Key": self.api_key, |
| 49 | + "X-Goog-FieldMask": "places.id,places.displayName,places.formattedAddress,places.location,places.types", |
| 50 | + }, |
| 51 | + method="POST", |
| 52 | + ) |
| 53 | + try: |
| 54 | + with urlopen(request, timeout=30) as response: |
| 55 | + return json.loads(response.read().decode("utf-8")) |
| 56 | + except (HTTPError, URLError) as exc: |
| 57 | + raise RuntimeError(f"Google Places request failed: {exc}") from exc |
| 58 | + |
| 59 | + |
| 60 | +class GooglePlacesRepairQuerier(GooglePlacesQuerier): |
| 61 | + def __init__(self, api_key: str | None = None): |
| 62 | + super().__init__(api_key=api_key, text_query="shoe repair Boston MA", data_source="google_places_repair") |
| 63 | + |
| 64 | + |
| 65 | +class GooglePlacesDonationQuerier(GooglePlacesQuerier): |
| 66 | + def __init__(self, api_key: str | None = None): |
| 67 | + super().__init__(api_key=api_key, text_query="donation centers Boston MA", data_source="google_places_donations") |
0 commit comments