sdcpp-img2img.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /**
  2. * @node sdcpp-img2img
  3. * @name SD.cpp Image to Image
  4. * @category sdcpp
  5. * @version 1.0.0
  6. * @description Queue an image generation that starts from an existing image
  7. * @icon images
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. serverUrl: {
  13. type: 'string', title: 'Server URL',
  14. description: 'Base address of the sdcpp-restapi server',
  15. default: 'http://localhost:8077'
  16. },
  17. credentialId: {
  18. type: 'string', title: 'Credential',
  19. description: 'A basic credential holding the sdcpp-restapi username and password',
  20. dynamicOptions: { source: 'credentials', filter: { type: ['basic'] } }
  21. },
  22. prompt: {
  23. type: 'string', title: 'Prompt',
  24. description: 'What to generate. Supports {{variable}} interpolation, <lora:name:weight>, and {a|b|c} dynamic prompts which the server expands into one queue item per variation',
  25. format: 'textarea'
  26. },
  27. negativePrompt: {
  28. type: 'string', title: 'Negative Prompt',
  29. description: 'Concepts to exclude. Has no effect on LCM and one-step SDXS models',
  30. format: 'textarea'
  31. },
  32. initImageBase64: {
  33. type: 'string', title: 'Init Image (base64)',
  34. description: 'The image to start from, base64 without a data: prefix. Usually {{$json.files[0].data}} from a previous node'
  35. },
  36. maskImageBase64: {
  37. type: 'string', title: 'Mask (base64)',
  38. description: 'Inpainting mask. White marks the area to regenerate'
  39. },
  40. strength: {
  41. type: 'number', title: 'Strength',
  42. description: 'How far the result may move from the init image, 0 to 1. Higher changes more'
  43. },
  44. width: { type: 'number', title: 'Width', description: 'Leave empty to use the loaded architecture default' },
  45. height: { type: 'number', title: 'Height', description: 'Leave empty to use the loaded architecture default' },
  46. steps: { type: 'number', title: 'Steps', description: 'Leave empty for the architecture default - 4 for Flux Schnell and LCM, 20 for most others' },
  47. cfgScale: { type: 'number', title: 'CFG Scale', description: 'Leave empty for the architecture default. Distilled models such as Flux Schnell, LCM and Z-Image want 1.0' },
  48. sampler: {
  49. type: 'string', title: 'Sampler',
  50. enum: ['', 'euler', 'euler_a', 'heun', 'dpm2', 'dpm++2s_a', 'dpm++2m', 'dpm++2mv2',
  51. 'ipndm', 'ipndm_v', 'lcm', 'ddim_trailing', 'tcd', 'res_multistep', 'res_2s',
  52. 'er_sde', 'euler_cfg_pp', 'euler_a_cfg_pp', 'euler_ge'],
  53. default: '', description: 'Leave empty to use the architecture default'
  54. },
  55. scheduler: {
  56. type: 'string', title: 'Scheduler',
  57. enum: ['', 'discrete', 'karras', 'exponential', 'ays', 'gits', 'sgm_uniform',
  58. 'simple', 'smoothstep', 'kl_optimal', 'lcm', 'bong_tangent', 'ltx2'],
  59. default: '', description: 'Leave empty to use the architecture default'
  60. },
  61. seed: { type: 'number', title: 'Seed', description: 'Use -1 for a random seed. Any other value reproduces the same image' },
  62. batchCount: { type: 'number', title: 'Batch Count', description: 'How many to generate in this one job, all sharing the prompt' },
  63. clipSkip: { type: 'number', title: 'CLIP Skip', description: 'Skip the last N CLIP layers. Negative means the model default' },
  64. title: { type: 'string', title: 'Job Title', description: 'Optional label stored with the job, useful for finding it again in the queue' },
  65. extraOptions: {
  66. type: 'object', title: 'Extra Options',
  67. description: 'Any other generation field passed straight through, such as slg_scale, cache_mode or vae_tiling. See /options/generation on the server for the full list'
  68. },
  69. timeout: {
  70. type: 'number', title: 'Timeout (ms)',
  71. description: 'Applies to queueing the job, not to the render. The call returns as soon as the job is accepted',
  72. default: 30000
  73. }
  74. },
  75. required: ['credentialId']
  76. };
  77. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  78. const outputSchema = {
  79. type: 'object',
  80. properties: {
  81. jobId: { type: 'string', description: 'Id of the queued job, to pass to SD.cpp Wait For Job' },
  82. status: { type: 'string', description: 'Queue status when the job was accepted, normally pending' },
  83. position: { type: 'number', description: 'Place in the queue' },
  84. request: { type: 'object', description: 'The body actually sent, useful for seeing which defaults were left to the server' }
  85. }
  86. };
  87. function normalizeServer(url) {
  88. const value = String(url || '').trim();
  89. if (!value) {
  90. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  91. }
  92. return value.replace(/\/+$/, '');
  93. }
  94. function readCredential(credentialId) {
  95. const auth = smartbotic.credentials.get(credentialId);
  96. if (!auth || auth.success !== true) {
  97. throw new Error('SD.cpp: could not read the credential: ' +
  98. ((auth && auth.error) || 'unknown error'));
  99. }
  100. const value = auth.headerValue || '';
  101. if (value.indexOf('Basic ') !== 0) {
  102. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  103. 'username and password');
  104. }
  105. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  106. const separator = decoded.indexOf(':');
  107. if (separator < 1) {
  108. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  109. }
  110. return {
  111. username: decoded.substring(0, separator),
  112. password: decoded.substring(separator + 1)
  113. };
  114. }
  115. function call(options) {
  116. const response = smartbotic.http.request(options);
  117. let body = response.data;
  118. if (typeof body === 'string' && body.length > 0) {
  119. try {
  120. body = JSON.parse(body);
  121. } catch (e) {
  122. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  123. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  124. ' with a body that is not JSON: ' + snippet);
  125. }
  126. }
  127. if (response.status < 200 || response.status >= 300) {
  128. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  129. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  130. }
  131. return body || {};
  132. }
  133. function login(server, credential, timeout) {
  134. const session = call({
  135. method: 'POST',
  136. url: server + '/auth/login',
  137. headers: { 'Content-Type': 'application/json' },
  138. body: JSON.stringify({
  139. username: credential.username,
  140. password: credential.password
  141. }),
  142. timeout: timeout,
  143. what: 'signing in'
  144. });
  145. if (!session.token) {
  146. throw new Error('SD.cpp: the server accepted the login but returned no token');
  147. }
  148. return session.token;
  149. }
  150. // /health is unauthenticated, and it is the only way to find out what is
  151. // already loaded without asking for a token first.
  152. function readHealth(server, timeout) {
  153. return call({
  154. method: 'GET',
  155. url: server + '/health',
  156. timeout: timeout,
  157. what: 'reading server health'
  158. });
  159. }
  160. function putIfSet(target, key, value) {
  161. if (value === undefined || value === null || value === '') {
  162. return;
  163. }
  164. target[key] = value;
  165. }
  166. // Width, steps, cfg_scale and the rest are architecture defaults: the server
  167. // fills them from the loaded model's preset when the field is absent. Sending an
  168. // empty box as 0 would override that preset with nonsense, so a field the user
  169. // did not fill is left out of the body entirely - and the test is emptiness,
  170. // never truthiness, because seed 0 and clip_skip 0 are legitimate values.
  171. async function execute(config, input, context) {
  172. const server = normalizeServer(config.serverUrl);
  173. const timeout = config.timeout || 30000;
  174. const credential = readCredential(config.credentialId);
  175. const token = login(server, credential, timeout);
  176. const body = {};
  177. putIfSet(body, 'prompt', config.prompt);
  178. if (!body.prompt) {
  179. throw new Error('SD.cpp: img2img needs a prompt');
  180. }
  181. putIfSet(body, 'negative_prompt', config.negativePrompt);
  182. putIfSet(body, 'width', config.width);
  183. putIfSet(body, 'height', config.height);
  184. putIfSet(body, 'steps', config.steps);
  185. putIfSet(body, 'cfg_scale', config.cfgScale);
  186. putIfSet(body, 'sampler', config.sampler);
  187. putIfSet(body, 'scheduler', config.scheduler);
  188. putIfSet(body, 'seed', config.seed);
  189. putIfSet(body, 'batch_count', config.batchCount);
  190. putIfSet(body, 'clip_skip', config.clipSkip);
  191. putIfSet(body, 'init_image_base64', config.initImageBase64);
  192. putIfSet(body, 'mask_image_base64', config.maskImageBase64);
  193. putIfSet(body, 'strength', config.strength);
  194. if (!body.init_image_base64) {
  195. throw new Error('SD.cpp: img2img needs an init image');
  196. }
  197. putIfSet(body, 'title', config.title);
  198. // Anything else the API accepts, passed through, so a new server field does
  199. // not need a node change to be reachable.
  200. const extra = config.extraOptions;
  201. if (extra && typeof extra === 'object') {
  202. const keys = Object.keys(extra);
  203. for (let i = 0; i < keys.length; i++) {
  204. putIfSet(body, keys[i], extra[keys[i]]);
  205. }
  206. }
  207. const queued = call({
  208. method: 'POST',
  209. url: server + '/img2img',
  210. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
  211. body: JSON.stringify(body),
  212. timeout: timeout,
  213. what: 'queueing the img2img job'
  214. });
  215. if (!queued.job_id) {
  216. throw new Error('SD.cpp: the job was accepted but no job id came back');
  217. }
  218. smartbotic.log.info('SD.cpp: queued img2img job ' + queued.job_id);
  219. return {
  220. jobId: queued.job_id,
  221. status: queued.status || 'pending',
  222. position: queued.position !== undefined ? queued.position : -1,
  223. request: body
  224. };
  225. }
  226. module.exports = { configSchema, inputSchema, outputSchema, execute };