|
|
""" |
|
|
Example script for using the Transparent Background Remover Inference Endpoint. |
|
|
|
|
|
This script: |
|
|
- Loads three sample images (sample1.png, sample2.png, sample3.png) |
|
|
- Encodes them as base64 data URIs |
|
|
- Builds a JSON payload and sends a POST request to the endpoint |
|
|
- Receives the processed images (base64-encoded) and saves them as PNG files |
|
|
|
|
|
Requirements: |
|
|
- Python 3.10+ |
|
|
- requests |
|
|
|
|
|
Usage: |
|
|
python example.py |
|
|
""" |
|
|
|
|
|
import requests |
|
|
import base64 |
|
|
|
|
|
|
|
|
def encode_image_to_base64(filename): |
|
|
""" |
|
|
Encode an image file to a base64 data URI. |
|
|
|
|
|
Args: |
|
|
filename (str): Path to the image file. |
|
|
|
|
|
Returns: |
|
|
str: Base64-encoded string with data URI prefix. |
|
|
""" |
|
|
with open(filename, "rb") as f: |
|
|
image_bytes = f.read() |
|
|
encoded = base64.b64encode(image_bytes).decode("utf-8") |
|
|
|
|
|
data_uri = f"data:image/png;base64,{encoded}" |
|
|
return data_uri |
|
|
|
|
|
|
|
|
def save_base64_to_file(data_uri, output_filename): |
|
|
""" |
|
|
Decode a base64 data URI and save it as an image file. |
|
|
|
|
|
Args: |
|
|
data_uri (str): The data URI containing the base64-encoded image. |
|
|
output_filename (str): The output filename to save the image. |
|
|
""" |
|
|
header, encoded = data_uri.split(",", 1) |
|
|
image_data = base64.b64decode(encoded) |
|
|
with open(output_filename, "wb") as f: |
|
|
f.write(image_data) |
|
|
print(f"Saved {output_filename}") |
|
|
|
|
|
|
|
|
def main(): |
|
|
|
|
|
endpoint_url = "https://endpoints.huggingface.co/your-endpoint-url" |
|
|
headers = { |
|
|
"Authorization": "Bearer YOUR_API_TOKEN", |
|
|
"Content-Type": "application/json" |
|
|
} |
|
|
|
|
|
|
|
|
sample_images = [ |
|
|
encode_image_to_base64("bear1.png"), |
|
|
encode_image_to_base64("bear2.png"), |
|
|
encode_image_to_base64("bear3.png") |
|
|
] |
|
|
|
|
|
|
|
|
payload = { |
|
|
"inputs": { |
|
|
"images": sample_images, |
|
|
"output_type": "rgba", |
|
|
"threshold": 0.1, |
|
|
"reverse": False |
|
|
} |
|
|
} |
|
|
|
|
|
print("Sending request to endpoint...") |
|
|
response = requests.post(endpoint_url, json=payload, headers=headers) |
|
|
|
|
|
if response.status_code != 200: |
|
|
print("Error:", response.status_code, response.text) |
|
|
return |
|
|
|
|
|
result = response.json() |
|
|
print("Processing Times:\n", result.get("processing_times", "No timing info provided.")) |
|
|
|
|
|
|
|
|
images = result.get("images", []) |
|
|
for idx, data_uri in enumerate(images): |
|
|
save_base64_to_file(data_uri, f"output_{idx+1}.png") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|