Iot / src /app /api /generate /route.ts
veltrixcode's picture
Upload 74 files
64fa001 verified
Raw History Blame Contribute Delete
4.69 kB
import { auth } from "@/auth"
import { checkAndResetDailyCredits, deductCredits } from "@/lib/credits"
import { prisma } from "@/lib/prisma"
import { NextRequest, NextResponse } from "next/server"
export const DEFAULT_NEGATIVE_PROMPT = "blurry, low quality, bad anatomy, bad hands, distorted, ugly, pixelated, watermark, text, signature, grains, haze"
export async function POST(req: NextRequest) {
try {
const session = await auth()
if (!session || !session.user || !session.user.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const { prompt, model = "flux-dev", width = 1024, height = 1024 } = await req.json()
if (!prompt) {
return NextResponse.json({ error: "Prompt is required" }, { status: 400 })
}
// 1. Check Credits
const credits = await checkAndResetDailyCredits(session.user.id)
// 2. Load Balancing Configuration
// Parse workers from Environment Variable (comma separated) or default to known instances
const envWorkers = process.env.CLOUDFLARE_WORKER_URL
? process.env.CLOUDFLARE_WORKER_URL.split(",").map(url => url.trim())
: []
// Add hardcoded fallbacks/extras if they aren't in the env
// The user might put the primary in env and want to add others here or in env
const extraWorkers = [
"https://bitter-forest-7e87.bob17040246.workers.dev/"
]
// Combine and Deduplicate
const ALL_WORKERS = Array.from(new Set([...envWorkers, ...extraWorkers])).filter(url => url.length > 0)
if (ALL_WORKERS.length === 0) {
return NextResponse.json({ error: "Server configuration error: No worker URLs found" }, { status: 500 })
}
// Round-robin selection
if (typeof (global as any).requestCounter === 'undefined') {
(global as any).requestCounter = 0
}
const counter = (global as any).requestCounter++
const selectedWorkerUrl = ALL_WORKERS[counter % ALL_WORKERS.length]
console.log(`[LoadBalancer] Request #${counter} -> Using Worker ${counter % ALL_WORKERS.length + 1}/${ALL_WORKERS.length}: ${selectedWorkerUrl}`)
// Clean up URL construction
const baseUrl = selectedWorkerUrl.endsWith("/") ? selectedWorkerUrl.slice(0, -1) : selectedWorkerUrl
// If model includes a slash, remove it for consistency
const cleanModel = model.startsWith("/") ? model.slice(1) : model
const url = `${baseUrl}/${cleanModel}`
// Prepare payload with Negative Prompt
const payload = {
prompt,
negative_prompt: DEFAULT_NEGATIVE_PROMPT, // Pass explicit negative prompt
width,
height,
steps: 30
}
// For Flux models that might ignore negative_prompt, we can optionally append it to the prompt
// IF the model is known to not support it. But standard practice is to send it separately first.
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
})
// }
if (!response.ok) {
const errorText = await response.text()
console.error("AI Generation failed:", errorText)
return NextResponse.json({ error: "Image generation failed upstream" }, { status: 500 })
}
const result = await response.json()
if (!result.success || !result.url) {
return NextResponse.json({ error: "Image generation returned no URL" }, { status: 500 })
}
// 3. Deduct Credits (Success confirmed) - 5 credits per generation
await deductCredits(session.user.id, 5)
// 4. Save to Database
const generation = await prisma.generation.create({
data: {
prompt,
model,
width,
height,
imageUrl: result.url,
userId: session.user.id,
isPublic: true, // Default to public as per requirement "gallery... new non auth users will be able to see"
}
})
return NextResponse.json({
success: true,
url: generation.imageUrl,
width: generation.width,
height: generation.height,
prompt: generation.prompt,
model: generation.model
})
} catch (error) {
console.error("Generate API error:", error)
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
}
}