@chad.dev/dsh-adclip 0.0.0-stage → 0.1.1

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.
Files changed (51) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +28 -2
  4. package/client.js +2256 -0
  5. package/cordis.patch.yml +10 -0
  6. package/engine/requirements.txt +9 -0
  7. package/engine/src/adclip/__init__.py +0 -0
  8. package/engine/src/adclip/api.py +704 -0
  9. package/engine/src/adclip/catalog.py +341 -0
  10. package/engine/src/adclip/image_params.py +45 -0
  11. package/engine/src/adclip/intents.py +209 -0
  12. package/engine/src/adclip/llm.py +142 -0
  13. package/engine/src/adclip/media/__init__.py +0 -0
  14. package/engine/src/adclip/media/asr.py +79 -0
  15. package/engine/src/adclip/media/ffmpeg.py +294 -0
  16. package/engine/src/adclip/media/stitch.py +124 -0
  17. package/engine/src/adclip/media/subtitles.py +45 -0
  18. package/engine/src/adclip/media/vision.py +105 -0
  19. package/engine/src/adclip/models.py +127 -0
  20. package/engine/src/adclip/params.py +158 -0
  21. package/engine/src/adclip/personas.py +60 -0
  22. package/engine/src/adclip/pipeline/__init__.py +0 -0
  23. package/engine/src/adclip/pipeline/analyze.py +133 -0
  24. package/engine/src/adclip/pipeline/generate.py +196 -0
  25. package/engine/src/adclip/pipeline/image_runner.py +146 -0
  26. package/engine/src/adclip/pipeline/persona.py +56 -0
  27. package/engine/src/adclip/pipeline/post.py +40 -0
  28. package/engine/src/adclip/pipeline/qa.py +44 -0
  29. package/engine/src/adclip/pipeline/replace.py +191 -0
  30. package/engine/src/adclip/pipeline/runner.py +138 -0
  31. package/engine/src/adclip/pipeline/script.py +226 -0
  32. package/engine/src/adclip/pipeline/segment.py +87 -0
  33. package/engine/src/adclip/providers/__init__.py +0 -0
  34. package/engine/src/adclip/providers/ark.py +122 -0
  35. package/engine/src/adclip/providers/ark_image.py +114 -0
  36. package/engine/src/adclip/providers/base.py +30 -0
  37. package/engine/src/adclip/providers/discovery.py +56 -0
  38. package/engine/src/adclip/providers/kling.py +101 -0
  39. package/engine/src/adclip/providers/minimax.py +155 -0
  40. package/engine/src/adclip/providers/minimax_image.py +89 -0
  41. package/engine/src/adclip/settings.py +109 -0
  42. package/engine/src/adclip/store.py +378 -0
  43. package/host/dsh.js +60 -0
  44. package/host/engine.js +265 -0
  45. package/host/proxy.js +142 -0
  46. package/host/supervisor.js +251 -0
  47. package/icon.svg +6 -0
  48. package/index.js +39 -0
  49. package/locale/en.json +12 -0
  50. package/locale/zh.json +12 -0
  51. package/package.json +47 -4
@@ -0,0 +1,704 @@
1
+ """FastAPI surface for AdClip.
2
+
3
+ No pricing, quotes or billing endpoints exist. The first slice runs a local
4
+ demo pipeline so the DSH UI, storyboard, edits, personas and stitching can be
5
+ exercised end to end without paid credentials.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import copy
11
+ from contextlib import asynccontextmanager
12
+ import mimetypes
13
+ import shutil
14
+ import time
15
+ import zipfile
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from fastapi import Body, FastAPI, HTTPException, Query, Request
20
+ from fastapi.responses import FileResponse, JSONResponse
21
+
22
+ from . import catalog as model_catalog
23
+ from . import image_params, intents, llm, params, personas, settings, store
24
+ from .providers import discovery
25
+ from .media import ffmpeg
26
+ from .media import stitch as stitch_mod
27
+ from .media import subtitles
28
+ from .models import AssistantRequest, Run, RunStep, StitchRequest
29
+ from .pipeline import image_runner
30
+ from .pipeline import replace as segment_replace
31
+ from .pipeline import qa as qa_pipeline
32
+ from .pipeline import runner, segment
33
+
34
+ @asynccontextmanager
35
+ async def _lifespan(_app: FastAPI):
36
+ store.migrate_legacy()
37
+ store.ensure_dirs()
38
+ settings.load_into_env()
39
+ personas.ensure_default()
40
+ yield
41
+
42
+
43
+ app = FastAPI(title="AdClip", version="0.1.0", lifespan=_lifespan)
44
+ VERSION = "0.1.1"
45
+
46
+
47
+ def _media_type(path: Path) -> str:
48
+ return mimetypes.guess_type(path.name)[0] or "application/octet-stream"
49
+
50
+
51
+ def _probe_asset(asset_id: str) -> dict[str, Any]:
52
+ record = store.get_asset(asset_id)
53
+ if record is None:
54
+ raise HTTPException(status_code=404, detail="asset not found")
55
+ target = store.safe_media_path(record["path"])
56
+ try:
57
+ if record.get("kind") == "video":
58
+ facts = ffmpeg.probe(target)
59
+ record.update({k: facts[k] for k in ("width", "height", "duration_s")})
60
+ elif record.get("kind") == "image":
61
+ from PIL import Image
62
+
63
+ with Image.open(target) as image:
64
+ record["width"], record["height"] = image.size
65
+ except Exception:
66
+ pass
67
+ return record
68
+
69
+
70
+ @app.get("/health")
71
+ def health() -> dict[str, Any]:
72
+ models = params.catalog()
73
+ return {
74
+ "ok": True,
75
+ "service": "adclip",
76
+ "version": VERSION,
77
+ "demo": False,
78
+ "data": str(store.DATA),
79
+ "models": len(models),
80
+ "available_models": [row["id"] for row in models if row.get("available")],
81
+ "text_llm": llm.available(),
82
+ "text_model": llm.model_label(),
83
+ "text_provider": llm.provider_label(),
84
+ "text_llm_last_error": llm.LAST_ERROR,
85
+ "runs": len(store.list_runs(limit=200)),
86
+ "deps": ffmpeg.dependencies(),
87
+ }
88
+
89
+
90
+ @app.get("/scenarios")
91
+ def scenarios() -> dict[str, Any]:
92
+ return {"scenarios": params.SCENARIOS}
93
+
94
+
95
+ @app.get("/models")
96
+ def models(kind: str = "", capability: str = "") -> dict[str, Any]:
97
+ rows = model_catalog.rows()
98
+ if kind:
99
+ rows = [row for row in rows if row["kind"] == kind]
100
+ if capability:
101
+ rows = [row for row in rows if capability in (row.get("capabilities") or [])]
102
+ return {"models": rows, "kinds": sorted({row["kind"] for row in rows}),
103
+ "capabilities": {kind_name: sorted({cap for row in rows if row["kind"] == kind_name for cap in row["capabilities"]})
104
+ for kind_name in sorted({row["kind"] for row in rows})}}
105
+
106
+
107
+ @app.post("/assets/upload")
108
+ async def upload_asset(request: Request, kind: str = "video", name: str = "") -> dict[str, Any]:
109
+ if kind not in {"image", "video"}:
110
+ raise HTTPException(status_code=400, detail="only image and video assets are supported")
111
+ raw = await request.body()
112
+ if not raw:
113
+ raise HTTPException(status_code=400, detail="empty file")
114
+ if len(raw) > 2 * 1024**3:
115
+ raise HTTPException(status_code=413, detail="file too large")
116
+ import hashlib
117
+
118
+ mime = request.headers.get("content-type") or "application/octet-stream"
119
+ digest = hashlib.sha256(raw).hexdigest()
120
+ existing = store.get_asset_by_sha(digest)
121
+ if existing is not None:
122
+ return {"ok": True, "asset": existing, "deduplicated": True}
123
+ try:
124
+ asset = store.create_asset(raw, name or f"upload-{store.new_id('file')}", kind, mime)
125
+ except ValueError as exc:
126
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
127
+ record = _probe_asset(asset.id)
128
+ return {"ok": True, "asset": record}
129
+
130
+
131
+ @app.get("/assets")
132
+ def list_assets(
133
+ kind: str = "", q: str = "", offset: int = 0, limit: int = 24,
134
+ from_: str = Query("", alias="from"), to: str = "",
135
+ ) -> dict[str, Any]:
136
+ rows, total = store.list_assets_page(kind=kind, query=q, offset=offset, limit=limit, date_from=from_, date_to=to)
137
+ return {"assets": rows, "total": total, "offset": max(0, offset), "limit": max(1, min(limit, 200)), "has_more": offset + len(rows) < total}
138
+
139
+
140
+ @app.get("/assets/{asset_id}")
141
+ def get_asset(asset_id: str) -> dict[str, Any]:
142
+ record = store.get_asset(asset_id)
143
+ if record is None:
144
+ raise HTTPException(status_code=404, detail="asset not found")
145
+ return {"asset": record}
146
+
147
+
148
+ @app.get("/media")
149
+ def media(path: str) -> FileResponse:
150
+ try:
151
+ target = store.safe_media_path(path)
152
+ except (ValueError, FileNotFoundError) as exc:
153
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
154
+ return FileResponse(target, media_type=_media_type(target))
155
+
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # local provider keys
159
+ # ---------------------------------------------------------------------------
160
+ @app.get("/settings/models")
161
+ def get_settings_models() -> dict[str, Any]:
162
+ return {"enabled": settings.enabled_models(), "models": model_catalog.rows()}
163
+
164
+
165
+ @app.post("/settings/models")
166
+ def set_settings_models(payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
167
+ valid = {str(row["id"]) for row in model_catalog.rows()}
168
+ enabled = []
169
+ for value in payload.get("enabled") or []:
170
+ value = str(value or "").strip()
171
+ if value in valid and value not in enabled:
172
+ enabled.append(value)
173
+ settings.set_enabled_models(enabled)
174
+ return {"enabled": enabled, "models": model_catalog.rows()}
175
+
176
+
177
+ @app.get("/models/discover")
178
+ def discover_models() -> dict[str, Any]:
179
+ return {"providers": discovery.discover()}
180
+
181
+
182
+ @app.get("/settings/keys")
183
+ def get_settings_keys() -> dict[str, Any]:
184
+ return {"keys": settings.status()}
185
+
186
+
187
+ @app.post("/settings/keys")
188
+ def set_settings_key(payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
189
+ try:
190
+ rows = settings.set_key(str(payload.get("name") or ""), str(payload.get("value") or ""))
191
+ except ValueError as exc:
192
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
193
+ return {"keys": rows, "models": params.catalog()}
194
+
195
+
196
+ # ---------------------------------------------------------------------------
197
+ # personas
198
+ # ---------------------------------------------------------------------------
199
+ @app.get("/personas")
200
+ def list_personas() -> dict[str, Any]:
201
+ return {"personas": store.list_personas()}
202
+
203
+
204
+ @app.post("/personas")
205
+ def create_persona(payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
206
+ try:
207
+ return {"persona": personas.create(payload)}
208
+ except ValueError as exc:
209
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
210
+
211
+
212
+ @app.patch("/personas/{persona_id}")
213
+ def patch_persona(persona_id: str, payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
214
+ result = personas.update(persona_id, payload)
215
+ if result is None:
216
+ raise HTTPException(status_code=404, detail="persona not found")
217
+ return {"persona": result}
218
+
219
+
220
+ @app.delete("/personas/{persona_id}")
221
+ def remove_persona(persona_id: str) -> dict[str, Any]:
222
+ return {"removed": personas.delete(persona_id)}
223
+
224
+
225
+ # ---------------------------------------------------------------------------
226
+ # runs
227
+ # ---------------------------------------------------------------------------
228
+ def _scenario_or_404(scenario_id: str) -> dict[str, Any]:
229
+ scenario = params.scenario(scenario_id)
230
+ if scenario is None:
231
+ raise HTTPException(status_code=400, detail=f"unknown scenario: {scenario_id}")
232
+ if scenario.get("status") != "ready":
233
+ raise HTTPException(status_code=409, detail="scenario is not ready")
234
+ return scenario
235
+
236
+
237
+ def _validate_inputs(scenario: dict[str, Any], inputs: dict[str, Any]) -> None:
238
+ if scenario["id"] == "viral-remake":
239
+ ref = inputs.get("reference_asset_id")
240
+ if not ref or store.get_asset(ref) is None:
241
+ raise HTTPException(status_code=400, detail="reference video is required")
242
+ if scenario["id"] == "text-to-video" and not str(inputs.get("brief") or "").strip():
243
+ raise HTTPException(status_code=400, detail="brief is required")
244
+
245
+
246
+ def _new_run(scenario_id: str, inputs: dict[str, Any], advanced: dict[str, Any], *, title: str = "", parent: Run | None = None, changes: list[dict[str, Any]] | None = None) -> Run:
247
+ run_id = store.new_id("run")
248
+ store.run_dir(run_id).mkdir(parents=True, exist_ok=True)
249
+ (store.run_dir(run_id) / "artifacts").mkdir(parents=True, exist_ok=True)
250
+ persona_map = dict((advanced or {}).get("persona_map") or {})
251
+ persona_snapshot = {}
252
+ persona_obj = (advanced or {}).get("persona")
253
+ if isinstance(persona_obj, dict):
254
+ persona_snapshot = persona_obj
255
+ if not title:
256
+ brief = str(inputs.get("brief") or "").strip()
257
+ head = (brief.split("。")[0].split(",")[0] or "").strip()[:26]
258
+ label = params.scenario(scenario_id)["label"]
259
+ title = f"{label} · {head}" if head else label
260
+ run = Run(
261
+ id=run_id,
262
+ scenario=scenario_id,
263
+ title=title[:60],
264
+ status="queued",
265
+ step="queued",
266
+ generation_mode=str((advanced or {}).get("generation_mode") or "fast"),
267
+ inputs=inputs,
268
+ advanced=advanced,
269
+ persona_map=persona_map,
270
+ persona_snapshot=persona_snapshot,
271
+ steps=[RunStep(name=name, label=label) for name, label, _ in runner.STEPS],
272
+ created_at=store.now(),
273
+ parent_run_id=parent.id if parent else None,
274
+ version=(parent.version + 1) if parent else 1,
275
+ changes=changes or [],
276
+ demo=False,
277
+ )
278
+ store.write_run(run)
279
+ runner.manager.start(run.id)
280
+ return run
281
+
282
+
283
+ @app.post("/runs")
284
+ def create_run(payload: dict[str, Any] = Body(...)) -> JSONResponse:
285
+ scenario_id = str(payload.get("scenario") or "viral-remake")
286
+ scenario = _scenario_or_404(scenario_id)
287
+ inputs = dict(payload.get("inputs") or {})
288
+ advanced = params.merged_advanced(dict(payload.get("advanced") or {}))
289
+ _validate_inputs(scenario, inputs)
290
+ run = _new_run(scenario_id, inputs, advanced, title=str(payload.get("title") or ""))
291
+ return JSONResponse(status_code=202, content={"run": run.model_dump()})
292
+
293
+
294
+ @app.get("/image/models")
295
+ def get_image_models() -> dict[str, Any]:
296
+ rows = image_params.catalog()
297
+ return {"models": rows, "available": any(row.get("available") for row in rows)}
298
+
299
+
300
+ @app.post("/images")
301
+ def create_image(payload: dict[str, Any] = Body(...)) -> JSONResponse:
302
+ prompt = str(payload.get("prompt") or "").strip()
303
+ if not prompt:
304
+ raise HTTPException(status_code=400, detail="prompt is required")
305
+ try:
306
+ run = image_runner.create(
307
+ prompt,
308
+ model_id=str(payload.get("model") or ""),
309
+ aspect=str(payload.get("aspect") or "1:1"),
310
+ area=str(payload.get("area") or "2K"),
311
+ reference_asset_id=str(payload.get("reference_asset_id") or ""),
312
+ )
313
+ except ValueError as exc:
314
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
315
+ return JSONResponse(status_code=202, content={"run": run.model_dump()})
316
+
317
+
318
+ @app.post("/images/{run_id}/retry")
319
+ def retry_image(run_id: str) -> JSONResponse:
320
+ parent = store.read_run(run_id)
321
+ if parent is None:
322
+ raise HTTPException(status_code=404, detail="run not found")
323
+ if parent.scenario != "text-to-image":
324
+ raise HTTPException(status_code=409, detail="not an image run")
325
+ advanced = parent.advanced or {}
326
+ try:
327
+ run = image_runner.create(
328
+ str((parent.inputs or {}).get("prompt") or ""),
329
+ model_id=str(advanced.get("model") or ""),
330
+ aspect=str(advanced.get("aspect") or "1:1"),
331
+ area=str(advanced.get("area") or "2K"),
332
+ parent=parent,
333
+ )
334
+ except ValueError as exc:
335
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
336
+ return JSONResponse(status_code=202, content={"run": run.model_dump()})
337
+
338
+
339
+ @app.get("/runs")
340
+ def list_runs(
341
+ offset: int = 0, limit: int = 20, q: str = "",
342
+ from_: str = Query("", alias="from"), to: str = "", status: str = "",
343
+ scenario: str = "", sort: str = "created_desc",
344
+ ) -> dict[str, Any]:
345
+ rows, total = store.list_runs_page(
346
+ offset=offset, limit=limit, query=q, date_from=from_, date_to=to,
347
+ status=status, scenario=scenario, sort=sort,
348
+ )
349
+ return {"runs": rows, "total": total, "offset": max(0, offset), "limit": max(1, min(limit, 200)), "has_more": offset + len(rows) < total}
350
+
351
+
352
+ @app.post("/runs/export")
353
+ def export_runs(payload: dict[str, Any] = Body(...)) -> FileResponse:
354
+ ids = [str(x) for x in (payload.get("run_ids") or []) if str(x).strip()]
355
+ ids = list(dict.fromkeys(ids))[:50]
356
+ if not ids:
357
+ raise HTTPException(status_code=400, detail="run_ids is required")
358
+ export_dir = store.DATA / "exports"
359
+ export_dir.mkdir(parents=True, exist_ok=True)
360
+ target = export_dir / f"adplus-export-{int(time.time())}.zip"
361
+ included = []
362
+ with zipfile.ZipFile(target, "w", compression=zipfile.ZIP_DEFLATED) as zf:
363
+ for run_id in ids:
364
+ run = store.read_run(run_id)
365
+ if run is None or run.status != "succeeded":
366
+ continue
367
+ root = store.run_dir(run_id)
368
+ folder = run_id
369
+ zf.write(root / "run.json", arcname=f"{folder}/run.json")
370
+ for name in ("final.mp4", "image.jpg", "subtitles.srt", "qa.json", "script.json", "skeleton.json", "storyboard.json"):
371
+ path = root / "artifacts" / name
372
+ if path.is_file():
373
+ zf.write(path, arcname=f"{folder}/artifacts/{name}")
374
+ included.append(run_id)
375
+ if not included:
376
+ target.unlink(missing_ok=True)
377
+ raise HTTPException(status_code=409, detail="no succeeded runs to export")
378
+ return FileResponse(target, media_type="application/zip", filename=target.name)
379
+
380
+
381
+ @app.patch("/runs/{run_id}")
382
+ def rename_run(run_id: str, payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
383
+ run = store.read_run(run_id)
384
+ if run is None:
385
+ raise HTTPException(status_code=404, detail="run not found")
386
+ title = str(payload.get("title") or "").strip()
387
+ if not title:
388
+ raise HTTPException(status_code=400, detail="title is required")
389
+ run.title = title[:120]
390
+ store.write_run(run)
391
+ return {"run": run.model_dump()}
392
+
393
+
394
+ @app.get("/runs/{run_id}")
395
+ def get_run(run_id: str) -> dict[str, Any]:
396
+ run = store.read_run(run_id)
397
+ if run is None:
398
+ raise HTTPException(status_code=404, detail="run not found")
399
+ data = run.model_dump()
400
+ storyboard = store.read_json(store.run_dir(run_id) / "artifacts" / "storyboard.json")
401
+ if storyboard:
402
+ data["storyboard"] = storyboard.get("segments") or []
403
+ return {"run": data}
404
+
405
+
406
+ @app.post("/runs/{run_id}/cancel")
407
+ def cancel_run(run_id: str) -> dict[str, Any]:
408
+ run = store.read_run(run_id)
409
+ if run is None:
410
+ raise HTTPException(status_code=404, detail="run not found")
411
+ run.cancel_requested = True
412
+ if run.status in {"queued", "running"}:
413
+ run.status = "canceled"
414
+ run.error = "已取消"
415
+ run.finished_at = store.now()
416
+ store.write_run(run)
417
+ return {"ok": True, "run": run.model_dump()}
418
+
419
+
420
+ @app.post("/runs/{run_id}/retry")
421
+ def retry_run(run_id: str) -> dict[str, Any]:
422
+ run = store.read_run(run_id)
423
+ if run is None:
424
+ raise HTTPException(status_code=404, detail="run not found")
425
+ new_run = _new_run(run.scenario, copy.deepcopy(run.inputs), copy.deepcopy(run.advanced), title=run.title, parent=run, changes=[])
426
+ return {"run": new_run.model_dump()}
427
+
428
+
429
+ @app.get("/runs/{run_id}/storyboard")
430
+ def storyboard(run_id: str) -> dict[str, Any]:
431
+ run = store.read_run(run_id)
432
+ if run is None:
433
+ raise HTTPException(status_code=404, detail="run not found")
434
+ data = store.read_json(store.run_dir(run_id) / "artifacts" / "storyboard.json")
435
+ if not data:
436
+ data = segment.build_storyboard(run_id)
437
+ return data
438
+
439
+
440
+ def _apply_changes(advanced: dict[str, Any], inputs: dict[str, Any], changes: list[dict[str, Any]]) -> None:
441
+ for change in changes:
442
+ field = str(change.get("field") or "")
443
+ value = change.get("to")
444
+ if field.startswith("advanced."):
445
+ advanced[field.split(".", 1)[1]] = value
446
+ elif field.startswith("post."):
447
+ advanced[field.split(".", 1)[1]] = value
448
+ elif field.startswith("persona."):
449
+ persona = dict(advanced.get("persona") or {})
450
+ persona[field.split(".", 1)[1]] = value
451
+ advanced["persona"] = persona
452
+ elif field == "inputs.brief":
453
+ inputs["brief"] = value
454
+
455
+
456
+ def _post_derive(parent: Run, changes: list[dict[str, Any]]) -> Run:
457
+ """Apply post-only changes without calling any video model."""
458
+ run_id = store.new_id("run")
459
+ root = store.run_dir(run_id) / "artifacts"
460
+ root.mkdir(parents=True, exist_ok=True)
461
+ src = store.run_dir(parent.id) / "artifacts"
462
+ for name in ("script.json", "skeleton.json", "storyboard.json", "qa.json"):
463
+ source = src / name
464
+ if source.is_file():
465
+ shutil.copy2(source, root / name)
466
+ advanced = copy.deepcopy(parent.advanced)
467
+ inputs = copy.deepcopy(parent.inputs)
468
+ _apply_changes(advanced, inputs, changes)
469
+ # The SRT follows the post-processed run's own setting, regenerated from the
470
+ # script that came over with the parent.
471
+ script = store.read_json(store.run_dir(parent.id) / "artifacts" / "script.json", {}) or {}
472
+ srt_target = root / "subtitles.srt"
473
+ if str(advanced.get("subtitle") or "off") == "sidecar":
474
+ subtitles.write_srt(script, srt_target)
475
+ else:
476
+ srt_target.unlink(missing_ok=True)
477
+ bitrate = str(advanced.get("export_bitrate") or "8M")
478
+ fps = int(advanced.get("fps") or 30)
479
+ source_video = src / "final.mp4"
480
+ if not source_video.is_file():
481
+ raise HTTPException(status_code=409, detail="run has no final video to post-process")
482
+ target = root / "final.mp4"
483
+ ffmpeg.transcode(
484
+ source_video,
485
+ target,
486
+ bitrate=bitrate,
487
+ fps=fps,
488
+ trim_start=advanced.get("trim_start"),
489
+ trim_end=advanced.get("trim_end"),
490
+ )
491
+ notes = []
492
+ if any(str((c.get("field") or "")).startswith("post.subtitle") for c in changes):
493
+ if str(advanced.get("subtitle") or "off") == "sidecar":
494
+ notes.append("字幕已改为 SRT 旁挂文件(画面不烧录)")
495
+ else:
496
+ notes.append("字幕已关闭,本次不生成 SRT")
497
+ if any(str((c.get("field") or "")).startswith("post.music") for c in changes):
498
+ notes.append("音乐替换尚未接入;本次未改动音轨")
499
+ run = Run(
500
+ id=run_id,
501
+ scenario=parent.scenario,
502
+ title=parent.title,
503
+ status="succeeded",
504
+ step="post",
505
+ progress=1.0,
506
+ generation_mode=parent.generation_mode,
507
+ inputs=inputs,
508
+ advanced=advanced,
509
+ persona_map=copy.deepcopy(parent.persona_map),
510
+ persona_snapshot=copy.deepcopy(parent.persona_snapshot),
511
+ steps=[RunStep(name="post", label="后期", status="done", progress=1.0, started_at=store.now(), finished_at=store.now())],
512
+ storyboard=copy.deepcopy(parent.storyboard),
513
+ result={
514
+ "video": store.rel_to_data(target),
515
+ "srt": store.rel_to_data(root / "subtitles.srt") if (root / "subtitles.srt").is_file() else None,
516
+ "width": (parent.result or {}).get("width"),
517
+ "height": (parent.result or {}).get("height"),
518
+ "duration_s": ffmpeg.probe(target)["duration_s"],
519
+ "qa": (parent.result or {}).get("qa"),
520
+ "demo": parent.demo,
521
+ "model": (parent.result or {}).get("model"),
522
+ "post_notes": notes,
523
+ "post_only": True,
524
+ },
525
+ demo=parent.demo,
526
+ created_at=store.now(),
527
+ finished_at=store.now(),
528
+ parent_run_id=parent.id,
529
+ version=parent.version + 1,
530
+ changes=changes,
531
+ )
532
+ store.write_run(run)
533
+ # The copied QA report described the parent's artifact set; re-check so a
534
+ # subtitle toggle shows up as the new run's own verdict.
535
+ report = qa_pipeline.check(run_id)
536
+ reloaded = store.read_run(run_id) or run
537
+ reloaded.result = {**(reloaded.result or {}), "qa": report}
538
+ store.write_run(reloaded)
539
+ return reloaded
540
+
541
+
542
+ @app.post("/runs/{run_id}/derive")
543
+ def derive_run(run_id: str, payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
544
+ parent = store.read_run(run_id)
545
+ if parent is None:
546
+ raise HTTPException(status_code=404, detail="run not found")
547
+ changes = list(payload.get("changes") or [])
548
+ if changes and all(str(change.get("stage") or "") == "post" for change in changes):
549
+ return {"run": _post_derive(parent, changes).model_dump()}
550
+ advanced = copy.deepcopy(parent.advanced)
551
+ inputs = copy.deepcopy(parent.inputs)
552
+ _apply_changes(advanced, inputs, changes)
553
+ title = str(payload.get("title") or parent.title)
554
+ new_run = _new_run(parent.scenario, inputs, advanced, title=title, parent=parent, changes=changes)
555
+ return {"run": new_run.model_dump()}
556
+
557
+
558
+ @app.post("/runs/{run_id}/segments/{segment_id}/regenerate")
559
+ def regenerate_segment(run_id: str, segment_id: str, payload: dict[str, Any] = Body(default={})) -> dict[str, Any]:
560
+ parent = store.read_run(run_id)
561
+ if parent is None:
562
+ raise HTTPException(status_code=404, detail="run not found")
563
+ advanced = copy.deepcopy(parent.advanced)
564
+ inputs = copy.deepcopy(parent.inputs)
565
+ changes = list(payload.get("changes") or [])
566
+ _apply_changes(advanced, inputs, changes)
567
+ advanced["generation_mode"] = "fine"
568
+ new_run = _new_run(parent.scenario, inputs, advanced, title=parent.title, parent=parent, changes=[{"field": "selected_segment_id", "from": None, "to": segment_id, "stage": "generate", "requires_regeneration": True}] + changes)
569
+ return {"run": new_run.model_dump()}
570
+
571
+
572
+ @app.post("/runs/{run_id}/segments/{segment_id}/replace")
573
+ def replace_segment(run_id: str, segment_id: str) -> JSONResponse:
574
+ try:
575
+ run = segment_replace.start_replace(run_id, segment_id)
576
+ except ValueError as exc:
577
+ message = str(exc)
578
+ code = 404 if "not found" in message else 409
579
+ raise HTTPException(status_code=code, detail=message) from exc
580
+ return JSONResponse(status_code=202, content={"run": run.model_dump()})
581
+
582
+
583
+ @app.post("/runs/{run_id}/rollback")
584
+ def rollback_segment(run_id: str) -> dict[str, Any]:
585
+ try:
586
+ run = segment_replace.rollback(run_id)
587
+ except ValueError as exc:
588
+ message = str(exc)
589
+ code = 404 if "not found" in message else 409
590
+ raise HTTPException(status_code=code, detail=message) from exc
591
+ return {"run": run.model_dump()}
592
+
593
+
594
+ @app.get("/runs/{run_id}/export")
595
+ def export_run(run_id: str) -> FileResponse:
596
+ run = store.read_run(run_id)
597
+ if run is None:
598
+ raise HTTPException(status_code=404, detail="run not found")
599
+ root = store.run_dir(run_id)
600
+ target = root / "artifacts" / "export.zip"
601
+ with zipfile.ZipFile(target, "w", compression=zipfile.ZIP_DEFLATED) as zf:
602
+ for name in ("final.mp4", "subtitles.srt", "qa.json", "script.json", "skeleton.json", "storyboard.json"):
603
+ path = root / "artifacts" / name
604
+ if path.is_file():
605
+ zf.write(path, arcname=name)
606
+ return FileResponse(target, media_type="application/zip", filename=f"{run_id}.zip")
607
+
608
+
609
+ # ---------------------------------------------------------------------------
610
+ # stitch
611
+ # ---------------------------------------------------------------------------
612
+ def _resolve_clips(payload: StitchRequest) -> list[dict[str, Any]]:
613
+ rows = []
614
+ for clip in payload.clips:
615
+ record = store.get_asset(clip.asset_id)
616
+ if record is None:
617
+ raise HTTPException(status_code=404, detail=f"asset not found: {clip.asset_id}")
618
+ rows.append({"path": str(store.safe_media_path(record["path"])), "in_s": clip.in_s, "out_s": clip.out_s})
619
+ return rows
620
+
621
+
622
+ @app.post("/stitch/plan")
623
+ def stitch_plan(payload: StitchRequest) -> dict[str, Any]:
624
+ rows = _resolve_clips(payload)
625
+ output = payload.output or {}
626
+ width, height = params.size_for(str(output.get("aspect") or "9:16"), str(output.get("resolution") or "720p"))
627
+ try:
628
+ plan = stitch_mod.plan(rows, width=width, height=height, fit=payload.fit, transition=payload.transition, audio=payload.audio)
629
+ except (ValueError, FileNotFoundError) as exc:
630
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
631
+ return {"plan": plan, "output": output}
632
+
633
+
634
+ @app.post("/stitch")
635
+ def stitch(payload: StitchRequest) -> dict[str, Any]:
636
+ rows = _resolve_clips(payload)
637
+ output = payload.output or {}
638
+ width, height = params.size_for(str(output.get("aspect") or "9:16"), str(output.get("resolution") or "720p"))
639
+ try:
640
+ plan = stitch_mod.plan(rows, width=width, height=height, fit=payload.fit, transition=payload.transition, audio=payload.audio)
641
+ run_id = store.new_id("stitch")
642
+ target = store.run_dir(run_id) / "artifacts" / "final.mp4"
643
+ target.parent.mkdir(parents=True, exist_ok=True)
644
+ stitch_mod.execute(plan, target)
645
+ except Exception as exc: # noqa: BLE001
646
+ raise HTTPException(status_code=500, detail=f"stitch failed: {exc}") from exc
647
+ asset = store.create_asset(target.read_bytes(), f"stitch-{run_id}.mp4", "video", "video/mp4")
648
+ record = _probe_asset(asset.id)
649
+ run = Run(
650
+ id=run_id,
651
+ scenario="stitch",
652
+ title="拼接结果",
653
+ status="succeeded",
654
+ step="done",
655
+ progress=1.0,
656
+ inputs={"asset_ids": [clip.asset_id for clip in payload.clips]},
657
+ advanced={"stitch": payload.model_dump()},
658
+ steps=[],
659
+ result={"video": record["path"], "asset_id": record["id"], "duration_s": record.get("duration_s"), "warnings": plan.get("warnings") or []},
660
+ demo=False,
661
+ created_at=store.now(),
662
+ finished_at=store.now(),
663
+ )
664
+ store.write_run(run)
665
+ return {"run": run.model_dump(), "asset": record, "plan": plan}
666
+
667
+
668
+ # ---------------------------------------------------------------------------
669
+ # context / assistant
670
+ # ---------------------------------------------------------------------------
671
+ @app.get("/context")
672
+ def get_context() -> dict[str, Any]:
673
+ return {"context": store.read_context()}
674
+
675
+
676
+ @app.post("/context")
677
+ def set_context(payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
678
+ return {"context": store.write_context(payload)}
679
+
680
+
681
+ @app.post("/assistant")
682
+ def assistant(req: AssistantRequest) -> dict[str, Any]:
683
+ return intents.analyze(req)
684
+
685
+
686
+ def main() -> None:
687
+ import uvicorn
688
+
689
+ parser = argparse.ArgumentParser()
690
+ parser.add_argument("--port", type=int, default=8787)
691
+ parser.add_argument("--host", default="127.0.0.1")
692
+ parser.add_argument("--graceful-timeout", type=int, default=5)
693
+ args = parser.parse_args()
694
+ uvicorn.run(
695
+ app,
696
+ host=args.host,
697
+ port=args.port,
698
+ log_level="warning",
699
+ timeout_graceful_shutdown=max(1, args.graceful_timeout),
700
+ )
701
+
702
+
703
+ if __name__ == "__main__":
704
+ main()