| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- // fmode-image — AI 配图生成库(纯 ESM、零依赖)
- // 七种模式:arch / app / scene / slide / explode / product / detail
- import { readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
- import { homedir } from 'node:os';
- import { join, resolve } from 'node:path';
- import { fileURLToPath } from 'node:url';
- import {
- DEFAULT_MODEL, MODEL_INFO, env, resolveModels, validateSize, estimateCost, apiBase,
- } from './config.mjs';
- export { DEFAULT_MODEL, MODEL_INFO, validateSize, estimateCost, apiBase, resolveModels, FALLBACK_STATUS } from './config.mjs';
- // 模式默认尺寸的单价(倍率 1.0,人民币/张)
- function costOf(size) {
- return estimateCost(size, DEFAULT_MODEL) ?? 0;
- }
- const LANDSCAPE = '1792x1024';
- const SQUARE = '1024x1024';
- // ===== 模式注册表 =====
- // 键是短名(arch),命令行参数和旧式 flag(--arch)都归一到短名
- export const MODES = {
- arch: {
- prefix: '纯白背景扁平风格架构图。',
- suffix: '简洁扁平商务风格,纯白背景适合PPT。',
- size: LANDSCAPE, cost: costOf(LANDSCAPE), desc: '架构/分层/闭环图',
- },
- app: {
- prefix: '现代SaaS应用界面截图,浅色主题。',
- suffix: '界面细节清晰锐利,中文界面文字,像真实在运行的产品。',
- size: LANDSCAPE, cost: costOf(LANDSCAPE), desc: '产品界面(表现力最强)',
- },
- explode: {
- prefix: '技术爆炸图,内部分层剖开并标注数据流向。',
- suffix: '扁平科技风格,纯白背景,层级与流向清晰。',
- size: LANDSCAPE, cost: costOf(LANDSCAPE), desc: '内部运转/拆解图',
- },
- product: {
- prefix: '产品设计效果图,纯白背景,多角度组合渲染。',
- suffix: '工业设计质感,材质细腻,白底适合PPT,写实渲染。',
- size: LANDSCAPE, cost: costOf(LANDSCAPE), desc: '产品设计图(硬件/工业)',
- },
- scene: {
- prefix: '扁平插画场景。',
- suffix: '清新明亮风格。',
- size: SQUARE, cost: costOf(SQUARE), desc: '场景/人物/痛点插图',
- },
- detail: {
- prefix: '精密细节特写图。',
- suffix: '写实质感,清晰锐利。',
- size: SQUARE, cost: costOf(SQUARE), desc: '零件/材质/实物特写',
- },
- slide: {
- prefix: '一页16:9演示幻灯片。',
- suffix: '留白充足,字号层级分明,商务演示风格。',
- size: '1920x1088', cost: costOf('1920x1088'), desc: '整页PPT直接使用',
- },
- };
- export const MODE_NAMES = Object.keys(MODES);
- // '--arch' / 'arch' / 'ARCH' → 'arch';未知返回 null
- export function normalizeMode(mode) {
- if (!mode) return null;
- const key = String(mode).replace(/^-+/, '').toLowerCase();
- return MODES[key] ? key : null;
- }
- function modeConfig(mode) {
- const key = normalizeMode(mode);
- if (!key) throw new Error(`Unknown mode: ${mode}(可选:${MODE_NAMES.join(' / ')})`);
- return MODES[key];
- }
- // ===== 凭据自动获取 =====
- export function getApiKey() {
- const key = process.env.FMODE_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN || '';
- if (key && !key.includes('***') && key.length > 10) return key;
- try {
- const p = join(homedir(), '.fmode', 'config.json');
- if (existsSync(p)) {
- const c = JSON.parse(readFileSync(p, 'utf-8'));
- for (const k of ['api_key', 'FMODE_API_KEY', 'fmodeApiToken']) if (c[k]) return c[k];
- }
- } catch {}
- try {
- const p = join(homedir(), '.fmode', 'config.yaml');
- if (existsSync(p)) {
- for (const l of readFileSync(p, 'utf-8').split('\n')) {
- for (const kw of ['api_key', 'FMODE_API_KEY', 'fmodeApiToken']) {
- if (l.includes(kw)) {
- const v = l.split(':').slice(1).join(':').trim().replace(/["']/g, '');
- if (v && v !== '${FMODE_API_KEY}') return v;
- }
- }
- }
- }
- } catch {}
- const envFiles = [
- ...(env('FMODE_ENV_FILE') ? [env('FMODE_ENV_FILE')] : []),
- '.env',
- join(homedir(), '.env'),
- ];
- for (const p of envFiles) {
- try {
- if (!existsSync(p)) continue;
- for (const l of readFileSync(p, 'utf-8').split('\n')) {
- if (l.includes('FMODE_API_KEY')) {
- const v = l.split('=').slice(1).join('=').trim().replace(/["']/g, '');
- if (v && !v.includes('***') && v.length > 10) return v;
- }
- }
- } catch {}
- }
- throw new Error(
- 'No API Key found. Set FMODE_API_KEY env, or ~/.fmode/config.json {"api_key": "sk-..."}, '
- + 'or point FMODE_ENV_FILE at an .env file',
- );
- }
- // ===== HTTP 小工具 =====
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
- function apiError(resp, body) {
- const e = new Error(`API ${resp.status}: ${body.slice(0, 300)}`);
- e.status = resp.status;
- e.body = body;
- try { e.code = JSON.parse(body)?.error?.code; } catch {}
- return e;
- }
- async function download(url) {
- // 图已在服务端生成并计费,下载失败必须重试,不能丢弃
- const tries = Number(env('FMODE_IMAGE_DL_RETRIES') || 3);
- let lastErr;
- for (let i = 0; i <= tries; i++) {
- try {
- const r = await fetch(url, { signal: AbortSignal.timeout(Number(env('FMODE_IMAGE_DL_TIMEOUT_MS') || 120000)) });
- if (!r.ok) throw new Error(`Download failed: ${r.status}`);
- return Buffer.from(await r.arrayBuffer());
- } catch (e) {
- lastErr = e;
- if (i < tries) await sleep(2000 * (i + 1));
- }
- }
- throw lastErr;
- }
- // 只有「模型本身不可用」才换模型;429 限流、5xx 故障走重试
- function shouldFallback(err) {
- if (err.status === 400 || err.status === 404) return true;
- return err.status === 503 && /model_not_found|No available channel/i.test(err.body || '');
- }
- // ===== API 调用(纯 fetch,零依赖) =====
- // options.model 单模型;options.models 回退链;options.retries 单模型重试次数
- export async function callImageAPI(prompt, size, options = {}) {
- if (!validateSize(size)) {
- throw new Error(`Invalid size ${size}: width and height must both be divisible by 16`);
- }
- const key = getApiKey();
- const models = resolveModels(options);
- const retries = options.retries ?? Number(env('FMODE_IMAGE_RETRIES') || 0);
- const url = `${apiBase()}/v1/images/generations`;
- const errors = [];
- for (let mi = 0; mi < models.length; mi++) {
- const model = models[mi];
- for (let attempt = 0; attempt <= retries; attempt++) {
- const resp = await fetch(url, {
- method: 'POST',
- headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
- body: JSON.stringify({ model, prompt, n: 1, size }),
- signal: AbortSignal.timeout(Number(env('FMODE_IMAGE_GEN_TIMEOUT_MS') || 900000)),
- });
- if (resp.ok) {
- const data = await resp.json();
- let buf;
- if (data?.data?.[0]?.b64_json) buf = Buffer.from(data.data[0].b64_json, 'base64');
- else if (data?.data?.[0]?.url) buf = await download(data.data[0].url);
- else throw new Error(`Response has no image data (model=${model})`);
- return options.withModel ? { data: buf, model } : buf;
- }
- const err = apiError(resp, await resp.text().catch(() => ''));
- err.model = model;
- const retryable = err.status === 429 || (err.status >= 500 && !shouldFallback(err));
- if (retryable && attempt < retries) {
- await sleep(3000 * 2 ** attempt);
- continue;
- }
- errors.push(err);
- break;
- }
- const err = errors[errors.length - 1];
- const next = models[mi + 1];
- if (next && shouldFallback(err)) {
- console.warn(` WARN ${model} 不可用(${err.status} ${err.code || ''}),回退 ${next}`);
- continue;
- }
- break;
- }
- const last = errors[errors.length - 1];
- last.message = `${last.message} [model: ${models.slice(0, errors.length).join(' → ')}]`;
- throw last;
- }
- // ===== 统一生成 =====
- // gen('app', prompt, name, { size, model, models, retries, outDir, silent })
- export async function gen(mode, prompt, name = 'output', options = {}) {
- const cfg = modeConfig(mode);
- if (!prompt || !String(prompt).trim()) throw new Error('prompt required');
- const size = options.size || cfg.size;
- if (!validateSize(size)) {
- throw new Error(`Invalid size ${size}: width and height must both be divisible by 16`);
- }
- const models = resolveModels(options);
- const outdir = options.outDir || process.env.SKILL_IMAGE_OUTPUT || '.';
- const fullPrompt = `${cfg.prefix}${prompt} ${cfg.suffix}`;
- mkdirSync(outdir, { recursive: true });
- const outPath = resolve(outdir, `${name}.png`);
- if (!options.silent) process.stdout.write(` ${name}: `);
- const { data: imgData, model: usedModel } = await callImageAPI(fullPrompt, size, {
- models, retries: options.retries, withModel: true,
- });
- writeFileSync(outPath, imgData);
- if (!options.silent) {
- console.log(`OK ${cfg.desc} | ${Math.round(imgData.length / 1024)}KB | ${size} | ${usedModel}`);
- }
- return outPath;
- }
- export const genArch = (p, n, o) => gen('arch', p, n, o);
- export const genApp = (p, n, o) => gen('app', p, n, o);
- export const genExplode = (p, n, o) => gen('explode', p, n, o);
- export const genProduct = (p, n, o) => gen('product', p, n, o);
- export const genScene = (p, n, o) => gen('scene', p, n, o);
- export const genDetail = (p, n, o) => gen('detail', p, n, o);
- export const genSlide = (p, n, o) => gen('slide', p, n, o);
- // 批量生成:任务之间默认间隔 3s 避免限流
- // 接受 ['arch', 'name', 'prompt'] 或 { mode, name, prompt }
- export async function batch(tasks, options = {}) {
- const intervalMs = options.intervalMs ?? Number(env('FMODE_IMAGE_INTERVAL_MS') || 3000);
- const results = [];
- let total = 0;
- for (let i = 0; i < tasks.length; i++) {
- const t = Array.isArray(tasks[i])
- ? { mode: tasks[i][0], name: tasks[i][1], prompt: tasks[i][2] }
- : tasks[i];
- if (i > 0 && intervalMs > 0) await sleep(intervalMs);
- try {
- const path = await gen(t.mode, t.prompt, t.name ?? `image-${i + 1}`, options);
- results.push({ name: t.name, path, ok: true });
- total += MODES[normalizeMode(t.mode)]?.cost ?? 0;
- } catch (e) {
- console.error(` FAIL ${t.name}: ${e.message}`);
- results.push({ name: t.name, ok: false, error: e.message });
- }
- }
- const ok = results.filter((r) => r.ok).length;
- if (!options.silent) console.log(`\n完成 ${ok}/${tasks.length} | 约 ¥${total.toFixed(1)}`);
- return { ok, fail: results.length - ok, cost: total, results };
- }
- export default { gen, genArch, genApp, genExplode, genProduct, genScene, genDetail, genSlide, batch, MODES, MODEL_INFO, DEFAULT_MODEL };
- // ===== 向后兼容:直接执行本文件或 lib/fmode-image.mjs 时走 CLI =====
- // 不用顶层 await:lib → cli → lib 的动态 import 成环时,顶层 await 可能永不结算
- function isEntry(file) {
- return Boolean(process.argv[1]) && resolve(process.argv[1]) === resolve(file);
- }
- const self = fileURLToPath(import.meta.url);
- const legacy = fileURLToPath(new URL('./fmode-image.mjs', import.meta.url));
- if (isEntry(self) || isEntry(legacy)) {
- import('../bin/cli.mjs')
- .then(({ run }) => run(process.argv.slice(2)))
- .then((code) => process.exit(code))
- .catch((e) => {
- console.error(`Error: ${e.message}`);
- process.exit(1);
- });
- }
|