Sking / image_api_utils.py
EntropyDrop
update
627f55a
Raw
History Blame Contribute Delete
7.59 kB
import base64
import binascii
import json
import mimetypes
import os
import time
import requests
from dotenv import load_dotenv
# Load .env file from the directory of this module
env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
load_dotenv(env_path)
IMAGE_API_BASE_URL = os.getenv("IMAGE_API_BASE_URL")
API_KEY = os.getenv("API_KEY")
MAX_REFERENCE_IMAGES = 14
MAX_IMAGE_BYTES = 10 * 1024 * 1024
MAX_BASE64_TOTAL_BYTES = 30 * 1024 * 1024
MAX_REQUEST_BODY_BYTES = 50 * 1024 * 1024
def get_auth_headers(api_key=None, content_type="application/json"):
"""
Construct HTTP headers including Bearer Authorization token.
"""
key = api_key or API_KEY
headers = {}
if content_type:
headers["Content-Type"] = content_type
if key:
headers["Authorization"] = f"Bearer {key}"
return headers
def _validate_data_url(data_url):
header, separator, encoded_data = data_url.partition(",")
header_lower = header.lower()
if (
not separator
or not header_lower.startswith("data:image/")
or ";base64" not in header_lower
):
raise ValueError(
"Inline reference images must use the format "
"'data:image/...;base64,<data>'."
)
try:
decoded_size = len(base64.b64decode(encoded_data, validate=True))
except (binascii.Error, ValueError) as exc:
raise ValueError("Reference image contains invalid base64 data.") from exc
if decoded_size > MAX_IMAGE_BYTES:
raise ValueError(
f"Inline reference image is {decoded_size / 1024 / 1024:.2f}MB after decoding; "
f"the maximum is {MAX_IMAGE_BYTES / 1024 / 1024:.0f}MB."
)
return decoded_size
def _local_image_to_data_url(image_path):
image_path = os.fspath(image_path)
if not os.path.isfile(image_path):
raise FileNotFoundError(f"Local reference image '{image_path}' does not exist.")
file_size = os.path.getsize(image_path)
if file_size > MAX_IMAGE_BYTES:
raise ValueError(
f"Reference image '{image_path}' is {file_size / 1024 / 1024:.2f}MB; "
f"the maximum is {MAX_IMAGE_BYTES / 1024 / 1024:.0f}MB."
)
mime_type, _ = mimetypes.guess_type(image_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError(
f"Could not determine an image MIME type for '{image_path}'. "
"Use a standard image extension such as .png, .jpg, .webp, or .gif."
)
print(f"[*] Encoding local reference image as base64: {image_path}")
with open(image_path, "rb") as image_file:
image_data = image_file.read()
encoded_data = base64.b64encode(image_data).decode("ascii")
return f"data:{mime_type};base64,{encoded_data}", file_size
def prepare_reference_images(image_inputs):
"""Convert local paths to data URLs and validate reference image limits."""
if not image_inputs:
return None
if isinstance(image_inputs, (str, os.PathLike)):
image_inputs = [image_inputs]
else:
image_inputs = list(image_inputs)
if len(image_inputs) > MAX_REFERENCE_IMAGES:
raise ValueError(
f"At most {MAX_REFERENCE_IMAGES} reference images are allowed; "
f"received {len(image_inputs)}."
)
images = []
base64_total_bytes = 0
for image_input in image_inputs:
value = os.fspath(image_input)
value_lower = value.lower()
if value_lower.startswith(("http://", "https://")):
images.append(value)
continue
if value_lower.startswith("data:"):
decoded_size = _validate_data_url(value)
images.append(value)
else:
data_url, decoded_size = _local_image_to_data_url(value)
images.append(data_url)
base64_total_bytes += decoded_size
if base64_total_bytes > MAX_BASE64_TOTAL_BYTES:
raise ValueError(
f"Base64 reference images total {base64_total_bytes / 1024 / 1024:.2f}MB "
f"after decoding; the maximum is "
f"{MAX_BASE64_TOTAL_BYTES / 1024 / 1024:.0f}MB."
)
return images
def encode_json_request(payload):
"""Serialize a JSON request and enforce the API's request-body size limit."""
payload_body = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
if len(payload_body) > MAX_REQUEST_BODY_BYTES:
raise ValueError(
f"Request body is {len(payload_body) / 1024 / 1024:.2f}MB; "
f"the maximum is {MAX_REQUEST_BODY_BYTES / 1024 / 1024:.0f}MB."
)
return payload_body
def poll_task_status(task_id, api_base_url=None, api_key=None, timeout_seconds=320, poll_interval=10):
"""
Polls the async task result from the Grsai nano-banana API.
Queries GET {base_url}/v1/api/result?id={task_id} until the task reaches
a terminal state (succeeded / failed / violation).
"""
base_url = api_base_url or IMAGE_API_BASE_URL
status_url = f"{base_url}/v1/api/result"
start_time = time.time()
print(f"[*] Polling task status (timeout={timeout_seconds}s, interval={poll_interval}s)...")
headers = get_auth_headers(api_key=api_key, content_type=None)
while True:
elapsed = time.time() - start_time
if elapsed > timeout_seconds:
raise TimeoutError(f"Task {task_id} timed out after {timeout_seconds} seconds.")
try:
response = requests.get(status_url, params={"id": task_id}, headers=headers)
response.raise_for_status()
data = response.json()
status = data.get("status")
progress = data.get("progress", 0)
task_id_resp = data.get("id", task_id)
print(f"[*] [Elapsed: {int(elapsed)}s] Task: {task_id_resp}, Status: {status}, Progress: {progress}%")
if status == "succeeded":
results = data.get("results", [])
if not results or not results[0].get("url"):
raise ValueError("Task succeeded but no result URL found in response.")
return results[0]["url"]
if status in ("failed", "violation"):
error_msg = data.get("error", "Unknown error")
raise RuntimeError(f"Task {status}: {error_msg}")
# status == "running" → keep polling
except (requests.RequestException, ValueError, RuntimeError, TimeoutError):
raise
except Exception as e:
print(f"[!] Error querying task status: {e}")
time.sleep(poll_interval)
def download_image(url, output_path):
"""
Downloads the final image from the given URL and saves it locally.
"""
print(f"[*] Downloading result image from: {url}")
response = requests.get(url, stream=True)
response.raise_for_status()
with open(output_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"[+] Image saved successfully to: {output_path}")
def poll_and_download_result(
task_id,
output_path=None,
default_prefix="result",
api_base_url=None,
api_key=None,
):
"""Poll a media task and download its final image."""
result_url = poll_task_status(
task_id,
api_base_url=api_base_url,
api_key=api_key,
)
if not output_path:
output_path = f"{default_prefix}_{int(time.time())}.png"
download_image(result_url, output_path)
return output_path