返回 last30days-skill
shortform_envelope.py
根目录 / skills / last30days / scripts / lib / shortform_envelope.py
1 """Host-found TikTok and Instagram URLs: the ``--shortform-urls`` lane.
2
3 A host with its own web search collects TikTok and Instagram post URLs (and
4 TikTok creator profile URLs) during its pre-research search and writes them
5 to a ``.json`` file. The engine reads only each entry's URL. Post URLs go
6 through the keyless short-form lane (``shortform_oss``): the id-date filter
7 drops stale posts before any fetch, yt-dlp hydrates the rest logged out, and
8 the window and the topic bar drop what does not belong. TikTok creator
9 profiles become leads for creator expansion. A caption, count or date the
10 host wrote is never used.
11
12 Shape (``schema: "last30days-shortform-urls/1"``)::
13
14 {
15 "schema": "last30days-shortform-urls/1",
16 "topic": "<the run topic>",
17 "urls": [
18 {"url": "https://www.tiktok.com/@<handle>/video/<id>"},
19 {"url": "https://www.instagram.com/reel/<code>/"},
20 {"url": "https://www.tiktok.com/@<creator>"}
21 ]
22 }
23
24 The file is read with the same safety contract as ``--reddit-threads``
25 (``reddit_envelope``): a file path or ``-`` only, a regular ``.json`` file
26 outside the config dir and credential stores, 1 MiB, strict UTF-8, a
27 matching ``topic``. The reader is strict at the envelope level (exit-2
28 contract error) and lenient per entry (a bad entry is dropped with a named
29 counter). At most ``MAX_URLS`` distinct URLs are used.
30
31 The URLs are used only when the keyless lane runs (no ScrapeCreators key, or
32 ScrapeCreators returned 402); with a working key ScrapeCreators stays the
33 TikTok and Instagram path.
34
35 Security contract: contract errors name the path and the field, never a
36 field value, and nothing the host wrote reaches an outcome detail.
37 """
38
39 from __future__ import annotations
40
41 import hashlib
42 import json
43 import os
44 import re
45 from dataclasses import dataclass, field
46 from typing import Any, Optional
47 from urllib.parse import urlsplit
48
49 from . import log
50 from .reddit_envelope import (
51 _CONTROL_RE,
52 _REDIRECT_HOST,
53 MAX_BYTES,
54 MAX_ENTRIES,
55 MAX_FIELD_CHARS,
56 STDIN,
57 EnvelopeContractError,
58 _normalize_topic,
59 _read_bytes,
60 looks_inline_json,
61 )
62
63 SCHEMA = "last30days-shortform-urls/1"
64 MAX_URLS = 40
65
66 ENTRY_FIELDS = frozenset({"url"})
67 # Counters, in receipt order. All are judged when the file is read; the
68 # hydration outcome is logged per platform by the keyless lane.
69 COUNTERS = (
70 "non-shortform",
71 "redirect",
72 "not-a-post",
73 "instagram-profile",
74 "invalid",
75 "duplicate",
76 "truncated",
77 "extra-fields",
78 )
79
80 _REMEDY = (
81 "Rewrite the file to the last30days-shortform-urls/1 shape, or re-run "
82 "without --shortform-urls."
83 )
84
85 _TIKTOK_POST = re.compile(r"^/@([\w.\-]{1,64})/video/(\d{6,25})/?$")
86 _TIKTOK_PROFILE = re.compile(r"^/@([\w.\-]{1,64})/?$")
87 _INSTAGRAM_POST = re.compile(r"^/(?:reel|reels|p)/([\w\-]{5,40})/?$")
88 _INSTAGRAM_PROFILE = re.compile(r"^/[\w.]{1,30}/?$")
89
90 __all__ = [
91 "SCHEMA", "MAX_URLS", "MAX_BYTES", "MAX_ENTRIES", "STDIN",
92 "Envelope", "EnvelopeContractError", "looks_inline_json", "read",
93 ]
94
95
96 @dataclass
97 class Envelope:
98 """A validated ``--shortform-urls`` file, ready for the keyless lane."""
99
100 path: str
101 sha256: str
102 topic: str
103 tiktok_posts: list[str]
104 instagram_posts: list[str]
105 tiktok_creators: list[str]
106 counters: dict[str, int]
107 total: int
108 notes: list[str] = field(default_factory=list)
109
110 @property
111 def accepted(self) -> int:
112 return len(self.tiktok_posts) + len(self.instagram_posts) + len(self.tiktok_creators)
113
114 def posts(self, kind: str) -> list[str]:
115 """Canonical post URLs for ``kind`` (``tiktok`` or ``instagram``)."""
116 return list(self.tiktok_posts if kind == "tiktok" else self.instagram_posts if kind == "instagram" else [])
117
118 def creators(self, kind: str) -> list[str]:
119 """TikTok creator handles; Instagram has no logged-out profile listing."""
120 return list(self.tiktok_creators) if kind == "tiktok" else []
121
122 def receipt(self) -> str:
123 dropped = ", ".join(
124 f"{name} {count}" for name, count in self.counters.items() if count
125 ) or "none"
126 line = (
127 f"host short-form URLs: accepted {self.accepted} of {self.total} "
128 f"(TikTok posts {len(self.tiktok_posts)}, TikTok creators "
129 f"{len(self.tiktok_creators)}, Instagram posts {len(self.instagram_posts)}; "
130 f"dropped: {dropped})"
131 )
132 if self.notes:
133 line += "; notes: " + "; ".join(self.notes)
134 return line
135
136
137 def _log(msg: str) -> None:
138 log.source_log("TikTok", msg, tty_only=False)
139
140
141 def _classify(text: str) -> tuple[str, str]:
142 """``(kind, value)`` for one URL, where kind is a counter name or one of
143 ``tiktok-post`` / ``instagram-post`` / ``tiktok-creator``."""
144 candidate = text if "://" in text else "https://" + text
145 try:
146 parts = urlsplit(candidate)
147 host = (parts.hostname or "").lower()
148 except ValueError:
149 return "invalid", ""
150 if not host or parts.scheme.lower() not in ("http", "https"):
151 return "invalid", ""
152 if _REDIRECT_HOST.search(host):
153 return "redirect", ""
154 path = parts.path or "/"
155 if host in ("tiktok.com", "www.tiktok.com", "m.tiktok.com"):
156 m = _TIKTOK_POST.match(path)
157 if m:
158 return "tiktok-post", f"https://www.tiktok.com/@{m.group(1)}/video/{m.group(2)}"
159 m = _TIKTOK_PROFILE.match(path)
160 if m:
161 return "tiktok-creator", m.group(1)
162 return "not-a-post", ""
163 if host in ("instagram.com", "www.instagram.com", "m.instagram.com"):
164 m = _INSTAGRAM_POST.match(path)
165 if m:
166 return "instagram-post", f"https://www.instagram.com/reel/{m.group(1)}/"
167 if _INSTAGRAM_PROFILE.match(path):
168 return "instagram-profile", ""
169 return "not-a-post", ""
170 if host.endswith(".tiktok.com") or host.endswith(".instagram.com"):
171 # Short links (vm.tiktok.com) need a network round trip to resolve.
172 return "not-a-post", ""
173 return "non-shortform", ""
174
175
176 def read(path: str | os.PathLike[str], topic: str) -> Envelope:
177 """Validate a ``--shortform-urls`` file (or ``-`` for stdin) for this run.
178
179 ``topic`` is the run topic. Raises ``EnvelopeContractError`` (exit 2) for
180 every fail-closed case; a bad entry is only counted.
181 """
182 raw_path = os.fspath(path)
183
184 def fail(what: str) -> EnvelopeContractError:
185 where = "on stdin" if raw_path == STDIN else raw_path
186 return EnvelopeContractError(f"--shortform-urls file {where} {what}. {_REMEDY}")
187
188 data = _read_bytes(raw_path, fail)
189 digest = hashlib.sha256(data).hexdigest()
190 try:
191 payload = json.loads(data.decode("utf-8"))
192 except UnicodeDecodeError:
193 raise fail("is not valid UTF-8") from None
194 except (RecursionError, MemoryError):
195 raise fail("is too deeply nested or too large to parse") from None
196 except ValueError:
197 raise fail("is not valid JSON") from None
198
199 if not isinstance(payload, dict):
200 raise fail("must be a JSON object")
201 if payload.get("schema") != SCHEMA:
202 raise fail('has a missing or unsupported "schema" field')
203 if not _normalize_topic(topic) or _normalize_topic(payload.get("topic")) != _normalize_topic(topic):
204 raise fail('has a "topic" field that does not match this run\'s topic')
205 entries = payload.get("urls")
206 if not isinstance(entries, list):
207 raise fail('has a "urls" field that is not a list')
208 if not entries:
209 raise fail('has an empty "urls" list (omit --shortform-urls when no URL was found)')
210 if len(entries) > MAX_ENTRIES:
211 raise fail(f'has more than {MAX_ENTRIES} entries in "urls"')
212
213 counters = {name: 0 for name in COUNTERS}
214 buckets: dict[str, list[str]] = {"tiktok-post": [], "instagram-post": [], "tiktok-creator": []}
215 seen: set[str] = set()
216 kept = 0
217 for entry in entries:
218 if not isinstance(entry, dict):
219 counters["invalid"] += 1
220 continue
221 if set(entry) - ENTRY_FIELDS:
222 counters["extra-fields"] += 1
223 raw = entry.get("url")
224 if not isinstance(raw, str) or not raw.strip() or len(raw) > MAX_FIELD_CHARS:
225 counters["invalid"] += 1
226 continue
227 kind, value = _classify(_CONTROL_RE.sub("", raw).strip())
228 if kind not in buckets:
229 counters[kind] += 1
230 continue
231 key = f"{kind}:{value.lower()}"
232 if key in seen:
233 counters["duplicate"] += 1
234 continue
235 if kept >= MAX_URLS:
236 counters["truncated"] += 1
237 continue
238 seen.add(key)
239 kept += 1
240 buckets[kind].append(value)
241 notes: list[str] = []
242 if counters["truncated"]:
243 notes.append(f"only the first {MAX_URLS} URLs are used")
244
245 envelope = Envelope(
246 path=raw_path, sha256=digest, topic=topic,
247 tiktok_posts=buckets["tiktok-post"],
248 instagram_posts=buckets["instagram-post"],
249 tiktok_creators=buckets["tiktok-creator"],
250 counters=counters, total=len(entries), notes=notes,
251 )
252 _log(envelope.receipt())
253 return envelope
254
255
256 def from_config(config: Optional[dict[str, Any]]) -> Optional[Envelope]:
257 """The run's envelope, carried on the config dict by the pipeline."""
258 value = (config or {}).get("_shortform_envelope")
259 return value if isinstance(value, Envelope) else None
260
260 lines PYTHON