sdcpp-img2img.js 11 KB

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