sdcpp-upscale.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /**
  2. * @node sdcpp-upscale
  3. * @name SD.cpp Upscale
  4. * @category sdcpp
  5. * @version 1.0.0
  6. * @description Enlarge an image with the loaded upscaler
  7. * @icon maximize-2
  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. // Generated from the server's own reference at /options/generation - see
  27. // scripts/gen-sdcpp-generation-options.py. Every field the endpoint accepts
  28. // has a setting here, grouped the way the server groups them.
  29. uiGroups: [
  30. {
  31. "title": "Server",
  32. "fields": [
  33. "serverUrl",
  34. "credentialId"
  35. ]
  36. },
  37. {
  38. "title": "/upscale Endpoint",
  39. "fields": [
  40. "imageBase64",
  41. "jobId",
  42. "imageIndex",
  43. "upscaleFactor",
  44. "tileSize",
  45. "repeats"
  46. ]
  47. },
  48. {
  49. "title": "Job",
  50. "fields": [
  51. "title",
  52. "extraOptions",
  53. "timeout"
  54. ]
  55. }
  56. ],
  57. prefill: {
  58. "label": "Take the architecture defaults",
  59. "description": "Fill these in from the preset for whichever model the server has loaded - the same values it would use if these were left empty",
  60. "node": "sdcpp-architecture",
  61. "needs": [
  62. "serverUrl",
  63. "credentialId"
  64. ],
  65. "map": {}
  66. },
  67. properties: {
  68. serverUrl: {
  69. type: 'string', title: 'Server URL',
  70. description: 'Base address of the sdcpp-restapi server',
  71. default: 'http://localhost:8077'
  72. },
  73. credentialId: {
  74. type: 'string', title: 'Credential',
  75. description: 'A basic credential holding the sdcpp-restapi username and password',
  76. dynamicOptions: { source: 'credentials', filter: { type: ['sdcpp', 'basic'] } }
  77. },
  78. imageBase64: { title: "Source Image (base64)", description: "Base64-encoded source image for upscaling. Recommended: Required. Leave empty for the architecture default.", type: "string" },
  79. imageIndex: { title: "Source Image Index", description: "Which output of the source job to upscale. Used with `job_id` when the source job produced multiple images (e.g. batch_count > 1). Ignored when `job_id` is absent. 0-based: 0 = first output. Recommended: Leave at 0 unless the source job had batch_count > 1 and you want a specific image. Leave empty for the architecture default.", type: "number" },
  80. jobId: { title: "Source Job ID", description: "Convenience: use the output of an existing completed job as the source for upscaling, instead of providing `image_base64`. handle_upscale loads `outputs[image_index]` from disk, base64-encodes it, and substitutes `image_base64` before the worker runs - so to the worker the two paths are indistinguishable. Recommended: Use this when chaining 'generate, then upscale' from a queued job. Leave empty for the architecture default.", type: "string" },
  81. repeats: { title: "Upscale Repeats", description: "Run the upscaler N times. With a 4× model: 1 pass = 4×, 2 passes = 16×. Recommended: 1. Leave empty for the architecture default.", type: "number" },
  82. tileSize: { title: "Upscale Tile Size", description: "Tile size for streaming the source image through the upscaler. Smaller = less VRAM, more boundary artifacts. 0 = whole-image. Recommended: 128 default. Drop to 64 if hitting VRAM limits. Leave empty for the architecture default.", type: "number" },
  83. upscaleFactor: { title: "Upscale Factor", description: "Target upscale factor. 4 = 4× the source image (default for ESRGAN). Recommended: Match the loaded upscaler's native factor (4 for most ESRGAN variants). Leave empty for the architecture default.", type: "number" },
  84. title: { type: "string", title: "Job Title", description: "Optional label stored with the job, useful for finding it again in the queue" },
  85. extraOptions: { type: "object", title: "Extra Options", description: "Any other generation field passed straight through. Everything the server documents already has a setting above, so this is only needed for a field a newer server has gained" },
  86. timeout: { type: "number", title: "Timeout (ms)", description: "Applies to queueing the job, not to the render. The call returns as soon as the job is accepted", default: 30000 }
  87. },
  88. required: ['credentialId']
  89. };
  90. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  91. const outputSchema = {
  92. type: 'object',
  93. properties: {
  94. jobId: { type: 'string', description: 'Id of the queued job, to pass to SD.cpp Wait For Job' },
  95. status: { type: 'string', description: 'Queue status when the job was accepted, normally pending' },
  96. position: { type: 'number', description: 'Place in the queue' },
  97. request: { type: 'object', description: 'The body actually sent, useful for seeing which defaults were left to the server' }
  98. }
  99. };
  100. function normalizeServer(url) {
  101. const value = String(url || '').trim();
  102. if (!value) {
  103. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  104. }
  105. return value.replace(/\/+$/, '');
  106. }
  107. function readCredential(credentialId) {
  108. const auth = smartbotic.credentials.get(credentialId);
  109. if (!auth || auth.success !== true) {
  110. throw new Error('SD.cpp: could not read the credential: ' +
  111. ((auth && auth.error) || 'unknown error'));
  112. }
  113. const value = auth.headerValue || '';
  114. if (value.indexOf('Basic ') !== 0) {
  115. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  116. 'username and password');
  117. }
  118. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  119. const separator = decoded.indexOf(':');
  120. if (separator < 1) {
  121. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  122. }
  123. return {
  124. username: decoded.substring(0, separator),
  125. password: decoded.substring(separator + 1)
  126. };
  127. }
  128. function call(options) {
  129. const response = smartbotic.http.request(options);
  130. let body = response.data;
  131. if (typeof body === 'string' && body.length > 0) {
  132. try {
  133. body = JSON.parse(body);
  134. } catch (e) {
  135. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  136. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  137. ' with a body that is not JSON: ' + snippet);
  138. }
  139. }
  140. if (response.status < 200 || response.status >= 300) {
  141. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  142. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  143. }
  144. return body || {};
  145. }
  146. function login(server, credential, timeout) {
  147. const session = call({
  148. method: 'POST',
  149. url: server + '/auth/login',
  150. headers: { 'Content-Type': 'application/json' },
  151. body: JSON.stringify({
  152. username: credential.username,
  153. password: credential.password
  154. }),
  155. timeout: timeout,
  156. what: 'signing in'
  157. });
  158. if (!session.token) {
  159. throw new Error('SD.cpp: the server accepted the login but returned no token');
  160. }
  161. return session.token;
  162. }
  163. // /health is unauthenticated, and it is the only way to find out what is
  164. // already loaded without asking for a token first.
  165. function readHealth(server, timeout) {
  166. return call({
  167. method: 'GET',
  168. url: server + '/health',
  169. timeout: timeout,
  170. what: 'reading server health'
  171. });
  172. }
  173. function putIfSet(target, key, value) {
  174. if (value === undefined || value === null || value === '') {
  175. return;
  176. }
  177. target[key] = value;
  178. }
  179. // Every generation field the server documents, and the setting it comes
  180. // from. Generated alongside the schema above so the two cannot drift.
  181. const GENERATION_OPTIONS = [
  182. { setting: "imageBase64", server: "image_base64" },
  183. { setting: "imageIndex", server: "image_index" },
  184. { setting: "jobId", server: "job_id" },
  185. { setting: "repeats", server: "repeats" },
  186. { setting: "tileSize", server: "tile_size" },
  187. { setting: "upscaleFactor", server: "upscale_factor" }
  188. ];
  189. // What the server accepts for each choice, as it described them when this
  190. // file was generated. See scripts/gen-sdcpp-generation-options.py.
  191. const KNOWN_CHOICES = {
  192. };
  193. async function execute(config, input, context) {
  194. const server = normalizeServer(config.serverUrl);
  195. const timeout = config.timeout || 30000;
  196. const credential = readCredential(config.credentialId);
  197. const token = login(server, credential, timeout);
  198. const body = {};
  199. // Built from the table above rather than field by field, so a setting the
  200. // server documents cannot be quietly missing from the request. A setting
  201. // left empty is left out of the body entirely: the server fills an absent
  202. // field from the loaded model's architecture preset, and sending an empty
  203. // box as 0 would override that preset with nonsense. The test is emptiness,
  204. // never truthiness - seed 0 and clip_skip 0 are legitimate values.
  205. for (let i = 0; i < GENERATION_OPTIONS.length; i++) {
  206. const option = GENERATION_OPTIONS[i];
  207. const value = config[option.setting];
  208. if (Array.isArray(value)) {
  209. // A list setting is usually filled with one entry holding an
  210. // expression for a whole list from an earlier node, which arrives
  211. // as a list inside a list. Left alone, the inner list is sent as a
  212. // single item and the server sees one nonsense value instead of
  213. // several - the same way a batch of two images once became one file
  214. // named "a.png,b.png".
  215. let flat = [];
  216. for (let j = 0; j < value.length; j++) {
  217. if (Array.isArray(value[j])) {
  218. flat = flat.concat(value[j]);
  219. } else if (value[j] !== undefined && value[j] !== null && value[j] !== '') {
  220. flat.push(value[j]);
  221. }
  222. }
  223. if (flat.length > 0) {
  224. body[option.server] = flat;
  225. }
  226. } else if (option.server === 'cache_mode' && value === 'off') {
  227. // The server reads an absent cache_mode as "use the architecture's
  228. // preference" and an empty one as "off". A dropdown cannot express
  229. // both with the same empty string, so "off" is sent as the explicit
  230. // empty the server wants - which is the only way to stop a preset
  231. // that switches caching on.
  232. body.cache_mode = '';
  233. } else {
  234. putIfSet(body, option.server, value);
  235. }
  236. }
  237. putIfSet(body, 'title', config.title);
  238. if (!body.image_base64) {
  239. throw new Error('SD.cpp: upscale needs an image');
  240. }
  241. // Anything else the API accepts, passed through, so a new server field does
  242. // not need a node change to be reachable.
  243. const extra = config.extraOptions;
  244. if (extra && typeof extra === 'object') {
  245. const keys = Object.keys(extra);
  246. for (let i = 0; i < keys.length; i++) {
  247. putIfSet(body, keys[i], extra[keys[i]]);
  248. }
  249. }
  250. const queued = call({
  251. method: 'POST',
  252. url: server + '/upscale',
  253. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
  254. body: JSON.stringify(body),
  255. timeout: timeout,
  256. what: 'queueing the upscale job'
  257. });
  258. if (!queued.job_id) {
  259. throw new Error('SD.cpp: the job was accepted but no job id came back');
  260. }
  261. smartbotic.log.info('SD.cpp: queued upscale job ' + queued.job_id);
  262. return {
  263. jobId: queued.job_id,
  264. status: queued.status || 'pending',
  265. position: queued.position !== undefined ? queued.position : -1,
  266. request: body
  267. };
  268. }
  269. module.exports = { configSchema, inputSchema, outputSchema, execute };