Final Instagram Reel Cutter Application Script

Mar 24, 2026
Python
Advertisement
Article Top Ad (728x90)
Final Instagram Reel Cutter Application Script

Overview

Introduction

The provided Python script represents a desktop-based video processing application developed to automate the creation of short-form video content from longer video files. This tool is specifically designed to support modern content creation workflows by enabling efficient generation of vertically formatted video clips suitable for platforms such as Instagram Reels, YouTube Shorts, and similar media channels.

The application is built using a combination of well-established Python libraries, including Tkinter for graphical user interface (GUI) development, MoviePy for video editing and processing, and Pillow (PIL) for image and text rendering. Together, these technologies provide a robust and user-friendly environment for performing complex video manipulation tasks without requiring manual editing in external software.

The primary function of this application is to allow users to select a video file, define a specific time range, and divide that segment into multiple smaller clips of equal duration. Each generated clip is automatically formatted into a vertical resolution (1080 × 1920), ensuring compatibility with short-form video platforms. Additionally, the tool supports the inclusion of customizable top and bottom text overlays, which can be used for titles, captions, or branding purposes. This system incorporates automation features such as sequential file naming, dynamic text wrapping, and real-time progress tracking. It also includes validation mechanisms to handle input errors, ensuring reliable execution. Furthermore, the use of multi-threading prevents the user interface from freezing during video processing, thereby improving usability and performance. Overall, this application serves as an efficient solution for automating repetitive video editing tasks. It reduces manual effort, enhances productivity, and enables consistent output generation, making it particularly valuable for content creators, educators, and developers working in media automation and digital content production.
 
import os
import tkinter as tk
from tkinter import filedialog, messagebox

from moviepy.editor import VideoFileClip, CompositeVideoClip, ColorClip, ImageClip
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import threading

# ================= PIL FIX =================
ifnot hasattr(Image, "ANTIALIAS"):
    Image.ANTIALIAS = Image.Resampling.LANCZOS
# ==========================================

# ================= UTILS =================
def get_next_index(folder):
    ifnot os.path.exists(folder):
        return0
    nums = []
    for f in os.listdir(folder):
        if f.endswith(".mp4"):
            try:
                nums.append(int(os.path.splitext(f)[0]))
            except:
                pass
    return max(nums) + 1if nums else0

# ================= TEXT UTILS =================
def wrap_text(draw, text, font, max_width):
    words = text.split()
    lines = []
    line = ""
    for w in words:
        test = line + w + " "
        if draw.textbbox((0, 0), test, font=font)[2] <= max_width:
            line = test + " "if line else w + " "
        else:
            lines.append(line)
            line = w + " "
    lines.append(line)
    return lines

def calc_text_height(draw, lines, font, line_spacing):
    height = 0
    for l in lines:
        bbox = draw.textbbox((0, 0), l, font=font)
        height += (bbox[3] - bbox[1]) + line_spacing
    return height

def draw_text(draw, lines, font, img_width, padding, line_spacing):
    y = padding
    for l in lines:
        bbox = draw.textbbox((0, 0), l, font=font)
        w = bbox[2] - bbox[0]
        h = bbox[3] - bbox[1]
        draw.text(
            ((img_width - w) // 2, y),
            l,
            font=font,
            fill="white"
        )
        y += h + line_spacing

# ================= CORE LOGIC =================
def process_video_thread():
    threading.Thread(target=process_video, daemon=True).start()

def process_video():
    try:
        video_path = video_var.get()
        out_folder = folder_var.get()

        ifnot video_path ornot out_folder:
            messagebox.showerror("Error", "Video aur Output Folder select karo")
            return

        start_time = start_min.get() * 60 + start_sec.get()
        end_time = end_min.get() * 60 + end_sec.get()

        if start_time >= end_time:
            messagebox.showerror("Error", "Start Time End Time se chhota hona chahiye")
            return

        part_seconds = int(part_var.get())
        if part_seconds < 2:
            messagebox.showerror("Error", "Part Seconds minimum 2 hone chahiye")
            return

        top_text = top_text_var.get()
        bottom_text = bottom_text_var.get()
        start_number = int(number_var.get())

        os.makedirs(out_folder, exist_ok=True)
        index = get_next_index(out_folder)

        full_clip = VideoFileClip(video_path)

        if end_time > full_clip.duration:
            messagebox.showerror(
                "Error",
                f"End Time video duration ({int(full_clip.duration)} sec) se zyada hai"
            )
            return

        clip = full_clip.subclip(start_time, end_time)

        FINAL_W, FINAL_H = 1080, 1920
        TEXT_VIDEO_GAP = 10

        font_top = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", 64)
        font_bottom = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", 58)

        t = 0
        count = 0
        created = 0

        total_parts = int(np.ceil(clip.duration / part_seconds))
        progress_var.set(f"Total Parts: {total_parts}")
        root.update_idletasks()

        while t < clip.duration:
            end_t = min(t + part_seconds, clip.duration)
            if end_t <= t:
                break

            part = clip.subclip(t, end_t)

            video = part.resize(width=FINAL_W)
            bg = ColorClip((FINAL_W, FINAL_H), (0, 0, 0), duration=part.duration)
            video = video.set_position("center")

            video_top = (FINAL_H - video.h) // 2
            video_bottom = video_top + video.h

            # ---------- TOP TEXT ----------
            dummy = Image.new("RGBA", (FINAL_W, 10))
            draw_dummy = ImageDraw.Draw(dummy)
            top_lines = wrap_text(
                draw_dummy,
                f"{top_text}{start_number + count}",
                font_top,
                FINAL_W - 40
            )
            top_h = calc_text_height(draw_dummy, top_lines, font_top, 8) + 20
            img_top = Image.new("RGBA", (FINAL_W, top_h), (0, 0, 0, 0))
            draw_top = ImageDraw.Draw(img_top)
            draw_text(draw_top, top_lines, font_top, FINAL_W, 10, 8)
            top_clip = ImageClip(np.array(img_top))\
                .set_duration(part.duration)\
                .set_position(("center", video_top - top_h - TEXT_VIDEO_GAP))

            # ---------- BOTTOM TEXT ----------
            dummy2 = Image.new("RGBA", (FINAL_W, 10))
            draw_dummy2 = ImageDraw.Draw(dummy2)
            bot_lines = wrap_text(
                draw_dummy2,
                bottom_text,
                font_bottom,
                FINAL_W - 40
            )
            bot_h = calc_text_height(draw_dummy2, bot_lines, font_bottom, 10) + 20
            img_bot = Image.new("RGBA", (FINAL_W, bot_h), (0, 0, 0, 0))
            draw_bot = ImageDraw.Draw(img_bot)
            draw_text(draw_bot, bot_lines, font_bottom, FINAL_W, 10, 10)
            bot_clip = ImageClip(np.array(img_bot))\
                .set_duration(part.duration)\
                .set_position(("center", video_bottom + TEXT_VIDEO_GAP))

            final = CompositeVideoClip([bg, video, top_clip, bot_clip])

            current_filename = f"{index}.mp4"
            progress_var.set(
                f"Processing: {current_filename} | Part {created + 1}/{total_parts}"
            )
            root.update_idletasks()

            final.write_videofile(
                os.path.join(out_folder, current_filename),
                fps=30,
                codec="libx264",
                audio_codec="aac",
                verbose=True  # default logger
            )

            index += 1
            count += 1
            created += 1
            t += part_seconds

            progress_var.set(
                f"Completed: {created}/{total_parts} | Next: {index}.mp4"
            )
            root.update_idletasks()

        progress_var.set(f"Done! {created} reels created successfully 🎉")
        messagebox.showinfo("Done", f"{created} reels created successfully 🎉")

    except Exception as e:
        messagebox.showerror("Error", str(e))

# ================= GUI =================
root = tk.Tk()
root.title("Instagram Reel Cutter - King Edition 👑")
root.geometry("550x750")

video_var = tk.StringVar()
part_var = tk.StringVar(value="5")
top_text_var = tk.StringVar()
bottom_text_var = tk.StringVar()
number_var = tk.StringVar(value="1")
folder_var = tk.StringVar()

start_min = tk.IntVar(value=0)
start_sec = tk.IntVar(value=0)
end_min = tk.IntVar(value=0)
end_sec = tk.IntVar(value=0)

def pick_video():
    path = filedialog.askopenfilename(
        filetypes=[("Video Files", "*.mp4 *.mkv"), ("All Files", "*.*")]
    )
    ifnot path:
        return
    video_var.set(path)
    try:
        clip = VideoFileClip(path)
        duration = int(clip.duration)
        clip.close()
        end_min.set(duration // 60)
        end_sec.set(duration % 60)
    except Exception as e:
        messagebox.showerror("Error", f"Video load nahi ho paya\n{e}")

def pick_folder():
    folder_var.set(filedialog.askdirectory())

# ----- Video Selection -----
tk.Label(root, text="Select Video").pack()
tk.Entry(root, textvariable=video_var, width=50).pack()
tk.Button(root, text="Browse", command=pick_video).pack(pady=4)

# Time and Part Frames
time_frame = tk.Frame(root)
time_frame.pack(pady=5)

start_frame = tk.Frame(time_frame)
start_frame.pack(side="left", padx=10)
tk.Label(start_frame, text="Start Time (mm:ss)").pack()
fs = tk.Frame(start_frame)
fs.pack()
tk.Spinbox(fs, from_=0, to=59, width=3, textvariable=start_min).pack(side="left")
tk.Label(fs, text=" : ").pack(side="left")
tk.Spinbox(fs, from_=0, to=59, width=3, textvariable=start_sec).pack(side="left")
tk.Label(start_frame, text="Part Seconds").pack(pady=(5,0))
tk.Spinbox(start_frame, from_=2, to=999, width=5, textvariable=part_var).pack()

end_frame = tk.Frame(time_frame)
end_frame.pack(side="left", padx=50)
tk.Label(end_frame, text="End Time (mm:ss) [Auto]").pack()
fe = tk.Frame(end_frame)
fe.pack()
tk.Spinbox(fe, from_=0, to=999, width=3, textvariable=end_min).pack(side="left")
tk.Label(fe, text=" : ").pack(side="left")
tk.Spinbox(fe, from_=0, to=59, width=3, textvariable=end_sec).pack(side="left")
tk.Label(end_frame, text="Start Number").pack(pady=(5,0))
tk.Spinbox(end_frame, from_=1, to=9999, width=5, textvariable=number_var).pack()

# Other fields
fields = [
    ("Top Text", top_text_var),
    ("Bottom Text", bottom_text_var),
    ("Output Folder", folder_var),
]

for label, var in fields:
    tk.Label(root, text=label).pack()
    tk.Entry(root, textvariable=var, width=50).pack()

tk.Button(root, text="Browse Folder", command=pick_folder).pack(pady=4)

# Start Button
tk.Button(
    root,
    text="START CUTTING 🚀",
    bg="green",
    fg="white",
    font=("Arial", 12, "bold"),
    command=process_video_thread
).pack(pady=10)

# Progress Display
progress_var = tk.StringVar(value="Progress will appear here")
progress_label = tk.Label(root, textvariable=progress_var, justify="left", fg="blue", font=("Arial", 10))
progress_label.pack(pady=10)

root.mainloop()

Detailed Code Explanation

The provided Python script implements a complete automated video processing application. The following explanation is written in a structured, professional manner to help students clearly understand how the code works internally.

The script begins with the import of required libraries, each serving a specific role in the application. The os module is used for interacting with the file system, such as reading directories and creating folders. The tkinter library provides the graphical user interface components, enabling user interaction through buttons, input fields, and labels. The moviepy.editor module is responsible for all video-related operations, including loading video files, cutting clips, resizing frames, and exporting final outputs. The PIL (Pillow) library is used to generate images and render text, which later become overlays on the video. The numpy library is used to convert image data into array format for compatibility with MoviePy, and the threading module allows the program to execute long-running tasks without freezing the interface.

A compatibility fix is included to handle differences between Pillow versions. The script checks whether the ANTIALIAS attribute exists in the Image module. If it does not, it assigns the modern equivalent Image.Resampling.LANCZOS. This ensures that image resizing functions work correctly across different environments.

The first functional component in the script is a utility function that determines the next available file index for saving output videos. It scans the selected output directory, identifies all .mp4 files, extracts numeric file names, and calculates the next index value. This mechanism prevents overwriting existing files and maintains a sequential naming system.

The script then defines a set of text-processing functions. The text wrapping function takes a string input and splits it into multiple lines so that it fits within a specified width. It uses bounding box calculations to measure text size dynamically. Another function calculates the total height of the wrapped text, which is necessary for positioning the text correctly on the video. A third function handles the actual rendering of text onto an image, ensuring that each line is centered horizontally and spaced evenly. These functions work together to produce clean and readable text overlays. To maintain responsiveness of the graphical interface, the script uses a separate thread for video processing. A helper function is defined to start the main processing function inside a background thread. This prevents the user interface from freezing while the video is being processed, which is especially important for large files. The main logic of the application is implemented in the video processing function. This function begins by retrieving all user inputs from the interface, including the selected video file, output directory, start and end times, segment duration, and overlay text. It performs validation checks to ensure that all required inputs are provided and that the start time is less than the end time. It also ensures that the segment duration meets the minimum requirement. The time values entered by the user are converted from minutes and seconds into total seconds. This allows precise control when extracting portions of the video. The video file is then loaded using MoviePy, and its total duration is checked to ensure that the selected end time does not exceed the actual video length. A subclip is created from the original video based on the specified time range. The script defines a fixed output resolution of 1080 by 1920 pixels, which is suitable for vertical video platforms. A black background is created using a color clip, and the video is resized to fit within the width of this frame while maintaining its aspect ratio. The video is then positioned at the center of the frame.

The application processes the video in a loop, dividing it into smaller segments based on the specified duration. For each segment, a new clip is created. The script then generates text overlays for both the top and bottom sections of the video. The top text includes dynamic numbering, which increments for each segment, while the bottom text remains constant. The text is first wrapped and rendered onto an image using Pillow, then converted into a MoviePy ImageClip. These clips are positioned relative to the main video frame, ensuring proper spacing and alignment.

Once all elements are prepared, they are combined into a single composite video using MoviePy’s composition functionality. This composite includes the background, the resized video segment, and both text overlays. The final video is then exported as an MP4 file using standard encoding settings, including a frame rate of 30 frames per second and widely supported audio and video codecs. During the processing loop, the application continuously updates a progress variable, which is displayed in the user interface. This provides real-time feedback on the number of clips processed and the current status. After all segments have been processed, a completion message is displayed to inform the user that the operation has finished successfully. The graphical user interface is constructed using Tkinter. A main window is created with a defined size and title. Input fields are provided for selecting the video file, entering time values, specifying segment duration, and adding overlay text. Buttons are included for browsing files and starting the processing operation. Spin boxes are used for numerical input, ensuring controlled and error-free data entry. A progress label is also included to display real-time updates. Finally, the application enters the main event loop, which keeps the interface active and responsive. All user interactions are handled within this loop, and the application continues running until it is closed. Overall, this code demonstrates a well-structured approach to building a real-world application that combines user interface design, multimedia processing, and automation. It provides students with a clear understanding of how different components of Python can be integrated to solve practical problems efficiently.
 

Advantages

The application provides a highly efficient solution for automating video editing tasks. One of its primary advantages is the ability to convert long-form videos into multiple short clips automatically, significantly reducing the time and effort required for manual editing. This makes it especially useful for content creators who regularly produce short-form videos for social media platforms. Another important advantage is its user-friendly graphical interface. Since the application is built using Tkinter, users do not need programming knowledge to operate it. All functionalities, including video selection, time configuration, and text input, are accessible through simple interface elements. The use of automation in this script ensures consistency across all generated video clips. Each output maintains the same resolution, formatting, and text positioning, which is essential for professional content production. Additionally, the automatic file naming system prevents overwriting and keeps output files organized. The application also incorporates multi-threading, which improves performance by allowing video processing to run in the background. This ensures that the user interface remains responsive during execution, enhancing the overall user experience. Another key strength is the dynamic text handling capability. The script automatically wraps and aligns text based on the available width, ensuring that overlays remain readable and visually appealing regardless of content length. Furthermore, the application includes proper error handling and input validation. This minimizes runtime errors and provides clear feedback to the user, making the system more reliable and robust.

Disadvantages

Despite its strengths, the application has certain limitations. One of the main disadvantages is its dependency on specific system configurations. For example, the script uses a fixed font path (C:/Windows/Fonts/arial.ttf), which may not work on non-Windows systems or machines where the font is unavailable. This reduces portability.

Another limitation is performance scalability. Video processing, especially for large files or high-resolution videos, can be resource-intensive and time-consuming. Since the script processes clips sequentially, it may not fully utilize system resources for faster execution. The application also lacks advanced video editing features. It focuses primarily on cutting and adding text overlays, without support for transitions, effects, filters, or audio enhancements. This limits its use for more complex video production requirements. Additionally, the graphical interface, while functional, is relatively basic in design. It does not include advanced usability features such as drag-and-drop support, preview functionality, or customizable themes, which could enhance user experience. Another drawback is the absence of cross-platform optimization. Although Python is cross-platform, certain elements in the script, such as file paths and dependencies, may require modification to run smoothly on different operating systems. Finally, the application does not include logging or detailed reporting mechanisms. While it provides basic progress updates, it lacks comprehensive logs that could be useful for debugging or performance analysis.
Sponsored Content
In-Content Ad (300x250)
Python Blog Verified
Written by

Administrator

Coding Educator
Verified Author
Advertisement
Ad Banner
(300x250)
Advertisement
Ad Banner (728x90)

User Reviews & Comments

Share your experience with this Blog. Your feedback helps our community make informed decisions!

0 reviews

Share Your Experience

Help others by sharing your thoughts about this Blog.

0/1000 characters

No Reviews Yet

Be the first to share your experience with this Blog!

Related Blogs

Explore more Blogs in the same language

Automating Long Video Splitting into Short Clips Using Python

Automating Long Video Splitting into Short Clips Using Python

Python

Learn how to automatically split long videos into short clips using Python. Create reels-ready videos with free, local video automation for Instagram and Facebook.

Automate Video Editing with Python: Add Dynamic Top & Bottom Text to Shorts

Automate Video Editing with Python: Add Dynamic Top & Bottom Text to Shorts

Python

Learn how to automate video editing with Python by converting long videos into Shorts or Reels. This tutorial explains dynamic top and bottom text overlays, auto-incrementing part numbers, MoviePy usage, and GitHub-based version updates with git pull or clone.

Advertisement
Ad Banner (728x90)
Advertisement
Footer Ad (728x90)