sdcpp-upscaler-load.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * @node sdcpp-upscaler-load
  3. * @name SD.cpp Load Upscaler
  4. * @category sdcpp
  5. * @version 1.0.0
  6. * @description Make sure an upscaler is loaded, without reloading one that already is
  7. * @icon maximize
  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. modelName: {
  23. type: 'string', title: 'Upscaler',
  24. description: 'File name of the ESRGAN-family upscaler. Usually supplied by an SD.cpp Model node set to type esrgan'
  25. },
  26. force: {
  27. type: 'boolean', title: 'Force Reload',
  28. default: false,
  29. description: 'Load again even when this upscaler is already loaded'
  30. },
  31. timeout: { type: 'number', title: 'Timeout (ms)', default: 120000 }
  32. },
  33. required: []
  34. };
  35. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  36. const outputSchema = {
  37. type: 'object',
  38. properties: {
  39. upscalerName: { type: 'string' },
  40. loaded: { type: 'boolean', description: 'True when this node performed a load' },
  41. alreadyLoaded: { type: 'boolean' },
  42. previousUpscaler: { type: 'string' },
  43. elapsedMs: { type: 'number' }
  44. }
  45. };
  46. function normalizeServer(url) {
  47. const value = String(url || '').trim();
  48. if (!value) {
  49. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  50. }
  51. return value.replace(/\/+$/, '');
  52. }
  53. function readCredential(credentialId) {
  54. const auth = smartbotic.credentials.get(credentialId);
  55. if (!auth || auth.success !== true) {
  56. throw new Error('SD.cpp: could not read the credential: ' +
  57. ((auth && auth.error) || 'unknown error'));
  58. }
  59. const value = auth.headerValue || '';
  60. if (value.indexOf('Basic ') !== 0) {
  61. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  62. 'username and password');
  63. }
  64. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  65. const separator = decoded.indexOf(':');
  66. if (separator < 1) {
  67. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  68. }
  69. return {
  70. username: decoded.substring(0, separator),
  71. password: decoded.substring(separator + 1)
  72. };
  73. }
  74. function call(options) {
  75. const response = smartbotic.http.request(options);
  76. let body = response.data;
  77. if (typeof body === 'string' && body.length > 0) {
  78. try {
  79. body = JSON.parse(body);
  80. } catch (e) {
  81. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  82. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  83. ' with a body that is not JSON: ' + snippet);
  84. }
  85. }
  86. if (response.status < 200 || response.status >= 300) {
  87. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  88. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  89. }
  90. return body || {};
  91. }
  92. function login(server, credential, timeout) {
  93. const session = call({
  94. method: 'POST',
  95. url: server + '/auth/login',
  96. headers: { 'Content-Type': 'application/json' },
  97. body: JSON.stringify({
  98. username: credential.username,
  99. password: credential.password
  100. }),
  101. timeout: timeout,
  102. what: 'signing in'
  103. });
  104. if (!session.token) {
  105. throw new Error('SD.cpp: the server accepted the login but returned no token');
  106. }
  107. return session.token;
  108. }
  109. // /health is unauthenticated, and it is the only way to find out what is
  110. // already loaded without asking for a token first.
  111. function readHealth(server, timeout) {
  112. return call({
  113. method: 'GET',
  114. url: server + '/health',
  115. timeout: timeout,
  116. what: 'reading server health'
  117. });
  118. }
  119. function putIfSet(target, key, value) {
  120. if (value === undefined || value === null || value === '') {
  121. return;
  122. }
  123. target[key] = value;
  124. }
  125. async function execute(config, input, context) {
  126. const server = normalizeServer(config.serverUrl);
  127. const timeout = config.timeout > 0 ? config.timeout : 120000;
  128. const modelName = String(config.modelName || '').trim();
  129. if (!modelName) {
  130. throw new Error('SD.cpp: an upscaler name is required. Connect an SD.cpp Model node ' +
  131. 'set to type esrgan, or type the file name');
  132. }
  133. const startedAt = Date.now();
  134. const health = readHealth(server, Math.min(timeout, 15000));
  135. const current = health.upscaler_name || '';
  136. // The upscaler lives in its own slot, independent of the main model, so
  137. // loading one does not disturb whatever is generating.
  138. if (current === modelName && config.force !== true) {
  139. smartbotic.log.info('SD.cpp: upscaler ' + modelName + ' is already loaded');
  140. return {
  141. upscalerName: current,
  142. loaded: false,
  143. alreadyLoaded: true,
  144. previousUpscaler: '',
  145. elapsedMs: Date.now() - startedAt
  146. };
  147. }
  148. const credential = readCredential(config.credentialId);
  149. const token = login(server, credential, Math.min(timeout, 30000));
  150. call({
  151. method: 'POST',
  152. url: server + '/upscaler/load',
  153. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
  154. body: JSON.stringify({ model_name: modelName }),
  155. timeout: timeout,
  156. what: 'loading upscaler ' + modelName
  157. });
  158. smartbotic.log.info('SD.cpp: loaded upscaler ' + modelName);
  159. return {
  160. upscalerName: modelName,
  161. loaded: true,
  162. alreadyLoaded: false,
  163. previousUpscaler: current === modelName ? '' : current,
  164. elapsedMs: Date.now() - startedAt
  165. };
  166. }
  167. module.exports = { configSchema, inputSchema, outputSchema, execute };