google-flow-api-mcp 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,881 @@
1
+ """Core client for Google Flow (flow.google.com).
2
+
3
+ Reverse-engineered from live traffic; see TEAM.md / NOTES.md for the provenance
4
+ of every constant. Pure `requests` — no browser required, except that the caller
5
+ must supply a logged-in `.google.com` cookie jar and a single-use reCAPTCHA
6
+ Enterprise token minted in that same session.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import html
12
+ import json
13
+ import os
14
+ import random
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ import uuid
21
+ from datetime import datetime
22
+ from pathlib import Path
23
+ from typing import Any, Iterable
24
+
25
+ import requests
26
+
27
+ # --------------------------------------------------------------------------
28
+ # Constants (verified against captured traffic in fixtures/)
29
+ # --------------------------------------------------------------------------
30
+
31
+ BASE = "https://flow.google.com"
32
+ PAGE_URL = BASE + "/project/{project}"
33
+ BATCHEXECUTE = BASE + "/_/AiSandboxAngularFrontend/data/batchexecute"
34
+
35
+ IMAGE_RPC = "ogiZ0b"
36
+ IMAGE_MODEL = "GEM_PIX_2" # Nano Banana Pro
37
+
38
+ VIDEO_RPC = "YhhmEf"
39
+ VIDEO_MODEL = "macaron_cookie_t2v_8s" # Omni 1.2 Flash, 8s
40
+ VIDEO_STATUS_RPC = "jwpduf"
41
+ MEDIA_FETCH_RPC = "as29s"
42
+
43
+ RECAPTCHA_SITE_KEY = "6LdsFiUsAAAAAIjVDZcuLhaHiDn5nnHVXVRQGeMV"
44
+ RECAPTCHA_ACTION_IMAGE = "IMAGE_GENERATION"
45
+ RECAPTCHA_ACTION_VIDEO = "VIDEO_GENERATION"
46
+
47
+ DEFAULT_PROJECT_ID = "f73a2a1b-0904-4cec-8c9e-22ff6c858592"
48
+
49
+ HERE = Path(__file__).resolve().parent
50
+ REPO_ROOT = HERE.parent
51
+ DEFAULT_FIXTURES = Path(
52
+ os.environ.get("GOOGLE_FLOW_API_HOME", Path.home() / ".config" / "google-flow-api")
53
+ ).expanduser()
54
+ DEFAULT_OUT_DIR = Path(
55
+ os.environ.get(
56
+ "GOOGLE_FLOW_API_OUT",
57
+ os.environ.get("FLOW_OUT_DIR", Path.home() / "Downloads" / "google-flow-api"),
58
+ )
59
+ ).expanduser()
60
+ MINT_SCRIPT = REPO_ROOT / "auth_lab" / "mint_token.py"
61
+ # A reCAPTCHA score flag needs breathing room; retrying in 1.5s re-hits the same flag.
62
+ RETRY_DELAYS_S = (5.0, 15.0, 30.0)
63
+
64
+ IMAGE_EXTS = (".jpg", ".png", ".webp")
65
+ VIDEO_EXTS = (".mp4", ".webm", ".mov")
66
+
67
+ _URL_RE = re.compile(r"https://(?:flow-content\.google|[a-z0-9.-]*googleusercontent\.com)[^\"\\\s]+")
68
+ _UUID_RE = re.compile(
69
+ r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.I
70
+ )
71
+
72
+
73
+ class FlowError(RuntimeError):
74
+ """Any non-recoverable failure talking to Flow."""
75
+
76
+
77
+ class RecaptchaRejected(FlowError):
78
+ """The generation RPC refused the reCAPTCHA token (single-use / stale)."""
79
+
80
+
81
+ # --------------------------------------------------------------------------
82
+ # Response de-framing
83
+ # --------------------------------------------------------------------------
84
+
85
+ _DECODER = json.JSONDecoder()
86
+
87
+
88
+ def deframe(body: str) -> list[Any]:
89
+ """Split a batchexecute response into its JSON frames.
90
+
91
+ Wire format::
92
+
93
+ )]}'
94
+ \\n
95
+ <len>
96
+ <json array>\\n
97
+ <len>
98
+ <json array>\\n
99
+
100
+ `<len>` counts the JSON payload *including* its trailing newline, so we
101
+ bound the slice and let ``raw_decode`` consume exactly one JSON value.
102
+ """
103
+ if not body:
104
+ return []
105
+ if body.startswith(")]}'"):
106
+ body = body[4:]
107
+ frames: list[Any] = []
108
+ i, n = 0, len(body)
109
+ while i < n:
110
+ while i < n and body[i] in "\r\n\t ":
111
+ i += 1
112
+ if i >= n:
113
+ break
114
+ j = i
115
+ while j < n and body[j].isdigit():
116
+ j += 1
117
+ if j == i: # not a length line -> give up on the remainder
118
+ break
119
+ length = int(body[i:j])
120
+ k = j
121
+ while k < n and body[k] in "\r\n":
122
+ k += 1
123
+ window = body[k : k + length + 2]
124
+ try:
125
+ value, consumed = _DECODER.raw_decode(window)
126
+ except ValueError as exc:
127
+ raise FlowError(f"cannot parse batchexecute frame: {exc}") from exc
128
+ frames.append(value)
129
+ i = k + consumed
130
+ return frames
131
+
132
+
133
+ def wrb_payloads(body: str, rpcid: str) -> list[Any]:
134
+ """Return the decoded inner JSON of every ``wrb.fr`` frame for ``rpcid``."""
135
+ out: list[Any] = []
136
+ for frame in deframe(body):
137
+ if not isinstance(frame, list):
138
+ continue
139
+ for item in frame:
140
+ if not isinstance(item, list) or len(item) < 3:
141
+ continue
142
+ if item[0] == "wrb.fr" and item[1] == rpcid:
143
+ raw = item[2]
144
+ if raw is None or raw == "":
145
+ out.append(None)
146
+ else:
147
+ out.append(json.loads(raw))
148
+ elif item[0] == "er":
149
+ raise FlowError(f"batchexecute error frame: {json.dumps(item)[:500]}")
150
+ return out
151
+
152
+
153
+ def collect_urls(node: Any) -> list[str]:
154
+ """Depth-first collection of https URLs, order preserved, deduped."""
155
+ urls: list[str] = []
156
+
157
+ def walk(obj: Any) -> None:
158
+ if isinstance(obj, str):
159
+ if obj.startswith("https://") and obj not in urls:
160
+ urls.append(obj)
161
+ else:
162
+ for match in _URL_RE.finditer(obj):
163
+ url = unescape_url(match.group(0))
164
+ if url not in urls:
165
+ urls.append(url)
166
+ elif isinstance(obj, list):
167
+ for child in obj:
168
+ walk(child)
169
+ elif isinstance(obj, dict):
170
+ for child in obj.values():
171
+ walk(child)
172
+
173
+ walk(node)
174
+ return urls
175
+
176
+
177
+ def unescape_url(url: str) -> str:
178
+ return html.unescape(url.replace("\\u003d", "=").replace("\\u0026", "&"))
179
+
180
+
181
+ def asb_download_url(url: str) -> str | None:
182
+ """Rewrite an lh3 ``/asb/<TOKEN>`` URL to Flow's same-origin proxy URL.
183
+
184
+ ``https://lh3.googleusercontent.com/asb/<TOKEN>`` is not downloadable
185
+ (bounces to Google sign-in). The UI's own player uses
186
+ ``https://flow.google.com/asb/<TOKEN>=mm,22,15`` with the session cookies.
187
+ """
188
+ match = re.search(r"/asb/([A-Za-z0-9_\-]+)", url)
189
+ if not match:
190
+ return None
191
+ return f"{BASE}/asb/{match.group(1)}=mm,22,15"
192
+
193
+
194
+ def asb_image_url(url: str) -> str | None:
195
+ """Rewrite an lh3 ``/asb/<TOKEN>`` URL to the cookie-authed image variant."""
196
+ match = re.search(r"/asb/([A-Za-z0-9_\-]+)", url)
197
+ if not match:
198
+ return None
199
+ return f"{BASE}/asb/{match.group(1)}=s512-rw"
200
+
201
+
202
+ def pick_download_url(urls: Iterable[str], kind: str) -> str | None:
203
+ urls = list(urls)
204
+ if kind == "image":
205
+ for url in urls:
206
+ if "flow-content.google/image/" in url:
207
+ return url
208
+ for url in urls:
209
+ if re.search(r"\.(jpe?g|png|webp)(\?|$)", url):
210
+ return url
211
+ return None
212
+ for url in urls:
213
+ if "flow-content.google/video/" in url:
214
+ return url
215
+ for url in urls:
216
+ if re.search(r"\.(mp4|webm|mov)(\?|$)", url) or "/video/" in url:
217
+ return url
218
+ for url in urls:
219
+ if "googleusercontent.com" in url:
220
+ return url
221
+ return None
222
+
223
+
224
+ # --------------------------------------------------------------------------
225
+ # Token / cookie loading helpers
226
+ # --------------------------------------------------------------------------
227
+
228
+ def slugify(text: str, limit: int = 40) -> str:
229
+ slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
230
+ return (slug[:limit].rstrip("-") or "output")
231
+
232
+
233
+ def timestamp() -> str:
234
+ return datetime.now().strftime("%Y%m%d_%H%M%S")
235
+
236
+
237
+ def sniff_extension(blob: bytes) -> str | None:
238
+ if blob[:3] == b"\xff\xd8\xff":
239
+ return ".jpg"
240
+ if blob[:8] == b"\x89PNG\r\n\x1a\n":
241
+ return ".png"
242
+ if blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
243
+ return ".webp"
244
+ if blob[4:8] == b"ftyp":
245
+ return ".mp4"
246
+ if blob[:4] == b"\x1a\x45\xdf\xa3":
247
+ return ".webm"
248
+ return None
249
+
250
+
251
+ def load_cookie_json(path: str | Path) -> list[dict[str, Any]]:
252
+ data = json.loads(Path(path).read_text())
253
+ if isinstance(data, dict) and "cookies" in data:
254
+ data = data["cookies"]
255
+ if not isinstance(data, list):
256
+ raise FlowError(f"cookie file {path} is not a JSON array of cookies")
257
+ return data
258
+
259
+
260
+ def load_wiz_json(path: str | Path) -> dict[str, str]:
261
+ data = json.loads(Path(path).read_text())
262
+ out = {}
263
+ for key in ("at", "bl", "fsid"):
264
+ if data.get(key):
265
+ out[key] = str(data[key])
266
+ return out
267
+
268
+
269
+ def parse_wiz(html_text: str) -> dict[str, str]:
270
+ """Extract SNlM0e / cfb2h / FdrFJe from the project page HTML."""
271
+ mapping = {"at": "SNlM0e", "bl": "cfb2h", "fsid": "FdrFJe"}
272
+ out: dict[str, str] = {}
273
+ for alias, key in mapping.items():
274
+ match = re.search(
275
+ r'"' + re.escape(key) + r'"\s*:\s*"((?:[^"\\]|\\.)+)"', html_text
276
+ )
277
+ if match:
278
+ raw = match.group(0).split(":", 1)[1].strip()
279
+ try:
280
+ out[alias] = json.loads(raw)
281
+ except ValueError:
282
+ out[alias] = match.group(1)
283
+ missing = [alias for alias in mapping if alias not in out]
284
+ if missing:
285
+ raise FlowError(f"WIZ_global_data missing {missing} on project page")
286
+ return out
287
+
288
+
289
+ TOKEN_MAX_AGE_S = 90.0
290
+
291
+
292
+ def load_recaptcha_token(
293
+ path: str | Path | None, action: str, max_age_s: float | None = None
294
+ ) -> str | None:
295
+ """Read a token from a JSON file, a directory of JSON files, or raw text.
296
+
297
+ For a directory, tokens older than ``max_age_s`` (their ``ts``, epoch ms) are
298
+ skipped: reCAPTCHA Enterprise tokens are single-use and die in ~2 minutes, so
299
+ a stale file must lose to a fresh mint.
300
+ """
301
+ if path is None:
302
+ return None
303
+ p = Path(path).expanduser()
304
+ if not p.exists():
305
+ return None
306
+ if p.is_dir():
307
+ now_ms = time.time() * 1000
308
+ candidates = sorted(
309
+ p.glob("*.json"), key=lambda f: f.stat().st_mtime, reverse=True
310
+ )
311
+ for candidate in candidates:
312
+ try:
313
+ meta = json.loads(candidate.read_text())
314
+ except ValueError:
315
+ meta = None
316
+ if isinstance(meta, dict) and max_age_s is not None and meta.get("ts"):
317
+ age = (now_ms - float(meta["ts"])) / 1000.0
318
+ if age > max_age_s:
319
+ continue
320
+ token = load_recaptcha_token(candidate, action)
321
+ if token:
322
+ return token
323
+ return None
324
+ text = p.read_text().strip()
325
+ try:
326
+ data = json.loads(text)
327
+ except ValueError:
328
+ return text or None
329
+ if isinstance(data, str):
330
+ return data or None
331
+ if isinstance(data, dict):
332
+ token_action = str(data.get("action", "")).upper()
333
+ if token_action and token_action != action.upper():
334
+ return None
335
+ token = data.get("token") or data.get("recaptcha_token")
336
+ return str(token) if token else None
337
+ return None
338
+
339
+
340
+ # --------------------------------------------------------------------------
341
+ # Request builders (pure, used by the client and by selftest)
342
+ # --------------------------------------------------------------------------
343
+
344
+ def build_image_inner(
345
+ prompt: str,
346
+ project_id: str,
347
+ token: str,
348
+ seed: int | None = None,
349
+ u1: str | None = None,
350
+ u2: str | None = None,
351
+ ) -> list[Any]:
352
+ seed = random.randint(1, 2**31 - 1) if seed is None else seed
353
+ u1 = u1 or str(uuid.uuid4()).upper()
354
+ u2 = u2 or str(uuid.uuid4()).upper()
355
+ ctx = [None, 22, None, None, None, project_id, None, None, None, None, [token, 1]]
356
+ return [
357
+ None,
358
+ [
359
+ [
360
+ None,
361
+ None,
362
+ None,
363
+ seed,
364
+ 1,
365
+ IMAGE_MODEL,
366
+ None,
367
+ list(ctx),
368
+ [[[prompt]]],
369
+ None,
370
+ None,
371
+ None,
372
+ u1,
373
+ u2,
374
+ ]
375
+ ],
376
+ 1,
377
+ list(ctx),
378
+ ]
379
+
380
+
381
+ def build_video_inner(
382
+ prompt: str,
383
+ project_id: str,
384
+ token: str,
385
+ u1: str | None = None,
386
+ u2: str | None = None,
387
+ ) -> list[Any]:
388
+ u1 = u1 or str(uuid.uuid4()).upper()
389
+ u2 = u2 or str(uuid.uuid4()).upper()
390
+ ctx = [None, 22, None, None, None, project_id, None, None, None, None, [token, 1]]
391
+ return [
392
+ [
393
+ [
394
+ [None, None, [[[prompt]]], VIDEO_MODEL, 2, None, [None, None, None, None, u1, u2]]
395
+ ]
396
+ ],
397
+ list(ctx),
398
+ [u1, 1],
399
+ ]
400
+
401
+
402
+ # --------------------------------------------------------------------------
403
+ # Client
404
+ # --------------------------------------------------------------------------
405
+
406
+ class FlowClient:
407
+ def __init__(
408
+ self,
409
+ project_id: str = DEFAULT_PROJECT_ID,
410
+ cookie_file: str | Path | None = None,
411
+ wiz_file: str | Path | None = None,
412
+ token_file: str | Path | None = None,
413
+ timeout: int = 60,
414
+ out_dir: str | Path | None = None,
415
+ verbose: bool = True,
416
+ ) -> None:
417
+ self.project_id = project_id
418
+ self.timeout = timeout
419
+ self.out_dir = Path(out_dir) if out_dir else DEFAULT_OUT_DIR
420
+ self.verbose = verbose
421
+ self._token_file = token_file
422
+ self.cookie_file = str(cookie_file) if cookie_file else None
423
+ self.auto_mint = True
424
+ self._wiz: dict[str, str] = {}
425
+ self._reqid = random.randint(100000, 9000000)
426
+ self.last_response = ""
427
+
428
+ self.session = requests.Session()
429
+ self.session.headers.update(
430
+ {
431
+ "accept": "*/*",
432
+ "accept-language": "en-US,en;q=0.9",
433
+ "origin": BASE,
434
+ "referer": PAGE_URL.format(project=project_id),
435
+ "user-agent": (
436
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
437
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
438
+ "Chrome/140.0.0.0 Safari/537.36"
439
+ ),
440
+ }
441
+ )
442
+ if cookie_file:
443
+ for cookie in load_cookie_json(cookie_file):
444
+ self.session.cookies.set(
445
+ cookie["name"],
446
+ cookie.get("value", ""),
447
+ domain=cookie.get("domain") or ".google.com",
448
+ path=cookie.get("path") or "/",
449
+ )
450
+ if wiz_file:
451
+ self._wiz = load_wiz_json(wiz_file)
452
+
453
+ # -- diagnostics -------------------------------------------------------
454
+ def log(self, message: str) -> None:
455
+ if self.verbose:
456
+ import sys
457
+
458
+ print(f"[flow_api] {message}", file=sys.stderr, flush=True)
459
+
460
+ @property
461
+ def cookie_count(self) -> int:
462
+ return len(self.session.cookies)
463
+
464
+ # -- tokens ------------------------------------------------------------
465
+ def refresh_wiz(self) -> dict[str, str]:
466
+ url = PAGE_URL.format(project=self.project_id)
467
+ resp = self.session.get(url, timeout=self.timeout, allow_redirects=True)
468
+ if resp.status_code != 200:
469
+ raise FlowError(
470
+ f"cannot load project page ({resp.status_code}) — cookies expired?"
471
+ )
472
+ final = resp.url
473
+ if "accounts.google.com" in final or "/signin" in final:
474
+ raise FlowError("project page redirected to Google sign-in — cookies expired")
475
+ self._wiz = parse_wiz(resp.text)
476
+ self.log(f"WIZ loaded: at={self._wiz['at'][:18]}… bl={self._wiz['bl']}")
477
+ return self._wiz
478
+
479
+ def wiz(self, refresh: bool = False) -> dict[str, str]:
480
+ if refresh or not self._wiz:
481
+ return self.refresh_wiz()
482
+ return self._wiz
483
+
484
+ def _next_reqid(self) -> int:
485
+ self._reqid += 100000
486
+ return self._reqid
487
+
488
+ # -- batchexecute ------------------------------------------------------
489
+ def batchexecute(self, rpcid: str, inner: Any, retry_auth: bool = True) -> list[Any]:
490
+ """POST one RPC; return the decoded inner values for ``rpcid``."""
491
+ if isinstance(inner, (list, dict)):
492
+ inner_json = json.dumps(inner, separators=(",", ":"))
493
+ else:
494
+ inner_json = str(inner)
495
+ freq = json.dumps([[[rpcid, inner_json, None, "generic"]]], separators=(",", ":"))
496
+ wiz = self.wiz()
497
+ params = {
498
+ "rpcids": rpcid,
499
+ "source-path": f"/project/{self.project_id}",
500
+ "bl": wiz["bl"],
501
+ "f.sid": wiz["fsid"],
502
+ "hl": "en",
503
+ "_reqid": str(self._next_reqid()),
504
+ "rt": "c",
505
+ }
506
+ body = requests.utils.quote(freq, safe="")
507
+ data = f"f.req={body}&at={requests.utils.quote(wiz['at'], safe='')}"
508
+ headers = {
509
+ "content-type": "application/x-www-form-urlencoded;charset=utf-8",
510
+ "x-same-domain": "1",
511
+ }
512
+ resp = self.session.post(
513
+ BATCHEXECUTE, params=params, data=data, headers=headers, timeout=self.timeout
514
+ )
515
+ self.log(f"POST {rpcid} -> {resp.status_code} ({len(resp.content)} bytes)")
516
+ if resp.status_code in (400, 401, 403) and retry_auth:
517
+ self.log(f"{rpcid} {resp.status_code}; refreshing WIZ tokens and retrying")
518
+ self.refresh_wiz()
519
+ return self.batchexecute(rpcid, inner, retry_auth=False)
520
+ if resp.status_code != 200:
521
+ raise FlowError(
522
+ f"{rpcid} HTTP {resp.status_code}: {resp.text[:400]!r}"
523
+ )
524
+ text = resp.text
525
+ self.last_response = text[:4000]
526
+ self._raise_if_recaptcha(text, rpcid)
527
+ return wrb_payloads(text, rpcid)
528
+
529
+ @staticmethod
530
+ def _raise_if_recaptcha(text: str, rpcid: str) -> None:
531
+ if "PUBLIC_ERROR_UNUSUAL_ACTIVITY" in text or "UNUSUAL_ACTIVITY" in text:
532
+ raise RecaptchaRejected(
533
+ "recaptcha token rejected (need fresh token) "
534
+ f"[{rpcid}: PUBLIC_ERROR_UNUSUAL_ACTIVITY]"
535
+ )
536
+ if "recaptcha" in text.lower() and "error" in text.lower():
537
+ raise RecaptchaRejected(
538
+ f"recaptcha token rejected (need fresh token) [{rpcid}: {text[:200]}]"
539
+ )
540
+
541
+ # -- reCAPTCHA ---------------------------------------------------------
542
+ def recaptcha_token(self, action: str, explicit: str | None = None) -> str:
543
+ if explicit:
544
+ return explicit
545
+ env = os.environ.get("FLOW_RECAPTCHA_TOKEN")
546
+ if env:
547
+ return env
548
+ token = load_recaptcha_token(self._token_file, action, max_age_s=TOKEN_MAX_AGE_S)
549
+ if token:
550
+ return token
551
+ if self.auto_mint:
552
+ return self.mint_recaptcha_token(action)
553
+ raise FlowError(
554
+ "no reCAPTCHA token: pass --recaptcha-token, --token-file, "
555
+ "FLOW_RECAPTCHA_TOKEN, or drop a JSON file in fixtures/tokens/"
556
+ )
557
+
558
+ def mint_recaptcha_token(self, action: str) -> str:
559
+ """Mint a token at call time via auth_lab/mint_token.py (headless Chromium).
560
+
561
+ Tokens are single-use and expire in ~2 min, so we mint and use immediately.
562
+ """
563
+ script = REPO_ROOT / "auth_lab" / "mint_token.py"
564
+ if not script.exists():
565
+ raise FlowError(f"cannot mint token: {script} missing")
566
+ with tempfile.TemporaryDirectory() as tmp:
567
+ token_path = Path(tmp) / "token.txt"
568
+ cmd = [
569
+ sys.executable,
570
+ str(script),
571
+ "--action",
572
+ action,
573
+ "--out",
574
+ str(token_path),
575
+ "--project",
576
+ self.project_id,
577
+ "--json",
578
+ ]
579
+ if self.cookie_file:
580
+ cmd += ["--cookies", self.cookie_file]
581
+ self.log(f"minting {action} token via {script.name}")
582
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180)
583
+ if proc.returncode != 0 or not token_path.exists():
584
+ raise FlowError(
585
+ f"token mint failed (exit {proc.returncode}): "
586
+ f"{(proc.stderr or proc.stdout)[-500:]}"
587
+ )
588
+ token = token_path.read_text().strip()
589
+ minted = {}
590
+ try:
591
+ minted = json.loads(proc.stdout.strip().splitlines()[-1])
592
+ except (ValueError, IndexError):
593
+ minted = {}
594
+ if not token:
595
+ raise FlowError("token mint produced an empty token")
596
+ if all(minted.get(k) for k in ("at", "bl", "fsid")):
597
+ self._wiz = {"at": minted["at"], "bl": minted["bl"], "fsid": minted["fsid"]}
598
+ self.log(f"minted {action} token ({len(token)} chars)")
599
+ return token
600
+
601
+ # -- image -------------------------------------------------------------
602
+ def generate_image(
603
+ self,
604
+ prompt: str,
605
+ out: str | Path | None = None,
606
+ recaptcha_token: str | None = None,
607
+ download: bool = True,
608
+ ) -> dict[str, Any]:
609
+ payloads = None
610
+ last_exc: RecaptchaRejected | None = None
611
+ for attempt in range(3):
612
+ if attempt == 0:
613
+ token = self.recaptcha_token(RECAPTCHA_ACTION_IMAGE, recaptcha_token)
614
+ else:
615
+ token = self.mint_recaptcha_token(RECAPTCHA_ACTION_IMAGE)
616
+ try:
617
+ payloads = self.batchexecute(
618
+ IMAGE_RPC, build_image_inner(prompt, self.project_id, token)
619
+ )
620
+ break
621
+ except RecaptchaRejected as exc:
622
+ last_exc = exc
623
+ if not self.auto_mint or recaptcha_token:
624
+ raise
625
+ self.log(
626
+ f"image token rejected (attempt {attempt + 1}/3); minting a fresh one"
627
+ )
628
+ time.sleep(RETRY_DELAYS_S[attempt])
629
+ if payloads is None:
630
+ raise last_exc or FlowError("image generation failed: no response")
631
+ if not payloads:
632
+ raise FlowError("ogiZ0b returned no wrb.fr payload")
633
+ payload = payloads[0]
634
+ urls = collect_urls(payload)
635
+ media_id = None
636
+ try:
637
+ media_id = payload[0][0][0]
638
+ except (IndexError, TypeError):
639
+ uuids = _UUID_RE.findall(json.dumps(payload))
640
+ media_id = uuids[0] if uuids else None
641
+ url = pick_download_url(urls, "image")
642
+ if not url and media_id:
643
+ url = self.fetch_media_url(media_id, kind="image")
644
+ if not url:
645
+ raise FlowError(
646
+ "no image URL in ogiZ0b response: " + json.dumps(payload)[:600]
647
+ )
648
+ result = {
649
+ "kind": "image",
650
+ "model": IMAGE_MODEL,
651
+ "prompt": prompt,
652
+ "media_id": media_id,
653
+ "url": url,
654
+ }
655
+ if download:
656
+ result.update(self.download(url, prompt, "image", out=out))
657
+ return result
658
+
659
+ # -- video -------------------------------------------------------------
660
+ def generate_video(
661
+ self,
662
+ prompt: str,
663
+ out: str | Path | None = None,
664
+ recaptcha_token: str | None = None,
665
+ timeout: int = 600,
666
+ poll_interval: float = 5.0,
667
+ download: bool = True,
668
+ media_id: str | None = None,
669
+ ) -> dict[str, Any]:
670
+ job_id = None
671
+ if media_id:
672
+ self.log(f"resuming existing video media {media_id}")
673
+ else:
674
+ payloads = None
675
+ last_exc: RecaptchaRejected | None = None
676
+ for attempt in range(3):
677
+ if attempt == 0:
678
+ token = self.recaptcha_token(RECAPTCHA_ACTION_VIDEO, recaptcha_token)
679
+ else:
680
+ token = self.mint_recaptcha_token(RECAPTCHA_ACTION_VIDEO)
681
+ try:
682
+ payloads = self.batchexecute(
683
+ VIDEO_RPC, build_video_inner(prompt, self.project_id, token)
684
+ )
685
+ break
686
+ except RecaptchaRejected as exc:
687
+ last_exc = exc
688
+ if not self.auto_mint or recaptcha_token:
689
+ raise
690
+ self.log(
691
+ f"video token rejected (attempt {attempt + 1}/3); minting a fresh one"
692
+ )
693
+ time.sleep(RETRY_DELAYS_S[attempt])
694
+ if payloads is None:
695
+ raise last_exc or FlowError("video generation failed: no response")
696
+ if not payloads:
697
+ raise FlowError("YhhmEf returned no wrb.fr payload")
698
+ payload = payloads[0]
699
+ job_id, media_id = self._parse_video_submit(payload)
700
+ self.log(f"video submitted: job={job_id} media={media_id}")
701
+ result = {
702
+ "kind": "video",
703
+ "model": VIDEO_MODEL,
704
+ "prompt": prompt,
705
+ "job_id": job_id,
706
+ "media_id": media_id,
707
+ }
708
+ if not download:
709
+ return result
710
+
711
+ deadline = time.time() + timeout
712
+ last_status: Any = None
713
+ while True:
714
+ urls, status = self.video_status(media_id)
715
+ if status != last_status:
716
+ self.log(f"video status {status!r} (media {media_id})")
717
+ last_status = status
718
+ url = pick_download_url(urls, "video")
719
+ if not url and (status is None or status != 2):
720
+ # rendering reported done: ask as29s for the media token
721
+ url = self.fetch_media_url(media_id, kind="video")
722
+ if url:
723
+ try:
724
+ result["url"] = url
725
+ result.update(self.download(url, prompt, "video", out=out))
726
+ return result
727
+ except FlowError as exc:
728
+ self.log(f"media not downloadable yet: {exc}")
729
+ if self._video_failed(status):
730
+ raise FlowError(f"video job failed, status={status!r}")
731
+ if time.time() >= deadline:
732
+ raise FlowError(
733
+ f"video polling timed out after {timeout}s, last status={status!r}"
734
+ )
735
+ time.sleep(poll_interval)
736
+
737
+ @staticmethod
738
+ def _parse_video_submit(payload: Any) -> tuple[str | None, str | None]:
739
+ job_id = media_id = None
740
+ try:
741
+ entry = payload[2][0]
742
+ job_id = entry[0]
743
+ media_id = entry[3][4] # poll id sits in the prompt/ids tuple
744
+ except (IndexError, TypeError, KeyError):
745
+ pass
746
+ uuids = _UUID_RE.findall(json.dumps(payload))
747
+ if not job_id and uuids:
748
+ job_id = uuids[0]
749
+ if not media_id:
750
+ media_id = uuids[1] if len(uuids) > 1 else job_id
751
+ return job_id, media_id
752
+
753
+ @staticmethod
754
+ def _video_status_value(entry: Any) -> Any:
755
+ """Status is read from the media entry. Two verified slots depending on
756
+ the capture: jwpduf -> entry[5][8] == [2], and the progress int that the
757
+ lead observed at entry[7][0][16]. 2 = rendering; 3 = ready (not a
758
+ failure)."""
759
+ if not isinstance(entry, list):
760
+ return None
761
+ try:
762
+ status = entry[5][8]
763
+ if isinstance(status, list) and status:
764
+ return status[0]
765
+ if isinstance(status, int):
766
+ return status
767
+ except (IndexError, TypeError):
768
+ pass
769
+ try:
770
+ meta = entry[7][0]
771
+ if isinstance(meta, list) and len(meta) > 16 and isinstance(meta[16], int):
772
+ return meta[16]
773
+ except (IndexError, TypeError):
774
+ pass
775
+ return None
776
+
777
+ @staticmethod
778
+ def _video_failed(status: Any) -> bool:
779
+ return isinstance(status, int) and status < 0
780
+
781
+ def video_status(self, media_id: str) -> tuple[list[str], Any]:
782
+ payloads = self.batchexecute(VIDEO_STATUS_RPC, [None, None, [[media_id]]])
783
+ if not payloads:
784
+ return [], None
785
+ payload = payloads[0]
786
+ urls = collect_urls(payload)
787
+ status = None
788
+ try:
789
+ status = self._video_status_value(payload[2][0])
790
+ except (IndexError, TypeError):
791
+ pass
792
+ return urls, status
793
+
794
+ def fetch_media_url(self, media_id: str, kind: str = "image") -> str | None:
795
+ try:
796
+ payloads = self.batchexecute(MEDIA_FETCH_RPC, [media_id, None, [1]])
797
+ except FlowError as exc:
798
+ self.log(f"as29s failed: {exc}")
799
+ return None
800
+ if not payloads:
801
+ return None
802
+ url = pick_download_url(collect_urls(payloads[0]), kind)
803
+ if url and kind == "video" and "/asb/" in url:
804
+ return asb_download_url(url) or url
805
+ return url
806
+
807
+ # -- download ----------------------------------------------------------
808
+ def download_media(
809
+ self, media_id: str, kind: str = "video", out: str | Path | None = None
810
+ ) -> dict[str, Any]:
811
+ """Download an existing media id without generating anything."""
812
+ url = self.fetch_media_url(media_id, kind=kind)
813
+ if not url:
814
+ raise FlowError(f"as29s returned no {kind} URL for media {media_id}")
815
+ result = self.download(url, prompt=f"media {media_id}", kind=kind, out=out)
816
+ result.update(
817
+ {
818
+ "kind": kind,
819
+ "model": "media",
820
+ "prompt": "",
821
+ "media_id": media_id,
822
+ "url": url,
823
+ }
824
+ )
825
+ return result
826
+
827
+ def download(
828
+ self,
829
+ url: str,
830
+ prompt: str,
831
+ kind: str,
832
+ out: str | Path | None = None,
833
+ ) -> dict[str, Any]:
834
+ candidates = [url]
835
+ if "/asb/" in url:
836
+ proxy = asb_download_url(url) if kind == "video" else asb_image_url(url)
837
+ if proxy:
838
+ candidates = [proxy] + [u for u in candidates if u != proxy]
839
+ last_error = ""
840
+ for candidate in candidates:
841
+ fresh = requests.Session()
842
+ if candidate.startswith(BASE):
843
+ ordered = [("cookies", self.session), ("cookieless", fresh)]
844
+ else:
845
+ ordered = [("cookieless", fresh), ("cookies", self.session)]
846
+ for label, session in ordered:
847
+ headers = {"accept": "*/*"}
848
+ if label == "cookies":
849
+ headers["referer"] = PAGE_URL.format(project=self.project_id)
850
+ try:
851
+ resp = session.get(
852
+ candidate,
853
+ headers=headers,
854
+ timeout=self.timeout,
855
+ allow_redirects=True,
856
+ )
857
+ except requests.RequestException as exc:
858
+ last_error = f"{label} {candidate[:80]}: {exc}"
859
+ continue
860
+ ctype = resp.headers.get("content-type", "")
861
+ ext = sniff_extension(resp.content)
862
+ wanted = IMAGE_EXTS if kind == "image" else VIDEO_EXTS
863
+ if resp.status_code == 200 and ext in wanted and "html" not in ctype:
864
+ target = self._target_path(prompt, ext, out)
865
+ target.parent.mkdir(parents=True, exist_ok=True)
866
+ target.write_bytes(resp.content)
867
+ self.log(
868
+ f"downloaded {kind} ({len(resp.content)} bytes) via {label} -> {target}"
869
+ )
870
+ return {"path": str(target), "bytes": len(resp.content), "via": label}
871
+ last_error = (
872
+ f"{label} {candidate[:80]}: HTTP {resp.status_code} {ctype!r} "
873
+ f"final={resp.url[:120]} first_bytes={resp.content[:16]!r}"
874
+ )
875
+ self.log(f"download attempt failed — {last_error}")
876
+ raise FlowError(f"could not download {kind}: {last_error}")
877
+
878
+ def _target_path(self, prompt: str, ext: str, out: str | Path | None) -> Path:
879
+ if out:
880
+ return Path(out).expanduser()
881
+ return self.out_dir / f"{timestamp()}_{slugify(prompt)}{ext}"