img2img.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const path = require('path')
  2. const fs = require('fs')
  3. const aiModule = require(path.join(__dirname, '../../../../ai/ai.js'))
  4. function resolveSavePath(savePath, folderPath) {
  5. if (!savePath || typeof savePath !== 'string') return null
  6. const trimmed = savePath.trim()
  7. if (path.isAbsolute(trimmed) || /^[A-Za-z]:/.test(trimmed)) return trimmed
  8. return folderPath ? path.join(folderPath, trimmed) : path.resolve(trimmed)
  9. }
  10. /** 入参:prompt, model, imageUrl(参考图地址), savePath(可选,生成图保存路径) */
  11. async function executeImg2img({ prompt, model, imageUrl, savePath, folderPath }) {
  12. const p = prompt != null ? String(prompt).trim() : ''
  13. const url = imageUrl != null ? String(imageUrl).trim() : ''
  14. if (!url) return { success: false, error: 'img2img 缺少 imageUrl' }
  15. const m = model != null ? String(model).trim().toLowerCase() : ''
  16. const action = m === 'doubao' ? 'doubao_img2img' : 'img2img'
  17. const outPath = savePath ? resolveSavePath(savePath, folderPath) : null
  18. try {
  19. const result = await aiModule.run(action, p, url)
  20. if (!result.success) return { success: false, error: result.error || 'img2img 失败' }
  21. const data = result.data
  22. const item = data?.data?.[0]
  23. if (!item) return { success: false, error: 'img2img 无返回数据' }
  24. if (item.b64_json && outPath) {
  25. const dir = path.dirname(outPath)
  26. if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
  27. fs.writeFileSync(outPath, Buffer.from(item.b64_json, 'base64'))
  28. return { success: true, value: outPath, path: outPath }
  29. }
  30. const outUrl = item.url || ''
  31. return { success: true, value: outUrl, path: outUrl || undefined }
  32. } catch (e) {
  33. return { success: false, error: (e && (e.message || String(e))) || 'img2img 异常' }
  34. }
  35. }
  36. module.exports = { executeImg2img }