sdcpp-model.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /**
  2. * @node sdcpp-model
  3. * @name SD.cpp Model
  4. * @category sdcpp
  5. * @version 2.0.0
  6. * @description Pick a model from what the server has, and hand it to whichever node needs one
  7. * @icon layers
  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. The list of models is read from here',
  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. Listing models needs one',
  20. dynamicOptions: { source: 'credentials', filter: { type: ['basic'] } }
  21. },
  22. modelType: {
  23. type: 'string', title: 'Kind',
  24. enum: ['checkpoint', 'diffusion', 'vae', 'lora', 'clip', 't5', 'embedding',
  25. 'controlnet', 'llm', 'esrgan', 'taesd', 'motion_module', 'adetailer'],
  26. default: 'checkpoint',
  27. description: 'Which kind of model to choose from. esrgan is the upscaler kind'
  28. },
  29. modelName: {
  30. type: 'string', title: 'Model',
  31. description: 'Chosen from what the server has. Change the Kind above to list a different sort',
  32. dynamicOptions: {
  33. source: 'node',
  34. node: 'sdcpp-model',
  35. config: { listOnly: true },
  36. itemsPath: 'models',
  37. valueKey: 'name',
  38. labelKey: 'name',
  39. needs: ['serverUrl', 'credentialId', 'modelType']
  40. }
  41. },
  42. setting: {
  43. type: 'string', title: 'Supplies',
  44. description: 'The setting this fills in on the node it is connected to. Leave empty to use the ordinary name for the kind chosen - modelName for a checkpoint or diffusion model, vae, taesd, controlnet, llm and so on'
  45. },
  46. timeout: { type: 'number', title: 'Timeout (ms)', default: 60000 }
  47. },
  48. required: []
  49. };
  50. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  51. const outputSchema = {
  52. type: 'object',
  53. properties: {
  54. _config: { type: 'object', description: 'The setting this supplies, as the engine consumes it' },
  55. modelName: { type: 'string', description: 'The chosen model' },
  56. modelType: { type: 'string' },
  57. setting: { type: 'string', description: 'Which setting it was supplied as' },
  58. models: { type: 'array', description: 'Everything of this kind the server has. Only filled when listing' }
  59. }
  60. };
  61. // Which setting a kind of model ordinarily fills in. A checkpoint or a
  62. // diffusion model is the model itself; the rest are components named after
  63. // themselves. An upscaler is also "modelName", because SD.cpp Load Upscaler
  64. // takes it as its own model.
  65. const SETTING_FOR_KIND = {
  66. checkpoint: 'modelName',
  67. diffusion: 'modelName',
  68. esrgan: 'modelName',
  69. vae: 'vae',
  70. clip: 'clipL',
  71. t5: 't5xxl',
  72. llm: 'llm',
  73. taesd: 'taesd',
  74. controlnet: 'controlnet',
  75. motion_module: 'motionModule',
  76. lora: 'lora',
  77. embedding: 'embedding',
  78. adetailer: 'adetailer'
  79. };
  80. // The server groups models by kind under its own key names.
  81. const GROUP_FOR_KIND = {
  82. checkpoint: 'checkpoints',
  83. diffusion: 'diffusion_models',
  84. vae: 'vae',
  85. lora: 'loras',
  86. clip: 'clip',
  87. t5: 't5',
  88. embedding: 'embeddings',
  89. controlnet: 'controlnets',
  90. llm: 'llm',
  91. esrgan: 'esrgan',
  92. taesd: 'taesd',
  93. motion_module: 'motion_modules',
  94. adetailer: 'adetailers'
  95. };
  96. function normalizeServer(url) {
  97. const value = String(url || '').trim();
  98. if (!value) {
  99. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  100. }
  101. return value.replace(/\/+$/, '');
  102. }
  103. function readCredential(credentialId) {
  104. const auth = smartbotic.credentials.get(credentialId);
  105. if (!auth || auth.success !== true) {
  106. throw new Error('SD.cpp: could not read the credential: ' +
  107. ((auth && auth.error) || 'unknown error'));
  108. }
  109. const value = auth.headerValue || '';
  110. if (value.indexOf('Basic ') !== 0) {
  111. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  112. 'username and password');
  113. }
  114. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  115. const separator = decoded.indexOf(':');
  116. if (separator < 1) {
  117. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  118. }
  119. return {
  120. username: decoded.substring(0, separator),
  121. password: decoded.substring(separator + 1)
  122. };
  123. }
  124. function call(options) {
  125. const response = smartbotic.http.request(options);
  126. let body = response.data;
  127. if (typeof body === 'string' && body.length > 0) {
  128. try {
  129. body = JSON.parse(body);
  130. } catch (e) {
  131. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  132. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  133. ' with a body that is not JSON: ' + snippet);
  134. }
  135. }
  136. if (response.status < 200 || response.status >= 300) {
  137. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  138. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  139. }
  140. return body || {};
  141. }
  142. function login(server, credential, timeout) {
  143. const session = call({
  144. method: 'POST',
  145. url: server + '/auth/login',
  146. headers: { 'Content-Type': 'application/json' },
  147. body: JSON.stringify({
  148. username: credential.username,
  149. password: credential.password
  150. }),
  151. timeout: timeout,
  152. what: 'signing in'
  153. });
  154. if (!session.token) {
  155. throw new Error('SD.cpp: the server accepted the login but returned no token');
  156. }
  157. return session.token;
  158. }
  159. // /health is unauthenticated, and it is the only way to find out what is
  160. // already loaded without asking for a token first.
  161. function readHealth(server, timeout) {
  162. return call({
  163. method: 'GET',
  164. url: server + '/health',
  165. timeout: timeout,
  166. what: 'reading server health'
  167. });
  168. }
  169. function putIfSet(target, key, value) {
  170. if (value === undefined || value === null || value === '') {
  171. return;
  172. }
  173. target[key] = value;
  174. }
  175. function listModels(server, credentialId, modelType, timeout) {
  176. const credential = readCredential(credentialId);
  177. const token = login(server, credential, Math.min(timeout, 30000));
  178. const listed = call({
  179. method: 'GET',
  180. url: server + '/models?type=' + encodeURIComponent(modelType),
  181. headers: { 'Authorization': 'Bearer ' + token },
  182. timeout: timeout,
  183. what: 'listing ' + modelType + ' models'
  184. });
  185. const group = GROUP_FOR_KIND[modelType] || modelType;
  186. const entries = Array.isArray(listed[group]) ? listed[group] : [];
  187. const models = [];
  188. for (let i = 0; i < entries.length; i++) {
  189. const entry = entries[i];
  190. // Entries are sometimes plain file names and sometimes objects with a
  191. // name plus size and hash, so handle both rather than assuming one and
  192. // producing a list of undefined.
  193. if (entry && typeof entry === 'object') {
  194. models.push({ name: entry.name || entry.filename || '', details: entry });
  195. } else {
  196. models.push({ name: String(entry), details: null });
  197. }
  198. }
  199. return { models: models, loadedModel: listed.loaded_model || '' };
  200. }
  201. async function execute(config, input, context) {
  202. const server = normalizeServer(config.serverUrl);
  203. const timeout = config.timeout > 0 ? config.timeout : 60000;
  204. const modelType = config.modelType || 'checkpoint';
  205. // The editor asks for the list while a field is being filled in. It is not
  206. // what this node does during a run - a workflow that listed 358 models on
  207. // every execution would be paying for nothing.
  208. if (config.listOnly === true) {
  209. const listed = listModels(server, config.credentialId, modelType, timeout);
  210. return {
  211. modelName: '',
  212. modelType: modelType,
  213. setting: '',
  214. models: listed.models,
  215. loadedModel: listed.loadedModel
  216. };
  217. }
  218. const modelName = String(config.modelName || '').trim();
  219. if (!modelName) {
  220. throw new Error('SD.cpp Model: choose a model. Pick one from the list, which is read ' +
  221. 'from the server named above');
  222. }
  223. const setting = String(config.setting || '').trim() ||
  224. SETTING_FOR_KIND[modelType] || 'modelName';
  225. const values = {};
  226. values[setting] = modelName;
  227. smartbotic.log.info('SD.cpp Model: supplying ' + setting + ' = ' + modelName);
  228. // Same marker the Configurator uses, so this reaches a node through its
  229. // config input and replaces that node's own setting.
  230. return {
  231. _config: values,
  232. modelName: modelName,
  233. modelType: modelType,
  234. setting: setting,
  235. models: []
  236. };
  237. }
  238. module.exports = { configSchema, inputSchema, outputSchema, execute };