text2img.js 1.3 KB

12345678910111213141516171819202122232425262728
  1. const fs = require('fs')
  2. const path = require('path')
  3. const { runWithModel, resolveSavePath } = require('./shared')
  4. /** 入参:prompt, model, savePath(可选,图片保存路径;有则返回 b64 并写入文件,否则返回 url) */
  5. async function executeText2img ({ prompt, model, savePath, folderPath }) {
  6. const p = prompt != null ? String(prompt).trim() : ''
  7. const outPath = savePath ? resolveSavePath(savePath, folderPath) : null
  8. try {
  9. const result = await runWithModel('text2img', 'doubao_text2img', [p, outPath], model)
  10. if (!result.success) return { success: false, error: result.error || 'text2img 失败' }
  11. const data = result.data
  12. const item = data?.data?.[0]
  13. if (!item) return { success: false, error: 'text2img 无返回数据' }
  14. if (item.b64_json && outPath) {
  15. const dir = path.dirname(outPath)
  16. if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
  17. fs.writeFileSync(outPath, Buffer.from(item.b64_json, 'base64'))
  18. return { success: true, value: outPath, path: outPath }
  19. }
  20. const url = item.url || ''
  21. return { success: true, value: url, path: url || undefined }
  22. } catch (e) {
  23. return { success: false, error: (e && (e.message || String(e))) || 'text2img 异常' }
  24. }
  25. }
  26. module.exports = { executeText2img }