sdcpp-model.js 11 KB

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