/** * AI 一键出片:看图写文案 + 本机配音 * * - 文案:用户在「AI 设置」填的对话模型(带图时直接用该模型,需其支持图片输入) * - 配音:本机 unicut-tts(edge-tts),走同源 /localtts 反代,无需登录、无需密钥 */ import { aiVisionAvailable, localChatCompletion } from '@utils/localAi'; /** 一段口播 = 一句文案 + 对应第几张图(1 基) */ export interface QvSegment { text: string; image: number; } /** edge-tts 中文音色的人声标签 */ export const VOICE_LABELS: Record = { 'zh-CN-XiaoxiaoNeural': '晓晓 · 亲切女声', 'zh-CN-XiaoyiNeural': '晓伊 · 温柔女声', 'zh-CN-YunxiNeural': '云希 · 阳光男声', 'zh-CN-YunjianNeural': '云健 · 磁性男声', 'zh-CN-YunyangNeural': '云扬 · 新闻男声', 'zh-CN-YunxiaNeural': '云夏 · 少年男声', 'zh-CN-XiaoshuangNeural': '晓双 · 童声', 'zh-CN-liaoning-XiaobeiNeural': '晓北 · 东北女声', 'zh-CN-shaanxi-XiaoniNeural': '晓妮 · 陕西女声', 'zh-TW-HsiaoChenNeural': '晓臻 · 台湾女声', 'zh-TW-YunJheNeural': '云哲 · 台湾男声', 'zh-HK-HiuGaaiNeural': '晓佳 · 粤语女声', 'zh-HK-WanLungNeural': '云龙 · 粤语男声', }; export interface VoiceOption { id: string; label: string; gender: string; } /** 拉取本机音色列表(失败时兜底为固定常用音色) */ export async function fetchTtsVoices(): Promise { const fallbackIds = Object.keys(VOICE_LABELS); try { const res = await fetch('/localtts/voices'); const data = await res.json(); const list: any[] = data?.voices || []; if (list.length) { return list.map(v => ({ id: v.id, label: VOICE_LABELS[v.id] || v.id, gender: v.gender || '', })); } } catch (e) { console.warn('[qv] 拉取音色失败,使用兜底列表', e); } return fallbackIds.map(id => ({ id, label: VOICE_LABELS[id], gender: '' })); } /** 文案风格(影响提示词里对语气、结构的要求) */ export const COPY_STYLES = [ { value: '口播解说', desc: '自然口语,像跟朋友说话' }, { value: '教程讲解', desc: '步骤清晰,有“第一步”这类结构词' }, { value: '种草安利', desc: '有情绪、有画面感,卖点前置' }, { value: '情感旁白', desc: '短句、留白、文艺一点' }, { value: '新闻播报', desc: '客观、信息密度高' }, ]; /** 情绪(对应 unicut-tts 的 emotion,会微调语速与音调) */ export const EMOTIONS = [ { value: 'calm', label: '平和' }, { value: 'gentle', label: '温柔' }, { value: 'happy', label: '愉快' }, { value: 'excited', label: '兴奋' }, { value: 'serious', label: '严肃' }, { value: 'sad', label: '伤感' }, ]; /** 压缩图片给视觉模型看(控制上下文体积) */ export function shrinkImageForVision(dataUrl: string, max = 768): Promise { return new Promise(resolve => { try { const img = new Image(); img.onload = () => { const scale = Math.min(1, max / Math.max(img.width, img.height)); if (scale >= 1) return resolve(dataUrl); const w = Math.max(1, Math.round(img.width * scale)); const h = Math.max(1, Math.round(img.height * scale)); const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); if (!ctx) return resolve(dataUrl); ctx.drawImage(img, 0, 0, w, h); resolve(canvas.toDataURL('image/jpeg', 0.82)); }; img.onerror = () => resolve(dataUrl); img.src = dataUrl; } catch (e) { resolve(dataUrl); } }); } /** 宽松解析模型返回的 JSON(容忍 ```json 代码块与前后废话) */ export function parseJsonLoose(text: string): T | null { if (!text) return null; let s = String(text).trim(); const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/); if (fence) s = fence[1].trim(); const start = s.indexOf('{'); const end = s.lastIndexOf('}'); if (start >= 0 && end > start) s = s.slice(start, end + 1); try { return JSON.parse(s) as T; } catch (e) { return null; } } /** * 看图写口播文案 * @param images 用户选中的原图(data URL) * @returns 分段文案,每段带图序号 */ export async function generateQuickVideoCopy(params: { title: string; style: string; images: string[]; /** 文档 / 网页正文:有正文时以正文为内容依据,图片决定每段配什么画面 */ sourceText?: string; }): Promise<[{ title: string; segments: QvSegment[] } | null, string | null]> { const images = params.images || []; const sourceText = (params.sourceText || '').trim(); if (!images.length && !sourceText) return [null, '请先添加图片、文档或网址内容']; if (!params.title.trim()) return [null, '请填写标题']; // 只有配了视觉(多模态)模型才压图发图:纯文本模型看不了图、也会被 image_url 顶回错误, // 走纯文本路径按编号顺序配画面,照样能出片 const useVision = await aiVisionAvailable(); const shrunk: string[] = []; if (useVision) { for (const img of images) { shrunk.push(await shrinkImageForVision(img)); } } const lines: string[] = [`我在做一个短视频,标题是《${params.title}》。文案风格:${params.style}。`]; if (sourceText) { const body = sourceText.slice(0, 6000); lines.push( `素材正文(来自用户上传的 Word / PDF 文档或网页,共 ${sourceText.length} 字,先看前 ${body.length} 字):`, '"""', body, '"""', '文案必须基于上面的素材正文改写,不要编造素材里没有的事实;素材里的关键信息、数字、结论要保留在文案里。', ); } if (images.length) { lines.push( `共有 ${images.length} 张图片,编号从 1 到 ${images.length}(顺序就是它们出现的顺序)。`, !useVision ? '你看不到图片本身,image 按顺序循环分配(第1段填1、第2段填2,排到最后一张回到1);' : sourceText ? '素材正文决定每段说什么,图片决定每段配哪张画面(image 填最贴合的编号)。' : '请你逐张看图,理解每张图里展示的内容,然后写一段适合朗读的口播文案:', `1. 段落数 ${Math.min(images.length + 1, Math.max(3, images.length))} 段左右,每段 15~40 字,口语化、能直接读出来;`, '2. 每段给一个 image 字段,填这段对应第几张图(只填数字 1~' + images.length + ');', '3. 让整段文案围绕标题讲一个完整的小故事,第一段抓人,最后一段收尾;', '4. 不要出现“图片”“第一张”这种字眼,也不要加表情符号和换行。', ); } else { lines.push( '素材只有文字,没有配图:', '1. 写 4~6 段、每段 15~40 字,口语化、能直接读出来;', '2. 每段 image 字段一律填 1;', '3. 让整段文案围绕标题讲一个完整的小故事,第一段抓人,最后一段收尾;', '4. 不要加表情符号和换行。', ); } lines.push('只输出 JSON,不要任何解释,格式:', '{"segments":[{"text":"...","image":1}]}'); const prompt = lines.join('\n'); const content: any[] = [{ type: 'text', text: prompt }]; shrunk.forEach(url => { content.push({ type: 'image_url', image_url: { url } }); }); const [res, err] = await localChatCompletion({ messages: [ { role: 'system', content: '你是短视频编导,只输出 JSON。' }, { role: 'user', content }, ], }); if (err) return [null, err]; const raw = res?.choices?.[0]?.message?.content; const json = parseJsonLoose<{ segments?: any[] }>(typeof raw === 'string' ? raw : raw?.content || ''); const segments: QvSegment[] = (json?.segments || []) .map(seg => ({ text: String(seg?.text || '').replace(/\s+/g, '').trim(), image: Math.max(1, Math.min(images.length, Number(seg?.image) || 1)), })) .filter(seg => seg.text); if (!segments.length) return [null, '模型没有返回可用文案,请重试']; return [{ title: params.title, segments }, null]; } /** 封面文案:AI 根据标题 + 素材写吸引人的封面文字(主标题 / 副标题 / 角标) */ export interface QvCoverCopy { /** 主标题:突出重点、抓眼球,≤12 字 */ main: string; /** 副标题 / 钩子句,写出特色,≤18 字 */ sub?: string; /** 角标短词,≤6 字(如「实测有效」「保姆级教程」) */ tag?: string; /** true = AI 生成;false = 本地标题模板兜底 */ ai?: boolean; } export interface QvCover { url: string; w: number; h: number; /** true = AI 文案失败,用标题模板兜底渲染 */ local?: boolean; /** 渲染进封面的文案 */ copy?: QvCoverCopy; } /** 封面文案请求的固定标记(E2E mock 按它区分请求) */ export const COVER_COPY_MARK = '生成短视频封面文案'; /** 量图片尺寸(取不到按 16:9 兜底) */ function measureImage(img: HTMLImageElement): { w: number; h: number } { const w = Number(img.naturalWidth) || 0; const h = Number(img.naturalHeight) || 0; return { w: w > 0 ? w : 1280, h: h > 0 ? h : 720 }; } /** 远程图片转 data URL(失败返回空串,调用方退回无背景渲染) */ async function toDataUrl(url: string): Promise { try { const res = await fetch(url); if (!res.ok) return ''; const blob = await res.blob(); return await new Promise(resolve => { const fr = new FileReader(); fr.onload = () => resolve(String(fr.result || '')); fr.onerror = () => resolve(''); fr.readAsDataURL(blob); }); } catch (e) { return ''; } } /** 本地模板兜底文案:标题直接当主标题,素材首句当副标题 */ function templateCoverCopy(params: { title: string; sourceText?: string }): QvCoverCopy { const main = params.title.trim().slice(0, 14) || '未命名视频'; const first = (params.sourceText || '').split(/[。!?!?.\n]/).map(s => s.trim()).find(s => s.length > 4); return { main, sub: first ? first.slice(0, 18) : undefined, ai: false }; } /**让模型根据标题/素材写封面文案(可带首图帮助理解画面),失败返回 [null, 错误] */ async function askCoverCopy(params: { title: string; images?: string[]; sourceText?: string; }): Promise<[QvCoverCopy | null, string | null]> { const useVision = !!params.images?.length && (await aiVisionAvailable()); const text = `${COVER_COPY_MARK}。视频标题:${params.title}。\n` + (params.sourceText ? `素材正文节选:${params.sourceText.slice(0, 800)}。\n` : '') + '要求:写出现在最吸引人点击的封面文字,突出重点、有特色、口语化有钩子。\n' + '输出 JSON:{"main":"主标题,≤12字,必须突出重点","sub":"副标题/钩子句,≤18字,写出特色","tag":"角标短词,≤6字,可留空"}\n' + '只输出 JSON,不要任何解释。'; const content: any[] = [{ type: 'text', text }]; if (useVision) { content.push({ type: 'image_url', image_url: { url: await shrinkImageForVision(params.images![0], 640) } }); } const [res, err] = await localChatCompletion({ messages: [ { role: 'system', content: '你是短视频封面文案专家,只输出 JSON。' }, { role: 'user', content: useVision ? content : text }, ], }); if (err) return [null, err]; const raw = res?.choices?.[0]?.message?.content; const json = parseJsonLoose<{ main?: any; sub?: any; tag?: any }>(typeof raw === 'string' ? raw : raw?.content || ''); const main = String(json?.main || '').replace(/\s+/g, '').trim().slice(0, 16); if (!main) return [null, '模型没有返回封面文案']; const sub = String(json?.sub || '').replace(/\s+/g, '').trim().slice(0, 24) || undefined; const tag = String(json?.tag || '').replace(/\s+/g, '').trim().slice(0, 8) || undefined; return [{ main, sub, tag, ai: true }, null]; } /** 加载图片(失败 resolve null) */ function loadImage(src: string): Promise { return new Promise(resolve => { try { const img = new Image(); img.onload = () => resolve(img); img.onerror = () => resolve(null); img.src = src; } catch (e) { resolve(null); } }); } /** 按最大宽度缩字号(保证文字不出画) */ function fitFont(ctx: CanvasRenderingContext2D, text: string, maxW: number, start: number, min: number, weight = '900'): number { let size = start; ctx.font = `${weight} ${size}px "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`; while (size > min && ctx.measureText(text).width > maxW) { size -= 4; ctx.font = `${weight} ${size}px "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`; } return size; } /** * 大字发光描边绘制:先画发光层(shadowBlur),再描边,最后实心填充,文字突出重点 */ function drawGlowStrokeText( ctx: CanvasRenderingContext2D, text: string, x: number, y: number, size: number, fill: string, stroke: string, glow: string, weight = '900', ) { ctx.font = `${weight} ${size}px "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.lineJoin = 'round'; // 发光层:同色文字带大模糊阴影画两遍,亮度更足 ctx.save(); ctx.shadowColor = glow; ctx.shadowBlur = Math.max(18, size * 0.35); ctx.fillStyle = fill; ctx.fillText(text, x, y); ctx.fillText(text, x, y); ctx.restore(); // 描边层 ctx.strokeStyle = stroke; ctx.lineWidth = Math.max(4, size * 0.14); ctx.strokeText(text, x, y); // 实心填充 ctx.fillStyle = fill; ctx.fillText(text, x, y); } /** 本地渲染封面:素材图背景(暗化)或渐变底 + AI 文案大字发光描边 */ async function renderCover(copy: QvCoverCopy, bgDataUrl?: string): Promise<{ url: string; w: number; h: number }> { const W = 1280; const H = 720; const cv = document.createElement('canvas'); cv.width = W; cv.height = H; const ctx = cv.getContext('2d'); if (!ctx) throw new Error('canvas 不可用'); const bg = bgDataUrl ? await loadImage(bgDataUrl) : null; if (bg && (bg.naturalWidth || bg.width)) { const { w: iw, h: ih } = measureImage(bg); const scale = Math.max(W / iw, H / ih); const dw = iw * scale; const dh = ih * scale; ctx.drawImage(bg, (W - dw) / 2, (H - dh) / 2, dw, dh); // 暗化渐变蒙版,保证文字可读 const veil = ctx.createLinearGradient(0, 0, 0, H); veil.addColorStop(0, 'rgba(8,10,30,0.42)'); veil.addColorStop(0.5, 'rgba(8,10,30,0.58)'); veil.addColorStop(1, 'rgba(8,10,30,0.78)'); ctx.fillStyle = veil; ctx.fillRect(0, 0, W, H); } else { // 无背景:深色渐变 + 光斑,质感不输生图 const g = ctx.createLinearGradient(0, 0, W, H); g.addColorStop(0, '#101a4d'); g.addColorStop(0.55, '#25124f'); g.addColorStop(1, '#0b1030'); ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); const blob = (cx: number, cy: number, r: number, c: string) => { const rg = ctx.createRadialGradient(cx, cy, 0, cx, cy, r); rg.addColorStop(0, c); rg.addColorStop(1, 'rgba(0,0,0,0)'); ctx.fillStyle = rg; ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fill(); }; blob(220, 160, 380, 'rgba(88,120,255,0.35)'); blob(1080, 560, 420, 'rgba(255,95,140,0.28)'); blob(640, 360, 460, 'rgba(255,196,64,0.14)'); } const main = copy.main || '视频封面'; const sub = (copy.sub || '').slice(0, 24); const tag = (copy.tag || '').slice(0, 8); // 主标题:可拆两行,字号尽量大 let lines = [main]; if (main.length > 9) { const cut = Math.ceil(main.length / 2); lines = [main.slice(0, cut), main.slice(cut)]; } const mainSize = fitFont(ctx, lines.reduce((a, b) => (a.length > b.length ? a : b)), W - 180, lines.length > 1 ? 132 : 168, 72); const lineH = mainSize * 1.2; const tagH = tag ? 66 : 0; const subSize = sub ? fitFont(ctx, sub, W - 240, 62, 36, '800') : 0; const subGap = sub ? 40 : 0; const totalH = tagH + 34 + lines.length * lineH + subGap + (sub ? subSize : 0); let cursorY = (H - totalH) / 2 + tagH / 2; // 角标胶囊 if (tag) { const tagSize = 40; ctx.font = `900 ${tagSize}px "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`; const tw = ctx.measureText(tag).width; const pw = tw + 80; const ph = 66; const px = W / 2 - pw / 2; const py = cursorY - ph / 2; const r = ph / 2; ctx.beginPath(); ctx.moveTo(px + r, py); ctx.arcTo(px + pw, py, px + pw, py + ph, r); ctx.arcTo(px + pw, py + ph, px, py + ph, r); ctx.arcTo(px, py + ph, px, py, r); ctx.arcTo(px, py, px + pw, py, r); ctx.closePath(); ctx.save(); ctx.shadowColor = 'rgba(255,196,64,0.85)'; ctx.shadowBlur = 26; const bgg = ctx.createLinearGradient(px, py, px + pw, py + ph); bgg.addColorStop(0, '#ffd166'); bgg.addColorStop(1, '#ff9f43'); ctx.fillStyle = bgg; ctx.fill(); ctx.restore(); ctx.fillStyle = '#3a1d00'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(tag, W / 2, cursorY + 2); cursorY += ph / 2 + 34; } // 主标题(发光 + 描边 + 实心,突出重点) const mainFill = '#ffffff'; const mainStroke = 'rgba(6,8,24,0.92)'; lines.forEach((ln, i) => { drawGlowStrokeText(ctx, ln, W / 2, cursorY + lineH / 2 + i * lineH, mainSize, mainFill, mainStroke, 'rgba(120,170,255,0.95)'); }); cursorY += lines.length * lineH + subGap; // 副标题(暖色发光描边,次级重点) if (sub) { drawGlowStrokeText(ctx, sub, W / 2, cursorY + subSize / 2, subSize, '#ffe9a8', 'rgba(6,8,24,0.9)', 'rgba(255,196,64,0.9)', '800'); } const url = cv.toDataURL('image/png'); if (!url || !url.startsWith('data:image/')) throw new Error('封面画布导出失败'); return { url, w: W, h: H }; } /** * 自动封面:AI 根据标题/素材写吸引人的封面文案(主标题+副标题+角标), * 再本地渲染成大字发光描边封面(素材图作背景),不再依赖文生图。 * @param params 标题 / 素材图 / 素材正文 * @returns [封面, 错误];文案生成失败时仍返回模板兜底封面(local=true) */ export async function generateQuickVideoCover(params: { title: string; images?: string[]; sourceText?: string; }): Promise<[QvCover | null, string | null]> { let copy: QvCoverCopy | null = null; let copyErr: string | null = null; if (params.title.trim()) { try { [copy, copyErr] = await askCoverCopy(params); } catch (e: any) { copyErr = e?.message || String(e); } } if (!copy) copy = templateCoverCopy(params); // 背景优先用第一张素材图(转 data URL 避免画布跨域污染) let bg = ''; const first = params.images?.length ? params.images[0] : ''; if (first) bg = first.startsWith('data:') ? first : await toDataUrl(first); try { const out = await renderCover(copy, bg || undefined); return [{ ...out, local: !copy.ai, copy }, copyErr]; } catch (e: any) { return [null, copyErr || e?.message || String(e)]; } } /** * 合成一段配音,返回可直接用于