chore: 项目基线提交 - 拼豆图纸生成器 V1.0 核心代码
- 前端: React+Vite 首页/AI专区, 算法库(MARD色板/量化/背景去除), API对接 - 后端: Express+SQLite, 兑换码/订单/支付/chibi生成, 风控+云端同步 - CI/CD: GitHub Actions + Docker + nginx 配置 - 文档: PRD/DESIGN/LAUNCH/ROADMAP/E2E/竞品对照等 15 份 - 工程: 任务看板(taskboard) + 健康巡检(agent-health) + Git流程(gitflow)
This commit is contained in:
commit
02762400fb
174 files changed
+28059
No files matched your search
@@ -0,0 +1,279 @@
|
||||
/**
|
||||
* chibi AI 拼豆图像生成服务
|
||||
*
|
||||
* 流程: 先消耗一次兑换码次数(无剩余次数抛 生成次数不足) -> buildPrompt
|
||||
* 组装提示词 -> 调用 OpenAI 兼容图像接口 (AI_IMAGE_API_URL /
|
||||
* AI_IMAGE_API_KEY),未配置接口地址时使用内置 mock 模式生成占位图。
|
||||
*/
|
||||
import type Database from "better-sqlite3";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { deflateSync } from "node:zlib";
|
||||
import type { AccessInfo } from "../types/index.js";
|
||||
import { consumeCode, CodeError } from "../codes/service.js";
|
||||
import { buildPrompt, type ChibiCategory, type Composition } from "./prompts.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface GenerateRequest {
|
||||
/** 兑换码 */
|
||||
code: string;
|
||||
/** 用户上传的拼豆原图 (base64 dataURL) */
|
||||
image: string;
|
||||
/** 参考风格图 (base64 dataURL),可选 */
|
||||
referenceImage?: string;
|
||||
category: ChibiCategory;
|
||||
subtype: string;
|
||||
gridSize: number;
|
||||
colorCount: number;
|
||||
composition: Composition;
|
||||
detailTags: string[];
|
||||
customPrompt?: string;
|
||||
}
|
||||
|
||||
export interface GenerateResult {
|
||||
/** 生成的图像 (base64 dataURL) */
|
||||
image: string;
|
||||
/** 下载凭证 */
|
||||
downloadGrant: string;
|
||||
}
|
||||
|
||||
/** 生成成功时附带消耗后的 access 信息,供路由层返回。 */
|
||||
export type GenerateOutcome = GenerateResult & { access: AccessInfo };
|
||||
|
||||
export class ChibiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.name = "ChibiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock 占位图 (纯函数实现的最小合法 PNG: 纯色 RGB + gridSize 尺寸)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
}
|
||||
table[n] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(buf: Buffer): number {
|
||||
let c = 0xffffffff;
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
c = CRC_TABLE[(c ^ buf[i]!) & 0xff]! ^ (c >>> 8);
|
||||
}
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function pngChunk(type: string, data: Buffer): Buffer {
|
||||
const typeBuf = Buffer.from(type, "ascii");
|
||||
const header = Buffer.alloc(4);
|
||||
header.writeUInt32BE(data.length, 0);
|
||||
const crc = Buffer.alloc(4);
|
||||
crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
|
||||
return Buffer.concat([header, typeBuf, data, crc]);
|
||||
}
|
||||
|
||||
/** 生成 size×size 纯色 PNG,返回 base64 dataURL。 */
|
||||
function makePlaceholderPng(size: number, rgb: readonly [number, number, number]): string {
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(size, 0); // width
|
||||
ihdr.writeUInt32BE(size, 4); // height
|
||||
ihdr.writeUInt8(8, 8); // bit depth
|
||||
ihdr.writeUInt8(2, 9); // color type: truecolor RGB
|
||||
// bytes 10/11/12: compression / filter / interlace,默认 0
|
||||
|
||||
const row = Buffer.alloc(1 + size * 3);
|
||||
row.writeUInt8(0, 0); // filter: none
|
||||
for (let x = 0; x < size; x++) {
|
||||
row.writeUInt8(rgb[0], 1 + x * 3);
|
||||
row.writeUInt8(rgb[1], 2 + x * 3);
|
||||
row.writeUInt8(rgb[2], 3 + x * 3);
|
||||
}
|
||||
const raw = Buffer.concat(Array.from({ length: size }, () => row));
|
||||
const png = Buffer.concat([
|
||||
PNG_SIGNATURE,
|
||||
pngChunk("IHDR", ihdr),
|
||||
pngChunk("IDAT", deflateSync(raw)),
|
||||
pngChunk("IEND", Buffer.alloc(0)),
|
||||
]);
|
||||
return `data:image/png;base64,${png.toString("base64")}`;
|
||||
}
|
||||
|
||||
/** 每类一个主题色,mock 模式下占位图随分类变色,便于肉眼区分。 */
|
||||
const CATEGORY_COLORS: Record<ChibiCategory, readonly [number, number, number]> = {
|
||||
landscape: [96, 165, 250], // 天空蓝
|
||||
person: [251, 146, 60], // 活力橙
|
||||
pet: [167, 139, 250], // 香芋紫
|
||||
object: [52, 211, 153], // 抹茶绿
|
||||
food: [251, 113, 133], // 蜜桃粉
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AI 接口调用 (OpenAI 兼容)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 从 OpenAI 兼容响应中提取 base64 (或图像 url)。
|
||||
* 支持两种形态:
|
||||
* /v1/images/generations -> { data: [{ b64_json | url }] }
|
||||
* /v1/chat/completions -> { choices: [{ message: { images: [{ b64_json | url }] } }] }
|
||||
*/
|
||||
function extractImageBase64(payload: unknown): string | null {
|
||||
if (!payload || typeof payload !== "object") return null;
|
||||
const root = payload as Record<string, unknown>;
|
||||
|
||||
const data = Array.isArray(root["data"]) ? root["data"] : [];
|
||||
const first = data[0] as Record<string, unknown> | undefined;
|
||||
if (first) {
|
||||
if (typeof first["b64_json"] === "string") return first["b64_json"];
|
||||
if (typeof first["url"] === "string") return first["url"];
|
||||
}
|
||||
|
||||
const choices = Array.isArray(root["choices"]) ? root["choices"] : [];
|
||||
const choice = choices[0] as Record<string, unknown> | undefined;
|
||||
const message = choice?.["message"] as Record<string, unknown> | undefined;
|
||||
const images = Array.isArray(message?.["images"]) ? message["images"] : [];
|
||||
const image = images[0] as Record<string, unknown> | undefined;
|
||||
if (image) {
|
||||
if (typeof image["b64_json"] === "string") return image["b64_json"];
|
||||
if (typeof image["url"] === "string") return image["url"];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function requestAiImage(prompt: string, req: GenerateRequest): Promise<string> {
|
||||
const apiUrl = process.env["AI_IMAGE_API_URL"];
|
||||
const apiKey = process.env["AI_IMAGE_API_KEY"];
|
||||
const model = process.env["AI_IMAGE_MODEL"] ?? "gpt-image-1";
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
|
||||
|
||||
// chat/completions 走多模态消息 (携带原图/参考图),images/generations 走纯提示词
|
||||
const isChat = (apiUrl ?? "").includes("/chat/completions");
|
||||
let payload: unknown;
|
||||
if (isChat) {
|
||||
const content: Array<Record<string, unknown>> = [{ type: "text", text: prompt }];
|
||||
for (const img of [req.image, req.referenceImage]) {
|
||||
if (img && img.startsWith("data:")) {
|
||||
content.push({ type: "image_url", image_url: { url: img } });
|
||||
}
|
||||
}
|
||||
payload = { model, messages: [{ role: "user", content }] };
|
||||
} else {
|
||||
payload = {
|
||||
model,
|
||||
prompt,
|
||||
n: 1,
|
||||
size: `${req.gridSize}x${req.gridSize}`,
|
||||
response_format: "b64_json",
|
||||
};
|
||||
}
|
||||
|
||||
let res: Awaited<ReturnType<typeof fetch>>;
|
||||
try {
|
||||
res = await fetch(apiUrl!, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("chibi AI image request failed:", err);
|
||||
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
|
||||
}
|
||||
if (!res.ok) {
|
||||
console.error("chibi AI image api error:", res.status, await res.text().catch(() => ""));
|
||||
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
|
||||
}
|
||||
|
||||
const raw = (await res.json().catch(() => null)) as unknown;
|
||||
const b64OrUrl = extractImageBase64(raw);
|
||||
if (!b64OrUrl) {
|
||||
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
|
||||
}
|
||||
if (b64OrUrl.startsWith("http://") || b64OrUrl.startsWith("https://")) {
|
||||
// 接口返回 url 时下载并转为 base64 dataURL
|
||||
let imgRes: Awaited<ReturnType<typeof fetch>>;
|
||||
try {
|
||||
imgRes = await fetch(b64OrUrl, { signal: AbortSignal.timeout(60_000) });
|
||||
} catch (err) {
|
||||
console.error("chibi AI image download failed:", err);
|
||||
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
|
||||
}
|
||||
if (!imgRes.ok) {
|
||||
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
|
||||
}
|
||||
const buf = Buffer.from(await imgRes.arrayBuffer());
|
||||
const type = imgRes.headers.get("content-type") ?? "image/png";
|
||||
return `data:${type};base64,${buf.toString("base64")}`;
|
||||
}
|
||||
return b64OrUrl.startsWith("data:") ? b64OrUrl : `data:image/png;base64,${b64OrUrl}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成图像。未配置 AI_IMAGE_API_URL 时进入 mock 模式,返回 gridSize
|
||||
* 尺寸的纯色占位 PNG (dataURL)。
|
||||
*/
|
||||
async function generateImage(prompt: string, req: GenerateRequest): Promise<string> {
|
||||
const apiUrl = process.env["AI_IMAGE_API_URL"];
|
||||
if (!apiUrl) {
|
||||
return makePlaceholderPng(req.gridSize, CATEGORY_COLORS[req.category]);
|
||||
}
|
||||
return requestAiImage(prompt, req);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 主入口
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 生成 chibi 拼豆图。先原子消耗一次兑换码次数(无剩余次数时抛出
|
||||
* ChibiError "生成次数不足", 402),再调用 AI 接口。
|
||||
*/
|
||||
export async function generateChibiImage(
|
||||
db: Database.Database,
|
||||
req: GenerateRequest,
|
||||
): Promise<GenerateOutcome> {
|
||||
// 1. 组装提示词
|
||||
const prompt = buildPrompt({
|
||||
category: req.category,
|
||||
subtype: req.subtype,
|
||||
gridSize: req.gridSize,
|
||||
colorCount: req.colorCount,
|
||||
composition: req.composition,
|
||||
detailTags: req.detailTags,
|
||||
customPrompt: req.customPrompt,
|
||||
hasReferenceImage: req.referenceImage !== undefined && req.referenceImage !== "",
|
||||
});
|
||||
|
||||
// 2. 消耗一次次数 (原子校验 + 扣减)
|
||||
let access: AccessInfo;
|
||||
try {
|
||||
access = consumeCode(db, req.code);
|
||||
} catch (err) {
|
||||
if (err instanceof CodeError) {
|
||||
// 未找到 / 禁用 / 过期 / 用尽 统一视为无法生成
|
||||
throw new ChibiError("生成次数不足", 402);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
// 3. 生成图片
|
||||
const image = await generateImage(prompt, req);
|
||||
|
||||
return { image, downloadGrant: randomUUID(), access };
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* chibi AI 拼豆提示词模板库
|
||||
*
|
||||
* 5 大类 × 3 细分 = 15 套模板,参数来自竞品逆向(copy-library.md):
|
||||
* - 分类: 风景/人物/宠物/物品/食物
|
||||
* - 参数: gridSize 48/64/80/96 · colorCount 16/24/32/40 · 构图 3 种
|
||||
*/
|
||||
|
||||
export type ChibiCategory = "landscape" | "person" | "pet" | "object" | "food";
|
||||
export type Composition = "主体特写" | "半幅构图" | "完整构图";
|
||||
|
||||
export interface ChibiTemplate {
|
||||
category: ChibiCategory;
|
||||
categoryName: string;
|
||||
subtype: string;
|
||||
subtypeName: string;
|
||||
note: string;
|
||||
basePrompt: string;
|
||||
negativePrompt: string;
|
||||
styleHint: string;
|
||||
}
|
||||
|
||||
export interface BuildPromptOptions {
|
||||
category: ChibiCategory;
|
||||
subtype: string;
|
||||
gridSize: number;
|
||||
colorCount: number;
|
||||
composition: Composition;
|
||||
detailTags: string[];
|
||||
customPrompt?: string;
|
||||
hasReferenceImage?: boolean;
|
||||
}
|
||||
|
||||
/** 像素拼豆风格通用前缀 */
|
||||
const PIXEL_STYLE = "像素拼豆风格,色块分明,颗粒感强,马赛克效果";
|
||||
|
||||
/** 通用负面提示词 */
|
||||
const NEGATIVE_DEFAULT =
|
||||
"模糊,噪点,文字,水印,多手指,变形,复杂渐变,高光溢出,照片写实";
|
||||
|
||||
/** 15 套模板 */
|
||||
export const TEMPLATES: ChibiTemplate[] = [
|
||||
// ---------- 风景 ----------
|
||||
{
|
||||
category: "landscape", categoryName: "风景", subtype: "nature", subtypeName: "自然山川",
|
||||
note: "山川、森林、河流",
|
||||
basePrompt: "自然风景,山川森林河流,层次分明,构图大气",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",人物,杂乱线条",
|
||||
styleHint: "风景默认像素拼豆风",
|
||||
},
|
||||
{
|
||||
category: "landscape", categoryName: "风景", subtype: "city", subtypeName: "城市夜景",
|
||||
note: "霓虹、地标、灯火",
|
||||
basePrompt: "城市夜景,霓虹灯光,地标建筑,冷暖对比",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",过曝灯光,车流拖影",
|
||||
styleHint: "城市夜景霓虹风",
|
||||
},
|
||||
{
|
||||
category: "landscape", categoryName: "风景", subtype: "landmark", subtypeName: "地标建筑",
|
||||
note: "知名建筑与天际线",
|
||||
basePrompt: "地标建筑特写,轮廓清晰,比例准确",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",透视畸变",
|
||||
styleHint: "地标纪念风",
|
||||
},
|
||||
// ---------- 人物 ----------
|
||||
{
|
||||
category: "person", categoryName: "人物", subtype: "big-eye", subtypeName: "萌系大眼",
|
||||
note: "大眼、圆脸、粗轮廓",
|
||||
basePrompt: "萌系动漫人物,大眼圆脸,粗轮廓线条,可爱风格",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",写实五官",
|
||||
styleHint: "萌系大眼动漫风",
|
||||
},
|
||||
{
|
||||
category: "person", categoryName: "人物", subtype: "youth", subtypeName: "清爽少年",
|
||||
note: "自然五官、利落穿搭",
|
||||
basePrompt: "清爽少年形象,自然五官,利落穿搭,干净背景",
|
||||
negativePrompt: NEGATIVE_DEFAULT,
|
||||
styleHint: "清爽少年风",
|
||||
},
|
||||
{
|
||||
category: "person", categoryName: "人物", subtype: "retro", subtypeName: "复古像素",
|
||||
note: "怀旧配色、游戏感",
|
||||
basePrompt: "复古像素游戏风格人物,怀旧配色,8-bit 质感",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",现代写实",
|
||||
styleHint: "复古 8-bit 游戏风",
|
||||
},
|
||||
// ---------- 宠物 ----------
|
||||
{
|
||||
category: "pet", categoryName: "宠物", subtype: "cat", subtypeName: "猫咪头像",
|
||||
note: "圆润脸型与花纹",
|
||||
basePrompt: "猫咪头像特写,圆润脸型,花纹清晰,眼睛有神",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",多只猫,全身",
|
||||
styleHint: "宠物默认像素拼豆风",
|
||||
},
|
||||
{
|
||||
category: "pet", categoryName: "宠物", subtype: "dog", subtypeName: "狗狗全身",
|
||||
note: "耳朵、四肢和毛色",
|
||||
basePrompt: "狗狗全身像,耳朵四肢完整,毛色层次分明",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",多只狗",
|
||||
styleHint: "狗狗全身像素风",
|
||||
},
|
||||
{
|
||||
category: "pet", categoryName: "宠物", subtype: "duo", subtypeName: "双宠互动",
|
||||
note: "两只宠物同框",
|
||||
basePrompt: "两只宠物同框互动,姿态自然,主次分明",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",肢体重叠遮挡",
|
||||
styleHint: "双宠互动像素风",
|
||||
},
|
||||
// ---------- 物品 ----------
|
||||
{
|
||||
category: "object", categoryName: "物品", subtype: "toy", subtypeName: "手办玩具",
|
||||
note: "造型轮廓优先",
|
||||
basePrompt: "手办玩具,造型轮廓优先,还原特征细节",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",塑料反光过强",
|
||||
styleHint: "手办造型像素风",
|
||||
},
|
||||
{
|
||||
category: "object", categoryName: "物品", subtype: "daily", subtypeName: "生活用品",
|
||||
note: "保留结构与材质",
|
||||
basePrompt: "生活用品,结构清晰,材质质感还原",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",变形扭曲",
|
||||
styleHint: "生活用品像素风",
|
||||
},
|
||||
{
|
||||
category: "object", categoryName: "物品", subtype: "gift", subtypeName: "礼物纪念",
|
||||
note: "突出包装和装饰",
|
||||
basePrompt: "礼物纪念品,包装装饰突出,喜庆完整",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",包装破损",
|
||||
styleHint: "礼物纪念像素风",
|
||||
},
|
||||
// ---------- 食物 ----------
|
||||
{
|
||||
category: "food", categoryName: "食物", subtype: "dessert", subtypeName: "甜品蛋糕",
|
||||
note: "奶油与装饰清晰",
|
||||
basePrompt: "甜品蛋糕,奶油与装饰清晰,诱人色泽",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",融化变形",
|
||||
styleHint: "甜品像素风",
|
||||
},
|
||||
{
|
||||
category: "food", categoryName: "食物", subtype: "drink", subtypeName: "咖啡饮品",
|
||||
note: "杯型、分层和配料",
|
||||
basePrompt: "咖啡饮品,杯型正确,分层与配料清晰",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",杯型变形",
|
||||
styleHint: "饮品像素风",
|
||||
},
|
||||
{
|
||||
category: "food", categoryName: "食物", subtype: "meal", subtypeName: "家常美食",
|
||||
note: "主食材清晰可辨",
|
||||
basePrompt: "家常美食,主食材清晰可辨,色彩饱满",
|
||||
negativePrompt: NEGATIVE_DEFAULT + ",食材混杂难辨",
|
||||
styleHint: "家常美食像素风",
|
||||
},
|
||||
];
|
||||
|
||||
/** 按分类+细分查找模板 */
|
||||
export function findTemplate(category: ChibiCategory, subtype: string): ChibiTemplate {
|
||||
const t = TEMPLATES.find(
|
||||
(x) => x.category === category && x.subtype === subtype,
|
||||
);
|
||||
if (!t) {
|
||||
throw new Error(`未知的拼豆模板: ${category}/${subtype}`);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/** 组装最终提示词 */
|
||||
export function buildPrompt(options: BuildPromptOptions): string {
|
||||
const t = findTemplate(options.category, options.subtype);
|
||||
const grid = options.gridSize;
|
||||
const colors = options.colorCount;
|
||||
const comp = options.composition;
|
||||
const tags = options.detailTags.slice(0, 5); // 最多 5 项
|
||||
|
||||
const parts: string[] = [
|
||||
t.basePrompt,
|
||||
PIXEL_STYLE,
|
||||
`${grid}×${grid} 网格`,
|
||||
`最多 ${colors} 色`,
|
||||
`主体${comp}`,
|
||||
];
|
||||
if (tags.length) parts.push(`细节要求:${tags.join("、")}`);
|
||||
if (options.customPrompt?.trim()) parts.push(options.customPrompt.trim());
|
||||
if (options.hasReferenceImage) parts.push("参考示例风格(不复制示例主体)");
|
||||
|
||||
return parts.join(",");
|
||||
}
|
||||
|
||||
/** 组装负面提示词 */
|
||||
export function buildNegativePrompt(category: ChibiCategory, subtype: string): string {
|
||||
return findTemplate(category, subtype).negativePrompt;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import type Database from "better-sqlite3";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { generateChibiImage, ChibiError, type GenerateRequest } from "./generate.js";
|
||||
import { findTemplate, type ChibiCategory, type Composition } from "./prompts.js";
|
||||
|
||||
const CATEGORIES: readonly ChibiCategory[] = ["landscape", "person", "pet", "object", "food"];
|
||||
const COMPOSITIONS: readonly Composition[] = ["主体特写", "半幅构图", "完整构图"];
|
||||
|
||||
/** Resolve the database instance: injected DB for tests, else global singleton. */
|
||||
function resolveDb(injected?: Database.Database): Database.Database {
|
||||
return injected ?? getDb();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the chibi router. Accepts an optional injected database for testing.
|
||||
*
|
||||
* POST /api/chibi/generate
|
||||
* Request: { code, image, referenceImage?, category, subtype, gridSize,
|
||||
* colorCount, composition, detailTags, customPrompt? }
|
||||
* Response: 200 { image, access, downloadGrant }
|
||||
* 400 参数错误 (中文提示)
|
||||
* 402 { error: "生成次数不足" }
|
||||
* 500 服务器内部错误
|
||||
* 502 AI 图像生成失败
|
||||
*/
|
||||
export function createChibiRouter(injectedDb?: Database.Database): Router {
|
||||
const router = Router();
|
||||
|
||||
router.post("/generate", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||
|
||||
// ---- 基础字段校验 ----
|
||||
const code = typeof body.code === "string" ? body.code : "";
|
||||
if (!code) {
|
||||
res.status(400).json({ error: "请输入兑换码" });
|
||||
return;
|
||||
}
|
||||
const image = typeof body.image === "string" ? body.image : "";
|
||||
if (!image) {
|
||||
res.status(400).json({ error: "请上传图片" });
|
||||
return;
|
||||
}
|
||||
const referenceImage =
|
||||
typeof body.referenceImage === "string" && body.referenceImage !== ""
|
||||
? body.referenceImage
|
||||
: undefined;
|
||||
|
||||
// ---- 分类 / 细分模板 ----
|
||||
const category = body.category as ChibiCategory;
|
||||
if (!CATEGORIES.includes(category)) {
|
||||
res.status(400).json({ error: "未知的分类" });
|
||||
return;
|
||||
}
|
||||
const subtype = typeof body.subtype === "string" ? body.subtype : "";
|
||||
try {
|
||||
findTemplate(category, subtype);
|
||||
} catch {
|
||||
res.status(400).json({ error: "未知的模板类型" });
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- 构图 / 网格 / 颜色 ----
|
||||
const composition = body.composition as Composition;
|
||||
if (!COMPOSITIONS.includes(composition)) {
|
||||
res.status(400).json({ error: "未知的构图方式" });
|
||||
return;
|
||||
}
|
||||
const gridSize = Number(body.gridSize);
|
||||
if (!Number.isInteger(gridSize) || gridSize < 16 || gridSize > 512) {
|
||||
res.status(400).json({ error: "网格尺寸无效" });
|
||||
return;
|
||||
}
|
||||
const colorCount = Number(body.colorCount);
|
||||
if (!Number.isInteger(colorCount) || colorCount < 4 || colorCount > 64) {
|
||||
res.status(400).json({ error: "颜色数量无效" });
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- 细节标签 / 自定义提示词 ----
|
||||
const detailTags = Array.isArray(body.detailTags)
|
||||
? body.detailTags.filter((t): t is string => typeof t === "string")
|
||||
: [];
|
||||
const customPrompt =
|
||||
typeof body.customPrompt === "string" && body.customPrompt.trim() !== ""
|
||||
? body.customPrompt
|
||||
: undefined;
|
||||
|
||||
const payload: GenerateRequest = {
|
||||
code,
|
||||
image,
|
||||
referenceImage,
|
||||
category,
|
||||
subtype,
|
||||
gridSize,
|
||||
colorCount,
|
||||
composition,
|
||||
detailTags,
|
||||
customPrompt,
|
||||
};
|
||||
|
||||
const result = await generateChibiImage(resolveDb(injectedDb), payload);
|
||||
res.status(200).json({
|
||||
image: result.image,
|
||||
access: result.access,
|
||||
downloadGrant: result.downloadGrant,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof ChibiError) {
|
||||
res.status(err.status).json({ error: err.message });
|
||||
} else {
|
||||
console.error("POST /api/chibi/generate error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
Reference in new issue
Block a user