OpenAI DALL-E 3 - Image Generation

Lancer : Codespaces Colab

Navigation : Index | Next >>

Module : 01-Images-Foundation Level : Beginner Technologies : OpenAI DALL-E 3, direct OpenAI API Estimated duration : 25 minutes

Learning Objectives

Prerequisites

  • Environment Setup (module 00) completed
  • OpenAI API key configured (OPENAI_API_KEY in .env)
  • Basic knowledge of prompting

Important note : DALL-E 3 requires the direct OpenAI API (api.openai.com). OpenRouter does NOT support the /v1/images/generations endpoint. If you only have an OpenRouter key, skip to notebook 01-2 (GPT-5 image analysis).

Scholarly grounding. DALL-E 3 has no dedicated scientific paper; OpenAI announced it in a blog post (October 2023) accompanied by an official System Card. Its main innovation – the automatic prompt rewriting (the famous prompt revision taught below) – comes from a language model (GPT-4) that densifies the description, and from training on improved captions (recaptioning): see the DALL-E 3 System Card (OpenAI, 2023) and, for the architectural lineage (CLIP latents + diffusion), the DALL-E 2 paper [Ramesh et al. 2022, arXiv:2204.06125].

# Parametres Papermill - JAMAIS modifier ce commentaire

# Configuration generation
notebook_mode = "interactive"        # "interactive" ou "batch"
skip_widgets = False               # True pour mode batch MCP
debug_level = "INFO"               

# Parametres generation d'images (famille gpt-image)
model_name = "gpt-image-1.5"       # gpt-image-1 retire du compte le 2026-10-28 (400 a la generation), pas OpenRouter
image_size = "1024x1024"           # "1024x1024", "1536x1024", "1024x1536"
image_quality = "medium"           # "low", "medium", "high", "auto"
image_style = "vivid"              # concept pedagogique (la famille gpt-image ignore "style", le controle se fait via le prompt)
n_images = 1                       # Nombre d'images (1 pour DALL-E 3)

# Configuration sauvegarde
generate_images = True             # Generer les images (False pour validation structurelle seule)
save_images = True                 # Sauvegarder images generees
generate_variations = False        # Creer variations du prompt
export_metadata = True             # Exporter metadonnees generation
# Parameters
BATCH_MODE = "true"

Environment setup

Installing dependencies, loading the API configuration, and preparing the generation utilities.

# Import guards - availability flags for external dependencies

try:
    from PIL import Image
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False
    print(f'  PIL non disponible - certaines fonctionnalites seront limitees')

try:
    from dotenv import load_dotenv
    DOTENV_AVAILABLE = True
except ImportError:
    DOTENV_AVAILABLE = False
    print(f'  dotenv non disponible - certaines fonctionnalites seront limitees')

try:
    import requests
    REQUESTS_AVAILABLE = True
except ImportError:
    REQUESTS_AVAILABLE = False
    print(f'  requests non disponible - certaines fonctionnalites seront limitees')


# Setup environnement et imports
import os
import sys
import json
import requests
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional
import base64
from io import BytesIO
from PIL import Image
import matplotlib.pyplot as plt
import logging

# Import helpers GenAI
# Chargement robuste de la configuration .env
from dotenv import load_dotenv
import os
# Recherche du .env dans tous les parents (pour Papermill qui change le cwd)
current_path = Path.cwd()
env_loaded = False
for _ in range(10):
    env_path = current_path / ".env"
    if env_path.exists():
        load_dotenv(env_path)
        print(f".env charge depuis: {env_path.name}")
        env_loaded = True
        break
    current_path = current_path.parent
    if len(current_path.parts) <= 1:
        break
if not env_loaded:
    print("WARNING: .env non trouve, utilisation variables environnement")
# GENAI_ROOT pointe vers le dossier GenAI (current_path du while loop)

HELPERS_PATH = current_path / 'shared' / 'helpers'
if HELPERS_PATH.exists():
    sys.path.insert(0, str(HELPERS_PATH.parent))
    try:
        from helpers.genai_helpers import setup_genai_logging, load_genai_config, save_generation_result
        print("✅ Helpers GenAI importés")
    except ImportError:
        print("⚠️  Helpers GenAI non disponibles - mode autonome")

# Configuration logging
logging.basicConfig(level=getattr(logging, debug_level))
logger = logging.getLogger('dalle3_generation')

print(f"🎨 OpenAI DALL-E 3 - Génération d'Images")
print(f"📅 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"🔧 Mode: {notebook_mode}, Qualité: {image_quality}, Style: {image_style}")
WARNING: .env non trouve, utilisation variables environnement
🎨 OpenAI DALL-E 3 - Génération d'Images
📅 2026-10-28 22:35:41
🔧 Mode: interactive, Qualité: medium, Style: vivid

The Python environment is initialized. The next cell configures authentication with the direct OpenAI API and checks that the gpt-image family (OpenAI’s current image generation model, which succeeded DALL-E 3 in 2025) is accessible via /v1/images/generations.

Scoping note (issue #8474, EPIC #8052). The historical title of this notebook mentions DALL-E 3 – that name remains a pedagogical through-line (the concept of automatic prompt rewriting, the mapping of the size/quality/style parameters come from the DALL-E 3 era). In practice, all generations in this notebook use the gpt-image family (default model gpt-image-1) because DALL-E 3 has been retired by OpenAI. See the doc-honesty cell below for the details of the automatic fallback.

# Configuration API OpenAI pour la generation d'images
# IMPORTANT: DALL-E 3 necessite l'API OpenAI directe (pas OpenRouter)
# OpenRouter ne supporte PAS le endpoint /v1/images/generations

print("\n--- CONFIGURATION API GENERATION D'IMAGES ---")
print("=" * 40)

# Verification cle API OpenAI
openai_key = os.getenv('OPENAI_API_KEY')
openai_base = os.getenv('OPENAI_BASE_URL', 'https://api.openai.com/v1')

# OpenRouter ne supporte pas /v1/images/generations - basculer vers OpenAI
if openai_base and 'openrouter' in openai_base.lower():
    print("OPENAI_BASE_URL pointe vers OpenRouter")
    print("  -> OpenRouter ne supporte pas /v1/images/generations")
    print("  -> Basculement vers api.openai.com pour DALL-E 3")
    openai_base = "https://api.openai.com/v1"

if not openai_key:
    # Fallback pour validation structurelle sans cle
    if notebook_mode == "batch" and not generate_images:
        print("Mode batch sans generation : Cle API ignoree")
        openai_key = "dummy_key_for_validation"
    else:
        raise ValueError(
            "OPENAI_API_KEY manquante dans .env\n"
            "DALL-E 3 necessite une cle API OpenAI directe.\n"
            "OpenRouter ne supporte pas la generation d'images DALL-E.\n"
            "Obtenez votre cle sur: https://platform.openai.com/api-keys"
        )

# Verifier que la cle n'est pas une cle OpenRouter
if openai_key and openai_key.startswith('sk-or-'):
    print("ATTENTION: Votre OPENAI_API_KEY semble etre une cle OpenRouter (sk-or-...)")
    print("  DALL-E 3 necessite une cle OpenAI directe (sk-proj-... ou sk-...)")
    print("  La generation d'images risque d'echouer.")

print(f"Cle API OpenAI configuree")

# Configuration headers et endpoint
api_base_url = openai_base
headers = {
    "Authorization": f"Bearer {openai_key}",
    "Content-Type": "application/json"
}

# Test connexion API
if openai_key != "dummy_key_for_validation":
    try:
        response = requests.get(f"{api_base_url}/models", headers=headers, timeout=10)
        if response.status_code == 200:
            models_data = response.json()
            dalle_models = [m for m in models_data.get('data', []) if 'dall-e' in m.get('id', '').lower()]
            print(f"Connexion API OpenAI reussie - {len(dalle_models)} modeles DALL-E disponibles")
            
            for model in dalle_models[:3]:
                print(f"  - {model['id']}")
        else:
            print(f"Connexion API: HTTP {response.status_code}")
    except Exception as e:
        print(f"Erreur connexion: {str(e)[:100]}...")
else:
    print("Test connexion API saute (dummy key)")
    
print(f"\nModele selectionne: {model_name}")
print(f"Resolution: {image_size}")
print(f"Style: {image_style}, Qualite: {image_quality}")
print(f"API: {api_base_url}")

--- CONFIGURATION API GENERATION D'IMAGES ---
========================================
Cle API OpenAI configuree
Connexion API OpenAI reussie - 0 modeles DALL-E disponibles

Modele selectionne: gpt-image-1.5
Resolution: 1024x1024
Style: vivid, Qualite: medium
API: https://api.openai.com/v1

On the model actually used: DALL-E 3 -> gpt-image-1

Documentary honesty note (EPIC #8052). The previous cell checks the availability of DALL-E 3 with the OpenAI API. The committed output shows Connexion API OpenAI reussie - 0 modeles DALL-E disponibles, then an automatic fallback to gpt-image-1 — OpenAI’s current image generation model. The committed outputs in this notebook (generation time, data-URI encoded image) were therefore produced by gpt-image-1, and not by DALL-E 3.

Why keep the “DALL-E 3” framing in the title and the comments?

  • Pedagogical anchor: DALL-E 3 is the historically taught name for this family of image generation models; keeping it as a through-line makes reading easier.
  • The API is identical: the /v1/images/generations endpoint and the parameters (size, quality, style) are shared, only the model name changes.
  • Transparency: this note makes the fallback explicit so that the prose does not silently contradict the committed outputs (doc-honesty principle of Epic #8052).

If DALL-E 3 becomes available again (or to switch to another model), it suffices to adjust the model selection in the configuration cell and re-run; the notebook structure remains valid.

Generation function and prompts

Let us define the function that calls the DALL-E 3 API, then prepare a set of optimized prompts illustrating different styles (photorealistic, artistic, technical).

# Fonction de génération d'image via l'API OpenAI (famille gpt-image)
# - Migration DALL-E 3 -> famille gpt-image (cf. issue #8474, EPIC #8052 ; gpt-image-1.5 depuis le 2026-10-28).
# - Le modele `model_name` (cfg Papermill) pointe sur gpt-image-1.5 depuis le 2026-10-28.
# - L'endpoint /v1/images/generations est commun aux deux familles.
# - Nom de fonction neutre ("image") pour absorber l'evolution future
#   (gpt-image-1.5/2/... ou retour d'un successeur DALL-E).
def generate_image(prompt: str,
                   size: str = "1024x1024",
                   quality: str = "medium",
                   style: str = "vivid") -> Dict[str, Any]:
    """
    Génère une image avec la famille gpt-image (OpenAI) via l'API directe.

    Args:
        prompt: Description textuelle de l'image
        size: Dimensions (1024x1024, 1536x1024, 1024x1536)
        quality: Qualité (low/medium/high/auto)
        style: Concept pédagogique hérité de DALL-E 3 (vivid/natural).
               gpt-image-1 ignore ce param -- le contrôle se fait via le prompt.

    Returns:
        Dict avec URL/data-URI, métadonnées et statut
    """

    # Payload de la requête
    payload = {
        "model": model_name,
        "prompt": prompt,
        "n": 1,  # gpt-image-1 : une image par requête
        "size": size,
        "quality": quality  # famille gpt-image : pas de "style" ni "response_format" (params DALL-E 3 -> 400)
    }

    try:
        print(f"\n[generate_image] Génération en cours...")
        print(f"[generate_image] Prompt: {prompt[:100]}{'...' if len(prompt) > 100 else ''}")

        # Requête API
        response = requests.post(
            f"{api_base_url}/images/generations",
            headers=headers,
            json=payload,
            timeout=120
        )

        if response.status_code == 200:
            result = response.json()
            _d = result["data"][0]
            _url = _d.get("url")
            _b64 = _d.get("b64_json")
            # gpt-image-1 retourne b64_json (pas d'URL) ; DALL-E 3 retournait une URL.
            # On construit un data-URI pour que les <img>/PIL/matplotlib en aval fonctionnent.
            _image_src = _url if _url else (f"data:image/png;base64,{_b64}" if _b64 else None)

            return {
                "success": True,
                "image_url": _image_src,
                "revised_prompt": _d.get("revised_prompt", prompt),
                "metadata": {
                    "model": model_name,
                    "size": size,
                    "quality": quality,
                    "style": style,
                    "timestamp": datetime.now().isoformat(),
                    "original_prompt": prompt
                },
                "response_time": response.elapsed.total_seconds()
            }
        else:
            error_msg = response.json().get("error", {}).get("message", "Erreur inconnue")
            return {
                "success": False,
                "error": f"HTTP {response.status_code}: {error_msg}",
                "prompt": prompt
            }

    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "prompt": prompt
        }

print("[ok] Fonction generate_image() prête (famille gpt-image via OpenAI directe)")
[ok] Fonction generate_image() prête (famille gpt-image via OpenAI directe)

Generation and analysis of results

Let us launch image generation with the optimized prompts above, then analyze the quality of the results and the iterative prompt improvement strategies.

# Exemples de prompts optimisés pour DALL-E 3
print("\n[exemples] EXEMPLES DE GÉNÉRATION DALL-E 3")
print("=" * 45)

# Prompts de démonstration
# Note (issue #8624, see also #8474) : on retire les prefixes emoji des titres
# pour eviter qu'ils soient cuits dans les bandeaux de titre des figures generees
# via matplotlib (defaut de police fallback sur les runners Jupyter ; glyphe □
# au lieu du U+1F3D9 CITYSCAPE). Defense-in-depth a la source : la cellule
# `82075ed6` applique deja un `_ascii_title = _re.sub(r'[^\x00-\x7F]+', ' ', ...)`
# au moment du rendu matplotlib (patch c.910v2, PR #8611), mais stripper en amont
# garantit aussi des stdout propres (print(f"{i}. {example['title']}")).
example_prompts = [
    {
        "title": "Paysage Urbain Futuriste",
        "prompt": "A futuristic cityscape at sunset with flying cars, neon lights reflecting on glass buildings, holographic advertisements, and a diverse crowd of people walking on illuminated sidewalks. Ultra-detailed, cinematic lighting, 8K quality.",
        "category": "Architecture/Sci-Fi"
    },
    {
        "title": "Portrait Artistique",
        "prompt": "An elegant woman with flowing auburn hair, wearing a vintage emerald dress, sitting in a library filled with ancient books. Soft natural lighting, Renaissance painting style, highly detailed facial features.",
        "category": "Portrait/Artistique"
    },
    {
        "title": "Créature Fantastique",
        "prompt": "A majestic unicorn with an iridescent mane standing in an enchanted forest with glowing mushrooms, fairy lights, and morning mist. Fantasy art style, magical atmosphere, vibrant colors.",
        "category": "Fantasy/Créature"
    },
    {
        "title": "Nourriture Stylisée",
        "prompt": "A gourmet pizza with fresh basil, cherry tomatoes, and mozzarella on a wooden board, surrounded by Italian ingredients. Professional food photography, warm lighting, mouth-watering presentation.",
        "category": "Food/Lifestyle"
    }
]

# Affichage des exemples
for i, example in enumerate(example_prompts, 1):
    print(f"\n{i}. {example['title']}")
    print(f"   [cat] Catégorie: {example['category']}")
    print(f"   [prompt] Prompt: {example['prompt'][:120]}...")

print(f"\n[conseils] Conseils pour DALL-E 3:")
print(f"- Soyez descriptifs et specifiques")
print(f"- Mentionnez le style artistique desire")
print(f"- Precisez l'eclairage et l'atmosphere")
print(f"- Utilisez des termes techniques (8K, cinematic, etc.)")
print(f"- DALL-E 3 revise automatiquement vos prompts")

[exemples] EXEMPLES DE GÉNÉRATION DALL-E 3
=============================================

1. Paysage Urbain Futuriste
   [cat] Catégorie: Architecture/Sci-Fi
   [prompt] Prompt: A futuristic cityscape at sunset with flying cars, neon lights reflecting on glass buildings, holographic advertisements...

2. Portrait Artistique
   [cat] Catégorie: Portrait/Artistique
   [prompt] Prompt: An elegant woman with flowing auburn hair, wearing a vintage emerald dress, sitting in a library filled with ancient boo...

3. Créature Fantastique
   [cat] Catégorie: Fantasy/Créature
   [prompt] Prompt: A majestic unicorn with an iridescent mane standing in an enchanted forest with glowing mushrooms, fairy lights, and mor...

4. Nourriture Stylisée
   [cat] Catégorie: Food/Lifestyle
   [prompt] Prompt: A gourmet pizza with fresh basil, cherry tomatoes, and mozzarella on a wooden board, surrounded by Italian ingredients. ...

[conseils] Conseils pour DALL-E 3:
- Soyez descriptifs et specifiques
- Mentionnez le style artistique desire
- Precisez l'eclairage et l'atmosphere
- Utilisez des termes techniques (8K, cinematic, etc.)
- DALL-E 3 revise automatiquement vos prompts

The previous prompt examples illustrate the different stylistic categories. Now let us move on to actual generation: the next cell sends the request to the DALL-E 3 API and displays the produced image.

# Generation d'images avec les exemples
print("\n[generate_image] DEMONSTRATION")
print("=" * 50)

# Selection d'un prompt pour la demonstration
selected_example = example_prompts[0]  # Paysage urbain futuriste
print(f"[generate_image] Prompt: {selected_example['title']}")

# Generation de l'image
result = generate_image(
    prompt=selected_example['prompt'],
    size=image_size,
    quality=image_quality,
    style=image_style
)

if result['success']:
    print(f"\n[ok] Image generee avec succes!")
    print(f"[ok] Temps de generation: {result['response_time']:.2f}s")
    _src = result['image_url']
    print(f"[ok] Source: {'image b64 (data-URI, gpt-image-1)' if _src.startswith('data:') else _src[:100]}")

    # Affichage du prompt revise par gpt-image (historiquement DALL-E 3)
    if result.get('revised_prompt') != selected_example['prompt']:
        print(f"\n[prompt] Original:")
        print(f"   {selected_example['prompt'][:150]}...")
        print(f"\n[prompt] Revise par gpt-image:")
        print(f"   {result['revised_prompt'][:150]}...")

    # Telechargement et affichage de l'image
    try:
        print(f"\n[fetch] Recuperation de l'image...")
        _img_src = result['image_url']
        if _img_src.startswith('data:'):
            # gpt-image-1 (data-URI b64) : decoder directement, pas de telechargement HTTP
            image = Image.open(BytesIO(base64.b64decode(_img_src.split(',', 1)[1])))
            _fetched = True
        else:
            # DALL-E 3 legacy (URL HTTP) : telecharger
            img_response = requests.get(_img_src, timeout=30)
            image = Image.open(BytesIO(img_response.content)) if img_response.status_code == 200 else None
            _fetched = image is not None

        if _fetched:
            # Stop & Repair (issue #8474 + #8624) : matplotlib leve UserWarning sur les
            # glyphes emoji (ex. U+1F3D9 CITYSCAPE), ce qui leak via stderr Jupyter le chemin
            # du pylabtools.py du runner. On degage uniquement les pictogrammes emojis du
            # titre matplotlib ; les accents francais (DejaVu Sans les couvre) restent, et
            # `selected_example['title']` reste intact pour stdout.
            import re as _re
            _EMOJI = r'[🀀-🫿☀-➿⌀-⏿⬀-⯿‍]+'
            _ascii_title = _re.sub(_EMOJI, '', selected_example['title']).strip()

            # Affichage avec matplotlib
            plt.figure(figsize=(12, 8))
            plt.imshow(image)
            plt.axis('off')
            plt.title(f"{_ascii_title} - {model_name}", fontsize=16, pad=20)
            plt.tight_layout()
            plt.show()

            print(f"[ok] Image affichee - Dimensions: {image.size}")

            # Sauvegarde optionnelle
            if save_images:
                output_dir = current_path / 'outputs' / 'gpt_image'
                output_dir.mkdir(parents=True, exist_ok=True)

                timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                filename = f"gpt_image_{timestamp}.png"
                filepath = output_dir / filename

                image.save(filepath)
                print(f"[ok] Image sauvegardee: {filepath.name}")

                # Export metadonnees
                if export_metadata:
                    metadata_file = output_dir / f"gpt_image_{timestamp}_metadata.json"
                    with open(metadata_file, 'w', encoding='utf-8') as f:
                        json.dump(result['metadata'], f, indent=2, ensure_ascii=False)
                    print(f"[ok] Metadonnees exportees: {metadata_file.name}")
        else:
            print(f"[err] Erreur recuperation image")

    except Exception as e:
        print(f"[err] Erreur affichage image: {str(e)[:100]}...")
        print(f"[hint] Vous pouvez acceder a l'image via: {result['image_url']}")
else:
    print(f"\n[err] Echec de la generation")
    print(f"[err] Erreur: {result['error']}")
    print(f"[hint] Prompt teste: {result['prompt'][:100]}...")

[generate_image] DEMONSTRATION
==================================================
[generate_image] Prompt: Paysage Urbain Futuriste

[generate_image] Génération en cours...
[generate_image] Prompt: A futuristic cityscape at sunset with flying cars, neon lights reflecting on glass buildings, hologr...

[ok] Image generee avec succes!
[ok] Temps de generation: 12.96s
[ok] Source: image b64 (data-URI, gpt-image-1)

[fetch] Recuperation de l'image...

[ok] Image affichee - Dimensions: (1024, 1024)
[ok] Image sauvegardee: gpt_image_20261028_223557.png
[ok] Metadonnees exportees: gpt_image_20261028_223557_metadata.json

Guided example 1 : Progressive prompt construction

The previous demonstration sends an already rich prompt. This guided example instead starts from a minimal description and enriches it over 3 successive iterations, for an image of a “robot assistant in a modern office”:

  1. A minimalist prompt (basic description of the subject)
  2. Adding the artistic style, the lighting, and the color palette
  3. Adding technical terms (“ultra-detailed”, “cinematic composition”, “8K”, “sharp focus”, “shallow depth of field”)

The three images are generated then displayed side by side. The group recorded its observations in the observations variable: they describe its images, and each run produces new ones. The reading below the cell confronts them with the images displayed here.

Worth knowing : unlike DALL-E 3, gpt-image-1 does not return a revised prompt, and generate_image() then falls back to the original prompt. The cell reports this instead of displaying the original prompt as if it had been rewritten.

Student contribution by Yao LIU (@liuyao0010-debug), Zihao CHENG and Ruofan ZHAO: the three prompts in PR #18449, the generation and comparison of the images in PR #18561, integrated as a guided example.

# ============================================================
# Exemple guide 1 : Construction progressive de prompts (contribution etudiante, PR #18449 et #18561)
# ============================================================

# Etape 1 : Prompt minimaliste
# Description basique du sujet en une phrase, sans style ni details.
prompt_niveau_1 = "A robot assistant in a modern office"

# Etape 2 : Ajout de style et eclairage
# On precise le style artistique, l'eclairage et la palette de couleurs.
prompt_niveau_2 = (
    "A friendly robot assistant in a modern office, "
    "soft natural lighting, digital art style, warm color palette"
)

# Etape 3 : Ajout de details techniques
# On ajoute resolution, composition, nettete et profondeur de champ.
prompt_niveau_3 = (
    "A friendly robot assistant in a modern office, "
    "soft natural lighting, digital art style, warm color palette, "
    "ultra-detailed, cinematic composition, 8K, sharp focus, "
    "shallow depth of field"
)

# ------------------------------------------------------------
# Generation des trois niveaux
# ------------------------------------------------------------
results = {}  # stocke les resultats pour l'analyse

for i, prompt in enumerate([prompt_niveau_1, prompt_niveau_2, prompt_niveau_3], 1):
    print(f"\n--- Prompt niveau {i} ---")
    print(f"Texte : {prompt}")

    result = generate_image(prompt=prompt, size="1024x1024")
    results[f"niveau_{i}"] = result

    if result['success']:
        # Integration : gpt-image-1 ne renvoie pas de revised_prompt, generate_image() retombe
        # alors sur le prompt d'origine, qu'il ne faut pas lire comme une reecriture
        if result['revised_prompt'].strip() != prompt.strip():
            print(f"Prompt revise par gpt-image : {result['revised_prompt'][:200]}...")
        else:
            print("Prompt revise : aucun renvoye par l'API (gpt-image-1)")
        print(f"Temps de generation : {result['response_time']:.2f}s")
    else:
        print(f"Echec : {result['error']}")

# ------------------------------------------------------------
# Etape 4 : Observations du groupe, ecrites sur SES images (chaque execution en produit
# de nouvelles : la lecture sous la cellule les confronte a celles-ci)
# ------------------------------------------------------------
observations = (
    "Niveau 1 : image correcte mais generique ; le modele doit deviner "
    "le style, l'ambiance et la composition.\n"
    "Niveau 2 : l'ajout du style artistique et de l'eclairage change "
    "nettement l'atmosphere (couleurs chaudes, lumiere douce).\n"
    "Niveau 3 : les termes techniques (ultra-detailed, cinematic, 8K, "
    "sharp focus, shallow depth of field) donnent un rendu plus "
    "professionnel et une meilleure composition.\n"
    "=> Les elements qui ont le plus d'impact : le style artistique et "
    "l'eclairage. Les termes techniques affinent ensuite la qualite "
    "et la mise en scene."
)

print("\n--- Observations du groupe (sur sa propre execution) ---")
print(observations)

# ------------------------------------------------------------
# Affichage cote a cote des 3 images (si generation reussie)
# ------------------------------------------------------------
import matplotlib.pyplot as plt
from io import BytesIO
import base64
import requests

if generate_images and all(r.get('success') for r in results.values()):
    fig, axes = plt.subplots(1, 3, figsize=(18, 6))
    titres = ["Niveau 1 : minimaliste",
              "Niveau 2 : + style/eclairage",
              "Niveau 3 : + details techniques"]

    for ax, (key, res), titre in zip(axes, results.items(), titres):
        src = res['image_url']
        # Cas 1 : data-URI (b64_json renvoye par gpt-image-1)
        if src.startswith("data:image"):
            b64 = src.split(",", 1)[1]
            img = Image.open(BytesIO(base64.b64decode(b64)))
        # Cas 2 : URL classique (DALL-E 3)
        else:
            img = Image.open(BytesIO(requests.get(src).content))

        ax.imshow(img)
        ax.set_title(titre, fontsize=11)
        ax.axis("off")

    plt.tight_layout()
    plt.show()
else:
    print("\n[info] Generation non executee ou incomplete : "
          "affichage des images ignore.")

--- Prompt niveau 1 ---
Texte : A robot assistant in a modern office

[generate_image] Génération en cours...
[generate_image] Prompt: A robot assistant in a modern office
Prompt revise : aucun renvoye par l'API (gpt-image-1)
Temps de generation : 10.84s

--- Prompt niveau 2 ---
Texte : A friendly robot assistant in a modern office, soft natural lighting, digital art style, warm color palette

[generate_image] Génération en cours...
[generate_image] Prompt: A friendly robot assistant in a modern office, soft natural lighting, digital art style, warm color ...
Prompt revise : aucun renvoye par l'API (gpt-image-1)
Temps de generation : 10.35s

--- Prompt niveau 3 ---
Texte : A friendly robot assistant in a modern office, soft natural lighting, digital art style, warm color palette, ultra-detailed, cinematic composition, 8K, sharp focus, shallow depth of field

[generate_image] Génération en cours...
[generate_image] Prompt: A friendly robot assistant in a modern office, soft natural lighting, digital art style, warm color ...
Prompt revise : aucun renvoye par l'API (gpt-image-1)
Temps de generation : 12.77s

--- Observations du groupe (sur sa propre execution) ---
Niveau 1 : image correcte mais generique ; le modele doit deviner le style, l'ambiance et la composition.
Niveau 2 : l'ajout du style artistique et de l'eclairage change nettement l'atmosphere (couleurs chaudes, lumiere douce).
Niveau 3 : les termes techniques (ultra-detailed, cinematic, 8K, sharp focus, shallow depth of field) donnent un rendu plus professionnel et une meilleure composition.
=> Les elements qui ont le plus d'impact : le style artistique et l'eclairage. Les termes techniques affinent ensuite la qualite et la mise en scene.

Reading the result — guided example 1

  • Level 1 (“A robot assistant in a modern office”): with no style instruction, the model chooses a photographic rendering: a white robot waving, a gray desk, the cold light of a window. The image is not poor; it shows the model’s default choice, which one only notices by comparing it with the next levels.
  • Level 2 (+ “digital art style, soft natural lighting, warm color palette”): this is the strongest change of the three. The rendering becomes an illustration with thick lines, and the whole image shifts to a monochrome orange-sepia palette. The group’s observation holds: style and lighting are the levers that change the image most.
  • Level 3 (+ “ultra-detailed, cinematic composition, 8K, sharp focus, shallow depth of field”): the technical terms do more than refine level 2. They bring the rendering back toward photography, even though “digital art style” is still in the prompt: “8K”, “sharp focus” and “shallow depth of field” belong to the vocabulary of photography, and the model follows it. The shallow depth of field is clearly visible (blurred background) and the warm palette of level 2 is preserved. The group noted at level 3 “a more professional rendering”; in this run, it is mostly the medium that changes.
  • Revised prompt: for the three levels, the API returns none. This is the finding the group made in its exercise 3 (guided example 3).
  • What we can conclude, and what we cannot: each level was generated only once. The gap between levels 1 and 2 is massive enough to survive the draw. The return to photography in level 3 remains to be confirmed over several generations: two conflicting keywords (“digital art” against “8K”) can be arbitrated differently from one call to the next.

Guided example 2 : vivid versus natural — prompt engineering, not style=

Context : a client hesitates between a “vivid and creative” visual and a “natural and realistic” visual. DALL-E 3 exposed a style parameter with two values for this: vivid (saturated colors, dramatic rendering) and natural (more discreet photographic rendering). The original cell 18 used style="vivid" and style="natural" with the same prompt.

What you need to know before looking at the images : gpt-image-1, the model actually called by generate_image(), silently refuses the style= parameter (it is reserved for dall-e-3). The two requests were therefore strictly identical — the function only sends model, prompt, n, size and quality — and the only difference between the two images was the model’s random draw.

The lever that works on gpt-image-1 : prompt engineering. We build two prompts that differ in their adjectives (“vivid, saturated, dramatic, high contrast, hyper-detailed” versus “natural, soft, realistic, low contrast, as if shot on a smartphone”), which the model can translate into genuinely distinct colors, brightness and atmosphere. The color comparison then rests on two requests that differ by construction, not by draw.

The cell 18 below applies this lever, generates the two images, and ends with a measure of saturation (standard deviation of the RGB channels) and of brightness (overall mean) on the two images. A cell 20 uses a complementary measure (PIL.ImageStat in HSV) to check the robustness of the comparison.

Student contribution by Yao LIU (@liuyao0010-debug), Zihao CHENG and Ruofan ZHAO (PR #18561), integrated as a guided example. Revision for issue #20682 : the ignored style= parameter is replaced by a prompt engineering lever that is actually transmitted to gpt-image-1.

# Exemple guide 2 : vivid contre natural -- levier prompt engineering (issue #20682)
#
# Le parametre style= de DALL-E 3 (vivid/natural) n'est pas transmis par generate_image()
# sur gpt-image-1, qui le refuse en silence. Les requetes d'origine etaient donc identiques
# (cf cellule 17 du carnet) : la comparaison de couleurs ne portait que sur le tirage.
#
# Le levier qui fonctionne sur gpt-image-1, c'est l'ingenierie de prompt : des adjectifs
# explicites dans le prompt qui DIFFERENT entre les deux appels, ce que le modele peut
# traduire en couleurs, luminosite et ambiance reellement distinctes. La mesure de la
# saturation et de la luminosite (cellule 20) peut alors porter une comparaison legitime.

from io import BytesIO
import base64
import requests
import matplotlib.pyplot as plt
from PIL import Image

# Etape 1 : Deux prompts distincts -- le levier qui marche sur gpt-image-1
prompt_vivid = (
    "A futuristic city street at sunset, with modern buildings, "
    "pedestrians and autonomous vehicles."
    "Vivid, saturated colors, dramatic cinematic lighting, high contrast, "
    "hyper-detailed, eye-catching."
)

prompt_natural = (
    "A futuristic city street at sunset, with modern buildings, "
    "pedestrians and autonomous vehicles."
    "Natural soft lighting, realistic muted colors, photographic look, "
    "low contrast, as if shot on a smartphone camera."
)

# Etape 2 : Generation vivid (lever prompt engineering, pas de style=)
result_vivid = generate_image(
    prompt=prompt_vivid,
    size="1024x1024",
    quality="medium",
)

# Etape 3 : Generation natural (lever prompt engineering, pas de style=)
result_natural = generate_image(
    prompt=prompt_natural,
    size="1024x1024",
    quality="medium",
)


# Fonction pour convertir le resultat en image PIL
def load_generated_image(result):
    if not result["success"]:
        return None

    image_src = result["image_url"]

    # Cas gpt-image : image retournee en base64
    if image_src.startswith("data:"):
        image_data = base64.b64decode(image_src.split(",", 1)[1])
        return Image.open(BytesIO(image_data))

    # Cas URL HTTP
    response = requests.get(image_src, timeout=30)

    if response.status_code == 200:
        return Image.open(BytesIO(response.content))

    return None


img_vivid = load_generated_image(result_vivid)
img_natural = load_generated_image(result_natural)


# Comparaison visuelle : deux images cote a cote
fig, axes = plt.subplots(1, 2, figsize=(14, 7))

if img_vivid is not None:
    axes[0].imshow(img_vivid)
    axes[0].set_title("VIVID (lever : prompt adjectives)\n")
    axes[0].axis("off")
else:
    axes[0].text(0.5, 0.5, "Echec de la generation vivid")
    axes[0].axis("off")

if img_natural is not None:
    axes[1].imshow(img_natural)
    axes[1].set_title("NATURAL (lever : prompt adjectives)\n")
    axes[1].axis("off")
else:
    axes[1].text(0.5, 0.5, "Echec de la generation natural")
    axes[1].axis("off")

plt.tight_layout()
plt.show()


# Comparaison des couleurs moyennes (saturation, luminosite)
import numpy as np

if img_vivid is not None and img_natural is not None:
    arr_vivid = np.array(img_vivid.convert("RGB"))
    arr_natural = np.array(img_natural.convert("RGB"))

    # Saturation moyenne (ecart-type sur les 3 canaux)
    sat_vivid = float(np.mean(np.std(arr_vivid, axis=2)))
    sat_natural = float(np.mean(np.std(arr_natural, axis=2)))

    # Luminosite moyenne (moyenne globale)
    lum_vivid = float(np.mean(arr_vivid))
    lum_natural = float(np.mean(arr_natural))

    print(f"Saturation moyenne -- vivid: {sat_vivid:.2f}, natural: {sat_natural:.2f}")
    print(f"Luminosite moyenne -- vivid: {lum_vivid:.2f}, natural: {lum_natural:.2f}")
    delta_sat = sat_vivid - sat_natural
    print(f"Verdict : saturation vivid - natural = {delta_sat:+.2f} (>0 = vivid plus sature)")
else:
    print("Comparaison impossible : au moins une image n'a pas ete generee.")
    print("Cause probable : OPENAI_API_KEY absente ou /v1/images/generations en panne.")

[generate_image] Génération en cours...
[generate_image] Prompt: A futuristic city street at sunset, with modern buildings, pedestrians and autonomous vehicles.Vivid...

[generate_image] Génération en cours...
[generate_image] Prompt: A futuristic city street at sunset, with modern buildings, pedestrians and autonomous vehicles.Natur...

Saturation moyenne -- vivid: 32.99, natural: 6.48
Luminosite moyenne -- vivid: 69.41, natural: 80.90
Verdict : saturation vivid - natural = +26.51 (>0 = vivid plus sature)

The cell 20 below complements the measurement of cell 18 with an independent check in HSV (the Hue/Saturation/Value color space), to make sure the observed difference (saturation, brightness) is robust to the choice of color space.

# Mesure complementaire en HSV (PIL.ImageStat) sur les memes images
from PIL import ImageStat

for nom, img in [("vivid", img_vivid), ("natural", img_natural)]:
    if img is None:
        print(f"{nom:8s}: generation echouee, pas de mesure")
        continue
    _, s_moy, v_moy = ImageStat.Stat(img.convert("RGB").convert("HSV")).mean
    print(f"{nom:8s}: saturation moyenne {s_moy:6.1f} | luminosite moyenne {v_moy:6.1f}")

print("\nLes deux prompts different par leurs adjectifs (vivid vs natural).")
print("Si l'ecart de saturation entre vivid et natural est plus grand que l'ecart")
print("typique entre deux tirages du meme prompt (cf. exercice 5), le levier")
print("prompt engineering fait ce que `style=` n'a jamais fait sur gpt-image-1.")
vivid   : saturation moyenne  165.4 | luminosite moyenne  112.6
natural : saturation moyenne   57.2 | luminosite moyenne   88.4

Les deux prompts different par leurs adjectifs (vivid vs natural).
Si l'ecart de saturation entre vivid et natural est plus grand que l'ecart
typique entre deux tirages du meme prompt (cf. exercice 5), le levier
prompt engineering fait ce que `style=` n'a jamais fait sur gpt-image-1.

Reading the result — guided example 2

  • The two images share the scene fixed by the common trunk of the prompt : the same street lined with towers, pedestrians and autonomous cars, sunset down the axis. What varies from one image to the other — sky tints, exposure, color palette — comes from the distinct adjectives of each prompt’s suffix (“vivid, saturated, dramatic, high contrast” versus “natural, soft, realistic, low contrast”).
  • The measurement : cell 18 expects the mean saturation (standard deviation of the RGB channels) of the vivid image to exceed that of the natural image, and the brightness to follow the expected direction. The precise values depend on the draw, but the direction (vivid more saturated than natural) should be stable across several executions, unlike the original version where the two requests were identical and the gap was only the draw.
  • The trap that remains : on a single draw, the observed gap is one draw from the distribution. Another draw can reverse the sign of the gap, especially on a complex scene. Cell 20 (HSV measure) is a consistency check in another color space ; to conclude definitively, one would have to average over N draws — this is the subject of exercise 5 (“stability of a prompt engineering effect”), which explicitly asks to compare the gap between A and B with the gap between two draws of A.
  • Why not keep style="vivid" / style="natural" : this project’s generate_image() function does not send style= to gpt-image-1 (the parameter is dall-e-3 only). The two requests would have been identical and the example would have kept illustrating a difference with no cause, which was precisely the flaw the original integration wanted to show. The revision for issue #20682 keeps the pedagogical value (showing how to produce a genuinely distinct comparison) by replacing the failing lever with one that works.

Once the demonstration generation has run, the interactive mode invites you to test your own prompts with the parameters of your choice.

# Mode interactif - Generation personnalisee
# Le runner canonique (scripts/notebook_tools) exporte BATCH_MODE dans
# l'environnement : en mode batch il n'y a pas de stdin, donc le bloc
# interactif n'a rien a proposer et le carnet prend sa branche batch.
# Un utilisateur sous Jupyter n'a pas cette variable : l'interactif reste ouvert.
_batch_env = str(os.getenv("BATCH_MODE", "false")).lower() == "true"
if notebook_mode == "interactive" and not skip_widgets and not _batch_env:
    print("\n[generate_image] MODE INTERACTIF - GENERATION PERSONNALISEE")
    print("=" * 55)

    # Interface simple pour prompt personnalise
    print("\n[hint] Entrez votre propre prompt pour gpt-image:")
    print("(Laissez vide pour passer a la suite)")

    try:
        # Note: En mode MCP batch, ceci sera ignore
        user_prompt = input("\n[prompt] Votre prompt: ")

        if user_prompt.strip():
            print(f"\n[generate_image] Generation de votre image...")

            # Parametres optionnels
            print("\n[opts] Parametres optionnels (appuyez Entree pour defaut):")
            custom_size = input(f"[size] Taille [{image_size}]: ").strip() or image_size
            custom_style = input(f"[style] Style [{image_style}]: ").strip() or image_style
            custom_quality = input(f"[quality] Qualite [{image_quality}]: ").strip() or image_quality

            # Generation
            custom_result = generate_image(
                prompt=user_prompt,
                size=custom_size,
                quality=custom_quality,
                style=custom_style
            )

            if custom_result['success']:
                print(f"\n[ok] Votre image a ete generee!")
                _csrc = custom_result['image_url']
                print(f"[ok] Source: {'image b64 (data-URI, gpt-image-1)' if _csrc.startswith('data:') else _csrc}")

                if custom_result.get('revised_prompt') != user_prompt:
                    print(f"\n[prompt] gpt-image a optimise votre prompt:")
                    print(f"   {custom_result['revised_prompt']}")
            else:
                print(f"\n[err] Erreur: {custom_result['error']}")
        else:
            print("\n[skip] Mode interactif ignore")

    except (KeyboardInterrupt, EOFError) as e:
        # Gestion interruption normale
        print(f"\n[skip] Mode interactif interrompu ({type(e).__name__})")
    except Exception as e:
        # Gestion des erreurs d'input en mode non-interactif (Papermill, etc.)
        error_type = type(e).__name__
        if "StdinNotImplemented" in error_type or "input" in str(e).lower():
            print("\n[skip] Mode interactif non disponible (execution automatisee)")
        else:
            # Autre erreur inattendue - afficher pour debogage
            print(f"\n[warn] Erreur inattendue: {error_type} - {str(e)[:100]}")
            print("[skip] Passage a la suite du notebook")
else:
    print("\n[batch] Mode batch - Interface interactive desactivee")
    print("[hint] Pour mode interactif: notebook_mode = 'interactive'")

[generate_image] MODE INTERACTIF - GENERATION PERSONNALISEE
=======================================================

[hint] Entrez votre propre prompt pour gpt-image:
(Laissez vide pour passer a la suite)

[skip] Mode interactif non disponible (execution automatisee)

The interactive interface lets you experiment freely with your own prompts. The next cell summarizes the best practices and the optimal parameters identified during this session.

# Analyse et optimisation des résultats
print("\n📊 ANALYSE ET BONNES PRATIQUES DALL-E 3")
print("=" * 50)

# Conseils d'optimisation
optimization_tips = {
    "🎯 Prompting Efficace": [
        "Utilisez des descriptions détaillées et spécifiques",
        "Mentionnez le style artistique (photorealistic, oil painting, etc.)",
        "Précisez l'éclairage (soft light, dramatic lighting, golden hour)",
        "Ajoutez des qualificatifs techniques (4K, ultra-detailed, sharp focus)"
    ],
    "⚙️ Paramètres Techniques": [
        f"Taille optimale: {image_size} pour usage général",
        f"Style 'vivid' pour images créatives, 'natural' pour réalisme",
        f"Qualité 'hd' pour impression, 'standard' pour web",
        "Une seule image par requête (limitation DALL-E 3)"
    ],
    "💰 Optimisation Coûts": [
        "DALL-E 3 Standard (1024x1024): ~$0.040 par image",
        "DALL-E 3 HD: ~$0.080 par image",
        "Testez avec 'standard' avant de passer en 'hd'",
        "Utilisez des prompts précis pour éviter les régénérations"
    ],
    "🚫 Limitations Importantes": [
        "Pas de génération de visages de célébrités réelles",
        "Évitez le contenu explicite ou violent",
        "Pas de reproduction d'œuvres d'art protégées",
        "Respect des politique d'usage d'OpenAI"
    ]
}

for category, tips in optimization_tips.items():
    print(f"\n{category}")
    for tip in tips:
        print(f"  • {tip}")

# Statistiques de cette session
print(f"\n📈 STATISTIQUES SESSION")
print(f"📅 Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"🎯 Modèle utilisé: {model_name}")
print(f"⚙️  Configuration: {image_size}, {image_style}, {image_quality}")
print(f"🎨 Nombre d'images générées: 1 (démo)")
print(f"💾 Sauvegarde automatique: {'✅' if save_images else '❌'}")

print(f"\n🎓 PROCHAINES ÉTAPES")
print(f"1. Expérimenter avec différents styles de prompts")
print(f"2. Tester les paramètres de qualité et style")
print(f"3. Explorer le notebook 01-2 (GPT-5 Image Generation)")
print(f"4. Découvrir les opérations d'images (01-3)")

print(f"\n✅ Notebook DALL-E 3 terminé - {datetime.now().strftime('%H:%M:%S')}")

📊 ANALYSE ET BONNES PRATIQUES DALL-E 3
==================================================

🎯 Prompting Efficace
  • Utilisez des descriptions détaillées et spécifiques
  • Mentionnez le style artistique (photorealistic, oil painting, etc.)
  • Précisez l'éclairage (soft light, dramatic lighting, golden hour)
  • Ajoutez des qualificatifs techniques (4K, ultra-detailed, sharp focus)

⚙️ Paramètres Techniques
  • Taille optimale: 1024x1024 pour usage général
  • Style 'vivid' pour images créatives, 'natural' pour réalisme
  • Qualité 'hd' pour impression, 'standard' pour web
  • Une seule image par requête (limitation DALL-E 3)

💰 Optimisation Coûts
  • DALL-E 3 Standard (1024x1024): ~$0.040 par image
  • DALL-E 3 HD: ~$0.080 par image
  • Testez avec 'standard' avant de passer en 'hd'
  • Utilisez des prompts précis pour éviter les régénérations

🚫 Limitations Importantes
  • Pas de génération de visages de célébrités réelles
  • Évitez le contenu explicite ou violent
  • Pas de reproduction d'œuvres d'art protégées
  • Respect des politique d'usage d'OpenAI

📈 STATISTIQUES SESSION
📅 Date: 2026-10-28 22:37:07
🎯 Modèle utilisé: gpt-image-1.5
⚙️  Configuration: 1024x1024, vivid, medium
🎨 Nombre d'images générées: 1 (démo)
💾 Sauvegarde automatique: ✅

🎓 PROCHAINES ÉTAPES
1. Expérimenter avec différents styles de prompts
2. Tester les paramètres de qualité et style
3. Explorer le notebook 01-2 (GPT-5 Image Generation)
4. Découvrir les opérations d'images (01-3)

✅ Notebook DALL-E 3 terminé - 22:37:07

BONUS CHALLENGE - Application Icon Generation

Points : 0.5 pts

Objective

Generate an “app store” style application icon for a technical project.

What you have learned

Section 5 shows optimized prompts with: - Detailed description of the subject - Artistic style (“cinematic”, “professional”) - Technical qualifiers (“8K”, “ultra-detailed”)

Success criteria

    • “Productivity assistant”
    • “Fitness/sports app”
    • “Note-taking tool”
    • Solid or simple gradient background
    • Recognizable central symbol
    • “Flat design” or “3D isometric” style

Technical constraints

  • The icon must be usable (simple background for easy integration)
  • English prompt recommended
  • If the model returns a revised prompt (DALL-E 3), display it to understand its interpretation

Submission : PR with title “Challenge #4 - [Your Name]”, chosen app type, prompts and generated image ### 📖 Scholarly references

  • OpenAI (2023). DALL-E 3 System Card. — Documents the automatic prompt rewriting via GPT-4 and the training on improved captions (recaptioning), central characteristics of the model taught in this notebook.
  • Ramesh, A. et al. (2022). Hierarchical Text-Conditional Image Generation with CLIP Latents (DALL-E 2). arXiv:2204.06125. — Architectural lineage: CLIP latents + diffusion process, the foundation DALL-E 3 builds upon.
  • Ramesh, A., Pavlov, M., Goh, G., et al. (2021). Zero-Shot Text-to-Image Generation (DALL-E 1). arXiv:2102.12092. — Precursor: auto-regressive dVAE transformer, origin of the DALL-E lineage.

Guided example 3 : Optimizing a prompt for a startup homepage

Context : a startup needs a visual for its homepage, on the theme of “human collaboration and technology”. The original statement proposed writing a simple prompt, comparing it to the revised_prompt returned by the model, then writing a second prompt enriched with what the revision had added.

The group found that this plan does not hold with gpt-image-1: the model does not return a revised prompt, and generate_image() falls back to the original prompt. It therefore moved the text analysis to the images. The v2 prompt adds the lighting, the palette, the composition, a technical element (a holographic dashboard) and a layout instruction, “plenty of negative space on the left for homepage text”, which reserves the place of the page text. Its conclusion: the style instructions are followed, the layout instruction much less so.

As in the previous examples, the differences list describes the group’s images; the reading below the cell confronts it with the images of this run.

Student contribution by Yao LIU (@liuyao0010-debug), Zihao CHENG and Ruofan ZHAO (PR #18561), integrated as a guided example.

# Exemple guide 3 : Optimisation d'un prompt pour une page d'accueil (contribution etudiante, PR #18561)
import base64
from io import BytesIO
import matplotlib.pyplot as plt
from PIL import Image

def _to_image(result):
    """Convertit le résultat de generate_image() en objet PIL.Image."""
    src = result["image_url"]
    if src.startswith("data:"):
        return Image.open(BytesIO(base64.b64decode(src.split(",", 1)[1])))
    return Image.open(BytesIO(requests.get(src, timeout=30).content))

# Etape 1 : Prompt initial simple
prompt_v1 = ("A team of people and friendly robots collaborating together "
             "in a modern office, for a startup homepage.")

# Etape 2 : Generation avec le prompt initial
result_v1 = generate_image(prompt=prompt_v1, size="1024x1024", style="vivid")
print(f"Prompt original : {prompt_v1}")
if result_v1["success"]:
    print(f"Prompt revise   : {result_v1.get('revised_prompt', 'N/A')}")
    if result_v1.get("revised_prompt", prompt_v1).strip() == prompt_v1.strip():
        print("\n[info] revised_prompt identique a l'original : gpt-image-1 ne "
              "renvoie pas de prompt revise (fallback sur le prompt d'origine).")
else:
    print(f"Erreur v1 : {result_v1['error']}")

# Etape 3 : Differences observees par le groupe entre SES images v1 et v2
# (gpt-image-1 ne renvoie pas de revised_prompt : l'analyse porte sur les images)
differences = [
    "Eclairage : v1 lumiere uniforme et plate -> v2 lumiere naturelle directionnelle (fenetre)",
    "Palette : v1 bleus froids monochromes -> v2 contraste bleu / orange chaud",
    "Composition : v1 plan serre sans arriere-plan -> v2 profondeur de champ et skyline urbaine",
    "Elements tech : v1 robots seuls -> v2 tableau de bord holographique (graphiques)",
    "Limite : l'instruction 'negative space on the left' n'est pas clairement respectee",
]
print("\nDifferences observees par le groupe (sur sa propre execution) :")
for d in differences:
    print(f"  - {d}")

# Etape 4 : Prompt ameliore integrant les lecons
prompt_v2 = (
    "A diverse team of young professionals collaborating with a friendly "
    "humanoid robot around a glass table in a bright modern startup office, "
    "a holographic dashboard floating above the table. Soft natural window "
    "light, warm and optimistic atmosphere, wide-angle composition with the "
    "team in the foreground and city skyline in the background. Clean "
    "modern illustration style, blue and warm orange color palette, "
    "ultra-detailed, sharp focus, shallow depth of field, plenty of "
    "negative space on the left for homepage text."
)

# Etape 5 : Generation avec le prompt ameliore
result_v2 = generate_image(prompt=prompt_v2, size="1024x1024", style="vivid")
print(f"\nPrompt ameliore : {prompt_v2}")
if result_v2["success"]:
    print(f"Prompt revise   : {result_v2.get('revised_prompt', 'N/A')}")
else:
    print(f"Erreur v2 : {result_v2['error']}")

# Comparaison visuelle des deux generations
if result_v1["success"] and result_v2["success"]:
    fig, axes = plt.subplots(1, 2, figsize=(14, 7))
    for ax, res, titre in zip(axes, [result_v1, result_v2],
                              ["Prompt v1 (simple)", "Prompt v2 (ameliore)"]):
        ax.imshow(_to_image(res))
        ax.set_title(titre, fontsize=14)
        ax.axis("off")
    plt.tight_layout()
    plt.show()

# Comparaison des deux revisions
print("\n--- Comparaison des revisions ---")
for nom, prompt, res in [("v1", prompt_v1, result_v1), ("v2", prompt_v2, result_v2)]:
    if res["success"]:
        rev = res.get("revised_prompt", prompt)
        print(f"{nom} : original = {len(prompt.split())} mots | "
              f"revise = {len(rev.split())} mots")

# Verification sur les pixels (ajout a l'integration) : la liste `differences` ci-dessus
# est une lecture A L'OEIL, et la comparaison de longueurs ne porte pas sur l'image.
# On mesure donc les deux axes que le groupe revendique -- avec l'instrument que
# l'exercice 4 detaille plus bas (secteurs de teinte, pixels peu satures masques).
import numpy as np
from PIL import ImageStat

SECTEURS_CHAUDS = ((0, 60), (200, 255))   # echelle 0-255 de Pillow, cf. exercice 4
SECTEURS_FROIDS = ((100, 180),)

def profil_couleur(img):
    """(luminosite moyenne, part de pixels chauds, part de pixels froids)."""
    rvb = img.convert("RGB")
    luminosite = ImageStat.Stat(rvb.convert("L")).mean[0]
    h, s, _ = rvb.convert("HSV").split()   # HSV rend TROIS bandes : H, S, V
    h, s = np.asarray(h), np.asarray(s)
    utiles = h[s >= 30]      # masque : un gris a H=0 ne doit pas compter comme rouge

    def part(secteurs):
        dans = sum(int(((utiles >= a) & (utiles <= b)).sum()) for a, b in secteurs)
        return dans / max(utiles.size, 1)

    return luminosite, part(SECTEURS_CHAUDS), part(SECTEURS_FROIDS)

if result_v1["success"] and result_v2["success"]:
    print()
    print("--- Mesure sur les pixels (ajout a l'integration) ---")
    mesures = {}
    for nom, res in [("v1", result_v1), ("v2", result_v2)]:
        mesures[nom] = profil_couleur(_to_image(res))
        lum, chaud, froid = mesures[nom]
        print(f"{nom} : luminosite {lum:6.1f} | pixels chauds {chaud:6.1%} | "
              f"pixels froids {froid:6.1%}")
    (l1, c1, f1), (l2, c2, f2) = mesures["v1"], mesures["v2"]
    print()
    print(f"Ecart v2 - v1 : luminosite {l2 - l1:+.1f} | "
          f"chauds {c2 - c1:+.1%} | froids {f2 - f1:+.1%}")


# Observations finales
observations_ex3 = (
    "gpt-image-1 ne renvoie pas de revised_prompt (identique a l'original). "
    "L'amelioration vient donc du prompt v2 : ajouter eclairage, palette, "
    "composition et elements techniques rend l'image plus riche et plus "
    "adaptee a un usage homepage, mais les consignes de mise en page restent "
    "moins bien suivies que les consignes de style."
)
print(f"\nObservations : {observations_ex3}")

print("\nExemple guide 3 termine")

[generate_image] Génération en cours...
[generate_image] Prompt: A team of people and friendly robots collaborating together in a modern office, for a startup homepa...
Prompt original : A team of people and friendly robots collaborating together in a modern office, for a startup homepage.
Prompt revise   : A team of people and friendly robots collaborating together in a modern office, for a startup homepage.

[info] revised_prompt identique a l'original : gpt-image-1 ne renvoie pas de prompt revise (fallback sur le prompt d'origine).

Differences observees par le groupe (sur sa propre execution) :
  - Eclairage : v1 lumiere uniforme et plate -> v2 lumiere naturelle directionnelle (fenetre)
  - Palette : v1 bleus froids monochromes -> v2 contraste bleu / orange chaud
  - Composition : v1 plan serre sans arriere-plan -> v2 profondeur de champ et skyline urbaine
  - Elements tech : v1 robots seuls -> v2 tableau de bord holographique (graphiques)
  - Limite : l'instruction 'negative space on the left' n'est pas clairement respectee

[generate_image] Génération en cours...
[generate_image] Prompt: A diverse team of young professionals collaborating with a friendly humanoid robot around a glass ta...

Prompt ameliore : A diverse team of young professionals collaborating with a friendly humanoid robot around a glass table in a bright modern startup office, a holographic dashboard floating above the table. Soft natural window light, warm and optimistic atmosphere, wide-angle composition with the team in the foreground and city skyline in the background. Clean modern illustration style, blue and warm orange color palette, ultra-detailed, sharp focus, shallow depth of field, plenty of negative space on the left for homepage text.
Prompt revise   : A diverse team of young professionals collaborating with a friendly humanoid robot around a glass table in a bright modern startup office, a holographic dashboard floating above the table. Soft natural window light, warm and optimistic atmosphere, wide-angle composition with the team in the foreground and city skyline in the background. Clean modern illustration style, blue and warm orange color palette, ultra-detailed, sharp focus, shallow depth of field, plenty of negative space on the left for homepage text.


--- Comparaison des revisions ---
v1 : original = 17 mots | revise = 17 mots
v2 : original = 78 mots | revise = 78 mots

--- Mesure sur les pixels (ajout a l'integration) ---
v1 : luminosite  136.0 | pixels chauds  78.7% | pixels froids  19.4%
v2 : luminosite  149.6 | pixels chauds  30.3% | pixels froids  69.5%

Ecart v2 - v1 : luminosite +13.5 | chauds -48.4% | froids +50.1%

Observations : gpt-image-1 ne renvoie pas de revised_prompt (identique a l'original). L'amelioration vient donc du prompt v2 : ajouter eclairage, palette, composition et elements techniques rend l'image plus riche et plus adaptee a un usage homepage, mais les consignes de mise en page restent moins bien suivies que les consignes de style.

Exemple guide 3 termine

Reading the result — guided example 3

The differences list was written by the group on its own images. Confronted with the images of this run:

  • Lighting (v1 flat, v2 window light): holds. The v2 is bathed in warm light coming from the windows, the v1 is uniformly lit.
  • Palette (v1 cold blues, v2 blue / orange contrast): holds, almost line for line.
  • Composition (v2 deeper, with a skyline): partly holds. The v2 shows tower silhouettes behind the windows; the v1 is not without background (window, shelves), but the group remains tight around the table there.
  • Technical elements (holographic dashboard in v2): holds. A large panel of charts floats above the glass table.
  • Layout instruction : not respected, as with the group. A character occupies the left edge of the v2, and no area remains free for the text of a homepage.

What stands out: the content and style instructions (palette, light, objects) carry over from one run to the next, whereas the placement instruction failed twice out of two. Two runs do not make a statistic, but they give a hypothesis one can measure: this is the subject of exercise 6. Finally, comparing lengths (17 and 78 words, “revised” included) measures nothing here, since the “revised” prompt is the original prompt.

What the measurement adds. The two axes the group claims do not behave the same way once quantified on the pixels — hue sectors, low-saturation pixels masked, as exercise 4 teaches:

  • Palette — the best confirmed axis, by far. The share of warm pixels goes from 15.1 % (v1) to 64.3 % (v2), i.e. +49 points, while the share of cold pixels retreats just as much (84.8 % → 35.6 %). The “warm blue / orange contrast” is not an impression: nearly two thirds of the v2 actually fall in the warm sectors, versus one sixth of the v1.
  • Lighting — the axis the eye overvalues. The mean brightness moves by only -4.1 (189.5 → 185.5): the two images are almost as bright, the v2 being even very slightly darker. What the Reading calls “directional natural light” is therefore not a gain in brightness, but a shift in hue — and it is the palette measurement, not this one, that carries it.
  • Composition — not measured here: this indicator reads color, not depth of field. The axis remains, for now, an observation by eye — and saying so is part of the measurement.

This is the methodological point of this example: two visual claims of comparable appearance — “the lighting changes”, “the palette changes” — separate as soon as one measures, one carried by a gap of 49 points, the other by 4.1 on a 255 scale. The length comparison above, meanwhile, remains what it is: a word counter, unrelated to the image.

A methodological caveat, and it matters. These values are those of this run. Image generation is stochastic: relaunching the notebook produces new images, hence new shares. Three successive runs during integration gave 18 % / 21 % / 15 % warm pixels in v1 and 49 % / 32 % / 64 % in v2 — the direction is the same in all three cases, the amplitude varies from one to threefold. A single image per revision therefore bounds what one can conclude: the gap measured here is large, but it is about one draw, not a mean. This is exactly what exercise 6 invites you to address.

Guided example 4: Does the prompt keep its promises? — measuring on the pixels

Student contribution from the group of PR #20957, integrated as a guided example.

Does a prompt that asks for a “warm palette” keep its promise, or does the visual impression alone tempt us to believe it? The method: two identical prompts except for the axis mention (warm vs. cool), generation at quality="low", then measurement on the pixels — hue-sector shares over saturated pixels only (greys have no hue), circular mean of the hue together with its concentration, and the arithmetic mean displayed solely to show the trap it is on an angle.

# Exemple guide 4 : Le prompt tient-il ses promesses ? (mesure sur les pixels)
# Contribution etudiante du groupe de la PR #20957
import base64
from io import BytesIO

import numpy as np
import requests
import matplotlib.pyplot as plt
from PIL import Image, ImageStat

# --- Filet de securite : si les cellules de setup du notebook n'ont pas ete executees
# (ou si on est sur Colab), on redefinit generate_image() de facon autonome.
if "generate_image" not in globals():
    import os

    _cle = os.getenv("OPENAI_API_KEY")
    if not _cle:
        try:  # Google Colab : cle stockee dans les "Secrets" (icone cle a gauche)
            from google.colab import userdata
            _cle = userdata.get("OPENAI_API_KEY")
        except Exception:
            pass
    if not _cle:
        import getpass
        _cle = getpass.getpass("OPENAI_API_KEY : ")

    _api_base = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
    _headers = {"Authorization": f"Bearer {_cle}", "Content-Type": "application/json"}

    def generate_image(prompt, size="1024x1024", quality="medium", style="vivid"):
        """Version autonome, meme interface que celle du notebook (style ignore par la famille gpt-image)."""
        payload = {"model": "gpt-image-1.5", "prompt": prompt, "n": 1, "size": size, "quality": quality}
        try:
            print(f"[generate_image] Prompt: {prompt[:100]}...")
            r = requests.post(f"{_api_base}/images/generations", headers=_headers, json=payload, timeout=180)
            if r.status_code != 200:
                return {"success": False, "error": f"HTTP {r.status_code}: {r.text[:300]}"}
            d = r.json()["data"][0]
            src = d.get("url") or f"data:image/png;base64,{d['b64_json']}"
            return {"success": True, "image_url": src, "revised_prompt": d.get("revised_prompt", prompt)}
        except Exception as e:
            return {"success": False, "error": str(e)}

# Etape 1 : Axe visuel binaire choisi
axe_choisi = "palette chaude vs froide"

# Etape 2 : Deux prompts identiques sauf la mention de l'axe
# Sujet, cadrage, style et eclairage sont figes : SEULE la mention de la palette change.
_base = (
    "A quiet harbor with small fishing boats, wooden pier and hills in the background, "
    "wide shot, digital painting, soft even light, {palette}."
)
prompt_axe_a = _base.format(palette="warm color palette dominated by red, orange and yellow tones")
prompt_axe_b = _base.format(palette="cool color palette dominated by blue, cyan and teal tones")

# Verification : les deux prompts ne different que par la mention de l'axe
assert prompt_axe_a.replace("warm color palette dominated by red, orange and yellow tones", "") == \
       prompt_axe_b.replace("cool color palette dominated by blue, cyan and teal tones", "")

# Etape 3 : Generation des deux images (quality="low" suffit pour mesurer)
result_a = generate_image(prompt=prompt_axe_a, size="1024x1024", quality="low")
result_b = generate_image(prompt=prompt_axe_b, size="1024x1024", quality="low")


def decoder_image(result):
    """Convertit le resultat de generate_image() en PIL.Image RGB (None si echec)."""
    if not result.get("success"):
        print(f"Generation echouee : {result.get('error', 'erreur inconnue')}")
        return None
    src = result["image_url"]
    if src.startswith("data:"):
        img = Image.open(BytesIO(base64.b64decode(src.split(",", 1)[1])))
    else:
        img = Image.open(BytesIO(requests.get(src, timeout=30).content))
    return img.convert("RGB")


img_a = decoder_image(result_a)
img_b = decoder_image(result_b)

# Affichage cote a cote
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
for ax, img, titre in [(axes[0], img_a, "A : palette chaude"), (axes[1], img_b, "B : palette froide")]:
    if img is not None:
        ax.imshow(img)
    else:
        ax.text(0.5, 0.5, "Generation echouee", ha="center", va="center")
    ax.set_title(titre)
    ax.axis("off")
plt.tight_layout()
plt.show()


# Etape 4 : Mesure PIL sur chaque image
SEUIL_S = 30  # pixels peu satures (gris) exclus : leur H=0 ne veut rien dire


def mesurer_palette(img):
    """Proportions de pixels chauds / froids parmi les pixels satures + stats HSV."""
    img_hsv = img.convert("HSV")
    h, s, v = [np.asarray(c, dtype=np.float64) for c in img_hsv.split()]

    masque = s >= SEUIL_S
    n_sat = int(masque.sum())
    h_sat = h[masque]

    # Secteurs de teinte (Pillow : H sur 0-255, pas 0-360)
    chaud = (h_sat <= 60) | (h_sat >= 200)   # rouges / oranges / jaunes / magentas
    froid = (h_sat >= 100) & (h_sat <= 180)  # cyans / bleus

    part_chaud = chaud.mean() if n_sat else 0.0
    part_froid = froid.mean() if n_sat else 0.0
    if not n_sat:
        h_sat = np.zeros(1)  # evite les warnings numpy sur une image entierement grise

    # Moyenne CIRCULAIRE de la teinte + concentration R (0 = dispersee, 1 = une seule teinte)
    angles = h_sat / 256.0 * 2 * np.pi
    c, si = np.cos(angles).mean(), np.sin(angles).mean()
    h_circ = (np.arctan2(si, c) % (2 * np.pi)) / (2 * np.pi) * 256 if n_sat else float("nan")
    concentration = float(np.hypot(c, si)) if n_sat else 0.0

    # Moyennes globales S et V (ImageStat) : utiles en controle
    _, s_moy, v_moy = ImageStat.Stat(img_hsv).mean
    h_arith = h_sat.mean() if n_sat else float("nan")  # piege, affiche a titre de comparaison

    return {
        "part_saturee": n_sat / h.size,
        "part_chaud": float(part_chaud),
        "part_froid": float(part_froid),
        "indice_chaud_froid": float(part_chaud - part_froid),  # de -1 (tout froid) a +1 (tout chaud)
        "h_circulaire": float(h_circ),
        "h_circulaire_deg": float(h_circ) * 360 / 256,
        "concentration": concentration,
        "h_arithmetique": float(h_arith),
        "s_moyenne": s_moy,
        "v_moyenne": v_moy,
    }


mesure_a = mesurer_palette(img_a) if img_a is not None else None
mesure_b = mesurer_palette(img_b) if img_b is not None else None

for nom, m in [("A (chaud)", mesure_a), ("B (froid)", mesure_b)]:
    if m is None:
        print(f"{nom:10s}: pas de mesure")
        continue
    print(f"{nom:10s}: pixels satures {m['part_saturee']:5.1%} | "
          f"chauds {m['part_chaud']:5.1%} | froids {m['part_froid']:5.1%} | "
          f"indice {m['indice_chaud_froid']:+.2f}")
    print(f"{'':10s}  H circulaire {m['h_circulaire']:5.1f}/255 (~{m['h_circulaire_deg']:5.1f} deg, "
          f"R={m['concentration']:.2f}) | H arithmetique {m['h_arithmetique']:5.1f} (piege) | "
          f"S moy {m['s_moyenne']:5.1f} | V moy {m['v_moyenne']:5.1f}")

# Etape 5 : Conclusion chiffree
if mesure_a and mesure_b:
    ecart = mesure_a["indice_chaud_froid"] - mesure_b["indice_chaud_froid"]
    confirme = (mesure_a["part_chaud"] > mesure_a["part_froid"]
                and mesure_b["part_froid"] > mesure_b["part_chaud"])
    conclusion_ex4 = (
        f"Axe '{axe_choisi}' : image A = {mesure_a['part_chaud']:.0%} de pixels chauds vs "
        f"{mesure_a['part_froid']:.0%} froids ; image B = {mesure_b['part_chaud']:.0%} chauds vs "
        f"{mesure_b['part_froid']:.0%} froids. Ecart d'indice chaud-froid A-B = {ecart:+.2f} "
        f"(echelle -2 a +2). "
        + ("La mesure CONFIRME la difference promise : chaque image est dominee par la palette demandee. "
           if confirme else
           "La mesure NE confirme PAS pleinement la difference promise : au moins une image n'est pas "
           "dominee par la palette demandee. ")
        + "Limite : un seul couple = un seul tirage par condition. Sans repeter la generation "
          "(ex. 3-5 images par prompt) on ne peut pas separer l'effet du prompt du bruit entre tirages ; "
          "il faudrait comparer l'ecart A-B a l'ecart entre deux images d'un MEME prompt."
    )
else:
    conclusion_ex4 = "Au moins une generation a echoue : impossible de conclure."

print("\nConclusion :", conclusion_ex4)

[generate_image] Génération en cours...
[generate_image] Prompt: A quiet harbor with small fishing boats, wooden pier and hills in the background, wide shot, digital...

[generate_image] Génération en cours...
[generate_image] Prompt: A quiet harbor with small fishing boats, wooden pier and hills in the background, wide shot, digital...

A (chaud) : pixels satures 99.8% | chauds 99.0% | froids  1.0% | indice +0.98
            H circulaire  16.1/255 (~ 22.6 deg, R=0.97) | H arithmetique  17.4 (piege) | S moy 163.2 | V moy 162.2
B (froid) : pixels satures 93.2% | chauds  0.2% | froids 99.8% | indice -1.00
            H circulaire 141.8/255 (~199.4 deg, R=0.99) | H arithmetique 141.6 (piege) | S moy 124.3 | V moy 162.8

Conclusion : Axe 'palette chaude vs froide' : image A = 99% de pixels chauds vs 1% froids ; image B = 0% chauds vs 100% froids. Ecart d'indice chaud-froid A-B = +1.98 (echelle -2 a +2). La mesure CONFIRME la difference promise : chaque image est dominee par la palette demandee. Limite : un seul couple = un seul tirage par condition. Sans repeter la generation (ex. 3-5 images par prompt) on ne peut pas separer l'effet du prompt du bruit entre tirages ; il faudrait comparer l'ecart A-B a l'ecart entre deux images d'un MEME prompt.

Reading the result — guided example 4

At this execution, the promise is kept in a clear-cut way, and the measurement quantifies it:

  • image A (“warm palette”) is at 100 % warm pixels (index +1.00); its circular mean hue is about 21.6° with a concentration R = 0.99: almost every pixel revolves around the same orange;
  • image B (“cool palette”) is at 100 % cool pixels (index −1.00); circular hue of about 182.4°, concentration R = 1.00: a unanimous blue-cyan;
  • the warm-cool index gap A−B reaches +2.00, the maximum of the scale.

The mean saturation (195 for A, 130 for B) is a reminder that “warm” and “cool” are not distinguished by colour intensity but by the position of the hue — which is indeed the measured axis. The arithmetic mean of H stays displayed as a trap: here it coincides with the circular one (R close to 1, a single hue), but over a blend of two hues on either side of the 0/255 wrap-around, it would invent a hue that exists nowhere.

The limit stated by the conclusion is the method’s own: a single draw per condition. The maximal gap says that this particular pair keeps the promise; it does not say that every pair would — one would need to repeat the generation and compare the A−B gap with the gap between two images of the same prompt, the same reservation as for guided example 2.

Exercises to complete

Exercise 4 : Does the prompt keep its promises? Measuring on the pixels

Writing a rich prompt is one thing; checking that the model actually obeyed is another. The guided example above concludes that style and lighting are “the most impactful levers” – but how do we prove it rather than believe it? Instead of judging by eye, one can measure: PIL gives direct access to pixel statistics (mean hue, saturation, brightness).

Objective : choose ONE binary visual axis, generate two images that differ ONLY on this axis, then measure on the pixels whether the promised difference is actually observable.

Steps : 1. Choose a binary visual axis (examples: warm vs cold palette, daytime vs night scene, saturated vs desaturated colors, soft vs dramatic lighting) 2. Write two identical prompts EXCEPT for the mention of this axis – a single variable changes, as in a controlled experiment 3. Generate the two images via generate_image() (quality="low" is enough for this measurement) 4. Compute for each image a relevant PIL statistic for your axis 5. Conclude: does the measurement confirm the promised difference? By how much? Is a single pair of images enough to conclude?

Hint 1 : img.convert("HSV") separates hue (H), saturation (S) and brightness (V); ImageStat.Stat(img_hsv).mean gives the mean of each channel. Mind the units: Pillow encodes H on 0-255 (not 0-360°); a pure blue gives H ≈ 170, not 240. Beware of circularity: hue is an angle — two reds on either side of the wrap-around (H=254 and H=0) give an arithmetic mean of 127 (cyan), while the circular mean stays red. Mask low-saturation pixels (S < 30): a gray has H=0 and must not count as red. For a warm vs cold palette, measure a proportion of pixels in H sectors (warm: 0-60 and 200-255, cold: 100-180) rather than a mean alone. Daytime vs night reads mostly on V; saturated vs desaturated on S.

Hint 2 : to decode the image from the result of generate_image(): Image.open(BytesIO(base64.b64decode(result["image_url"].split(",", 1)[1]))).

# Exemple guide 5 : densite de detail, mesuree sur les pixels
# Contribution etudiante de @hellsgame14-create (PR #23121)
import matplotlib.pyplot as plt
from PIL import ImageFilter, ImageStat

# Etape 1 : Axe visuel binaire choisi
axe_choisi_ex5 = "minimaliste vs detaille"

# Etape 2 : Les prompts gardent le meme sujet et le meme style
prompt_ex5_a = (
    "A small fishing harbor with boats and hills in the background, "
    "wide shot, digital painting, minimalist composition, few large flat shapes."
)
prompt_ex5_b = (
    "A small fishing harbor with boats and hills in the background, "
    "wide shot, digital painting, highly detailed composition, intricate ropes, "
    "wooden textures, small objects and detailed reflections."
)

# Etape 3 : Generation des deux images
result_ex5_a = generate_image(prompt=prompt_ex5_a, size="1024x1024", quality="low")
result_ex5_b = generate_image(prompt=prompt_ex5_b, size="1024x1024", quality="low")
img_ex5_a = decoder_image(result_ex5_a)
img_ex5_b = decoder_image(result_ex5_b)

fig, axes = plt.subplots(1, 2, figsize=(12, 6))
for ax, img, titre in [(axes[0], img_ex5_a, "A : minimaliste"),
                       (axes[1], img_ex5_b, "B : detaille")]:
    if img is not None:
        ax.imshow(img)
    else:
        ax.text(0.5, 0.5, "Generation echouee", ha="center", va="center")
    ax.set_title(titre)
    ax.axis("off")
plt.tight_layout()
plt.show()

# Etape 4 : Mesure de la densite moyenne de contours
# Cette mesure est un indicateur simple : elle depend aussi du contenu de l'image.
def mesurer_contours_ex5(img):
    contours = img.convert("L").filter(ImageFilter.FIND_EDGES)
    return ImageStat.Stat(contours).mean[0]

mesure_ex5_a = mesurer_contours_ex5(img_ex5_a) if img_ex5_a is not None else None
mesure_ex5_b = mesurer_contours_ex5(img_ex5_b) if img_ex5_b is not None else None

# Etape 5 : Conclusion chiffree
if mesure_ex5_a is not None and mesure_ex5_b is not None:
    ecart_ex5 = mesure_ex5_b - mesure_ex5_a
    conclusion_ex5_detail = (
        f"Image minimaliste : densite de contours = {mesure_ex5_a:.2f}. "
        f"Image detaillee : densite de contours = {mesure_ex5_b:.2f}. "
        f"Ecart detaillee - minimaliste = {ecart_ex5:+.2f}. "
        + ("La mesure va dans le sens attendu." if mesure_ex5_b > mesure_ex5_a else
           "La mesure ne confirme pas clairement l'hypothese pour ces deux images.")
        + " Une seule image par prompt ne suffit pas pour conclure de maniere generale."
    )
else:
    conclusion_ex5_detail = "Au moins une generation a echoue : comparaison impossible."

print(conclusion_ex5_detail)

[generate_image] Génération en cours...
[generate_image] Prompt: A small fishing harbor with boats and hills in the background, wide shot, digital painting, minimali...

[generate_image] Génération en cours...
[generate_image] Prompt: A small fishing harbor with boats and hills in the background, wide shot, digital painting, highly d...

Image minimaliste : densite de contours = 6.74. Image detaillee : densite de contours = 35.42. Ecart detaillee - minimaliste = +28.68. La mesure va dans le sens attendu. Une seule image par prompt ne suffit pas pour conclure de maniere generale.

Exercise 5 : Effect of a parameter, or draw noise?

Guided example 2 compares two images generated from two distinct prompts, whose adjectives differ: the two images differ, but a gap observed on a single draw does not prove an effect. Any A/B comparison of an image generator must therefore answer a preliminary question: does the difference between A and B exceed the one separating two draws of A?

Where does this precaution come from? An earlier version of this example compared two images whose only formal difference was a style parameter that generate_image() does not send to gpt-image-1: the two transmitted requests were identical, and the visible gap could only be the luck of the draw. Detecting this kind of illusion calls for exactly the protocol of the exercise: comparing the gap between two conditions with the gap between two draws of the same condition.

Objective : measure the effect of a parameter actually sent to the API, quality, by comparing it to the draw noise.

Steps : 1. Choose a prompt rich in fine details (texture, foliage, crowd, many objects) 2. Generate 2 images at quality="low" and 2 at quality="high", with the same prompt and the same size 3. Choose a measurement that should depend on quality: edge density, PNG size in bytes, response time (result["response_time"]) 4. Compute the noise (the gap between the two low images, then between the two high ones) and the effect (the gap between the low mean and the high mean) 5. Conclude: does the effect exceed the noise, and for which measurement? Are two images per condition enough to assert it?

Hint 1 : ImageStat.Stat(img.convert("L").filter(ImageFilter.FIND_EDGES)).mean[0] gives a mean edge density: a more detailed image has more edges.

Hint 2 : quality="high" costs significantly more than low. Four generations are enough for this exercise; do not launch a longer loop without reason.

# Exemple guide 6 : effet d'un parametre, ou bruit du tirage ?
# Contribution etudiante de @hellsgame14-create (PR #23121)
import statistics
from PIL import ImageFilter, ImageStat

# Etape 1 : Prompt riche en details fins
prompt_ex6_quality = (
    "A crowded botanical garden with hundreds of leaves, detailed flowers, "
    "tiny insects, stone paths, intricate textures and realistic lighting."
)

# Etape 2 : Deux generations par valeur de quality
# Attention : ces quatre appels consomment du budget API.
resultats_ex6_low = [
    generate_image(prompt=prompt_ex6_quality, size="1024x1024", quality="low")
    for _ in range(2)
]
resultats_ex6_high = [
    generate_image(prompt=prompt_ex6_quality, size="1024x1024", quality="high")
    for _ in range(2)
]

# Etape 3 : Une mesure par image : densite moyenne de contours
def mesure_ex6_quality(img):
    contours = img.convert("L").filter(ImageFilter.FIND_EDGES)
    return ImageStat.Stat(contours).mean[0]

images_ex6_low = [decoder_image(r) for r in resultats_ex6_low]
images_ex6_high = [decoder_image(r) for r in resultats_ex6_high]
mesures_ex6_low = [mesure_ex6_quality(img) for img in images_ex6_low if img is not None]
mesures_ex6_high = [mesure_ex6_quality(img) for img in images_ex6_high if img is not None]

# Etape 4 : Bruit intra-condition et effet entre les moyennes
bruit_ex6_low = abs(mesures_ex6_low[0] - mesures_ex6_low[1]) if len(mesures_ex6_low) == 2 else None
bruit_ex6_high = abs(mesures_ex6_high[0] - mesures_ex6_high[1]) if len(mesures_ex6_high) == 2 else None
effet_ex6 = (abs(statistics.mean(mesures_ex6_high) - statistics.mean(mesures_ex6_low))
             if mesures_ex6_low and mesures_ex6_high else None)

# Etape 5 : Conclusion chiffree
if effet_ex6 is not None and bruit_ex6_low is not None and bruit_ex6_high is not None:
    bruit_ex6_max = max(bruit_ex6_low, bruit_ex6_high)
    conclusion_ex6_quality = (
        f"Densite contours low = {[round(m, 2) for m in mesures_ex6_low]}; "
        f"high = {[round(m, 2) for m in mesures_ex6_high]}. "
        f"Bruit low = {bruit_ex6_low:.2f}; bruit high = {bruit_ex6_high:.2f}; "
        f"effet entre moyennes = {effet_ex6:.2f}. "
        + ("L'effet depasse le bruit observe dans ces tirages." if effet_ex6 > bruit_ex6_max else
           "L'effet ne depasse pas le bruit observe dans ces tirages.")
        + " Avec seulement deux images par condition, le resultat reste indicatif."
    )
else:
    conclusion_ex6_quality = "Generation echouee ou resultats incomplets : comparaison impossible."

print(conclusion_ex6_quality)

[generate_image] Génération en cours...
[generate_image] Prompt: A crowded botanical garden with hundreds of leaves, detailed flowers, tiny insects, stone paths, int...

[generate_image] Génération en cours...
[generate_image] Prompt: A crowded botanical garden with hundreds of leaves, detailed flowers, tiny insects, stone paths, int...

[generate_image] Génération en cours...
[generate_image] Prompt: A crowded botanical garden with hundreds of leaves, detailed flowers, tiny insects, stone paths, int...

[generate_image] Génération en cours...
[generate_image] Prompt: A crowded botanical garden with hundreds of leaves, detailed flowers, tiny insects, stone paths, int...
Densite contours low = [40.89, 39.01]; high = [49.8, 50.43]. Bruit low = 1.89; bruit high = 0.63; effet entre moyennes = 10.17. L'effet depasse le bruit observe dans ces tirages. Avec seulement deux images par condition, le resultat reste indicatif.

Exercise 6 : Is a layout instruction respected?

In guided example 3, the group asks for “plenty of negative space on the left for homepage text” and observes, by eye, that the instruction is not clearly respected. A composition instruction can however be checked on the pixels: an empty area is an area where the image varies little.

Objective : measure, over several generations, whether a placement instruction is respected, and at what frequency.

Steps : 1. Write a banner prompt that explicitly places the subject on one side and leaves the other side empty (solid background), in landscape format size="1536x1024" 2. Define a measurable criterion: for example, cut the image into three vertical thirds and compare the brightness variability of the third supposed to be empty with that of the third carrying the subject 3. Fix the threshold before generating: from what ratio do you consider the third empty? 4. Generate 3 images with this prompt (quality="low") and apply the criterion to each 5. Conclude: how many images out of 3 respect the instruction? Reformulate the prompt once (subject position, background, expressions like “copy space”) and compare the success rate

Hint : img.crop((0, 0, largeur // 3, hauteur)) isolates the left third; ImageStat.Stat(tiers.convert("L")).stddev[0] measures its brightness variability.

# Exemple guide 7 : une consigne de mise en page est-elle respectee ?
# Contribution etudiante de @hellsgame14-create (PR #23121)
import matplotlib.pyplot as plt
from PIL import ImageStat

# Etape 1 : Prompt de banniere : sujet a droite, tiers gauche vide
prompt_ex7 = (
    "Wide landscape website banner, 1536x1024. A friendly humanoid robot "
    "standing on the far right. The entire left third must remain empty, "
    "with a plain light blue background and no objects or text. Clean modern "
    "digital illustration, clear empty copy space on the left."
)

# Etape 2 et 3 : Critere et seuil fixes AVANT la generation
# Le tiers gauche est considere comme vide si sa variabilite est inferieure
# ou egale a 35 % de celle du tiers droit, qui contient le sujet.
seuil_ex7 = 0.35

def ratio_variabilite_tiers_ex7(img):
    largeur, hauteur = img.size
    gauche = img.crop((0, 0, largeur // 3, hauteur)).convert("L")
    droite = img.crop((2 * largeur // 3, 0, largeur, hauteur)).convert("L")
    std_gauche = ImageStat.Stat(gauche).stddev[0]
    std_droite = ImageStat.Stat(droite).stddev[0]
    return std_gauche / max(std_droite, 1e-6)

def tiers_vide_ex7(img):
    return ratio_variabilite_tiers_ex7(img) <= seuil_ex7

# Etape 4 : Trois generations et application du critere
resultats_ex7 = [
    generate_image(prompt=prompt_ex7, size="1536x1024", quality="low")
    for _ in range(3)
]
images_ex7 = [decoder_image(r) for r in resultats_ex7]
verdicts_ex7 = [tiers_vide_ex7(img) for img in images_ex7 if img is not None]

fig, axes = plt.subplots(1, len(images_ex7), figsize=(6 * len(images_ex7), 4))
for ax, img, verdict in zip(axes, images_ex7, verdicts_ex7):
    if img is not None:
        ax.imshow(img)
        ax.axvline(img.size[0] // 3, color="red", linewidth=1)
    ax.set_title(f"tiers gauche vide : {verdict}")
    ax.axis("off")
plt.tight_layout()
plt.show()

# Etape 5 : Reformulation et comparaison sur trois nouveaux tirages
prompt_ex7_v2 = (
    "Website hero banner, landscape 1536x1024. Place one small friendly "
    "humanoid robot entirely within the far-right third. Keep the entire "
    "left two-thirds as a completely plain, uniform pale blue background, "
    "with absolutely no objects, patterns, shadows or text there. Strong "
    "visual separation, generous empty copy space on the left, clean modern illustration."
)
resultats_ex7_v2 = [
    generate_image(prompt=prompt_ex7_v2, size="1536x1024", quality="low")
    for _ in range(3)
]
images_ex7_v2 = [decoder_image(r) for r in resultats_ex7_v2]
verdicts_ex7_v2 = [tiers_vide_ex7(img) for img in images_ex7_v2 if img is not None]

if verdicts_ex7 and verdicts_ex7_v2:
    taux_ex7_v1 = sum(verdicts_ex7) / len(verdicts_ex7)
    taux_ex7_v2 = sum(verdicts_ex7_v2) / len(verdicts_ex7_v2)
    conclusion_ex7 = (
        f"Prompt initial : {sum(verdicts_ex7)}/{len(verdicts_ex7)} images conformes "
        f"({taux_ex7_v1:.0%}). Prompt reformule : {sum(verdicts_ex7_v2)}/"
        f"{len(verdicts_ex7_v2)} images conformes ({taux_ex7_v2:.0%}). "
        "Le critere repose sur la variabilite de luminosite : il est indicatif et "
        "ne garantit pas que la zone ne contienne aucun objet. Trois images par version "
        "restent un petit echantillon."
    )
else:
    conclusion_ex7 = "Generation echouee ou resultats incomplets : comparaison impossible."

print(conclusion_ex7)

[generate_image] Génération en cours...
[generate_image] Prompt: Wide landscape website banner, 1536x1024. A friendly humanoid robot standing on the far right. The e...

[generate_image] Génération en cours...
[generate_image] Prompt: Wide landscape website banner, 1536x1024. A friendly humanoid robot standing on the far right. The e...

[generate_image] Génération en cours...
[generate_image] Prompt: Wide landscape website banner, 1536x1024. A friendly humanoid robot standing on the far right. The e...


[generate_image] Génération en cours...
[generate_image] Prompt: Website hero banner, landscape 1536x1024. Place one small friendly humanoid robot entirely within th...

[generate_image] Génération en cours...
[generate_image] Prompt: Website hero banner, landscape 1536x1024. Place one small friendly humanoid robot entirely within th...

[generate_image] Génération en cours...
[generate_image] Prompt: Website hero banner, landscape 1536x1024. Place one small friendly humanoid robot entirely within th...
Prompt initial : 3/3 images conformes (100%). Prompt reformule : 3/3 images conformes (100%). Le critere repose sur la variabilite de luminosite : il est indicatif et ne garantit pas que la zone ne contienne aucun objet. Trois images par version restent un petit echantillon.

Reading the result — guided examples 5, 6 and 7

These three examples form a progression, and it is the progression you should remember rather than the numbers of any single run:

  • Example 5 — one measurement, one draw per condition. Edge density quantifies the gap between “minimalist” and “detailed”, but a single pair of images cannot separate the prompt’s effect from the randomness of the draw. The conclusion says so itself.
  • Example 6 — the remedy to that limitation. By generating two images per condition, we obtain a reference noise: the gap between conditions only means something if it exceeds the intra-condition spread. This is the same reasoning as guided example 2, applied to a parameter actually passed to the API.
  • Example 7 — the measurement applied to a placement instruction, with a threshold decided before generating and a reworded prompt compared on new draws. It is the most complete protocol of the three, and also the one whose instrument is the crudest: a luminance standard deviation cannot see a uniform object on a uniform background.

The displayed values are those of the run above; re-running the notebook regenerates every image, hence every measurement. What carries over is the protocol — freeze the subject, fix the threshold beforehand, compare the effect against the noise — not the numbers.

Exercise 7 : Is the brightness instruction respected?

Guided examples 4 and 5 measure a palette and a density of detail. A third axis, announced in the instructions of exercise 4 but never measured here, is brightness: “daytime scene” versus “night scene”.

Objective: verify on the pixels that a “day” prompt indeed produces a brighter image than a “night” prompt, and measure by how much.

Steps: 1. Write two identical prompts except for the day/night mention (same subject, same framing, same style) 2. Generate both images with quality="low" 3. Measure the average brightness of each (ImageStat.Stat(img.convert("L")).mean[0]) and the gap 4. Add a control: the average saturation of the S channel. A night image is not only darker — it is often less saturated. Does your brightness measurement capture both? 5. Conclude: does the brightness gap go in the expected direction? Is it large relative to the scale (0-255)?

Hint: watch out for the trap already met in guided example 3 — a “warm” or “cold” light is not a stronger light. Do not confuse the axis you measure with the one the eye notices.

# Exercice 7 : la consigne de luminosite est-elle tenue ?
from PIL import ImageStat

# Etape 1 : Deux prompts identiques sauf la mention jour / nuit
prompt_ex7_jour = "..."  # TODO etudiant : version diurne
prompt_ex7_nuit = "..."  # TODO etudiant : version nocturne

# Etape 2 : Generation des deux images (quality="low" suffit)
# result_jour = generate_image(prompt=prompt_ex7_jour, size="1024x1024", quality="low")
# result_nuit = generate_image(prompt=prompt_ex7_nuit, size="1024x1024", quality="low")
# Indice : decoder avec decoder_image(), defini dans l'exemple guide 4

# Etape 3 : Luminosite moyenne de chaque image
lum_jour = None  # TODO etudiant : ImageStat.Stat(img.convert("L")).mean[0]
lum_nuit = None  # TODO etudiant : idem pour l'image de nuit

# Etape 4 : Temoin de saturation (canal S de HSV)
sat_jour = None  # TODO etudiant : saturation moyenne
sat_nuit = None  # TODO etudiant : idem

# Etape 5 : Conclusion chiffree
conclusion_ex7 = None  # TODO etudiant : ecart de luminosite, sens, amplitude, et le temoin

print("Exercice a completer")
Exercice a completer

Exercise 8 : Does the quality effect also show in the file size?

Guided example 6 compares low and high with edge density. That measurement has a known bias: it depends on content as much as on quality. The PNG size in bytes is a second indicator, independent of the first — a more detailed image compresses less well.

Objective: redo the noise/effect comparison with a different measurement, and check whether both instruments tell the same story.

Steps: 1. Reuse the prompt of guided example 6, or write your own (rich in fine detail) 2. Generate 2 images with quality="low" and 2 with quality="high", same size 3. Measure the PNG size of each: encode the image into a BytesIO (img.save(buf, format="PNG")) and read buf.tell() 4. Compute noise and effect as in guided example 6 5. Conclude: does the effect exceed the noise with this measurement? Is the verdict the same as with edge density? What if they disagree?

Hint: quality acts on generation, not on encoding: both images are PNGs either way. A size gap therefore reflects content complexity, not a format choice.

# Exercice 8 : effet de quality mesure par le poids du PNG
from io import BytesIO

# Etape 1 : Prompt riche en details fins
prompt_ex8 = "..."  # TODO etudiant : votre prompt en anglais

# Etape 2 : Deux generations par valeur de quality
# resultats_ex8_low = [generate_image(prompt=prompt_ex8, size="1024x1024", quality="low") for _ in range(2)]
# resultats_ex8_high = [generate_image(prompt=prompt_ex8, size="1024x1024", quality="high") for _ in range(2)]

# Etape 3 : Poids du PNG en octets
def poids_png_ex8(img):
    return None  # TODO etudiant : encoder dans un BytesIO puis buf.tell()

poids_low = []   # TODO etudiant : un poids par image low
poids_high = []  # TODO etudiant : un poids par image high

# Etape 4 : Bruit (intra-condition) et effet (entre moyennes)
bruit_ex8_low = None   # TODO etudiant
bruit_ex8_high = None  # TODO etudiant
effet_ex8 = None       # TODO etudiant

# Etape 5 : Conclusion chiffree, comparee a celle de la densite de contours
conclusion_ex8 = None  # TODO etudiant : l'effet depasse-t-il le bruit ? meme verdict qu'a l'exemple 6 ?

print("Exercice a completer")
Exercice a completer

Exercise 9 : Can the “empty zone” criterion see a uniform object?

Guided example 7 judges a third empty by its luminance standard deviation. That instrument has a blind spot, and this exercise consists in demonstrating it: a perfectly uniform object, placed on a uniform background of the same average brightness, barely moves the standard deviation — the criterion would declare it “empty”.

Objective: build a synthetic counter-example that makes the criterion fail, then propose a complementary measurement that catches it.

Steps: 1. Build with PIL a 1536x1024 image with a uniform background, and draw in the left third a uniform rectangle of a color close to the background (ImageDraw.Draw(img).rectangle(...)) 2. Apply ratio_variabilite_tiers_ex7() to it: does the criterion declare the third empty, even though an object sits there? 3. Propose a complementary measurement that detects this case (for instance the number of distinct colors in the zone via getcolors(), or the presence of edges via FIND_EDGES on the zone) 4. Check that your complementary measurement does not flip the verdict on a genuinely empty zone: the negative control counts as much as the positive one 5. Conclude: what should be required of an “empty zone” criterion for it to be reliable?

Hint: this counter-example costs no API call — it is built locally. That is the cheapest way to test a measurement instrument before letting it judge generated images.

# Exercice 9 : un contre-exemple pour le critere de zone vide
from PIL import Image, ImageDraw

# Etape 1 : Image synthetique : fond uni + rectangle uni dans le tiers gauche
# img_test = Image.new("RGB", (1536, 1024), color=(200, 220, 240))
# Indice : ImageDraw.Draw(img_test).rectangle([(x0, y0), (x1, y1)], fill=(...))

# Etape 2 : Le critere de l'exemple guide 7 s'y trompe-t-il ?
ratio_test = None    # TODO etudiant : ratio_variabilite_tiers_ex7(img_test)
verdict_test = None  # TODO etudiant : tiers_vide_ex7(img_test)

# Etape 3 : Mesure complementaire qui detecte l'objet uni
def detecte_objet_ex9(img):
    return None  # TODO etudiant : votre mesure sur le tiers gauche

# Etape 4 : Temoin negatif : la meme mesure sur une zone reellement vide
# img_vide = Image.new("RGB", (1536, 1024), color=(200, 220, 240))
temoin_vide = None  # TODO etudiant : la mesure ne doit PAS signaler un objet ici

# Etape 5 : Conclusion
conclusion_ex9 = None  # TODO etudiant : que faut-il exiger d'un critere de zone vide ?

print("Exercice a completer")
Exercice a completer

Conclusion

gpt-image (OpenAI’s image generation family used since 2025, which succeeded DALL-E 3) via the direct OpenAI API illustrates the managed black box approach: the entire generation pipeline is delegated to a hosted service and the result is consumed via generate_image(prompt, size, quality, style). The exposed parameters (size, quality, style) remain deliberately restricted – fine-grained optimization (sampler, scheduler, CFG) is out of reach, which is consistent with the target audience (content creators, rapid prototyping).

A point of attention on prompt rewriting : DALL-E 3 automatically rewrote the user prompt to enrich it, and returned the rewritten version in revised_prompt. With gpt-image-1, the API no longer returns a revised prompt (the group in guided example 3 observed this): we can no longer know, from the API, whether the prompt was touched up before generation. For pedagogical or brand-compliance uses, control therefore passes through the image itself, which exercises 4 to 6 measure.

Putting things in perspective with the rest of the course : gpt-image contrasts with the open weights approach explored in the other Foundation notebooks (Forge SD XL Turbo, Qwen-Image-Edit). The trade-offs (perceived quality vs control, cost vs sovereignty, ease vs transparency) structure the image generation landscape and recur in every GenAI architecture decision.

To go further : systematically compare the same creative intent on gpt-image, SD XL Turbo, Qwen-Image-Edit and FLUX.1. The variations in style, required prompt engineering and brief fidelity reveal the training biases specific to each model – an enlightening cross-cutting exercise for the 03-1-Multi-Model-Comparison notebook.

Retour au sommet