Datasets:
File size: 7,585 Bytes
db3126e 72b170b db3126e 72b170b db3126e 72b170b db3126e 72b170b db3126e 72b170b db3126e 72b170b 627f55a 72b170b 627f55a 72b170b 627f55a 72b170b 627f55a 72b170b 627f55a 72b170b 627f55a 72b170b 627f55a 72b170b 627f55a 72b170b db3126e 72b170b db3126e | 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | 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
|