Files
html/api/ambre-tool-bg-remove.php
2026-04-22 00:35:02 +02:00

60 lines
2.0 KiB
PHP

<?php
header("Content-Type: application/json; charset=utf-8");
$in = json_decode(file_get_contents("php://input"), true) ?: $_POST ?: $_GET;
$url = trim($in["url"] ?? $in["image_url"] ?? "");
if (!$url) { echo json_encode(["error"=>"image url required"]); exit; }
$t0 = microtime(true);
$ctx = stream_context_create(["http"=>["timeout"=>20]]);
$orig = @file_get_contents($url, false, $ctx);
if (!$orig) { echo json_encode(["error"=>"source fetch failed"]); exit; }
// Ensure cache dir exists and is writable by www-data
$cache_dir = "/tmp/u2net_cache";
if (!is_dir($cache_dir)) @mkdir($cache_dir, 0777, true);
$tmp_in = tempnam(sys_get_temp_dir(), "bgin_") . ".png";
$tmp_out = tempnam(sys_get_temp_dir(), "bgout_") . ".png";
file_put_contents($tmp_in, $orig);
$py = <<<PYTHON
import os
os.environ['U2NET_HOME'] = '/tmp/u2net_cache'
os.environ['XDG_CACHE_HOME'] = '/tmp/xdg_cache'
from rembg import remove
with open('$tmp_in', 'rb') as f:
input_bytes = f.read()
output = remove(input_bytes)
with open('$tmp_out', 'wb') as f:
f.write(output)
print('OK')
PYTHON;
$py_file = tempnam(sys_get_temp_dir(), "bgpy_") . ".py";
file_put_contents($py_file, $py);
// Run with extended timeout for first-time model download (~170MB)
$run_out = @shell_exec("timeout 300 python3 $py_file 2>&1");
@unlink($py_file);
$result = @file_get_contents($tmp_out);
@unlink($tmp_in); @unlink($tmp_out);
if (!$result || strlen($result) < 500) {
echo json_encode(["error"=>"rembg processing failed", "py_out"=>substr($run_out ?? "", 0, 500)]);
exit;
}
$dir = "/var/www/html/generated";
if (!is_dir($dir)) @mkdir($dir, 0755, true);
$filename = "wevia-bgremove-" . date("Ymd-His") . "-" . bin2hex(random_bytes(3)) . ".png";
file_put_contents("$dir/$filename", $result);
echo json_encode([
"success"=>true, "original"=>$url,
"url"=>"https://weval-consulting.com/generated/$filename",
"size_kb"=>round(strlen($result)/1024, 1),
"elapsed_ms"=>round((microtime(true)-$t0)*1000),
"provider"=>"WEVIA BG Remove",
]);