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/trends.py ADDED
@@ -0,0 +1,1275 @@
1
+ """Google Trends domain namespace (`ub.trends`) and 1-line `pytrends` drop-in `TrendReq` replacement."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from decimal import Decimal
6
+ import re
7
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
8
+ from urllib.parse import urlparse
9
+
10
+ from ._exceptions import ProviderError, RateLimitError
11
+ from ._serialization import require_pandas, try_import_pandas
12
+ from ._transports import ProviderLiteral, Transport, unwrap_items_payload
13
+
14
+ if TYPE_CHECKING:
15
+ from .client import UnitBytes
16
+
17
+ ResponseError = ProviderError
18
+ TooManyRequestsError = RateLimitError
19
+
20
+ GeoResolution = Literal["COUNTRY", "REGION", "DMA", "CITY"]
21
+ TrendingTimeWindow = Literal["4h", "24h", "48h", "7d"]
22
+
23
+ PYTRENDS_PN_TO_ISO2: dict[str, str] = {
24
+ "united_states": "US",
25
+ "usa": "US",
26
+ "united_kingdom": "GB",
27
+ "uk": "GB",
28
+ "great_britain": "GB",
29
+ "england": "GB",
30
+ "canada": "CA",
31
+ "germany": "DE",
32
+ "france": "FR",
33
+ "spain": "ES",
34
+ "italy": "IT",
35
+ "australia": "AU",
36
+ "japan": "JP",
37
+ "south_korea": "KR",
38
+ "korea": "KR",
39
+ "india": "IN",
40
+ "brazil": "BR",
41
+ "mexico": "MX",
42
+ "colombia": "CO",
43
+ "poland": "PL",
44
+ "ukraine": "UA",
45
+ "netherlands": "NL",
46
+ "switzerland": "CH",
47
+ "sweden": "SE",
48
+ "norway": "NO",
49
+ "denmark": "DK",
50
+ "finland": "FI",
51
+ "belgium": "BE",
52
+ "austria": "AT",
53
+ "portugal": "PT",
54
+ "ireland": "IE",
55
+ "new_zealand": "NZ",
56
+ "singapore": "SG",
57
+ "hong_kong": "HK",
58
+ "taiwan": "TW",
59
+ "indonesia": "ID",
60
+ "philippines": "PH",
61
+ "vietnam": "VN",
62
+ "thailand": "TH",
63
+ "malaysia": "MY",
64
+ "turkey": "TR",
65
+ "saudi_arabia": "SA",
66
+ "united_arab_emirates": "AE",
67
+ "uae": "AE",
68
+ "israel": "IL",
69
+ "south_africa": "ZA",
70
+ "nigeria": "NG",
71
+ "egypt": "EG",
72
+ "argentina": "AR",
73
+ "chile": "CL",
74
+ "peru": "PE",
75
+ "greece": "GR",
76
+ "czech_republic": "CZ",
77
+ "czechia": "CZ",
78
+ "romania": "RO",
79
+ "hungary": "HU",
80
+ }
81
+
82
+ VALID_PREDEFINED_TIMEFRAMES: frozenset[str] = frozenset(
83
+ {
84
+ "now 1-H",
85
+ "now 4-H",
86
+ "now 1-d",
87
+ "now 7-d",
88
+ "today 1-m",
89
+ "today 3-m",
90
+ "today 12-m",
91
+ "today 5-y",
92
+ "all",
93
+ }
94
+ )
95
+
96
+ TIMEFRAME_ALIASES: dict[str, str] = {
97
+ "now 1-h": "now 1-H",
98
+ "now 4-h": "now 4-H",
99
+ "now 1-d": "now 1-d",
100
+ "now 7-d": "now 7-d",
101
+ "today 1-d": "now 1-d",
102
+ "today 7-d": "now 7-d",
103
+ "today 1-m": "today 1-m",
104
+ "today 3-m": "today 3-m",
105
+ "today 12-m": "today 12-m",
106
+ "today 1-y": "today 12-m",
107
+ "today 5-y": "today 5-y",
108
+ "1h": "now 1-H",
109
+ "4h": "now 4-H",
110
+ "1d": "now 1-d",
111
+ "24h": "now 1-d",
112
+ "7d": "now 7-d",
113
+ "30d": "today 1-m",
114
+ "1m": "today 1-m",
115
+ "90d": "today 3-m",
116
+ "3m": "today 3-m",
117
+ "12m": "today 12-m",
118
+ "1y": "today 12-m",
119
+ "5y": "today 5-y",
120
+ "all": "all",
121
+ }
122
+
123
+ GPROP_ALIASES: dict[str, str] = {
124
+ "": "web",
125
+ "web": "web",
126
+ "images": "images",
127
+ "image": "images",
128
+ "news": "news",
129
+ "froogle": "froogle",
130
+ "shopping": "froogle",
131
+ "google shopping": "froogle",
132
+ "youtube": "youtube",
133
+ "yt": "youtube",
134
+ }
135
+
136
+ _VALID_GOOGLE_TLD_SUFFIXES: frozenset[str] = frozenset(
137
+ {
138
+ "com", "ad", "ae", "al", "am", "as", "at", "az", "ba", "be", "bf", "bg", "bi", "bj",
139
+ "bs", "bt", "by", "ca", "cat", "cd", "cf", "cg", "ch", "ci", "cl", "cm", "cn", "cv",
140
+ "cz", "de", "dj", "dk", "dm", "dz", "ee", "es", "fi", "fm", "fr", "ga", "ge", "gg",
141
+ "gl", "gm", "gr", "gy", "hn", "hr", "ht", "hu", "ie", "im", "iq", "is", "it", "je",
142
+ "jo", "kg", "ki", "kz", "la", "li", "lk", "lt", "lu", "lv", "md", "me", "mg", "mk",
143
+ "ml", "mn", "mu", "mv", "mw", "ne", "nl", "no", "nr", "nu", "pl", "pn", "ps", "pt",
144
+ "ro", "rs", "ru", "rw", "sc", "se", "sh", "si", "sk", "sm", "sn", "so", "sr", "st",
145
+ "td", "tg", "tl", "tm", "tn", "to", "tt", "vg", "vu",
146
+ "co.ao", "co.bw", "co.ck", "co.cr", "co.id", "co.il", "co.in", "co.jp", "co.ke",
147
+ "co.kr", "co.ls", "co.ma", "co.mz", "co.nz", "co.th", "co.tz", "co.ug", "co.uk",
148
+ "co.uz", "co.ve", "co.vi", "co.za", "co.zm", "co.zw",
149
+ "com.af", "com.ag", "com.ai", "com.ar", "com.au", "com.bd", "com.bh", "com.bn",
150
+ "com.bo", "com.br", "com.bz", "com.co", "com.cu", "com.cy", "com.do", "com.ec",
151
+ "com.eg", "com.et", "com.fj", "com.gh", "com.gi", "com.gt", "com.hk", "com.jm",
152
+ "com.kh", "com.kw", "com.lb", "com.ly", "com.mm", "com.mt", "com.mx", "com.my",
153
+ "com.na", "com.ng", "com.ni", "com.np", "com.om", "com.pa", "com.pe", "com.pg",
154
+ "com.ph", "com.pk", "com.pr", "com.py", "com.qa", "com.sa", "com.sb", "com.sg",
155
+ "com.sl", "com.sv", "com.tj", "com.tr", "com.tw", "com.ua", "com.uy", "com.vc",
156
+ "com.vn",
157
+ }
158
+ )
159
+
160
+ _CUSTOM_DATE_RANGE_RE = re.compile(
161
+ r"^(\d{4}-\d{2}-\d{2}(?:T\d{2})?)\s*(?:to|until|-|\s)\s*(\d{4}-\d{2}-\d{2}(?:T\d{2})?)$",
162
+ re.IGNORECASE,
163
+ )
164
+ _SUBREGION_GEO_RE = re.compile(r"^[A-Z]{2}-[A-Z0-9]{1,4}(?:-[0-9]{1,4})?$")
165
+ _ISO2_RE = re.compile(r"^[A-Z]{2}$")
166
+
167
+ ACTOR_TRENDS_SCRAPER = "unitbytes/google-trends-scraper"
168
+ ACTOR_TRENDS_API = "unitbytes/google-trends-api"
169
+ ACTOR_TRENDING_NOW = "unitbytes/google-trending-now-scraper"
170
+ ACTOR_YOUTUBE_TRENDS = "unitbytes/youtube-trends-scraper"
171
+ ACTOR_SHOPPING_TRENDS = "unitbytes/google-shopping-trends-scraper"
172
+
173
+
174
+ def _normalize_keywords(keywords: Sequence[str] | str, *, max_count: int = 100) -> list[str]:
175
+ raw_list: list[str] = []
176
+ if isinstance(keywords, str):
177
+ raw_list.extend(part.strip() for part in keywords.split(",") if part.strip())
178
+ else:
179
+ for item in keywords:
180
+ cleaned = str(item or "").strip()
181
+ if cleaned:
182
+ raw_list.append(cleaned)
183
+ deduped: list[str] = []
184
+ seen: set[str] = set()
185
+ for kw in raw_list:
186
+ if kw not in seen:
187
+ seen.add(kw)
188
+ deduped.append(kw)
189
+ if not deduped:
190
+ raise ValueError("At least one non-empty keyword is required.")
191
+ if len(deduped) > max_count:
192
+ raise ValueError(f"Too many keywords ({len(deduped)}). Maximum supported is {max_count}.")
193
+ return deduped
194
+
195
+
196
+ def resolve_pn_to_geo(pn: str | None) -> str:
197
+ """Resolve a classic `pytrends.trending_searches(pn=...)` slug or ISO code to 2-letter ISO geo."""
198
+ raw = str(pn or "united_states").strip()
199
+ if not raw:
200
+ return "US"
201
+ slug = re.sub(r"[\s-]+", "_", raw.lower())
202
+ if slug in PYTRENDS_PN_TO_ISO2:
203
+ return PYTRENDS_PN_TO_ISO2[slug]
204
+ upper = raw.upper()
205
+ if _ISO2_RE.fullmatch(upper) or _SUBREGION_GEO_RE.fullmatch(upper):
206
+ return upper
207
+ raise ValueError(
208
+ f"Unsupported trending_searches pn={pn!r}. Pass a country slug like 'united_states' or ISO code like 'US'."
209
+ )
210
+
211
+
212
+ def normalize_geo_input(geo: str | None) -> tuple[str, str, str]:
213
+ """Normalize `geo` into `(geo_selection_type, common_geo, custom_geo_code)`."""
214
+ cleaned = str(geo or "").strip()
215
+ if not cleaned or cleaned.upper() in {"WORLDWIDE", "GLOBAL", "ALL"}:
216
+ return ("Common Countries", "WORLDWIDE", "")
217
+
218
+ slug = re.sub(r"[\s-]+", "_", cleaned.lower())
219
+ if slug in PYTRENDS_PN_TO_ISO2:
220
+ return ("Common Countries", PYTRENDS_PN_TO_ISO2[slug], "")
221
+
222
+ upper = cleaned.upper()
223
+ if _SUBREGION_GEO_RE.fullmatch(upper):
224
+ return ("Custom Geo Code", upper[:2], upper)
225
+ if _ISO2_RE.fullmatch(upper):
226
+ return ("Common Countries", upper, "")
227
+
228
+ raise ValueError(
229
+ f"Invalid geo={geo!r}. Expected '' / 'WORLDWIDE', 2-letter ISO code ('US', 'GB'), or sub-region ('US-NY')."
230
+ )
231
+
232
+
233
+ def normalize_timeframe_input(timeframe: str | None) -> tuple[str, str, str]:
234
+ """Normalize `pytrends` or custom timeframe into `(timeframe_type, predefined_timeframe, custom_timeframe)`."""
235
+ raw = str(timeframe or "today 12-m").strip()
236
+ if not raw:
237
+ return ("predefined", "today 12-m", "")
238
+
239
+ mapped = TIMEFRAME_ALIASES.get(raw.lower(), raw)
240
+ if mapped in VALID_PREDEFINED_TIMEFRAMES:
241
+ return ("predefined", mapped, "")
242
+
243
+ m_range = _CUSTOM_DATE_RANGE_RE.fullmatch(raw)
244
+ if m_range:
245
+ return ("custom", "today 12-m", f"{m_range.group(1)} {m_range.group(2)}")
246
+
247
+ if re.fullmatch(r"(?:today|now|\d{4}-\d{2}-\d{2})\s+\d+-[hdwmyHDWMY]", raw):
248
+ return ("predefined", raw, "")
249
+
250
+ raise ValueError(
251
+ f"Unsupported timeframe={timeframe!r}. Use a predefined range ('now 1-H', 'now 4-H', 'now 1-d', "
252
+ "'now 7-d', 'today 1-m', 'today 3-m', 'today 12-m', 'today 5-y', 'all') or 'YYYY-MM-DD YYYY-MM-DD'."
253
+ )
254
+
255
+
256
+ def normalize_gprop_input(gprop: str | None) -> str:
257
+ """Normalize Google Trends search property (`''`/`'web'`, `'images'`, `'news'`, `'froogle'`, `'youtube'`)."""
258
+ key = str(gprop or "").strip().lower()
259
+ if key not in GPROP_ALIASES:
260
+ raise ValueError(
261
+ f"Unsupported gprop={gprop!r}. Expected '', 'web', 'images', 'news', 'froogle' ('shopping'), or 'youtube'."
262
+ )
263
+ return GPROP_ALIASES[key]
264
+
265
+
266
+ def normalize_language_code(hl: str | None) -> str:
267
+ """Extract primary ISO language tag from `hl` (e.g. `'en-US'` -> `'en'`)."""
268
+ cleaned = str(hl or "en").strip()
269
+ if not cleaned:
270
+ return "en"
271
+ primary = cleaned.split("-")[0].split("_")[0].strip().lower()
272
+ return primary or "en"
273
+
274
+
275
+ def validate_trends_url(raw_url: str) -> str:
276
+ """Validate an `https://trends.google.com` URL (HTTPS only, port 443, no embedded credentials)."""
277
+ cleaned = str(raw_url or "").strip()
278
+ if not cleaned:
279
+ raise ValueError("Google Trends URL cannot be empty.")
280
+ if any(ch.isspace() or ord(ch) < 32 for ch in cleaned):
281
+ raise ValueError("Google Trends URL must not contain whitespace or control characters.")
282
+ parsed = urlparse(cleaned)
283
+ if parsed.scheme.lower() != "https":
284
+ raise ValueError(f"Google Trends URL must use https://, got {raw_url!r}.")
285
+ if parsed.username or parsed.password or "@" in (parsed.netloc or ""):
286
+ raise ValueError("Google Trends URL must not contain embedded credentials.")
287
+ if parsed.port not in (None, 443):
288
+ raise ValueError("Google Trends URL port must be 443 (or omitted).")
289
+ host = (parsed.hostname or "").lower().rstrip(".")
290
+ path_low = (parsed.path or "").lower()
291
+
292
+ is_trends_host = (
293
+ host.startswith("trends.google.")
294
+ and host[len("trends.google.") :] in _VALID_GOOGLE_TLD_SUFFIXES
295
+ )
296
+ is_main_google_trends_path = host in {"google.com", "www.google.com"} and (
297
+ path_low == "/trends" or path_low.startswith("/trends/")
298
+ )
299
+ if not (is_trends_host or is_main_google_trends_path):
300
+ raise ValueError(f"Expected an https://trends.google.com URL, got host {host!r}.")
301
+ return cleaned
302
+
303
+
304
+ def unwrap_trends_items(raw: Any, expected_section: str | None = None) -> list[dict[str, Any]]:
305
+ """Unwrap flat PPE rows, `/v1/trends/*` gateway envelopes, or legacy `{scrape_type, data}` envelopes."""
306
+ if isinstance(raw, Mapping) and "data" in raw and isinstance(raw.get("data"), (list, Mapping)):
307
+ data_field = raw["data"]
308
+ if isinstance(data_field, list):
309
+ return [dict(r) for r in data_field if isinstance(r, Mapping) and not r.get("error")]
310
+ if isinstance(data_field, Mapping):
311
+ if "items" in data_field and isinstance(data_field["items"], list):
312
+ return [dict(r) for r in data_field["items"] if isinstance(r, Mapping) and not r.get("error")]
313
+ if expected_section and isinstance(data_field.get(expected_section), list):
314
+ return [dict(r) for r in data_field[expected_section] if isinstance(r, Mapping)]
315
+ merged: list[dict[str, Any]] = []
316
+ for sec_name, sec_rows in data_field.items():
317
+ if isinstance(sec_rows, list):
318
+ for sec_row in sec_rows:
319
+ if isinstance(sec_row, Mapping):
320
+ merged.append({"scrape_type": sec_name, **sec_row})
321
+ return merged
322
+
323
+ rows = unwrap_items_payload(raw)
324
+ if len(rows) == 1 and "data" in rows[0] and isinstance(rows[0].get("data"), (list, Mapping)):
325
+ return unwrap_trends_items(rows[0], expected_section=expected_section)
326
+ return [r for r in rows if not r.get("error")]
327
+
328
+
329
+ def pivot_interest_over_time(items: Any, keywords: Sequence[str]) -> list[dict[str, Any]]:
330
+ """Convert flat `{date, keyword, value, isPartial}` rows (or wide rows) into ordered wide timeline dicts."""
331
+ unwrapped = unwrap_trends_items(items, expected_section="interest_over_time")
332
+ if not unwrapped:
333
+ return []
334
+
335
+ if "keyword" not in unwrapped[0] and any(kw in unwrapped[0] for kw in keywords):
336
+ return unwrapped
337
+
338
+ by_date: dict[str, dict[str, Any]] = {}
339
+ for row in unwrapped:
340
+ if row.get("scrape_type") and row.get("scrape_type") != "interest_over_time":
341
+ continue
342
+ dt = str(row.get("date") or row.get("timestamp") or "").strip()
343
+ kw = str(row.get("keyword") or "").strip()
344
+ if not dt or not kw:
345
+ continue
346
+ if dt not in by_date:
347
+ entry: dict[str, Any] = {"date": dt}
348
+ for k in keywords:
349
+ entry[k] = 0
350
+ entry["isPartial"] = bool(row.get("isPartial", False))
351
+ by_date[dt] = entry
352
+ by_date[dt][kw] = row.get("value", 0)
353
+ if row.get("isPartial") is not None:
354
+ by_date[dt]["isPartial"] = bool(row.get("isPartial"))
355
+
356
+ return list(by_date.values())
357
+
358
+
359
+ def pivot_interest_by_region(
360
+ items: Any,
361
+ keywords: Sequence[str],
362
+ *,
363
+ inc_geo_code: bool = False,
364
+ ) -> list[dict[str, Any]]:
365
+ """Convert flat `{geoName, geoCode, keyword, value}` rows into wide regional dicts."""
366
+ unwrapped = unwrap_trends_items(items, expected_section="interest_by_region")
367
+ if not unwrapped:
368
+ return []
369
+
370
+ if "keyword" not in unwrapped[0] and "geoName" in unwrapped[0]:
371
+ out_legacy: list[dict[str, Any]] = []
372
+ for row in unwrapped:
373
+ entry: dict[str, Any] = {"geoName": row.get("geoName")}
374
+ if inc_geo_code and row.get("geoCode") is not None:
375
+ entry["geoCode"] = row.get("geoCode")
376
+ for k in keywords:
377
+ entry[k] = row.get(k, 0)
378
+ out_legacy.append(entry)
379
+ return out_legacy
380
+
381
+ by_geo: dict[str, dict[str, Any]] = {}
382
+ for row in unwrapped:
383
+ if row.get("scrape_type") and row.get("scrape_type") != "interest_by_region":
384
+ continue
385
+ gname = str(row.get("geoName") or "").strip()
386
+ kw = str(row.get("keyword") or "").strip()
387
+ if not gname or not kw:
388
+ continue
389
+ if gname not in by_geo:
390
+ entry = {"geoName": gname}
391
+ if inc_geo_code:
392
+ entry["geoCode"] = row.get("geoCode") or ""
393
+ for k in keywords:
394
+ entry[k] = 0
395
+ by_geo[gname] = entry
396
+ elif inc_geo_code and row.get("geoCode") and not by_geo[gname].get("geoCode"):
397
+ by_geo[gname]["geoCode"] = row.get("geoCode")
398
+ by_geo[gname][kw] = row.get("value", 0)
399
+
400
+ return list(by_geo.values())
401
+
402
+
403
+ def group_related_records(
404
+ items: Any,
405
+ keywords: Sequence[str],
406
+ *,
407
+ kind: Literal["queries", "topics"] = "queries",
408
+ ) -> dict[str, dict[str, list[dict[str, Any]]]]:
409
+ """Organize related_queries / related_topics rows into `{kw: {'top': [...], 'rising': [...]}}`."""
410
+ expected_st = "related_queries" if kind == "queries" else "related_topics"
411
+ label_key = "query" if kind == "queries" else "topic_title"
412
+ default_kw = keywords[0] if keywords else ""
413
+
414
+ grouped: dict[str, dict[str, list[dict[str, Any]]]] = {
415
+ kw: {"top": [], "rising": []} for kw in keywords
416
+ }
417
+
418
+ unwrapped = unwrap_trends_items(items, expected_section=expected_st)
419
+ for row in unwrapped:
420
+ if ("top" in row or "rising" in row) and "subset" not in row:
421
+ for sub in ("top", "rising"):
422
+ sub_list = row.get(sub)
423
+ if isinstance(sub_list, list):
424
+ for rec in sub_list:
425
+ if not isinstance(rec, Mapping):
426
+ continue
427
+ orig_kw = str(rec.get("original_keyword") or default_kw)
428
+ grouped.setdefault(orig_kw, {"top": [], "rising": []})
429
+ clean_rec = {k: v for k, v in rec.items() if k != "original_keyword"}
430
+ grouped[orig_kw][sub].append(clean_rec)
431
+ continue
432
+
433
+ if row.get("scrape_type") and row.get("scrape_type") != expected_st:
434
+ continue
435
+ subset = str(row.get("subset") or "top").strip().lower()
436
+ if subset not in {"top", "rising"}:
437
+ subset = "top"
438
+ orig_kw = str(row.get("original_keyword") or row.get("keyword") or default_kw).strip()
439
+ if not orig_kw:
440
+ continue
441
+ grouped.setdefault(orig_kw, {"top": [], "rising": []})
442
+
443
+ rel_val = row.get("related_keyword") or row.get(label_key) or row.get("title") or ""
444
+ entry: dict[str, Any] = {
445
+ label_key: rel_val,
446
+ "value": row.get("value"),
447
+ }
448
+ for extra_k in ("topic_type", "topic_mid", "link"):
449
+ if row.get(extra_k) is not None:
450
+ entry[extra_k] = row[extra_k]
451
+ grouped[orig_kw][subset].append(entry)
452
+
453
+ return grouped
454
+
455
+
456
+ def parse_growth_score(raw_value: Any) -> tuple[float, bool]:
457
+ """Parse a Google Trends rising `value` or `volume_growth_pct` into `(numeric_pct, is_breakout)`."""
458
+ if raw_value is None or isinstance(raw_value, bool):
459
+ return (0.0, False)
460
+ if isinstance(raw_value, (int, float)):
461
+ val = float(raw_value)
462
+ return (val, val >= 5000.0)
463
+ text = str(raw_value).strip()
464
+ if not text:
465
+ return (0.0, False)
466
+ if "breakout" in text.lower():
467
+ return (5000.0, True)
468
+ cleaned = text.replace(",", "").replace("+", "").replace("%", "").strip()
469
+ m = re.search(r"-?\d+(?:\.\d+)?", cleaned)
470
+ if not m:
471
+ return (0.0, False)
472
+ val = float(m.group(0))
473
+ return (val, val >= 5000.0)
474
+
475
+
476
+ def extract_breakout_queries(
477
+ items: Sequence[Mapping[str, Any]],
478
+ *,
479
+ min_growth_pct: float = 500.0,
480
+ ) -> list[dict[str, Any]]:
481
+ """Filter and rank surging `Breakout` (`+5,000%`) and high-growth rising queries/topics/trends."""
482
+ out: list[dict[str, Any]] = []
483
+ for row in items:
484
+ if not isinstance(row, Mapping) or row.get("error"):
485
+ continue
486
+ if "is_breakout" in row and "growth_pct" in row:
487
+ pct = float(row.get("growth_pct") or 0.0)
488
+ is_bo = bool(row.get("is_breakout")) or pct >= 5000.0
489
+ if pct >= min_growth_pct or is_bo:
490
+ out.append(dict(row))
491
+ continue
492
+
493
+ st = str(row.get("scrape_type") or "")
494
+ if st == "trending_now" or "volume_growth_pct" in row:
495
+ pct, is_breakout = parse_growth_score(row.get("volume_growth_pct"))
496
+ if pct >= min_growth_pct or is_breakout:
497
+ out.append(
498
+ {
499
+ "source_type": "trending_now",
500
+ "seed_keyword": None,
501
+ "term": row.get("keyword") or row.get("query") or row.get("title"),
502
+ "growth_pct": pct,
503
+ "is_breakout": is_breakout,
504
+ "volume": row.get("volume"),
505
+ "geo": row.get("geo"),
506
+ }
507
+ )
508
+ continue
509
+
510
+ subset = str(row.get("subset") or "").lower()
511
+ if subset and subset != "rising":
512
+ continue
513
+ pct, is_breakout = parse_growth_score(row.get("value"))
514
+ if pct >= min_growth_pct or is_breakout:
515
+ out.append(
516
+ {
517
+ "source_type": st or "related_queries",
518
+ "seed_keyword": row.get("original_keyword") or row.get("keyword"),
519
+ "term": row.get("related_keyword") or row.get("query") or row.get("topic_title"),
520
+ "growth_pct": pct,
521
+ "is_breakout": is_breakout,
522
+ "raw_value": row.get("value"),
523
+ }
524
+ )
525
+
526
+ out.sort(key=lambda r: (0 if r.get("is_breakout") else 1, -float(r.get("growth_pct") or 0.0)))
527
+ return out
528
+
529
+
530
+ def maybe_to_timeline_df(wide_rows: list[dict[str, Any]], keywords: Sequence[str], *, use_df: bool) -> Any:
531
+ if not use_df:
532
+ return wide_rows
533
+ pd = require_pandas()
534
+ if not wide_rows:
535
+ return pd.DataFrame()
536
+ df = pd.DataFrame(wide_rows)
537
+ if "date" in df.columns:
538
+ try:
539
+ df["date"] = pd.to_datetime(df["date"])
540
+ except (ValueError, TypeError):
541
+ pass
542
+ df = df.set_index("date")
543
+ ordered_cols = [k for k in keywords if k in df.columns]
544
+ if "isPartial" in df.columns:
545
+ ordered_cols.append("isPartial")
546
+ remaining = [c for c in df.columns if c not in ordered_cols]
547
+ return df[ordered_cols + remaining]
548
+
549
+
550
+ def maybe_to_region_df(
551
+ wide_rows: list[dict[str, Any]],
552
+ keywords: Sequence[str],
553
+ *,
554
+ inc_geo_code: bool,
555
+ use_df: bool,
556
+ ) -> Any:
557
+ if not use_df:
558
+ return wide_rows
559
+ pd = require_pandas()
560
+ if not wide_rows:
561
+ return pd.DataFrame()
562
+ df = pd.DataFrame(wide_rows)
563
+ if "geoName" in df.columns:
564
+ df = df.set_index("geoName")
565
+ ordered_cols: list[str] = []
566
+ if inc_geo_code and "geoCode" in df.columns:
567
+ ordered_cols.append("geoCode")
568
+ ordered_cols.extend(k for k in keywords if k in df.columns)
569
+ remaining = [c for c in df.columns if c not in ordered_cols]
570
+ return df[ordered_cols + remaining]
571
+
572
+
573
+ def maybe_to_related_dfs(
574
+ grouped: dict[str, dict[str, list[dict[str, Any]]]],
575
+ *,
576
+ use_df: bool,
577
+ ) -> Any:
578
+ if not use_df:
579
+ return grouped
580
+ pd = require_pandas()
581
+ converted: dict[str, dict[str, Any]] = {}
582
+ for kw, subsets in grouped.items():
583
+ top_rows = subsets.get("top") or []
584
+ rising_rows = subsets.get("rising") or []
585
+ converted[kw] = {
586
+ "top": pd.DataFrame(top_rows) if top_rows else None,
587
+ "rising": pd.DataFrame(rising_rows) if rising_rows else None,
588
+ }
589
+ return converted
590
+
591
+
592
+ def maybe_to_trending_searches_df(items: list[dict[str, Any]], *, use_df: bool) -> Any:
593
+ if not use_df:
594
+ return items
595
+ pd = require_pandas()
596
+ terms = [
597
+ str(r.get("keyword") or r.get("title") or r.get("query") or "").strip()
598
+ for r in items
599
+ if str(r.get("keyword") or r.get("title") or r.get("query") or "").strip()
600
+ ]
601
+ if not terms:
602
+ return pd.DataFrame(columns=[0])
603
+ return pd.DataFrame({0: terms})
604
+
605
+
606
+ class TrendsNamespace:
607
+ """Google Trends intelligence methods (`ub.trends`)."""
608
+
609
+ def __init__(self, client: UnitBytes) -> None:
610
+ self._client = client
611
+
612
+ def _build_keyword_run_input(
613
+ self,
614
+ keywords: Sequence[str] | str,
615
+ *,
616
+ scrape_type: str,
617
+ scrape_types: Sequence[str] | None = None,
618
+ timeframe: str = "today 12-m",
619
+ geo: str = "US",
620
+ geo_resolution: GeoResolution = "COUNTRY",
621
+ inc_low_vol: bool = False,
622
+ gprop: str = "web",
623
+ category: int = 0,
624
+ compare_keywords: bool = True,
625
+ language: str = "en",
626
+ trends_urls: Sequence[str] | None = None,
627
+ max_events: int = 2000,
628
+ ) -> tuple[list[str], dict[str, Any], dict[str, Any]]:
629
+ max_kw_cap = 5 if compare_keywords else 100
630
+ kw_list = _normalize_keywords(keywords, max_count=max_kw_cap)
631
+ tf_type, pre_tf, cust_tf = normalize_timeframe_input(timeframe)
632
+ geo_sel_type, common_geo, custom_geo = normalize_geo_input(geo)
633
+ norm_gprop = normalize_gprop_input(gprop)
634
+ lang_iso = normalize_language_code(language)
635
+ validated_urls = [validate_trends_url(u) for u in (trends_urls or []) if str(u).strip()]
636
+
637
+ actor_payload: dict[str, Any] = {
638
+ "scrape_type": scrape_type,
639
+ "keywords": kw_list,
640
+ "compare_keywords": bool(compare_keywords),
641
+ "gprop": norm_gprop,
642
+ "category": max(0, int(category)),
643
+ "timeframe_type": tf_type,
644
+ "predefined_timeframe": pre_tf,
645
+ "geo_selection_type": geo_sel_type,
646
+ "common_geo": common_geo,
647
+ "geo_resolution": geo_resolution.strip().upper(),
648
+ "inc_low_vol": bool(inc_low_vol),
649
+ "trending_language": lang_iso,
650
+ "output_format": "flat",
651
+ "max_events": max(1, min(10000, int(max_events))),
652
+ }
653
+ if cust_tf:
654
+ actor_payload["custom_timeframe"] = cust_tf
655
+ if custom_geo:
656
+ actor_payload["custom_geo_code"] = custom_geo
657
+ if scrape_types:
658
+ actor_payload["scrape_types"] = list(scrape_types)
659
+ if validated_urls:
660
+ actor_payload["trends_urls"] = validated_urls
661
+
662
+ rest_geo = custom_geo or ("" if common_geo == "WORLDWIDE" else common_geo)
663
+ rest_params: dict[str, Any] = {
664
+ "keywords": ",".join(kw_list),
665
+ "timeframe": cust_tf or pre_tf,
666
+ "geo": rest_geo,
667
+ "category": max(0, int(category)) or None,
668
+ "gprop": norm_gprop,
669
+ "language": lang_iso,
670
+ }
671
+ return kw_list, actor_payload, rest_params
672
+
673
+ def trending_now(
674
+ self,
675
+ *,
676
+ geo: str = "US",
677
+ time_window: TrendingTimeWindow = "24h",
678
+ hours: int | None = None,
679
+ trending_hours: int | None = None,
680
+ category: int = 0,
681
+ language: str = "en",
682
+ trends_urls: Sequence[str] | None = None,
683
+ max_events: int = 200,
684
+ max_total_charge_usd: float | Decimal | None = None,
685
+ ) -> list[dict[str, Any]]:
686
+ """Fetch real-time viral searches, search volume, growth %, and related news."""
687
+ _, common_geo, custom_geo = normalize_geo_input(geo or "US")
688
+ if common_geo == "WORLDWIDE" and not custom_geo:
689
+ common_geo = "US"
690
+
691
+ effective_hours = hours if hours is not None else trending_hours
692
+ resolved_window: str = time_window
693
+ if effective_hours in (4, 24, 48, 168) and time_window == "24h":
694
+ resolved_window = {4: "4h", 24: "24h", 48: "48h", 168: "7d"}[int(effective_hours)]
695
+
696
+ lang_iso = normalize_language_code(language)
697
+ actor_input: dict[str, Any] = {
698
+ "common_geo": common_geo,
699
+ "time_window": resolved_window,
700
+ "trending_language": lang_iso,
701
+ "output_format": "flat",
702
+ "max_events": max(1, min(10000, int(max_events))),
703
+ }
704
+ if custom_geo:
705
+ actor_input["custom_geo_code"] = custom_geo
706
+ if effective_hours is not None:
707
+ if effective_hours < 1 or effective_hours > 191:
708
+ raise ValueError(f"trending_hours must be between 1 and 191, got {effective_hours}.")
709
+ actor_input["trending_hours"] = int(effective_hours)
710
+ if trends_urls:
711
+ actor_input["trends_urls"] = [validate_trends_url(u) for u in trends_urls if str(u).strip()]
712
+
713
+ hours_map = {"4h": 4, "24h": 24, "48h": 48, "7d": 168}
714
+ rest_params: dict[str, Any] = {
715
+ "geo": custom_geo or common_geo,
716
+ "hours": int(effective_hours) if effective_hours is not None else hours_map.get(resolved_window, 24),
717
+ "category": int(category) if category else None,
718
+ "page_size": min(60, max(1, int(max_events))),
719
+ "language": lang_iso,
720
+ }
721
+
722
+ raw = self._client._transport.execute_operation(
723
+ service="trends",
724
+ operation="trending-now",
725
+ actor_slug=ACTOR_TRENDING_NOW,
726
+ actor_input=actor_input,
727
+ http_method="GET",
728
+ params=rest_params,
729
+ max_total_charge_usd=max_total_charge_usd,
730
+ )
731
+ return unwrap_trends_items(raw)
732
+
733
+ def interest_over_time(
734
+ self,
735
+ keywords: Sequence[str] | str,
736
+ *,
737
+ timeframe: str = "today 12-m",
738
+ geo: str = "US",
739
+ gprop: str = "web",
740
+ category: int = 0,
741
+ compare_keywords: bool = True,
742
+ language: str = "en",
743
+ max_events: int = 2500,
744
+ as_dataframe: bool = False,
745
+ max_total_charge_usd: float | Decimal | None = None,
746
+ ) -> Any:
747
+ """Fetch historical or real-time Google Trends search interest over time (`0–100`)."""
748
+ if as_dataframe:
749
+ require_pandas()
750
+ kw_list, actor_input, rest_params = self._build_keyword_run_input(
751
+ keywords,
752
+ scrape_type="interest_over_time",
753
+ timeframe=timeframe,
754
+ geo=geo,
755
+ gprop=gprop,
756
+ category=category,
757
+ compare_keywords=compare_keywords,
758
+ language=language,
759
+ max_events=max_events,
760
+ )
761
+ raw = self._client._transport.execute_operation(
762
+ service="trends",
763
+ operation="interest-over-time",
764
+ actor_slug=ACTOR_TRENDS_SCRAPER,
765
+ actor_input=actor_input,
766
+ http_method="GET",
767
+ params=rest_params,
768
+ max_total_charge_usd=max_total_charge_usd,
769
+ )
770
+ wide_rows = pivot_interest_over_time(raw, kw_list)
771
+ return maybe_to_timeline_df(wide_rows, kw_list, use_df=as_dataframe)
772
+
773
+ def interest_by_region(
774
+ self,
775
+ keywords: Sequence[str] | str,
776
+ *,
777
+ timeframe: str = "today 12-m",
778
+ geo: str = "US",
779
+ geo_resolution: GeoResolution = "REGION",
780
+ inc_low_vol: bool = False,
781
+ inc_geo_code: bool = False,
782
+ gprop: str = "web",
783
+ category: int = 0,
784
+ compare_keywords: bool = True,
785
+ language: str = "en",
786
+ max_events: int = 2500,
787
+ as_dataframe: bool = False,
788
+ max_total_charge_usd: float | Decimal | None = None,
789
+ ) -> Any:
790
+ """Fetch geographic search interest breakdown by `COUNTRY`, `REGION`, `DMA`, or `CITY`."""
791
+ if as_dataframe:
792
+ require_pandas()
793
+ kw_list, actor_input, rest_params = self._build_keyword_run_input(
794
+ keywords,
795
+ scrape_type="interest_by_region",
796
+ timeframe=timeframe,
797
+ geo=geo,
798
+ geo_resolution=geo_resolution,
799
+ inc_low_vol=inc_low_vol,
800
+ gprop=gprop,
801
+ category=category,
802
+ compare_keywords=compare_keywords,
803
+ language=language,
804
+ max_events=max_events,
805
+ )
806
+ rest_params["geo_resolution"] = geo_resolution.strip().upper()
807
+ raw = self._client._transport.execute_operation(
808
+ service="trends",
809
+ operation="interest-by-region",
810
+ actor_slug=ACTOR_TRENDS_SCRAPER,
811
+ actor_input=actor_input,
812
+ http_method="GET",
813
+ params=rest_params,
814
+ max_total_charge_usd=max_total_charge_usd,
815
+ )
816
+ wide_rows = pivot_interest_by_region(raw, kw_list, inc_geo_code=inc_geo_code)
817
+ return maybe_to_region_df(wide_rows, kw_list, inc_geo_code=inc_geo_code, use_df=as_dataframe)
818
+
819
+ def related_queries(
820
+ self,
821
+ keywords: Sequence[str] | str,
822
+ *,
823
+ timeframe: str = "today 12-m",
824
+ geo: str = "US",
825
+ gprop: str = "web",
826
+ category: int = 0,
827
+ compare_keywords: bool = True,
828
+ language: str = "en",
829
+ max_events: int = 1000,
830
+ as_dataframe: bool = False,
831
+ max_total_charge_usd: float | Decimal | None = None,
832
+ ) -> Any:
833
+ """Fetch `top` and `rising` (`Breakout` / `+5,000%`) related search queries per keyword."""
834
+ if as_dataframe:
835
+ require_pandas()
836
+ kw_list, actor_input, rest_params = self._build_keyword_run_input(
837
+ keywords,
838
+ scrape_type="related_queries",
839
+ timeframe=timeframe,
840
+ geo=geo,
841
+ gprop=gprop,
842
+ category=category,
843
+ compare_keywords=compare_keywords,
844
+ language=language,
845
+ max_events=max_events,
846
+ )
847
+ raw = self._client._transport.execute_operation(
848
+ service="trends",
849
+ operation="related-queries",
850
+ actor_slug=ACTOR_TRENDS_SCRAPER,
851
+ actor_input=actor_input,
852
+ http_method="GET",
853
+ params=rest_params,
854
+ max_total_charge_usd=max_total_charge_usd,
855
+ )
856
+ grouped = group_related_records(raw, kw_list, kind="queries")
857
+ return maybe_to_related_dfs(grouped, use_df=as_dataframe)
858
+
859
+ def related_topics(
860
+ self,
861
+ keywords: Sequence[str] | str,
862
+ *,
863
+ timeframe: str = "today 12-m",
864
+ geo: str = "US",
865
+ gprop: str = "web",
866
+ category: int = 0,
867
+ compare_keywords: bool = True,
868
+ language: str = "en",
869
+ max_events: int = 1000,
870
+ as_dataframe: bool = False,
871
+ max_total_charge_usd: float | Decimal | None = None,
872
+ ) -> Any:
873
+ """Fetch `top` and `rising` Knowledge Graph topics per keyword."""
874
+ if as_dataframe:
875
+ require_pandas()
876
+ kw_list, actor_input, rest_params = self._build_keyword_run_input(
877
+ keywords,
878
+ scrape_type="related_topics",
879
+ timeframe=timeframe,
880
+ geo=geo,
881
+ gprop=gprop,
882
+ category=category,
883
+ compare_keywords=compare_keywords,
884
+ language=language,
885
+ max_events=max_events,
886
+ )
887
+ raw = self._client._transport.execute_operation(
888
+ service="trends",
889
+ operation="related-topics",
890
+ actor_slug=ACTOR_TRENDS_SCRAPER,
891
+ actor_input=actor_input,
892
+ http_method="GET",
893
+ params=rest_params,
894
+ max_total_charge_usd=max_total_charge_usd,
895
+ )
896
+ grouped = group_related_records(raw, kw_list, kind="topics")
897
+ return maybe_to_related_dfs(grouped, use_df=as_dataframe)
898
+
899
+ def breakouts(
900
+ self,
901
+ keywords: Sequence[str] | str | None = None,
902
+ *,
903
+ timeframe: str = "today 3-m",
904
+ geo: str = "US",
905
+ hours: int = 24,
906
+ gprop: str = "web",
907
+ category: int = 0,
908
+ min_growth_pct: float = 500.0,
909
+ language: str = "en",
910
+ max_total_charge_usd: float | Decimal | None = None,
911
+ ) -> list[dict[str, Any]]:
912
+ """Discover ranked `Breakout` (`+5,000%`) and surging rising queries/trends."""
913
+ if keywords is None:
914
+ _, common_geo, custom_geo = normalize_geo_input(geo or "US")
915
+ if common_geo == "WORLDWIDE" and not custom_geo:
916
+ common_geo = "US"
917
+ lang_iso = normalize_language_code(language)
918
+ actor_input: dict[str, Any] = {
919
+ "common_geo": common_geo,
920
+ "trending_hours": max(1, min(191, int(hours))),
921
+ "trending_language": lang_iso,
922
+ "output_format": "flat",
923
+ "max_events": 200,
924
+ }
925
+ if custom_geo:
926
+ actor_input["custom_geo_code"] = custom_geo
927
+ rest_params = {
928
+ "geo": custom_geo or common_geo,
929
+ "hours": int(hours),
930
+ "category": int(category) if category else None,
931
+ "min_growth_pct": float(min_growth_pct),
932
+ "language": lang_iso,
933
+ }
934
+ raw = self._client._transport.execute_operation(
935
+ service="trends",
936
+ operation="breakouts",
937
+ actor_slug=ACTOR_TRENDING_NOW,
938
+ actor_input=actor_input,
939
+ http_method="GET",
940
+ params=rest_params,
941
+ max_total_charge_usd=max_total_charge_usd,
942
+ )
943
+ return extract_breakout_queries(unwrap_trends_items(raw), min_growth_pct=min_growth_pct)
944
+
945
+ kw_norm = _normalize_keywords(keywords, max_count=100)
946
+ _, actor_input, rest_params = self._build_keyword_run_input(
947
+ kw_norm,
948
+ scrape_type="all",
949
+ scrape_types=["related_queries", "related_topics"],
950
+ timeframe=timeframe,
951
+ geo=geo,
952
+ gprop=gprop,
953
+ category=category,
954
+ compare_keywords=len(kw_norm) <= 5,
955
+ language=language,
956
+ max_events=1500,
957
+ )
958
+ rest_params["min_growth_pct"] = float(min_growth_pct)
959
+ rest_params["hours"] = int(hours)
960
+ raw = self._client._transport.execute_operation(
961
+ service="trends",
962
+ operation="breakouts",
963
+ actor_slug=ACTOR_TRENDS_API,
964
+ actor_input=actor_input,
965
+ http_method="GET",
966
+ params=rest_params,
967
+ max_total_charge_usd=max_total_charge_usd,
968
+ )
969
+ return extract_breakout_queries(unwrap_trends_items(raw), min_growth_pct=min_growth_pct)
970
+
971
+ def youtube_trends(
972
+ self,
973
+ keywords: Sequence[str] | str,
974
+ *,
975
+ scrape_type: Literal["all", "related_queries", "interest_over_time", "interest_by_region", "related_topics"] = "all",
976
+ timeframe: str = "today 12-m",
977
+ geo: str = "US",
978
+ geo_resolution: GeoResolution = "COUNTRY",
979
+ category: int = 0,
980
+ compare_keywords: bool = True,
981
+ language: str = "en",
982
+ max_events: int = 2000,
983
+ max_total_charge_usd: float | Decimal | None = None,
984
+ ) -> list[dict[str, Any]]:
985
+ """Extract YouTube video search demand, breakout creator keywords, and viewer regions."""
986
+ _, actor_input, rest_params = self._build_keyword_run_input(
987
+ keywords,
988
+ scrape_type=scrape_type,
989
+ timeframe=timeframe,
990
+ geo=geo,
991
+ geo_resolution=geo_resolution,
992
+ gprop="youtube",
993
+ category=category,
994
+ compare_keywords=compare_keywords,
995
+ language=language,
996
+ max_events=max_events,
997
+ )
998
+ raw = self._client._transport.execute_operation(
999
+ service="trends",
1000
+ operation="interest-over-time",
1001
+ actor_slug=ACTOR_YOUTUBE_TRENDS,
1002
+ actor_input=actor_input,
1003
+ http_method="GET",
1004
+ params=rest_params,
1005
+ max_total_charge_usd=max_total_charge_usd,
1006
+ )
1007
+ return unwrap_trends_items(raw)
1008
+
1009
+ def shopping_trends(
1010
+ self,
1011
+ keywords: Sequence[str] | str,
1012
+ *,
1013
+ scrape_type: Literal["all", "related_queries", "interest_over_time", "interest_by_region", "related_topics"] = "all",
1014
+ timeframe: str = "today 12-m",
1015
+ geo: str = "US",
1016
+ geo_resolution: GeoResolution = "COUNTRY",
1017
+ category: int = 0,
1018
+ compare_keywords: bool = True,
1019
+ language: str = "en",
1020
+ max_events: int = 2000,
1021
+ max_total_charge_usd: float | Decimal | None = None,
1022
+ ) -> list[dict[str, Any]]:
1023
+ """Extract Google Shopping product demand, seasonal curves, and breakout retail queries."""
1024
+ _, actor_input, rest_params = self._build_keyword_run_input(
1025
+ keywords,
1026
+ scrape_type=scrape_type,
1027
+ timeframe=timeframe,
1028
+ geo=geo,
1029
+ geo_resolution=geo_resolution,
1030
+ gprop="froogle",
1031
+ category=category,
1032
+ compare_keywords=compare_keywords,
1033
+ language=language,
1034
+ max_events=max_events,
1035
+ )
1036
+ raw = self._client._transport.execute_operation(
1037
+ service="trends",
1038
+ operation="interest-over-time",
1039
+ actor_slug=ACTOR_SHOPPING_TRENDS,
1040
+ actor_input=actor_input,
1041
+ http_method="GET",
1042
+ params=rest_params,
1043
+ max_total_charge_usd=max_total_charge_usd,
1044
+ )
1045
+ return unwrap_trends_items(raw)
1046
+
1047
+
1048
+ class TrendReq:
1049
+ """Unofficial 1-line drop-in compatibility replacement for archived `pytrends.request.TrendReq`.
1050
+
1051
+ Supports all 4 `unitbytes` backends (`apify`, `cloud`, `rapidapi`, `zyla`) and optional `pandas.DataFrame`
1052
+ conversion when `pandas` is installed (`ImportError` raised if `as_dataframe=True` without `pandas`).
1053
+ """
1054
+
1055
+ def __init__(
1056
+ self,
1057
+ hl: str = "en-US",
1058
+ tz: int = 360,
1059
+ geo: str = "",
1060
+ timeout: tuple[float, float] | int | float = (10, 25),
1061
+ proxies: Any = "",
1062
+ retries: int = 2,
1063
+ backoff_factor: float = 0.5,
1064
+ requests_args: Mapping[str, Any] | None = None,
1065
+ *,
1066
+ api_key: str | None = None,
1067
+ api_token: str | None = None,
1068
+ apify_token: str | None = None,
1069
+ provider: ProviderLiteral = "auto",
1070
+ base_url: str | None = None,
1071
+ rapidapi_host: str | None = None,
1072
+ allow_custom_endpoints: bool = False,
1073
+ transport: Transport | None = None,
1074
+ client: UnitBytes | None = None,
1075
+ as_dataframe: bool | None = None,
1076
+ max_total_charge_usd: float | Decimal | None = None,
1077
+ ) -> None:
1078
+ if as_dataframe is True:
1079
+ require_pandas()
1080
+
1081
+ self.hl = hl
1082
+ self.tz = tz
1083
+ self.geo = geo
1084
+ self.timeout = timeout
1085
+ self.proxies = proxies
1086
+ self.retries = retries
1087
+ self.backoff_factor = backoff_factor
1088
+ self.requests_args = dict(requests_args) if requests_args else {}
1089
+ self._default_as_dataframe = as_dataframe
1090
+
1091
+ if isinstance(timeout, (tuple, list)) and timeout:
1092
+ effective_timeout = max(60, int(max(float(x) for x in timeout)))
1093
+ elif isinstance(timeout, (int, float)):
1094
+ effective_timeout = max(60, int(timeout))
1095
+ else:
1096
+ effective_timeout = 180
1097
+
1098
+ if client is not None:
1099
+ self._ub = client
1100
+ else:
1101
+ from .client import UnitBytes
1102
+
1103
+ resolved_key = api_key if api_key is not None else (api_token if api_token is not None else apify_token)
1104
+ self._ub = UnitBytes(
1105
+ api_key=resolved_key,
1106
+ provider=provider,
1107
+ base_url=base_url,
1108
+ rapidapi_host=rapidapi_host,
1109
+ timeout_secs=effective_timeout,
1110
+ max_total_charge_usd=max_total_charge_usd,
1111
+ allow_custom_endpoints=allow_custom_endpoints,
1112
+ transport=transport,
1113
+ )
1114
+
1115
+ self.kw_list: list[str] = []
1116
+ self.cat: int = 0
1117
+ self.timeframe: str = "today 5-y"
1118
+ self.gprop: str = ""
1119
+
1120
+ def __repr__(self) -> str:
1121
+ return (
1122
+ f"TrendReq(hl={self.hl!r}, tz={self.tz!r}, geo={self.geo!r}, "
1123
+ f"provider={self._ub.provider!r}, api_key='[REDACTED]')"
1124
+ )
1125
+
1126
+ def _resolve_df_flag(self, override: bool | None) -> bool:
1127
+ explicit = override if override is not None else self._default_as_dataframe
1128
+ if explicit is not None:
1129
+ if explicit:
1130
+ require_pandas()
1131
+ return bool(explicit)
1132
+ return try_import_pandas() is not None
1133
+
1134
+ def _require_payload(self) -> None:
1135
+ if not self.kw_list:
1136
+ raise ValueError("Call build_payload(kw_list, ...) before querying keyword endpoints.")
1137
+
1138
+ def build_payload(
1139
+ self,
1140
+ kw_list: Sequence[str] | str,
1141
+ cat: int = 0,
1142
+ timeframe: str = "today 5-y",
1143
+ geo: str = "",
1144
+ gprop: str = "",
1145
+ ) -> None:
1146
+ """Configure keywords, category, timeframe, geo, and property for subsequent `TrendReq` calls."""
1147
+ self.kw_list = _normalize_keywords(kw_list, max_count=100)
1148
+ self.cat = int(cat or 0)
1149
+ self.timeframe = str(timeframe or "today 5-y").strip()
1150
+ if geo != "" or not self.geo:
1151
+ self.geo = str(geo or "").strip()
1152
+ self.gprop = str(gprop or "").strip()
1153
+
1154
+ def interest_over_time(self, *, as_dataframe: bool | None = None) -> Any:
1155
+ self._require_payload()
1156
+ use_df = self._resolve_df_flag(as_dataframe)
1157
+ return self._ub.trends.interest_over_time(
1158
+ self.kw_list,
1159
+ timeframe=self.timeframe,
1160
+ geo=self.geo,
1161
+ gprop=self.gprop,
1162
+ category=self.cat,
1163
+ compare_keywords=len(self.kw_list) <= 5,
1164
+ language=self.hl,
1165
+ as_dataframe=use_df,
1166
+ )
1167
+
1168
+ def interest_by_region(
1169
+ self,
1170
+ resolution: str = "COUNTRY",
1171
+ inc_low_vol: bool = True,
1172
+ inc_geo_code: bool = False,
1173
+ *,
1174
+ as_dataframe: bool | None = None,
1175
+ ) -> Any:
1176
+ self._require_payload()
1177
+ use_df = self._resolve_df_flag(as_dataframe)
1178
+ res_norm = str(resolution or "COUNTRY").strip().upper()
1179
+ if res_norm not in {"COUNTRY", "REGION", "DMA", "CITY"}:
1180
+ raise ValueError(f"Unsupported resolution={resolution!r}. Expected COUNTRY, REGION, DMA, or CITY.")
1181
+ return self._ub.trends.interest_by_region(
1182
+ self.kw_list,
1183
+ timeframe=self.timeframe,
1184
+ geo=self.geo,
1185
+ geo_resolution=res_norm, # type: ignore[arg-type]
1186
+ inc_low_vol=inc_low_vol,
1187
+ inc_geo_code=inc_geo_code,
1188
+ gprop=self.gprop,
1189
+ category=self.cat,
1190
+ compare_keywords=len(self.kw_list) <= 5,
1191
+ language=self.hl,
1192
+ as_dataframe=use_df,
1193
+ )
1194
+
1195
+ def related_queries(self, *, as_dataframe: bool | None = None) -> dict[str, dict[str, Any]]:
1196
+ self._require_payload()
1197
+ use_df = self._resolve_df_flag(as_dataframe)
1198
+ return self._ub.trends.related_queries(
1199
+ self.kw_list,
1200
+ timeframe=self.timeframe,
1201
+ geo=self.geo,
1202
+ gprop=self.gprop,
1203
+ category=self.cat,
1204
+ compare_keywords=len(self.kw_list) <= 5,
1205
+ language=self.hl,
1206
+ as_dataframe=use_df,
1207
+ )
1208
+
1209
+ def related_topics(self, *, as_dataframe: bool | None = None) -> dict[str, dict[str, Any]]:
1210
+ self._require_payload()
1211
+ use_df = self._resolve_df_flag(as_dataframe)
1212
+ return self._ub.trends.related_topics(
1213
+ self.kw_list,
1214
+ timeframe=self.timeframe,
1215
+ geo=self.geo,
1216
+ gprop=self.gprop,
1217
+ category=self.cat,
1218
+ compare_keywords=len(self.kw_list) <= 5,
1219
+ language=self.hl,
1220
+ as_dataframe=use_df,
1221
+ )
1222
+
1223
+ def trending_searches(
1224
+ self,
1225
+ pn: str = "united_states",
1226
+ *,
1227
+ hours: int = 24,
1228
+ as_dataframe: bool | None = None,
1229
+ ) -> Any:
1230
+ use_df = self._resolve_df_flag(as_dataframe)
1231
+ iso_geo = resolve_pn_to_geo(pn)
1232
+ items = self._ub.trends.trending_now(
1233
+ geo=iso_geo,
1234
+ trending_hours=hours,
1235
+ language=self.hl,
1236
+ )
1237
+ return maybe_to_trending_searches_df(items, use_df=use_df)
1238
+
1239
+ def realtime_trending_searches(
1240
+ self,
1241
+ pn: str = "US",
1242
+ *,
1243
+ cat: str = "all",
1244
+ count: int = 100,
1245
+ hours: int = 4,
1246
+ as_dataframe: bool | None = None,
1247
+ ) -> Any:
1248
+ _ = cat
1249
+ use_df = self._resolve_df_flag(as_dataframe)
1250
+ iso_geo = resolve_pn_to_geo(pn)
1251
+ items = self._ub.trends.trending_now(
1252
+ geo=iso_geo,
1253
+ time_window="4h",
1254
+ trending_hours=hours,
1255
+ language=self.hl,
1256
+ max_events=count,
1257
+ )
1258
+ if not use_df:
1259
+ return items
1260
+ pd = require_pandas()
1261
+ return pd.DataFrame(items) if items else pd.DataFrame()
1262
+
1263
+
1264
+ __all__ = [
1265
+ "TrendsNamespace",
1266
+ "TrendReq",
1267
+ "ResponseError",
1268
+ "TooManyRequestsError",
1269
+ "extract_breakout_queries",
1270
+ "pivot_interest_over_time",
1271
+ "pivot_interest_by_region",
1272
+ "group_related_records",
1273
+ "resolve_pn_to_geo",
1274
+ "validate_trends_url",
1275
+ ]