返回 last30days-skill
tiktok.py
根目录 / skills / last30days / scripts / lib / tiktok.py
1 """TikTok search via ScrapeCreators API for /last30days.
2
3 Uses ScrapeCreators REST API to search TikTok by keyword, extract engagement
4 metrics (views, likes, comments, shares), and fetch video transcripts.
5
6 Requires SCRAPECREATORS_API_KEY in config. 100 free API calls, then PAYG.
7 API docs: https://scrapecreators.com/docs
8
9 When the key is missing or ScrapeCreators returns 402, search_and_enrich
10 falls back to web discovery + yt-dlp (lib.shortform_oss).
11 """
12
13 import re
14 import sys
15 import threading
16 import time
17 from typing import Any, Dict, List, Optional, Set
18
19 from . import dates, http, log
20
21 SCRAPECREATORS_BASE = "https://api.scrapecreators.com/v1/tiktok"
22
23
24 def _sc_base() -> str:
25 if SCRAPECREATORS_BASE != "https://api.scrapecreators.com/v1/tiktok":
26 return SCRAPECREATORS_BASE
27 from . import env
28 return f"{env.get_scrapecreators_base_url()}/v1/tiktok"
29
30
31 def _sc_root() -> str:
32 from . import env
33 return env.get_scrapecreators_base_url()
34
35 # Depth configurations: how many results to fetch / captions to extract
36 DEPTH_CONFIG = {
37 "quick": {"results_per_page": 10, "max_captions": 3},
38 "default": {"results_per_page": 20, "max_captions": 5},
39 "deep": {"results_per_page": 40, "max_captions": 8},
40 }
41
42 # Max words to keep from each caption
43 CAPTION_MAX_WORDS = 500
44
45 BUDGET_ERROR = "TikTok timed out: research budget exhausted or cancelled"
46
47 from .query import infer_query_intent
48 from .relevance import token_overlap_relevance as _compute_relevance
49
50
51 def _check_budget(deadline: float | None, cancel: threading.Event | None) -> None:
52 if (cancel is not None and cancel.is_set()) or (
53 deadline is not None and time.monotonic() >= deadline
54 ):
55 raise http.DeadlineExceeded()
56
57
58 def _extract_core_subject(topic: str) -> str:
59 """Extract core subject from verbose query for TikTok search."""
60 from .query import VIRAL_NOISE, extract_core_subject
61 return extract_core_subject(topic, noise=VIRAL_NOISE)
62
63
64 def expand_tiktok_queries(topic: str, depth: str) -> List[str]:
65 """Generate multiple TikTok search queries from a topic.
66
67 Mirrors reddit.py's expand_reddit_queries() pattern:
68 1. Extract core subject (strip noise words)
69 2. Include original topic if different from core
70 3. Add intent-specific OR-joined content-type variants
71 4. Cap by depth: 1 for quick, 2 for default, 3 for deep
72
73 Returns 1-3 query strings depending on depth.
74 """
75 core = _extract_core_subject(topic)
76 queries = [core]
77
78 # Include cleaned original topic as variant if different from core
79 original_clean = topic.strip().rstrip('?!.')
80 if core.lower() != original_clean.lower() and len(original_clean.split()) <= 8:
81 queries.append(original_clean)
82
83 qtype = infer_query_intent(topic)
84
85 # Intent-specific TikTok content-type variants
86 if qtype in ("breaking_news", "opinion"):
87 queries.append(f"{core} edit OR reaction OR trend")
88 elif qtype == "product":
89 queries.append(f"{core} review OR haul OR unboxing")
90 elif qtype == "comparison":
91 queries.append(f"{core} vs OR compared OR which is better")
92 elif qtype == "how_to":
93 queries.append(f"{core} tutorial OR hack OR tip")
94 else:
95 queries.append(f"{core} edit OR reaction OR trend")
96
97 # Deep depth: add viral content variant
98 if depth == "deep":
99 queries.append(f"{core} viral OR fyp OR trending")
100
101 # Cap by depth budget
102 caps = {"quick": 1, "default": 2, "deep": 3}
103 cap = caps.get(depth, 2)
104 return queries[:cap]
105
106
107 def _log(msg: str):
108 log.source_log("TikTok", msg, tty_only=False)
109
110
111 def _parse_date(item: Dict[str, Any]) -> Optional[str]:
112 """Parse date from ScrapeCreators TikTok item to YYYY-MM-DD."""
113 ts = item.get("create_time")
114 if ts:
115 try:
116 return dates.timestamp_to_date(int(ts))
117 except (ValueError, TypeError):
118 pass
119 return None
120
121
122 def _clean_webvtt(text: str) -> str:
123 """Strip WebVTT timestamps and headers from transcript text."""
124 if not text:
125 return ""
126 lines = text.split('\n')
127 cleaned = []
128 for line in lines:
129 line = line.strip()
130 if not line:
131 continue
132 if line.startswith('WEBVTT'):
133 continue
134 if re.match(r'^\d{2}:\d{2}', line):
135 continue
136 if '-->' in line:
137 continue
138 cleaned.append(line)
139 return ' '.join(cleaned)
140
141
142 def _parse_items(raw_items: List[Dict[str, Any]], core_topic: str) -> List[Dict[str, Any]]:
143 """Parse raw TikTok items into normalized dicts."""
144 items = []
145 for raw in raw_items:
146 video_id = str(raw.get("aweme_id", ""))
147 text = raw.get("desc", "")
148
149 stats = raw.get("statistics") if isinstance(raw.get("statistics"), dict) else {}
150 play_count = stats.get("play_count")
151 digg_count = stats.get("digg_count") if stats.get("digg_count") is not None else 0
152 comment_count = stats.get("comment_count") if stats.get("comment_count") is not None else 0
153 share_count = stats.get("share_count") if stats.get("share_count") is not None else 0
154
155 author_raw = raw.get("author")
156 if isinstance(author_raw, dict):
157 author_name = author_raw.get("unique_id", "")
158 elif isinstance(author_raw, str):
159 author_name = author_raw
160 else:
161 author_name = ""
162
163 share_url = raw.get("share_url", "")
164 text_extra = raw.get("text_extra") or []
165 hashtag_names = [t.get("hashtag_name", "") for t in text_extra
166 if isinstance(t, dict) and t.get("hashtag_name")]
167
168 video_raw = raw.get("video")
169 duration = video_raw.get("duration") if isinstance(video_raw, dict) else None
170
171 date_str = _parse_date(raw)
172
173 # Compute relevance with hashtag boost
174 relevance = _compute_relevance(core_topic, text, hashtag_names)
175
176 # Build URL: prefer share_url, fallback to constructed URL
177 url = share_url.split("?")[0] if share_url else ""
178 if not url and author_name and video_id:
179 url = f"https://www.tiktok.com/@{author_name}/video/{video_id}"
180
181 items.append({
182 "video_id": video_id,
183 "text": text,
184 "url": url,
185 "author_name": author_name,
186 "date": date_str,
187 "engagement": {
188 "views": play_count,
189 "likes": digg_count,
190 "comments": comment_count,
191 "shares": share_count,
192 },
193 "hashtags": hashtag_names,
194 "duration": duration,
195 "relevance": relevance,
196 "why_relevant": f"TikTok: {text[:60]}" if text else f"TikTok: {core_topic}",
197 "caption_snippet": "", # populated by fetch_captions
198 })
199 return items
200
201
202 def _hashtag_search(
203 hashtag: str,
204 token: str,
205 *,
206 deadline: float | None = None,
207 cancel: threading.Event | None = None,
208 ) -> List[Dict[str, Any]]:
209 """Search TikTok by hashtag via ScrapeCreators.
210
211 Args:
212 hashtag: Hashtag name (without #)
213 token: ScrapeCreators API key
214
215 Returns:
216 List of raw TikTok item dicts (aweme_info format).
217 """
218 _check_budget(deadline, cancel)
219 _log(f"Hashtag search: #{hashtag}")
220 try:
221 data = http.get(
222 f"{_sc_base()}/search/hashtag",
223 params={"hashtag": hashtag},
224 headers=http.scrapecreators_headers(token),
225 timeout=30,
226 retries=2,
227 deadline_monotonic=deadline,
228 cancel=cancel,
229 )
230 except http.DeadlineExceeded:
231 raise
232 except Exception as e:
233 _log(f"Hashtag search error for #{hashtag}: {e}")
234 return []
235
236 raw_items = data.get("aweme_list") or data.get("data") or []
237 _log(f" -> {len(raw_items)} results for #{hashtag}")
238 return raw_items
239
240
241 def _profile_videos(
242 handle: str,
243 token: str,
244 count: int = 10,
245 *,
246 deadline: float | None = None,
247 cancel: threading.Event | None = None,
248 ) -> List[Dict[str, Any]]:
249 """Fetch a TikTok creator's recent videos via ScrapeCreators.
250
251 Args:
252 handle: TikTok username (without @)
253 token: ScrapeCreators API key
254 count: Max videos to return
255
256 Returns:
257 List of raw TikTok item dicts (aweme_info format).
258 """
259 _check_budget(deadline, cancel)
260 _log(f"Profile videos: @{handle}")
261 profile_url = f"{_sc_root()}/v3/tiktok/profile/videos"
262 try:
263 data = http.get(
264 profile_url,
265 params={"handle": handle, "sort_by": "latest"},
266 headers=http.scrapecreators_headers(token),
267 timeout=30,
268 retries=2,
269 deadline_monotonic=deadline,
270 cancel=cancel,
271 )
272 except http.DeadlineExceeded:
273 raise
274 except Exception as e:
275 _log(f"Profile videos error for @{handle}: {e}")
276 return []
277
278 raw_items = data.get("aweme_list") or data.get("data") or []
279 _log(f" -> {len(raw_items)} videos from @{handle}")
280 return raw_items[:count]
281
282
283 def search_tiktok(
284 topic: str,
285 from_date: str,
286 to_date: str,
287 depth: str = "default",
288 token: str = None,
289 *,
290 deadline: float | None = None,
291 cancel: threading.Event | None = None,
292 ) -> Dict[str, Any]:
293 """Search TikTok via ScrapeCreators API.
294
295 Args:
296 topic: Search topic
297 from_date: Start date (YYYY-MM-DD)
298 to_date: End date (YYYY-MM-DD)
299 depth: 'quick', 'default', or 'deep'
300 token: ScrapeCreators API key
301
302 Returns:
303 Dict with 'items' list and optional 'error'.
304 """
305 if not token:
306 return {"items": [], "error": "No SCRAPECREATORS_API_KEY configured"}
307
308 _check_budget(deadline, cancel)
309 config = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
310 core_topic = _extract_core_subject(topic)
311
312 _log(f"Searching TikTok for '{core_topic}' (depth={depth}, count={config['results_per_page']})")
313
314 try:
315 data = http.get(
316 f"{_sc_base()}/search/keyword",
317 params={"query": core_topic, "sort_by": "relevance"},
318 headers=http.scrapecreators_headers(token),
319 timeout=30,
320 retries=2,
321 deadline_monotonic=deadline,
322 cancel=cancel,
323 )
324 except http.DeadlineExceeded:
325 raise
326 except Exception as e:
327 _log(f"ScrapeCreators error: {e}")
328 return {"items": [], "error": f"{type(e).__name__}: {e}"}
329
330 # Items are nested under aweme_info
331 raw_entries = data.get("search_item_list") or data.get("data") or []
332 raw_items = []
333 for entry in raw_entries:
334 if isinstance(entry, dict):
335 info = entry.get("aweme_info", entry)
336 raw_items.append(info)
337
338 # Limit to configured count
339 raw_items = raw_items[:config["results_per_page"]]
340
341 # Parse items
342 items = _parse_items(raw_items, core_topic)
343
344 # Hard date filter
345 in_range = [i for i in items if i["date"] and from_date <= i["date"] <= to_date]
346 out_of_range = len(items) - len(in_range)
347 if in_range:
348 items = in_range
349 if out_of_range:
350 _log(f"Filtered {out_of_range} videos outside date range")
351 else:
352 _log(f"No videos within date range, keeping all {len(items)}")
353
354 # Sort by views descending
355 items.sort(key=lambda x: x.get("engagement", {}).get("views") or 0, reverse=True)
356
357 _log(f"Found {len(items)} TikTok videos")
358 return {"items": items}
359
360
361 def fetch_captions(
362 video_items: List[Dict[str, Any]],
363 token: str,
364 depth: str = "default",
365 *,
366 deadline: float | None = None,
367 cancel: threading.Event | None = None,
368 ) -> Dict[str, str]:
369 """Fetch transcripts for top N TikTok videos via ScrapeCreators.
370
371 Strategy:
372 1. Use the 'text' field (video description) as baseline caption
373 2. For top N, call /video/transcript for spoken-word captions
374
375 Args:
376 video_items: Items from search_tiktok()
377 token: ScrapeCreators API key
378 depth: Depth level for caption limit
379
380 Returns:
381 Dict mapping video_id -> caption text (truncated to 500 words).
382 Captions are also attached to items as they arrive, even if a later
383 request raises DeadlineExceeded.
384 """
385 config = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
386 max_captions = config["max_captions"]
387
388 if not video_items or not token:
389 return {}
390
391 top_items = video_items[:max_captions]
392 _log(f"Enriching captions for {len(top_items)} videos")
393
394 captions = {}
395
396 # First pass: use text field as caption (always available, free)
397 for item in top_items:
398 vid = item["video_id"]
399 text = item.get("text", "")
400 if text:
401 words = text.split()
402 if len(words) > CAPTION_MAX_WORDS:
403 text = ' '.join(words[:CAPTION_MAX_WORDS]) + '...'
404 captions[vid] = text
405 item["caption_snippet"] = text
406
407 # Second pass: try to get spoken-word transcripts (1 credit each)
408 for item in top_items:
409 _check_budget(deadline, cancel)
410 vid = item["video_id"]
411 url = item.get("url", "")
412 if not url:
413 continue
414 try:
415 # Isolate transcript fetch errors from the pipeline-level
416 # capture_failures() context so an individual video's 400
417 # doesn't poison the entire source outcome.
418 with http.capture_failures() as _tf:
419 data = http.get(
420 f"{_sc_base()}/video/transcript",
421 params={"url": url},
422 headers=http.scrapecreators_headers(token),
423 timeout=15,
424 retries=1,
425 deadline_monotonic=deadline,
426 cancel=cancel,
427 )
428 transcript = data.get("transcript")
429 if transcript:
430 if isinstance(transcript, list):
431 transcript = " ".join(str(s) for s in transcript)
432 transcript = _clean_webvtt(transcript)
433 if transcript:
434 words = transcript.split()
435 if len(words) > CAPTION_MAX_WORDS:
436 transcript = ' '.join(words[:CAPTION_MAX_WORDS]) + '...'
437 captions[vid] = transcript
438 item["caption_snippet"] = transcript
439 item["caption_is_transcript"] = True
440 except http.DeadlineExceeded:
441 raise
442 except Exception as e:
443 _log(f"Transcript fetch failed for {vid}: {e}")
444
445 got = sum(1 for v in captions.values() if v)
446 _log(f"Got captions for {got}/{len(top_items)} videos")
447 return captions
448
449
450 def search_and_enrich(
451 topic: str,
452 from_date: str,
453 to_date: str,
454 depth: str = "default",
455 token: str = None,
456 hashtags: List[str] | None = None,
457 creators: List[str] | None = None,
458 config: Dict[str, Any] | None = None,
459 *,
460 deadline: float | None = None,
461 cancel: threading.Event | None = None,
462 ) -> Dict[str, Any]:
463 """Full TikTok search: find videos, then fetch captions for top results.
464
465 Uses expand_tiktok_queries() to generate multiple search queries,
466 runs ScrapeCreators for each, and merges/deduplicates results by video ID.
467 Falls back to web discovery + yt-dlp when the key is missing or 402s.
468
469 Args:
470 topic: Search topic (raw topic, not planner's narrowed query)
471 from_date: Start date (YYYY-MM-DD)
472 to_date: End date (YYYY-MM-DD)
473 depth: 'quick', 'default', or 'deep'
474 token: ScrapeCreators API key
475 hashtags: Optional list of TikTok hashtags to search (without #)
476 creators: Optional list of TikTok creator handles to fetch videos from
477 config: Optional env config (discovery keys for the OSS fallback)
478 deadline: Shared monotonic deadline for search and enrichment
479 cancel: Optional research cancellation event
480
481 Returns:
482 Dict with 'items' list. Each item has a 'caption_snippet' field.
483 """
484 from . import shortform_oss
485
486 core_topic = _extract_core_subject(topic)
487 seen_ids: Set[str] = set()
488 items: List[Dict[str, Any]] = []
489 last_error = None
490
491 try:
492 # Step 0a: Hashtag search (high-signal, runs first)
493 if hashtags and token:
494 for hashtag in hashtags:
495 raw_items = _hashtag_search(hashtag, token, deadline=deadline, cancel=cancel)
496 parsed = _parse_items(raw_items, core_topic)
497 for item in parsed:
498 vid = item.get("video_id", "")
499 if vid and vid not in seen_ids:
500 seen_ids.add(vid)
501 items.append(item)
502
503 # Step 0b: Creator profile videos (high-signal)
504 if creators and token:
505 for creator in creators:
506 raw_items = _profile_videos(creator, token, deadline=deadline, cancel=cancel)
507 parsed = _parse_items(raw_items, core_topic)
508 for item in parsed:
509 vid = item.get("video_id", "")
510 if vid and vid not in seen_ids:
511 seen_ids.add(vid)
512 items.append(item)
513
514 # Step 1: Multi-query keyword search — run ScrapeCreators for each expanded query
515 if token:
516 queries = expand_tiktok_queries(topic, depth)
517 for q in queries:
518 search_result = search_tiktok(
519 q, from_date, to_date, depth, token, deadline=deadline, cancel=cancel,
520 )
521 if search_result.get("error"):
522 last_error = search_result["error"]
523 for item in search_result.get("items", []):
524 vid = item.get("video_id", "")
525 if vid and vid not in seen_ids:
526 seen_ids.add(vid)
527 items.append(item)
528 except http.DeadlineExceeded:
529 last_error = BUDGET_ERROR
530
531 # Sort merged results by views descending
532 items.sort(key=lambda x: x.get("engagement", {}).get("views") or 0, reverse=True)
533
534 # OSS fallback: web discovery + yt-dlp when the key is missing or credits
535 # are exhausted. Bounded by the same deadline/cancel as the paid path.
536 from_oss = False
537 if not items and (not token or shortform_oss.credits_exhausted(last_error)):
538 cfg = config
539 if cfg is None:
540 from . import env as envmod
541 cfg = envmod.get_config()
542 oss = shortform_oss.search(
543 "tiktok", topic, from_date, to_date, depth, cfg, creators=creators,
544 deadline=deadline, cancel=cancel,
545 )
546 items = oss.get("items") or []
547 from_oss = bool(items)
548 if from_oss:
549 last_error = None
550 elif not last_error:
551 last_error = oss.get("error")
552
553 if not items:
554 return {"items": [], "error": last_error}
555
556 # Attach captions as they arrive so a later timeout cannot discard them.
557 # OSS items already carry caption_snippet from the video description.
558 if not from_oss and last_error != BUDGET_ERROR:
559 try:
560 fetch_captions(items, token, depth, deadline=deadline, cancel=cancel)
561 except http.DeadlineExceeded:
562 last_error = BUDGET_ERROR
563
564 return {"items": items, "error": last_error}
565
566
567 def parse_tiktok_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
568 """Parse TikTok search response to normalized format.
569
570 Returns:
571 List of item dicts ready for normalization.
572 """
573 return response.get("items", [])
574
575
576 def _tiktok_total_engagement(item: Dict[str, Any]) -> int:
577 """Total engagement for ranking which posts deserve comment enrichment."""
578 eng = item.get("engagement", {})
579 return (eng.get("views", 0) or 0) + (eng.get("likes", 0) or 0) + (eng.get("comments", 0) or 0)
580
581
582 def enrich_with_comments(
583 items: List[Dict[str, Any]],
584 token: str,
585 max_posts: int = 3,
586 max_comments: int = 5,
587 *,
588 deadline: float | None = None,
589 cancel: threading.Event | None = None,
590 public: bool = False,
591 ) -> List[Dict[str, Any]]:
592 """Enrich top TikTok posts with comment data from ScrapeCreators.
593
594 With ``public=True`` the comments come from TikTok's public web comment
595 endpoint instead: free, no key, same comment shape.
596
597 For the top N posts by engagement, fetches comments via the SC API
598 and attaches them as a ``top_comments`` field on each item. Mirrors
599 youtube_yt.enrich_with_comments.
600
601 Args:
602 items: TikTok items from search_tiktok()
603 token: ScrapeCreators API key
604 max_posts: How many posts to enrich with comments
605 max_comments: Max comments to keep per post
606
607 Returns:
608 Items list (mutated in place) with top_comments added to enriched items.
609 Raises DeadlineExceeded on a budget stop; collected comments remain attached.
610 """
611 if not items or max_posts <= 0 or not (token or public):
612 return items
613 fetch = _fetch_public_comments if public else _fetch_post_comments
614
615 _check_budget(deadline, cancel)
616 ranked = sorted(items, key=_tiktok_total_engagement, reverse=True)
617 top_items = ranked[:max_posts]
618 _log(f"Enriching comments for {len(top_items)} TikTok posts")
619
620 from concurrent.futures import ThreadPoolExecutor, as_completed
621
622 def _enrich_one(item: dict) -> bool:
623 post_url = item.get("url", "")
624 if not post_url:
625 return False
626 try:
627 comments = fetch(
628 post_url, token, max_comments, deadline=deadline, cancel=cancel,
629 creator=str(item.get("author_name") or ""),
630 )
631 if comments:
632 item["top_comments"] = comments
633 return True
634 except http.DeadlineExceeded:
635 raise
636 except Exception as exc:
637 _log(f"Comment enrichment failed for {post_url}: {exc}")
638 return False
639
640 enriched_count = 0
641 with ThreadPoolExecutor(max_workers=min(4, len(top_items))) as executor:
642 futures = {http.submit_with_context(executor, _enrich_one, item): item for item in top_items}
643 for future in as_completed(futures):
644 if future.result():
645 enriched_count += 1
646
647 _log(f"Enriched {enriched_count}/{len(top_items)} posts with comments")
648 return items
649
650
651 def _fetch_post_comments(
652 post_url: str,
653 token: str,
654 max_comments: int = 5,
655 *,
656 deadline: float | None = None,
657 cancel: threading.Event | None = None,
658 creator: str = "",
659 ) -> List[Dict[str, Any]]:
660 """Fetch comments for a single TikTok post via ScrapeCreators.
661
662 SC endpoint: GET /v1/tiktok/video/comments?url=<video_url>
663 Response shape: { comments: [{text, user.nickname, digg_count, create_time, ...}], cursor, total }
664
665 Args:
666 post_url: Canonical TikTok post URL (share_url form works)
667 token: ScrapeCreators API key
668 max_comments: Maximum comments to return
669
670 Returns:
671 List of comment dicts with author, text, digg_count (likes), date.
672 Empty list on provider errors; DeadlineExceeded propagates to the lane.
673 """
674 _check_budget(deadline, cancel)
675 try:
676 data = http.get(
677 f"{_sc_base()}/video/comments",
678 params={"url": post_url, "trim": "true"},
679 headers=http.scrapecreators_headers(token),
680 timeout=30,
681 retries=2,
682 deadline_monotonic=deadline,
683 cancel=cancel,
684 )
685 except http.DeadlineExceeded:
686 raise
687 except Exception as exc:
688 _log(f"Comment fetch error for {post_url}: {exc}")
689 return []
690
691 raw_comments = data.get("comments") or data.get("data") or []
692 return _normalize_comments(raw_comments, max_comments, creator)
693
694
695 _PUBLIC_COMMENTS_URL = "https://www.tiktok.com/api/comment/list/"
696 _POST_ID_RE = re.compile(r"/(?:video|photo)/(\d{8,})")
697
698
699 def _fetch_public_comments(
700 post_url: str,
701 _token: str = "",
702 max_comments: int = 5,
703 *,
704 deadline: float | None = None,
705 cancel: threading.Event | None = None,
706 creator: str = "",
707 ) -> List[Dict[str, Any]]:
708 """Top comments for one post from TikTok's public web endpoint, no key.
709
710 Same shape as ``_fetch_post_comments``. Empty list on any provider error;
711 DeadlineExceeded propagates to the lane.
712 """
713 m = _POST_ID_RE.search(post_url or "")
714 if not m:
715 return []
716 _check_budget(deadline, cancel)
717 try:
718 # Optional and backed up by ScrapeCreators: a failure here is logged,
719 # never recorded as the run's own, so a recovered stream stays
720 # cacheable and is not refetched (paid calls included) by later streams.
721 with http.capture_failures():
722 data = http.get(
723 _PUBLIC_COMMENTS_URL,
724 params={"aweme_id": m.group(1), "count": 20, "cursor": 0, "aid": 1988},
725 headers={"User-Agent": http.BROWSER_USER_AGENT, "Referer": "https://www.tiktok.com/"},
726 timeout=10,
727 retries=1,
728 deadline_monotonic=deadline,
729 cancel=cancel,
730 )
731 except http.DeadlineExceeded:
732 raise
733 except Exception as exc:
734 _log(f"Public comment fetch error for {post_url}: {exc}")
735 return []
736 raw_comments = data.get("comments") if isinstance(data, dict) else None
737 return _normalize_comments(raw_comments or [], max_comments, creator)
738
739
740 def _normalize_comments(
741 raw_comments: List[Dict[str, Any]], max_comments: int, creator: str,
742 ) -> List[Dict[str, Any]]:
743 """TikTok comment payloads (ScrapeCreators or the public endpoint, same
744 field names) to the ``top_comments`` shape, most liked first."""
745 raw_comments = [c for c in raw_comments if isinstance(c, dict)]
746 # Sort by digg_count desc so normalize sees the highest-signal first.
747 raw_comments = sorted(
748 raw_comments,
749 key=lambda c: c.get("digg_count", 0) or 0,
750 reverse=True,
751 )
752 out: List[Dict[str, Any]] = []
753 for c in raw_comments[:max_comments]:
754 text = c.get("text") or ""
755 if not text:
756 continue
757 user = c.get("user") if isinstance(c.get("user"), dict) else {}
758 # Prefer unique_id (the @handle) over nickname (display name) so
759 # downstream render can cite @handle consistently across platforms.
760 author = user.get("unique_id") or user.get("nickname") or ""
761 create_time = c.get("create_time")
762 date_str = ""
763 if create_time:
764 try:
765 date_str = dates.timestamp_to_date(int(create_time)) or ""
766 except (ValueError, TypeError):
767 date_str = ""
768 out.append({
769 "author": author,
770 "text": text[:400],
771 "digg_count": c.get("digg_count", 0) or 0,
772 "date": date_str,
773 })
774 # Whether the post's own creator wrote this. Both are handles, a stable
775 # identifier, so they compare exactly. With no handle on either side
776 # the key is left out: unknown.
777 handle = str(user.get("unique_id") or "").strip().lstrip("@").lower()
778 owner = str(creator or "").strip().lstrip("@").lower()
779 if handle and owner:
780 out[-1]["is_uploader"] = handle == owner
781 return out
782
782 lines PYTHON