PRINTFILM: AI short-video marketing and AI short-drama creation platform
Add client-side history downloads, kepu batch skill, and tighter gitignore.
yi3b534f64d684
diff --git a/.cursor/skills/kepu-batch-opensource/SKILL.md b/.cursor/skills/kepu-batch-opensource/SKILL.mdnew file mode 100644index 0000000..fe1eed3--- /dev/null+++ b/.cursor/skills/kepu-batch-opensource/SKILL.md@@ -0,0 +1,111 @@+---+name: kepu-batch-opensource+description: >-+ Batch create PRINTFILM/kepu open-source科普 videos from WeChat articles + GitCC+ repos: scrape 公众号正文, write source_type=script口播 (no URLs), diversify+ template/ratio/voice, SSH-submit to prod, confirm storyboards, continue full+ pipeline. Use when user asks to 批量提交开源项目、抓公众号生成口播、确认分镜开始生成、+ kepu.printfilm.com demo 批量任务, or redo bad source_text from article text.+---++# Kepu 开源科普批量成片++线上:`https://kepu.printfilm.com/` · 账号:`[email protected]` / `demo1234`+API 变更优先走 **SSH → 服务器 `http://127.0.0.1:8000`**(外网 SSL 常不稳定)。++工作目录约定:本地产物放 `.tmp/`(已 gitignore),勿提交 token / JSON / 日志。++## 何时用++- 用户给出一批「标题 + GitCC + 可选公众号链接」要做成片+- 要求「先抓公众号再写 source_text」或纠正错误口播后重提+- 「确认所有分镜 / 继续生成」整批续跑++## 流程清单++```+Task Progress:+- [ ] 1. 解析清单(repo / article / 约束)+- [ ] 2. 浏览器抓公众号正文(必做;删文则 GitCC README)+- [ ] 3. 写 .tmp/scripts_YYYYMMDD.json(script + 多样性)+- [ ] 4. base64 SSH 上传并创建+首次 generate(到 SCRIPT_READY)+- [ ] 5. ascii() 校验标题/口播 UTF-8+- [ ] 6. SCRIPT_READY 后二次 generate(成片)+- [ ] 7. 汇报 studio 链接表+```++### 1. 解析清单++每条至少:`title_hint`、`repo`、可选 `article`(mp.weixin.qq.com)。+默认:`source_type=script`、`pipeline_mode=full`、`resolution_mode=preview`。+用户指定「只到分镜」则停在步骤 4,勿执行步骤 6。++### 2. 抓公众号(硬约束)++1. 用 **cursor-ide-browser**:`browser_navigate` → `browser_lock` → 等正文 → CDP `document.body.innerText` 或 snapshot。+2. 写入 `.tmp/wechat-YYYYMMDD.md`(标题、要点、功能、场景)。+3. **禁止**仅凭标题/简介编功能细节当正文。+4. 公众号「已删除」→ 抓 GitCC README(公开页);仍无文则标 `source=user_brief`,口播只展开用户原句,并在汇报里标明。+5. 私仓需登录时不要硬登;改用用户文案或请用户补链接。++### 3. 写口播 JSON++路径:`.tmp/scripts_YYYYMMDD.json`,UTF-8 数组。字段:++| 字段 | 说明 |+|------|------|+| `title` | 中文短标题 |+| `source_text` | 完整口播,3 段左右,**禁止** URL / 域名 / 端口 / `http` |+| `template_id` | 每条尽量不同,见 [reference.md](reference.md) |+| `output_ratio` | 在 `16:9` / `9:16` 间打散 |+| `voice_id` | 在 5 个 openspeech 音色间打散 |+| `pipeline_mode` | 默认 `full` |+| `repo` / `article` | 溯源用,不进口播 |++口播结构:痛点/风口 → 核心能力(来自正文)→ 场景与开源价值。++### 4. 提交(拆分镜)++```bash+python .cursor/skills/kepu-batch-opensource/scripts/batch_submit.py .tmp/scripts_YYYYMMDD.json+```++脚本会:读 SSH 凭据(见下)→ base64 上传 JSON → demo 登录 → `POST /api/projects` → `POST .../generate` → 写 `.tmp/submit-results.json`。++凭据(勿写入 skill / 勿提交):++1. 环境变量 `KEPU_SSH_HOST` / `KEPU_SSH_USER` / `KEPU_SSH_PASSWORD`+2. 或已 gitignore 的 `deploy/scripts/deploy_kepu.py` 中 `HOST`/`USER`/`PASSWORD`++### 5. UTF-8 校验++在服务器对新建 project:`ascii(title)` + `source_text[:20]`。乱码则 cancel+delete 后用 base64 重传,勿用可能损坏编码的 scp/echo。++### 6. 确认分镜并成片++分镜齐后(`SCRIPT_READY` 且 `shots>0`):++```bash+python .cursor/skills/kepu-batch-opensource/scripts/batch_confirm_continue.py --ids 49-58+# 或 --from-results .tmp/submit-results.json+```++等价 API:对每个 `SCRIPT_READY` 再 `POST /api/projects/{id}/generate` → 进入 `IMAGING`…+进行中(`SCRIPTING`/`IMAGING`/…)勿重复点,会 409。++重做整批:先 `POST .../cancel`(可忽略失败)再 `DELETE`,再提交。++### 7. 汇报++表格:`# | id | title | template | ratio | voice | shots | status | studio URL`。+注明哪些口播来自公众号 / README / 用户简介。++## 运维注意++- 生产前端构建:`VITE_API_BASE` 必须为空(同源),禁止把本地 `.env` 打进 dist。+- Celery 需听 `-Q pipeline,oss`(异步 OSS 上传)。+- 勿 commit `.tmp/`、token、含密码的 deploy 脚本。++## 详细参考++- 模板 / 音色 / API / 状态机:[reference.md](reference.md)diff --git a/.cursor/skills/kepu-batch-opensource/reference.md b/.cursor/skills/kepu-batch-opensource/reference.mdnew file mode 100644index 0000000..98051c7--- /dev/null+++ b/.cursor/skills/kepu-batch-opensource/reference.md@@ -0,0 +1,69 @@+# Kepu batch — reference++## Endpoints(localhost on prod)++| Method | Path | 用途 |+|--------|------|------|+| POST | `/api/auth/login` | `{"email","password"}` → `access_token` |+| POST | `/api/projects` | 创建;`source_type=script` |+| PATCH | `/api/projects/{id}` | 补 `output_ratio` / `voice_id` / `pipeline_mode` |+| GET | `/api/projects/{id}` | 状态、`shots`、`source_text` |+| POST | `/api/projects/{id}/generate` | 首次→拆分镜;`SCRIPT_READY` 再调→成片 |+| POST | `/api/projects/{id}/cancel` | 取消进行中 |+| DELETE | `/api/projects/{id}` | 删除 |++Create body 关键字段:`template_id`, `title`, `source_type`, `source_text`, `resolution_mode`, `pipeline_mode`, `output_ratio`, `voice_id`。++## Status++`DRAFT` → `SCRIPTING` → `SCRIPT_READY` → `IMAGING` → `VIDEOING` / `AUDIOING` → `COMPOSING` → `DONE`+失败/取消:`FAILED` / `CANCELLED`。忙碌态勿重复 generate。++## Templates(`backend/app/services/templates_seed.py`)++多样打散优先非重复;开源向可用 `opensource_showcase`,也可混用风格模板:++`opensource_showcase`, `portrait_story`, `live_cinematic`, `live_person`, `photo_realism`, `film_cinematic`, `noir_thriller`, `vox_papercut`, `docu_warm`, `kids_flat`, `soft_anime`, `chalk_whiteboard`, `cyber_neon`, `epic_fantasy`, `magazine_collage`, `brand_clean`, `pixel_retro`, `retro_vhs`, `ink_guofeng`++## Voices(`backend/app/services/voices.py`)++| voice_id | 标签 |+|----------|------|+| `zh_female_cancan_uranus_bigtts` | 灿灿 · 女声旁白 |+| `zh_female_tianmeixiaoyuan_uranus_bigtts` | 甜美女声 · 故事 |+| `zh_female_shuangkuaisisi_uranus_bigtts` | 爽快女声 · 都市 |+| `zh_female_vv_uranus_bigtts` | Vivi · 国风女声 |+| `zh_male_shaonianzixin_uranus_bigtts` | 少年梓辛 · 男声 |++## scripts JSON 示例++```json+[+ {+ "repo": "https://www.gitcc.com/org/repo",+ "article": "https://mp.weixin.qq.com/s/xxxx",+ "template_id": "cyber_neon",+ "output_ratio": "16:9",+ "voice_id": "zh_male_shaonianzixin_uranus_bigtts",+ "pipeline_mode": "full",+ "title": "示例标题",+ "source_text": "第一段痛点。\n\n第二段能力(来自公众号)。\n\n第三段场景与开源价值。"+ }+]+```++## SSH 传输++中文 JSON **必须** base64 整文件写远端,例如:++```python+open("/tmp/scripts.json","wb").write(base64.b64decode(b64))+```++本地控制台乱码不代表库坏;以远端 `ascii(title)` 为准。++## 凭据++- Demo:`[email protected]` / `demo1234`+- SSH:环境变量或 `deploy/scripts/deploy_kepu.py`(该文件已 gitignore)+- 公开站:`https://kepu.printfilm.com/studio/{id}`diff --git a/.cursor/skills/kepu-batch-opensource/scripts/_kepu_ssh.py b/.cursor/skills/kepu-batch-opensource/scripts/_kepu_ssh.pynew file mode 100644index 0000000..fcd782e--- /dev/null+++ b/.cursor/skills/kepu-batch-opensource/scripts/_kepu_ssh.py@@ -0,0 +1,68 @@+# -*- coding: utf-8 -*-+"""SSH helpers for kepu.printfilm.com batch jobs."""+from __future__ import annotations++import base64+import os+import re+from pathlib import Path++import paramiko++REPO_ROOT = Path(__file__).resolve().parents[4]+DEPLOY_KEPU = REPO_ROOT / "deploy" / "scripts" / "deploy_kepu.py"+DEFAULT_API = "http://127.0.0.1:8000"+DEMO_EMAIL = "[email protected]"+DEMO_PASSWORD = "demo1234"+++def load_ssh_creds() -> tuple[str, str, str]:+ host = os.environ.get("KEPU_SSH_HOST", "").strip()+ user = os.environ.get("KEPU_SSH_USER", "").strip()+ password = os.environ.get("KEPU_SSH_PASSWORD", "").strip()+ if host and user and password:+ return host, user, password+ if not DEPLOY_KEPU.is_file():+ raise FileNotFoundError(+ "Set KEPU_SSH_HOST/USER/PASSWORD or provide deploy/scripts/deploy_kepu.py"+ )+ text = DEPLOY_KEPU.read_text(encoding="utf-8", errors="replace")++ def grab(name: str) -> str:+ m = re.search(rf'^{name}\s*=\s*([\'"])(.*?)\1', text, re.M)+ if not m:+ raise ValueError(f"{name} not found in {DEPLOY_KEPU}")+ return m.group(2)++ return grab("HOST"), grab("USER"), grab("PASSWORD")+++def connect() -> paramiko.SSHClient:+ host, user, password = load_ssh_creds()+ ssh = paramiko.SSHClient()+ ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())+ ssh.connect(host, username=user, password=password, timeout=30)+ return ssh+++def run(ssh: paramiko.SSHClient, cmd: str, timeout: int = 120) -> tuple[str, str]:+ _i, o, e = ssh.exec_command(cmd, timeout=timeout)+ return o.read().decode("utf-8", "replace"), e.read().decode("utf-8", "replace")+++def put_bytes(ssh: paramiko.SSHClient, remote_path: str, data: bytes) -> None:+ b64 = base64.b64encode(data).decode("ascii")+ py = (+ "python3 - <<'PY'\n"+ "import base64\n"+ f"open({remote_path!r},'wb').write(base64.b64decode({b64!r}))\n"+ f"print('wrote', {remote_path!r}, len(open({remote_path!r},'rb').read()))\n"+ "PY"+ )+ out, err = run(ssh, py, timeout=180)+ if "wrote" not in out:+ raise RuntimeError(f"put_bytes failed: {out}\n{err}")+++def put_text(ssh: paramiko.SSHClient, remote_path: str, text: str) -> None:+ put_bytes(ssh, remote_path, text.encode("utf-8"))diff --git a/.cursor/skills/kepu-batch-opensource/scripts/batch_confirm_continue.py b/.cursor/skills/kepu-batch-opensource/scripts/batch_confirm_continue.pynew file mode 100644index 0000000..60f1bfd--- /dev/null+++ b/.cursor/skills/kepu-batch-opensource/scripts/batch_confirm_continue.py@@ -0,0 +1,161 @@+# -*- coding: utf-8 -*-+"""Wait until SCRIPT_READY then continue full pipeline for project ids.++Usage:+ python batch_confirm_continue.py --ids 49-58+ python batch_confirm_continue.py --ids 49,50,51+ python batch_confirm_continue.py --from-results .tmp/submit-results.json+"""+from __future__ import annotations++import argparse+import json+import sys+import textwrap+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _kepu_ssh import DEFAULT_API, DEMO_EMAIL, DEMO_PASSWORD, connect, put_text, run++REMOTE_RUNNER = "/tmp/kepu_batch_confirm_runner.py"+REMOTE_OUT = "/tmp/kepu_batch_confirm_results.json"+++def parse_ids(spec: str) -> list[int]:+ ids: list[int] = []+ for part in spec.split(","):+ part = part.strip()+ if not part:+ continue+ if "-" in part:+ a, b = part.split("-", 1)+ ids.extend(range(int(a), int(b) + 1))+ else:+ ids.append(int(part))+ return ids+++def build_runner(pids: list[int], wait_sec: int) -> str:+ return textwrap.dedent(+ f"""\+ # -*- coding: utf-8 -*-+ import json, time, urllib.request, urllib.error+ BASE = {DEFAULT_API!r}+ PIDS = {pids!r}+ OUT = {REMOTE_OUT!r}+ EMAIL = {DEMO_EMAIL!r}+ PASSWORD = {DEMO_PASSWORD!r}+ WAIT = {wait_sec}++ def api(method, path, body=None, token=None, timeout=120):+ data = None+ headers = {{"Accept": "application/json"}}+ if token:+ headers["Authorization"] = "Bearer " + token+ if body is not None:+ data = json.dumps(body, ensure_ascii=False).encode("utf-8")+ headers["Content-Type"] = "application/json; charset=utf-8"+ req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ raw = resp.read().decode("utf-8")+ return json.loads(raw) if raw else {{}}+ except urllib.error.HTTPError as e:+ text = e.read().decode("utf-8", "replace")+ raise RuntimeError(f"{{method}} {{path}} -> {{e.code}}: {{text[:500]}}") from e++ tok = api("POST", "/api/auth/login", {{"email": EMAIL, "password": PASSWORD}})["access_token"]+ print("login ok", flush=True)+ deadline = time.time() + WAIT+ while time.time() < deadline:+ rows = []+ for pid in PIDS:+ p = api("GET", f"/api/projects/{{pid}}", token=tok)+ rows.append((pid, p.get("status"), len(p.get("shots") or []), p.get("title") or ""))+ scripting = [r for r in rows if r[1] == "SCRIPTING"]+ ready = [r for r in rows if r[1] == "SCRIPT_READY"]+ print(+ "poll ready=%d scripting=%d | %s"+ % (len(ready), len(scripting), " | ".join(f"{{a}}:{{b}}/{{c}}t" for a,b,c,*_ in rows)),+ flush=True,+ )+ if not scripting:+ break+ time.sleep(8)++ results = []+ for pid in PIDS:+ p = api("GET", f"/api/projects/{{pid}}", token=tok)+ st = p.get("status")+ title = p.get("title") or ""+ tpl = p.get("template_id")+ shots = len(p.get("shots") or [])+ if st == "SCRIPT_READY":+ try:+ gen = api("POST", f"/api/projects/{{pid}}/generate", token=tok)+ row = {{+ "id": pid, "title": title, "template_id": tpl, "shots": shots,+ "action": "continue", "status": gen.get("status"),+ "url": f"https://kepu.printfilm.com/studio/{{pid}}",+ }}+ print("CONTINUE", pid, title, "->", gen.get("status"), flush=True)+ except Exception as ex:+ row = {{+ "id": pid, "title": title, "template_id": tpl, "shots": shots,+ "action": "error", "status": str(ex),+ "url": f"https://kepu.printfilm.com/studio/{{pid}}",+ }}+ print("FAIL", pid, ex, flush=True)+ else:+ row = {{+ "id": pid, "title": title, "template_id": tpl, "shots": shots,+ "action": "skip", "status": st,+ "url": f"https://kepu.printfilm.com/studio/{{pid}}",+ }}+ print("SKIP", pid, st, "shots=", shots, title, flush=True)+ results.append(row)+ time.sleep(0.4)++ open(OUT, "w", encoding="utf-8").write(json.dumps(results, ensure_ascii=False, indent=2))+ print("DONE", OUT, flush=True)+ """+ )+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--ids", help="e.g. 49-58 or 49,50,51")+ ap.add_argument("--from-results", type=Path, help="submit-results.json with id fields")+ ap.add_argument("--wait", type=int, default=900, help="max seconds waiting for SCRIPT_READY")+ ap.add_argument("--out", type=Path, default=Path(".tmp/confirm-continue-results.json"))+ args = ap.parse_args()++ pids: list[int] = []+ if args.from_results:+ rows = json.loads(args.from_results.read_text(encoding="utf-8"))+ pids = [int(r["id"]) for r in rows]+ if args.ids:+ pids = parse_ids(args.ids)+ if not pids:+ print("provide --ids or --from-results", file=sys.stderr)+ return 2+ print("pids", pids)++ ssh = connect()+ try:+ put_text(ssh, REMOTE_RUNNER, build_runner(pids, args.wait))+ out, err = run(ssh, f"python3 {REMOTE_RUNNER}", timeout=args.wait + 120)+ print(out)+ if err.strip():+ print("STDERR", err[-800:], file=sys.stderr)+ out_bytes, _ = run(ssh, f"cat {REMOTE_OUT}", timeout=30)+ args.out.parent.mkdir(parents=True, exist_ok=True)+ args.out.write_text(out_bytes, encoding="utf-8")+ print("saved", args.out)+ finally:+ ssh.close()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.cursor/skills/kepu-batch-opensource/scripts/batch_submit.py b/.cursor/skills/kepu-batch-opensource/scripts/batch_submit.pynew file mode 100644index 0000000..e812dff--- /dev/null+++ b/.cursor/skills/kepu-batch-opensource/scripts/batch_submit.py@@ -0,0 +1,132 @@+# -*- coding: utf-8 -*-+"""Upload scripts JSON via SSH and create+generate projects on prod localhost API.++Usage:+ python .cursor/skills/kepu-batch-opensource/scripts/batch_submit.py .tmp/scripts.json+"""+from __future__ import annotations++import argparse+import json+import sys+import textwrap+from pathlib import Path++# allow running as script from any cwd+sys.path.insert(0, str(Path(__file__).resolve().parent))+from _kepu_ssh import DEFAULT_API, DEMO_EMAIL, DEMO_PASSWORD, connect, put_bytes, put_text, run++REMOTE_SCRIPTS = "/tmp/kepu_batch_scripts.json"+REMOTE_RUNNER = "/tmp/kepu_batch_submit_runner.py"+REMOTE_OUT = "/tmp/kepu_batch_submit_results.json"+++def build_runner() -> str:+ return textwrap.dedent(+ f"""\+ # -*- coding: utf-8 -*-+ import json, time, urllib.request, urllib.error+ BASE = {DEFAULT_API!r}+ SCRIPTS = {REMOTE_SCRIPTS!r}+ OUT = {REMOTE_OUT!r}+ EMAIL = {DEMO_EMAIL!r}+ PASSWORD = {DEMO_PASSWORD!r}++ def api(method, path, body=None, token=None, timeout=120):+ data = None+ headers = {{"Accept": "application/json"}}+ if token:+ headers["Authorization"] = "Bearer " + token+ if body is not None:+ data = json.dumps(body, ensure_ascii=False).encode("utf-8")+ headers["Content-Type"] = "application/json; charset=utf-8"+ req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ raw = resp.read().decode("utf-8")+ return json.loads(raw) if raw else {{}}+ except urllib.error.HTTPError as e:+ text = e.read().decode("utf-8", "replace")+ raise RuntimeError(f"{{method}} {{path}} -> {{e.code}}: {{text[:800]}}") from e++ tok = api("POST", "/api/auth/login", {{"email": EMAIL, "password": PASSWORD}})["access_token"]+ print("login ok", flush=True)+ items = json.load(open(SCRIPTS, encoding="utf-8"))+ print("count", len(items), "title0", items[0].get("title"), flush=True)+ results = []+ for i, it in enumerate(items, 1):+ print(f"=== {{i}}/{{len(items)}} {{it.get('title')}} tpl={{it.get('template_id')}}", flush=True)+ body = {{+ "template_id": it["template_id"],+ "title": it["title"],+ "source_type": "script",+ "source_text": it["source_text"],+ "resolution_mode": it.get("resolution_mode", "preview"),+ "pipeline_mode": it.get("pipeline_mode", "full"),+ "output_ratio": it["output_ratio"],+ "voice_id": it["voice_id"],+ }}+ p = api("POST", "/api/projects", body, token=tok)+ pid = p["id"]+ api("PATCH", f"/api/projects/{{pid}}", {{+ "output_ratio": it["output_ratio"],+ "voice_id": it["voice_id"],+ "pipeline_mode": it.get("pipeline_mode", "full"),+ }}, token=tok)+ gen = api("POST", f"/api/projects/{{pid}}/generate", token=tok)+ row = {{+ "id": pid,+ "title": gen.get("title") or it["title"],+ "template_id": gen.get("template_id"),+ "status": gen.get("status"),+ "output_ratio": gen.get("output_ratio"),+ "voice_id": gen.get("voice_id"),+ "url": f"https://kepu.printfilm.com/studio/{{pid}}",+ }}+ results.append(row)+ print(json.dumps(row, ensure_ascii=False), flush=True)+ time.sleep(0.5)++ for r in results:+ d = api("GET", f"/api/projects/{{r['id']}}", token=tok)+ print("verify", r["id"], ascii(d.get("title")), d.get("status"),+ ascii((d.get("source_text") or "")[:16]), flush=True)++ open(OUT, "w", encoding="utf-8").write(json.dumps(results, ensure_ascii=False, indent=2))+ print("DONE", OUT, flush=True)+ """+ )+++def main() -> int:+ ap = argparse.ArgumentParser(description="Batch create kepu projects from scripts JSON")+ ap.add_argument("scripts_json", type=Path)+ ap.add_argument("--out", type=Path, default=Path(".tmp/submit-results.json"))+ args = ap.parse_args()++ raw = args.scripts_json.read_bytes()+ items = json.loads(raw.decode("utf-8"))+ if not isinstance(items, list) or not items:+ print("scripts json must be a non-empty array", file=sys.stderr)+ return 2+ print("local0", items[0].get("title"), "count", len(items))++ ssh = connect()+ try:+ put_bytes(ssh, REMOTE_SCRIPTS, raw)+ put_text(ssh, REMOTE_RUNNER, build_runner())+ out, err = run(ssh, f"python3 {REMOTE_RUNNER}", timeout=600)+ print(out)+ if err.strip():+ print("STDERR", err[-800:], file=sys.stderr)+ out_bytes, _ = run(ssh, f"cat {REMOTE_OUT}", timeout=30)+ args.out.parent.mkdir(parents=True, exist_ok=True)+ args.out.write_text(out_bytes, encoding="utf-8")+ print("saved", args.out)+ finally:+ ssh.close()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.gitignore b/.gitignoreindex a93438e..2e16b4e 100644--- a/.gitignore+++ b/.gitignore@@ -1,20 +1,61 @@+# OS / editor.DS_StoreThumbs.db-*.log.idea/.vscode/+*.swp+*~++# Logs & local scratch (batch ops, polls, tokens)+*.log+.tmp/+.tmp/**+agent-tools/++# Python__pycache__/-*.pyc+*.py[cod]+*$py.class+*.egg-info/+.pytest_cache/+.mypy_cache/+.ruff_cache/+.coverage+htmlcov/backend/.venv/-backend/ai_movie.db-backend/.env+.venv/+venv/++# Secrets & local env (keep *.example and frontend/.env.production committed)+.env+**/.env+!**/.env.example+!**/.env.*.example+!frontend/.env.productiondeploy/.env.proddeploy/scripts/deploy_kepu.py+frontend/.env.local+frontend/.env.*.local++# Never commit tokens / credentials dumps+**/token.txt+**/*credentials*.json+**/*.pem+**/*.key+!**/example*.pem++# Backend runtime data+backend/ai_movie.db+backend/*.dbbackend/.celery_autoscale/backend/static/generated/backend/static/voice_previews/backend/frontend/-.claude/-frontend/.env++# Frontend buildfrontend/node_modules/frontend/dist/++# Claude / local agent notes (project skills live under .cursor/skills — keep those)+.claude/+.work/diff --git a/backend/app/main.py b/backend/app/main.pyindex 9c8906a..28ec8ef 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -50,6 +50,12 @@ async def on_startup() -> None:await init_db()await _migrate_sqlite()await seed_templates()+ try:+ from app.services import oss as oss_svc++ oss_svc.ensure_browser_cors()+ except Exception: # noqa: BLE001+ passasync def _migrate_sqlite() -> None:diff --git a/backend/app/services/oss.py b/backend/app/services/oss.pyindex 3b3b552..b4747e4 100644--- a/backend/app/services/oss.py+++ b/backend/app/services/oss.py@@ -59,6 +59,47 @@ def public_url(object_key: str) -> str:return f"{public_base()}/{key}"+def ensure_browser_cors() -> None:+ """Allow SPA origins to fetch OSS media (needed for client-side zip)."""+ if not oss_enabled():+ return+ s = get_settings()+ origins = [+ o.strip()+ for o in (s.cors_origins or "").split(",")+ if o.strip()+ ]+ # Production site + common local/dev+ for extra in (+ "https://kepu.printfilm.com",+ "http://kepu.printfilm.com",+ "http://localhost:5173",+ "http://127.0.0.1:5173",+ "http://localhost:4173",+ "http://127.0.0.1:4173",+ ):+ if extra not in origins:+ origins.append(extra)+ pub = (s.public_base_url or "").rstrip("/")+ if pub and pub not in origins:+ origins.append(pub)+ try:+ import oss2+ from oss2.models import BucketCors, CorsRule++ rule = CorsRule(+ allowed_origins=origins,+ allowed_methods=["GET", "HEAD"],+ allowed_headers=["*"],+ expose_headers=["ETag", "Content-Length", "Content-Type"],+ max_age_seconds=3600,+ )+ _bucket().put_bucket_cors(BucketCors([rule]))+ logger.info("oss CORS updated for %s origin(s)", len(origins))+ except Exception: # noqa: BLE001+ logger.exception("oss CORS update failed")++def key_for_local(path: Path, *, static_root: Path) -> str:"""Map backend/static/... → {folder}/..."""rel = path.resolve().relative_to(static_root.resolve()).as_posix()diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex b89ae97..fc21352 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -8,11 +8,13 @@"name": "frontend","version": "0.0.0","dependencies": {+ "jszip": "^3.10.1","react": "^19.2.8","react-dom": "^19.2.8","react-router-dom": "^7.18.2"},"devDependencies": {+ "@types/jszip": "^3.4.0","@types/node": "^24.13.3","@types/react": "^19.2.17","@types/react-dom": "^19.2.3",@@ -642,6 +644,16 @@"dev": true,"license": "MIT"},+ "node_modules/@types/jszip": {+ "version": "3.4.0",+ "resolved": "https://registry.npmmirror.com/@types/jszip/-/jszip-3.4.0.tgz",+ "integrity": "sha512-GFHqtQQP3R4NNuvZH3hNCYD0NbyBZ42bkN7kO3NDrU/SnvIZWMS8Bp38XCsRKBT5BXvgm0y1zqpZWp/ZkRzBzg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "jszip": "*"+ }+ },"node_modules/@types/node": {"version": "24.13.3","resolved": "https://registry.npmmirror.com/@types/node/-/node-24.13.3.tgz",@@ -711,6 +723,12 @@"url": "https://opencollective.com/express"}},+ "node_modules/core-util-is": {+ "version": "1.0.3",+ "resolved": "https://registry.npmmirror.com/core-util-is/-/core-util-is-1.0.3.tgz",+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",+ "license": "MIT"+ },"node_modules/csstype": {"version": "3.2.3","resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",@@ -761,6 +779,45 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/immediate": {+ "version": "3.0.6",+ "resolved": "https://registry.npmmirror.com/immediate/-/immediate-3.0.6.tgz",+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",+ "license": "MIT"+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/isarray": {+ "version": "1.0.0",+ "resolved": "https://registry.npmmirror.com/isarray/-/isarray-1.0.0.tgz",+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",+ "license": "MIT"+ },+ "node_modules/jszip": {+ "version": "3.10.1",+ "resolved": "https://registry.npmmirror.com/jszip/-/jszip-3.10.1.tgz",+ "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",+ "license": "(MIT OR GPL-3.0-or-later)",+ "dependencies": {+ "lie": "~3.3.0",+ "pako": "~1.0.2",+ "readable-stream": "~2.3.6",+ "setimmediate": "^1.0.5"+ }+ },+ "node_modules/lie": {+ "version": "3.3.0",+ "resolved": "https://registry.npmmirror.com/lie/-/lie-3.3.0.tgz",+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",+ "license": "MIT",+ "dependencies": {+ "immediate": "~3.0.5"+ }+ },"node_modules/lightningcss": {"version": "1.33.0","resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.33.0.tgz",@@ -1102,6 +1159,12 @@}}},+ "node_modules/pako": {+ "version": "1.0.11",+ "resolved": "https://registry.npmmirror.com/pako/-/pako-1.0.11.tgz",+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",+ "license": "(MIT AND Zlib)"+ },"node_modules/picocolors": {"version": "1.1.1","resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",@@ -1151,6 +1214,12 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/process-nextick-args": {+ "version": "2.0.1",+ "resolved": "https://registry.npmmirror.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz",+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",+ "license": "MIT"+ },"node_modules/react": {"version": "19.2.8","resolved": "https://registry.npmmirror.com/react/-/react-19.2.8.tgz",@@ -1210,6 +1279,21 @@"react-dom": ">=18"}},+ "node_modules/readable-stream": {+ "version": "2.3.8",+ "resolved": "https://registry.npmmirror.com/readable-stream/-/readable-stream-2.3.8.tgz",+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",+ "license": "MIT",+ "dependencies": {+ "core-util-is": "~1.0.0",+ "inherits": "~2.0.3",+ "isarray": "~1.0.0",+ "process-nextick-args": "~2.0.0",+ "safe-buffer": "~5.1.1",+ "string_decoder": "~1.1.1",+ "util-deprecate": "~1.0.1"+ }+ },"node_modules/rolldown": {"version": "1.2.2","resolved": "https://registry.npmmirror.com/rolldown/-/rolldown-1.2.2.tgz",@@ -1243,6 +1327,12 @@"@rolldown/binding-win32-x64-msvc": "1.2.2"}},+ "node_modules/safe-buffer": {+ "version": "5.1.2",+ "resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.1.2.tgz",+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",+ "license": "MIT"+ },"node_modules/scheduler": {"version": "0.27.0","resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.27.0.tgz",@@ -1255,6 +1345,12 @@"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==","license": "MIT"},+ "node_modules/setimmediate": {+ "version": "1.0.5",+ "resolved": "https://registry.npmmirror.com/setimmediate/-/setimmediate-1.0.5.tgz",+ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",+ "license": "MIT"+ },"node_modules/source-map-js": {"version": "1.2.1","resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz",@@ -1265,6 +1361,15 @@"node": ">=0.10.0"}},+ "node_modules/string_decoder": {+ "version": "1.1.1",+ "resolved": "https://registry.npmmirror.com/string_decoder/-/string_decoder-1.1.1.tgz",+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.1.0"+ }+ },"node_modules/tinyglobby": {"version": "0.2.17","resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz",@@ -1303,6 +1408,12 @@"dev": true,"license": "MIT"},+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },"node_modules/vite": {"version": "8.2.0","resolved": "https://registry.npmmirror.com/vite/-/vite-8.2.0.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 21f1141..731d256 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -10,11 +10,13 @@"preview": "vite preview"},"dependencies": {+ "jszip": "^3.10.1","react": "^19.2.8","react-dom": "^19.2.8","react-router-dom": "^7.18.2"},"devDependencies": {+ "@types/jszip": "^3.4.0","@types/node": "^24.13.3","@types/react": "^19.2.17","@types/react-dom": "^19.2.3",diff --git a/frontend/src/components/ui/HelpCenter.tsx b/frontend/src/components/ui/HelpCenter.tsxindex 594cf7e..435ec82 100644--- a/frontend/src/components/ui/HelpCenter.tsx+++ b/frontend/src/components/ui/HelpCenter.tsx@@ -55,7 +55,7 @@ const FAQ_ITEMS = [},{q: '成片在哪里下载?',- a: '项目状态为「已完成」后,在分镜页预览弹窗或「历史」列表中可下载成片;历史页也支持批量打包下载。',+ a: '项目状态为「已完成」后,在「历史」列表可单独下载成片;勾选多个项目后点「打包下载」,由浏览器依次拉取并打成 ZIP,不经过服务器中转。',},{q: '需要角色始终同一人吗?',diff --git a/frontend/src/lib/clientDownload.ts b/frontend/src/lib/clientDownload.tsnew file mode 100644index 0000000..561b7c5--- /dev/null+++ b/frontend/src/lib/clientDownload.ts@@ -0,0 +1,75 @@+/** Client-side video download + zip (no server pack endpoint). */++import JSZip from 'jszip'++export function safeDownloadBasename(title: string, projectId: number): string {+ const raw = (title || '未命名作品').trim() || '未命名作品'+ const cleaned = raw+ .replace(/[<>:"/\\|?*\x00-\x1f]+/g, '_')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, 60)+ return `${cleaned || '未命名作品'}_p${projectId}`+}++export function triggerBlobDownload(blob: Blob, filename: string) {+ const url = URL.createObjectURL(blob)+ const a = document.createElement('a')+ a.href = url+ a.download = filename+ document.body.appendChild(a)+ a.click()+ a.remove()+ URL.revokeObjectURL(url)+}++export async function fetchMediaBlob(url: string): Promise<Blob> {+ const res = await fetch(url, { mode: 'cors', credentials: 'omit' })+ if (!res.ok) {+ throw new Error(`下载失败(${res.status})`)+ }+ return res.blob()+}++export async function downloadSingleVideo(opts: {+ url: string+ title: string+ projectId: number+}): Promise<void> {+ const blob = await fetchMediaBlob(opts.url)+ triggerBlobDownload(blob, `${safeDownloadBasename(opts.title, opts.projectId)}.mp4`)+}++export type ZipVideoItem = {+ id: number+ title: string+ url: string+}++export async function zipVideosClient(+ items: ZipVideoItem[],+ onProgress?: (done: number, total: number) => void,+): Promise<{ blob: Blob; filename: string }> {+ if (!items.length) {+ throw new Error('请选择已完成的项目')+ }+ const zip = new JSZip()+ const used = new Set<string>()+ const total = items.length++ for (let i = 0; i < items.length; i++) {+ const item = items[i]+ const blob = await fetchMediaBlob(item.url)+ let base = `${safeDownloadBasename(item.title, item.id)}.mp4`+ if (used.has(base)) {+ base = `${safeDownloadBasename(item.title, item.id)}_${i + 1}.mp4`+ }+ used.add(base)+ zip.file(base, blob)+ onProgress?.(i + 1, total)+ }++ const out = await zip.generateAsync({ type: 'blob', compression: 'STORE' })+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '')+ return { blob: out, filename: `printfilm_videos_${stamp}_${items.length}.zip` }+}diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsxindex a6ea82c..9c85ebc 100644--- a/frontend/src/pages/HistoryPage.tsx+++ b/frontend/src/pages/HistoryPage.tsx@@ -23,6 +23,11 @@ import {IconTrash,} from '../components/ui/Icons'import { dialog } from '../lib/dialog'+import {+ downloadSingleVideo,+ triggerBlobDownload,+ zipVideosClient,+} from '../lib/clientDownload'import { isRunning, STATUS_CN, statusTone } from '../lib/status'type HistoryItem = Omit<Project, 'shots'>@@ -40,17 +45,6 @@ function canDownload(p: HistoryItem) {return p.status === 'DONE' && Boolean(p.final_video_url)}-function triggerBlobDownload(blob: Blob, filename: string) {- const url = URL.createObjectURL(blob)- const a = document.createElement('a')- a.href = url- a.download = filename- document.body.appendChild(a)- a.click()- a.remove()- URL.revokeObjectURL(url)-}-function statusBadgeClass(status: string) {const tone = statusTone(status)if (tone === 'ok') return 'ok'@@ -68,11 +62,16 @@ export default function HistoryPage() {const [loading, setLoading] = useState(true)const [busyId, setBusyId] = useState<number | null>(null)const [packing, setPacking] = useState(false)+ const [packProgress, setPackProgress] = useState('')const [selected, setSelected] = useState<Set<number>>(new Set())const [tab, setTab] = useState('全部')const [q, setQ] = useState('')const [page, setPage] = useState(1)- const [preview, setPreview] = useState<{ url: string; title: string } | null>(null)+ const [preview, setPreview] = useState<{+ url: string+ title: string+ projectId: number+ } | null>(null)const hasRunning = useMemo(() => items.some((p) => isRunning(p.status) && p.progress < 100),@@ -178,16 +177,60 @@ export default function HistoryPage() {}}+ async function downloadOne(p: HistoryItem) {+ if (!canDownload(p) || !p.final_video_url) return+ setBusyId(p.id)+ setError('')+ try {+ await downloadSingleVideo({+ url: api.assetUrl(p.final_video_url, p.updated_at),+ title: p.title,+ projectId: p.id,+ })+ } catch (err) {+ setError(err instanceof Error ? err.message : '下载失败')+ } finally {+ setBusyId(null)+ }+ }++ async function downloadPreview() {+ if (!preview) return+ setBusyId(preview.projectId)+ setError('')+ try {+ await downloadSingleVideo({+ url: preview.url,+ title: preview.title,+ projectId: preview.projectId,+ })+ } catch (err) {+ setError(err instanceof Error ? err.message : '下载失败')+ } finally {+ setBusyId(null)+ }+ }+async function packSelected() {if (!selectedDownloadable.length) returnsetPacking(true)+ setPackProgress(`0/${selectedDownloadable.length}`)+ setError('')try {- const { blob, filename } = await api.downloadZip(selectedDownloadable.map((p) => p.id))+ const { blob, filename } = await zipVideosClient(+ selectedDownloadable.map((p) => ({+ id: p.id,+ title: p.title,+ url: api.assetUrl(p.final_video_url!, p.updated_at),+ })),+ (done, total) => setPackProgress(`${done}/${total}`),+ )triggerBlobDownload(blob, filename)} catch (err) {setError(err instanceof Error ? err.message : '打包失败')} finally {setPacking(false)+ setPackProgress('')}}@@ -282,9 +325,11 @@ export default function HistoryPage() {onClick={packSelected}><IconDownload size={15} />- {packing ? '打包中…' : `打包下载 (${selectedDownloadable.length})`}+ {packing+ ? `打包中 ${packProgress}…`+ : `打包下载 (${selectedDownloadable.length})`}</button>- <span>可选中已完成项目批量下载</span>+ <span>勾选已完成项目后,浏览器依次下载并打成 ZIP(不经服务器)</span></div>{error ? <p className="pf-error">{error}</p> : null}@@ -356,12 +401,22 @@ export default function HistoryPage() {setPreview({url: api.assetUrl(p.final_video_url, p.updated_at),title: p.title,+ projectId: p.id,})}><IconEye size={14} />预览</button>+ <button+ type="button"+ className="pf-btn-text"+ disabled={!canDownload(p) || busyId === p.id || packing}+ onClick={() => downloadOne(p)}+ >+ <IconDownload size={14} />+ {busyId === p.id ? '下载中…' : '下载'}+ </button><button type="button" className="pf-btn-text" disabled title="即将推出"><IconCopy size={14} />复制@@ -489,11 +544,33 @@ export default function HistoryPage() {{preview ? (<div className="modal-backdrop" onClick={() => setPreview(null)}><div className="modal preview-modal" onClick={(e) => e.stopPropagation()}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ gap: '0.75rem',+ alignItems: 'center',+ }}+ ><h3 style={{ margin: 0 }}>{preview.title}</h3>- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={() => setPreview(null)}>- 关闭- </button>+ <div style={{ display: 'flex', gap: '0.4rem' }}>+ <button+ type="button"+ className="pf-btn pf-btn-ghost pf-btn-sm"+ disabled={busyId === preview.projectId}+ onClick={downloadPreview}+ >+ <IconDownload size={14} />+ {busyId === preview.projectId ? '下载中…' : '下载'}+ </button>+ <button+ type="button"+ className="pf-btn pf-btn-ghost pf-btn-sm"+ onClick={() => setPreview(null)}+ >+ 关闭+ </button>+ </div></div><video className="preview-media" src={preview.url} controls autoPlay /></div>