Best Picks Labor

Destilliertes Wissen zu Schule und Technik

Bilder im Batch generieren

Ich wollte schon immer als Aktivität ein H5p Memory erstellen. Leider ist es einfach zu aufwändig da diese App für jede Karte ein Bild braucht. In Zeiten der generativen KI muss das aber einfach sein. Ich habe darum ein Python Script erstellt, welches mit dem Bildmodell Flux über den Provider Replicate diese Bilder im Batch erstellt. Die Bilder werden dabei Lokal auf der Festplatte abgelegt damit sie direkt weiterverarbeitet werden können.

Wenn du das Script nutzen willst beachte:

Ca auf Zeile 92 musst du einen API Key für Replicate eingeben. Bilder mit Flux in der Auflösung sind echt günstig aber eben nicht gratis.
replicate_api_key = „YOUR_REPLICATE_API_KEY“ # <— Replace this
Wenn du dem Script nicht traust, limitiere seitens Replicate die Nutzung auf ein paar wenige Dollar.

Die verwendeten Bibliotheken für Python installierst du auf einem Mac via Terminal: „pip3 install replicate“

Wenn du den Bildoutput noch anpassen willst, schau dir die Pythonparameter auf Replicate an diese findest du auch im Code unten. Standard habe ich das kleinstmögliche Bild gewählt mit Seitenverhältsnis 1 zu 1.

Die generierten Bilder werden im gleichen Ordner generiert wie das Pythonscript.

Das Script führt man auf einem Mac aus indem du es in eine leere Textdatei einfügst und speicherst als scriptdatei.py via Terminal und dem Befehl: python3 scriptdatei.py

Code zum kopieren

import replicate
import os
from io import BytesIO
from PIL import Image
import requests  # Import the requests library

def generate_image_replicate(prompt, replicate_api_key, image_size=300):
    """
    Generates a square image using Replicate, with Flux Schnell, based on a user-provided prompt.

    Args:
        prompt (str): The prompt to use for image generation.
        replicate_api_key (str): Your Replicate API key.
        image_size (int, optional): The size of the square image in pixels.
            Defaults to 300.
    Returns:
        str: The filename of the generated image (word.png), or None on error.
    """
    os.environ["REPLICATE_API_TOKEN"] = replicate_api_key

    # Generate image with Flux Schnell
    model = "black-forest-labs/flux-schnell"
    try:
        output = replicate.run(
            model,
            input={
                "prompt": prompt,
                "go_fast": True,
                "megapixels": "1",
                "num_outputs": 1,
                "aspect_ratio": "1:1",  # Ensure square image
                "output_format": "jpg",
                "output_quality": 80,
                "num_inference_steps": 4
            }
        )
        # Check if the output is a list and not empty
        if isinstance(output, list) and output:
            image_url = output[0]  # Get the first URL
        else:
            print(f"Error: Replicate output is not a valid URL for prompt: {prompt}. Output: {output}")
            return None

    except Exception as e:
        print(f"Error generating image for prompt '{prompt}' with Flux Schnell: {e}")
        return None

    # Open the image from the URL.
    try:
        response = requests.get(image_url)
        response.raise_for_status()
        img = Image.open(BytesIO(response.content))
    except Exception as e:
        print(f"Error opening image from URL: {e}")
        return None

    # Save the image as a PNG file.  Use a sanitized version of the prompt as filename.
    #  Only use the content for the filename
    filename = f"{''.join(c if c.isalnum() else '_' for c in prompt.split(',')[-1].lower())[:50]}.png"  # Sanitize and truncate
    img.save(filename, "PNG")
    return filename



def generate_images(prompts, replicate_api_key, image_size=300):
    """
    Generates square images for a list of prompts using Replicate.

    Args:
        prompts (list): A list of prompts.
        replicate_api_key (str): Your Replicate API key.
        image_size (int, optional): The size of the square image in pixels.
            Defaults to 300.
    """
    generated_files = []
    for prompt in prompts:
        filename = generate_image_replicate(prompt, replicate_api_key, image_size)
        if filename:
            generated_files.append(filename)
            print(f"Generated image: {filename}")
        else:
            print(f"Failed to generate image for prompt: {prompt}")
    return generated_files



if __name__ == "__main__":
    #  Replace with your actual Replicate API key.  Important: Keep this secure.
    replicate_api_key = "YOUR_REPLICATE_API_KEY" # <---  Replace this

    if replicate_api_key == "YOUR_REPLICATE_API_KEY":
        print("Error: Please replace 'YOUR_REPLICATE_API_KEY' with your actual Replicate API key.")
    else:
        # Get the image style from the user
        image_style = input("Enter the style of the images you want to generate (e.g., 'photorealistic', 'cartoon', 'pixel art', 'oil painting'): ")

        # Get the image content from the user, semicolon-separated
        image_content_input = input("Enter the content of the images, separated by semicolons (e.g., 'Apple; Green banana; Smiling moon'): ")
        image_contents = [item.strip() for item in image_content_input.split(';')] #split

        # Construct prompts
        prompts = [f"{image_style}, {content}" for content in image_contents] #removed square image

        # Generate images
        print("Generating images using Replicate:")
        generated_images = generate_images(prompts, replicate_api_key, image_size=200)

        print("\nDone! The images have been saved as PNG files in the same directory as the script.")
        print("Use these images in your H5P memory game.")

Related Posts

None found