sdcpp-model.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. // The kinds the server sorts its models into. Kept in step with the
  53. // type filter on GET /models.
  54. enum: ['checkpoint', 'diffusion', 'vae', 'lora', 'clip', 't5', 'embedding',
  55. 'controlnet', 'ip_adapter', 'llm', 'esrgan', 'taesd', 'motion_module',
  56. 'adetailer'],
  57. default: 'checkpoint',
  58. description: 'Which kind of model to choose from. esrgan is the upscaler kind'
  59. },
  60. modelName: {
  61. type: 'string', title: 'Model',
  62. description: 'Chosen from what the server has. Change the Kind above to list a different sort',
  63. dynamicOptions: {
  64. source: 'node',
  65. node: 'sdcpp-model',
  66. config: { listOnly: true },
  67. itemsPath: 'models',
  68. valueKey: 'name',
  69. labelKey: 'name',
  70. needs: ['serverUrl', 'credentialId', 'modelType']
  71. }
  72. },
  73. setting: {
  74. type: 'string', title: 'Supplies',
  75. 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'
  76. },
  77. timeout: { type: 'number', title: 'Timeout (ms)', default: 60000 }
  78. },
  79. required: []
  80. };
  81. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  82. const outputSchema = {
  83. type: 'object',
  84. properties: {
  85. _config: { type: 'object', description: 'The setting this supplies, as the engine consumes it' },
  86. modelName: { type: 'string', description: 'The chosen model' },
  87. modelType: { type: 'string' },
  88. setting: { type: 'string', description: 'Which setting it was supplied as' },
  89. models: { type: 'array', description: 'Everything of this kind the server has. Only filled when listing' },
  90. loadedModel: { type: 'string', description: 'What the server currently has loaded for this kind. Only present 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. const modelName = String(config.modelName || '').trim();
  263. if (!modelName) {
  264. throw new Error('SD.cpp Model: choose a model. Pick one from the list, which is read ' +
  265. 'from the server named above');
  266. }
  267. const values = {};
  268. const setting = String(config.setting || '').trim() ||
  269. SETTING_FOR_KIND[modelType] || 'modelName';
  270. values[setting] = modelName;
  271. smartbotic.log.info('SD.cpp Model: supplying ' + setting + ' = ' + modelName);
  272. // Same marker the Configurator uses, so this reaches a node through its
  273. // config input and replaces that node's own setting.
  274. return {
  275. _config: values,
  276. modelName: modelName,
  277. modelType: modelType,
  278. setting: setting,
  279. models: []
  280. };
  281. }
  282. module.exports = { configSchema, inputSchema, outputSchema, execute };