Spaces:
Sleeping
Sleeping
File size: 4,441 Bytes
fbb9523 | 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 | """Backend logic for DALL·E AI Image Generator."""
from __future__ import annotations
import base64
import logging
import os
import time
from datetime import datetime
from io import BytesIO
from pathlib import Path
from typing import List, Tuple
from dotenv import load_dotenv
from openai import OpenAI
from PIL import Image
# -------------------------------------------------------------------
# Load Environment Variables
# -------------------------------------------------------------------
load_dotenv()
# -------------------------------------------------------------------
# Directories
# -------------------------------------------------------------------
BASE_DIR = Path(__file__).parent
GENERATED_DIR = BASE_DIR / "generated_images"
LOG_DIR = BASE_DIR / "logs"
GENERATED_DIR.mkdir(exist_ok=True)
LOG_DIR.mkdir(exist_ok=True)
# -------------------------------------------------------------------
# Logging
# -------------------------------------------------------------------
logging.basicConfig(
filename=LOG_DIR / "app.log",
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
)
logger = logging.getLogger(__name__)
# -------------------------------------------------------------------
# OpenAI Client
# -------------------------------------------------------------------
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY")
)
# -------------------------------------------------------------------
# Prompt History
# -------------------------------------------------------------------
prompt_history: List[str] = []
# -------------------------------------------------------------------
# Validation
# -------------------------------------------------------------------
def validate_prompt(prompt: str) -> None:
if not prompt or not prompt.strip():
raise ValueError("Prompt cannot be empty.")
if len(prompt.strip()) < 3:
raise ValueError("Prompt too short.")
# -------------------------------------------------------------------
# Save Image
# -------------------------------------------------------------------
def save_image(image: Image.Image) -> str:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"generated_{timestamp}.png"
output_path = GENERATED_DIR / filename
image.save(output_path)
logger.info("Image saved: %s", output_path)
return str(output_path)
# -------------------------------------------------------------------
# Generate Image
# -------------------------------------------------------------------
def generate_image(
prompt: str,
size: str = "1024x1024",
quality: str = "high",
style: str = "vivid",
retries: int = 3,
) -> Tuple[str, List[str], str]:
validate_prompt(prompt)
prompt_history.append(prompt)
for attempt in range(retries):
try:
logger.info("Generating image: %s", prompt)
response = client.images.generate(
model="gpt-image-1",
prompt=prompt,
size=size,
quality=quality,
n=1,
)
image_base64 = response.data[0].b64_json
image_bytes = base64.b64decode(image_base64)
image = Image.open(BytesIO(image_bytes))
image_path = save_image(image)
return (
image_path,
prompt_history[-10:],
"✅ Image generated successfully!",
)
except Exception as error:
logger.error("Generation failed: %s", error)
if attempt == retries - 1:
return (
None,
prompt_history[-10:],
f"❌ Error: {error}",
)
time.sleep(2)
return (
None,
prompt_history[-10:],
"❌ Unknown error occurred.",
)
# -------------------------------------------------------------------
# Clear History
# -------------------------------------------------------------------
def clear_history():
prompt_history.clear()
return []
"""Main launcher for Gradio app."""
from UI import build_demo
from app import clear_history, generate_image
demo = build_demo()
demo.queue()
demo.launch()
|