| 123456789101112131415161718192021222324252627282930313233343536373839 |
- const path = require('path')
- const fs = require('fs')
- const aiModule = require(path.join(__dirname, '../../../../ai/ai.js'))
- function resolveSavePath(savePath, folderPath) {
- if (!savePath || typeof savePath !== 'string') return null
- const trimmed = savePath.trim()
- if (path.isAbsolute(trimmed) || /^[A-Za-z]:/.test(trimmed)) return trimmed
- return folderPath ? path.join(folderPath, trimmed) : path.resolve(trimmed)
- }
- /** 入参:prompt, model, imageUrl(参考图地址), savePath(可选,生成图保存路径) */
- async function executeImg2img({ prompt, model, imageUrl, savePath, folderPath }) {
- const p = prompt != null ? String(prompt).trim() : ''
- const url = imageUrl != null ? String(imageUrl).trim() : ''
- if (!url) return { success: false, error: 'img2img 缺少 imageUrl' }
- const m = model != null ? String(model).trim().toLowerCase() : ''
- const action = m === 'doubao' ? 'doubao_img2img' : 'img2img'
- const outPath = savePath ? resolveSavePath(savePath, folderPath) : null
- try {
- const result = await aiModule.run(action, p, url)
- if (!result.success) return { success: false, error: result.error || 'img2img 失败' }
- const data = result.data
- const item = data?.data?.[0]
- if (!item) return { success: false, error: 'img2img 无返回数据' }
- if (item.b64_json && outPath) {
- const dir = path.dirname(outPath)
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
- fs.writeFileSync(outPath, Buffer.from(item.b64_json, 'base64'))
- return { success: true, value: outPath, path: outPath }
- }
- const outUrl = item.url || ''
- return { success: true, value: outUrl, path: outUrl || undefined }
- } catch (e) {
- return { success: false, error: (e && (e.message || String(e))) || 'img2img 异常' }
- }
- }
- module.exports = { executeImg2img }
|