Ir para o conteúdo

tempest_fastapi_sdk.integrations.places.gmaps_scraper

Cliente assíncrono endurecido e parser CSV para o sidecar gosom/google-maps-scraper.

« Integrações e pagamentos


GmapsScraperClient

GmapsScraperClient(
    client: HTTPClient,
    *,
    default_keywords: Sequence[str] = (),
    zoom: int = 15,
    depth: int = 1,
    lang: str = "pt",
    max_time_seconds: int = MIN_GMAPS_MAX_TIME_SECONDS,
    poll_seconds: float = 2.0,
    wait_seconds: float = 600.0,
)

Async client for gosom/google-maps-scraper satisfying PlacesBackend.

Wraps a caller-owned :class:~tempest_fastapi_sdk.HTTPClient pointed at the sidecar. Supports direct scraping with explicit keywords via :meth:scrape as well as provider-agnostic discovery through :meth:search_nearby (implementing :class:~tempest_fastapi_sdk.geo.PlacesBackend).

Attributes:

Name Type Description
default_keywords tuple[str, ...]

Fallback search keywords used by :meth:search_nearby when included_types is omitted.

zoom int

Default map zoom level (1-21).

depth int

Default pagination depth (>= 1).

lang str

Default ISO language code sent to Google Maps.

max_time_seconds int

Default server-side job budget in seconds (>= 180).

poll_seconds float

Default polling interval in seconds.

wait_seconds float

Default client-side job deadline in seconds.

Initialize the Google Maps scraper client.

Parameters:

Name Type Description Default
client HTTPClient

Caller-owned HTTP client built with :func:gmaps_scraper_http_client or HTTPClient(**settings.gmaps_scraper_http_kwargs()).

required
default_keywords Sequence[str]

Optional default keywords used when :meth:search_nearby is called without included_types.

()
zoom int

Default map zoom level between 1 and 21. Defaults to 15.

15
depth int

Default scroll/pagination depth (>= 1). Defaults to 1.

1
lang str

Default language tag (for example "pt"). Defaults to "pt".

'pt'
max_time_seconds int

Default server-side max_time budget in seconds. Must be >= 180. Defaults to 180.

MIN_GMAPS_MAX_TIME_SECONDS
poll_seconds float

Default polling interval in seconds. Must be > 0. Defaults to 2.0.

2.0
wait_seconds float

Default total wait deadline in seconds. Must be > 0. Defaults to 600.0.

600.0

Raises:

Type Description
ValueError

When any default parameter is out of range or default_keywords contains a blank string.

build_job staticmethod

build_job(
    coordinate: Coordinate,
    *,
    keywords: Sequence[str],
    radius_m: int = 800,
    zoom: int = 15,
    depth: int = 1,
    lang: str = "pt",
    max_time_seconds: int = MIN_GMAPS_MAX_TIME_SECONDS,
) -> dict[str, JsonValue]

Build a hardened POST /api/v1/jobs payload for the sidecar.

Always pins fast_mode=True and email=False, never emits a proxies field, and converts max_time_seconds to Go nanoseconds.

Parameters:

Name Type Description Default
coordinate Coordinate

Center coordinate of the search area.

required
keywords Sequence[str]

One or more non-empty search terms.

required
radius_m int

Search radius in meters (> 0). Defaults to 800.

800
zoom int

Map zoom level between 1 and 21. Defaults to 15.

15
depth int

Pagination depth (>= 1). Defaults to 1.

1
lang str

Language code sent to Google Maps. Defaults to "pt".

'pt'
max_time_seconds int

Server-side job timeout in seconds (>= 180). Defaults to 180.

MIN_GMAPS_MAX_TIME_SECONDS

Returns:

Type Description
dict[str, JsonValue]

dict[str, JsonValue]: JSON-serializable job creation payload.

Raises:

Type Description
ValueError

When keywords is empty or contains blank entries, radius_m <= 0, zoom is outside 1..21, depth < 1, lang is blank, or max_time_seconds < 180.

scrape async

scrape(
    coordinate: Coordinate,
    *,
    keywords: Sequence[str],
    radius_m: int = 800,
    zoom: int | None = None,
    depth: int | None = None,
    lang: str | None = None,
    max_time_seconds: int | None = None,
    poll_seconds: float | None = None,
    wait_seconds: float | None = None,
) -> list[PlaceSchema]

Submit a scraping job, poll until completion, parse CSV and delete the job.

Always issues DELETE /api/v1/jobs/{job_id} in a finally block after the job is created — including when the job fails, times out, or raises an HTTP error — logging cleanup failures at WARNING without masking the original exception.

Parameters:

Name Type Description Default
coordinate Coordinate

Center coordinate of the search area.

required
keywords Sequence[str]

One or more non-empty search queries.

required
radius_m int

Search radius in meters (> 0). Defaults to 800.

800
zoom int | None

Optional zoom override (defaults to :attr:zoom).

None
depth int | None

Optional pagination depth override (defaults to :attr:depth).

None
lang str | None

Optional language override (defaults to :attr:lang).

None
max_time_seconds int | None

Optional server-side time budget in seconds (>= 180, defaults to :attr:max_time_seconds).

None
poll_seconds float | None

Optional polling interval in seconds (> 0, defaults to :attr:poll_seconds).

None
wait_seconds float | None

Optional client-side wait deadline in seconds (> 0, defaults to :attr:wait_seconds).

None

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Deduplicated places parsed from the job's CSV.

Raises:

Type Description
ValueError

When input parameters or the returned job_id are invalid.

GmapsScraperJobError

When the sidecar omits id, reports status="failed", or exceeds wait_seconds.

HTTPStatusError

When the sidecar responds with a non-2xx status on job creation, polling, or CSV download.

search_nearby async

search_nearby(
    coordinate: Coordinate,
    *,
    radius_m: int = 800,
    included_types: Sequence[str] | None = None,
) -> list[PlaceSchema]

Search places near coordinate, implementing :class:PlacesBackend.

Uses included_types as scraper keywords when supplied, falling back to :attr:default_keywords configured at client construction time.

Parameters:

Name Type Description Default
coordinate Coordinate

Center coordinate of the search.

required
radius_m int

Search radius in meters (> 0). Defaults to 800.

800
included_types Sequence[str] | None

Optional search keywords for this call; falls back to :attr:default_keywords when None.

None

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Deduplicated places returned by the scraper.

Raises:

Type Description
ValueError

When neither included_types nor :attr:default_keywords provides at least one keyword, or when radius_m <= 0.

GmapsScraperJobError

When the scraping job fails or times out.

HTTPStatusError

When the sidecar returns a non-2xx status.

gmaps_scraper_http_client

gmaps_scraper_http_client(
    base_url: str,
    *,
    timeout: float = 30.0,
    retry_policy: RetryPolicy | None = None,
    extra_headers: Mapping[str, str] | None = None,
    transport: AsyncBaseTransport | None = None,
) -> HTTPClient

Build an :class:~tempest_fastapi_sdk.HTTPClient for the scraper sidecar.

Parameters:

Name Type Description Default
base_url str

Internal base URL of the gosom/google-maps-scraper sidecar (for example "http://gmaps-scraper:8080").

required
timeout float

Per-request HTTP timeout in seconds. Must be strictly positive. Defaults to 30.0.

30.0
retry_policy RetryPolicy | None

Optional retry policy forwarded to :class:~tempest_fastapi_sdk.HTTPClient.

None
extra_headers Mapping[str, str] | None

Optional extra headers merged on top of {"Accept": "application/json"}.

None
transport AsyncBaseTransport | None

Transport override (for example httpx.MockTransport in offline tests).

None

Returns:

Name Type Description
HTTPClient HTTPClient

Configured HTTP client ready for

HTTPClient

class:GmapsScraperClient.

Raises:

Type Description
ValueError

When base_url is blank or timeout is not finite and positive.

MIN_GMAPS_MAX_TIME_SECONDS module-attribute

MIN_GMAPS_MAX_TIME_SECONDS: Final[int] = 180

Minimum max_time accepted by gosom/google-maps-scraper (3 minutes).

parse_gmaps_csv

parse_gmaps_csv(text: str) -> list[PlaceSchema]

Parse a gosom/google-maps-scraper CSV payload into PlaceSchema items.

Rows are read strictly as data via :class:csv.DictReader (handling an optional leading UTF-8 BOM). Rows missing place_id, title, or a valid finite WGS84 latitude/longitude pair are skipped, duplicate place_id entries keep their first occurrence, zero ratings become None, Brazilian states in complete_address normalize to 2-letter UFs, and Brazilian phone numbers normalize to +55 DD ....

Parameters:

Name Type Description Default
text str

Raw CSV content downloaded from GET /api/v1/jobs/{job_id}/download.

required

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Deduplicated places with source="gmaps_scraper"

list[PlaceSchema]

and external_id=<place_id>. Empty when no valid rows exist.

GMAPS_SCRAPER_SOURCE module-attribute

GMAPS_SCRAPER_SOURCE: Final[str] = 'gmaps_scraper'

Provider identifier stamped onto :attr:PlaceSchema.source.

BR_STATE_NAME_TO_UF module-attribute

BR_STATE_NAME_TO_UF: Final[dict[str, str]] = {
    "acre": "AC",
    "alagoas": "AL",
    "amapa": "AP",
    "amazonas": "AM",
    "bahia": "BA",
    "ceara": "CE",
    "distrito federal": "DF",
    "espirito santo": "ES",
    "goias": "GO",
    "maranhao": "MA",
    "mato grosso": "MT",
    "mato grosso do sul": "MS",
    "minas gerais": "MG",
    "para": "PA",
    "paraiba": "PB",
    "parana": "PR",
    "pernambuco": "PE",
    "piaui": "PI",
    "rio de janeiro": "RJ",
    "rio grande do norte": "RN",
    "rio grande do sul": "RS",
    "rondonia": "RO",
    "roraima": "RR",
    "santa catarina": "SC",
    "sao paulo": "SP",
    "sergipe": "SE",
    "tocantins": "TO",
}

Normalized (accent-free, lowercase) Brazilian state names mapped to UF.