kie.mjs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env node
  2. /**
  3. * scrollcraft asset generator: kie.ai unified jobs API.
  4. *
  5. * POST https://api.kie.ai/api/v1/jobs/createTask { model, input }
  6. * GET https://api.kie.ai/api/v1/jobs/recordInfo?taskId=...
  7. *
  8. * COMMANDS
  9. * still <prompt> <out.png> [--ar 16:9] [--ref a.png]
  10. * seedream/5-pro-text-to-image (or -image-to-image with --ref).
  11. * Photoreal by default. Stills are cheap; generate, look, reroll.
  12. *
  13. * shot <prompt> <in.png> <out.mp4> [--tail b.png] [--dur 5]
  14. * kling/v2-1-pro image-to-video. --tail pins the LAST frame, which is
  15. * the whole trick behind a seamless chain: leg N's tail is leg N+1's
  16. * head, so the cut between them is frame-identical and invisible.
  17. *
  18. * probe print account credit and exit.
  19. *
  20. * Env: KIE_AI_API_KEY, read from the project-root .env if not already set.
  21. */
  22. import fs from "node:fs";
  23. import path from "node:path";
  24. const API = "https://api.kie.ai";
  25. const UPLOAD = "https://kieai.redpandaai.co/api/file-base64-upload";
  26. const MODELS = {
  27. still: "seedream/5-pro-text-to-image",
  28. stillEdit: "seedream/5-pro-image-to-image",
  29. shot: "kling/v2-1-pro",
  30. };
  31. // ---------------------------------------------------------------- key ----
  32. function findEnv(start) {
  33. let dir = path.resolve(start);
  34. for (let i = 0; i < 8; i++) {
  35. const p = path.join(dir, ".env");
  36. if (fs.existsSync(p)) return p;
  37. const up = path.dirname(dir);
  38. if (up === dir) break;
  39. dir = up;
  40. }
  41. return null;
  42. }
  43. function loadKey() {
  44. if (process.env.KIE_AI_API_KEY) return process.env.KIE_AI_API_KEY;
  45. const envPath = findEnv(process.cwd());
  46. if (!envPath) throw new Error("KIE_AI_API_KEY not set and no .env found walking up from " + process.cwd());
  47. for (const line of fs.readFileSync(envPath, "utf8").split(/\r?\n/)) {
  48. const m = line.match(/^\s*KIE_AI_API_KEY\s*=\s*(.+?)\s*$/);
  49. if (m) return m[1].replace(/^["']|["']$/g, "");
  50. }
  51. throw new Error("KIE_AI_API_KEY not found in " + envPath);
  52. }
  53. const KEY = loadKey();
  54. const H = { "Content-Type": "application/json", Authorization: `Bearer ${KEY}` };
  55. // ------------------------------------------------------------- helpers ----
  56. const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  57. async function uploadLocal(file) {
  58. const abs = path.resolve(file);
  59. if (!fs.existsSync(abs)) throw new Error("input not found: " + abs);
  60. const ext = path.extname(abs).slice(1).toLowerCase();
  61. const mime = ext === "jpg" ? "image/jpeg" : `image/${ext}`;
  62. const dataUrl = `data:${mime};base64,${fs.readFileSync(abs).toString("base64")}`;
  63. const res = await fetch(UPLOAD, {
  64. method: "POST", headers: H,
  65. body: JSON.stringify({ base64Data: dataUrl, uploadPath: "scrollcraft", fileName: path.basename(abs) }),
  66. });
  67. const j = await res.json();
  68. const url = j?.data?.downloadUrl || j?.data?.fileUrl || j?.data?.url;
  69. if (!url) throw new Error("upload failed: " + JSON.stringify(j));
  70. return url;
  71. }
  72. // A local path becomes a hosted URL; an http(s) string passes straight through.
  73. const asUrl = (v) => (/^https?:\/\//i.test(v) ? Promise.resolve(v) : uploadLocal(v));
  74. async function createTask(model, input) {
  75. const res = await fetch(`${API}/api/v1/jobs/createTask`, {
  76. method: "POST", headers: H, body: JSON.stringify({ model, input }),
  77. });
  78. const j = await res.json();
  79. if (j.code !== 200 || !j?.data?.taskId) throw new Error(`createTask ${model}: ${JSON.stringify(j)}`);
  80. return j.data.taskId;
  81. }
  82. async function waitTask(taskId, { label = "job", timeoutMs = 15 * 60 * 1000 } = {}) {
  83. const t0 = Date.now();
  84. let delay = 4000;
  85. for (;;) {
  86. if (Date.now() - t0 > timeoutMs) throw new Error(`${label}: timed out after ${Math.round((Date.now() - t0) / 1000)}s`);
  87. const res = await fetch(`${API}/api/v1/jobs/recordInfo?taskId=${encodeURIComponent(taskId)}`, { headers: H });
  88. const j = await res.json();
  89. const d = j?.data || {};
  90. const state = d.state || d.status;
  91. if (state === "success") {
  92. let out = d.resultJson;
  93. if (typeof out === "string") { try { out = JSON.parse(out); } catch {} }
  94. const urls = out?.resultUrls || out?.result_urls || out?.urls || [];
  95. if (!urls.length) throw new Error(`${label}: success with no result url: ${JSON.stringify(d)}`);
  96. return urls;
  97. }
  98. if (state === "fail" || state === "failed") {
  99. throw new Error(`${label} failed: ${d.failMsg || d.failCode || JSON.stringify(d)}`);
  100. }
  101. process.stderr.write(` ${label}: ${state || "queued"} (${Math.round((Date.now() - t0) / 1000)}s)\n`);
  102. await sleep(delay);
  103. delay = Math.min(delay * 1.25, 15000);
  104. }
  105. }
  106. async function download(url, out) {
  107. fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
  108. const res = await fetch(url);
  109. if (!res.ok) throw new Error(`download ${res.status} ${url}`);
  110. fs.writeFileSync(path.resolve(out), Buffer.from(await res.arrayBuffer()));
  111. return out;
  112. }
  113. function flag(argv, name, dflt = null) {
  114. const i = argv.indexOf(name);
  115. return i > -1 && argv[i + 1] ? argv[i + 1] : dflt;
  116. }
  117. function flags(argv, name) {
  118. const out = [];
  119. argv.forEach((a, i) => { if (a === name && argv[i + 1]) out.push(argv[i + 1]); });
  120. return out;
  121. }
  122. // ---------------------------------------------------------------- main ----
  123. const [cmd, ...rest] = process.argv.slice(2);
  124. try {
  125. if (cmd === "probe") {
  126. const r = await fetch(`${API}/api/v1/chat/credit`, { headers: H });
  127. const j = await r.json();
  128. console.log("credit:", j.data);
  129. } else if (cmd === "still") {
  130. const [prompt, out] = rest;
  131. if (!prompt || !out) throw new Error('usage: kie.mjs still "<prompt>" <out.png> [--ar 16:9] [--ref a.png]');
  132. const ar = flag(rest, "--ar", "16:9");
  133. const refs = flags(rest, "--ref");
  134. let model = MODELS.still;
  135. // aspect_ratio, quality and output_format are all required by seedream;
  136. // omitting any one returns a bare "This field is required" that does not
  137. // name the field, so keep them explicit rather than relying on defaults.
  138. const input = {
  139. prompt,
  140. aspect_ratio: ar,
  141. quality: flag(rest, "--quality", "high"),
  142. output_format: "png",
  143. nsfw_checker: false,
  144. };
  145. if (refs.length) {
  146. model = MODELS.stillEdit;
  147. input.image_urls = await Promise.all(refs.map(asUrl));
  148. }
  149. const id = await createTask(model, input);
  150. const urls = await waitTask(id, { label: path.basename(out) });
  151. await download(urls[0], out);
  152. console.log(out);
  153. } else if (cmd === "shot") {
  154. const [prompt, head, out] = rest;
  155. if (!prompt || !head || !out) {
  156. throw new Error('usage: kie.mjs shot "<prompt>" <head.png> <out.mp4> [--tail b.png] [--dur 5]');
  157. }
  158. const dur = flag(rest, "--dur", "5");
  159. const tail = flag(rest, "--tail");
  160. const input = {
  161. prompt,
  162. image_url: await asUrl(head),
  163. duration: String(dur),
  164. // Camera-move clips are graded on smoothness, so the negative prompt
  165. // targets exactly what breaks a scrub: judder, warping, cuts.
  166. negative_prompt: "blur, distortion, low quality, warping, morphing, jitter, flicker, text, watermark, cut, scene change",
  167. cfg_scale: 0.5,
  168. };
  169. if (tail) input.tail_image_url = await asUrl(tail);
  170. const id = await createTask(MODELS.shot, input);
  171. const urls = await waitTask(id, { label: path.basename(out), timeoutMs: 20 * 60 * 1000 });
  172. await download(urls[0], out);
  173. console.log(out);
  174. } else {
  175. console.error(`scrollcraft asset generator
  176. node kie.mjs probe
  177. node kie.mjs still "<prompt>" <out.png> [--ar 16:9] [--ref ref.png]
  178. node kie.mjs shot "<prompt>" <head.png> <out.mp4> [--tail tail.png] [--dur 5]
  179. `);
  180. process.exit(1);
  181. }
  182. } catch (err) {
  183. console.error("ERROR:", err.message);
  184. process.exit(1);
  185. }