sdcpp-model.js 9.8 KB

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