Spaces:
Sleeping
Sleeping
| import axios from "axios"; | |
| import FormData from "form-data"; | |
| const BG_REMOVER_URL = process.env.BG_REMOVER_URL || "https://nexusbert-bg-remover.hf.space"; | |
| /** | |
| * Removes background from an image using the hosted background remover service | |
| * @param imageBuffer - The image file buffer | |
| * @param filename - Original filename | |
| * @param mimetype - Original file mimetype | |
| * @returns Buffer containing the processed image (PNG with transparent background) | |
| */ | |
| export async function removeBackground( | |
| imageBuffer: Buffer, | |
| filename: string, | |
| mimetype: string | |
| ): Promise<Buffer> { | |
| try { | |
| const formData = new FormData(); | |
| formData.append("file", imageBuffer, { | |
| filename: filename, | |
| contentType: mimetype, | |
| }); | |
| const endpoint = `${BG_REMOVER_URL}/remove-background`; | |
| let lastError: any = null; | |
| const maxAttempts = 2; | |
| for (let attempt = 1; attempt <= maxAttempts; attempt++) { | |
| try { | |
| const response = await axios.post(endpoint, formData, { | |
| headers: { | |
| ...formData.getHeaders(), | |
| }, | |
| responseType: "arraybuffer", | |
| timeout: 60000, // 60 second timeout for background removal | |
| validateStatus: (status) => status >= 200 && status < 300, | |
| }); | |
| return Buffer.from(response.data); | |
| } catch (error: any) { | |
| lastError = error; | |
| const status = error?.response?.status; | |
| if (attempt < maxAttempts && (status === 429 || status === 503 || status === 502)) { | |
| console.log(`Background remover API returned ${status}. Retrying...`); | |
| await new Promise((r) => setTimeout(r, 2000)); | |
| continue; | |
| } | |
| if (error?.response?.data) { | |
| const errorDetail = typeof error.response.data === 'string' | |
| ? error.response.data | |
| : error.response.data.detail || JSON.stringify(error.response.data); | |
| throw new Error(`Background remover API error: ${errorDetail}`); | |
| } | |
| if (error?.code === "ECONNREFUSED" || error?.code === "ETIMEDOUT") { | |
| throw new Error("Unable to connect to background remover service. Please try again later."); | |
| } | |
| throw error; | |
| } | |
| } | |
| throw lastError; | |
| } catch (error: any) { | |
| console.error("Background removal error:", error.response?.data || error.message); | |
| throw new Error( | |
| `Failed to remove background: ${error.message || "Unknown error"}` | |
| ); | |
| } | |
| } | |