Merge pull request #19 from theoleuthardt/feat/bg-remove

feat: bg-remover
This commit is contained in:
Theo Leuthardt 2025-02-23 13:14:15 +01:00 committed by GitHub
commit c4490949b3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 201 additions and 1 deletions

View file

@ -2,7 +2,11 @@
FROM node:18-alpine AS base
# Install system dependencies
RUN apk add --no-cache libc6-compat libreoffice ttf-liberation
RUN apk add --no-cache libc6-compat libreoffice ttf-liberation ffmpeg
RUN apk add --update --no-cache python3 py3-pip \
&& ln -sf python3 /usr/bin/python \
&& pip3 install --no-cache --upgrade pip setuptools \
RUN pip3 install --no-cache watchdog gradio rembg
WORKDIR /app

View file

@ -8,6 +8,7 @@ import { regexTest } from "./src/routes/regextest.route";
import { tmzConvert } from "./src/routes/tmzconvert.route";
import { generateQRCode } from "./src/routes/generateqrcode.route";
import { wordCounter } from "./src/routes/wordcounter.route";
import { removeBG } from "./src/routes/removebg.route";
const app = Fastify({ logger: true });
@ -25,6 +26,7 @@ app.register(regexTest);
app.register(tmzConvert);
app.register(generateQRCode);
app.register(wordCounter);
app.register(removeBG);
const PORT = process.env.PORT || 4000;
app.listen({ port: Number(PORT), host: "0.0.0.0" }, () => {

View file

@ -0,0 +1,78 @@
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
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;
for await (const part of parts) {
if (part.type === "file") {
fileBuffer = await part.toBuffer();
}
}
if (!fileBuffer) {
return reply.status(400).send({ error: "No file uploaded!" });
}
await fs.writeFile(inputPath, fileBuffer);
console.log("Received file, buffer length:", fileBuffer.length);
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(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!" });
}
},
);
}

View file

@ -0,0 +1,20 @@
import React from "react";
import type { Metadata } from "next";
import { toolLinks } from "@/constants";
export const metadata: Metadata = {
title: toolLinks[6].title,
description: "Remove backgrounds from your images!",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`antialiased`}>{children}</body>
</html>
);
}

View file

@ -0,0 +1,96 @@
"use client";
import React, { useState } from "react";
import Navbar from "../../components/Navbar";
import Footer from "../../components/Footer";
import Button from "../../components/Button";
export default function BGRemover() {
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
if (event.target.files && event.target.files.length > 0) {
const selectedFile = event.target.files[0];
setFile(selectedFile);
}
};
const removeBG = async () => {
if (!file) {
alert("No file selected");
return;
} else if (file.size > 5 * 1024 * 1024) {
alert("File size should be less than 5MB");
return;
}
const formData = new FormData();
formData.append("file", file);
setLoading(true);
try {
const response = await fetch(process.env.backend_url + "/api/remove-bg", {
method: "POST",
body: formData,
});
if (!response.ok) {
console.error(`Error: ${response.statusText}`);
return;
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const filename = file.name.split(".")[0];
const a = document.createElement("a");
a.href = url;
a.download = `${filename}.png`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => {
URL.revokeObjectURL(url);
}, 5000);
} catch (error) {
console.error("Error while converting:", error);
alert("Error while converting!");
} finally {
setLoading(false);
}
};
return (
<div className="w-screen h-auto min-h-screen bg-black text-white font-noto flex flex-col items-center">
<Navbar renderHomeLink={true} />
<div className="w-screen h-auto min-h-[calc(100vh-80px-60px)] flex flex-1 flex-col items-center justify-center">
<h2 className="text-5xl font-bold text-white mb-16">bg-remover</h2>
<div className="h-36 flex flex-row items-center justify-center gap-4">
<input
type="file"
className="h-16 border-2 border-white p-3 rounded-xl text-2xl text-center text-white"
id="documentUpload"
onChange={handleFileChange}
/>
</div>
<div className={"flex flex-row items-center gap-4 mt-4 mb-16"}>
<Button
content={
loading ? (
<div className="h-10 w-10 border-8 border-blue-100 border-t-blue-500 rounded-full animate-spin" />
) : (
"remove background"
)
}
onClick={removeBG}
/>
</div>
</div>
<Footer className="flex justify-center items-end" />
</div>
);
}