MP4_VIDEO_COMPRESSOR


The Python program featured in this tutorial attempts to reduce the data size of an MP4 video file to 24 megabytes (or smaller) using Python modules which are downloaded and installed on the local machine which executes the Python program. Videos which are “significantly larger” than 24 megabytes are not always possible to shrink down to 24 megabytes and, if the input video is already to be deemed “maximally compressed” by the Python program, the output video will be the same size as the input video. For example, when karbytes used that program to compress a video which had a data size of 150.0 megabytes, the resulting output video was 107.2 megabytes (and when karbytes attempted to make that output video the new input video to the program, the program output a video which was also 107.2 megabytes).

Note that 24 megabytes was arbitrarily selected to be the target output video size due to the fact that the maximum file size for files which are uploaded to GitHub is 25 megabytes (per commit).

To view hidden text inside each of the preformatted text boxes below, scroll horizontally.


SOFTWARE_APPLICATION_COMPONENTS


python_source_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_24/main/mp4_compressor.py


PROGRAM_INTERPRETATION_AND_EXECUTION


STEP_0: Copy and paste the Python source code into a new text editor document and save that document as the following file name:

mp4_compressor.py

STEP_1: Install pip (which, for karbytes, required using a virtual environment in which to install and run pip-installed Python modules) using the following Unix commands.

(The purpose of the virtual environment is to prevent conflicts which may arise from different processes using the same computing resources. In this case, the virtual environment enables the user to manage pip-installed packages independently of the system Python environment).

(Note also that installing the virtual environment automatically installs pip with it).

1.0: Create the virtual environment:

python3 -m venv myenv

1.1: Activate the virtual environment:

source myenv/bin/activate

1.2: Install MoviePy within the Virtual Environment:

pip install moviepy

1.3: Use the Virtual Environment:

While the virtual environment is active, any Python commands will use the packages installed in myenv. To deactivate the virtual environment, use the following command:

deactivate

STEP_2: While the virtual environment is active, set the current directory to wherever the Python program file is located on the local machine (e.g. Desktop).

cd Desktop

STEP_3: Run the program by entering the following command:

python3 mp4_compressor.py

STEP_4: If the program interpretation command does not work, then use the following commands (in top-down order) to install the Python interpreter:

sudo apt update
sudo apt install python3

STEP_5: Observe program results in the file directory where the input video file is located. The program should have created a folder there named compressed_output (if that folder did not exist there already) and generated the output file inside of that folder.


PROGRAM_SOURCE_CODE


Note that the text inside of each of the the preformatted text boxes below appears on this web page (while rendered correctly by the web browser) to be identical to the content of that preformatted text box text’s respective plain-text file or source code output file (whose Uniform Resource Locator is displayed as the green hyperlink immediately above that preformatted text box (if that hyperlink points to a source code file) or whose Uniform Resource Locator is displayed as the orange hyperlink immediately above that preformatted text box (if that hyperlink points to a plain-text file)).

(Note that angle brackets which resemble HTML tags (i.e. an “is less than” symbol (i.e. ‘<‘) followed by an “is greater than” symbol (i.e. ‘>’)) displayed on this web page have been replaced (at the source code level of this web page) with the Unicode symbols U+003C (which is rendered by the web browser as ‘<‘) and U+003E (which is rendered by the web browser as ‘>’). That is because the WordPress web page editor or web browser interprets a plain-text version of an “is less than” symbol followed by an “is greater than” symbol as being an opening HTML tag (which means that the WordPress web page editor or web browser deletes or fails to display those (plain-text) inequality symbols and the content between those (plain-text) inequality symbols)).

python_source_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_extension_pack_24/main/mp4_compressor.py


#########################################################################################
# file: mp4_compressor.py
# type: Python
# date: 01_NOVEMBER_2024
# author: karbytes
# license: PUBLIC_DOMAIN 
#########################################################################################
from moviepy.editor import VideoFileClip
import os

def compress_mp4(input_file, output_folder="compressed_output", target_size_mb=24):
    # Convert target size to bytes
    target_size_bytes = target_size_mb * 1024 * 1024

    # Check if input file exists and is an MP4
    if not os.path.isfile(input_file) or not input_file.endswith('.mp4'):
        print("Please provide a valid MP4 file.")
        return

    # Load the video to get its duration
    video = VideoFileClip(input_file)
    duration = video.duration  # in seconds

    # Calculate the current file size and bitrate
    current_size = os.path.getsize(input_file)
    current_bitrate = (current_size * 8) / duration  # in bits per second

    # Calculate target bitrate based on desired file size
    target_bitrate = (target_size_bytes * 8) / duration  # in bits per second

    # Check if we need to compress (if the target bitrate is lower than current)
    if target_bitrate >= current_bitrate:
        print(f"The file is already under {target_size_mb} MB.")
        video.close()
        return

    # Create output directory if it doesn't exist
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # Define output file path
    output_file = os.path.join(output_folder, os.path.basename(input_file))

    try:
        # Compress video using the target bitrate
        video.write_videofile(
            output_file,
            codec="libx264",
            bitrate=f"{int(target_bitrate)}",
            audio_codec="aac",
            threads=4,
            preset="medium"
        )
        print(f"Compression completed: {output_file}")
    except Exception as e:
        print(f"An error occurred during compression: {e}")
    finally:
        video.close()

input_mp4 = "input_video.mp4"  # Replace with your MP4 file path
compress_mp4(input_mp4)

This web page was last updated on 07_NOVEMBER_2024. The content displayed on this web page is licensed as PUBLIC_DOMAIN intellectual property.