scrapemapsapi 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,489 @@
1
+ """Typed response models. Field names match the API's JSON exactly.
2
+
3
+ Every model has a ``from_dict`` constructor that ignores unknown keys, so a newer API
4
+ that adds fields never breaks an older SDK.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Dict, List, Literal, Mapping, Optional
11
+
12
+ PlaceStatus = Literal["operational", "temporarily_closed", "permanently_closed"]
13
+ ReviewSort = Literal["relevant", "newest", "highest", "lowest"]
14
+ Weekday = Literal["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
15
+
16
+
17
+ def _list(value: Any) -> list:
18
+ return value if isinstance(value, list) else []
19
+
20
+
21
+ def _dict(value: Any) -> dict:
22
+ return value if isinstance(value, dict) else {}
23
+
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # Data models
27
+ # ---------------------------------------------------------------------------
28
+
29
+
30
+ @dataclass
31
+ class Location:
32
+ lat: float
33
+ lng: float
34
+
35
+ @classmethod
36
+ def from_dict(cls, d: Mapping[str, Any]) -> Location:
37
+ return cls(lat=d["lat"], lng=d["lng"])
38
+
39
+
40
+ @dataclass
41
+ class Address:
42
+ formatted: Optional[str] = None
43
+ street: Optional[str] = None
44
+ postal_code: Optional[str] = None
45
+ city: Optional[str] = None
46
+ region: Optional[str] = None
47
+ country_code: Optional[str] = None
48
+
49
+ @classmethod
50
+ def from_dict(cls, d: Mapping[str, Any]) -> Address:
51
+ return cls(
52
+ formatted=d.get("formatted"),
53
+ street=d.get("street"),
54
+ postal_code=d.get("postal_code"),
55
+ city=d.get("city"),
56
+ region=d.get("region"),
57
+ country_code=d.get("country_code"),
58
+ )
59
+
60
+
61
+ @dataclass
62
+ class PlaceIds:
63
+ """Every identifier of a place. ``place_id`` (ChIJ...) can be null for some places."""
64
+
65
+ cid: str
66
+ feature_id: str
67
+ google_maps_url: str
68
+ place_id: Optional[str] = None
69
+
70
+ @classmethod
71
+ def from_dict(cls, d: Mapping[str, Any]) -> PlaceIds:
72
+ return cls(
73
+ place_id=d.get("place_id"),
74
+ cid=d["cid"],
75
+ feature_id=d["feature_id"],
76
+ google_maps_url=d["google_maps_url"],
77
+ )
78
+
79
+
80
+ #: ``places.resolve()`` returns the same shape as ``PlaceIds``.
81
+ ResolvedIds = PlaceIds
82
+
83
+
84
+ @dataclass
85
+ class TimePeriod:
86
+ open: str
87
+ """HH:MM, 24h, local time."""
88
+ close: str
89
+ """HH:MM, 24h; may be lower than ``open`` when past midnight."""
90
+
91
+ @classmethod
92
+ def from_dict(cls, d: Mapping[str, Any]) -> TimePeriod:
93
+ return cls(open=d["open"], close=d["close"])
94
+
95
+
96
+ @dataclass
97
+ class DayHours:
98
+ day: Weekday
99
+ closed: bool
100
+ open_24h: bool = False
101
+ periods: List[TimePeriod] = field(default_factory=list)
102
+ text: Optional[str] = None
103
+
104
+ @classmethod
105
+ def from_dict(cls, d: Mapping[str, Any]) -> DayHours:
106
+ return cls(
107
+ day=d["day"],
108
+ closed=bool(d.get("closed", False)),
109
+ open_24h=bool(d.get("open_24h", False)),
110
+ periods=[TimePeriod.from_dict(p) for p in _list(d.get("periods"))],
111
+ text=d.get("text"),
112
+ )
113
+
114
+
115
+ @dataclass
116
+ class OpeningHours:
117
+ weekly: List[DayHours] = field(default_factory=list)
118
+ status_text: Optional[str] = None
119
+
120
+ @classmethod
121
+ def from_dict(cls, d: Mapping[str, Any]) -> OpeningHours:
122
+ return cls(
123
+ weekly=[DayHours.from_dict(x) for x in _list(d.get("weekly"))],
124
+ status_text=d.get("status_text"),
125
+ )
126
+
127
+
128
+ @dataclass
129
+ class Photo:
130
+ url: str
131
+ width: Optional[int] = None
132
+ height: Optional[int] = None
133
+
134
+ @classmethod
135
+ def from_dict(cls, d: Mapping[str, Any]) -> Photo:
136
+ return cls(url=d["url"], width=d.get("width"), height=d.get("height"))
137
+
138
+
139
+ @dataclass
140
+ class Link:
141
+ url: str
142
+ domain: Optional[str] = None
143
+
144
+ @classmethod
145
+ def from_dict(cls, d: Mapping[str, Any]) -> Link:
146
+ return cls(url=d["url"], domain=d.get("domain"))
147
+
148
+
149
+ def _summary_kwargs(d: Mapping[str, Any]) -> dict[str, Any]:
150
+ return {
151
+ "id": d.get("id"),
152
+ "ids": PlaceIds.from_dict(d["ids"]),
153
+ "name": d["name"],
154
+ "categories": list(_list(d.get("categories"))),
155
+ "address": Address.from_dict(_dict(d.get("address"))),
156
+ "location": Location.from_dict(d["location"]),
157
+ "rating": d.get("rating"),
158
+ "review_count": d.get("review_count"),
159
+ "phone": d.get("phone"),
160
+ "website": d.get("website"),
161
+ "status": d.get("status"),
162
+ }
163
+
164
+
165
+ @dataclass
166
+ class PlaceSummary:
167
+ """A place as returned by search."""
168
+
169
+ ids: PlaceIds
170
+ name: str
171
+ address: Address
172
+ location: Location
173
+ id: Optional[str] = None
174
+ """Place ID (ChIJ...), the primary identifier. Null for the rare places without one: use ``ids.cid``."""
175
+ categories: List[str] = field(default_factory=list)
176
+ rating: Optional[float] = None
177
+ review_count: Optional[int] = None
178
+ phone: Optional[str] = None
179
+ website: Optional[str] = None
180
+ status: Optional[PlaceStatus] = None
181
+
182
+ @property
183
+ def ref(self) -> str:
184
+ """The best identifier to pass to ``places.get()`` / ``places.reviews()``."""
185
+ return self.id or self.ids.place_id or self.ids.cid
186
+
187
+ @classmethod
188
+ def from_dict(cls, d: Mapping[str, Any]) -> PlaceSummary:
189
+ return cls(**_summary_kwargs(d))
190
+
191
+
192
+ @dataclass
193
+ class Place(PlaceSummary):
194
+ """A place with full details."""
195
+
196
+ local_name: Optional[str] = None
197
+ phone_international: Optional[str] = None
198
+ plus_code: Optional[str] = None
199
+ timezone: Optional[str] = None
200
+ description: Optional[str] = None
201
+ opening_hours: Optional[OpeningHours] = None
202
+ attributes: Dict[str, List[str]] = field(default_factory=dict)
203
+ photos: List[Photo] = field(default_factory=list)
204
+ booking_links: List[Link] = field(default_factory=list)
205
+ knowledge_graph_id: Optional[str] = None
206
+
207
+ @classmethod
208
+ def from_dict(cls, d: Mapping[str, Any]) -> Place:
209
+ hours = d.get("opening_hours")
210
+ return cls(
211
+ **_summary_kwargs(d),
212
+ local_name=d.get("local_name"),
213
+ phone_international=d.get("phone_international"),
214
+ plus_code=d.get("plus_code"),
215
+ timezone=d.get("timezone"),
216
+ description=d.get("description"),
217
+ opening_hours=OpeningHours.from_dict(hours) if isinstance(hours, dict) else None,
218
+ attributes={k: list(v) for k, v in _dict(d.get("attributes")).items()},
219
+ photos=[Photo.from_dict(p) for p in _list(d.get("photos"))],
220
+ booking_links=[Link.from_dict(x) for x in _list(d.get("booking_links"))],
221
+ knowledge_graph_id=d.get("knowledge_graph_id"),
222
+ )
223
+
224
+
225
+ @dataclass
226
+ class ReviewAuthor:
227
+ id: Optional[str] = None
228
+ """Pseudonymous, stable author ID. Names, photos and profile links are never returned."""
229
+
230
+ @classmethod
231
+ def from_dict(cls, d: Mapping[str, Any]) -> ReviewAuthor:
232
+ return cls(id=d.get("id"))
233
+
234
+
235
+ @dataclass
236
+ class OwnerResponse:
237
+ text: str
238
+ translated_text: Optional[str] = None
239
+ relative_date: Optional[str] = None
240
+
241
+ @classmethod
242
+ def from_dict(cls, d: Mapping[str, Any]) -> OwnerResponse:
243
+ return cls(
244
+ text=d.get("text") or "",
245
+ translated_text=d.get("translated_text"),
246
+ relative_date=d.get("relative_date"),
247
+ )
248
+
249
+
250
+ @dataclass
251
+ class Review:
252
+ id: str
253
+ author: ReviewAuthor = field(default_factory=ReviewAuthor)
254
+ rating: Optional[int] = None
255
+ published_at: Optional[str] = None
256
+ """ISO 8601, UTC."""
257
+ relative_date: Optional[str] = None
258
+ language: Optional[str] = None
259
+ text: Optional[str] = None
260
+ translated_text: Optional[str] = None
261
+ """Google's translation into the requested language, when different from the original."""
262
+ owner_response: Optional[OwnerResponse] = None
263
+ photos: List[Photo] = field(default_factory=list)
264
+ details: Dict[str, str] = field(default_factory=dict)
265
+ """Structured answers, e.g. ``{"Price per person": "€20–30", "Food": "5"}``."""
266
+ source: Optional[str] = None
267
+
268
+ @classmethod
269
+ def from_dict(cls, d: Mapping[str, Any]) -> Review:
270
+ owner = d.get("owner_response")
271
+ return cls(
272
+ id=d["id"],
273
+ author=ReviewAuthor.from_dict(_dict(d.get("author"))),
274
+ rating=d.get("rating"),
275
+ published_at=d.get("published_at"),
276
+ relative_date=d.get("relative_date"),
277
+ language=d.get("language"),
278
+ text=d.get("text"),
279
+ translated_text=d.get("translated_text"),
280
+ owner_response=OwnerResponse.from_dict(owner) if isinstance(owner, dict) else None,
281
+ photos=[Photo.from_dict(p) for p in _list(d.get("photos"))],
282
+ details=dict(_dict(d.get("details"))),
283
+ source=d.get("source"),
284
+ )
285
+
286
+
287
+ # ---------------------------------------------------------------------------
288
+ # Envelopes
289
+ # ---------------------------------------------------------------------------
290
+
291
+
292
+ @dataclass
293
+ class Pagination:
294
+ has_more: bool
295
+ next_cursor: Optional[str] = None
296
+
297
+ @classmethod
298
+ def from_dict(cls, d: Mapping[str, Any]) -> Pagination:
299
+ return cls(has_more=bool(d.get("has_more")), next_cursor=d.get("next_cursor"))
300
+
301
+
302
+ @dataclass
303
+ class Meta:
304
+ credits_used: int
305
+ cached: bool
306
+
307
+ @classmethod
308
+ def from_dict(cls, d: Mapping[str, Any]) -> Meta:
309
+ return cls(credits_used=int(d.get("credits_used", 0)), cached=bool(d.get("cached")))
310
+
311
+
312
+ @dataclass
313
+ class SearchMeta(Meta):
314
+ query: str = ""
315
+ language: str = ""
316
+ region: str = ""
317
+
318
+ @classmethod
319
+ def from_dict(cls, d: Mapping[str, Any]) -> SearchMeta:
320
+ return cls(
321
+ credits_used=int(d.get("credits_used", 0)),
322
+ cached=bool(d.get("cached")),
323
+ query=d.get("query", ""),
324
+ language=d.get("language", ""),
325
+ region=d.get("region", ""),
326
+ )
327
+
328
+
329
+ @dataclass
330
+ class PlaceMeta(Meta):
331
+ language: str = ""
332
+
333
+ @classmethod
334
+ def from_dict(cls, d: Mapping[str, Any]) -> PlaceMeta:
335
+ return cls(
336
+ credits_used=int(d.get("credits_used", 0)),
337
+ cached=bool(d.get("cached")),
338
+ language=d.get("language", ""),
339
+ )
340
+
341
+
342
+ @dataclass
343
+ class ReviewsMeta(Meta):
344
+ cid: str = ""
345
+ sort: ReviewSort = "relevant"
346
+ language: str = ""
347
+ place_id: Optional[str] = None
348
+ original_language: Optional[str] = None
349
+
350
+ @classmethod
351
+ def from_dict(cls, d: Mapping[str, Any]) -> ReviewsMeta:
352
+ return cls(
353
+ credits_used=int(d.get("credits_used", 0)),
354
+ cached=bool(d.get("cached")),
355
+ place_id=d.get("place_id"),
356
+ cid=d.get("cid", ""),
357
+ sort=d.get("sort", "relevant"),
358
+ language=d.get("language", ""),
359
+ original_language=d.get("original_language"),
360
+ )
361
+
362
+
363
+ def _header_int(headers: Mapping[str, str], name: str) -> Optional[int]:
364
+ value = headers.get(name)
365
+ if value is None:
366
+ return None
367
+ try:
368
+ return int(value)
369
+ except ValueError:
370
+ return None
371
+
372
+
373
+ @dataclass
374
+ class ResponseInfo:
375
+ """Billing and cache information read from the response headers."""
376
+
377
+ credits_used: Optional[int] = None
378
+ """``X-Credits-Used``: credits charged for this call."""
379
+ credits_remaining: Optional[int] = None
380
+ """``X-Credits-Remaining``: credits left on the account after this call."""
381
+ cache: Optional[str] = None
382
+ """``X-Cache``: ``HIT`` or ``MISS``."""
383
+ processing_time_ms: Optional[int] = None
384
+
385
+ @classmethod
386
+ def from_headers(cls, headers: Mapping[str, str]) -> ResponseInfo:
387
+ return cls(
388
+ credits_used=_header_int(headers, "x-credits-used"),
389
+ credits_remaining=_header_int(headers, "x-credits-remaining"),
390
+ cache=headers.get("x-cache"),
391
+ processing_time_ms=_header_int(headers, "x-processing-time"),
392
+ )
393
+
394
+
395
+ class _WithInfo:
396
+ info: ResponseInfo
397
+ meta: Meta
398
+
399
+ @property
400
+ def credits_used(self) -> int:
401
+ """Credits charged for this call (header, falling back to ``meta.credits_used``)."""
402
+ if self.info.credits_used is not None:
403
+ return self.info.credits_used
404
+ return self.meta.credits_used
405
+
406
+ @property
407
+ def credits_remaining(self) -> Optional[int]:
408
+ """Credits left after this call, or None if the server did not say."""
409
+ return self.info.credits_remaining
410
+
411
+
412
+ @dataclass
413
+ class SearchResponse(_WithInfo):
414
+ data: List[PlaceSummary]
415
+ pagination: Pagination
416
+ meta: SearchMeta
417
+ info: ResponseInfo = field(default_factory=ResponseInfo)
418
+
419
+ @property
420
+ def next_cursor(self) -> Optional[str]:
421
+ return self.pagination.next_cursor
422
+
423
+ @property
424
+ def has_more(self) -> bool:
425
+ return self.pagination.has_more
426
+
427
+ @classmethod
428
+ def from_dict(cls, d: Mapping[str, Any], headers: Optional[Mapping[str, str]] = None) -> SearchResponse:
429
+ return cls(
430
+ data=[PlaceSummary.from_dict(x) for x in _list(d.get("data"))],
431
+ pagination=Pagination.from_dict(_dict(d.get("pagination"))),
432
+ meta=SearchMeta.from_dict(_dict(d.get("meta"))),
433
+ info=ResponseInfo.from_headers(headers or {}),
434
+ )
435
+
436
+
437
+ @dataclass
438
+ class PlaceResponse(_WithInfo):
439
+ data: Place
440
+ meta: PlaceMeta
441
+ info: ResponseInfo = field(default_factory=ResponseInfo)
442
+
443
+ @classmethod
444
+ def from_dict(cls, d: Mapping[str, Any], headers: Optional[Mapping[str, str]] = None) -> PlaceResponse:
445
+ return cls(
446
+ data=Place.from_dict(d["data"]),
447
+ meta=PlaceMeta.from_dict(_dict(d.get("meta"))),
448
+ info=ResponseInfo.from_headers(headers or {}),
449
+ )
450
+
451
+
452
+ @dataclass
453
+ class ReviewsResponse(_WithInfo):
454
+ data: List[Review]
455
+ pagination: Pagination
456
+ meta: ReviewsMeta
457
+ info: ResponseInfo = field(default_factory=ResponseInfo)
458
+
459
+ @property
460
+ def next_cursor(self) -> Optional[str]:
461
+ return self.pagination.next_cursor
462
+
463
+ @property
464
+ def has_more(self) -> bool:
465
+ return self.pagination.has_more
466
+
467
+ @classmethod
468
+ def from_dict(cls, d: Mapping[str, Any], headers: Optional[Mapping[str, str]] = None) -> ReviewsResponse:
469
+ return cls(
470
+ data=[Review.from_dict(x) for x in _list(d.get("data"))],
471
+ pagination=Pagination.from_dict(_dict(d.get("pagination"))),
472
+ meta=ReviewsMeta.from_dict(_dict(d.get("meta"))),
473
+ info=ResponseInfo.from_headers(headers or {}),
474
+ )
475
+
476
+
477
+ @dataclass
478
+ class ResolveResponse(_WithInfo):
479
+ data: ResolvedIds
480
+ meta: Meta
481
+ info: ResponseInfo = field(default_factory=ResponseInfo)
482
+
483
+ @classmethod
484
+ def from_dict(cls, d: Mapping[str, Any], headers: Optional[Mapping[str, str]] = None) -> ResolveResponse:
485
+ return cls(
486
+ data=PlaceIds.from_dict(d["data"]),
487
+ meta=Meta.from_dict(_dict(d.get("meta"))),
488
+ info=ResponseInfo.from_headers(headers or {}),
489
+ )