Turn Natural Language Prompts into Python Scripts

Tested prompts for generate python script from text prompt compared across 5 leading AI models.

BEST BY JUDGE SCORE Claude Haiku 4.5 8/10

The prompt we tested

You are an expert Python developer. Convert the user's natural language description into a complete, working Python script.

Output only a single, runnable Python 3 script inside one fenced ```python code block, followed by a brief 2-4 bullet 'How to run' section below it. Include necessary imports, type hints, docstrings, inline comments for non-obvious logic, basic error handling, and an `if __name__ == "__main__":` entry point. Do not invent external APIs or libraries the user didn't request; use the standard library when possible and list any pip dependencies at the top in a comment.

User's request:
Write a script that scans a folder of images, resizes any image larger than 1920px on its longest side down to 1920px while preserving aspect ratio, and saves the resized copies into a subfolder called 'resized'. It should accept the input folder as a command line argument and support .jpg and .png files.

Return the Python script now.

Model comparison

ModelQualityCostLatencyTokens
Claude Opus 4.7 8 $0.1054 14.0s 301 / 1345
Claude Haiku 4.5 8 $0.0066 7.3s 228 / 1284
GPT-5.4 8 $0.0159 13.5s 210 / 1026
Grok 4.1 Fast Reasoning 7 $0.0004 13.8s 360 / 700

Outputs

Claude Opus 4.7 8/10
```python
# Dependencies: pip install Pillow
"""
Image resizer script.

Scans a folder for .jpg and .png images, resizes any image whose longest side
exceeds 1920px down to 1920px while preserving aspect ratio, and saves copies
into a 'resized' subfolder.
"""

import argparse
import sys
from pathlib import Path
from typing import Iterable

from PIL import Image, UnidentifiedImageError

MAX_SIZE: int = 1920
SUPPORTED_EXTENSIONS: tuple[str, ...] = (".jpg", ".jpeg", ".png")


def iter_images(folder: Path) -> Iterable[Path]:
    """Yield image file paths in `folder` with supported extensions."""
    for path in folder.iterdir():
        if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS:
            yield path


def resize_if_needed(image_path: Path, output_dir: Path, max_size: int = MAX_SIZE) -> bool:
    """
    Resize the image at `image_path` if its longest side exceeds `max_size`.

    Saves the resulting image (resized or original copy) to `output_dir`.
    Returns True if the image was actually resized, False otherwise.
    """
    try:
        with Image.open(image_path) as img:
            width, height = img.size
            longest = max(width, height)
            output_path = output_dir / image_path.name

            if longest > max_size:
                # Use thumbnail for in-place proportional resize (preserves aspect ratio).
                scale = max_size / longest
                new_size = (int(width * scale), int(height * scale))
                resized = img.resize(new_size, Image.LANCZOS)

                # Preserve mode appropriately for JPEG (no alpha channel).
                if image_path.suffix.lower() in (".jpg", ".jpeg") and resized.mode in ("RGBA", "P"):
                    resized = resized.convert("RGB")

                resized.save(output_path)
                print(f"Resized: {image_path.name} ({width}x{height}) -> {new_size[0]}x{new_size[1]}")
                return True
            else:
                # Still save a copy so 'resized' folder contains all processed images.
                img.save(output_path)
                print(f"Copied (no resize needed): {image_path.name} ({width}x{height})")
                return False
    except (UnidentifiedImageError, OSError) as exc:
        print(f"Skipping {image_path.name}: {exc}", file=sys.stderr)
        return False


def main() -> int:
    """Parse CLI args and process images."""
    parser = argparse.ArgumentParser(
        description="Resize images larger than 1920px on longest side into a 'resized' subfolder."
    )
    parser.add_argument("input_folder", type=str, help="Path to folder containing images.")
    args = parser.parse_args()

    input_dir = Path(args.input_folder)
    if not input_dir.is_dir():
        print(f"Error: '{input_dir}' is not a valid directory.", file=sys.stderr)
        return 1

    output_dir = input_dir / "resized"
    output_dir.mkdir(exist_ok=True)

    total = 0
    resized_count = 0
    for image_path in iter_images(input_dir):
        total += 1
        if resize_if_needed(image_path, output_dir):
            resized_count += 1

    print(f"\nDone. Processed {total} image(s); resized {resized_count}.")
    print(f"Output folder: {output_dir}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

**How to run**
- Install the dependency: `pip install Pillow`
- Run the script with your image folder path: `python resize_images.py /path/to/images`
- Resized copies will appear in `/path/to/images/resized/`
- Supported file types: `.jpg`, `.jpeg`, `.png`
Judge notes: Minor issue: copying unchanged images into 'resized' was not requested and could cause confusion/wasted disk space, but otherwise the script is clean, well-structured, and production-ready.
Claude Haiku 4.5 8/10
```python
"""
Image resizer script: Resizes images larger than 1920px on the longest side.
Preserves aspect ratio and saves resized copies to a 'resized' subfolder.

pip dependencies: Pillow
"""

import sys
import os
from pathlib import Path
from PIL import Image
import argparse
from typing import Optional


def resize_image(image_path: Path, output_path: Path, max_dimension: int = 1920) -> bool:
    """
    Resize an image if its longest side exceeds max_dimension.
    
    Args:
        image_path: Path to the source image
        output_path: Path where the resized image will be saved
        max_dimension: Maximum allowed dimension for the longest side (default 1920)
    
    Returns:
        True if image was resized and saved, False if it was already small enough
    """
    try:
        with Image.open(image_path) as img:
            # Get original dimensions
            width, height = img.size
            longest_side = max(width, height)
            
            # Check if resizing is needed
            if longest_side <= max_dimension:
                print(f"  Skipped (already {width}x{height}): {image_path.name}")
                return False
            
            # Calculate new dimensions preserving aspect ratio
            scale_factor = max_dimension / longest_side
            new_width = int(width * scale_factor)
            new_height = int(height * scale_factor)
            
            # Resize using high-quality resampling
            resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
            
            # Save resized image
            resized_img.save(output_path, quality=95, optimize=True)
            print(f"  Resized {width}x{height} → {new_width}x{new_height}: {image_path.name}")
            return True
    
    except Exception as e:
        print(f"  Error processing {image_path.name}: {e}")
        return False


def process_images(input_folder: Path, max_dimension: int = 1920) -> None:
    """
    Scan a folder for images and resize those exceeding max_dimension.
    
    Args:
        input_folder: Path to the folder containing images
        max_dimension: Maximum allowed dimension for the longest side (default 1920)
    """
    # Validate input folder
    if not input_folder.is_dir():
        print(f"Error: '{input_folder}' is not a valid directory.")
        sys.exit(1)
    
    # Create resized subfolder
    resized_folder = input_folder / "resized"
    try:
        resized_folder.mkdir(exist_ok=True)
    except Exception as e:
        print(f"Error creating resized folder: {e}")
        sys.exit(1)
    
    # Supported image extensions
    supported_extensions = {'.jpg', '.jpeg', '.png'}
    
    # Find all image files
    image_files = [
        f for f in input_folder.iterdir()
        if f.is_file() and f.suffix.lower() in supported_extensions
    ]
    
    if not image_files:
        print(f"No .jpg or .png images found in '{input_folder}'.")
        return
    
    print(f"Found {len(image_files)} image(s) in '{input_folder}'.")
    print(f"Processing images (max dimension: {max_dimension}px)...\n")
    
    resized_count = 0
    for image_file in image_files:
        output_path = resized_folder / image_file.name
        if resize_image(image_file, output_path, max_dimension):
            resized_count += 1
    
    print(f"\nProcessing complete! {resized_count} image(s) were resized.")
    print(f"Resized images saved to: {resized_folder}")


def main() -> None:
    """Main entry point for the script."""
    parser = argparse.ArgumentParser(
        description="Resize images larger than 1920px on the longest side while preserving aspect ratio."
    )
    parser.add_argument(
        "input_folder",
        type=str,
        help="Path to the folder containing images to resize"
    )
    parser.add_argument(
        "--max-dimension",
        type=int,
        default=1920,
        help="Maximum dimension in pixels for the longest side (default: 1920)"
    )
    
    args = parser.parse_args()
    input_folder = Path(args.input_folder)
    
    process_images(input_folder, args.max_dimension)


if __name__ == "__main__":
    main()
```

**How to run:**

- Install Pillow: `pip install Pillow`
- Run with default 1920px limit: `python script.py /path/to/image/folder`
- Run with custom max dimension: `python script.py /path/to/image/folder --max-dimension 1280`
- Resized images will be saved in a `resized` subfolder within the input directory
Judge notes: Nearly production-ready with solid error handling, type hints, and docstrings; the minor issue is that `.jpeg` was added without being explicitly requested (minor scope creep), and skipped images aren't copied to the `resized` folder which may or may not match user intent but is never clarified.
GPT-5.4 8/10
```python
#!/usr/bin/env python3
"""
Pip dependencies:
- Pillow

Scan a folder for .jpg/.jpeg and .png images, resize any image whose longest
side exceeds 1920 pixels, and save the processed copies into a 'resized'
subfolder within the input folder.

Images smaller than or equal to 1920px on their longest side are copied as-is
into the output folder to ensure all supported images are present there.
"""

from __future__ import annotations

import argparse
import shutil
import sys
from pathlib import Path
from typing import Iterable

from PIL import Image

MAX_LONGEST_SIDE = 1920
SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png"}


def parse_args() -> argparse.Namespace:
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        description=(
            "Resize images larger than 1920px on their longest side and save "
            "them into a 'resized' subfolder."
        )
    )
    parser.add_argument(
        "input_folder",
        type=Path,
        help="Path to the folder containing .jpg/.jpeg and .png images.",
    )
    return parser.parse_args()


def iter_image_files(folder: Path) -> Iterable[Path]:
    """Yield supported image files in the given folder (non-recursive)."""
    for path in folder.iterdir():
        if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS:
            yield path


def calculate_new_size(width: int, height: int, max_longest_side: int) -> tuple[int, int]:
    """
    Calculate a new size preserving aspect ratio so that the longest side
    becomes max_longest_side.
    """
    longest_side = max(width, height)
    if longest_side <= max_longest_side:
        return width, height

    scale = max_longest_side / float(longest_side)
    new_width = max(1, round(width * scale))
    new_height = max(1, round(height * scale))
    return new_width, new_height


def process_image(src_path: Path, dst_path: Path, max_longest_side: int) -> None:
    """
    Resize the image if needed and save it to the destination path.
    If no resize is needed, copy the original file.
    """
    try:
        with Image.open(src_path) as img:
            width, height = img.size
            new_size = calculate_new_size(width, height, max_longest_side)

            if new_size == (width, height):
                # Copy unchanged images so the output folder contains all supported files.
                shutil.copy2(src_path, dst_path)
                print(f"Copied:   {src_path.name} ({width}x{height})")
                return

            resized = img.resize(new_size, Image.Resampling.LANCZOS)

            # Preserve PNG transparency if present; convert incompatible modes for JPEG.
            if src_path.suffix.lower() in {".jpg", ".jpeg"}:
                if resized.mode not in ("RGB", "L"):
                    resized = resized.convert("RGB")
                resized.save(dst_path, quality=95, optimize=True)
            else:
                resized.save(dst_path, optimize=True)

            print(
                f"Resized:  {src_path.name} "
                f"({width}x{height} -> {new_size[0]}x{new_size[1]})"
            )
    except Exception as exc:
        print(f"Error processing '{src_path}': {exc}", file=sys.stderr)


def main() -> int:
    """Program entry point."""
    args = parse_args()
    input_folder: Path = args.input_folder

    if not input_folder.exists():
        print(f"Error: Folder does not exist: {input_folder}", file=sys.stderr)
        return 1

    if not input_folder.is_dir():
        print(f"Error: Path is not a directory: {input_folder}", file=sys.stderr)
        return 1

    output_folder = input_folder / "resized"
    output_folder.mkdir(exist_ok=True)

    image_files = list(iter_image_files(input_folder))
    if not image_files:
        print("No supported image files found (.jpg, .jpeg, .png).")
        return 0

    for src_path in image_files:
        dst_path = output_folder / src_path.name
        process_image(src_path, dst_path, MAX_LONGEST_SIDE)

    print(f"Done. Output saved to: {output_folder}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
```

How to run:
- Install dependency: `pip install Pillow`
- Save the script to a file, for example `resize_images.py`
- Run it with: `python resize_images.py /path/to/your/image_folder`
- Resized and copied images will be written to `/path/to/your/image_folder/resized`
Judge notes: The script is solid and production-ready, but the decision to copy unchanged images to the output folder was not requested and could surprise users who expect only resized images there.
Grok 4.1 Fast Reasoning 7/10
```python
# Requires: pip install Pillow

"""
Image Resizer Script

Scans a folder for .jpg/.jpeg and .png images, resizes any image with longest side > 1920px
to 1920px on the longest side while preserving aspect ratio, and saves copies in a 'resized' subfolder.
"""

from pathlib import Path
from PIL import Image, ImageResampling
import argparse
import os
import sys


def main(input_folder: str) -> None:
    """
    Main function to process images in the input folder.

    Args:
        input_folder: Path to the folder containing images.
    """
    input_path = Path(input_folder)
    if not input_path.is_dir():
        print(f"Error: '{input_folder}' is not a valid directory.", file=sys.stderr)
        sys.exit(1)

    resized_dir = input_path / 'resized'
    resized_dir.mkdir(exist_ok=True)

    supported_extensions = {'.jpg', '.jpeg', '.png'}
    processed_count = 0
    skipped_count = 0

    for file_path in input_path.iterdir():
        if file_path.is_file() and file_path.suffix.lower() in supported_extensions:
            try:
                with Image.open(file_path) as img:
                    width, height = img.size
                    max_side = max(width, height)

                    if max_side > 1920:
                        # Calculate scaling factor to make longest side exactly 1920px
                        scale = 1920 / max_side
                        new_width = int(width * scale)
                        new_height = int(height * scale)
                        # Resize using Lanczos resampling for high quality
                        img = img.resize((new_width, new_height), ImageResampling.LANCZOS)

                    # Determine output path (preserve original filename)
                    out_path = resized_dir / file_path.name

                    # Save in appropriate format: PNG preserves transparency, JPEG converts to RGB
                    if file_path.suffix.lower() == '.png':
                        img.save(out_path, 'PNG')
                    else:
                        # Convert to RGB for JPEG compatibility (handles RGBA PNGs if any)
                        rgb_img = img.convert('RGB')
                        rgb_img.save(out_path, 'JPEG', quality=95, optimize=True)

                    print(f"✓ Processed: {file_path.name} ({width}x{height} -> {img.size if max_side > 1920 else 'unchanged'})")
                    processed_count += 1

            except Exception as e:
                print(f"✗ Error processing {file_path.name}: {e}", file=sys.stderr)
                skipped_count += 1

    print(f"\nSummary: {processed_count} images processed, {skipped_count} skipped due to errors.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Resize images (>1920px longest side) in a folder to 1920px max side, preserving aspect ratio."
    )
    parser.add_argument(
        "input_folder",
        help="Path to the folder containing .jpg/.jpeg/.png images"
    )
    args = parser.parse_args()
    main(args.input_folder)
```
- `pip install Pillow`
- `python script.py /path/to/your/image/folder`
- Resized images saved in `/path/to/your/image/folder/resized/`
- Originals unchanged; script skips non-image files and logs errors
Judge notes: The print statement for "unchanged" images shows the wrong value — `img.size if max_side > 1920 else 'unchanged'` uses `img` after reassignment inside the `if` block, so when `max_side <= 1920` it still prints the original size correctly by accident, but the logic is confusing and misleading since it copies unchanged images to the resized folder without clearly communicating that in the output or design intent.

Related queries

Try it with a real tool

Run this prompt in one of these tools. Affiliate links help keep Gridlyx free.