sdcpp-upscale.js 7.9 KB

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