text2img.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637
  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, savePath(可选,图片保存路径;有则返回 b64 并写入文件,否则返回 url) */
  11. async function executeText2img({ prompt, model, savePath, folderPath }) {
  12. const p = prompt != null ? String(prompt).trim() : ''
  13. const m = model != null ? String(model).trim().toLowerCase() : ''
  14. const action = m === 'doubao' ? 'doubao_text2img' : 'text2img'
  15. const outPath = savePath ? resolveSavePath(savePath, folderPath) : null
  16. try {
  17. const result = await aiModule.run(action, p, outPath)
  18. if (!result.success) return { success: false, error: result.error || 'text2img 失败' }
  19. const data = result.data
  20. const item = data?.data?.[0]
  21. if (!item) return { success: false, error: 'text2img 无返回数据' }
  22. if (item.b64_json && outPath) {
  23. const dir = path.dirname(outPath)
  24. if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
  25. fs.writeFileSync(outPath, Buffer.from(item.b64_json, 'base64'))
  26. return { success: true, value: outPath, path: outPath }
  27. }
  28. const url = item.url || ''
  29. return { success: true, value: url, path: url || undefined }
  30. } catch (e) {
  31. return { success: false, error: (e && (e.message || String(e))) || 'text2img 异常' }
  32. }
  33. }
  34. module.exports = { executeText2img }