File size: 5,036 Bytes
19e93fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271370e
 
 
 
 
 
 
 
 
19e93fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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;
}