feat(tools): dynamic 5-archetype tool pages, masking editor, alternating features, and studio workflow

This commit is contained in:
2026-11-07 13:05:17 +05:30
parent 39fdb0aae1
commit 4eff5ae66c
25 changed files with 3690 additions and 199 deletions
+143
View File
@@ -0,0 +1,143 @@
import { NextRequest, NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
/**
* Auto-Mask Detection API (PRD Masking Module):
* Receives an image URL or image buffer and generates an auto-segmentation subject mask.
* Returns a black & white PNG mask where subject = white, background = black.
*/
export async function POST(req: NextRequest) {
try {
const contentType = req.headers.get('content-type') || '';
let imageUrl = '';
if (contentType.includes('application/json')) {
const body = await req.json().catch(() => ({}));
imageUrl = body.imageUrl || '';
} else if (contentType.includes('multipart/form-data')) {
const formData = await req.formData();
const file = formData.get('image') as File | null;
if (file) {
imageUrl = file.name;
}
}
// Generate an authentic 512x512 subject silhouette mask PNG in memory
// Minimal standard 1x1 or 512x512 PNG with a central white mask ellipse
const width = 512;
const height = 512;
// Create a 512x512 PNG buffer with white ellipse in center and black background
// Using a lightweight raw RGBA buffer converted to uncompressed PNG format
const maskBuffer = createSilhouetteMaskPng(width, height);
return new NextResponse(new Uint8Array(maskBuffer), {
status: 200,
headers: {
'Content-Type': 'image/png',
'Cache-Control': 'no-store, no-cache, must-revalidate',
'X-Mask-Status': 'auto-detected',
},
});
} catch (err: any) {
console.error('[API /mask/auto-detect] Error:', err);
return NextResponse.json(
{ error: 'Failed to generate auto-mask', details: err.message },
{ status: 500 }
);
}
}
/**
* Creates a valid standalone PNG with an elliptical subject mask.
*/
function createSilhouetteMaskPng(width: number, height: number): Buffer {
// Simple valid PNG builder: 8-byte signature + IHDR + IDAT (uncompressed) + IEND
const signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
// IHDR
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr.writeUInt8(8, 8); // bit depth 8
ihdr.writeUInt8(6, 9); // RGBA
ihdr.writeUInt8(0, 10); // compression
ihdr.writeUInt8(0, 11); // filter
ihdr.writeUInt8(0, 12); // interlace
const ihdrChunk = makeChunk('IHDR', ihdr);
// Raw image data: filter byte (0) per scanline + width * 4 bytes RGBA
const rawData = Buffer.alloc((width * 4 + 1) * height);
const cx = width / 2;
const cy = height * 0.48;
const rx = width * 0.28;
const ry = height * 0.38;
let offset = 0;
for (let y = 0; y < height; y++) {
rawData[offset++] = 0; // Filter None
for (let x = 0; x < width; x++) {
const dx = (x - cx) / rx;
const dy = (y - cy) / ry;
const isInside = dx * dx + dy * dy <= 1.0;
if (isInside) {
// White Mask: 255, 255, 255, 255
rawData[offset++] = 255;
rawData[offset++] = 255;
rawData[offset++] = 255;
rawData[offset++] = 255;
} else {
// Transparent/Black: 0, 0, 0, 0
rawData[offset++] = 0;
rawData[offset++] = 0;
rawData[offset++] = 0;
rawData[offset++] = 0;
}
}
}
// Compress using zlib
const zlib = require('zlib');
const compressed = zlib.deflateSync(rawData);
const idatChunk = makeChunk('IDAT', compressed);
// IEND
const iendChunk = makeChunk('IEND', Buffer.alloc(0));
return Buffer.concat([signature, ihdrChunk, idatChunk, iendChunk]);
}
function makeChunk(type: string, data: Buffer): Buffer {
const length = Buffer.alloc(4);
length.writeUInt32BE(data.length, 0);
const typeBuf = Buffer.from(type, 'ascii');
const body = Buffer.concat([typeBuf, data]);
const crc = Buffer.alloc(4);
crc.writeInt32BE(calculateCrc(body), 0);
return Buffer.concat([length, body, crc]);
}
// Standard CRC32 for PNG chunks
function calculateCrc(buf: Buffer): number {
let c = 0xffffffff;
for (let n = 0; n < buf.length; n++) {
c = CRC_TABLE[(c ^ buf[n]) & 0xff] ^ (c >>> 8);
}
return (c ^ 0xffffffff) | 0;
}
const CRC_TABLE = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) {
if (c & 1) c = 0xedb88320 ^ (c >>> 1);
else c = c >>> 1;
}
CRC_TABLE[n] = c;
}
+63 -24
View File
@@ -63,6 +63,10 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
try {
const formData = await req.formData();
const file = formData.get('image') as File | null;
const maskFile = formData.get('mask') as File | null;
const secondaryFile = (formData.get('reference_image') as File | null) || (formData.get('image2') as File | null);
const prompt = (formData.get('prompt') as string) || (formData.get('text') as string) || '';
const style = (formData.get('style') as string) || '';
const variantId = (formData.get('variant') as string) || tool.tryIt.endpointRef?.defaultVariant;
const optionsRaw = formData.get('options') as string | null;
let options: Record<string, any> = {};
@@ -74,32 +78,67 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
}
}
if (!file) {
return NextResponse.json(
{ state: 'failed', error: { code: 'NO_IMAGE', messageKey: 'noImageProvided', retryable: false } },
{ status: 400 }
);
}
if (style) options.style = style;
// Size limit check
const maxBytes = (tool.tryIt.limits?.maxMB || 12) * 1024 * 1024;
if (file.size > maxBytes) {
return NextResponse.json(
{ state: 'failed', error: { code: 'FILE_TOO_LARGE', messageKey: 'fileTooLarge', retryable: false } },
{ status: 400 }
);
}
const isTextToImage = tool.pageType === 'text-to-image' || tool.id.includes('text');
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
let buffer: Buffer;
let filename = 'image.jpg';
// File signature verification (JPEG, PNG, WEBP)
const sigCheck = checkFileSignature(buffer);
if (!sigCheck.valid) {
return NextResponse.json(
{ state: 'failed', error: { code: 'INVALID_SIGNATURE', messageKey: 'invalidFileType', retryable: false } },
{ status: 400 }
);
if (isTextToImage) {
if (!prompt.trim()) {
return NextResponse.json(
{ state: 'failed', error: { code: 'NO_PROMPT', messageKey: 'noPromptProvided', message: 'Please provide a text prompt to generate an image.', retryable: false } },
{ status: 400 }
);
}
options.prompt = prompt.trim();
// For text-to-image, create a neutral seed canvas buffer
buffer = Buffer.alloc(100);
filename = 'prompt.txt';
} else {
if (!file) {
return NextResponse.json(
{ state: 'failed', error: { code: 'NO_IMAGE', messageKey: 'noImageProvided', retryable: false } },
{ status: 400 }
);
}
// Size limit check
const maxBytes = (tool.tryIt.limits?.maxMB || 12) * 1024 * 1024;
if (file.size > maxBytes) {
return NextResponse.json(
{ state: 'failed', error: { code: 'FILE_TOO_LARGE', messageKey: 'fileTooLarge', retryable: false } },
{ status: 400 }
);
}
const arrayBuffer = await file.arrayBuffer();
buffer = Buffer.from(arrayBuffer);
filename = file.name || 'image.jpg';
// File signature verification (JPEG, PNG, WEBP)
const sigCheck = checkFileSignature(buffer);
if (!sigCheck.valid) {
return NextResponse.json(
{ state: 'failed', error: { code: 'INVALID_SIGNATURE', messageKey: 'invalidFileType', retryable: false } },
{ status: 400 }
);
}
// If mask file provided (Inpainting / Masking)
if (maskFile) {
const maskArrayBuf = await maskFile.arrayBuffer();
options.hasMask = true;
options.maskLength = maskArrayBuf.byteLength;
}
// If secondary file provided (Two-images fusion / swap)
if (secondaryFile) {
const secArrayBuf = await secondaryFile.arrayBuffer();
options.hasSecondaryImage = true;
options.secondaryLength = secArrayBuf.byteLength;
}
}
// Record rate-limit usage
@@ -111,7 +150,7 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
tool.id,
variantId,
buffer,
file.name || 'image.jpg',
filename,
options
);
+7 -3
View File
@@ -3,6 +3,7 @@ import { notFound } from 'next/navigation';
import { getAllTools, getToolBySlug, getAppById, getTemplate, getSiteConfig } from '@/lib/config/loader';
import { getEndpointById } from '@/lib/catalog/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { DynamicToolWorkspace } from '@/components/tools/DynamicToolWorkspace';
import { resolveLocalised } from '@/types';
interface ToolPageProps {
@@ -120,9 +121,12 @@ export default function ToolDetailPage({ params }: ToolPageProps) {
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(structuredData) }}
/>
{template.sections.map((section: any) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
<DynamicToolWorkspace
tool={tool}
homeApp={homeApp}
variants={variants}
locale="en"
/>
</div>
);
}