index.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // fmode-image — AI 配图生成库(纯 ESM、零依赖)
  2. // 七种模式:arch / app / scene / slide / explode / product / detail
  3. import { readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
  4. import { homedir } from 'node:os';
  5. import { join, resolve } from 'node:path';
  6. import { fileURLToPath } from 'node:url';
  7. import {
  8. DEFAULT_MODEL, MODEL_INFO, env, resolveModels, validateSize, estimateCost, apiBase,
  9. } from './config.mjs';
  10. export { DEFAULT_MODEL, MODEL_INFO, validateSize, estimateCost, apiBase, resolveModels, FALLBACK_STATUS } from './config.mjs';
  11. // 模式默认尺寸的单价(倍率 1.0,人民币/张)
  12. function costOf(size) {
  13. return estimateCost(size, DEFAULT_MODEL) ?? 0;
  14. }
  15. const LANDSCAPE = '1792x1024';
  16. const SQUARE = '1024x1024';
  17. // ===== 模式注册表 =====
  18. // 键是短名(arch),命令行参数和旧式 flag(--arch)都归一到短名
  19. export const MODES = {
  20. arch: {
  21. prefix: '纯白背景扁平风格架构图。',
  22. suffix: '简洁扁平商务风格,纯白背景适合PPT。',
  23. size: LANDSCAPE, cost: costOf(LANDSCAPE), desc: '架构/分层/闭环图',
  24. },
  25. app: {
  26. prefix: '现代SaaS应用界面截图,浅色主题。',
  27. suffix: '界面细节清晰锐利,中文界面文字,像真实在运行的产品。',
  28. size: LANDSCAPE, cost: costOf(LANDSCAPE), desc: '产品界面(表现力最强)',
  29. },
  30. explode: {
  31. prefix: '技术爆炸图,内部分层剖开并标注数据流向。',
  32. suffix: '扁平科技风格,纯白背景,层级与流向清晰。',
  33. size: LANDSCAPE, cost: costOf(LANDSCAPE), desc: '内部运转/拆解图',
  34. },
  35. product: {
  36. prefix: '产品设计效果图,纯白背景,多角度组合渲染。',
  37. suffix: '工业设计质感,材质细腻,白底适合PPT,写实渲染。',
  38. size: LANDSCAPE, cost: costOf(LANDSCAPE), desc: '产品设计图(硬件/工业)',
  39. },
  40. scene: {
  41. prefix: '扁平插画场景。',
  42. suffix: '清新明亮风格。',
  43. size: SQUARE, cost: costOf(SQUARE), desc: '场景/人物/痛点插图',
  44. },
  45. detail: {
  46. prefix: '精密细节特写图。',
  47. suffix: '写实质感,清晰锐利。',
  48. size: SQUARE, cost: costOf(SQUARE), desc: '零件/材质/实物特写',
  49. },
  50. slide: {
  51. prefix: '一页16:9演示幻灯片。',
  52. suffix: '留白充足,字号层级分明,商务演示风格。',
  53. size: '1920x1088', cost: costOf('1920x1088'), desc: '整页PPT直接使用',
  54. },
  55. };
  56. export const MODE_NAMES = Object.keys(MODES);
  57. // '--arch' / 'arch' / 'ARCH' → 'arch';未知返回 null
  58. export function normalizeMode(mode) {
  59. if (!mode) return null;
  60. const key = String(mode).replace(/^-+/, '').toLowerCase();
  61. return MODES[key] ? key : null;
  62. }
  63. function modeConfig(mode) {
  64. const key = normalizeMode(mode);
  65. if (!key) throw new Error(`Unknown mode: ${mode}(可选:${MODE_NAMES.join(' / ')})`);
  66. return MODES[key];
  67. }
  68. // ===== 凭据自动获取 =====
  69. export function getApiKey() {
  70. const key = process.env.FMODE_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN || '';
  71. if (key && !key.includes('***') && key.length > 10) return key;
  72. try {
  73. const p = join(homedir(), '.fmode', 'config.json');
  74. if (existsSync(p)) {
  75. const c = JSON.parse(readFileSync(p, 'utf-8'));
  76. for (const k of ['api_key', 'FMODE_API_KEY', 'fmodeApiToken']) if (c[k]) return c[k];
  77. }
  78. } catch {}
  79. try {
  80. const p = join(homedir(), '.fmode', 'config.yaml');
  81. if (existsSync(p)) {
  82. for (const l of readFileSync(p, 'utf-8').split('\n')) {
  83. for (const kw of ['api_key', 'FMODE_API_KEY', 'fmodeApiToken']) {
  84. if (l.includes(kw)) {
  85. const v = l.split(':').slice(1).join(':').trim().replace(/["']/g, '');
  86. if (v && v !== '${FMODE_API_KEY}') return v;
  87. }
  88. }
  89. }
  90. }
  91. } catch {}
  92. const envFiles = [
  93. ...(env('FMODE_ENV_FILE') ? [env('FMODE_ENV_FILE')] : []),
  94. '.env',
  95. join(homedir(), '.env'),
  96. ];
  97. for (const p of envFiles) {
  98. try {
  99. if (!existsSync(p)) continue;
  100. for (const l of readFileSync(p, 'utf-8').split('\n')) {
  101. if (l.includes('FMODE_API_KEY')) {
  102. const v = l.split('=').slice(1).join('=').trim().replace(/["']/g, '');
  103. if (v && !v.includes('***') && v.length > 10) return v;
  104. }
  105. }
  106. } catch {}
  107. }
  108. throw new Error(
  109. 'No API Key found. Set FMODE_API_KEY env, or ~/.fmode/config.json {"api_key": "sk-..."}, '
  110. + 'or point FMODE_ENV_FILE at an .env file',
  111. );
  112. }
  113. // ===== HTTP 小工具 =====
  114. const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  115. function apiError(resp, body) {
  116. const e = new Error(`API ${resp.status}: ${body.slice(0, 300)}`);
  117. e.status = resp.status;
  118. e.body = body;
  119. try { e.code = JSON.parse(body)?.error?.code; } catch {}
  120. return e;
  121. }
  122. async function download(url) {
  123. // 图已在服务端生成并计费,下载失败必须重试,不能丢弃
  124. const tries = Number(env('FMODE_IMAGE_DL_RETRIES') || 3);
  125. let lastErr;
  126. for (let i = 0; i <= tries; i++) {
  127. try {
  128. const r = await fetch(url, { signal: AbortSignal.timeout(Number(env('FMODE_IMAGE_DL_TIMEOUT_MS') || 120000)) });
  129. if (!r.ok) throw new Error(`Download failed: ${r.status}`);
  130. return Buffer.from(await r.arrayBuffer());
  131. } catch (e) {
  132. lastErr = e;
  133. if (i < tries) await sleep(2000 * (i + 1));
  134. }
  135. }
  136. throw lastErr;
  137. }
  138. // 只有「模型本身不可用」才换模型;429 限流、5xx 故障走重试
  139. function shouldFallback(err) {
  140. if (err.status === 400 || err.status === 404) return true;
  141. return err.status === 503 && /model_not_found|No available channel/i.test(err.body || '');
  142. }
  143. // ===== API 调用(纯 fetch,零依赖) =====
  144. // options.model 单模型;options.models 回退链;options.retries 单模型重试次数
  145. export async function callImageAPI(prompt, size, options = {}) {
  146. if (!validateSize(size)) {
  147. throw new Error(`Invalid size ${size}: width and height must both be divisible by 16`);
  148. }
  149. const key = getApiKey();
  150. const models = resolveModels(options);
  151. const retries = options.retries ?? Number(env('FMODE_IMAGE_RETRIES') || 0);
  152. const url = `${apiBase()}/v1/images/generations`;
  153. const errors = [];
  154. for (let mi = 0; mi < models.length; mi++) {
  155. const model = models[mi];
  156. for (let attempt = 0; attempt <= retries; attempt++) {
  157. const resp = await fetch(url, {
  158. method: 'POST',
  159. headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
  160. body: JSON.stringify({ model, prompt, n: 1, size }),
  161. signal: AbortSignal.timeout(Number(env('FMODE_IMAGE_GEN_TIMEOUT_MS') || 900000)),
  162. });
  163. if (resp.ok) {
  164. const data = await resp.json();
  165. let buf;
  166. if (data?.data?.[0]?.b64_json) buf = Buffer.from(data.data[0].b64_json, 'base64');
  167. else if (data?.data?.[0]?.url) buf = await download(data.data[0].url);
  168. else throw new Error(`Response has no image data (model=${model})`);
  169. return options.withModel ? { data: buf, model } : buf;
  170. }
  171. const err = apiError(resp, await resp.text().catch(() => ''));
  172. err.model = model;
  173. const retryable = err.status === 429 || (err.status >= 500 && !shouldFallback(err));
  174. if (retryable && attempt < retries) {
  175. await sleep(3000 * 2 ** attempt);
  176. continue;
  177. }
  178. errors.push(err);
  179. break;
  180. }
  181. const err = errors[errors.length - 1];
  182. const next = models[mi + 1];
  183. if (next && shouldFallback(err)) {
  184. console.warn(` WARN ${model} 不可用(${err.status} ${err.code || ''}),回退 ${next}`);
  185. continue;
  186. }
  187. break;
  188. }
  189. const last = errors[errors.length - 1];
  190. last.message = `${last.message} [model: ${models.slice(0, errors.length).join(' → ')}]`;
  191. throw last;
  192. }
  193. // ===== 统一生成 =====
  194. // gen('app', prompt, name, { size, model, models, retries, outDir, silent })
  195. export async function gen(mode, prompt, name = 'output', options = {}) {
  196. const cfg = modeConfig(mode);
  197. if (!prompt || !String(prompt).trim()) throw new Error('prompt required');
  198. const size = options.size || cfg.size;
  199. if (!validateSize(size)) {
  200. throw new Error(`Invalid size ${size}: width and height must both be divisible by 16`);
  201. }
  202. const models = resolveModels(options);
  203. const outdir = options.outDir || process.env.SKILL_IMAGE_OUTPUT || '.';
  204. const fullPrompt = `${cfg.prefix}${prompt} ${cfg.suffix}`;
  205. mkdirSync(outdir, { recursive: true });
  206. const outPath = resolve(outdir, `${name}.png`);
  207. if (!options.silent) process.stdout.write(` ${name}: `);
  208. const { data: imgData, model: usedModel } = await callImageAPI(fullPrompt, size, {
  209. models, retries: options.retries, withModel: true,
  210. });
  211. writeFileSync(outPath, imgData);
  212. if (!options.silent) {
  213. console.log(`OK ${cfg.desc} | ${Math.round(imgData.length / 1024)}KB | ${size} | ${usedModel}`);
  214. }
  215. return outPath;
  216. }
  217. export const genArch = (p, n, o) => gen('arch', p, n, o);
  218. export const genApp = (p, n, o) => gen('app', p, n, o);
  219. export const genExplode = (p, n, o) => gen('explode', p, n, o);
  220. export const genProduct = (p, n, o) => gen('product', p, n, o);
  221. export const genScene = (p, n, o) => gen('scene', p, n, o);
  222. export const genDetail = (p, n, o) => gen('detail', p, n, o);
  223. export const genSlide = (p, n, o) => gen('slide', p, n, o);
  224. // 批量生成:任务之间默认间隔 3s 避免限流
  225. // 接受 ['arch', 'name', 'prompt'] 或 { mode, name, prompt }
  226. export async function batch(tasks, options = {}) {
  227. const intervalMs = options.intervalMs ?? Number(env('FMODE_IMAGE_INTERVAL_MS') || 3000);
  228. const results = [];
  229. let total = 0;
  230. for (let i = 0; i < tasks.length; i++) {
  231. const t = Array.isArray(tasks[i])
  232. ? { mode: tasks[i][0], name: tasks[i][1], prompt: tasks[i][2] }
  233. : tasks[i];
  234. if (i > 0 && intervalMs > 0) await sleep(intervalMs);
  235. try {
  236. const path = await gen(t.mode, t.prompt, t.name ?? `image-${i + 1}`, options);
  237. results.push({ name: t.name, path, ok: true });
  238. total += MODES[normalizeMode(t.mode)]?.cost ?? 0;
  239. } catch (e) {
  240. console.error(` FAIL ${t.name}: ${e.message}`);
  241. results.push({ name: t.name, ok: false, error: e.message });
  242. }
  243. }
  244. const ok = results.filter((r) => r.ok).length;
  245. if (!options.silent) console.log(`\n完成 ${ok}/${tasks.length} | 约 ¥${total.toFixed(1)}`);
  246. return { ok, fail: results.length - ok, cost: total, results };
  247. }
  248. export default { gen, genArch, genApp, genExplode, genProduct, genScene, genDetail, genSlide, batch, MODES, MODEL_INFO, DEFAULT_MODEL };
  249. // ===== 向后兼容:直接执行本文件或 lib/fmode-image.mjs 时走 CLI =====
  250. // 不用顶层 await:lib → cli → lib 的动态 import 成环时,顶层 await 可能永不结算
  251. function isEntry(file) {
  252. return Boolean(process.argv[1]) && resolve(process.argv[1]) === resolve(file);
  253. }
  254. const self = fileURLToPath(import.meta.url);
  255. const legacy = fileURLToPath(new URL('./fmode-image.mjs', import.meta.url));
  256. if (isEntry(self) || isEntry(legacy)) {
  257. import('../bin/cli.mjs')
  258. .then(({ run }) => run(process.argv.slice(2)))
  259. .then((code) => process.exit(code))
  260. .catch((e) => {
  261. console.error(`Error: ${e.message}`);
  262. process.exit(1);
  263. });
  264. }