// 获取 API 代码(WP C-1,方案 §4.4):由作品的参数快照(任务详情 request)生成等价的公开接口调用。 // 图像 → POST /v1/images/generations(编辑模式的参考图换成占位 URL); // 视频 → POST /v1/video/generations 标准 director 协议(model / prompt / duration / // metadata{resolution, aspect_ratio, negative_prompt, seed, generate_audio, watermark, // camera{movement}, return_last_frame, prompt_extend} / media[{type, url}], // 字段与 controller/experience_video_director.go、relay/common/video_director.go 一致)。 // 不依赖 React / 浏览器,node --test 覆盖(creationApiCode.test.js)。 export const API_KEY_PLACEHOLDER = 'sk-xxx'; export const IMAGE_URL_PLACEHOLDER = ''; export const API_CODE_LANGS = ['curl', 'python', 'javascript']; export const IMAGE_API_PATH = '/v1/images/generations'; export const VIDEO_API_PATH = '/v1/video/generations'; /** 说明(i18n key):替换占位图片 / 视频为异步任务。 */ export const API_CODE_NOTES = { replaceImages: '请把 替换为你自己的公网图片地址(/v1 接口支持外部链接)', asyncVideo: '视频为异步任务:提交后返回 task_id,再用 GET {{path}}/{task_id} 查询结果', }; /** 接口地址:系统设置的服务器地址优先,否则当前页面的 origin;去掉结尾斜杠。 */ export const apiBaseUrlOf = (status, origin = '') => { const configured = String(status?.server_address || '').trim(); const base = configured || String(origin || '').trim(); return base.replace(/\/+$/, ''); }; const str = (v) => (typeof v === 'string' ? v.trim() : ''); const isBool = (v) => typeof v === 'boolean'; const isInt = (v) => typeof v === 'number' && Number.isFinite(v); /** n 张占位图:1 张为 ,多张编号 …,保证每张可区分。 */ const placeholders = (count) => Array.from({ length: count }, (_, i) => count > 1 ? `` : IMAGE_URL_PLACEHOLDER, ); // --------------------------------------------------------------------------- // 请求体 // --------------------------------------------------------------------------- /** 图像任务 → /v1/images/generations 请求体。task 为作品流的作品(含详情 request 时优先用快照)。 */ export const imageApiBody = (task) => { const t = task || {}; const req = t.request || {}; const hasSnapshot = Boolean(t.request); const body = { model: str(req.model) || str(t.model), prompt: hasSnapshot ? String(req.prompt || '') : String(t.prompt || ''), }; const n = Number(hasSnapshot ? req.n : t.n); if (Number.isInteger(n) && n > 0) body.n = n; const size = str(req.size) || str(t.size); if (size) body.size = size; const quality = str(req.quality) || str(t.quality); if (quality) body.quality = quality; if (str(req.negative_prompt)) body.negative_prompt = str(req.negative_prompt); if (isInt(req.seed)) body.seed = req.seed; ['style', 'background', 'output_format'].forEach((k) => { if (str(req[k])) body[k] = str(req[k]); }); if (isBool(req.watermark)) body.watermark = req.watermark; const mode = str(req.mode) || str(t.mode); const isEdit = mode === 'edit' || mode === 'image-to-image'; let count = 0; if (Array.isArray(req.reference_image_refs)) { count = req.reference_image_refs.length; } else if (Array.isArray(req.reference_images)) { count = req.reference_images.length; } if (isEdit && count === 0) count = 1; if (count > 0) { const urls = placeholders(count); body.image = urls.length === 1 ? urls[0] : urls; } return body; }; /** 视频任务 → /v1/video/generations 标准 director 请求体。 */ export const videoApiBody = (task) => { const t = task || {}; const req = t.request || {}; const body = { model: str(req.model) || str(t.model), prompt: t.request ? String(req.prompt || '') : String(t.prompt || ''), }; const duration = Number(req.duration) || Number(t.duration) || 0; if (duration > 0) body.duration = duration; const metadata = {}; const resolution = str(req.resolution) || str(t.resolution); if (resolution) metadata.resolution = resolution; const ratio = str(req.aspect_ratio) || str(req.ratio) || str(t.ratio); if (ratio) metadata.aspect_ratio = ratio; if (str(req.negative_prompt)) { metadata.negative_prompt = str(req.negative_prompt); } if (isInt(req.seed)) metadata.seed = req.seed; if (isBool(req.generate_audio)) metadata.generate_audio = req.generate_audio; else if (req.audio === true) metadata.generate_audio = true; // watermark / audio 在快照 DTO 中为 omitempty:缺省即未开启,不写出 if (req.watermark === true) metadata.watermark = true; if (str(req.camera)) metadata.camera = { movement: str(req.camera) }; if (isBool(req.return_last_frame)) { metadata.return_last_frame = req.return_last_frame; } if (isBool(req.prompt_extend)) metadata.prompt_extend = req.prompt_extend; if (Object.keys(metadata).length) body.metadata = metadata; const types = []; if (str(req.image_ref) || str(req.image)) types.push('first_image'); if (str(req.last_image_ref) || str(req.last_image)) types.push('last_image'); const refs = Array.isArray(req.reference_image_refs) ? req.reference_image_refs : Array.isArray(req.reference_images) ? req.reference_images : []; refs.forEach(() => types.push('reference_image')); if (types.length) { const urls = placeholders(types.length); body.media = types.map((type, i) => ({ type, url: urls[i] })); } return body; }; /** * 作品 → 等价的公开接口调用。 * @returns {{ kind, method: 'POST', url: string, path: string, body: object, notes: string[] }} * notes 为 i18n key(API_CODE_NOTES 的值) */ export const buildApiCall = (task, { baseUrl = '' } = {}) => { const kind = task?.kind === 'video' ? 'video' : 'image'; const path = kind === 'video' ? VIDEO_API_PATH : IMAGE_API_PATH; const body = kind === 'video' ? videoApiBody(task) : imageApiBody(task); const notes = []; const usesPlaceholder = kind === 'video' ? Boolean(body.media) : Boolean(body.image); if (usesPlaceholder) notes.push(API_CODE_NOTES.replaceImages); if (kind === 'video') notes.push(API_CODE_NOTES.asyncVideo); return { kind, method: 'POST', path, url: `${String(baseUrl || '').replace(/\/+$/, '')}${path}`, body, notes, }; }; // --------------------------------------------------------------------------- // 代码渲染 // --------------------------------------------------------------------------- const indentLines = (text, pad) => text .split('\n') .map((line, i) => (i === 0 ? line : pad + line)) .join('\n'); /** JSON 值 → Python 字面量(True / False / None,4 空格缩进,与 json 序列化顺序一致)。 */ export const toPythonLiteral = (value, indent = '') => { if (value === null || value === undefined) return 'None'; if (value === true) return 'True'; if (value === false) return 'False'; if (typeof value === 'number') { return Number.isFinite(value) ? String(value) : 'None'; } if (typeof value === 'string') return JSON.stringify(value); const inner = `${indent} `; if (Array.isArray(value)) { if (!value.length) return '[]'; const items = value.map((v) => `${inner}${toPythonLiteral(v, inner)},`); return `[\n${items.join('\n')}\n${indent}]`; } const keys = Object.keys(value); if (!keys.length) return '{}'; const items = keys.map( (k) => `${inner}${JSON.stringify(k)}: ${toPythonLiteral(value[k], inner)},`, ); return `{\n${items.join('\n')}\n${indent}}`; }; const shellQuote = (text) => `'${String(text).replace(/'/g, `'\\''`)}'`; export const renderCurl = (call, apiKey = API_KEY_PLACEHOLDER) => [ `curl -X POST ${shellQuote(call.url)} \\`, ` -H ${shellQuote(`Authorization: Bearer ${apiKey}`)} \\`, ` -H 'Content-Type: application/json' \\`, ` -d ${shellQuote(JSON.stringify(call.body, null, 2))}`, ].join('\n'); export const renderPython = (call, apiKey = API_KEY_PLACEHOLDER) => [ 'import requests', '', 'resp = requests.post(', ` ${JSON.stringify(call.url)},`, ` headers={"Authorization": ${JSON.stringify(`Bearer ${apiKey}`)}},`, ` json=${toPythonLiteral(call.body, ' ')},`, ' timeout=300,', ')', 'print(resp.json())', ].join('\n'); export const renderJavaScript = (call, apiKey = API_KEY_PLACEHOLDER) => [ `const resp = await fetch(${JSON.stringify(call.url)}, {`, ` method: 'POST',`, ' headers: {', ` Authorization: ${JSON.stringify(`Bearer ${apiKey}`)},`, ` 'Content-Type': 'application/json',`, ' },', ` body: JSON.stringify(${indentLines(JSON.stringify(call.body, null, 2), ' ')}),`, '});', 'console.log(await resp.json());', ].join('\n'); /** @param {'curl'|'python'|'javascript'} lang */ export const renderApiCode = (call, lang, apiKey = API_KEY_PLACEHOLDER) => { if (!call) return ''; if (lang === 'python') return renderPython(call, apiKey); if (lang === 'javascript') return renderJavaScript(call, apiKey); return renderCurl(call, apiKey); };