93 lines
2.7 KiB
TypeScript
93 lines
2.7 KiB
TypeScript
import { spawn } from "child_process";
|
|
import { writeFile, readFile, mkdir, unlink } from "fs/promises";
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
import path from "path";
|
|
import os from "os";
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const formData = await req.formData();
|
|
const file = formData.get("file") as File;
|
|
|
|
if (!file) {
|
|
return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
|
}
|
|
|
|
const tempDir = path.join(os.tmpdir(), "xgrids-pipeline");
|
|
await mkdir(tempDir, { recursive: true });
|
|
|
|
const safeName = file.name.replace(/[^a-z0-9.]/gi, "_").toLowerCase();
|
|
const timestamp = Date.now();
|
|
const inputPath = path.join(tempDir, `${timestamp}_${safeName}`);
|
|
const outputPath = inputPath.replace(/\.(lcc|lci|bin)$/i, ".ply");
|
|
|
|
// DETERMINE WHICH SCRIPT TO RUN
|
|
let scriptName = "convert_lci_to_ply.py";
|
|
if (file.name.toLowerCase().includes("environment.bin")) {
|
|
scriptName = "convert_env_to_ply.py";
|
|
}
|
|
|
|
const scriptPath = path.join(
|
|
process.cwd(),
|
|
"scripts",
|
|
"preprocess",
|
|
scriptName,
|
|
);
|
|
|
|
const buffer = Buffer.from(await file.arrayBuffer());
|
|
await writeFile(inputPath, buffer);
|
|
|
|
return new Promise<NextResponse>((resolve) => {
|
|
const pythonProcess = spawn("python3", [
|
|
scriptPath,
|
|
inputPath,
|
|
outputPath,
|
|
]);
|
|
|
|
let errorOutput = "";
|
|
pythonProcess.stderr.on("data", (data) => {
|
|
errorOutput += data.toString();
|
|
});
|
|
|
|
pythonProcess.on("close", async (code) => {
|
|
if (code !== 0) {
|
|
await unlink(inputPath).catch(() => {});
|
|
return resolve(
|
|
NextResponse.json(
|
|
{ error: `Python failed (${scriptName}): ${errorOutput}` },
|
|
{ status: 500 },
|
|
),
|
|
);
|
|
}
|
|
|
|
try {
|
|
const plyBuffer = await readFile(outputPath);
|
|
await Promise.all([
|
|
unlink(inputPath).catch(() => {}),
|
|
unlink(outputPath).catch(() => {}),
|
|
]);
|
|
|
|
resolve(
|
|
new NextResponse(plyBuffer, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": "application/octet-stream",
|
|
"Content-Disposition": `attachment; filename="${file.name.replace(/\.[^/.]+$/, "")}.ply"`,
|
|
},
|
|
}),
|
|
);
|
|
} catch (e) {
|
|
resolve(
|
|
NextResponse.json(
|
|
{ error: "Failed to read output PLY" },
|
|
{ status: 500 },
|
|
),
|
|
);
|
|
}
|
|
});
|
|
});
|
|
} catch (error: any) {
|
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
|
}
|
|
}
|