fix: removed bad error handling structure, using good error handling like video-to-audio route with tmp files

This commit is contained in:
theoleuthardt 2025-02-22 22:29:26 +01:00
parent 6bca341d50
commit 1a63971fff
3 changed files with 45 additions and 1536 deletions

1526
backend/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -14,15 +14,13 @@
"dependencies": {
"@fastify/cors": "^10.0.2",
"@fastify/multipart": "^9.0.3",
"@imgly/background-removal-node": "^1.4.3",
"dotenv": "^16.4.7",
"fastify": "^5.2.1",
"fastify-cors": "^6.0.3",
"fastify-multipart": "^5.3.1",
"libreoffice-convert": "^1.6.0",
"luxon": "^3.5.0",
"qrcode": "^1.5.4",
"sharp": "^0.33.5"
"qrcode": "^1.5.4"
},
"devDependencies": {
"@types/luxon": "^3.4.2",

View file

@ -1,13 +1,21 @@
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { removeBackground } from "@imgly/background-removal-node";
import sharp from "sharp";
import { promises as fs } from "fs";
import * as path from "path";
import { randomUUID } from "crypto";
import { spawn } from "child_process";
export async function removeBG(app: FastifyInstance) {
app.post(
"/api/remove-bg",
async (request: FastifyRequest, reply: FastifyReply) => {
const tmpDir = path.join(process.cwd(), "tmp");
const sessionId = randomUUID();
const inputPath = path.join(tmpDir, `input-${sessionId}.png`);
const outputPath = path.join(tmpDir, `output-${sessionId}.png`);
try {
const parts = request.parts();
await fs.mkdir(tmpDir, { recursive: true });
let fileBuffer: Buffer | null = null;
@ -21,20 +29,47 @@ export async function removeBG(app: FastifyInstance) {
return reply.status(400).send({ error: "No file uploaded!" });
}
await fs.writeFile(inputPath, fileBuffer);
console.log("Received file, buffer length:", fileBuffer.length);
const rightFileBuffer = await sharp(fileBuffer)
.toFormat("png")
.toBuffer();
console.log("Converted file:", rightFileBuffer);
const convertedBuffer = await removeBackground(rightFileBuffer);
await new Promise<void>((resolve, reject) => {
const pythonProcess = spawn("rembg", ["i", inputPath, outputPath]);
pythonProcess.stderr.on("data", (data) => {
console.log(`ffmpeg stderr: ${data}`);
});
pythonProcess.on("close", (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`rembg process exited with code ${code}`));
}
});
pythonProcess.on("error", (err) => {
reject(err);
});
});
const outputImageBuffer = await fs.readFile(outputPath);
await Promise.all([fs.unlink(inputPath), fs.unlink(outputPath)]);
reply
.header("Content-Type", "image/png")
.header("Content-Disposition", `attachment; filename="converted.png"`)
.status(200)
.send(convertedBuffer);
.send(outputImageBuffer);
} catch (error) {
try {
await Promise.all([
fs.unlink(inputPath).catch(() => {}),
fs.unlink(outputPath).catch(() => {}),
]);
} catch (cleanupError) {
console.error("Cleanup error:", cleanupError);
}
console.error("Convert error:", error);
reply.status(500).send({ error: "Error while converting!" });
}