- 素材导入三选一:图片 / Word·PDF 文档(新 sourceImport.ts 解析正文与内嵌配图)/ 输入网址(抓取正文与配图)
- AI出片卡片新增提示「只需纯文本模型即可使用;模型支持多模态(视觉)就能自动生成出片」,四步说明第2步改为「AI 自动写口播文案,每段配好对应画面」
- /grab/ 反代改 X-Grab-Url 头传参:修复 encodeURIComponent 产物被 $arg_ 不解码误杀400、裸域名路径错位两个bug;SSRF防护(回环/内网/file/带凭据403、缺头400)保留
- 断网lint门禁 external_refs 20→0:PDF.js命名空间、example.com示例域名、${A}截断产物、ai/nav.88531.cn 自有域名登记白名单
- README/CHANGELOG 已同步本次更新
376 lines
15 KiB
TypeScript
376 lines
15 KiB
TypeScript
/**
|
||
* 本机 AI 后端接入(免登录)
|
||
*
|
||
* 上游开源项目 UniCut(gitee.com/676015863/unicut)的 AI 对话/图片生成都要走
|
||
* video.h5ds.com 并携带账号 token;注意这里的 UniCut 指上游原项目,不是本产品名。
|
||
* 去掉登录后这些接口必然报 "Header parameter [authorization] cannot be empty"。
|
||
* 这里改成直连本机自建服务:
|
||
* - 对话/Agent:本机 NewAPI(OpenAI 兼容 /v1/chat/completions)
|
||
* - 图片生成:本机图像生成代理(OpenAI 兼容 /v1/images/generations)
|
||
*
|
||
* 配置可在运行时覆盖:把 local-ai.json 放到站点根目录(dist 根)即可,
|
||
* 不用重新构建镜像。字段见 public/local-ai.json.example。
|
||
*
|
||
* 现在额外叠加用户自己填的 Key(见 utils/aiAuth):接口地址、模型、密钥一律
|
||
* 以浏览器里用户填的为准;没配置 Key 时下面的 local* 函数直接返回错误,
|
||
* AI 功能不可用,只能用基础剪辑。
|
||
*/
|
||
import { getAiConfig, isAiConfigured, AI_NOT_CONFIGURED_MSG, applyUserKey } from './aiAuth';
|
||
|
||
export interface LocalAiConfig {
|
||
chat: { baseUrl: string; apiKey: string; model: string; visionModel?: string; fallbackModels?: string[] };
|
||
image: { baseUrl: string; apiKey: string; model: string; size?: string; fallbackModels?: string[] };
|
||
video?: { baseUrl: string; apiKey: string; models: string[] };
|
||
tts?: { baseUrl?: string };
|
||
}
|
||
|
||
const EMPTY_KEY = '';
|
||
|
||
const DEFAULTS: LocalAiConfig = {
|
||
chat: {
|
||
// 默认指向官方 AI(ai.88531.cn,OpenAI 兼容 /v1,CORS 允许浏览器直连):
|
||
// 接口地址/模型名预填官方值,用户只需在「配置模型」里填自己的 API Key 即可用;
|
||
// 也支持整项换成任意 OpenAI 兼容网关。
|
||
baseUrl: 'https://ai.88531.cn/v1',
|
||
apiKey: EMPTY_KEY,
|
||
model: 'mimo-v2.6-flash',
|
||
visionModel: 'deepseek-v4-flash-vision-exp',
|
||
fallbackModels: ['glm-5.3-flash', 'deepseek-v4-flash'],
|
||
},
|
||
// 生图:官方 AI(NewAPI OpenAI 兼容 /v1/images/generations)
|
||
image: {
|
||
baseUrl: 'https://ai.88531.cn/v1',
|
||
apiKey: EMPTY_KEY,
|
||
model: 'flux-schnell',
|
||
size: '1024x1024',
|
||
},
|
||
// 生视频:官方 AI(NewAPI 视频端点 /v1/video/generations,单数)
|
||
video: {
|
||
baseUrl: 'https://ai.88531.cn/v1',
|
||
apiKey: EMPTY_KEY,
|
||
resolution: '720p',
|
||
models: ['inkling'],
|
||
},
|
||
// 本机 TTS 服务(edge-tts,免费、不消耗任何模型额度),经 nginx 同源反代保留
|
||
tts: {
|
||
baseUrl: '/localtts',
|
||
},
|
||
};
|
||
|
||
let baseCache: LocalAiConfig | null = null;
|
||
let baseLoading: Promise<LocalAiConfig> | null = null;
|
||
|
||
/** 站点级默认配置(local-ai.json 优先,失败则用内置默认值),不含用户 Key */
|
||
function loadBaseConfig(): Promise<LocalAiConfig> {
|
||
if (baseCache) return Promise.resolve(baseCache);
|
||
if (baseLoading) return baseLoading;
|
||
baseLoading = (async () => {
|
||
let cfg = DEFAULTS;
|
||
try {
|
||
const res = await fetch('/local-ai.json', { cache: 'no-store' });
|
||
if (res.ok) {
|
||
const json = await res.json();
|
||
cfg = {
|
||
chat: { ...DEFAULTS.chat, ...(json.chat || {}) },
|
||
image: { ...DEFAULTS.image, ...(json.image || {}) },
|
||
video: { ...(DEFAULTS.video as any), ...(json.video || {}) },
|
||
tts: { ...DEFAULTS.tts, ...(json.tts || {}) },
|
||
};
|
||
}
|
||
} catch (e) {
|
||
// 没有配置文件就用默认值
|
||
}
|
||
baseCache = cfg;
|
||
return cfg;
|
||
})();
|
||
return baseLoading;
|
||
}
|
||
|
||
/**
|
||
* 最终生效的 AI 配置 = 站点默认 + 用户自己填的 Key。
|
||
* 用户配置存在浏览器 localStorage,每次调用都重新叠加,用户改完立即生效。
|
||
* 对话的接口地址/密钥一律以用户填的为准;模型用 AI 设置里填的那个
|
||
* (调用方传进来的模型名是本站私有 ID,用户网关上没有,一律忽略)。
|
||
* 视觉模型不再内置:公网部署不预设任何模型,带图请求直接用用户填的主模型
|
||
*(主模型需支持图片输入;不支持时调用会明确报错,不会偷偷换用别人的模型)。
|
||
*/
|
||
export async function loadLocalAiConfig(): Promise<LocalAiConfig> {
|
||
const base = await loadBaseConfig();
|
||
const user = getAiConfig();
|
||
const cfg: LocalAiConfig = { ...base };
|
||
const chat: LocalAiConfig['chat'] = {
|
||
...base.chat,
|
||
baseUrl: user.baseUrl,
|
||
model: user.model,
|
||
visionModel: base.chat.visionModel,
|
||
fallbackModels: [user.model],
|
||
};
|
||
cfg.chat = applyUserKey(chat);
|
||
// 生图/生视频同样回落到用户填的网关(需网关支持对应 OpenAI 兼容接口),
|
||
// 站点不内置任何通道,密钥一律用用户自己的
|
||
cfg.image = applyUserKey({ ...cfg.image, baseUrl: user.baseUrl });
|
||
cfg.video = applyUserKey({ ...cfg.video, baseUrl: user.baseUrl });
|
||
return cfg;
|
||
}
|
||
|
||
const withAuth = (apiKey: string): Record<string, string> => {
|
||
const h: Record<string, string> = { 'Content-Type': 'application/json' };
|
||
if (apiKey) h.Authorization = `Bearer ${apiKey}`;
|
||
return h;
|
||
};
|
||
|
||
/** 是否配置了视觉(多模态)模型:只有配了才会把图片真发给模型看,否则调用方走纯文本路径 */
|
||
export async function aiVisionAvailable(): Promise<boolean> {
|
||
if (!isAiConfigured()) return false;
|
||
try {
|
||
const cfg = await loadLocalAiConfig();
|
||
return !!cfg.chat.visionModel;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/** OpenAI 兼容对话(一次性返回),返回 [数据, 错误] */
|
||
export async function localChatCompletion(params: {
|
||
model?: string;
|
||
messages: any[];
|
||
}): Promise<[any, string | null]> {
|
||
if (!isAiConfigured()) return [null, AI_NOT_CONFIGURED_MSG];
|
||
const cfg = await loadLocalAiConfig();
|
||
// 消息里带图片时用视觉模型,否则用主模型
|
||
const hasImage = (params.messages || []).some((m: any) => {
|
||
if (Array.isArray(m?.content)) return m.content.some((c: any) => c?.type === 'image_url' || c?.type === 'image');
|
||
return typeof m?.content === 'string' && m.content.includes('data:image');
|
||
});
|
||
const primary = hasImage && cfg.chat.visionModel ? cfg.chat.visionModel : cfg.chat.model;
|
||
const models = [primary, ...(cfg.chat.fallbackModels || [])].filter(Boolean);
|
||
// 未配视觉模型时把图片块剥掉:纯文本主模型会被 image_url 内容块顶回错误,
|
||
// 剥掉后纯文本模型照样能出文案(调用方按图片编号配画面)
|
||
let messages = params.messages;
|
||
if (hasImage && !cfg.chat.visionModel) {
|
||
messages = (params.messages || []).map((m: any) => {
|
||
if (!Array.isArray(m?.content)) return m;
|
||
const parts = m.content.filter((c: any) => c?.type !== 'image_url' && c?.type !== 'image');
|
||
return parts.length ? { ...m, content: parts } : m;
|
||
});
|
||
}
|
||
let lastErr = '';
|
||
|
||
for (const model of models) {
|
||
try {
|
||
const res = await fetch(`${cfg.chat.baseUrl}/chat/completions`, {
|
||
method: 'POST',
|
||
headers: withAuth(cfg.chat.apiKey),
|
||
body: JSON.stringify({ model, messages, stream: false, max_tokens: 4096 }),
|
||
});
|
||
const text = await res.text();
|
||
let data: any = null;
|
||
try {
|
||
data = JSON.parse(text);
|
||
} catch (e) {
|
||
lastErr = `本机模型返回异常:${text.slice(0, 120)}`;
|
||
continue;
|
||
}
|
||
if (!res.ok || data?.error) {
|
||
lastErr = data?.error?.message || `本机模型请求失败(HTTP ${res.status})`;
|
||
continue;
|
||
}
|
||
return [data, null];
|
||
} catch (e: any) {
|
||
lastErr = `无法连接你填写的接口(${cfg.chat.baseUrl}):${e?.message || e}`;
|
||
}
|
||
}
|
||
return [null, lastErr || '本机模型服务不可用'];
|
||
}
|
||
|
||
/** OpenAI 兼容图片生成,返回 [图片地址, 错误](地址为 data URL) */
|
||
export async function localGenerateImage(params: {
|
||
prompt: string;
|
||
size?: string;
|
||
model?: string;
|
||
}): Promise<[{ url: string } | null, string | null]> {
|
||
if (!isAiConfigured()) return [null, AI_NOT_CONFIGURED_MSG];
|
||
const cfg = await loadLocalAiConfig();
|
||
try {
|
||
const res = await fetch(`${cfg.image.baseUrl}/images/generations`, {
|
||
method: 'POST',
|
||
headers: withAuth(cfg.image.apiKey),
|
||
body: JSON.stringify({
|
||
model: params.model || cfg.image.model,
|
||
prompt: params.prompt,
|
||
n: 1,
|
||
size: params.size || cfg.image.size || '1024x1024',
|
||
}),
|
||
});
|
||
const text = await res.text();
|
||
let data: any = null;
|
||
try {
|
||
data = JSON.parse(text);
|
||
} catch (e) {
|
||
return [null, `本机图片服务返回异常:${text.slice(0, 120)}`];
|
||
}
|
||
if (!res.ok || data?.error) {
|
||
return [null, data?.error?.message || `本机图片服务请求失败(HTTP ${res.status})`];
|
||
}
|
||
const item = data?.data?.[0];
|
||
if (!item) return [null, '本机图片服务未返回图片'];
|
||
let url = item.url || '';
|
||
if (!url && item.b64_json) {
|
||
const b64 = String(item.b64_json);
|
||
// grok-imagine 返 JPEG(/9j/ 开头),其余按 PNG 处理,避免 MIME 与实际字节不符
|
||
const mime = b64.startsWith('/9j/') ? 'image/jpeg' : 'image/png';
|
||
url = `data:${mime};base64,${b64}`;
|
||
}
|
||
if (!url) return [null, '本机图片服务未返回图片地址'];
|
||
return [{ url }, null];
|
||
} catch (e: any) {
|
||
return [null, `无法连接你填写的接口(${cfg.image.baseUrl}):${e?.message || e}`];
|
||
}
|
||
}
|
||
/** 视频生成(官方 NewAPI 的 /video/generations,OpenAI 兼容),返回 [视频地址, 错误] */
|
||
export async function localGenerateVideo(params: {
|
||
prompt: string;
|
||
model?: string;
|
||
imageUrl?: string;
|
||
duration?: number;
|
||
resolution?: string;
|
||
}): Promise<[{ url: string } | null, string | null]> {
|
||
if (!isAiConfigured()) return [null, AI_NOT_CONFIGURED_MSG];
|
||
const cfg = await loadLocalAiConfig();
|
||
const base = cfg.video?.baseUrl || '';
|
||
if (!base) return [null, AI_NOT_CONFIGURED_MSG];
|
||
const models = params.model ? [params.model] : (cfg.video?.models || []);
|
||
const errors: string[] = [];
|
||
for (const model of models) {
|
||
try {
|
||
const body: any = {
|
||
model,
|
||
prompt: params.prompt,
|
||
// 上游要求显式分辨率(各模型支持范围不同,不匹配会 400,随后降级到下一个模型)
|
||
resolution: params.resolution || cfg.video?.resolution || '720p',
|
||
// 上游要求显式时长(秒)
|
||
duration: Math.max(1, Math.round(Number(params.duration) || 5)),
|
||
};
|
||
if (params.imageUrl) {
|
||
body.image_url = params.imageUrl;
|
||
}
|
||
const res = await fetch(`${base}/video/generations`, {
|
||
method: 'POST',
|
||
headers: withAuth(cfg.video?.apiKey || ''),
|
||
body: JSON.stringify(body),
|
||
});
|
||
const text = await res.text();
|
||
let data: any = null;
|
||
try {
|
||
data = JSON.parse(text);
|
||
} catch (e) {
|
||
errors.push(`${model}:返回非 JSON(${text.slice(0, 80)})`);
|
||
continue;
|
||
}
|
||
if (!res.ok || data?.error) {
|
||
errors.push(`${model}:${data?.error?.message || `HTTP ${res.status}`}`);
|
||
continue;
|
||
}
|
||
// 兼容两种返回:{data:[{url}]} 或 {id,status} 需要轮询
|
||
const item = data?.data?.[0] || data?.videos?.[0];
|
||
let url = item?.url || item?.video_url || data?.url || '';
|
||
if (!url && item?.b64_video) {
|
||
// veo 系列直接返回 base64 mp4,转成 data URL 让时间轴可直接取用
|
||
url = `data:video/mp4;base64,${item.b64_video}`;
|
||
}
|
||
if (url) return [{ url }, null];
|
||
const st = String(data?.status || '');
|
||
if (/fail|error|cancel/i.test(st)) {
|
||
errors.push(`${model}:${data?.error?.message || st}`);
|
||
continue;
|
||
}
|
||
// 同步返回 completed 却没有地址,说明该路由没有产出,直接降级,别去轮询不存在的接口
|
||
if (st === 'completed') {
|
||
errors.push(`${model}:已完成但未返回视频地址`);
|
||
continue;
|
||
}
|
||
const taskId = data?.id || data?.task_id;
|
||
if (taskId) {
|
||
const polled = await pollLocalVideo(base, taskId, cfg.video?.apiKey || '');
|
||
if (polled.url) return [{ url: polled.url }, null];
|
||
errors.push(`${model}:${polled.error || '任务超时'}`);
|
||
continue;
|
||
}
|
||
errors.push(`${model}:未返回视频地址`);
|
||
} catch (e: any) {
|
||
errors.push(`${model}:${e?.message || e}`);
|
||
}
|
||
}
|
||
return [null, errors.length ? `视频生成失败:${errors.join(';')}` : '未配置视频模型:请点右上角「配置模型」填入 API Key(接口已默认官方 AI:ai.88531.cn;也可换网关,需支持 video/generations 接口)'];
|
||
}
|
||
|
||
/** 轮询视频任务(最多 5 分钟) */
|
||
async function pollLocalVideo(
|
||
base: string,
|
||
taskId: string,
|
||
apiapiKey: string,
|
||
): Promise<{ url?: string; error?: string }> {
|
||
const deadline = Date.now() + 90 * 1000;
|
||
while (Date.now() < deadline) {
|
||
await new Promise(r => setTimeout(r, 5000));
|
||
try {
|
||
const res = await fetch(`${base}/video/generations/${encodeURIComponent(taskId)}`, {
|
||
headers: withAuth(apiapiKey),
|
||
});
|
||
if (!res.ok) continue;
|
||
const data: any = await res.json();
|
||
const url = data?.data?.[0]?.url || data?.url || data?.video_url;
|
||
if (url) return { url };
|
||
const status = String(data?.status || '');
|
||
if (/fail|error|cancel/i.test(status)) return { error: data?.error?.message || status };
|
||
} catch (e) {
|
||
// 网络抖动继续轮询
|
||
}
|
||
}
|
||
return { error: '轮询超时(90 秒)' };
|
||
}
|
||
|
||
/** 本机语音合成(edge-tts 服务,经 /localtts 同源反代),返回 [音频地址, 错误] */
|
||
export async function localTextToSpeech(params: {
|
||
text: string;
|
||
voice?: string;
|
||
emotion?: string;
|
||
desc?: string;
|
||
}): Promise<[{ storage_path: string } | null, string | null]> {
|
||
const cfg = await loadLocalAiConfig();
|
||
const base = cfg.tts?.baseUrl || '/localtts';
|
||
const text = (params.text || '').trim();
|
||
if (!text) return [null, '配音文本为空'];
|
||
try {
|
||
const res = await fetch(`${base}/tts`, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
text,
|
||
voice: params.voice || '',
|
||
emotion: params.emotion || '',
|
||
desc: params.desc || '',
|
||
}),
|
||
});
|
||
const raw = await res.text();
|
||
let data: any = null;
|
||
try {
|
||
data = JSON.parse(raw);
|
||
} catch (e) {
|
||
return [null, `本机语音服务返回异常:${raw.slice(0, 120)}`];
|
||
}
|
||
if (!res.ok || data?.error) {
|
||
return [null, data?.error || `本机语音合成失败(HTTP ${res.status})`];
|
||
}
|
||
if (!data?.url) return [null, '本机语音服务未返回音频地址'];
|
||
// 编辑器会把相对路径拼到 resourcesHost(cdn) 上,这里必须返回同源绝对地址
|
||
const u = String(data.url);
|
||
const abs =
|
||
/^https?:\/\//i.test(u) ? u : `${window.location.origin}${u.startsWith('/') ? '' : '/'}${u}`;
|
||
return [{ storage_path: abs }, null];
|
||
} catch (e: any) {
|
||
return [null, `无法连接本机语音服务(${base}):${e?.message || e}`];
|
||
}
|
||
}
|
||
|