diff --git a/CHANGELOG.md b/CHANGELOG.md index 8042970..a3c672a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ --- +## 2026-11-17 + +### ✨ AI 一键出片:按标题和图片自动生成视频封面 + +- 新增 `generateQuickVideoCover()`(`src/utils/aiQuickVideo.ts`):根据用户输入的**标题 + 素材图片 + 正文**自动生成一张封面图 + - 提示词三级降级:视觉模型看图写英文生图提示词 → 纯文本模型按标题/正文写 → 标题拼模板提示词,保证封面永远能出 + - 生图两级降级:先试 16:9(1280x720),失败回退网关默认尺寸;再失败由调用方用本地 `makeTitleCover()` 标题封面兜底(界面明确提示「AI 生图失败,已用本地封面代替」) + - 远程生图链接自动转 data URL,避免工程保存后链接过期导致封面裂图;转不动则保持原地址 +- 向导流程改动(`QuickVideo.tsx`): + - 第 1 步「生成文案」时**文案与封面并行生成**(封面只依赖标题/图片/正文,不必等文案),loading 文案改为「正在识别图片写文案、生成封面…」 + - 第 4 步确认页新增封面预览行:缩略图 + 状态(AI 生成 / 本地标题封面 / 生成中 / 失败原因);「预计成片」与页脚「总长约」计入封面 3 秒 + - 「确认生成视频」在封面未就绪时拦截提示;封面插到**时间轴最前面 3 秒**(无配音无字幕,与后续画面同轨道,吃同样的转场/运镜设置) + - 收尾 Toast 带「封面 +」前缀;`resetAll` 清理封面状态 +- 样式:`quickvideo.module.less` 新增 `.coverRow/.coverThumb/.coverInfo`(132×74 缩略图 + 虚线分隔) +- 第 1 步说明文案同步提及「根据标题和图片自动生成视频封面(片头 3 秒)」 + +--- + ## 2026-11-14 ### 🛡️ MCP 每 IP 每日 5 次限流(防刷爆) diff --git a/README.md b/README.md index 8f9a3c2..3e3183b 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ | 开源入口 | 编辑器右上角新增「开源地址」按钮,一键直达源码仓库 gitee.com/jinghui111/unicut | | AI 面板瘦身 | 左侧「AI创作」移除「AI 视频生成 / AI 图片生成」页签,保留一键出片与生成结果;生图 / 生视频走 AI 助手对话 | | 首页去背书 | 移除首页「受到众多大品牌信赖」与 UCAP / 圆通 / 中国电信 / 中国移动 品牌 logo 背书区 | -| AI 一键出片 | 添加图片 → AI 生成口播文案 → 13 种人声配音试听 → 一键排入时间轴,转场 / 动效 / 字幕样式可调 | +| AI 一键出片 | 添加图片 → AI 生成口播文案 + 按标题和图片自动生成视频封面(片头 3 秒)→ 13 种人声配音试听 → 一键排入时间轴,转场 / 动效 / 字幕样式可调 | | 模板导入修复 | 修复"导入第一个模板后,再导入会把浏览器拖崩"的问题,支持连续换模板 | | 品牌与首页 | 产品名改为米剪,首页新增导航站 / 开源地址入口,移除收费栏目与账号类外链 | | 接入授权中心 | 版本号、公告、检查更新(授权中心不可达时静默降级,绝不拦功能) | diff --git a/data-quality/scripts/site/00_lint_dist.py b/data-quality/scripts/site/00_lint_dist.py index 336b058..05c77ed 100644 --- a/data-quality/scripts/site/00_lint_dist.py +++ b/data-quality/scripts/site/00_lint_dist.py @@ -135,6 +135,8 @@ def classify(url, relpath, allow_rules): return 'doc', '文档里写的本机示例地址,不会发起请求' return 'local', '本机地址(残留的开发期配置)' if re.match(r'^(192\.168\.\d+|10\.\d+|172\.(1[6-9]|2\d|3[01])|169\.254)\.\d+$', host): + if ext in DOC_EXT: + return 'doc', '文档里写的内网示例地址,不会发起请求' return 'lan', '内网地址,仍会发起网络请求' if ext in DOC_EXT: return 'doc', '文档/Source Map 文件' diff --git a/data-quality/scripts/site/external_ref_allowlist.txt b/data-quality/scripts/site/external_ref_allowlist.txt index e513278..af5a5eb 100644 --- a/data-quality/scripts/site/external_ref_allowlist.txt +++ b/data-quality/scripts/site/external_ref_allowlist.txt @@ -16,6 +16,7 @@ ^http://\$$ allow pdf.worker 模板字面量 http://${A} 的提取截断产物,仅 new URL() 构造不发起请求 ^https://ai\.88531\.cn(/.*)?$ allow 自有域名:官方 AI 网关默认接口地址与「获取 Key」引导链接(产品默认配置本体,删掉功能即失效;断网时静默降级不拦功能) ^https://nav\.88531\.cn(/.*)?$ allow 自有域名:首页导航站入口链接(纯跳转,断网时点击打不开但不影响编辑器功能) +^https://doc\.88531\.cn(/.*)?$ allow 自有域名:素材下载文档站入口链接(window.open 纯跳转,断网时点击打不开但不影响编辑器功能) github\.com allow vendored 依赖(pixi/semi/opencv 等)压缩产物里的项目主页与许可证链接,仅字符串 gist\.github\.com allow vendored 依赖 README 片段里的示例链接,仅字符串 raw\.githubusercontent\.com allow vendored 依赖 README 片段里的源码链接,仅字符串 diff --git a/public/articles/about.md b/public/articles/about.md index 5af9982..7ae2b58 100644 --- a/public/articles/about.md +++ b/public/articles/about.md @@ -70,7 +70,9 @@ - **标题**(最多 30 字,例:三步搞定一张海报)——它决定文案的主题方向,别留空 - **文案风格**五选一:口播解说(自然口语)/ 教程讲解(步骤清晰)/ 种草安利(卖点前置)/ 情感旁白(文艺留白)/ 新闻播报(客观密度高) -底部实时显示「素材池 N/8 张图片 · 正文 X 字」。素材齐了点右下角主按钮——按钮文案随方式变化:**「① 识别图片 · 生成文案」/「① 读取文档 · 生成文案」/「① 分析网页 · 生成文案」**。没选素材就点,会提示「请先添加图片」/「请先上传 Word / PDF 文档」/「请先抓取网址内容」。 +底部实时显示「素材池 N/8 张图片 · 正文 X 字」。素材齐了点右下角主按钮——按钮文案随方式变化:**「① 识别图片 · 生成文案」/「① 读取文档 · 生成文案」/「① 分析网页 · 生成文案」**(生成时按钮会变成「正在识别图片写文案、生成封面…」,文案和封面是并行生成的)。没选素材就点,会提示「请先添加图片」/「请先上传 Word / PDF 文档」/「请先抓取网址内容」。 + +点下去之后 AI 会做两件事:按素材写口播文案,同时**根据你输入的标题和图片自动生成一张视频封面**(片头 3 秒,确认页可预览;生图失败会自动换成本地标题封面兜底)。 ![一键出片第 1 步 素材与标题](/articles/images/shot-wizard1.png) *图:第 1 步:选素材类型、上传图片、填标题、挑文案风格* @@ -122,7 +124,8 @@ 下方信息栏逐项汇总你要生成的东西: -- 图片 N 张 · 口播 M 段 · **预计成片 X 秒** +- **视频封面**:缩略图 + 状态(「AI 按标题和图片生成」/「本地标题封面」;还在生成时显示转圈「AI 正在根据标题和图片生成封面…」) +- 图片 N 张 · 口播 M 段 · **预计成片 X 秒**(已含封面 3 秒) - 转场 / 动效选择 · 共 N-1 个转场 - 字幕位置 · 大小 · 配色 · 入场 - 人声 · 情绪 · 语速 @@ -130,9 +133,9 @@ ⚠ **注意红字提示:「生成字幕会覆盖当前工程已有的字幕。」**——如果你在时间轴上已有手动字幕,先想清楚再继续(建议新工程做一键出片)。 -确认无误点 **「③ 确认生成视频(总长约 X 秒)」**(某段配音没就绪时按钮灰色)。成功提示: +确认无误点 **「③ 确认生成视频(总长约 X 秒)」**(某段配音没就绪、或封面还在生成时按钮会拦截提示)。成功提示: -> 已生成 N 段:图片(带动效)、配音、字幕已就位,X 个转场 +> 封面 + 已生成 N 段:图片(带动效)、配音、字幕已就位,X 个转场 弹窗自动关闭。失败时显示「生成失败:原因」,按提示处理后重来。 @@ -144,6 +147,7 @@ 回到时间轴,你会看到: - **图片**按顺序排在同一条轨道(转场要求同轨道相邻,别挪散) +- **视频封面**在最前面单独 3 秒(AI 按标题和图片生成,无配音无字幕) - **配音**在另一条独立轨道,与图片错开避免撞车 - **字幕**已按段生成 - 图片带运镜动效(推近 / 拉远 / 平移的关键帧) @@ -176,7 +180,10 @@ **7. 传的纯文档没有一张图怎么办?** 不用管:无配图时自动生成一张标题封面兜底,时间轴一定有画面;想要更好效果就在第 1 步补传图片。 -**8. 生成的文案太书面 / 太长?** +**8. 封面是 AI 生成的吗?能换吗?** +封面根据你输入的标题和素材图片自动生成,放在片头 3 秒。如果提示「AI 生图失败,已用本地封面代替」,一般是 Key 额度或网关生图接口的问题——回第 1 步重新点生成即可重试。 + +**9. 生成的文案太书面 / 太长?** 第 2 步整段随便改,或回第 1 步换「文案风格」重新生成;段落之间换图、删段都很方便。 ## 十、相关链接 diff --git a/scripts/e2e_quickvideo_cover.py b/scripts/e2e_quickvideo_cover.py new file mode 100644 index 0000000..067b81b --- /dev/null +++ b/scripts/e2e_quickvideo_cover.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""AI 一键出片「自动封面」端到端:mock 掉对话/生图网关(无需真实 Key), +真实跑完向导 4 步,断言: + 1. 确认页出现封面预览行且状态为「AI 按标题和图片生成」 + 2. 生成后时间轴第一个元素是「视频封面」图片、时长 3 秒、在片头 + 3. 字幕从封面之后才开始(第一条字幕 BeginTime >= 3000ms) + +用法:python3 scripts/e2e_quickvideo_cover.py +""" +import sys, time, json, base64 +from playwright.sync_api import sync_playwright + +BASE = "https://127.0.0.1:3005" +APPID = "qv_cover_%d" % int(time.time()) +STAMP = time.strftime("%H:%M:%S") + + +def log(msg): + print("[%s] %s" % (STAMP, msg), flush=True) + + +GUARD = """async () => { + try { + const root = await navigator.storage.getDirectory(); + const db = await new Promise((res, rej) => { + const rq = indexedDB.open('H5VideoLocalDB'); + rq.onupgradeneeded = () => rq.result.createObjectStore('folderHandles'); + rq.onsuccess = () => res(rq.result); + rq.onerror = () => rej(rq.error); + }); + const done = await new Promise((res, rej) => { + const tx = db.transaction('folderHandles', 'readwrite'); + const st = tx.objectStore('folderHandles'); + const rec = { id: 'root', handle: root }; + if (st.keyPath) st.put(rec); else st.put(rec, 'root'); + tx.oncomplete = () => res(true); + tx.onerror = () => rej(tx.error); + }); + db.close(); + return done; + } catch (e) { return String(e); } +}""" + +# 1280x720 纯色 PNG(mock 生图返回 b64_json) +def make_cover_png_b64(): + from PIL import Image + import io + im = Image.new("RGB", (1280, 720), (30, 90, 200)) + buf = io.BytesIO() + im.save(buf, format="PNG") + return base64.b64encode(buf.getvalue()).decode() + + +COPY_JSON = json.dumps({ + "segments": [ + {"text": "第一段测试口播内容,介绍这张封面", "image": 1}, + {"text": "第二段测试口播内容继续讲下去", "image": 2}, + {"text": "第三段测试口播内容收尾总结一下", "image": 3}, + ] +}, ensure_ascii=False) +COVER_PROMPT = "A striking tech product cover, blue gradient, cinematic light, no text" + + +def install_mock(page, cover_b64): + """对话/生图网关全部本地 mock:按请求内容区分文案请求与封面提示词请求""" + def handler(route): + req = route.request + url = req.url + if req.method == "OPTIONS": + return route.fulfill(status=204, headers={ + "access-control-allow-origin": "*", + "access-control-allow-methods": "POST, OPTIONS", + "access-control-allow-headers": "content-type, authorization", + }) + body = req.post_data or "" + headers = {"access-control-allow-origin": "*", "content-type": "application/json"} + if "chat/completions" in url: + # 封面提示词请求的 prompt 里有「做一张封面图」,文案请求有「只输出 JSON」 + if "做一张封面图" in body: + content = COVER_PROMPT + else: + content = COPY_JSON + payload = json.dumps({"choices": [{"message": {"content": content}}]}) + return route.fulfill(status=200, headers=headers, body=payload) + if "images/generations" in url: + payload = json.dumps({"data": [{"b64_json": cover_b64}]}) + return route.fulfill(status=200, headers=headers, body=payload) + return route.fulfill(status=404, headers=headers, body="{}") + + page.route("**/v1/chat/completions", handler) + page.route("**/v1/images/generations", handler) + + +def js_click(page, expr, desc): + ok = page.evaluate("() => { const e = %s; if (e) { e.click(); return true; } return false; }" % expr) + log("点 %s: %s" % (desc, ok)) + return ok + + +def wait_text(page, text, seconds=120, label=""): + for _ in range(seconds): + page.wait_for_timeout(1000) + if page.evaluate("() => document.body.innerText.includes(%s)" % json.dumps(text)): + log("到位[%s]: %s" % (label, text)) + return True + log("等待超时[%s]: %s" % (label, text)) + return False + + +def make_images(): + from PIL import Image, ImageDraw + out = [] + for i, color in enumerate([(200, 60, 60), (60, 140, 200), (80, 170, 90)], 1): + p = "/tmp/qvc_img%d.png" % i + im = Image.new("RGB", (960, 720), color) + d = ImageDraw.Draw(im) + d.text((40, 40), "COVER TEST %d" % i, fill=(255, 255, 255)) + im.save(p) + out.append(p) + return out + + +def main(): + imgs = make_images() + cover_b64 = make_cover_png_b64() + log("测试图片: %s" % imgs) + with sync_playwright() as p: + browser = p.chromium.launch( + executable_path="/usr/bin/chromium", + headless=True, + args=["--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", "--mute-audio", + "--autoplay-policy=no-user-gesture-required"], + ) + ctx = browser.new_context(ignore_https_errors=True) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.on("console", lambda m: errors.append("console:" + m.text[:200]) if m.type == "error" else None) + page.on("console", lambda m: log("页面日志 %s" % m.text[:220]) if "[qv]" in m.text else None) + + # 预置 AI 配置(Key 是假的,所有请求都被 route mock 掉) + page.add_init_script(""" + localStorage.setItem('micut.ai.config.v1', JSON.stringify({ + baseUrl: 'https://ai.88531.cn/v1', + apiKey: 'e2e-mock-key', + model: 'mock-model', + })); + """) + install_mock(page, cover_b64) + + log("打开工程 %s" % APPID) + page.goto("%s/editor/%s" % (BASE, APPID), wait_until="domcontentloaded", timeout=120000) + page.wait_for_timeout(4000) + log("守卫: %s" % page.evaluate(GUARD)) + page.reload(wait_until="domcontentloaded") + page.wait_for_selector("#h5dsCanvas", timeout=90000) + try: + page.wait_for_function("() => document.body.innerText.includes('AI创作')", timeout=90000) + log("侧栏已就绪") + except Exception as e: + log("侧栏等待超时: %s" % e) + page.wait_for_timeout(3000) + + js_click(page, """(() => { + const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + let n; + while (n = w.nextNode()) { + const t = (n.textContent || '').trim(); + if (t === 'AI创作' && n.parentElement) return n.parentElement; + } + return null; + })()""", "AI创作") + page.wait_for_timeout(2500) + js_click(page, "[...document.querySelectorAll('button')].find(x => (x.innerText||'').includes('一键出片'))", + "开始一键出片") + page.wait_for_timeout(3000) + + # 步骤1:3 张图 + 标题 + fi = page.query_selector("div.semi-modal input[type=file]") + if not fi: + fi = page.query_selector("input[type=file][accept='image/*']") + if not fi: + log("ERROR: 找不到向导的图片输入框") + print(json.dumps({"ok": False, "why": "no-file-input"}, ensure_ascii=False)) + return 1 + fi.set_input_files(imgs) + page.wait_for_timeout(2500) + page.fill("input[placeholder*='三步搞定']", "封面功能端到端验证") + page.wait_for_timeout(500) + + js_click(page, "[...document.querySelectorAll('button')].find(x=>(x.innerText||'').includes('① 识别图片'))", "生成文案") + got = wait_text(page, "下一步:配置声音", 180, "第2步") + log("文案生成完成: %s" % got) + if not got: + print(json.dumps({"ok": False, "why": "copy-timeout", "errors": errors[-6:]}, ensure_ascii=False)) + return 1 + + js_click(page, "[...document.querySelectorAll('button')].find(x=>(x.innerText||'').includes('下一步:配置声音'))", "下一步") + page.wait_for_timeout(2000) + + # 步骤3:合成全部配音(真实 edge-tts) + js_click(page, "[...document.querySelectorAll('button')].find(x=>(x.innerText||'').includes('合成全部配音'))", "合成全部配音") + done = wait_text(page, "图片转场", 300, "第4步效果面板") + log("配音合成完成: %s" % done) + if not done: + print(json.dumps({"ok": False, "why": "synth-timeout", "errors": errors[-6:]}, ensure_ascii=False)) + return 1 + page.wait_for_timeout(1500) + + # 断言 1:确认页封面预览行 + body = page.inner_text(".semi-modal-body") + has_cover_row = ("视频封面" in body) and ("AI 按标题和图片生成" in body) + has_cover_thumb = page.evaluate("""() => { + const img = [...document.querySelectorAll('.semi-modal img')].find(i => (i.alt||'') === '视频封面'); + return !!(img && img.src && img.src.startsWith('data:image/png')); + }""") + has_total = "预计成片" in body + log("确认页封面行: %s, 缩略图 dataURL: %s" % (has_cover_row, has_cover_thumb)) + page.screenshot(path="/tmp/qvc_step4.png", full_page=False) + + # 生成 + js_click(page, "[...document.querySelectorAll('button')].find(x=>(x.innerText||'').includes('③ 确认生成视频'))", "确认生成视频") + page.wait_for_timeout(12000) + + # 断言 2/3:时间轴数据 + res = page.evaluate("""() => { + const ed = window.__editor && window.__editor.movie; + if (!ed) return {err:'no-editor'}; + const d = ed.data || {}; + const els = (d.elements || []).slice().sort((a,b) => (a.startTime||0) - (b.startTime||0)); + const imgs = els.filter(e => e.type === 'image'); + const caps = d.captions || []; + const f = els[0] || null; + // 元素本身不存 url,资源经 resourceManage.getResouceById(resourceId) 取 + let resUrl = ''; + const rid = f && f.resourceId; + if (rid) { + const mgr = window.__editor.movie.resourceManage; + try { + const r = mgr && mgr.getResouceById && mgr.getResouceById(rid); + if (r) resUrl = r.url || (r.urls && r.urls.url) || ''; + } catch (e) { resUrl = 'ERR:' + e; } + } + return { + first: f, + coverResourceUrl: resUrl.slice(0, 40), + imgCount: imgs.length, + elements: els.map(e => ({ name: e.name, type: e.type, t: e.startTime, d: e.duration })), + captionCount: caps.length, + caption0: caps[0] ? JSON.parse(JSON.stringify(caps[0])) : null, + canvas: { w: d.width, h: d.height }, + }; + }""") + log("工程数据: " + json.dumps(res, ensure_ascii=False)[:2000]) + + f = res.get("first") or {} + cap0 = res.get("caption0") or {} + # 字幕在元素数据里以秒存 startTime(addCaptions 的 BeginTime 输入被 SDK 归一化) + cap_begin = cap0.get("startTime", cap0.get("BeginTime", cap0.get("beginTime"))) + url = res.get("coverResourceUrl") or ((f.get("urls") or {}).get("url") or f.get("url") or "") + checks = { + "cover_row_on_step4": has_cover_row, + "cover_thumb_dataurl": has_cover_thumb, + "first_is_cover": f.get("name") == "视频封面" and f.get("type") == "image", + "cover_at_head": (f.get("startTime") is not None) and abs(float(f.get("startTime"))) < 0.01, + "cover_dur_3": abs(float(f.get("duration") or 0) - 3) < 0.01, + "cover_has_url": bool(url), + "cover_url_is_dataurl": str(url).startswith("data:image"), + # 字幕从封面结束(第 3 秒)起接续 + "caption_after_cover": (cap_begin or 0) >= 3, + "caption_count_3": res.get("captionCount") == 3, + } + log("原始首元素: " + json.dumps({k: v for k, v in f.items() if k in ('name','type','startTime','duration','urls','url','trackIndex')}, ensure_ascii=False)[:800]) + log("原始字幕0: " + json.dumps(cap0, ensure_ascii=False)[:400]) + log("断言: " + json.dumps(checks, ensure_ascii=False)) + log("JS 错误: %s" % (errors[-5:] if errors else "无")) + + # 播一下确认渲染 + page.evaluate("""() => { + const m = window.__editor && window.__editor.movie; + if (m && m.pause) m.pause(); + const st = window.__editor; + if (st && st.updateMovie) st.updateMovie(1.0); + }""") + page.wait_for_timeout(2500) + page.screenshot(path="/tmp/qvc_playing.png", full_page=False) + log("截图: /tmp/qvc_step4.png /tmp/qvc_playing.png") + + # 刷新确认封面持久化 + saved = page.evaluate("""() => { + const s = window.__editor; + if (typeof s.saveApp === 'function') { s.saveApp(() => {}); return 'saveApp 已调用'; } + return '没有 saveApp'; + }""") + log("手动保存: %s" % saved) + page.wait_for_timeout(8000) + page.reload(wait_until="domcontentloaded") + page.wait_for_selector("#h5dsCanvas", timeout=90000) + page.wait_for_timeout(12000) + after = page.evaluate("""() => { + const d = (window.__editor && window.__editor.movie && window.__editor.movie.data) || {}; + const els = (d.elements || []).slice().sort((a,b) => (a.startTime||0) - (b.startTime||0)); + const f = els[0] || {}; + return { firstName: f.name, firstT: f.startTime, firstD: f.duration, + els: els.length, caps: (d.captions||[]).length }; + }""") + log("刷新后: " + json.dumps(after, ensure_ascii=False)) + checks["cover_persist_after_reload"] = ( + after.get("firstName") == "视频封面" + and after.get("firstT") is not None and abs(float(after.get("firstT"))) < 0.01 + ) + + ok = all(checks.values()) + print(json.dumps({"ok": ok, "checks": checks, "errors": errors[-5:]}, ensure_ascii=False)) + browser.close() + return 0 if ok else 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/pages/editor/components/sources/ai/QuickVideo.tsx b/src/pages/editor/components/sources/ai/QuickVideo.tsx index aad6393..13e1d1d 100644 --- a/src/pages/editor/components/sources/ai/QuickVideo.tsx +++ b/src/pages/editor/components/sources/ai/QuickVideo.tsx @@ -24,8 +24,10 @@ import { EMOTIONS, VoiceOption, QvSegment, + QvCover, fetchTtsVoices, generateQuickVideoCopy, + generateQuickVideoCover, synthesizeSegment, decodeAudio, } from '@utils/aiQuickVideo'; @@ -62,11 +64,13 @@ const GEN_LABEL: Record = { url: '① 分析网页 · 生成文案', }; const GEN_LOADING: Record = { - image: '正在识别图片写文案…', - doc: '正在读取文档写文案…', - url: '正在分析网页写文案…', + image: '正在识别图片写文案、生成封面…', + doc: '正在读取文档写文案、生成封面…', + url: '正在分析网页写文案、生成封面…', }; const MAX_IMAGES = 8; +/** 视频封面在片头占的时长(秒) */ +const COVER_DUR = 3; const { Option } = Select; @@ -342,6 +346,11 @@ export default function QuickVideo({ const [segs, setSegs] = useState([]); const [genLoading, setGenLoading] = useState(false); + /* AI 封面:第 1 步与文案并行生成,第 4 步预览,确认时插到片头 */ + const [cover, setCover] = useState(null); + const [coverErr, setCoverErr] = useState(null); + const [coverLoading, setCoverLoading] = useState(false); + const [voices, setVoices] = useState([]); const [voice, setVoice] = useState('zh-CN-XiaoxiaoNeural'); const [rate, setRate] = useState(0); @@ -519,6 +528,17 @@ export default function QuickVideo({ } if (!title.trim()) return Toast.warning('请填写标题'); setGenLoading(true); + setCover(null); + setCoverErr(null); + // 文案与封面并行生成:封面只依赖标题/图片/正文,不必等文案出结果 + setCoverLoading(true); + const coverTask = generateQuickVideoCover({ + title: title.trim(), + images: images.map(i => i.url), + sourceText: bodyText || undefined, + }) + .then(r => r) + .catch((e): [null, string] => [null, e?.message || String(e)]); const [res, err] = await generateQuickVideoCopy({ title: title.trim(), style, @@ -526,17 +546,34 @@ export default function QuickVideo({ sourceText: bodyText || undefined, }); setGenLoading(false); - if (err || !res) return Toast.error(err || '文案生成失败'); + if (err || !res) { + // 文案失败也要把封面任务收掉,避免悬挂的 loading + const [cv, cerr] = await coverTask; + setCoverLoading(false); + return Toast.error(err || '文案生成失败'); + } // 纯文档 / 纯文字素材没有配图时,自动生成一张标题封面,保证时间轴有画面可用 if (!images.length) { - const cover = makeTitleCover(title.trim()); - setImages([{ id: util.randomID(), url: cover.url, name: '标题封面', w: cover.w, h: cover.h }]); + const cover0 = makeTitleCover(title.trim()); + setImages([{ id: util.randomID(), url: cover0.url, name: '标题封面', w: cover0.w, h: cover0.h }]); } const list = res.segments.map(s => newSeg(s.text, s.image)); setSegs(list); setAudio({}); setStep(1); Toast.success(`已生成 ${list.length} 段文案`); + // 封面还没好就继续等(生图通常几秒到几十秒),失败则用本地标题封面兜底 + const [cv, cerr] = await coverTask; + setCoverLoading(false); + if (cv) { + setCover(cv); + Toast.success(cv.local ? '封面已生成(本地标题封面)' : 'AI 封面已生成'); + } else { + const fb = makeTitleCover(title.trim()); + setCover({ url: fb.url, w: fb.w, h: fb.h, local: true }); + setCoverErr(cerr || 'AI 生图失败'); + Toast.warning(`AI 封面生成失败,已用本地标题封面代替:${cerr || ''}`); + } }; const editSegText = (uid: string, text: string) => @@ -619,6 +656,7 @@ export default function QuickVideo({ const build = async () => { const { editor } = stores; if (!editor.data) return Toast.error('没有打开的视频项目'); + if (coverLoading) return Toast.warning('封面还在生成中,稍等几秒再确认'); const missing = segs.filter(s => !audio[s.uid]?.url); if (missing.length) return Toast.warning(`还有 ${missing.length} 段没有配音,请先合成`); @@ -637,6 +675,29 @@ export default function QuickVideo({ let imgTrack: number | undefined; const captions: any[] = []; + // 片头封面:AI 按标题/图片生成的封面图放最前面 3 秒(无配音无字幕) + if (cover) { + const coverItem: any = { + id: util.randomID(), + name: '视频封面', + convert_status: -1, + app_id: editor.appid, + type: 'image', + urls: { url: cover.url }, + attrs: { duration: COVER_DUR, naturalWidth: cover.w, naturalHeight: cover.h }, + }; + const cEl: any = await addImageVideoAudioItem(coverItem, t, undefined, true); + if (cEl) { + cEl.startTime = t; + cEl.duration = COVER_DUR; + if (editor.checkTrackElementOverlap(cEl.trackIndex)) cEl.trackIndex += 0.5; + imgTrack = cEl.trackIndex; + // 封面也吃运镜设置,避免与后面画面风格不一致 + applyImageMotion(cEl, COVER_DUR, -1, fxMotion); + } + t = Number((t + COVER_DUR).toFixed(2)); + } + for (let i = 0; i < segs.length; i++) { const seg = segs[i]; const track = audio[seg.uid]; @@ -710,7 +771,8 @@ export default function QuickVideo({ const transCount = fxTrans === 'none' ? 0 : Math.max(0, segs.length - 1); Toast.success( - `已生成 ${segs.length} 段:图片${fxMotion === 'none' ? '' : '(带动效)'}、配音、字幕已就位` + + (cover ? '封面 + ' : '') + + `已生成 ${segs.length} 段:图片${fxMotion === 'none' ? '' : '(带动效)'}、配音、字幕已就位` + (transCount ? `,${transCount} 个转场` : ''), ); onClose(); @@ -732,6 +794,9 @@ export default function QuickVideo({ setAudio({}); setTitle(''); setImages([]); + setCover(null); + setCoverErr(null); + setCoverLoading(false); setRate(0); setEmotion('calm'); }; @@ -822,7 +887,7 @@ export default function QuickVideo({ <>
素材三选一:上传图片,或上传 Word / PDF 文档,或输入网址自动抓取正文和配图 —— - AI 看懂素材后写口播文案,再生成字幕和配音。 + AI 看懂素材后写口播文案,并根据标题和图片自动生成一张视频封面(片头 3 秒),再生成字幕和配音。
+
+ 视频封面 +
+
+ {coverLoading ? ( + <> + AI 正在根据标题和图片生成封面… + + ) : cover ? ( + <> + 视频封面 · 片头 {COVER_DUR} 秒 ·{' '} + {cover.local ? '本地标题封面' : 'AI 按标题和图片生成'} + + ) : ( + '未生成封面' + )} +
+ {coverErr && !coverLoading && ( +
AI 生图失败({coverErr}),已用本地封面代替
+ )} +
+
图片 {images.length} 张 · 口播 {segs.length} 段 · - 预计成片 {totalDur.toFixed(1)} 秒 + 预计成片 {(totalDur + (cover ? COVER_DUR : 0)).toFixed(1)} 秒
转场 {TRANS_OPTIONS.find(o => o.value === fxTrans)?.label} · 动效{' '} @@ -1248,7 +1335,7 @@ export default function QuickVideo({ `素材池 ${images.length}/${MAX_IMAGES} 张图片${src?.text ? ` · 正文 ${src.text.length} 字` : ''}`} {step === 1 && `${segs.length} 段文案`} {step === 2 && `已配音 ${freshCount}/${segs.length} 段`} - {step === 3 && `总长约 ${totalDur.toFixed(1)} 秒`} + {step === 3 && `总长约 ${(totalDur + (cover ? COVER_DUR : 0)).toFixed(1)} 秒`}
diff --git a/src/pages/editor/components/sources/ai/quickvideo.module.less b/src/pages/editor/components/sources/ai/quickvideo.module.less index 888c72b..ca09031 100644 --- a/src/pages/editor/components/sources/ai/quickvideo.module.less +++ b/src/pages/editor/components/sources/ai/quickvideo.module.less @@ -169,6 +169,33 @@ line-height: 2; } +/* AI 封面预览(确认生成页) */ +.coverRow { + display: flex; + align-items: center; + gap: 12px; + padding-bottom: 8px; + margin-bottom: 4px; + border-bottom: 1px dashed rgba(255, 255, 255, 0.35); +} + +.coverThumb { + width: 132px; + height: 74px; + object-fit: cover; + border-radius: 6px; + border: 1px solid #fff; + background: rgba(255, 255, 255, 0.06); + flex: 0 0 auto; +} + +.coverInfo { + font-size: 13px; + color: #fff; + line-height: 1.7; + min-width: 0; +} + .footer { display: flex; justify-content: space-between; diff --git a/src/utils/aiQuickVideo.ts b/src/utils/aiQuickVideo.ts index b4b45ee..7fcd91c 100644 --- a/src/utils/aiQuickVideo.ts +++ b/src/utils/aiQuickVideo.ts @@ -4,7 +4,7 @@ * - 文案:用户在「AI 设置」填的对话模型(带图时直接用该模型,需其支持图片输入) * - 配音:本机 unicut-tts(edge-tts),走同源 /localtts 反代,无需登录、无需密钥 */ -import { aiVisionAvailable, localChatCompletion } from '@utils/localAi'; +import { aiVisionAvailable, localChatCompletion, localGenerateImage } from '@utils/localAi'; /** 一段口播 = 一句文案 + 对应第几张图(1 基) */ export interface QvSegment { @@ -205,6 +205,127 @@ export async function generateQuickVideoCopy(params: { return [{ title: params.title, segments }, null]; } +/** 封面图:AI 根据标题 + 素材(图片/正文)写提示词再文生图 */ +export interface QvCover { + url: string; + w: number; + h: number; + /** true = 本地标题封面兜底(AI 生图失败时),false = AI 生成 */ + local?: boolean; +} + +/** 量图片真实尺寸(加载失败抛错,调用方兜底) */ +function measureImage(url: string): Promise<{ w: number; h: number }> { + return new Promise((resolve, reject) => { + const img = new Image(); + const timer = setTimeout(() => reject(new Error('封面图片加载超时')), 15000); + img.onload = () => { + clearTimeout(timer); + resolve({ w: img.naturalWidth || 1280, h: img.naturalHeight || 720 }); + }; + img.onerror = () => { + clearTimeout(timer); + reject(new Error('封面图片加载失败')); + }; + img.src = url; + }); +} + +/** 远程图片尽量转 data URL,避免工程保存后生图链接过期导致封面裂图;失败保持原地址 */ +async function toDataUrl(url: string): Promise { + if (!url || url.startsWith('data:')) return url; + try { + const res = await fetch(url); + if (!res.ok) return url; + const blob = await res.blob(); + if (!blob.size || blob.size > 8 * 1024 * 1024) return url; + return await new Promise((resolve, reject) => { + const fr = new FileReader(); + fr.onload = () => resolve(String(fr.result)); + fr.onerror = () => reject(new Error('read fail')); + fr.readAsDataURL(blob); + }); + } catch (e) { + return url; + } +} + +/** + * 生成视频封面(根据标题和素材图片,AI 自动生成一张封面图) + * + * 三级降级,保证封面永远能出: + * 1. 视觉模型看图 + 标题/正文 → 输出英文生图提示词 + * 2. 纯文本模型(按标题/正文)→ 输出提示词 + * 3. 都失败 → 用标题拼一条模板提示词 + * 生图也降级:先试 16:9(1280x720),失败回退网关默认尺寸;再失败返回 null, + * 由调用方用本地 makeTitleCover 兜底。 + */ +export async function generateQuickVideoCover(params: { + title: string; + images: string[]; + sourceText?: string; +}): Promise<[QvCover | null, string | null]> { + const title = (params.title || '').trim() || '我的短视频'; + const images = params.images || []; + const sourceText = (params.sourceText || '').trim(); + + const askPrompt = async (withImages: boolean): Promise => { + const lines = [ + `我要给短视频《${title}》做一张封面图。`, + sourceText ? `素材正文开头:${sourceText.slice(0, 400)}` : '', + '请输出一条给文生图模型的英文提示词(一句话):描述封面画面的主体、构图、风格与色调,要贴合标题和素材内容,画面有吸引力;', + '画面里不要出现任何文字、字母、数字、水印、logo。', + '只输出提示词本身,不要引号、不要解释、不要换行。', + ].filter(Boolean); + const content: any[] = [{ type: 'text', text: lines.join('\n') }]; + if (withImages) { + for (const img of images.slice(0, 4)) { + try { + content.push({ type: 'image_url', image_url: { url: await shrinkImageForVision(img, 640) } }); + } catch (e) { + // 单张图压缩失败不影响其余 + } + } + } + const [r, e] = await localChatCompletion({ + messages: [{ role: 'user', content }], + }); + if (e || !r) throw new Error(e || '提示词生成失败'); + const raw = r?.choices?.[0]?.message?.content; + const text = String(typeof raw === 'string' ? raw : raw?.content || '').trim(); + if (!text) throw new Error('模型没有返回提示词'); + return text.replace(/^["'「]+|["'」]+$/g, '').slice(0, 600); + }; + + let prompt = ''; + try { + prompt = await askPrompt(images.length > 0 && (await aiVisionAvailable())); + } catch (e1) { + try { + prompt = await askPrompt(false); + } catch (e2) { + prompt = `A striking short video cover about "${title}", clean composition, vibrant colors, cinematic lighting, no text`; + console.warn('[qv] 封面提示词三级降级到模板:', e1, e2); + } + } + + let [img, err] = await localGenerateImage({ prompt, size: '1280x720' }); + if (err || !img) { + console.warn('[qv] 封面 16:9 生图失败,回退默认尺寸:', err); + [img, err] = await localGenerateImage({ prompt }); + } + if (err || !img) return [null, err || '封面生成失败']; + + try { + const url = await toDataUrl(img.url); + const dim = await measureImage(url); + return [{ url, w: dim.w, h: dim.h }, null]; + } catch (e: any) { + // 尺寸量不到也照样能插时间轴(用 16:9 默认值) + return [{ url: img.url, w: 1280, h: 720 }, null]; + } +} + /** * 合成一段配音,返回可直接用于