sdcpp-generate.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. /**
  2. * @node sdcpp-generate
  3. * @name SD.cpp Generate
  4. * @category sdcpp
  5. * @version 1.0.0
  6. * @description Queue an image or video generation job on an sdcpp-restapi server and return its job id
  7. * @icon image-plus
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. serverUrl: {
  13. type: 'string',
  14. title: 'Server URL',
  15. description: 'Base address of the sdcpp-restapi server, such as http://localhost:8077. No trailing slash needed',
  16. default: 'http://localhost:8077'
  17. },
  18. credentialId: {
  19. type: 'string',
  20. title: 'Credential',
  21. description: 'A basic credential holding the sdcpp-restapi username and password. Every endpoint except health requires one',
  22. dynamicOptions: {
  23. source: 'credentials',
  24. filter: { type: ['basic'] }
  25. }
  26. },
  27. operation: {
  28. type: 'string',
  29. title: 'Operation',
  30. enum: ['txt2img', 'img2img', 'txt2vid', 'upscale'],
  31. default: 'txt2img',
  32. description: 'txt2img generates from a prompt alone, img2img and txt2vid start from an image, upscale enlarges one using the separately loaded upscaler'
  33. },
  34. prompt: {
  35. type: 'string',
  36. title: 'Prompt',
  37. description: 'What to generate. Supports {{variable}} interpolation and <lora:name:weight> syntax. Also supports {a|b|c} dynamic prompts, which the server expands into one queue item per variation',
  38. format: 'textarea'
  39. },
  40. negativePrompt: {
  41. type: 'string',
  42. title: 'Negative Prompt',
  43. description: 'Concepts to exclude. Has no effect on LCM and one-step SDXS models',
  44. format: 'textarea'
  45. },
  46. width: {
  47. type: 'number',
  48. title: 'Width',
  49. description: 'Leave empty to use the loaded architecture default, such as 1024 for SDXL and Flux'
  50. },
  51. height: {
  52. type: 'number',
  53. title: 'Height',
  54. description: 'Leave empty to use the loaded architecture default'
  55. },
  56. steps: {
  57. type: 'number',
  58. title: 'Steps',
  59. description: 'Sampling steps. Leave empty to use the architecture default, which is 4 for Flux Schnell and LCM and 20 for most others'
  60. },
  61. cfgScale: {
  62. type: 'number',
  63. title: 'CFG Scale',
  64. description: 'Guidance strength. Leave empty to use the architecture default. Distilled models such as Flux Schnell, LCM and Z-Image want 1.0'
  65. },
  66. sampler: {
  67. type: 'string',
  68. title: 'Sampler',
  69. enum: ['', 'euler', 'euler_a', 'heun', 'dpm2', 'dpm++2s_a', 'dpm++2m', 'dpm++2mv2',
  70. 'ipndm', 'ipndm_v', 'lcm', 'ddim_trailing', 'tcd', 'res_multistep', 'res_2s',
  71. 'er_sde', 'euler_cfg_pp', 'euler_a_cfg_pp', 'euler_ge'],
  72. default: '',
  73. description: 'Leave empty to use the architecture default'
  74. },
  75. scheduler: {
  76. type: 'string',
  77. title: 'Scheduler',
  78. enum: ['', 'discrete', 'karras', 'exponential', 'ays', 'gits', 'sgm_uniform',
  79. 'simple', 'smoothstep', 'kl_optimal', 'lcm', 'bong_tangent', 'ltx2'],
  80. default: '',
  81. description: 'Leave empty to use the architecture default'
  82. },
  83. seed: {
  84. type: 'number',
  85. title: 'Seed',
  86. description: 'Use -1 for a random seed. Any other value reproduces the same image. Leave empty to let the server decide'
  87. },
  88. batchCount: {
  89. type: 'number',
  90. title: 'Batch Count',
  91. description: 'How many images to generate in this one job, all sharing the prompt'
  92. },
  93. clipSkip: {
  94. type: 'number',
  95. title: 'CLIP Skip',
  96. description: 'Skip the last N CLIP layers. Negative means the model default'
  97. },
  98. title: {
  99. type: 'string',
  100. title: 'Job Title',
  101. description: 'Optional label stored with the job, useful for finding it again in the queue'
  102. },
  103. initImageBase64: {
  104. type: 'string',
  105. title: 'Init Image (base64)',
  106. description: 'Starting image for img2img and txt2vid, and the image to enlarge for upscale. Base64 without a data: prefix. Usually {{$json.file.data}} from a previous node'
  107. },
  108. maskImageBase64: {
  109. type: 'string',
  110. title: 'Mask Image (base64)',
  111. description: 'Inpainting mask for img2img. White marks the area to regenerate'
  112. },
  113. strength: {
  114. type: 'number',
  115. title: 'Strength',
  116. description: 'How far img2img and txt2vid may move from the init image, from 0 to 1. Higher changes more'
  117. },
  118. upscaleFactor: {
  119. type: 'number',
  120. title: 'Upscale Factor',
  121. description: 'For the upscale operation. The upscaler model must already be loaded'
  122. },
  123. videoFrames: {
  124. type: 'number',
  125. title: 'Video Frames',
  126. description: 'For txt2vid, how many frames to render'
  127. },
  128. fps: {
  129. type: 'number',
  130. title: 'FPS',
  131. description: 'For txt2vid, frames per second of the output video'
  132. },
  133. extraOptions: {
  134. type: 'object',
  135. title: 'Extra Options',
  136. description: 'Any other generation field passed straight through to the server, such as slg_scale, cache_mode, ref_images or vae_tiling. Names must match the API exactly. See /options/generation on the server for the full list with descriptions'
  137. },
  138. timeout: {
  139. type: 'number',
  140. title: 'Timeout (ms)',
  141. description: 'Applies to queueing the job, not to the render itself. The call returns as soon as the job is accepted',
  142. default: 30000
  143. }
  144. },
  145. required: ['credentialId']
  146. };
  147. const inputSchema = {
  148. type: 'object',
  149. properties: {
  150. data: { type: 'any' }
  151. }
  152. };
  153. const outputSchema = {
  154. type: 'object',
  155. properties: {
  156. jobId: { type: 'string', description: 'Id of the queued job, to pass to SD.cpp Job Status or Wait' },
  157. status: { type: 'string', description: 'Queue status at the moment of accepting, normally pending' },
  158. position: { type: 'number', description: 'Place in the queue when it was accepted' },
  159. operation: { type: 'string', description: 'Which generation endpoint was called' },
  160. request: { type: 'object', description: 'The body actually sent, useful for debugging which defaults were left to the server' }
  161. }
  162. };
  163. function normalizeServer(url) {
  164. const value = String(url || '').trim();
  165. if (!value) {
  166. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  167. }
  168. return value.replace(/\/+$/, '');
  169. }
  170. function readCredential(credentialId) {
  171. const auth = smartbotic.credentials.get(credentialId);
  172. if (!auth || auth.success !== true) {
  173. throw new Error('SD.cpp: could not read the credential: ' +
  174. ((auth && auth.error) || 'unknown error'));
  175. }
  176. const value = auth.headerValue || '';
  177. if (value.indexOf('Basic ') !== 0) {
  178. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  179. 'username and password');
  180. }
  181. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  182. const separator = decoded.indexOf(':');
  183. if (separator < 1) {
  184. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  185. }
  186. return {
  187. username: decoded.substring(0, separator),
  188. password: decoded.substring(separator + 1)
  189. };
  190. }
  191. function call(options) {
  192. const response = smartbotic.http.request(options);
  193. let body = response.data;
  194. if (typeof body === 'string' && body.length > 0) {
  195. try {
  196. body = JSON.parse(body);
  197. } catch (e) {
  198. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  199. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  200. ' with a body that is not JSON: ' + snippet);
  201. }
  202. }
  203. if (response.status < 200 || response.status >= 300) {
  204. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  205. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  206. }
  207. return body || {};
  208. }
  209. function login(server, credential, timeout) {
  210. const session = call({
  211. method: 'POST',
  212. url: server + '/auth/login',
  213. headers: { 'Content-Type': 'application/json' },
  214. body: JSON.stringify({
  215. username: credential.username,
  216. password: credential.password
  217. }),
  218. timeout: timeout,
  219. what: 'signing in'
  220. });
  221. if (!session.token) {
  222. throw new Error('SD.cpp: the server accepted the login but returned no token');
  223. }
  224. return session.token;
  225. }
  226. // Width, steps, cfg_scale and friends are architecture defaults: the server
  227. // fills them from the loaded model's preset when the field is absent. Sending
  228. // an empty box as 0 or "" would override that preset with nonsense, so a field
  229. // the user did not fill must not appear in the body at all.
  230. //
  231. // The test is emptiness, never truthiness. seed 0 and clip_skip 0 are both
  232. // legitimate values that a truthy check would silently drop.
  233. function putIfSet(target, key, value) {
  234. if (value === undefined || value === null || value === '') {
  235. return;
  236. }
  237. if (typeof value === 'number' && !isFinite(value)) {
  238. return;
  239. }
  240. target[key] = value;
  241. }
  242. async function execute(config, input, context) {
  243. const server = normalizeServer(config.serverUrl);
  244. const operation = config.operation || 'txt2img';
  245. const timeout = config.timeout || 30000;
  246. if (['txt2img', 'img2img', 'txt2vid', 'upscale'].indexOf(operation) === -1) {
  247. throw new Error('SD.cpp: unknown operation "' + operation + '"');
  248. }
  249. const credential = readCredential(config.credentialId);
  250. const token = login(server, credential, timeout);
  251. const body = {};
  252. if (operation === 'upscale') {
  253. // Upscale is not a generation call - it takes an image and the upscaler
  254. // slot, and none of the prompt or sampler fields apply.
  255. putIfSet(body, 'image_base64', config.initImageBase64);
  256. if (!body.image_base64) {
  257. throw new Error('SD.cpp: the upscale operation needs an init image, ' +
  258. 'given as base64 in the Init Image field');
  259. }
  260. putIfSet(body, 'upscale_factor', config.upscaleFactor);
  261. putIfSet(body, 'title', config.title);
  262. } else {
  263. putIfSet(body, 'prompt', config.prompt);
  264. if (!body.prompt) {
  265. throw new Error('SD.cpp: ' + operation + ' needs a prompt');
  266. }
  267. putIfSet(body, 'negative_prompt', config.negativePrompt);
  268. putIfSet(body, 'width', config.width);
  269. putIfSet(body, 'height', config.height);
  270. putIfSet(body, 'steps', config.steps);
  271. putIfSet(body, 'cfg_scale', config.cfgScale);
  272. putIfSet(body, 'sampler', config.sampler);
  273. putIfSet(body, 'scheduler', config.scheduler);
  274. putIfSet(body, 'seed', config.seed);
  275. putIfSet(body, 'batch_count', config.batchCount);
  276. putIfSet(body, 'clip_skip', config.clipSkip);
  277. putIfSet(body, 'title', config.title);
  278. if (operation === 'img2img' || operation === 'txt2vid') {
  279. putIfSet(body, 'init_image_base64', config.initImageBase64);
  280. putIfSet(body, 'strength', config.strength);
  281. }
  282. if (operation === 'img2img') {
  283. putIfSet(body, 'mask_image_base64', config.maskImageBase64);
  284. }
  285. if (operation === 'txt2vid') {
  286. putIfSet(body, 'video_frames', config.videoFrames);
  287. putIfSet(body, 'fps', config.fps);
  288. }
  289. if (operation === 'img2img' && !body.init_image_base64) {
  290. throw new Error('SD.cpp: img2img needs an init image, given as base64 in the ' +
  291. 'Init Image field');
  292. }
  293. }
  294. // The API has around seventy generation fields and this node exposes the
  295. // common ones. Anything else the user names here goes straight through, so
  296. // a new server field does not need a node change to be reachable.
  297. const extra = config.extraOptions;
  298. if (extra && typeof extra === 'object') {
  299. const keys = Object.keys(extra);
  300. for (let i = 0; i < keys.length; i++) {
  301. putIfSet(body, keys[i], extra[keys[i]]);
  302. }
  303. }
  304. const queued = call({
  305. method: 'POST',
  306. url: server + '/' + operation,
  307. headers: {
  308. 'Content-Type': 'application/json',
  309. 'Authorization': 'Bearer ' + token
  310. },
  311. body: JSON.stringify(body),
  312. timeout: timeout,
  313. what: 'queueing the ' + operation + ' job'
  314. });
  315. if (!queued.job_id) {
  316. throw new Error('SD.cpp: the ' + operation + ' job was accepted but no job id came back');
  317. }
  318. smartbotic.log.info('SD.cpp: queued ' + operation + ' job ' + queued.job_id +
  319. ' at position ' + (queued.position !== undefined ? queued.position : 'unknown'));
  320. return {
  321. jobId: queued.job_id,
  322. status: queued.status || 'pending',
  323. position: queued.position !== undefined ? queued.position : -1,
  324. operation: operation,
  325. request: body
  326. };
  327. }
  328. module.exports = { configSchema, inputSchema, outputSchema, execute };