Skip to content

imagine_image_files()

Generates and saves image files based on given prompts, with options for animations and videos.

Parameters:

Name Type Description Default
prompts list[ImaginePrompt] | ImaginePrompt

A prompt or list of prompts for image generation.

required
outdir str

Directory path where the generated images and other files will be saved.

required
precision str

Precision mode for image generation, defaults to 'autocast'.

'autocast'
record_step_images bool

If True, saves step-by-step images of the generation process, defaults to False.

False
output_file_extension str

File extension for output images, must be 'jpg' or 'png', defaults to 'jpg'.

'jpg'
print_caption bool

If True, prints captions on the generated images, defaults to False.

False
make_gif bool

If True, creates a GIF from the generation steps, defaults to False.

False
make_compare_gif bool

If True, creates a comparison GIF with initial and generated images, defaults to False.

False
return_filename_type str

Type of filenames to return, defaults to 'generated'.

'generated'
videogen bool

If True, generates a video from the generated images, defaults to False.

False

Returns:

Type Description

list[str]: A list of filenames of the generated images.

Raises:

Type Description
ValueError

If the output file extension is not 'jpg' or 'png'.

Source code in imaginairy/api/generate.py
def imagine_image_files(
    prompts: "list[ImaginePrompt] | ImaginePrompt",
    outdir: str,
    precision: str = "autocast",
    record_step_images: bool = False,
    output_file_extension: str = "jpg",
    print_caption: bool = False,
    make_gif: bool = False,
    make_compare_gif: bool = False,
    return_filename_type: str = "generated",
    videogen: bool = False,
):
    """
    Generates and saves image files based on given prompts, with options for animations and videos.

    Args:
        prompts (list[ImaginePrompt] | ImaginePrompt): A prompt or list of prompts for image generation.
        outdir (str): Directory path where the generated images and other files will be saved.
        precision (str, optional): Precision mode for image generation, defaults to 'autocast'.
        record_step_images (bool, optional): If True, saves step-by-step images of the generation process, defaults to False.
        output_file_extension (str, optional): File extension for output images, must be 'jpg' or 'png', defaults to 'jpg'.
        print_caption (bool, optional): If True, prints captions on the generated images, defaults to False.
        make_gif (bool, optional): If True, creates a GIF from the generation steps, defaults to False.
        make_compare_gif (bool, optional): If True, creates a comparison GIF with initial and generated images, defaults to False.
        return_filename_type (str, optional): Type of filenames to return, defaults to 'generated'.
        videogen (bool, optional): If True, generates a video from the generated images, defaults to False.

    Returns:
        list[str]: A list of filenames of the generated images.

    Raises:
        ValueError: If the output file extension is not 'jpg' or 'png'.
    """
    from PIL import ImageDraw

    from imaginairy.api.video_sample import generate_video
    from imaginairy.utils import get_next_filenumber, prompt_normalized

    generated_imgs_path = os.path.join(outdir, "generated")
    os.makedirs(generated_imgs_path, exist_ok=True)

    base_count = get_next_filenumber(generated_imgs_path)
    output_file_extension = output_file_extension.lower()
    if output_file_extension not in {"jpg", "png"}:
        raise ValueError("Must output a png or jpg")

    if not isinstance(prompts, list):
        prompts = [prompts]

    def _record_step(img, description, image_count, step_count, prompt):
        steps_path = os.path.join(outdir, "steps", f"{base_count:08}_S{prompt.seed}")
        os.makedirs(steps_path, exist_ok=True)
        filename = f"{base_count:08}_S{prompt.seed}_{image_count:04}_step{step_count:03}_{prompt_normalized(description)[:40]}.jpg"

        destination = os.path.join(steps_path, filename)
        draw = ImageDraw.Draw(img)
        draw.text((10, 10), str(description))
        img.save(destination)

    if make_gif:
        for p in prompts:
            p.collect_progress_latents = True
    result_filenames = []
    for result in imagine(
        prompts,
        precision=precision,
        debug_img_callback=_record_step if record_step_images else None,
        add_caption=print_caption,
    ):
        primary_filename = save_image_result(
            result,
            base_count,
            outdir=outdir,
            output_file_extension=output_file_extension,
            primary_filename_type=return_filename_type,
            make_gif=make_gif,
            make_compare_gif=make_compare_gif,
        )
        if not primary_filename:
            continue
        result_filenames.append(primary_filename)
        if primary_filename and videogen:
            try:
                generate_video(
                    input_path=primary_filename,
                )
            except FileNotFoundError as e:
                logger.error(str(e))
                exit(1)

        base_count += 1
        del result

    return result_filenames