/** * ==================================================================== * BRIA RMBG 1.4 - AI Background Remover Scraper (Free & Non-Cloudflare) * Author: Vamz Spectre * Mendukung: URL Gambar, Path File Lokal, Buffer Node.js, & Base64 * Tanpa API Key & Bebas Cloudflare / Turnstile Captcha * ==================================================================== */ const fs = require("fs"); const path = require("path"); /** * Menghapus background dari gambar secara otomatis * @param {string | Buffer} input - Bisa berupa: * 1. URL Gambar publik ("https://example.com/foto.jpg") * 2. Path File Lokal ("./foto.jpg" atau "/root/foto.png") * 3. Buffer gambar (Buffer dari bot WhatsApp / upload) * 4. Base64 string ("data:image/png;base64,..." atau raw base64) * @param {object} [options] - Opsi konfigurasi * @param {string} [options.outPath] - Path file tujuan jika ingin langsung disimpan ke disk * @returns {Promise<{ success: boolean, buffer: Buffer, url: string, size: number, mimeType: string }>} */ async function removeBackground(input, options = {}) { // Menggunakan @gradio/client untuk koneksi websocket/SSE mulus ke model BRIA RMBG 1.4 const { Client } = await import("@gradio/client"); // Endpoint publik tanpa autentikasi / non-Cloudflare const client = await Client.connect("briaai/BRIA-RMBG-1.4"); let blob; // 1. Tipe Input: String (Bisa URL, Base64, atau Path File Lokal) if (typeof input === "string") { const trimmed = input.trim(); // A. URL Gambar (HTTP / HTTPS) if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) { const res = await fetch(trimmed); if (!res.ok) { throw new Error(`Gagal mengunduh gambar dari URL (${res.status} ${res.statusText})`); } blob = await res.blob(); } // B. Base64 String (Data URI atau raw Base64) else if (trimmed.startsWith("data:image/") || (trimmed.length > 100 && /^[A-Za-z0-9+/=\s]+$/.test(trimmed))) { const b64Data = trimmed.includes(",") ? trimmed.split(",")[1] : trimmed; const buf = Buffer.from(b64Data, "base64"); blob = new Blob([new Uint8Array(buf)], { type: "image/png" }); } // C. Path File Lokal (Relatif maupun Absolut) else { const resolvedPath = path.resolve(trimmed); if (!fs.existsSync(resolvedPath)) { throw new Error(`File lokal tidak ditemukan di: ${trimmed}`); } const fileBuffer = fs.readFileSync(resolvedPath); // Tentukan mime type sederhana berdasarkan ekstensi const ext = path.extname(resolvedPath).toLowerCase(); const mimeType = ext === ".jpg" || ext === ".jpeg" ? "image/jpeg" : (ext === ".webp" ? "image/webp" : "image/png"); blob = new Blob([new Uint8Array(fileBuffer)], { type: mimeType }); } } // 2. Tipe Input: Binary Buffer (Misal: hasil downloadMediaMessage bot WhatsApp) else if (Buffer.isBuffer(input)) { blob = new Blob([new Uint8Array(input)], { type: "image/png" }); } // 3. Tipe Input: Blob else if (input instanceof Blob) { blob = input; } else { throw new Error("Format input tidak didukung. Harap berikan URL gambar, path file lokal, Buffer, atau Base64."); } // Kirim gambar ke AI untuk proses penghapusan background const result = await client.predict("/run", { image: blob }); // Index 1 pada kembalian data BRIA RMBG 1.4 adalah file PNG dengan background transparan const fileData = result.data?.[1]; if (!fileData || !fileData.url) { throw new Error("Gagal menerima hasil gambar transparan dari server AI."); } // Unduh buffer biner hasil gambar transparan const imgRes = await fetch(fileData.url); if (!imgRes.ok) { throw new Error(`Gagal mengunduh gambar hasil: ${imgRes.statusText}`); } const arrayBuf = await imgRes.arrayBuffer(); const buffer = Buffer.from(arrayBuf); // Jika outPath diisi, simpan langsung ke penyimpanan lokal if (options.outPath) { const targetDir = path.dirname(path.resolve(options.outPath)); if (!fs.existsSync(targetDir)) { fs.mkdirSync(targetDir, { recursive: true }); } fs.writeFileSync(options.outPath, buffer); } return { success: true, buffer, url: fileData.url, size: buffer.length, mimeType: "image/png" }; } if (typeof module !== "undefined" && module.exports) { module.exports = { removeBackground }; } // ==================================================================== // CLI Handler: Eksekusi Langsung dari Terminal // ==================================================================== if (require.main === module) { const args = process.argv.slice(2); const target = args.find(a => !a.startsWith("--")); if (!target) { console.log("Penggunaan CLI:"); console.log(" node rmbg.js [--out hasil.png]"); console.log(""); console.log("Contoh:"); console.log(" 1. Menggunakan URL gambar:"); console.log(" node rmbg.js https://example.com/foto.jpg --out hasil.png"); console.log(""); console.log(" 2. Menggunakan File Lokal:"); console.log(" node rmbg.js ./foto_saya.jpg --out nobg.png"); process.exit(1); } const outIndex = args.indexOf("--out"); const outFile = (outIndex !== -1 && args[outIndex + 1]) ? args[outIndex + 1] : "output_nobg.png"; console.log(`[RMBG AI] Memproses gambar (${target.startsWith("http") ? "URL" : "File Lokal"})...`); const startTime = Date.now(); removeBackground(target, { outPath: outFile }) .then(res => { const elapsed = ((Date.now() - startTime) / 1000).toFixed(2); console.log(`[RMBG AI] Sukses dalam ${elapsed} detik!`); console.log(` - File Disimpan : ${outFile}`); console.log(` - Ukuran Output : ${res.size} bytes`); console.log(` - Direct URL : ${res.url}`); }) .catch(err => { console.error(`[RMBG AI] Gagal:`, err.message); process.exit(1); }); }