sdcpp-txt2vid.js 10 KB

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