Drip-Creator / pages /api /optimize.ts
2Btainment's picture
security: load design system prompt from DRIP_SYSTEM_PROMPT secret
271370e verified
Raw History Blame Contribute Delete
5.04 kB
import type { NextApiRequest, NextApiResponse } from "next";
import { clientIp, rateLimited } from "@/lib/rateLimit";
const GEMINI_KEY = process.env.GEMINI_API_KEY || "";
const GEMINI_API = "https://generativelanguage.googleapis.com/v1beta/models";
export const config = {
api: { bodyParser: { sizeLimit: "1mb" } },
};
export interface OptimizeRequest {
prompt: string;
transparent?: boolean;
}
export interface OptimizeResponse {
optimized: string;
source: "gemini" | "local";
}
function buildSystemPrompt(transparent: boolean): string {
const bgHint = transparent
? "- Transparenter Hintergrund gewünscht → Prompt endet mit: 'isolated on transparent background'"
: "- Hintergrund: isoliert auf schwarzem Grund (kontrastreich)";
// Full prompt lives in Space Secret DRIP_SYSTEM_PROMPT (audit 2026-10-15).
const fromEnv = (process.env.DRIP_SYSTEM_PROMPT || "").trim();
if (fromEnv && !fromEnv.startsWith("# STUB")) {
return fromEnv.includes("{bg_hint}")
? fromEnv.replace("{bg_hint}", bgHint)
: `${fromEnv}\n${bgHint}`;
}
// Short safe fallback if secret missing
return `Du bist POD-Design-Direktor. Optimiere den Nutzerwunsch zu einem kurzen englischen Bildprompt (max 60 Wörter, eine Zeile, keine Erklärung). Druck-tauglich: bold contrast, clean edges, vibrant colors, no text/watermark. ${bgHint}`;
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Method not allowed" });
}
const body = (req.body || {}) as OptimizeRequest;
const raw = (body.prompt || "").trim();
if (!raw) {
return res.status(400).json({ error: "Bitte einen Prompt eingeben." });
}
// Rate-Limit pro IP (Schutz der Free-Tier-Keys im öffentlichen Space)
if (rateLimited(clientIp(req))) {
return res.status(429).json({
error: "Stundenlimit erreicht. Bitte später erneut versuchen.",
});
}
// 1) Gemini-Text (schnell, kostenlos)
if (GEMINI_KEY) {
try {
const system = buildSystemPrompt(!!body.transparent);
const url = `${GEMINI_API}/gemini-2.5-flash:generateContent?key=${encodeURIComponent(GEMINI_KEY)}`;
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 20000);
const resp = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [
{
role: "user",
parts: [
{ text: system },
{ text: `Nutzerwunsch: "${raw}"\n\nOptimiere diesen Prompt jetzt für den Druck.` },
],
},
],
generationConfig: {
temperature: 0.7,
maxOutputTokens: 2048,
thinkingConfig: { thinkingBudget: 0 },
},
}),
signal: ctrl.signal,
});
clearTimeout(t);
if (resp.ok) {
const data = await resp.json();
const text = data?.candidates?.[0]?.content?.parts?.[0]?.text;
// Nur verwenden, wenn vollständig genug — zu knappe Antworten sind abgeschnitten
if (text && text.trim().length >= 80) {
return res.json({ optimized: text.trim().replace(/\s+/g, " "), source: "gemini" });
}
}
} catch {
// Fallback unten
}
}
// 2) Lokale Regel-Engine (Fallback, immer verfügbar)
return res.json({ optimized: optimizeLocal(raw, !!body.transparent), source: "local" });
}
/** Regelbasierte Druck-Optimierung — kein LLM nötig */
export function optimizeLocal(prompt: string, transparent: boolean): string {
const p = prompt.trim().replace(/\s+/g, " ");
const low = p.toLowerCase();
// Ziel-Analyse → Stil-Bausteine
let style = "";
if (/(logo|emblem|icon|marke|monogram|zeichen|badge|crest)/.test(low)) {
style = "minimalist bold emblem, centered, isolated, strong silhouette";
} else if (/(anime|manga|chibi|illustration|cartoon|zeichnung|kawaii|manga)/.test(low)) {
style = "vibrant illustration style, clean bold lines, saturated colors";
} else if (/(photo|realistic|realismus|portrait|person|woman|man|face|studio|foto|photograph)/.test(low)) {
style = "photorealistic, high detail, dramatic lighting";
} else if (/(abstract|abstrakt|geometric|geometrisch|minimal|art)/.test(low)) {
style = "modern graphic art, bold shapes, strong composition";
} else {
style = "stylized graphic design";
}
// Druck-Suffix
const print = transparent
? "isolated on transparent background, cutout style"
: "isolated on solid black background, high contrast";
const parts = [p, style, `print-ready design, bold contrast, clean edges, vibrant colors, ${print}, no text, no watermark, no signature`];
// Kompression: max ~420 Zeichen
let out = parts.join(", ");
if (out.length > 420) {
out = `${p}, ${style}, print-ready, bold contrast, clean edges, ${print}, no text, no watermark`.slice(0, 420);
}
return out;
}