The script calculates a file size budget based on the square root of the image's dimensions, and iteratively encodes images to fall in that budget.
This script will encode AVIF by default, but I've also thrown in JPEG-XL and JPEG support, too. This script is tuned to create very lossy images with small sizes, so if you're looking for a miracle app that uses AI to infinitely enhance like on CSI, look elsewhere.