What's wrong with this script, rewrite it and fix it's problems. import numpy as np
from PIL import Image
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import logging
import time

# Configure logging
logging.basicConfig(filename='process.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

def log_and_print(message, level='info'):
    """Log and print messages."""
    if level == 'info':
        logging.info(message)
    elif level == 'debug':
        logging.debug(message)
    elif level == 'error':
        logging.error(message)
    print(message)

def resize_image(image_path, new_size=(256, 256)):
    """Resize the image to a smaller size."""
    try:
        img = Image.open(image_path)
        img = img.resize(new_size, Image.Resampling.LANCZOS)  # Resize image with correct attribute
        resized_path = 'resized_image.png'
        img.save(resized_path)
        log_and_print(f"Image resized and saved to {resized_path}")
        return resized_path
    except Exception as e:
        log_and_print(f"Error resizing image: {e}", 'error')
        return None

def process_image(image_path):
    """Process image with t-SNE and save transformed image."""
    resized_image_path = resize_image(image_path)
    if not resized_image_path:
        return False

    try:
        log_and_print(f"Processing image: {resized_image_path}")
        
        # Read image
        img = Image.open(resized_image_path).convert('RGBA')
        img_array = np.array(img)
        
        # Convert image to RGB
        img_array_rgb = img_array[:, :, :3]  # Exclude Alpha channel
        
        # Flatten image
        img_flattened = img_array_rgb.reshape(-1, 3)
        
        # Apply t-SNE
        log_and_print("Applying t-SNE...")
        start_time = time.time()
        try:
            tsne = TSNE(n_components=2, random_state=0)
            img_tsne = tsne.fit_transform(img_flattened)
            end_time = time.time()
            log_and_print(f"t-SNE computation time: {end_time - start_time:.2f} seconds")
        except MemoryError:
            log_and_print("MemoryError: t-SNE failed due to insufficient memory.", 'error')
            log_and_print("Attempting to process with a smaller image or fewer pieces.")
            return handle_t_sne_failure(image_path)

        # Reshape t-SNE output
        img_tsne_reshaped = img_tsne.reshape(img_array.shape[0], img_array.shape[1], 2)
        
        # Normalize t-SNE output for visualization
        img_tsne_normalized = (img_tsne_reshaped - np.min(img_tsne_reshaped)) / (np.max(img_tsne_reshaped) - np.min(img_tsne_reshaped))
        img_tsne_rgb = (img_tsne_normalized * 255).astype(np.uint8)
        
        # Plot t-SNE results
        plt.imshow(img_tsne_rgb)
        plt.axis('off')
        plt.savefig('transformed_image.png', bbox_inches='tight')
        
        log_and_print("Image transformation completed successfully.")
    except Exception as e:
        log_and_print(f"Error processing image: {e}", 'error')
        return False
    return True

def handle_t_sne_failure(image_path):
    """Handle t-SNE failure by resizing the image or breaking it into smaller pieces."""
    response = input("Do you want to resize the image or break it into smaller pieces? (resize/split/skip): ").strip().lower()
    
    if response == 'resize':
        new_size = input("Enter new image size (width,height) e.g. 256,256: ").strip()
        try:
            width, height = map(int, new_size.split(','))
            resized_path = resize_image(image_path, new_size=(width, height))
            if resized_path:
                return process_image(resized_path)
        except ValueError:
            log_and_print("Invalid size format. Please use (width,height) format.", 'error')
    
    elif response == 'split':
        log_and_print("Image splitting is not yet implemented.", 'info')
    
    elif response == 'skip':
        log_and_print("Skipping processing due to errors.", 'info')
    
    else:
        log_and_print("Invalid response. Skipping.", 'info')
    
    return False

# Main execution
if __name__ == "__main__":
    image_path = '/root/it/image.png'
    text_message = input("What text would you like to magically appear? ")

    log_and_print(f"Starting process with image: {image_path}")
    log_and_print(f"Text message to display on the plot: {text_message}")
    
    success = process_image(image_path)
    if success:
        log_and_print("Process completed successfully.")
    else:
        log_and_print("Process failed.")