Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.
Python ai-toolsauto-captionscaptionscliffmpegmcpmcp-serveropusclip-alternativepodcast-clipspodcastsshortform-videovertical-videowhisper
Sign the CLI in through a browser, and cut in the cloud from it (#213)
Nika Siradze61e7ca876f95
diff --git a/backend/cli.py b/backend/cli.pyindex f1ae6fb..0764f47 100644--- a/backend/cli.py+++ b/backend/cli.py@@ -810,6 +810,13 @@ def cmd_process(args):)os.makedirs(output_dir, exist_ok=True)+ # Handed over before any local analysis: the cloud worker runs this same+ # engine, so transcribing here first would be the whole job done twice.+ if getattr(args, "cloud", False):+ from services import cloud_render+ cloud_render.main(video_path, config, output_dir, args)+ return+enc_info = get_encoder_info()print(f"\n podcli — processing")print(f" Encoder: {enc_info['best']} ({enc_info['system']})")@@ -2665,6 +2672,41 @@ def cmd_thumbnail_options(args):print(json.dumps({"texts": [list(t) for t in texts], "frames": frames}))+_BROWSER_IMAGE_FORMATS = {"PNG", "JPEG", "WEBP", "GIF", "AVIF", "BMP", "ICO"}+++def _check_frame(path):+ """Refuse a frame the renderer would fail to draw, while it is still a message.++ A thumbnail is an HTML page photographed by headless Chrome, so the frame is+ an <img>. A file the browser cannot decode is not an error there: the page+ renders anyway, the caption box and the logo land on bg_color, and this+ command exits 0 with a path to a blank card carrying a 15px broken-image+ glyph. A missing frame is worse, because it also moves the box to the+ no-photo height. Callers cannot tell either apart from a picture that+ worked, so neither is allowed past here.+ """+ if not os.path.exists(path):+ print(f"thumbnail render failed: no frame at {path}", file=sys.stderr)+ sys.exit(1)+ if path.lower().endswith(".svg"):+ return+ try:+ from PIL import Image+ with Image.open(path) as im:+ fmt = im.format+ except Exception as err:+ print(f"thumbnail render failed: {path} is not an image ({err})", file=sys.stderr)+ sys.exit(1)+ if fmt not in _BROWSER_IMAGE_FORMATS:+ print(+ f"thumbnail render failed: {path} is {fmt}, which the renderer cannot draw. "+ "Convert it to PNG, JPEG or WebP first.",+ file=sys.stderr,+ )+ sys.exit(1)++def cmd_thumbnail_render(args):"""Render one final thumbnail from a chosen frame + headline.@@ -2673,6 +2715,7 @@ def cmd_thumbnail_render(args):from services.thumbnail_ai import generate_thumbnail_with_templatefrom services.asset_store import resolve_logo+ _check_frame(args.frame)frame_info = json.loads(args.frame_info) if args.frame_info else Noneout = generate_thumbnail_with_template(title=args.title,@@ -3946,30 +3989,77 @@ def _apply_template(config: dict, name_or_id: str) -> None:def cmd_login(args):+ """+ Sign in through the browser, so no password is ever typed at a terminal.++ A password at the prompt lands in scrollback, and one passed as a flag lands+ in shell history and in `ps`. The browser already holds a session; this asks+ podcli.com to lend one to this machine.+ """import getpass+ import socket+ import time+ import webbrowserfrom services import podcli_cloud- email = (args.email or input("Email: ")).strip()- # Prefer the prompt: a password in argv is visible in ps output and lands in- # the user's shell history.- password = args.password or getpass.getpass("Password: ")- if not email or not password:- print("Email and password are required.")+ accent = "\033[38;2;212;135;74m"+ gray = "\033[38;5;245m"+ bold = "\033[1m"+ reset = "\033[0m"++ label = f"{getpass.getuser()}@{socket.gethostname()}"+ try:+ start = podcli_cloud.start_cli_auth(label)+ except podcli_cloud.CloudError as exc:+ print(f"Sign-in failed: {exc}")+ sys.exit(1)++ url, code = start["verifyUrl"], start["userCode"]+ print(f"\n Approve this machine at {accent}{url}{reset}")+ print(f" Your code is {bold}{code}{reset}")+ print(f" {gray}Only approve it if your browser shows the same code.{reset}\n")++ # A machine without a browser is the normal case over SSH, and opening one+ # there prints an error into the middle of the code we just asked them to+ # read. The link above is the fallback either way.+ if not args.no_browser:+ try:+ webbrowser.open(url)+ except Exception:+ pass++ interval = max(1, int(start.get("interval") or 3))+ deadline = time.monotonic() + int(start.get("expiresIn") or 600)+ session = None+ print(f" {gray}Waiting for approval…{reset}", end="", flush=True)+ while session is None and time.monotonic() < deadline:+ time.sleep(interval)+ try:+ session = podcli_cloud.poll_cli_auth(start["deviceCode"])+ except podcli_cloud.CloudError as exc:+ # A dropped connection mid-wait is not a refusal; the request is+ # still open on the server and the next poll picks it back up.+ if not exc.retryable and exc.status:+ print(f"\r {exc}{' ' * 20}")+ sys.exit(1)+ print("\r" + " " * 40 + "\r", end="")++ if session is None:+ print(" That code expired. Run `podcli login` again.")sys.exit(1)try:- podcli_cloud.login(email, password)account = podcli_cloud.me()podcli_cloud.remember_plan(account.get("plan", ""))except podcli_cloud.CloudError as exc:- print(f"Sign-in failed: {exc}")+ print(f"Signed in, but the account could not be read: {exc}")sys.exit(1)workspace = account.get("workspace") or {}- print(f"Signed in to {workspace.get('name', 'your workspace')} "+ print(f" Signed in to {workspace.get('name', 'your workspace')} "f"({account.get('plan', 'free')} plan, {account.get('role', 'member')}).")if account.get("plan") == "free":- print("This workspace has no active subscription — podcli will keep using "+ print(" This workspace has no active subscription — podcli will keep using ""your local AI CLI until one starts.")# Everything already rendered on this machine belongs in the workspace too,@@ -3979,9 +4069,9 @@ def cmd_login(args):except Exception:synced, failed = 0, 0if synced:- print(f"Synced {synced} existing clip{'s' if synced != 1 else ''} to your workspace.")+ print(f" Synced {synced} existing clip{'s' if synced != 1 else ''} to your workspace.")if failed:- print(f"{failed} could not be synced — `podcli whoami` will retry later.")+ print(f" {failed} could not be synced — `podcli whoami` will retry later.")def cmd_logout(args):@@ -3990,6 +4080,12 @@ def cmd_logout(args):if not podcli_cloud.signed_in():print("Not signed in.")return+ # The local file goes either way: a server that cannot be reached is not a+ # reason to leave a machine looking signed in.+ try:+ podcli_cloud.revoke_session()+ except podcli_cloud.CloudError as exc:+ print(f"Signed out here, but the session may still be live: {exc}")podcli_cloud.clear_token()print("Signed out. podcli will use your local AI CLI from now on.")@@ -4263,9 +4359,9 @@ def main():sub = parser.add_subparsers(dest="command")# ── podcli Pro account ──- login_p = sub.add_parser("login", help="Sign in to podcli Pro")- login_p.add_argument("--email", help="Account email (prompted if omitted)")- login_p.add_argument("--password", help="Password (prompted if omitted; prefer the prompt)")+ login_p = sub.add_parser("login", help="Sign in to podcli Pro through your browser")+ login_p.add_argument("--no-browser", action="store_true",+ help="Print the link instead of opening it, for SSH sessions")sub.add_parser("logout", help="Sign out of podcli Pro on this machine")sub.add_parser("whoami", help="Show the signed-in podcli Pro account")ws_p = sub.add_parser("workspace", help="Switch between shows in podcli Pro")@@ -4283,6 +4379,10 @@ def main():proc.add_argument("-n", "--top", type=int, help="Number of top clips to export (default: 5)")proc.add_argument("-o", "--output", help="Output directory (default: ./clips)")proc.add_argument("-p", "--preset", help="Load a saved preset")+ proc.add_argument("--cloud", action="store_true",+ help="Render on podcli.com instead of this machine (needs `podcli login`)")+ proc.add_argument("--template-id",+ help="Cut in a saved cloud template, by id (with --cloud)")proc.add_argument("--engine", choices=["whisper-py", "whispercpp", "assemblyai"], help="Transcription engine (default: whisper-py; whispercpp is local; assemblyai uses ASSEMBLYAI_API_KEY)")proc.add_argument("--language", help="Language of the recording (e.g. es, pt-BR, ka). Auto-detect if omitted.")proc.add_argument("--assemblyai-api-key", help="AssemblyAI API key for --engine assemblyai. Prefer ASSEMBLYAI_API_KEY; command-line secrets can appear in process listings.")diff --git a/backend/services/cloud_render.py b/backend/services/cloud_render.pynew file mode 100644index 0000000..3e07dbf--- /dev/null+++ b/backend/services/cloud_render.py@@ -0,0 +1,251 @@+"""+Cutting an episode on podcli.com instead of on this machine.++The engine here and the engine the cloud worker runs are the same code, so this+module renders nothing. It uploads the recording, queues the render the studio+would have queued, follows it, and brings the finished clips back down to the+same output folder a local run would have written.++The chain is the one the web studio uses:++ POST /v1/jobs/sources reserve a place and get somewhere to PUT to+ PUT <signed url> the bytes, straight to object storage+ POST /v1/jobs/sources/:id/complete+ POST /v1/jobs queue the render+ GET /v1/jobs/:id follow it+ GET /v1/episodes find what it made+"""++import os+import sys+import time+import urllib.error+import urllib.request++from services import podcli_cloud++ACCENT = "\033[38;2;212;135;74m"+GRAY = "\033[38;5;245m"+RESET = "\033[0m"++POLL_SECONDS = 3+# A queue can be long and an episode is an hour of video. This is a ceiling on+# waiting, not an expectation of it.+MAX_WAIT_SECONDS = 6 * 3600+++class CloudRenderError(Exception):+ pass+++def run(video_path: str, config: dict, output_dir: str, args) -> None:+ """Render one episode in the cloud and download the clips it produced."""+ if not podcli_cloud.signed_in():+ raise CloudRenderError(+ "cloud rendering needs a podcli Pro session — run `podcli login`")++ size = os.path.getsize(video_path)+ print(f"\n podcli — rendering in the cloud")+ print(f" Video: {os.path.basename(video_path)} ({_megabytes(size)})")+ print(f" Output: {output_dir}/\n")++ source_id = _upload(video_path, size)+ job = podcli_cloud.request("POST", "/v1/jobs", {+ "sourceId": source_id,+ "kind": "render",+ "params": _params(config, args),+ **({"templateId": args.template_id} if getattr(args, "template_id", None) else {}),+ }, timeout=60)++ print(f" Queued as {GRAY}{job['id']}{RESET}")+ finished = _follow(job["id"])++ made = (finished.get("result") or {}).get("clips")+ print(f"\n Rendered {made if made is not None else 'the'} "+ f"clip{'' if made == 1 else 's'} in the cloud.")+ downloaded = _download_clips(source_id, output_dir)+ if downloaded:+ print(f" Saved {downloaded} file{'' if downloaded == 1 else 's'} to {output_dir}/")+ else:+ print(f" {GRAY}Nothing to download yet — see them at podcli.com/app{RESET}")+++def _params(config: dict, args) -> dict:+ """+ The look, in the shape the worker takes it.++ Only what the cloud understands is sent. Everything else in a local config,+ such as a logo file on this disk, means nothing to a machine that cannot+ see this disk, and the workspace's own template covers it there.+ """+ params = {+ "topN": config.get("top_clips"),+ "captionStyle": config.get("caption_style"),+ "crop": config.get("crop_strategy"),+ "format": config.get("format"),+ "quality": config.get("quality"),+ "profile": config.get("profile"),+ "thumbnails": config.get("generate_thumbnails"),+ }+ if config.get("fast_mode"):+ params["fast"] = True+ return {key: value for key, value in params.items() if value is not None}+++def _upload(video_path: str, size: int) -> str:+ opened = podcli_cloud.request("POST", "/v1/jobs/sources", {+ "filename": os.path.basename(video_path),+ "sizeBytes": size,+ }, timeout=60)++ multipart = opened.get("multipart")+ if not multipart:+ with open(video_path, "rb") as fh:+ _put(opened["uploadUrl"], fh.read(), size, 1, 1)+ parts = None+ else:+ parts = _upload_parts(video_path, size, multipart)++ podcli_cloud.request(+ "POST", f"/v1/jobs/sources/{opened['sourceId']}/complete",+ {"parts": parts} if parts else {}, timeout=120)+ print(f"\r Uploaded {_megabytes(size)}{' ' * 24}")+ return opened["sourceId"]+++def _upload_parts(video_path: str, size: int, multipart: dict) -> list:+ part_size, urls = multipart["partSize"], multipart["urls"]+ parts = []+ with open(video_path, "rb") as fh:+ for index, url in enumerate(urls, start=1):+ chunk = fh.read(part_size)+ if not chunk:+ break+ # S3 identifies a finished part by the ETag it answers the PUT with,+ # so a part uploaded without reading that header cannot be joined.+ etag = _put(url, chunk, size, index, len(urls))+ if not etag:+ raise CloudRenderError(+ f"storage did not return an ETag for part {index}, so the "+ "upload cannot be completed")+ parts.append({"partNumber": index, "etag": etag})+ return parts+++def _put(url: str, body: bytes, total: int, index: int, count: int) -> str:+ done = min(total, index * len(body)) if count > 1 else total+ print(f"\r Uploading {_megabytes(done)} of {_megabytes(total)}"+ f"{f' (part {index}/{count})' if count > 1 else ''}…",+ end="", flush=True)++ req = urllib.request.Request(url, data=body, method="PUT",+ headers={"content-type": "application/octet-stream"})+ try:+ with urllib.request.urlopen(req, timeout=1800) as response:+ return (response.headers.get("ETag") or "").strip('"')+ except urllib.error.HTTPError as exc:+ raise CloudRenderError(f"upload failed: HTTP {exc.code}") from None+ except urllib.error.URLError as exc:+ raise CloudRenderError(f"upload failed: {exc.reason}") from None+++def _follow(job_id: str) -> dict:+ """Print what the worker is doing until it stops doing it."""+ deadline = time.monotonic() + MAX_WAIT_SECONDS+ last = ""+ while time.monotonic() < deadline:+ time.sleep(POLL_SECONDS)+ try:+ job = podcli_cloud.request("GET", f"/v1/jobs/{job_id}", timeout=30)+ except podcli_cloud.CloudError as exc:+ # A render that takes an hour will outlive the odd bad minute. Only+ # an answer that will not change is worth giving up on.+ if exc.retryable or not exc.status:+ continue+ raise CloudRenderError(str(exc)) from None++ status = job.get("status")+ if status in ("done", "failed", "canceled"):+ print("\r" + " " * len(last) + "\r", end="")+ if status != "done":+ raise CloudRenderError(job.get("error") or f"the render was {status}")+ return job++ line = (f" {ACCENT}{job.get('progress', 0)}%{RESET} "+ f"{job.get('stage') or status}"+ f"{' — ' + job['detail'] if job.get('detail') else ''}")+ print("\r" + " " * len(last) + "\r" + line, end="", flush=True)+ last = line++ raise CloudRenderError("gave up waiting; the render is still running at podcli.com/app")+++def _download_clips(source_id: str, output_dir: str) -> int:+ """+ Bring down what the render made.++ Found through the episode rather than through the job: the job's result+ counts the clips, and the episode is what they hang off.+ """+ episodes = podcli_cloud.request("GET", "/v1/episodes", timeout=60).get("episodes", [])+ episode = next((e for e in episodes if e.get("source_id") == source_id), None)+ if not episode:+ return 0++ detail = podcli_cloud.request("GET", f"/v1/episodes/{episode['id']}", timeout=60)+ saved = 0+ for clip in detail.get("clips", []):+ if not clip.get("video"):+ continue+ name = _filename(clip, saved + 1)+ try:+ _download(clip["video"], os.path.join(output_dir, name))+ except CloudRenderError as exc:+ print(f" {GRAY}{name}: {exc}{RESET}")+ continue+ saved += 1+ return saved+++def _filename(clip: dict, position: int) -> str:+ title = "".join(+ char if char.isalnum() or char in " -_" else "_"+ for char in (clip.get("title") or "clip")+ ).strip().replace(" ", "_")[:60]+ return f"{position:02d}_{title or 'clip'}.mp4"+++def _download(url: str, path: str) -> None:+ print(f"\r Downloading {os.path.basename(path)}…{' ' * 12}", end="", flush=True)+ try:+ with urllib.request.urlopen(url, timeout=900) as response, \+ open(path, "wb") as fh:+ while True:+ chunk = response.read(1 << 20)+ if not chunk:+ break+ fh.write(chunk)+ except urllib.error.HTTPError as exc:+ raise CloudRenderError(f"HTTP {exc.code}") from None+ except urllib.error.URLError as exc:+ raise CloudRenderError(str(exc.reason)) from None+ finally:+ print("\r" + " " * 60 + "\r", end="")+++def _megabytes(size: int) -> str:+ if size >= 1 << 30:+ return f"{size / (1 << 30):.1f} GB"+ return f"{size / (1 << 20):.0f} MB"+++def main(video_path: str, config: dict, output_dir: str, args) -> None:+ """Entry point for the CLI, which reports failures rather than raising."""+ try:+ run(video_path, config, output_dir, args)+ except CloudRenderError as exc:+ print(f"\n Cloud render failed: {exc}", file=sys.stderr)+ sys.exit(1)+ except podcli_cloud.CloudError as exc:+ print(f"\n Cloud render failed: {exc}", file=sys.stderr)+ sys.exit(1)diff --git a/backend/services/podcli_cloud.py b/backend/services/podcli_cloud.pyindex 8b0da9c..1c42b97 100644--- a/backend/services/podcli_cloud.py+++ b/backend/services/podcli_cloud.py@@ -111,6 +111,16 @@ def entitled() -> bool:return plan in PAID_PLANS+def revoke_session() -> None:+ """+ End this machine's session at the server, not just on disk.++ Deleting the file alone leaves the token live for its full month, so a+ laptop signed out because it was about to be lost stays signed in.+ """+ request("POST", "/v1/auth/logout", {}, timeout=15)++def clear_token() -> None:try:os.unlink(_auth_path())@@ -376,21 +386,43 @@ def me() -> dict:return request("GET", "/v1/auth/me", timeout=30)-def login(email: str, password: str) -> dict:- """Exchange credentials for a session token. Does not require an existing one."""- data = json.dumps({"email": email, "password": password}).encode("utf-8")+def start_cli_auth(label: str) -> dict:+ """+ Open a sign-in that the browser will approve.++ Returns the device code the CLI keeps to itself, the short code the person+ matches across the two screens, and the link to approve it at. No existing+ session is needed, and no credential is taken here.+ """+ return _unauthenticated("POST", "/v1/auth/cli", {"label": label})+++def poll_cli_auth(device_code: str) -> Optional[dict]:+ """+ Ask whether the browser has approved yet.++ None means keep waiting. A dict is the session, and is written to disk+ before returning so a crash between here and the caller cannot lose the one+ token this device code will ever mint.+ """+ payload = _unauthenticated("POST", "/v1/auth/cli/poll", {"deviceCode": device_code})+ if payload.get("status") == "pending":+ return None+ write_token(payload["token"], payload.get("workspaceId", ""))+ return payload+++def _unauthenticated(method: str, path: str, body: dict) -> dict:+ """Like `request`, for the endpoints that run before there is a session."""req = urllib.request.Request(- f"{api_url()}/v1/auth/login", data=data, method="POST",+ f"{api_url()}{path}", data=json.dumps(body).encode("utf-8"), method=method,headers={"content-type": "application/json"},)try:with urllib.request.urlopen(req, timeout=30) as response:- payload = json.loads(response.read().decode("utf-8"))+ return json.loads(response.read().decode("utf-8"))except urllib.error.HTTPError as exc:- detail, _ = _describe(exc)- raise CloudError(detail, status=exc.code) from None+ detail, retryable = _describe(exc)+ raise CloudError(detail, status=exc.code, retryable=retryable) from Noneexcept urllib.error.URLError as exc:raise CloudError(f"could not reach {api_url()}: {exc.reason}") from None-- write_token(payload["token"], payload.get("workspaceId", ""))- return payloaddiff --git a/backend/services/thumbnail_html.py b/backend/services/thumbnail_html.pyindex eb093f0..81f6f11 100644--- a/backend/services/thumbnail_html.py+++ b/backend/services/thumbnail_html.py@@ -460,7 +460,10 @@ def _build_html(photo_css = ""photo_uri = ""if has_photo:- photo_uri = f"file://{os.path.abspath(photo_path)}"+ # as_uri() rather than an f-string: a '#' or '?' anywhere in the path is+ # a fragment or a query to the browser, so the image silently drops and+ # the card renders as bg_color with a broken-image glyph.+ photo_uri = Path(photo_path).absolute().as_uri()brightness = cfg.get("photo_brightness", 0.85)photo_css = f""".photo {{@@ -471,7 +474,7 @@ def _build_html(.photo img {{width: 100%; height: 100%;object-fit: cover;- object-position: center center;+ object-position: {cfg.get("photo_object_position", "center center")};filter: brightness({brightness});}}.photo-vignette {{@@ -485,7 +488,7 @@ def _build_html(layers_html = _layer_html(cfg.get("layers"))logo_pos = cfg.get("logo_position", "none")if logo_path and os.path.exists(logo_path) and logo_pos != "none":- logo_uri = f"file://{os.path.abspath(logo_path)}"+ logo_uri = Path(logo_path).absolute().as_uri()logo_h = cfg.get("logo_height", "50px")logo_margin = cfg.get("logo_margin", "50px")logo_opacity = cfg.get("logo_opacity", 0.35)@@ -555,7 +558,9 @@ def _build_html(l1_lh = cfg.get("line1_line_height", 1.15)l1_mb = cfg.get("line1_margin_bottom", "10px")l1_color = cfg.get("line1_color", "#FFFFFF")- l1_nowrap = "nowrap" # Always nowrap — we shrink to fit instead+ # Shrinking to fit is the default, so line 1 stays on one line. A template+ # that turns it off is asking to wrap instead.+ l1_nowrap = "nowrap" if cfg.get("line1_nowrap", True) else "normal"l2_weight = cfg.get("line2_font_weight", "500")l2_style = cfg.get("line2_font_style", "italic")diff --git a/tests/test_browser_login.py b/tests/test_browser_login.pynew file mode 100644index 0000000..c873345--- /dev/null+++ b/tests/test_browser_login.py@@ -0,0 +1,93 @@+import io+import json+import os+import sys+import tempfile+import unittest+import urllib.error+from unittest import mock++sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "backend"))++from services import podcli_cloud # noqa: E402+++def http_error(code, body):+ return urllib.error.HTTPError(+ "https://api.podcli.com", code, "err", {},+ io.BytesIO(json.dumps(body).encode("utf-8")))+++class BrowserLoginTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.mkdtemp()+ patcher = mock.patch.dict(podcli_cloud.paths, {"home": self.tmp})+ patcher.start()+ self.addCleanup(patcher.stop)+ env = mock.patch.dict(os.environ, {"PODCLI_TOKEN": ""})+ env.start()+ self.addCleanup(env.stop)++ def test_the_cli_never_offers_to_take_a_password(self):+ self.assertFalse(hasattr(podcli_cloud, "login"))++ def test_starting_asks_for_a_code_and_takes_no_credential(self):+ with mock.patch.object(podcli_cloud, "_unauthenticated") as call:+ call.return_value = {"deviceCode": "d", "userCode": "BCDF-2345"}+ podcli_cloud.start_cli_auth("nik@studio")++ method, path, body = call.call_args[0]+ self.assertEqual((method, path), ("POST", "/v1/auth/cli"))+ self.assertEqual(body, {"label": "nik@studio"})++ def test_a_pending_poll_is_not_a_session(self):+ with mock.patch.object(podcli_cloud, "_unauthenticated") as call:+ call.return_value = {"status": "pending", "interval": 3}+ self.assertIsNone(podcli_cloud.poll_cli_auth("d"))+ self.assertFalse(podcli_cloud.signed_in())++ def test_an_approved_poll_writes_the_session_to_disk(self):+ with mock.patch.object(podcli_cloud, "_unauthenticated") as call:+ call.return_value = {"token": "sess-abc", "workspaceId": "w1"}+ podcli_cloud.poll_cli_auth("d")++ self.assertEqual(podcli_cloud.read_token(), "sess-abc")+ self.assertEqual(podcli_cloud._auth_data()["workspace_id"], "w1")++ @unittest.skipIf(os.name == "nt", "Unix file modes are not enforced on Windows")+ def test_the_token_file_is_not_readable_by_other_users(self):+ with mock.patch.object(podcli_cloud, "_unauthenticated") as call:+ call.return_value = {"token": "sess-abc", "workspaceId": "w1"}+ podcli_cloud.poll_cli_auth("d")++ mode = os.stat(os.path.join(self.tmp, "auth.json")).st_mode+ self.assertEqual(mode & 0o077, 0)++ def test_a_denied_request_is_final_rather_than_worth_retrying(self):+ with mock.patch("urllib.request.urlopen",+ side_effect=http_error(403, {"error": "sign-in was denied"})):+ with self.assertRaises(podcli_cloud.CloudError) as caught:+ podcli_cloud.poll_cli_auth("d")++ self.assertFalse(caught.exception.retryable)+ self.assertIn("denied", str(caught.exception))++ def test_being_rate_limited_while_waiting_is_worth_retrying(self):+ with mock.patch("urllib.request.urlopen",+ side_effect=http_error(429, {"error": "slow down"})):+ with self.assertRaises(podcli_cloud.CloudError) as caught:+ podcli_cloud.poll_cli_auth("d")++ self.assertTrue(caught.exception.retryable)++ def test_a_dropped_connection_carries_no_status_to_give_up_on(self):+ with mock.patch("urllib.request.urlopen",+ side_effect=urllib.error.URLError("connection reset")):+ with self.assertRaises(podcli_cloud.CloudError) as caught:+ podcli_cloud.poll_cli_auth("d")++ self.assertEqual(caught.exception.status, 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_cloud_render.py b/tests/test_cloud_render.pynew file mode 100644index 0000000..d688e53--- /dev/null+++ b/tests/test_cloud_render.py@@ -0,0 +1,188 @@+import argparse+import os+import sys+import tempfile+import unittest+from unittest import mock++sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "backend"))++from services import cloud_render, podcli_cloud # noqa: E402+++class FakePut:+ """Stands in for object storage, recording what was PUT where."""++ def __init__(self):+ self.puts = []++ def __call__(self, url, body, total, index, count):+ self.puts.append((url, len(body)))+ return f"etag-{index}"+++class ParamsTests(unittest.TestCase):+ def test_only_what_the_worker_understands_is_sent(self):+ params = cloud_render._params({+ "top_clips": 6,+ "caption_style": "hormozi",+ "crop_strategy": "speaker",+ "format": "vertical",+ "logo_path": "/Users/nik/logo.png",+ "outro_path": "/Users/nik/outro.mp4",+ }, argparse.Namespace())++ self.assertEqual(params["topN"], 6)+ self.assertEqual(params["captionStyle"], "hormozi")+ self.assertEqual(params["crop"], "speaker")+ # A path on this disk means nothing to a machine that cannot see it.+ self.assertNotIn("logo_path", params)+ self.assertNotIn("outro_path", params)++ def test_keys_the_config_never_set_are_left_out_entirely(self):+ params = cloud_render._params({"top_clips": 3}, argparse.Namespace())+ self.assertEqual(set(params), {"topN"})++ def test_fast_mode_is_passed_through_as_a_draft(self):+ params = cloud_render._params({"fast_mode": True}, argparse.Namespace())+ self.assertTrue(params["fast"])+++class UploadTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.mkdtemp()+ self.video = os.path.join(self.tmp, "episode.mp4")+ with open(self.video, "wb") as fh:+ fh.write(b"x" * 2500)++ def test_a_small_file_goes_up_in_one_put(self):+ put = FakePut()+ with mock.patch.object(cloud_render, "_put", put), \+ mock.patch.object(podcli_cloud, "request") as api:+ api.return_value = {"sourceId": "s1", "uploadUrl": "https://store/put"}+ source_id = cloud_render._upload(self.video, 2500)++ self.assertEqual(source_id, "s1")+ self.assertEqual(put.puts, [("https://store/put", 2500)])+ # Completing a single PUT must not claim a part list it never made.+ self.assertEqual(api.call_args_list[-1][0][2], {})++ def test_a_large_file_goes_up_in_pieces_and_reports_their_etags(self):+ put = FakePut()+ with mock.patch.object(cloud_render, "_put", put), \+ mock.patch.object(podcli_cloud, "request") as api:+ api.return_value = {+ "sourceId": "s1",+ "multipart": {"partSize": 1000, "urls": ["u1", "u2", "u3"]},+ }+ cloud_render._upload(self.video, 2500)++ self.assertEqual([size for _, size in put.puts], [1000, 1000, 500])+ self.assertEqual(api.call_args_list[-1][0][2], {"parts": [+ {"partNumber": 1, "etag": "etag-1"},+ {"partNumber": 2, "etag": "etag-2"},+ {"partNumber": 3, "etag": "etag-3"},+ ]})++ def test_a_part_with_no_etag_stops_the_upload_rather_than_completing_it(self):+ with mock.patch.object(cloud_render, "_put", return_value=""), \+ mock.patch.object(podcli_cloud, "request") as api:+ api.return_value = {+ "sourceId": "s1",+ "multipart": {"partSize": 1000, "urls": ["u1", "u2", "u3"]},+ }+ with self.assertRaises(cloud_render.CloudRenderError):+ cloud_render._upload(self.video, 2500)++ # Only the opening call happened: nothing was marked complete.+ self.assertEqual(len(api.call_args_list), 1)+++class FollowTests(unittest.TestCase):+ def setUp(self):+ patcher = mock.patch.object(cloud_render.time, "sleep")+ patcher.start()+ self.addCleanup(patcher.stop)++ def test_a_finished_render_is_returned(self):+ with mock.patch.object(podcli_cloud, "request") as api:+ api.side_effect = [+ {"status": "running", "progress": 20, "stage": "transcribing"},+ {"status": "done", "progress": 100, "result": {"clips": 4}},+ ]+ job = cloud_render._follow("j1")++ self.assertEqual(job["result"]["clips"], 4)++ def test_a_failed_render_says_why(self):+ with mock.patch.object(podcli_cloud, "request") as api:+ api.return_value = {"status": "failed", "error": "no speech found"}+ with self.assertRaises(cloud_render.CloudRenderError) as caught:+ cloud_render._follow("j1")++ self.assertIn("no speech found", str(caught.exception))++ def test_a_bad_minute_does_not_abandon_an_hour_long_render(self):+ with mock.patch.object(podcli_cloud, "request") as api:+ api.side_effect = [+ podcli_cloud.CloudError("gateway", status=503, retryable=True),+ podcli_cloud.CloudError("connection reset"),+ {"status": "done", "progress": 100, "result": {"clips": 1}},+ ]+ job = cloud_render._follow("j1")++ self.assertEqual(job["status"], "done")++ def test_a_revoked_session_stops_the_wait(self):+ with mock.patch.object(podcli_cloud, "request") as api:+ api.side_effect = podcli_cloud.CloudError("session expired", status=401)+ with self.assertRaises(cloud_render.CloudRenderError):+ cloud_render._follow("j1")+++class DownloadTests(unittest.TestCase):+ def setUp(self):+ self.out = tempfile.mkdtemp()++ def test_clips_land_in_the_output_folder_under_readable_names(self):+ with mock.patch.object(podcli_cloud, "request") as api, \+ mock.patch.object(cloud_render, "_download") as download:+ api.side_effect = [+ {"episodes": [{"id": "e1", "source_id": "s1"}]},+ {"clips": [+ {"title": "The 3 rules of hiring", "video": "https://store/1"},+ {"title": "Why it/works", "video": "https://store/2"},+ ]},+ ]+ saved = cloud_render._download_clips("s1", self.out)++ self.assertEqual(saved, 2)+ names = [os.path.basename(call[0][1]) for call in download.call_args_list]+ self.assertEqual(names, ["01_The_3_rules_of_hiring.mp4", "02_Why_it_works.mp4"])++ def test_a_clip_whose_video_has_not_landed_yet_is_skipped(self):+ with mock.patch.object(podcli_cloud, "request") as api, \+ mock.patch.object(cloud_render, "_download"):+ api.side_effect = [+ {"episodes": [{"id": "e1", "source_id": "s1"}]},+ {"clips": [{"title": "Pending", "video": None}]},+ ]+ self.assertEqual(cloud_render._download_clips("s1", self.out), 0)++ def test_another_upload_s_episode_is_not_mistaken_for_this_one(self):+ with mock.patch.object(podcli_cloud, "request") as api:+ api.return_value = {"episodes": [{"id": "e9", "source_id": "someone-else"}]}+ self.assertEqual(cloud_render._download_clips("s1", self.out), 0)+++class GateTests(unittest.TestCase):+ def test_rendering_in_the_cloud_needs_a_session(self):+ with mock.patch.object(podcli_cloud, "signed_in", return_value=False):+ with self.assertRaises(cloud_render.CloudRenderError) as caught:+ cloud_render.run("/tmp/x.mp4", {}, "/tmp", argparse.Namespace())++ self.assertIn("podcli login", str(caught.exception))+++if __name__ == "__main__":+ unittest.main()