unitbytes 1.0.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.
unitbytes/travel.py ADDED
@@ -0,0 +1,878 @@
1
+ """Google Travel domain namespace (`ub.travel`) for Google Flights, Google Hotels, flexible-date calendars, and OTA rate parity audits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ from dataclasses import asdict, dataclass
7
+ from datetime import date, timedelta
8
+ from decimal import Decimal
9
+ import re
10
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
11
+ from urllib.parse import urlparse
12
+
13
+ from ._exceptions import redact_secrets
14
+ from ._serialization import normalize_max_charge_usd
15
+ from ._transports import unwrap_items_payload
16
+
17
+ if TYPE_CHECKING:
18
+ from .client import UnitBytes
19
+
20
+ ACTOR_GOOGLE_FLIGHTS = "unitbytes/google-flights-scraper"
21
+ ACTOR_GOOGLE_HOTELS = "unitbytes/google-hotels-scraper"
22
+
23
+ TripType = Literal["one_way", "round_trip"]
24
+ CabinClass = Literal["economy", "premium_economy", "business", "first"]
25
+ MaxStops = Literal["any", "nonstop", "1_stop_or_fewer", "2_stops_or_fewer"]
26
+ FlightSortBy = Literal["best", "cheapest", "departure_time", "arrival_time", "duration", "emissions"]
27
+
28
+ PropertyType = Literal["hotels", "vacation_rentals"]
29
+ HotelMinRating = Literal["any", "3.5", "4.0", "4.5"]
30
+ HotelSortBy = Literal["relevance", "lowest_price", "highest_rating"]
31
+ ParityStatus = Literal["undercut", "parity", "direct_cheaper", "no_direct_offer", "no_ota_offers"]
32
+
33
+ _VALID_TRIP_TYPES = {"one_way", "round_trip"}
34
+ _VALID_CABIN_CLASSES = {"economy", "premium_economy", "business", "first"}
35
+ _VALID_MAX_STOPS = {"any", "nonstop", "1_stop_or_fewer", "2_stops_or_fewer"}
36
+ _VALID_FLIGHT_SORTS = {"best", "cheapest", "departure_time", "arrival_time", "duration", "emissions"}
37
+ _VALID_PROPERTY_TYPES = {"hotels", "vacation_rentals"}
38
+ _VALID_HOTEL_RATINGS = {"any", "3.5", "4.0", "4.5"}
39
+ _VALID_HOTEL_SORTS = {"relevance", "lowest_price", "highest_rating"}
40
+ _ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
41
+
42
+ _VALID_GOOGLE_TLD_SUFFIXES: frozenset[str] = frozenset(
43
+ {
44
+ "com", "ad", "ae", "al", "am", "as", "at", "az", "ba", "be", "bf", "bg", "bi", "bj",
45
+ "bs", "bt", "by", "ca", "cat", "cd", "cf", "cg", "ch", "ci", "cl", "cm", "cn", "cv",
46
+ "cz", "de", "dj", "dk", "dm", "dz", "ee", "es", "fi", "fm", "fr", "ga", "ge", "gg",
47
+ "gl", "gm", "gr", "gy", "hn", "hr", "ht", "hu", "ie", "im", "iq", "is", "it", "je",
48
+ "jo", "kg", "ki", "kz", "la", "li", "lk", "lt", "lu", "lv", "md", "me", "mg", "mk",
49
+ "ml", "mn", "mu", "mv", "mw", "ne", "nl", "no", "nr", "nu", "pl", "pn", "ps", "pt",
50
+ "ro", "rs", "ru", "rw", "sc", "se", "sh", "si", "sk", "sm", "sn", "so", "sr", "st",
51
+ "td", "tg", "tl", "tm", "tn", "to", "tt", "vg", "vu",
52
+ "co.ao", "co.bw", "co.ck", "co.id", "co.cr", "co.il", "co.in", "co.jp", "co.ke",
53
+ "co.kr", "co.ls", "co.ma", "co.mz", "co.nz", "co.th", "co.tz", "co.ug", "co.uk",
54
+ "co.uz", "co.ve", "co.vi", "co.za", "co.zm", "co.zw",
55
+ "com.af", "com.ag", "com.ai", "com.ar", "com.au", "com.bd", "com.bh", "com.bn",
56
+ "com.bo", "com.br", "com.bz", "com.co", "com.cu", "com.cy", "com.do", "com.ec",
57
+ "com.eg", "com.et", "com.fj", "com.gh", "com.gi", "com.gt", "com.hk", "com.jm",
58
+ "com.kh", "com.kw", "com.lb", "com.ly", "com.mm", "com.mt", "com.mx", "com.my",
59
+ "com.na", "com.ng", "com.ni", "com.np", "com.om", "com.pa", "com.pe", "com.pg",
60
+ "com.ph", "com.pk", "com.pr", "com.py", "com.qa", "com.sa", "com.sb", "com.sg",
61
+ "com.sl", "com.sv", "com.tj", "com.tr", "com.tw", "com.ua", "com.uy", "com.vc",
62
+ "com.vn",
63
+ }
64
+ )
65
+
66
+ KNOWN_THIRD_PARTY_OTAS: frozenset[str] = frozenset(
67
+ {
68
+ "booking", "booking.com", "expedia", "expedia.com", "hotels.com", "agoda", "agoda.com",
69
+ "priceline", "priceline.com", "trip.com", "ctrip", "orbitz", "orbitz.com", "travelocity",
70
+ "cheaptickets", "kayak", "trivago", "edreams", "hotwire", "vio.com", "vio", "super.com",
71
+ "stayforlong", "zenhotels", "vrbo", "airbnb", "hopper", "traveluro", "algotels",
72
+ "snaptravel", "getaroom", "prestigia", "ostrovok", "klook", "makemytrip", "goibibo",
73
+ "cleartrip", "despegar", "decolar", "lastminute.com", "hrs", "hrs.com",
74
+ }
75
+ )
76
+
77
+
78
+ def _to_float(value: Any) -> float | None:
79
+ if value is None or isinstance(value, bool):
80
+ return None
81
+ if isinstance(value, (int, float)):
82
+ return float(value)
83
+ text = str(value).strip().replace(",", "")
84
+ if not text:
85
+ return None
86
+ match = re.search(r"-?\d+(?:\.\d+)?", text)
87
+ if not match:
88
+ return None
89
+ try:
90
+ return float(match.group(0))
91
+ except ValueError:
92
+ return None
93
+
94
+
95
+ def _to_int(value: Any) -> int | None:
96
+ parsed = _to_float(value)
97
+ return int(round(parsed)) if parsed is not None else None
98
+
99
+
100
+ def parse_iso_date(raw_date: str, field_name: str = "date") -> date:
101
+ cleaned = str(raw_date or "").strip()
102
+ if not _ISO_DATE_RE.fullmatch(cleaned):
103
+ raise ValueError(f"{field_name} must be in YYYY-MM-DD format, got {raw_date!r}.")
104
+ try:
105
+ return date.fromisoformat(cleaned)
106
+ except ValueError as exc:
107
+ raise ValueError(f"{field_name} is not a valid calendar date: {raw_date!r}.") from exc
108
+
109
+
110
+ def build_date_range(start_date: str, end_date: str, *, step_days: int = 1) -> list[str]:
111
+ """Generate inclusive `YYYY-MM-DD` date strings between `start_date` and `end_date`."""
112
+ if step_days < 1:
113
+ raise ValueError(f"step_days must be >= 1, got {step_days}.")
114
+ d_start = parse_iso_date(start_date, "start_date")
115
+ d_end = parse_iso_date(end_date, "end_date")
116
+ if d_end < d_start:
117
+ raise ValueError(f"end_date ({end_date}) must be on or after start_date ({start_date}).")
118
+ if (d_end - d_start).days > 180:
119
+ raise ValueError("Date range span cannot exceed 180 days in a single calendar scan.")
120
+ out: list[str] = []
121
+ cur = d_start
122
+ while cur <= d_end:
123
+ out.append(cur.isoformat())
124
+ cur += timedelta(days=step_days)
125
+ return out
126
+
127
+
128
+ def _is_valid_google_travel_host(host: str) -> bool:
129
+ for prefix in ("google.", "www.google."):
130
+ if host.startswith(prefix):
131
+ return host[len(prefix) :] in _VALID_GOOGLE_TLD_SUFFIXES
132
+ return False
133
+
134
+
135
+ def validate_google_travel_url(raw_url: str, *, kind: Literal["flights", "hotels"] = "flights") -> str:
136
+ cleaned = str(raw_url or "").strip()
137
+ if not cleaned:
138
+ raise ValueError(f"Google {kind} URL cannot be empty.")
139
+ if any(ch.isspace() or ord(ch) < 32 for ch in cleaned):
140
+ raise ValueError(f"Google {kind} URL must not contain whitespace or control characters.")
141
+ parsed = urlparse(cleaned)
142
+ if parsed.scheme.lower() != "https":
143
+ raise ValueError(f"Google {kind} URL must use https://, got {raw_url!r}.")
144
+ if parsed.username or parsed.password or "@" in (parsed.netloc or ""):
145
+ raise ValueError(f"Google {kind} URL must not contain embedded credentials.")
146
+ if parsed.port not in (None, 443):
147
+ raise ValueError(f"Google {kind} URL port must be 443 (or omitted).")
148
+ host = (parsed.hostname or "").lower().rstrip(".")
149
+ if not _is_valid_google_travel_host(host):
150
+ raise ValueError(f"Expected a Google Travel domain, got host {host!r}.")
151
+ path_lower = (parsed.path or "").lower()
152
+ if kind == "flights":
153
+ if not (
154
+ path_lower == "/travel/flights"
155
+ or path_lower.startswith("/travel/flights/")
156
+ or path_lower == "/flights"
157
+ or path_lower.startswith("/flights/")
158
+ ):
159
+ raise ValueError(f"Expected a Google Flights URL starting with '/travel/flights', got {parsed.path!r}.")
160
+ else:
161
+ if not (
162
+ path_lower == "/travel/hotels"
163
+ or path_lower.startswith("/travel/hotels/")
164
+ or path_lower == "/travel/search"
165
+ or path_lower.startswith("/travel/search/")
166
+ or path_lower == "/hotels"
167
+ or path_lower.startswith("/hotels/")
168
+ ):
169
+ raise ValueError(f"Expected a Google Hotels URL, got {parsed.path!r}.")
170
+ return cleaned
171
+
172
+
173
+ @dataclass(frozen=True)
174
+ class FlightDealAnalysis:
175
+ price: int | None
176
+ currency: str
177
+ price_level: str | None
178
+ typical_low: int | None
179
+ typical_high: int | None
180
+ savings_vs_typical_low: int | None
181
+ savings_pct_vs_typical_low: float | None
182
+ is_below_typical: bool
183
+ co2_grams: int | None
184
+ emissions_diff_pct: int | None
185
+ stops: int
186
+ duration_minutes: int | None
187
+
188
+ def to_dict(self) -> dict[str, Any]:
189
+ return asdict(self)
190
+
191
+
192
+ def analyze_flight_deal(flight: Mapping[str, Any]) -> FlightDealAnalysis:
193
+ price = _to_int(flight.get("price"))
194
+ currency = str(flight.get("currency") or "USD").strip().upper()
195
+ price_level = str(flight.get("priceLevel") or "").strip().lower() or None
196
+ typical_raw = flight.get("typicalPriceRange")
197
+ typical_low = _to_int(typical_raw[0]) if isinstance(typical_raw, Sequence) and not isinstance(typical_raw, (str, bytes)) and len(typical_raw) >= 2 else None
198
+ typical_high = _to_int(typical_raw[1]) if isinstance(typical_raw, Sequence) and not isinstance(typical_raw, (str, bytes)) and len(typical_raw) >= 2 else None
199
+
200
+ savings: int | None = None
201
+ savings_pct: float | None = None
202
+ is_below = price_level == "low"
203
+ if price is not None and typical_low is not None and typical_low > 0:
204
+ diff = typical_low - price
205
+ savings = diff
206
+ savings_pct = round((diff / typical_low) * 100.0, 2)
207
+ if diff > 0:
208
+ is_below = True
209
+
210
+ return FlightDealAnalysis(
211
+ price=price,
212
+ currency=currency,
213
+ price_level=price_level,
214
+ typical_low=typical_low,
215
+ typical_high=typical_high,
216
+ savings_vs_typical_low=savings,
217
+ savings_pct_vs_typical_low=savings_pct,
218
+ is_below_typical=is_below,
219
+ co2_grams=_to_int(flight.get("co2Grams")),
220
+ emissions_diff_pct=_to_int(flight.get("emissionsDiffPct")),
221
+ stops=_to_int(flight.get("stops")) or 0,
222
+ duration_minutes=_to_int(flight.get("durationMinutes")),
223
+ )
224
+
225
+
226
+ @dataclass(frozen=True)
227
+ class FlexibleDateFarePoint:
228
+ departure_date: str
229
+ return_date: str | None
230
+ cheapest_price: int | None
231
+ currency: str
232
+ airline: str | None
233
+ flight_numbers: list[str]
234
+ stops: int | None
235
+ duration_minutes: int | None
236
+ price_level: str | None
237
+ co2_grams: int | None
238
+ google_flights_url: str | None
239
+ offers_count: int
240
+ error: str | None = None
241
+
242
+ def to_dict(self) -> dict[str, Any]:
243
+ return asdict(self)
244
+
245
+
246
+ def _extract_root_domain(url_str: str | None) -> str | None:
247
+ if not url_str or not str(url_str).strip():
248
+ return None
249
+ try:
250
+ host = (urlparse(str(url_str).strip()).hostname or "").lower().rstrip(".")
251
+ except ValueError:
252
+ return None
253
+ if not host or "google." in host:
254
+ return None
255
+ if host.startswith("www."):
256
+ host = host[4:]
257
+ parts = host.split(".")
258
+ return parts[-2] if len(parts) >= 2 else host
259
+
260
+
261
+ def is_direct_hotel_offer(offer: Mapping[str, Any], hotel: Mapping[str, Any]) -> bool:
262
+ if bool(offer.get("isOfficial")) or bool(offer.get("isDirect")):
263
+ return True
264
+ provider = str(offer.get("provider") or "").strip()
265
+ if not provider:
266
+ return False
267
+ prov_low = provider.lower()
268
+ prov_clean = re.sub(r"\s*\(.*?\)\s*", "", prov_low).strip()
269
+ if prov_clean in KNOWN_THIRD_PARTY_OTAS:
270
+ return False
271
+ for known_ota in KNOWN_THIRD_PARTY_OTAS:
272
+ if len(known_ota) >= 4 and known_ota in prov_low:
273
+ return False
274
+ if any(tag in prov_low for tag in ("official site", "official website", "official", "direct", "book direct")):
275
+ return True
276
+
277
+ hotel_brand_root = _extract_root_domain(str(hotel.get("website") or ""))
278
+ offer_url_root = _extract_root_domain(str(offer.get("url") or ""))
279
+ if hotel_brand_root and len(hotel_brand_root) >= 4:
280
+ if hotel_brand_root in prov_low or (offer_url_root and offer_url_root == hotel_brand_root):
281
+ return True
282
+
283
+ generic_words = {
284
+ "hotel", "hotels", "resort", "resorts", "suites", "suite", "inn",
285
+ "lodge", "plaza", "grand", "park", "city", "beach", "downtown",
286
+ "center", "centre", "the", "and", "spa", "club", "boutique", "luxury",
287
+ "collection", "autograph", "tribute", "curio", "apartment", "apartments",
288
+ }
289
+ hotel_tokens = [
290
+ tok
291
+ for tok in re.findall(r"[a-z0-9]{4,}", str(hotel.get("name") or "").lower())
292
+ if tok not in generic_words
293
+ ]
294
+ prov_tokens = set(re.findall(r"[a-z0-9]{4,}", prov_low))
295
+ if hotel_tokens and any(tok in prov_tokens or tok in prov_low for tok in hotel_tokens):
296
+ return True
297
+ return False
298
+
299
+
300
+ @dataclass(frozen=True)
301
+ class HotelOtaParityReport:
302
+ name: str
303
+ property_id: str | None
304
+ currency: str
305
+ check_in_date: str | None
306
+ check_out_date: str | None
307
+ headline_price_per_night: int | None
308
+ direct_provider: str | None
309
+ direct_price: int | None
310
+ direct_total_price: int | None
311
+ direct_url: str | None
312
+ cheapest_ota_provider: str | None
313
+ cheapest_ota_price: int | None
314
+ cheapest_ota_total_price: int | None
315
+ cheapest_ota_url: str | None
316
+ highest_ota_price: int | None
317
+ undercut_amount: int | None
318
+ undercut_pct: float | None
319
+ ota_spread_pct: float | None
320
+ parity_status: ParityStatus
321
+ is_undercut: bool
322
+ ota_offers_count: int
323
+ google_hotels_url: str | None
324
+
325
+ def to_dict(self) -> dict[str, Any]:
326
+ return asdict(self)
327
+
328
+
329
+ def audit_hotel_ota_parity(
330
+ hotels: Sequence[Mapping[str, Any]],
331
+ *,
332
+ fallback_to_headline_price: bool = False,
333
+ only_undercut: bool = False,
334
+ ) -> list[dict[str, Any]]:
335
+ """Audit direct/official hotel rates against third-party OTAs (`Booking.com`, `Expedia`, `Hotels.com`, `Agoda`, etc.)."""
336
+ reports: list[dict[str, Any]] = []
337
+ for hotel in hotels:
338
+ if not isinstance(hotel, Mapping):
339
+ continue
340
+ name = str(hotel.get("name") or "").strip()
341
+ if not name:
342
+ continue
343
+
344
+ prop_id = str(hotel.get("propertyId") or "").strip() or None
345
+ currency = str(hotel.get("currency") or "USD").strip().upper()
346
+ headline_price = _to_int(hotel.get("pricePerNight"))
347
+ raw_offers = hotel.get("otaOffers")
348
+ offers_seq = raw_offers if isinstance(raw_offers, Sequence) and not isinstance(raw_offers, (str, bytes)) else []
349
+
350
+ direct_offers: list[dict[str, Any]] = []
351
+ ota_offers: list[dict[str, Any]] = []
352
+ for raw_offer in offers_seq:
353
+ if not isinstance(raw_offer, Mapping):
354
+ continue
355
+ price_val = _to_int(raw_offer.get("price"))
356
+ if price_val is None or price_val <= 0:
357
+ continue
358
+ normalized_offer = {
359
+ "provider": str(raw_offer.get("provider") or "Unknown").strip(),
360
+ "price": price_val,
361
+ "totalPrice": _to_int(raw_offer.get("totalPrice")),
362
+ "url": str(raw_offer.get("url") or "").strip() or None,
363
+ }
364
+ if is_direct_hotel_offer(raw_offer, hotel):
365
+ direct_offers.append(normalized_offer)
366
+ else:
367
+ ota_offers.append(normalized_offer)
368
+
369
+ direct_offers.sort(key=lambda x: x["price"])
370
+ ota_offers.sort(key=lambda x: x["price"])
371
+
372
+ best_direct = direct_offers[0] if direct_offers else None
373
+ if best_direct is None and fallback_to_headline_price and headline_price is not None and headline_price > 0:
374
+ best_direct = {
375
+ "provider": "Headline Rate (Fallback)",
376
+ "price": headline_price,
377
+ "totalPrice": _to_int(hotel.get("totalPrice")),
378
+ "url": str(hotel.get("website") or hotel.get("googleHotelsUrl") or "").strip() or None,
379
+ }
380
+
381
+ best_ota = ota_offers[0] if ota_offers else None
382
+ worst_ota = ota_offers[-1] if ota_offers else None
383
+
384
+ ota_spread_pct: float | None = None
385
+ if best_ota and worst_ota and worst_ota["price"] > 0:
386
+ ota_spread_pct = round(((worst_ota["price"] - best_ota["price"]) / worst_ota["price"]) * 100.0, 2)
387
+
388
+ undercut_amount: int | None = None
389
+ undercut_pct: float | None = None
390
+ status: ParityStatus
391
+ if best_ota is None:
392
+ status = "no_ota_offers"
393
+ elif best_direct is None:
394
+ status = "no_direct_offer"
395
+ else:
396
+ d_price = best_direct["price"]
397
+ o_price = best_ota["price"]
398
+ diff = d_price - o_price
399
+ undercut_amount = diff
400
+ undercut_pct = round((diff / d_price) * 100.0, 2) if d_price > 0 else 0.0
401
+ status = "undercut" if diff > 0 else ("parity" if diff == 0 else "direct_cheaper")
402
+
403
+ is_undercut = status == "undercut"
404
+ if only_undercut and not is_undercut:
405
+ continue
406
+
407
+ report = HotelOtaParityReport(
408
+ name=name,
409
+ property_id=prop_id,
410
+ currency=currency,
411
+ check_in_date=str(hotel.get("checkInDate") or "").strip() or None,
412
+ check_out_date=str(hotel.get("checkOutDate") or "").strip() or None,
413
+ headline_price_per_night=headline_price,
414
+ direct_provider=best_direct["provider"] if best_direct else None,
415
+ direct_price=best_direct["price"] if best_direct else None,
416
+ direct_total_price=best_direct["totalPrice"] if best_direct else None,
417
+ direct_url=best_direct["url"] if best_direct else None,
418
+ cheapest_ota_provider=best_ota["provider"] if best_ota else None,
419
+ cheapest_ota_price=best_ota["price"] if best_ota else None,
420
+ cheapest_ota_total_price=best_ota["totalPrice"] if best_ota else None,
421
+ cheapest_ota_url=best_ota["url"] if best_ota else None,
422
+ highest_ota_price=worst_ota["price"] if worst_ota else None,
423
+ undercut_amount=undercut_amount,
424
+ undercut_pct=undercut_pct,
425
+ ota_spread_pct=ota_spread_pct,
426
+ parity_status=status,
427
+ is_undercut=is_undercut,
428
+ ota_offers_count=len(ota_offers),
429
+ google_hotels_url=str(hotel.get("googleHotelsUrl") or "").strip() or None,
430
+ )
431
+ reports.append(report.to_dict())
432
+
433
+ reports.sort(
434
+ key=lambda r: (
435
+ 0 if r["is_undercut"] else 1,
436
+ -(r["undercut_pct"] if r["undercut_pct"] is not None else -9999.0),
437
+ )
438
+ )
439
+ return reports
440
+
441
+
442
+ audit_hotel_ota_rate_parity = audit_hotel_ota_parity
443
+
444
+
445
+ def _normalize_str_list(val: Sequence[str] | str | None) -> list[str]:
446
+ if val is None:
447
+ return []
448
+ if isinstance(val, str):
449
+ return [part.strip() for part in val.split(",") if part.strip()]
450
+ return [str(item).strip() for item in val if item is not None and str(item).strip()]
451
+
452
+
453
+ class TravelNamespace:
454
+ """Google Flights, Google Hotels, flexible-date calendars, and OTA parity audits (`ub.travel`)."""
455
+
456
+ def __init__(self, client: UnitBytes) -> None:
457
+ self._client = client
458
+
459
+ def flights(
460
+ self,
461
+ origins: Sequence[str] | str | None = None,
462
+ destinations: Sequence[str] | str | None = None,
463
+ *,
464
+ from_origin: str | None = None,
465
+ to_destination: str | None = None,
466
+ departure_date: str | None = None,
467
+ return_date: str | None = None,
468
+ trip_type: TripType = "one_way",
469
+ cabin_class: CabinClass = "economy",
470
+ adults: int = 1,
471
+ children: int = 0,
472
+ max_stops: MaxStops = "any",
473
+ sort_by: FlightSortBy = "best",
474
+ currency: str = "USD",
475
+ country: str = "us",
476
+ language: str = "en",
477
+ urls: Sequence[str] | str | None = None,
478
+ max_flights: int = 30,
479
+ proxy_configuration: Mapping[str, Any] | None = None,
480
+ max_total_charge_usd: float | Decimal | None = None,
481
+ ) -> list[dict[str, Any]]:
482
+ """Search live Google Flights itineraries across one-way, round-trip, or origin × destination matrices."""
483
+ if max_flights < 1 or max_flights > 500:
484
+ raise ValueError(f"max_flights must be between 1 and 500, got {max_flights}.")
485
+ if adults < 1 or adults > 9:
486
+ raise ValueError(f"adults must be between 1 and 9, got {adults}.")
487
+ if children < 0 or children > 8:
488
+ raise ValueError(f"children must be between 0 and 8, got {children}.")
489
+ if adults + children > 9:
490
+ raise ValueError("Google Flights supports at most 9 total passengers per search.")
491
+ if trip_type not in _VALID_TRIP_TYPES:
492
+ raise ValueError(f"Invalid trip_type {trip_type!r}. Expected one_way or round_trip.")
493
+ if cabin_class not in _VALID_CABIN_CLASSES:
494
+ raise ValueError(f"Invalid cabin_class {cabin_class!r}.")
495
+ if max_stops not in _VALID_MAX_STOPS:
496
+ raise ValueError(f"Invalid max_stops {max_stops!r}.")
497
+ if sort_by not in _VALID_FLIGHT_SORTS:
498
+ raise ValueError(f"Invalid sort_by {sort_by!r}.")
499
+
500
+ orig_list = _normalize_str_list(origins)
501
+ dest_list = _normalize_str_list(destinations)
502
+ raw_urls = _normalize_str_list(urls)
503
+ validated_urls = [validate_google_travel_url(u, kind="flights") for u in raw_urls]
504
+
505
+ from_str = (from_origin or "").strip() or None
506
+ to_str = (to_destination or "").strip() or None
507
+
508
+ if not validated_urls and not (bool(orig_list or from_str) and bool(dest_list or to_str)):
509
+ raise ValueError(
510
+ "Provide both origins/from_origin and destinations/to_destination, or a Google Flights URL in urls."
511
+ )
512
+
513
+ dep_dt = parse_iso_date(departure_date, "departure_date") if departure_date else None
514
+ ret_dt = parse_iso_date(return_date, "return_date") if return_date else None
515
+ if dep_dt and ret_dt and ret_dt < dep_dt:
516
+ raise ValueError(f"return_date ({return_date}) must be on or after departure_date ({departure_date}).")
517
+
518
+ effective_trip_type: TripType = "round_trip" if ret_dt is not None else trip_type
519
+
520
+ run_input: dict[str, Any] = {
521
+ "tripType": effective_trip_type,
522
+ "cabinClass": cabin_class,
523
+ "adults": adults,
524
+ "children": children,
525
+ "maxStops": max_stops,
526
+ "sortBy": sort_by,
527
+ "currency": currency.strip().upper(),
528
+ "country": country.strip().lower(),
529
+ "language": language.strip(),
530
+ "maxFlights": max_flights,
531
+ }
532
+ if orig_list:
533
+ run_input["origins"] = orig_list
534
+ elif from_str:
535
+ run_input["from"] = from_str
536
+ if dest_list:
537
+ run_input["destinations"] = dest_list
538
+ elif to_str:
539
+ run_input["to"] = to_str
540
+ if dep_dt:
541
+ run_input["departureDate"] = dep_dt.isoformat()
542
+ if ret_dt:
543
+ run_input["returnDate"] = ret_dt.isoformat()
544
+ if validated_urls:
545
+ run_input["urls"] = validated_urls
546
+ if proxy_configuration:
547
+ run_input["proxyConfiguration"] = dict(proxy_configuration)
548
+
549
+ raw = self._client._transport.execute_operation(
550
+ service="travel",
551
+ operation="flights",
552
+ actor_slug=ACTOR_GOOGLE_FLIGHTS,
553
+ actor_input=run_input,
554
+ http_method="POST",
555
+ json_body=run_input,
556
+ max_total_charge_usd=max_total_charge_usd,
557
+ )
558
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")][:max_flights]
559
+
560
+ def hotels(
561
+ self,
562
+ locations: Sequence[str] | str | None = None,
563
+ *,
564
+ queries: Sequence[str] | str | None = None,
565
+ urls: Sequence[str] | str | None = None,
566
+ check_in_date: str | None = None,
567
+ check_out_date: str | None = None,
568
+ adults: int = 2,
569
+ children: int = 0,
570
+ property_type: PropertyType = "hotels",
571
+ min_rating: HotelMinRating = "any",
572
+ hotel_stars: Sequence[int] | None = None,
573
+ min_price: int | None = None,
574
+ max_price: int | None = None,
575
+ sort_by: HotelSortBy = "relevance",
576
+ currency: str = "USD",
577
+ country: str = "us",
578
+ language: str = "en",
579
+ max_hotels: int = 20,
580
+ proxy_configuration: Mapping[str, Any] | None = None,
581
+ max_total_charge_usd: float | Decimal | None = None,
582
+ ) -> list[dict[str, Any]]:
583
+ """Search Google Hotels & Vacation Rentals with multi-OTA offers, GPS coordinates, and HD photos."""
584
+ if max_hotels < 1 or max_hotels > 500:
585
+ raise ValueError(f"max_hotels must be between 1 and 500, got {max_hotels}.")
586
+ if adults < 1 or adults > 16:
587
+ raise ValueError(f"adults must be between 1 and 16, got {adults}.")
588
+ if children < 0 or children > 8:
589
+ raise ValueError(f"children must be between 0 and 8, got {children}.")
590
+ if property_type not in _VALID_PROPERTY_TYPES:
591
+ raise ValueError(f"Invalid property_type {property_type!r}.")
592
+ if str(min_rating) not in _VALID_HOTEL_RATINGS:
593
+ raise ValueError(f"Invalid min_rating {min_rating!r}.")
594
+ if sort_by not in _VALID_HOTEL_SORTS:
595
+ raise ValueError(f"Invalid sort_by {sort_by!r}.")
596
+
597
+ loc_list = _normalize_str_list(locations)
598
+ query_list = _normalize_str_list(queries)
599
+ raw_urls = _normalize_str_list(urls)
600
+ validated_urls = [validate_google_travel_url(u, kind="hotels") for u in raw_urls]
601
+
602
+ if not loc_list and not query_list and not validated_urls:
603
+ raise ValueError("Provide at least one destination/hotel in locations, queries, or urls.")
604
+
605
+ ci_dt = parse_iso_date(check_in_date, "check_in_date") if check_in_date else None
606
+ co_dt = parse_iso_date(check_out_date, "check_out_date") if check_out_date else None
607
+ if ci_dt and co_dt:
608
+ if co_dt <= ci_dt:
609
+ raise ValueError(f"check_out_date ({check_out_date}) must be strictly after check_in_date ({check_in_date}).")
610
+ if (co_dt - ci_dt).days > 30:
611
+ raise ValueError("Stay duration between check_in_date and check_out_date cannot exceed 30 nights.")
612
+
613
+ if min_price is not None and max_price is not None and max_price < min_price:
614
+ raise ValueError(f"max_price ({max_price}) must be >= min_price ({min_price}).")
615
+
616
+ stars_clean: list[int] = []
617
+ if hotel_stars:
618
+ for star in hotel_stars:
619
+ if isinstance(star, bool) or int(star) not in {2, 3, 4, 5}:
620
+ raise ValueError(f"hotel_stars entries must be integers in 2..5, got {star!r}.")
621
+ if int(star) not in stars_clean:
622
+ stars_clean.append(int(star))
623
+ stars_clean.sort()
624
+
625
+ run_input: dict[str, Any] = {
626
+ "adults": adults,
627
+ "children": children,
628
+ "propertyType": property_type,
629
+ "minRating": min_rating,
630
+ "sortBy": sort_by,
631
+ "currency": currency.strip().upper(),
632
+ "country": country.strip().lower(),
633
+ "language": language.strip(),
634
+ "maxHotels": max_hotels,
635
+ }
636
+ if loc_list:
637
+ run_input["locations"] = loc_list
638
+ if query_list:
639
+ run_input["queries"] = query_list
640
+ if validated_urls:
641
+ run_input["urls"] = validated_urls
642
+ if ci_dt:
643
+ run_input["checkInDate"] = ci_dt.isoformat()
644
+ if co_dt:
645
+ run_input["checkOutDate"] = co_dt.isoformat()
646
+ if stars_clean:
647
+ run_input["hotelStars"] = stars_clean
648
+ if min_price is not None:
649
+ run_input["minPrice"] = int(min_price)
650
+ if max_price is not None:
651
+ run_input["maxPrice"] = int(max_price)
652
+ if proxy_configuration:
653
+ run_input["proxyConfiguration"] = dict(proxy_configuration)
654
+
655
+ raw = self._client._transport.execute_operation(
656
+ service="travel",
657
+ operation="hotels",
658
+ actor_slug=ACTOR_GOOGLE_HOTELS,
659
+ actor_input=run_input,
660
+ http_method="POST",
661
+ json_body=run_input,
662
+ max_total_charge_usd=max_total_charge_usd,
663
+ )
664
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")][:max_hotels]
665
+
666
+ def scan_flexible_dates(
667
+ self,
668
+ origin: str,
669
+ destination: str,
670
+ departure_dates: Sequence[str],
671
+ *,
672
+ stay_nights: int | None = None,
673
+ cabin_class: CabinClass = "economy",
674
+ adults: int = 1,
675
+ children: int = 0,
676
+ max_stops: MaxStops = "any",
677
+ currency: str = "USD",
678
+ country: str = "us",
679
+ language: str = "en",
680
+ max_flights_per_date: int = 10,
681
+ concurrency: int = 3,
682
+ max_total_charge_usd: float | Decimal | None = None,
683
+ ) -> dict[str, Any]:
684
+ """Scan multiple departure dates to build a cheapest-day fare calendar while preserving partial results on single-date errors."""
685
+ orig_clean = str(origin or "").strip()
686
+ dest_clean = str(destination or "").strip()
687
+ if not orig_clean or not dest_clean:
688
+ raise ValueError("Both origin and destination must be non-empty strings.")
689
+ if cabin_class not in _VALID_CABIN_CLASSES:
690
+ raise ValueError(f"Invalid cabin_class {cabin_class!r}.")
691
+ if max_stops not in _VALID_MAX_STOPS:
692
+ raise ValueError(f"Invalid max_stops {max_stops!r}.")
693
+ if max_flights_per_date < 1 or max_flights_per_date > 500:
694
+ raise ValueError(f"max_flights_per_date must be between 1 and 500, got {max_flights_per_date}.")
695
+ if adults < 1 or adults > 9 or children < 0 or children > 8 or adults + children > 9:
696
+ raise ValueError("Invalid passenger count for Google Flights (1..9 total passengers).")
697
+ normalize_max_charge_usd(max_total_charge_usd)
698
+
699
+ unique_dates: list[str] = []
700
+ seen_dates: set[str] = set()
701
+ for raw_d in departure_dates:
702
+ iso_d = parse_iso_date(raw_d, "departure_dates").isoformat()
703
+ if iso_d not in seen_dates:
704
+ seen_dates.add(iso_d)
705
+ unique_dates.append(iso_d)
706
+
707
+ if not unique_dates:
708
+ raise ValueError("departure_dates must contain at least one YYYY-MM-DD date.")
709
+ if len(unique_dates) > 31:
710
+ raise ValueError("departure_dates supports up to 31 dates per scan.")
711
+ if stay_nights is not None and stay_nights < 1:
712
+ raise ValueError(f"stay_nights must be >= 1 when specified, got {stay_nights}.")
713
+
714
+ curr_upper = currency.strip().upper()
715
+
716
+ def _fetch_single_date(dep_iso: str) -> FlexibleDateFarePoint:
717
+ ret_iso: str | None = None
718
+ trip_mode: TripType = "one_way"
719
+ if stay_nights is not None:
720
+ ret_iso = (parse_iso_date(dep_iso) + timedelta(days=int(stay_nights))).isoformat()
721
+ trip_mode = "round_trip"
722
+
723
+ try:
724
+ offers = self.flights(
725
+ origins=[orig_clean],
726
+ destinations=[dest_clean],
727
+ departure_date=dep_iso,
728
+ return_date=ret_iso,
729
+ trip_type=trip_mode,
730
+ cabin_class=cabin_class,
731
+ adults=adults,
732
+ children=children,
733
+ max_stops=max_stops,
734
+ sort_by="cheapest",
735
+ currency=curr_upper,
736
+ country=country,
737
+ language=language,
738
+ max_flights=max_flights_per_date,
739
+ max_total_charge_usd=max_total_charge_usd,
740
+ )
741
+ except (TypeError, AttributeError):
742
+ raise
743
+ except Exception as exc:
744
+ safe_err = redact_secrets(str(exc))
745
+ return FlexibleDateFarePoint(
746
+ departure_date=dep_iso,
747
+ return_date=ret_iso,
748
+ cheapest_price=None,
749
+ currency=curr_upper,
750
+ airline=None,
751
+ flight_numbers=[],
752
+ stops=None,
753
+ duration_minutes=None,
754
+ price_level=None,
755
+ co2_grams=None,
756
+ google_flights_url=None,
757
+ offers_count=0,
758
+ error=safe_err,
759
+ )
760
+
761
+ priced_offers = [o for o in offers if _to_int(o.get("price")) is not None]
762
+ priced_offers.sort(key=lambda o: _to_int(o.get("price")) or 10**9)
763
+ best = priced_offers[0] if priced_offers else (offers[0] if offers else None)
764
+
765
+ if best is None:
766
+ return FlexibleDateFarePoint(
767
+ departure_date=dep_iso,
768
+ return_date=ret_iso,
769
+ cheapest_price=None,
770
+ currency=curr_upper,
771
+ airline=None,
772
+ flight_numbers=[],
773
+ stops=None,
774
+ duration_minutes=None,
775
+ price_level=None,
776
+ co2_grams=None,
777
+ google_flights_url=None,
778
+ offers_count=0,
779
+ error=None,
780
+ )
781
+
782
+ fnums = best.get("flightNumbers")
783
+ fnum_list = [str(x) for x in fnums] if isinstance(fnums, Sequence) and not isinstance(fnums, (str, bytes)) else []
784
+ return FlexibleDateFarePoint(
785
+ departure_date=dep_iso,
786
+ return_date=ret_iso,
787
+ cheapest_price=_to_int(best.get("price")),
788
+ currency=str(best.get("currency") or curr_upper).upper(),
789
+ airline=str(best.get("airline") or "").strip() or None,
790
+ flight_numbers=fnum_list,
791
+ stops=_to_int(best.get("stops")),
792
+ duration_minutes=_to_int(best.get("durationMinutes")),
793
+ price_level=str(best.get("priceLevel") or "").strip() or None,
794
+ co2_grams=_to_int(best.get("co2Grams")),
795
+ google_flights_url=str(best.get("googleFlightsUrl") or "").strip() or None,
796
+ offers_count=len(offers),
797
+ error=None,
798
+ )
799
+
800
+ workers = max(1, min(8, int(concurrency), len(unique_dates)))
801
+ if workers == 1:
802
+ points = [_fetch_single_date(d) for d in unique_dates]
803
+ else:
804
+ with ThreadPoolExecutor(max_workers=workers) as pool:
805
+ points = list(pool.map(_fetch_single_date, unique_dates))
806
+
807
+ points_sorted = sorted(points, key=lambda p: p.departure_date)
808
+ priced_points = [p for p in points_sorted if p.cheapest_price is not None]
809
+ errors_list = [
810
+ {"departure_date": pt.departure_date, "error": pt.error}
811
+ for pt in points_sorted
812
+ if pt.error is not None
813
+ ]
814
+
815
+ cheapest_point = min(priced_points, key=lambda p: p.cheapest_price or 10**9) if priced_points else None
816
+ priciest_point = max(priced_points, key=lambda p: p.cheapest_price or 0) if priced_points else None
817
+
818
+ savings_amount: int | None = None
819
+ savings_pct: float | None = None
820
+ if (
821
+ cheapest_point is not None
822
+ and priciest_point is not None
823
+ and cheapest_point.cheapest_price is not None
824
+ and priciest_point.cheapest_price is not None
825
+ and priciest_point.cheapest_price > 0
826
+ ):
827
+ savings_amount = priciest_point.cheapest_price - cheapest_point.cheapest_price
828
+ savings_pct = round((savings_amount / priciest_point.cheapest_price) * 100.0, 2)
829
+
830
+ return {
831
+ "origin": orig_clean,
832
+ "destination": dest_clean,
833
+ "trip_type": "round_trip" if stay_nights is not None else "one_way",
834
+ "stay_nights": stay_nights,
835
+ "cabin_class": cabin_class,
836
+ "currency": curr_upper,
837
+ "dates_scanned": len(points_sorted),
838
+ "cheapest_date": cheapest_point.departure_date if cheapest_point else None,
839
+ "cheapest_return_date": cheapest_point.return_date if cheapest_point else None,
840
+ "cheapest_price": cheapest_point.cheapest_price if cheapest_point else None,
841
+ "cheapest_airline": cheapest_point.airline if cheapest_point else None,
842
+ "cheapest_url": cheapest_point.google_flights_url if cheapest_point else None,
843
+ "highest_date_price": priciest_point.cheapest_price if priciest_point else None,
844
+ "calendar_savings_amount": savings_amount,
845
+ "calendar_savings_pct": savings_pct,
846
+ "errors": errors_list,
847
+ "calendar": [pt.to_dict() for pt in points_sorted],
848
+ }
849
+
850
+ @staticmethod
851
+ def audit_hotel_ota_parity(
852
+ hotels: Sequence[Mapping[str, Any]],
853
+ *,
854
+ fallback_to_headline_price: bool = False,
855
+ only_undercut: bool = False,
856
+ ) -> list[dict[str, Any]]:
857
+ """Compare direct/official hotel rates against Booking.com, Expedia, Hotels.com, and Agoda `otaOffers`."""
858
+ return audit_hotel_ota_parity(
859
+ hotels,
860
+ fallback_to_headline_price=fallback_to_headline_price,
861
+ only_undercut=only_undercut,
862
+ )
863
+
864
+ audit_hotel_ota_rate_parity = audit_hotel_ota_parity
865
+
866
+
867
+ __all__ = [
868
+ "TravelNamespace",
869
+ "FlightDealAnalysis",
870
+ "FlexibleDateFarePoint",
871
+ "HotelOtaParityReport",
872
+ "analyze_flight_deal",
873
+ "audit_hotel_ota_parity",
874
+ "audit_hotel_ota_rate_parity",
875
+ "build_date_range",
876
+ "parse_iso_date",
877
+ "validate_google_travel_url",
878
+ ]