sdcpp-model.js 13 KB

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