sdcpp-edit.js 11 KB

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