How do I make this code less stressful for my phone to handle? \n\n import mpmath
from PIL import Image, ImageDraw, ImageFont
import math
import os

def get_pi_digits(n):
    """
    Calculate n digits of pi using mpmath.

    Args:
        n (int): Number of pi digits to calculate.

    Returns:
        str: A string containing n digits of pi (without the initial '3').
    """
    mpmath.mp.dps = n + 2  # Decimal places; 1 extra for '3.'
    pi_str = str(mpmath.mp.pi)
    pi_digits = pi_str.replace('.', '')[1:n+1]  # Exclude the initial '3'
    return pi_digits

def find_max_font_size(font_path, image_width, image_height):
    """
    Find the maximum font size that allows the text to fit within the image dimensions.

    Args:
        font_path (str): Path to the TTF font file.
        image_width (int): Width of the image in pixels.
        image_height (int): Height of the image in pixels.

    Returns:
        tuple: (font_size, chars_per_line, lines)
            font_size (int): Maximum feasible font size.
            chars_per_line (int): Number of characters per line.
            lines (int): Number of lines per image.
    """
    lower = 1
    upper = 500  # Arbitrary upper limit for font size
    best_font_size = 0
    best_chars_per_line = 0
    best_lines = 0

    while lower <= upper:
        mid = (lower + upper) // 2
        try:
            font = ImageFont.truetype(font_path, mid)
        except IOError:
            # If the font size is too large and unsupported, decrease upper
            upper = mid - 1
            continue

        # Use '0' as a representative character to measure width and height
        bbox = font.getbbox('0')
        char_width = bbox[2] - bbox[0]
        char_height = bbox[3] - bbox[1]

        if char_width == 0 or char_height == 0:
            upper = mid - 1
            continue

        # Calculate how many characters fit per line and number of lines
        chars_per_line = image_width // char_width
        lines = image_height // char_height

        if chars_per_line == 0 or lines == 0:
            upper = mid - 1
            continue

        # To maximize font size, ensure that at least one digit fits
        if chars_per_line * lines > 0:
            best_font_size = mid
            best_chars_per_line = chars_per_line
            best_lines = lines
            lower = mid + 1  # Try a larger font size
        else:
            upper = mid - 1  # Try a smaller font size

    return best_font_size, best_chars_per_line, best_lines

def create_pi_images(pi_digits, font_path, image_width=2480, image_height=3508):
    """
    Create one or more A4-sized images containing the pi digits.

    Args:
        pi_digits (str): String of pi digits.
        font_path (str): Path to the TTF font file.
        image_width (int, optional): Width of the image in pixels. Defaults to 2480 (A4 at 300 DPI).
        image_height (int, optional): Height of the image in pixels. Defaults to 3508 (A4 at 300 DPI).

    Returns:
        list: A list of PIL Image objects.
    """
    images = []
    digits_per_page = 0
    font_size = 0
    chars_per_line = 0
    lines_per_page = 0

    # Determine maximum font size and capacity
    font_size, chars_per_line, lines_per_page = find_max_font_size(font_path, image_width, image_height)

    if font_size == 0:
        raise ValueError("Unable to determine a suitable font size.")

    digits_per_page = chars_per_line * lines_per_page

    # Split the digits into chunks for each page
    pages = [pi_digits[i:i + digits_per_page] for i in range(0, len(pi_digits), digits_per_page)]

    for page_num, chunk in enumerate(pages, start=1):
        # Create a new white image
        img = Image.new('RGB', (image_width, image_height), color='white')
        draw = ImageDraw.Draw(img)

        # Load the font with the determined size
        font = ImageFont.truetype(font_path, font_size)

        # Split the chunk into lines
        lines = [chunk[i:i + chars_per_line] for i in range(0, len(chunk), chars_per_line)]

        # Draw each line onto the image
        y = 0
        for line in lines:
            draw.text((0, y), line, font=font, fill='black')
            y += font.getbbox(line)[3] - font.getbbox(line)[1]  # Increment y by character height

        images.append(img)

    return images

def save_images(images, output_folder):
    """
    Save the generated images to the specified folder.

    Args:
        images (list): List of PIL Image objects.
        output_folder (str): Directory where images will be saved.
    """
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for idx, img in enumerate(images):
        img_path = os.path.join(output_folder, f'pi_digits_page_{idx+1}.png')
        # Save with 300 DPI
        img.save(img_path, 'PNG', dpi=(300, 300))
        print(f"Saved {img_path}")

def main():
    """
    Main function to execute the pi digit image generation.
    """
    # User-configurable parameters
    n_digits = 100000  # Number of pi digits to calculate
    font_path = 'DejaVuSansMono.ttf'  # Ensure the font file is in the same directory
    image_width = 2480  # A4 width in pixels at 300 DPI
    image_height = 3508  # A4 height in pixels at 300 DPI
    output_folder = 'pi_images'  # Output directory for images

    # Step 1: Calculate pi digits
    print(f"Calculating {n_digits} digits of pi...")
    pi_digits = get_pi_digits(n_digits)
    print("Pi digit calculation complete.")

    # Step 2: Create images with pi digits
    print("Generating image(s) with pi digits...")
    images = create_pi_images(pi_digits, font_path, image_width, image_height)
    print(f"Generated {len(images)} image(s).")

    # Step 3: Save the images
    print("Saving images...")
    save_images(images, output_folder)
    print("All images have been saved successfully.")

if __name__ == "__main__":
    main()