sdcpp-upscale.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /**
  2. * @node sdcpp-upscale
  3. * @name SD.cpp Upscale
  4. * @category sdcpp
  5. * @version 1.0.0
  6. * @description Enlarge an image with the loaded upscaler
  7. * @icon maximize-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. imageBase64: {
  23. type: 'string', title: 'Image (base64)',
  24. description: 'The image to enlarge, base64 without a data: prefix'
  25. },
  26. upscaleFactor: { type: 'number', title: 'Factor', description: 'How much to enlarge by' },
  27. repeats: { type: 'number', title: 'Repeats', description: 'Run the upscaler more than once' },
  28. tileSize: { type: 'number', title: 'Tile Size', description: 'Tile the work to fit in memory' },
  29. title: { type: 'string', title: 'Job Title', description: 'Optional label stored with the job, useful for finding it again in the queue' },
  30. extraOptions: {
  31. type: 'object', title: 'Extra Options',
  32. 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'
  33. },
  34. timeout: {
  35. type: 'number', title: 'Timeout (ms)',
  36. description: 'Applies to queueing the job, not to the render. The call returns as soon as the job is accepted',
  37. default: 30000
  38. }
  39. },
  40. required: ['credentialId']
  41. };
  42. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  43. const outputSchema = {
  44. type: 'object',
  45. properties: {
  46. jobId: { type: 'string', description: 'Id of the queued job, to pass to SD.cpp Wait For Job' },
  47. status: { type: 'string', description: 'Queue status when the job was accepted, normally pending' },
  48. position: { type: 'number', description: 'Place in the queue' },
  49. request: { type: 'object', description: 'The body actually sent, useful for seeing which defaults were left to the server' }
  50. }
  51. };
  52. function normalizeServer(url) {
  53. const value = String(url || '').trim();
  54. if (!value) {
  55. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  56. }
  57. return value.replace(/\/+$/, '');
  58. }
  59. function readCredential(credentialId) {
  60. const auth = smartbotic.credentials.get(credentialId);
  61. if (!auth || auth.success !== true) {
  62. throw new Error('SD.cpp: could not read the credential: ' +
  63. ((auth && auth.error) || 'unknown error'));
  64. }
  65. const value = auth.headerValue || '';
  66. if (value.indexOf('Basic ') !== 0) {
  67. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  68. 'username and password');
  69. }
  70. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  71. const separator = decoded.indexOf(':');
  72. if (separator < 1) {
  73. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  74. }
  75. return {
  76. username: decoded.substring(0, separator),
  77. password: decoded.substring(separator + 1)
  78. };
  79. }
  80. function call(options) {
  81. const response = smartbotic.http.request(options);
  82. let body = response.data;
  83. if (typeof body === 'string' && body.length > 0) {
  84. try {
  85. body = JSON.parse(body);
  86. } catch (e) {
  87. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  88. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  89. ' with a body that is not JSON: ' + snippet);
  90. }
  91. }
  92. if (response.status < 200 || response.status >= 300) {
  93. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  94. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  95. }
  96. return body || {};
  97. }
  98. function login(server, credential, timeout) {
  99. const session = call({
  100. method: 'POST',
  101. url: server + '/auth/login',
  102. headers: { 'Content-Type': 'application/json' },
  103. body: JSON.stringify({
  104. username: credential.username,
  105. password: credential.password
  106. }),
  107. timeout: timeout,
  108. what: 'signing in'
  109. });
  110. if (!session.token) {
  111. throw new Error('SD.cpp: the server accepted the login but returned no token');
  112. }
  113. return session.token;
  114. }
  115. // /health is unauthenticated, and it is the only way to find out what is
  116. // already loaded without asking for a token first.
  117. function readHealth(server, timeout) {
  118. return call({
  119. method: 'GET',
  120. url: server + '/health',
  121. timeout: timeout,
  122. what: 'reading server health'
  123. });
  124. }
  125. function putIfSet(target, key, value) {
  126. if (value === undefined || value === null || value === '') {
  127. return;
  128. }
  129. target[key] = value;
  130. }
  131. // Width, steps, cfg_scale and the rest are architecture defaults: the server
  132. // fills them from the loaded model's preset when the field is absent. Sending an
  133. // empty box as 0 would override that preset with nonsense, so a field the user
  134. // did not fill is left out of the body entirely - and the test is emptiness,
  135. // never truthiness, because seed 0 and clip_skip 0 are legitimate values.
  136. async function execute(config, input, context) {
  137. const server = normalizeServer(config.serverUrl);
  138. const timeout = config.timeout || 30000;
  139. const credential = readCredential(config.credentialId);
  140. const token = login(server, credential, timeout);
  141. const body = {};
  142. putIfSet(body, 'image_base64', config.imageBase64);
  143. putIfSet(body, 'upscale_factor', config.upscaleFactor);
  144. putIfSet(body, 'repeats', config.repeats);
  145. putIfSet(body, 'tile_size', config.tileSize);
  146. if (!body.image_base64) {
  147. throw new Error('SD.cpp: upscale needs an image');
  148. }
  149. putIfSet(body, 'title', config.title);
  150. // Anything else the API accepts, passed through, so a new server field does
  151. // not need a node change to be reachable.
  152. const extra = config.extraOptions;
  153. if (extra && typeof extra === 'object') {
  154. const keys = Object.keys(extra);
  155. for (let i = 0; i < keys.length; i++) {
  156. putIfSet(body, keys[i], extra[keys[i]]);
  157. }
  158. }
  159. const queued = call({
  160. method: 'POST',
  161. url: server + '/upscale',
  162. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
  163. body: JSON.stringify(body),
  164. timeout: timeout,
  165. what: 'queueing the upscale job'
  166. });
  167. if (!queued.job_id) {
  168. throw new Error('SD.cpp: the job was accepted but no job id came back');
  169. }
  170. smartbotic.log.info('SD.cpp: queued upscale job ' + queued.job_id);
  171. return {
  172. jobId: queued.job_id,
  173. status: queued.status || 'pending',
  174. position: queued.position !== undefined ? queued.position : -1,
  175. request: body
  176. };
  177. }
  178. module.exports = { configSchema, inputSchema, outputSchema, execute };