sdcpp-upscaler-load.js 7.2 KB

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