File size: 2,486 Bytes
0db47ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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"}`
    );
  }
}