sdcpp-edit.js 11 KB

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