@cliptude/cli 0.1.5 → 0.1.9

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.
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import mimetypes
6
7
  import os
7
8
  from contextvars import ContextVar
8
9
  from pathlib import Path
@@ -13,9 +14,7 @@ import httpx
13
14
  from cliptude_mcp.credentials import stored_access_token
14
15
 
15
16
  DEFAULT_SAAS_URL = "https://cliptude.com"
16
- FACELESS_EXPLAINER_FORMAT = "faceless_explainer"
17
- FACELESS_CODING_EXTERNAL = "external"
18
- FACELESS_CODING_CLIPTUDE = "cliptude"
17
+ TALKING_HEAD_EXTS = {".mp4", ".mov", ".webm", ".avi"}
19
18
  _request_token: ContextVar[str | None] = ContextVar("cliptude_request_token", default=None)
20
19
 
21
20
 
@@ -75,6 +74,48 @@ class CliptudeApiError(Exception):
75
74
  self.payload = payload
76
75
 
77
76
 
77
+ def _talking_head_content_type(ext: str) -> str:
78
+ return {
79
+ ".mp4": "video/mp4",
80
+ ".mov": "video/quicktime",
81
+ ".webm": "video/webm",
82
+ ".avi": "video/x-msvideo",
83
+ }.get((ext or "").lower(), "video/mp4")
84
+
85
+
86
+ def _probe_local_video_duration_seconds(path: Path) -> float | None:
87
+ """Return duration via ffprobe when available; None if ffprobe is missing or fails."""
88
+ import shutil
89
+ import subprocess
90
+
91
+ ffprobe = shutil.which("ffprobe")
92
+ if not ffprobe:
93
+ return None
94
+ try:
95
+ result = subprocess.run(
96
+ [
97
+ ffprobe,
98
+ "-v",
99
+ "error",
100
+ "-show_entries",
101
+ "format=duration",
102
+ "-of",
103
+ "default=noprint_wrappers=1:nokey=1",
104
+ str(path),
105
+ ],
106
+ capture_output=True,
107
+ text=True,
108
+ timeout=30,
109
+ check=False,
110
+ )
111
+ value = float((result.stdout or "").strip())
112
+ if value > 0:
113
+ return value
114
+ except (OSError, ValueError, subprocess.TimeoutExpired):
115
+ return None
116
+ return None
117
+
118
+
78
119
  def _resolve_token(explicit: str | None) -> str:
79
120
  return (
80
121
  (explicit or "").strip()
@@ -84,9 +125,79 @@ def _resolve_token(explicit: str | None) -> str:
84
125
  )
85
126
 
86
127
 
128
+ def _avatar_job_fields(
129
+ avatar_intro_only: bool | None,
130
+ avatar_ai_footage: bool | None,
131
+ *,
132
+ as_strings: bool = False,
133
+ avatar_profile_id: int | str | None = None,
134
+ avatar_engine: str | None = None,
135
+ ) -> dict[str, Any]:
136
+ fields: dict[str, Any] = {}
137
+ if avatar_profile_id not in (None, ""):
138
+ fields["avatar_profile_id"] = str(avatar_profile_id) if as_strings else int(avatar_profile_id)
139
+ if avatar_engine:
140
+ fields["avatar_engine"] = str(avatar_engine).strip().lower()
141
+ if avatar_intro_only is not None:
142
+ fields["avatar_intro_only"] = (
143
+ ("true" if avatar_intro_only else "false") if as_strings else bool(avatar_intro_only)
144
+ )
145
+ if avatar_ai_footage is not None:
146
+ fields["avatar_ai_footage"] = (
147
+ ("true" if avatar_ai_footage else "false") if as_strings else bool(avatar_ai_footage)
148
+ )
149
+ return fields
150
+
151
+
152
+ def _thumbnail_job_field(thumbnail: dict[str, str] | None, *, as_string: bool = False) -> dict[str, Any]:
153
+ """create_job's per-job thumbnail ({custom_prompt} or {reference_url}); multipart sends it as JSON text."""
154
+ cleaned = {k: str(v).strip() for k, v in (thumbnail or {}).items() if v is not None and str(v).strip()}
155
+ if not cleaned:
156
+ return {}
157
+ return {"thumbnail": json.dumps(cleaned) if as_string else cleaned}
158
+
159
+
160
+ def _motion_control_job_fields(
161
+ *,
162
+ disable_animations: bool | None = None,
163
+ disable_overlays: bool | None = None,
164
+ disable_effects: bool | None = None,
165
+ disable_transitions: bool | None = None,
166
+ excluded_animation_types: list[str] | None = None,
167
+ excluded_transition_kinds: list[str] | None = None,
168
+ as_strings: bool = False,
169
+ ) -> dict[str, Any]:
170
+ fields: dict[str, Any] = {}
171
+ bool_fields = {
172
+ "disable_animations": disable_animations,
173
+ "disable_overlays": disable_overlays,
174
+ "disable_effects": disable_effects,
175
+ "disable_transitions": disable_transitions,
176
+ }
177
+ for key, value in bool_fields.items():
178
+ if value is not None:
179
+ fields[key] = ("true" if value else "false") if as_strings else bool(value)
180
+ list_fields = {
181
+ "excluded_animation_types": excluded_animation_types,
182
+ "excluded_transition_kinds": excluded_transition_kinds,
183
+ }
184
+ for key, value in list_fields.items():
185
+ if value is not None:
186
+ fields[key] = ",".join(value) if as_strings else list(value)
187
+ return fields
188
+
189
+
87
190
  class CliptudeClient:
88
- def __init__(self, base_url: str | None = None, api_key: str | None = None, timeout: float = 30.0):
191
+ def __init__(
192
+ self,
193
+ base_url: str | None = None,
194
+ api_key: str | None = None,
195
+ timeout: float = 30.0,
196
+ client_kind: str | None = None,
197
+ ):
89
198
  self.base_url = (base_url or resolve_base_url()).rstrip("/")
199
+ # "cli" or "mcp": sent as X-Cliptude-Client so Cliptude records where a job was started.
200
+ self.client_kind = (client_kind or os.environ.get("CLIPTUDE_CLIENT_KIND") or "").strip().lower()
90
201
  self.api_key = _resolve_token(api_key)
91
202
  self.timeout = timeout
92
203
  self._session_file = not bool(
@@ -103,6 +214,8 @@ class CliptudeClient:
103
214
  "Accept": "application/json",
104
215
  **django_proxy_headers(self.base_url),
105
216
  }
217
+ if self.client_kind:
218
+ headers["X-Cliptude-Client"] = self.client_kind
106
219
  if json_content:
107
220
  headers["Content-Type"] = "application/json"
108
221
  return headers
@@ -154,25 +267,20 @@ class CliptudeClient:
154
267
  def get_template(self, template_id: str) -> Any:
155
268
  return self.request("GET", f"/api/v1/templates/{template_id}")
156
269
 
157
- def _template_format(self, template_id: str) -> str:
158
- try:
159
- tmpl = self.get_template(template_id)
160
- except CliptudeApiError:
161
- return ""
162
- if not isinstance(tmpl, dict):
163
- return ""
164
- return str(tmpl.get("format") or "").strip().lower()
165
-
166
- def _resolve_faceless_coding(self, template_id: str, faceless_coding: str | None) -> str | None:
167
- """CLI/MCP default is external for Faceless Explainer. Other formats omit the field."""
168
- raw = (faceless_coding or "").strip().lower() or None
169
- if raw == FACELESS_CODING_CLIPTUDE:
170
- return FACELESS_CODING_CLIPTUDE
171
- if raw not in (None, FACELESS_CODING_EXTERNAL):
172
- return raw
173
- if self._template_format(template_id) == FACELESS_EXPLAINER_FORMAT:
174
- return FACELESS_CODING_EXTERNAL
175
- return None
270
+ def create_template(self, *, name: str, format: str, settings: dict[str, Any]) -> Any:
271
+ """Create a ready-to-use template from settings (no create wizard)."""
272
+ return self.request(
273
+ "POST", "/api/v1/templates", json_body={"name": name, "format": format, "settings": settings}
274
+ )
275
+
276
+ def template_options(self, format: str) -> Any:
277
+ return self.request("GET", "/api/v1/templates/options", params={"format": format})
278
+
279
+ def list_voices(self, *, provider: str = "elevenlabs", language: str | None = None) -> Any:
280
+ params = {"provider": provider}
281
+ if language:
282
+ params["language"] = language
283
+ return self.request("GET", "/api/v1/voices", params=params)
176
284
 
177
285
  def create_job(
178
286
  self,
@@ -181,48 +289,169 @@ class CliptudeClient:
181
289
  title: str,
182
290
  prompt: str | None = None,
183
291
  script: str | None = None,
184
- faceless_coding: str | None = None,
185
292
  duration: str | None = None,
186
293
  voiceover_path: str | Path | None = None,
294
+ voiceover_url: str | None = None,
295
+ talking_head_path: str | Path | None = None,
296
+ output: str | None = None,
297
+ avatar_intro_only: bool | None = None,
298
+ avatar_ai_footage: bool | None = None,
299
+ avatar_profile_id: int | str | None = None,
300
+ avatar_engine: str | None = None,
301
+ disable_animations: bool | None = None,
302
+ disable_overlays: bool | None = None,
303
+ disable_effects: bool | None = None,
304
+ disable_transitions: bool | None = None,
305
+ excluded_animation_types: list[str] | None = None,
306
+ excluded_transition_kinds: list[str] | None = None,
307
+ render_only: bool | None = None,
308
+ thumbnail: dict[str, str] | None = None,
309
+ vector_character_id: str | None = None,
310
+ vector_reveal_mode: str | None = None,
187
311
  ) -> Any:
188
- coding = self._resolve_faceless_coding(template_id, faceless_coding)
189
- if voiceover_path:
312
+ if voiceover_path and voiceover_url:
313
+ raise CliptudeApiError("Give voiceover_path or voiceover_url, not both.")
314
+ if render_only and ((output or "").strip().lower() != "plan" or not (voiceover_path or voiceover_url)):
315
+ raise CliptudeApiError(
316
+ "render_only is a plan job with your own narration: pass output=\"plan\" and a voiceover "
317
+ "(voiceover_path, or voiceover_url for a public link)."
318
+ )
319
+ motion_fields = _motion_control_job_fields(
320
+ disable_animations=disable_animations,
321
+ disable_overlays=disable_overlays,
322
+ disable_effects=disable_effects,
323
+ disable_transitions=disable_transitions,
324
+ excluded_animation_types=excluded_animation_types,
325
+ excluded_transition_kinds=excluded_transition_kinds,
326
+ )
327
+ motion_fields_str = _motion_control_job_fields(
328
+ disable_animations=disable_animations,
329
+ disable_overlays=disable_overlays,
330
+ disable_effects=disable_effects,
331
+ disable_transitions=disable_transitions,
332
+ excluded_animation_types=excluded_animation_types,
333
+ excluded_transition_kinds=excluded_transition_kinds,
334
+ as_strings=True,
335
+ )
336
+ th_path = (str(talking_head_path).strip() if talking_head_path else "") or None
337
+ vo_path = (str(voiceover_path).strip() if voiceover_path else "") or None
338
+ output_kind = (output or "").strip().lower() or None
339
+ if output_kind and output_kind not in ("video", "script", "voiceover", "plan"):
340
+ raise CliptudeApiError('output must be "video", "script", "voiceover", or "plan".')
341
+ if output_kind in ("script", "voiceover") and (th_path or vo_path):
342
+ raise CliptudeApiError(
343
+ "Script and voiceover jobs cannot upload a voiceover or talking-head file."
344
+ )
345
+ if th_path and vo_path:
346
+ raise CliptudeApiError("Upload either a talking head video or a voiceover — not both.")
347
+ if th_path and (prompt or script):
348
+ raise CliptudeApiError(
349
+ "Upload a talking head video, or send a prompt / custom script — not both. "
350
+ "An uploaded talking head is transcribed and used as the narration."
351
+ )
352
+ if vo_path and (prompt or script):
353
+ raise CliptudeApiError(
354
+ "Upload a voiceover, or send a prompt / custom script — not both. "
355
+ "An uploaded file is transcribed and used as the narration."
356
+ )
357
+ if th_path:
358
+ return self._create_job_talking_head(
359
+ template_id=template_id,
360
+ title=title,
361
+ talking_head_path=th_path,
362
+ avatar_intro_only=avatar_intro_only,
363
+ avatar_ai_footage=avatar_ai_footage,
364
+ disable_animations=disable_animations,
365
+ disable_overlays=disable_overlays,
366
+ disable_effects=disable_effects,
367
+ disable_transitions=disable_transitions,
368
+ excluded_animation_types=excluded_animation_types,
369
+ excluded_transition_kinds=excluded_transition_kinds,
370
+ thumbnail=thumbnail,
371
+ )
372
+ if vo_path:
373
+ extra_data = {
374
+ **_avatar_job_fields(
375
+ avatar_intro_only, avatar_ai_footage, as_strings=True,
376
+ avatar_profile_id=avatar_profile_id, avatar_engine=avatar_engine,
377
+ ),
378
+ **motion_fields_str,
379
+ **({"output": output_kind} if output_kind == "plan" else {}),
380
+ **({"render_only": "true"} if render_only else {}),
381
+ **_thumbnail_job_field(thumbnail, as_string=True),
382
+ **({"vector_character_id": str(vector_character_id)} if vector_character_id else {}),
383
+ **({"vector_reveal_mode": str(vector_reveal_mode)} if vector_reveal_mode else {}),
384
+ }
190
385
  return self._create_job_multipart(
191
386
  template_id=template_id,
192
387
  title=title,
193
- faceless_coding=coding,
194
388
  duration=duration,
195
- voiceover_path=voiceover_path,
389
+ file_field="voiceover",
390
+ file_path=vo_path,
391
+ missing_message=f"Voiceover file not found: {vo_path}",
392
+ extra_data=extra_data or None,
196
393
  )
197
394
  body: dict[str, Any] = {"template_id": template_id, "title": title}
198
395
  if prompt:
199
396
  body["prompt"] = prompt
200
397
  if script:
201
398
  body["script"] = script
202
- if coding:
203
- body["faceless_coding"] = coding
204
399
  if duration:
205
400
  body["duration"] = duration
401
+ if output_kind and output_kind != "video":
402
+ body["output"] = output_kind
403
+ if voiceover_url:
404
+ # A public link to the narration: Cliptude downloads it (remote hosts cannot upload a file).
405
+ body["voiceover_url"] = str(voiceover_url).strip()
406
+ if render_only:
407
+ body["render_only"] = True
408
+ body.update(_avatar_job_fields(
409
+ avatar_intro_only, avatar_ai_footage,
410
+ avatar_profile_id=avatar_profile_id, avatar_engine=avatar_engine,
411
+ ))
412
+ body.update(motion_fields)
413
+ body.update(_thumbnail_job_field(thumbnail))
414
+ if vector_character_id:
415
+ body["vector_character_id"] = str(vector_character_id)
416
+ if vector_reveal_mode:
417
+ body["vector_reveal_mode"] = str(vector_reveal_mode)
206
418
  return self.request("POST", "/api/v1/jobs", json_body=body)
207
419
 
420
+ def _raise_http(self, resp, *, payload=None) -> None:
421
+ if payload is None:
422
+ try:
423
+ payload = resp.json()
424
+ except ValueError:
425
+ payload = {"error": resp.text}
426
+ message = payload.get("error") if isinstance(payload, dict) else str(payload)
427
+ if resp.status_code == 401:
428
+ message = message or "Not authenticated. Run: cliptude auth login"
429
+ raise CliptudeApiError(
430
+ message or f"HTTP {resp.status_code}",
431
+ status=resp.status_code,
432
+ payload=payload,
433
+ )
434
+
208
435
  def _create_job_multipart(
209
436
  self,
210
437
  *,
211
438
  template_id: str,
212
439
  title: str,
213
- faceless_coding: str | None,
214
440
  duration: str | None,
215
- voiceover_path: str | Path,
441
+ file_field: str,
442
+ file_path: str | Path,
443
+ missing_message: str,
444
+ extra_data: dict[str, str] | None = None,
216
445
  _retried: bool = False,
217
446
  ) -> Any:
218
- path = Path(voiceover_path)
447
+ path = Path(file_path)
219
448
  if not path.is_file():
220
- raise CliptudeApiError(f"Voiceover file not found: {path}")
449
+ raise CliptudeApiError(missing_message)
221
450
  data: dict[str, str] = {"template_id": str(template_id), "title": title}
222
- if faceless_coding:
223
- data["faceless_coding"] = faceless_coding
224
451
  if duration:
225
452
  data["duration"] = duration
453
+ if extra_data:
454
+ data.update(extra_data)
226
455
  url = f"{self.base_url}/api/v1/jobs"
227
456
  headers = self._headers(json_content=False)
228
457
  try:
@@ -231,7 +460,7 @@ class CliptudeClient:
231
460
  url,
232
461
  headers=headers,
233
462
  data=data,
234
- files={"voiceover": (path.name, fh, "application/octet-stream")},
463
+ files={file_field: (path.name, fh, "application/octet-stream")},
235
464
  timeout=max(self.timeout, 300.0),
236
465
  )
237
466
  except httpx.HTTPError as exc:
@@ -240,9 +469,11 @@ class CliptudeClient:
240
469
  return self._create_job_multipart(
241
470
  template_id=template_id,
242
471
  title=title,
243
- faceless_coding=faceless_coding,
244
472
  duration=duration,
245
- voiceover_path=voiceover_path,
473
+ file_field=file_field,
474
+ file_path=file_path,
475
+ missing_message=missing_message,
476
+ extra_data=extra_data,
246
477
  _retried=True,
247
478
  )
248
479
  try:
@@ -250,32 +481,254 @@ class CliptudeClient:
250
481
  except ValueError:
251
482
  payload = {"error": resp.text}
252
483
  if resp.status_code >= 400:
253
- message = payload.get("error") if isinstance(payload, dict) else str(payload)
254
- if resp.status_code == 401:
255
- message = message or "Not authenticated. Run: cliptude auth login"
256
- raise CliptudeApiError(message or f"HTTP {resp.status_code}", status=resp.status_code, payload=payload)
484
+ self._raise_http(resp, payload=payload)
257
485
  return payload
258
486
 
487
+ def _abort_talking_head_upload(self, key: str | None, upload_id: str | None) -> None:
488
+ if not key or not upload_id:
489
+ return
490
+ try:
491
+ self.request(
492
+ "POST",
493
+ "/api/v1/uploads/talking-head/abort",
494
+ json_body={"key": key, "upload_id": upload_id},
495
+ )
496
+ except Exception:
497
+ pass
498
+
499
+ def _create_job_talking_head(
500
+ self,
501
+ *,
502
+ template_id: str,
503
+ title: str,
504
+ talking_head_path: str | Path,
505
+ avatar_intro_only: bool | None = None,
506
+ avatar_ai_footage: bool | None = None,
507
+ disable_animations: bool | None = None,
508
+ disable_overlays: bool | None = None,
509
+ disable_effects: bool | None = None,
510
+ disable_transitions: bool | None = None,
511
+ excluded_animation_types: list[str] | None = None,
512
+ excluded_transition_kinds: list[str] | None = None,
513
+ thumbnail: dict[str, str] | None = None,
514
+ ) -> Any:
515
+ motion_extra = _motion_control_job_fields(
516
+ disable_animations=disable_animations,
517
+ disable_overlays=disable_overlays,
518
+ disable_effects=disable_effects,
519
+ disable_transitions=disable_transitions,
520
+ excluded_animation_types=excluded_animation_types,
521
+ excluded_transition_kinds=excluded_transition_kinds,
522
+ as_strings=True,
523
+ )
524
+ path = Path(talking_head_path)
525
+ if not path.is_file():
526
+ raise CliptudeApiError(f"Talking head file not found: {path}")
527
+ ext = path.suffix.lower()
528
+ if ext not in TALKING_HEAD_EXTS:
529
+ raise CliptudeApiError(
530
+ f'Unsupported file type "{ext}". Please upload MP4, MOV, WEBM, or AVI.'
531
+ )
532
+ size = path.stat().st_size
533
+ duration = _probe_local_video_duration_seconds(path)
534
+ init = self.request(
535
+ "POST",
536
+ "/api/v1/uploads/talking-head/init",
537
+ json_body={
538
+ "filename": path.name,
539
+ "size": size,
540
+ "content_type": _talking_head_content_type(ext),
541
+ },
542
+ )
543
+ if not isinstance(init, dict) or init.get("fallback"):
544
+ extra_data = {
545
+ **_avatar_job_fields(avatar_intro_only, avatar_ai_footage, as_strings=True),
546
+ **motion_extra,
547
+ **_thumbnail_job_field(thumbnail, as_string=True),
548
+ }
549
+ return self._create_job_multipart(
550
+ template_id=template_id,
551
+ title=title,
552
+ duration=None,
553
+ file_field="talking_head",
554
+ file_path=path,
555
+ missing_message=f"Talking head file not found: {path}",
556
+ extra_data=extra_data or None,
557
+ )
558
+ key = str(init.get("key") or "").strip()
559
+ upload_id = str(init.get("upload_id") or "").strip()
560
+ if duration is None:
561
+ self._abort_talking_head_upload(key, upload_id)
562
+ extra_data = {
563
+ **_avatar_job_fields(avatar_intro_only, avatar_ai_footage, as_strings=True),
564
+ **motion_extra,
565
+ **_thumbnail_job_field(thumbnail, as_string=True),
566
+ }
567
+ return self._create_job_multipart(
568
+ template_id=template_id,
569
+ title=title,
570
+ duration=None,
571
+ file_field="talking_head",
572
+ file_path=path,
573
+ missing_message=f"Talking head file not found: {path}",
574
+ extra_data=extra_data or None,
575
+ )
576
+ try:
577
+ self._upload_talking_head_parts(path, init)
578
+ self.request(
579
+ "POST",
580
+ "/api/v1/uploads/talking-head/complete",
581
+ json_body={"key": key, "upload_id": upload_id},
582
+ )
583
+ except Exception:
584
+ self._abort_talking_head_upload(key, upload_id)
585
+ raise
586
+ body: dict[str, Any] = {
587
+ "template_id": str(template_id),
588
+ "title": title,
589
+ "talking_head_r2_key": key,
590
+ "talking_head_duration": str(duration),
591
+ }
592
+ body.update(_avatar_job_fields(avatar_intro_only, avatar_ai_footage))
593
+ body.update(_thumbnail_job_field(thumbnail))
594
+ body.update(
595
+ _motion_control_job_fields(
596
+ disable_animations=disable_animations,
597
+ disable_overlays=disable_overlays,
598
+ disable_effects=disable_effects,
599
+ disable_transitions=disable_transitions,
600
+ excluded_animation_types=excluded_animation_types,
601
+ excluded_transition_kinds=excluded_transition_kinds,
602
+ )
603
+ )
604
+ return self.request("POST", "/api/v1/jobs", json_body=body)
605
+
606
+ def _upload_talking_head_parts(self, path: Path, init: dict[str, Any]) -> None:
607
+ self._upload_parts(path, init, "/api/v1/uploads/talking-head/sign-parts", "talking head")
608
+
609
+ def _upload_parts(self, path: Path, init: dict[str, Any], sign_path: str, label: str) -> None:
610
+ """PUT the file straight to R2, part by part, on URLs Cliptude signs (no R2 keys here)."""
611
+ key = str(init.get("key") or "").strip()
612
+ upload_id = str(init.get("upload_id") or "").strip()
613
+ part_size = int(init.get("part_size") or 0)
614
+ part_count = int(init.get("part_count") or 0)
615
+ if not key or not upload_id or part_size <= 0 or part_count <= 0:
616
+ raise CliptudeApiError(f"The {label} upload init returned an incomplete plan.")
617
+ with path.open("rb") as fh:
618
+ for start in range(0, part_count, 50):
619
+ nums = list(range(start + 1, min(start + 50, part_count) + 1))
620
+ signed = self.request(
621
+ "POST",
622
+ sign_path,
623
+ json_body={"key": key, "upload_id": upload_id, "part_numbers": nums},
624
+ )
625
+ urls = (signed or {}).get("urls") if isinstance(signed, dict) else None
626
+ if not isinstance(urls, dict):
627
+ raise CliptudeApiError(f"Could not sign {label} upload parts.")
628
+ for num in nums:
629
+ url = urls.get(str(num))
630
+ if not url:
631
+ raise CliptudeApiError(f"Could not sign part {num}.")
632
+ chunk = fh.read(part_size)
633
+ try:
634
+ resp = httpx.put(url, content=chunk, timeout=max(self.timeout, 300.0))
635
+ except httpx.HTTPError as exc:
636
+ raise CliptudeApiError(str(exc)) from exc
637
+ if resp.status_code >= 400:
638
+ raise CliptudeApiError(
639
+ f"Failed to upload {label} part {num}.",
640
+ status=resp.status_code,
641
+ )
642
+
259
643
  def get_job(self, job_id: str) -> Any:
260
644
  return self.request("GET", f"/api/v1/jobs/{job_id}")
261
645
 
262
- def download_coding_kit(self, job_id: str) -> Any:
263
- """Return coding_kit url/path from get_job. Never downloads zip bytes."""
264
- job = self.get_job(job_id)
265
- kit = job.get("coding_kit") if isinstance(job, dict) else None
266
- if not kit:
267
- raise CliptudeApiError("Coding kit is not ready yet. Poll until status is awaiting_project.")
268
- return kit
646
+ def continue_job(self, job_id: str) -> Any:
647
+ """Queue a completed script/voiceover job, or a plan job with a locked plan, as a full video."""
648
+ return self.request("POST", f"/api/v1/jobs/{job_id}/continue")
269
649
 
270
- def download_coding_kit_file(self, job_id: str, dest: Path) -> Path:
271
- url = f"{self.base_url}/api/v1/jobs/{job_id}/coding-kit"
650
+ # Agent-planned videos -------------------------------------------------------------------------
651
+
652
+ def upload_plan_media(self, job_id: str, path: str | Path) -> Any:
653
+ """Send a picture or clip you found to a plan job; returns {keep, file, media_type, size} for media.keep."""
654
+ path = Path(path)
655
+ if not path.is_file():
656
+ raise CliptudeApiError(f"File not found: {path}")
657
+ base = f"/api/v1/jobs/{job_id}/media"
658
+ init = self.request(
659
+ "POST",
660
+ f"{base}/init",
661
+ json_body={
662
+ "filename": path.name,
663
+ "size": path.stat().st_size,
664
+ "content_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
665
+ },
666
+ )
667
+ body = {"key": (init or {}).get("key"), "upload_id": (init or {}).get("upload_id")}
668
+ try:
669
+ self._upload_parts(path, init, f"{base}/sign-parts", "media")
670
+ return self.request("POST", f"{base}/complete", json_body=body)
671
+ except Exception:
672
+ try:
673
+ self.request("POST", f"{base}/abort", json_body=body)
674
+ except Exception:
675
+ pass
676
+ raise
677
+
678
+ def get_narration(self, job_id: str) -> Any:
679
+ """Numbered sentences (with word timings), digest, pricing and template flags of a plan job."""
680
+ return self.request("GET", f"/api/v1/jobs/{job_id}/narration")
681
+
682
+ def get_kind_catalog(
683
+ self,
684
+ *,
685
+ format: str | None = None,
686
+ theme: str | None = None,
687
+ compact: bool = False,
688
+ types: list[str] | None = None,
689
+ premium: bool = False,
690
+ ) -> Any:
691
+ """Every graphic an agent can place. compact: one summary line each; types: full entries for those;
692
+ premium: only the premium boards."""
693
+ params = {k: v for k, v in (("format", format), ("theme", theme)) if v}
694
+ if compact:
695
+ params["compact"] = "1"
696
+ if premium:
697
+ params["premium"] = "1"
698
+ if types:
699
+ params["types"] = ",".join(types)
700
+ return self.request("GET", "/api/v1/catalog/kinds", params=params or None)
701
+
702
+ def put_plan(self, job_id: str, plan: dict[str, Any], *, dry_run: bool = True) -> Any:
703
+ """Check a plan (dry_run) or lock it. A failing check returns its report, not an exception."""
704
+ path = f"/api/v1/jobs/{job_id}/plan" + ("?dry_run=1" if dry_run else "")
705
+ try:
706
+ return self.request("PUT", path, json_body=plan)
707
+ except CliptudeApiError as exc:
708
+ if exc.status in (400, 409, 413) and isinstance(exc.payload, dict) and "errors" in exc.payload:
709
+ return {**exc.payload, "http_status": exc.status}
710
+ raise
711
+
712
+ def get_plan(self, job_id: str) -> Any:
713
+ return self.request("GET", f"/api/v1/jobs/{job_id}/plan")
714
+
715
+ def get_plan_report(self, job_id: str) -> Any:
716
+ """What sourcing used for each media request of the locked plan, and every fallback."""
717
+ return self.request("GET", f"/api/v1/jobs/{job_id}/plan/report")
718
+
719
+ def get_plan_review(self, job_id: str) -> Any:
720
+ """The built design, beat by beat and graphic by graphic, with links to the media (review before render)."""
721
+ return self.request("GET", f"/api/v1/jobs/{job_id}/plan/review")
722
+
723
+ def download_voiceover_file(self, job_id: str, dest: Path) -> Path:
724
+ url = f"{self.base_url}/api/v1/jobs/{job_id}/voiceover"
272
725
  try:
273
726
  with httpx.stream(
274
727
  "GET",
275
728
  url,
276
729
  headers={
277
730
  "Authorization": f"Bearer {self.api_key}",
278
- "Accept": "application/zip, application/json",
731
+ "Accept": "audio/mpeg, application/json",
279
732
  **django_proxy_headers(self.base_url),
280
733
  },
281
734
  timeout=self.timeout,
@@ -300,43 +753,170 @@ class CliptudeClient:
300
753
  raise CliptudeApiError(str(exc)) from exc
301
754
  return dest
302
755
 
303
- def submit_faceless_project(self, job_id: str, zip_path: str | Path) -> Any:
304
- path = Path(zip_path)
305
- if not path.is_file():
306
- raise CliptudeApiError(f"Project zip not found: {path}")
307
- url = f"{self.base_url}/api/v1/jobs/{job_id}/project"
308
- headers = {
309
- "Authorization": f"Bearer {self.api_key}",
310
- "Accept": "application/json",
311
- **django_proxy_headers(self.base_url),
756
+ def list_jobs(self, *, status: str | None = None, limit: int = 20, offset: int = 0) -> Any:
757
+ params: dict[str, Any] = {"limit": limit, "offset": offset}
758
+ if status:
759
+ params["status"] = status
760
+ return self.request("GET", "/api/v1/jobs", params=params)
761
+
762
+ def cancel_job(self, job_id: str) -> Any:
763
+ return self.request("POST", f"/api/v1/jobs/{job_id}/cancel")
764
+
765
+ # --- Timeline editor + Cliptude Agent -------------------------------------------------
766
+
767
+ def open_editor_project(self, job_id: str) -> Any:
768
+ """Open (or create) the editor project for a completed video job; includes a compact timeline."""
769
+ return self.request("GET", f"/api/v1/jobs/{job_id}/editor-project")
770
+
771
+ def get_editor_project(self, project_id: int | str, *, design: bool = False) -> Any:
772
+ params = {"design": "1"} if design else None
773
+ return self.request("GET", f"/api/v1/editor-projects/{project_id}", params=params)
774
+
775
+ def agent_tiers(self) -> Any:
776
+ return self.request("GET", "/api/v1/agent/tiers")
777
+
778
+ def run_agent(
779
+ self,
780
+ project_id: int | str,
781
+ *,
782
+ prompt: str,
783
+ tier: str = "fast",
784
+ referenced_item_ids: list[str] | None = None,
785
+ chat_id: str | None = None,
786
+ expected_revision: int | None = None,
787
+ idempotency_key: str | None = None,
788
+ ) -> Any:
789
+ """Ask Cliptude Agent to edit the timeline. Uses the project's current revision unless given."""
790
+ import uuid
791
+
792
+ if expected_revision is None:
793
+ project = self.get_editor_project(project_id).get("project") or {}
794
+ expected_revision = int(project.get("revision") or 0)
795
+ body: dict[str, Any] = {
796
+ "prompt": prompt,
797
+ "tier": tier,
798
+ "referenced_item_ids": list(referenced_item_ids or []),
799
+ "expected_revision": expected_revision,
800
+ "idempotency_key": idempotency_key or uuid.uuid4().hex,
312
801
  }
802
+ if chat_id:
803
+ body["chat_id"] = chat_id
804
+ return self.request("POST", f"/api/v1/editor-projects/{project_id}/agent/runs", json_body=body)
805
+
806
+ def get_agent_run(self, project_id: int | str, run_id: str) -> Any:
807
+ return self.request("GET", f"/api/v1/editor-projects/{project_id}/agent/runs/{run_id}")
808
+
809
+ def cancel_agent_run(self, project_id: int | str, run_id: str) -> Any:
810
+ return self.request("POST", f"/api/v1/editor-projects/{project_id}/agent/runs/{run_id}/cancel")
811
+
812
+ def render_project(self, project_id: int | str) -> Any:
813
+ """Render the edited timeline to a new MP4 (charged like an editor export)."""
814
+ return self.request("POST", f"/api/v1/editor-projects/{project_id}/render")
815
+
816
+ def get_render(self, render_id: int | str) -> Any:
817
+ return self.request("GET", f"/api/v1/editor-renders/{render_id}")
818
+
819
+ def get_account(self) -> Any:
820
+ return self.request("GET", "/api/v1/account")
821
+
822
+ def estimate_credits(
823
+ self,
824
+ *,
825
+ template_id: str,
826
+ prompt: str | None = None,
827
+ script: str | None = None,
828
+ duration: str | None = None,
829
+ voiceover_seconds: float | None = None,
830
+ talking_head_seconds: float | None = None,
831
+ output: str | None = None,
832
+ avatar_intro_only: bool | None = None,
833
+ avatar_ai_footage: bool | None = None,
834
+ avatar_profile_id: int | str | None = None,
835
+ avatar_engine: str | None = None,
836
+ render_only: bool | None = None,
837
+ vector_reveal_mode: str | None = None,
838
+ ) -> Any:
839
+ """Credits a job would need; creates nothing."""
840
+ body: dict[str, Any] = {"template_id": template_id}
841
+ if render_only:
842
+ body["render_only"] = True
843
+ for key, value in (
844
+ ("prompt", prompt),
845
+ ("script", script),
846
+ ("duration", duration),
847
+ ("voiceover_seconds", voiceover_seconds),
848
+ ("talking_head_seconds", talking_head_seconds),
849
+ ("output", output),
850
+ ("vector_reveal_mode", vector_reveal_mode),
851
+ ):
852
+ if value is not None and value != "":
853
+ body[key] = value
854
+ body.update(_avatar_job_fields(
855
+ avatar_intro_only, avatar_ai_footage,
856
+ avatar_profile_id=avatar_profile_id, avatar_engine=avatar_engine,
857
+ ))
858
+ return self.request("POST", "/api/v1/jobs/estimate", json_body=body)
859
+
860
+ def list_vector_characters(self) -> Any:
861
+ """Vector Explainer characters: the built-in cast and your uploads (ids for vector_character_id)."""
862
+ return self.request("GET", "/api/v1/vector-characters")
863
+
864
+ def upload_vector_character(
865
+ self,
866
+ *,
867
+ image_path: str | Path | None = None,
868
+ image_url: str | None = None,
869
+ name: str = "",
870
+ _retried: bool = False,
871
+ ) -> Any:
872
+ """Add a Vector Explainer character from a local image or a public image URL; returns its id."""
873
+ if bool(image_path) == bool((image_url or "").strip()):
874
+ raise CliptudeApiError("Give image_path or image_url (one of them).")
875
+ if image_url:
876
+ return self.request(
877
+ "POST", "/api/v1/vector-characters", json_body={"image_url": image_url.strip(), "name": name}
878
+ )
879
+ path = Path(image_path)
880
+ if not path.is_file():
881
+ raise CliptudeApiError(f"Character image not found: {path}")
882
+ mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
313
883
  try:
314
884
  with path.open("rb") as fh:
315
885
  resp = httpx.post(
316
- url,
317
- headers=headers,
318
- files={"zip": (path.name, fh, "application/zip")},
886
+ f"{self.base_url}/api/v1/vector-characters",
887
+ headers=self._headers(json_content=False),
888
+ data={"name": name},
889
+ files={"image": (path.name, fh, mime)},
319
890
  timeout=max(self.timeout, 120.0),
320
891
  )
321
892
  except httpx.HTTPError as exc:
322
893
  raise CliptudeApiError(str(exc)) from exc
894
+ if resp.status_code == 401 and not _retried and self._maybe_refresh():
895
+ return self.upload_vector_character(image_path=image_path, name=name, _retried=True)
323
896
  try:
324
897
  payload = resp.json()
325
898
  except ValueError:
326
899
  payload = {"error": resp.text}
327
900
  if resp.status_code >= 400:
328
- message = payload.get("error") if isinstance(payload, dict) else str(payload)
329
- raise CliptudeApiError(message or f"HTTP {resp.status_code}", status=resp.status_code, payload=payload)
901
+ self._raise_http(resp, payload=payload)
330
902
  return payload
331
903
 
332
- def list_jobs(self, *, status: str | None = None, limit: int = 20, offset: int = 0) -> Any:
333
- params: dict[str, Any] = {"limit": limit, "offset": offset}
334
- if status:
335
- params["status"] = status
336
- return self.request("GET", "/api/v1/jobs", params=params)
904
+ def delete_vector_character(self, character_id: str) -> Any:
905
+ """Delete one of your uploaded characters (refused while a template uses it)."""
906
+ return self.request("DELETE", f"/api/v1/vector-characters/{character_id}")
337
907
 
338
- def cancel_job(self, job_id: str) -> Any:
339
- return self.request("POST", f"/api/v1/jobs/{job_id}/cancel")
340
-
341
- def get_account(self) -> Any:
342
- return self.request("GET", "/api/v1/account")
908
+ def list_avatars(
909
+ self,
910
+ *,
911
+ section: str | None = None,
912
+ search: str | None = None,
913
+ gender: str | None = None,
914
+ limit: int = 50,
915
+ offset: int = 0,
916
+ ) -> Any:
917
+ """Avatars for Avatar Video (ids for avatar_profile_id)."""
918
+ params: dict[str, Any] = {"limit": limit, "offset": offset}
919
+ for key, value in (("section", section), ("search", search), ("gender", gender)):
920
+ if value:
921
+ params[key] = value
922
+ return self.request("GET", "/api/v1/avatars", params=params)