richuj's picture
feat: initial project structure and UI components
e008c35
Raw History Blame Contribute Delete
4.84 kB
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { NextRequest, NextResponse } from "next/server";
import type { SegmentResponse } from "@/lib/types";
export const runtime = "nodejs";
/** Maximum time to wait for SAM segmentation (ms) */
const SAM_TIMEOUT_MS = 300_000;
/** Maximum input image file size (bytes) */
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
type PythonSegmentResponse = SegmentResponse & {
error?: string;
};
export async function POST(request: NextRequest) {
const formData = await request.formData();
const file = formData.get("image");
if (!(file instanceof File)) {
return NextResponse.json(
{ error: "Missing image upload." },
{ status: 400 }
);
}
if (file.size > MAX_FILE_SIZE) {
return NextResponse.json(
{ error: `Image too large. Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB.` },
{ status: 400 }
);
}
const bytes = Buffer.from(await file.arrayBuffer());
const tempDir = join("/tmp", `tile-room-${randomUUID()}`);
const inputPath = join(tempDir, sanitizeFileName(file.name));
await mkdir(tempDir, { recursive: true });
await writeFile(inputPath, bytes);
try {
const samResult = await runSamSegmenter(inputPath);
if (hasValidMasks(samResult) && !samResult.error) {
return NextResponse.json(samResult);
}
// Log SAM failure for debugging, then return error
if (samResult.error) {
console.error("[segment] SAM failed:", samResult.error);
return NextResponse.json(
{ error: `AI Segmentation failed: ${samResult.error}`, diagnostics: samResult.diagnostics },
{ status: 500 }
);
}
// If we reach here, no masks were generated but also no explicit error
console.warn("[segment] No masks generated. Diagnostics:", samResult.diagnostics);
return NextResponse.json(
{ error: "No surfaces detected in this image. Try a clearer room photo.", diagnostics: samResult.diagnostics },
{ status: 422 }
);
} finally {
await rm(tempDir, { recursive: true, force: true }).catch(() => { });
}
}
function sanitizeFileName(name: string) {
return name.replace(/[^a-z0-9._-]/gi, "_") || "room-image";
}
function runSamSegmenter(inputPath: string): Promise<PythonSegmentResponse> {
return new Promise((resolve) => {
const pythonPath = resolvePythonPath();
console.log(`[segment] Using Python: ${pythonPath}`);
const child = spawn(
pythonPath,
["backend/sam_segment.py", inputPath],
{
cwd: process.cwd(),
env: process.env,
}
);
let stdout = "";
let stderr = "";
const timer = setTimeout(() => {
child.kill("SIGTERM");
resolve({
...emptySegment(),
error: `SAM timed out after ${SAM_TIMEOUT_MS / 1000}s`,
});
}, SAM_TIMEOUT_MS);
child.stdout.on("data", (chunk) => {
stdout += chunk.toString();
});
child.stderr.on("data", (chunk) => {
stderr += chunk.toString();
// Log stderr in real-time for debugging model downloads etc.
process.stderr.write(chunk);
});
child.on("error", (err) => {
clearTimeout(timer);
resolve({ ...emptySegment(), error: `Python process failed to start: ${err.message}` });
});
child.on("close", (code) => {
clearTimeout(timer);
if (code !== 0) {
resolve({
...emptySegment(),
error: `SAM process exited with code ${code}. ${stderr.slice(-500)}`,
});
return;
}
try {
const result = JSON.parse(stdout) as PythonSegmentResponse;
resolve(result);
} catch {
resolve({
...emptySegment(),
error: `Invalid SAM response. stdout: ${stdout.slice(0, 200)}`,
});
}
});
});
}
function resolvePythonPath() {
// 1. Explicit env var
if (process.env.SAM_PYTHON) return process.env.SAM_PYTHON;
// 2. Project venv (has all dependencies installed)
const localPython = join(process.cwd(), ".venv", "bin", "python");
if (existsSync(localPython)) return localPython;
// 3. macOS Framework Python
const macOsFrameworkPython = "/Library/Frameworks/Python.framework/Versions/3.14/bin/python3";
if (existsSync(macOsFrameworkPython)) return macOsFrameworkPython;
// 4. System python3
return "python3";
}
function emptySegment(): SegmentResponse {
return {
diagnostics: [],
height: 0,
masks: {},
source: "fallback",
width: 0,
};
}
function hasValidMasks(segment: SegmentResponse) {
// At minimum, we need at least one mask with real data
return Object.values(segment.masks || {}).some(v => v && v.length > 50);
}