DEV Community

Cover image for A small Python quality gate for short video exports
Oliger Chen
Oliger Chen

Posted on

A small Python quality gate for short video exports

A short clip from a technical talk can play correctly on your laptop and still be the wrong file to hand to an editor. It might have a landscape frame, an unexpected pixel format, or no audio stream. Those are cheap mistakes to catch before someone reviews the actual explanation.

This tutorial builds a small command-line check around ffprobe. It inspects exported files, prints actionable failures, and returns a nonzero exit status when a file breaks the chosen delivery contract.

It does not try to decide whether the clip teaches anything. That remains a separate review.

Put the check after export

There are two different jobs in turning a recording into a short clip: selecting a useful passage and delivering a usable media file.

For the selection side, Video Cutter AI is one example of a service for making short clips from longer recordings. The checker below takes an ordinary local media file as input. It needs no connection to that service and assumes no API or integration.

For this example, imagine a team handing vertical clips from recorded programming talks to a publishing editor. Its internal delivery contract is:

  • An encoded frame close to 9:16, at least 720 × 1280.
  • Square pixels and no remaining rotation metadata that changes orientation.
  • H.264 video with the yuv420p pixel format.
  • A container duration between 2 and 90 seconds.
  • At least one audio stream.

These are example project requirements, not claims about any platform's upload limits. A silent animation or a landscape code demo would need a different contract.

Read metadata as JSON

Install Python 3 and an FFmpeg distribution that includes ffprobe. Confirm both tools are available:

The examples here were verified with Python 3.14.6 and FFmpeg/ffprobe 9.0.2 on macOS.

python3 --version
ffprobe -version
Enter fullscreen mode Exit fullscreen mode

The ffprobe documentation describes its machine-readable output. We will request stream and container metadata:

ffprobe -v error -show_streams -show_format -of json clip.mp4
Enter fullscreen mode Exit fullscreen mode

The distinction matters: dimensions and codecs belong to streams, while this example reads duration from the container. Missing duration is a failed check rather than a reason to silently substitute zero.

Save the following as clipcheck.py:

import json
import subprocess
import sys
from pathlib import Path


def check(path):
    try:
        result = subprocess.run(
            ["ffprobe", "-v", "error", "-show_streams", "-show_format",
             "-of", "json", str(path)],
            check=True, capture_output=True, text=True,
        )
        data = json.loads(result.stdout)
    except FileNotFoundError:
        return ["ffprobe is not installed or not on PATH"]
    except (subprocess.CalledProcessError, json.JSONDecodeError):
        return ["ffprobe could not read this file"]

    streams = data.get("streams", [])
    video = next((s for s in streams if s.get("codec_type") == "video"
                  and not s.get("disposition", {}).get("attached_pic")), None)
    if video is None:
        return ["no video stream"]

    errors = []
    width, height = video.get("width", 0), video.get("height", 0)
    if height <= 0 or abs(width / height - 9 / 16) > 0.01:
        errors.append("expected a 9:16 encoded frame")
    if width < 720 or height < 1280:
        errors.append("expected at least 720x1280 pixels")
    if video.get("sample_aspect_ratio") != "1:1":
        errors.append("expected explicit square pixels (SAR 1:1)")
    rotations = [s.get("rotation", 0) for s in video.get("side_data_list", [])]
    rotations.append(video.get("tags", {}).get("rotate", 0))
    if any(float(rotation) % 360 != 0 for rotation in rotations):
        errors.append("normalize rotation before checking dimensions")
    if video.get("codec_name") != "h264":
        errors.append("expected H.264 video")
    if video.get("pix_fmt") != "yuv420p":
        errors.append("expected 8-bit yuv420p")

    try:
        duration = float(data.get("format", {}).get("duration", "nan"))
    except (TypeError, ValueError):
        duration = float("nan")
    if not 2 <= duration <= 90:
        errors.append("expected a duration between 2 and 90 seconds")
    if not any(s.get("codec_type") == "audio" for s in streams):
        errors.append("no audio stream")
    return errors


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 clipcheck.py FILE [FILE ...]", file=sys.stderr)
        return 2
    failed = False
    for filename in sys.argv[1:]:
        errors = check(Path(filename))
        failed |= bool(errors)
        print(f"{'FAIL' if errors else 'PASS'} {filename}")
        for error in errors:
            print(f"  - {error}")
    return int(failed)


if __name__ == "__main__":
    raise SystemExit(main())
Enter fullscreen mode Exit fullscreen mode

The argument list passed to subprocess.run avoids shell parsing. A filename containing spaces stays a single argument, and the script does not interpolate filenames into a shell command.

The width-to-height comparison allows a small tolerance for rounded dimensions. It checks stored frame geometry only after also rejecting non-square pixels and rotation metadata. It is intentionally strict: files without an explicit 1:1 sample aspect ratio need inspection, even if a player displays them correctly.

This is also why checking whether height > width alone would be too weak. A tall file can have the wrong shape, and a rotated file can have stored dimensions that differ from its displayed orientation.

Try a passing file and a failing file

FFmpeg can generate synthetic video and audio, so this check needs no private recordings or sample downloads. The commands below create new files; -n prevents overwriting existing ones.

ffmpeg -v error -n \
  -f lavfi -i 'testsrc2=size=720x1280:rate=30' \
  -f lavfi -i 'sine=frequency=440:sample_rate=48000' \
  -t 3 -vf setsar=1 \
  -c:v libx264 -pix_fmt yuv420p -c:a aac good.mp4

ffmpeg -v error -n \
  -f lavfi -i 'testsrc2=size=1280x720:rate=30' \
  -t 3 -vf setsar=1 \
  -c:v libx264 -pix_fmt yuv420p bad.mp4

python3 clipcheck.py good.mp4
python3 clipcheck.py bad.mp4
Enter fullscreen mode Exit fullscreen mode

With these fixtures, the first check returns 0. The second returns 1 and reports the landscape frame, insufficient height, and missing audio:

PASS good.mp4
FAIL bad.mp4
  - expected a 9:16 encoded frame
  - expected at least 720x1280 pixels
  - no audio stream
Enter fullscreen mode Exit fullscreen mode

Run several files in one invocation to make failure useful in a batch job:

python3 clipcheck.py good.mp4 bad.mp4
Enter fullscreen mode Exit fullscreen mode

The script continues checking the remaining files and returns 1 if any file fails. A missing or unreadable input also fails. Calling it without filenames prints usage and returns 2.

Keep the human review next to the technical one

A PASS means the inspected metadata matches this contract. It does not mean the entire file decodes correctly. For a separate decode check, run:

ffmpeg -v error -xerror -i good.mp4 -f null -
Enter fullscreen mode Exit fullscreen mode

Even a clean decode cannot tell you whether a portrait crop removed the line of code being discussed. An audio stream can exist and contain silence. Burned-in captions are pixels; this script cannot inspect their spelling or timing.

For a programming clip, review the exported file on a phone-sized display. Check whether the code is readable, whether a prerequisite was cut away, and whether the speaker finishes the explanation. If the useful part is a wide terminal session, a landscape excerpt may be a better editorial choice than forcing a vertical crop.

Keep those questions on the same handoff checklist as the automated result. The script can reject a predictable file mistake early, leaving the reviewer time to look at the explanation itself.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

This is the kind of check that pays for itself the first time it catches a landscape export before it reaches the publisher, Oliger. Two additions I would consider: first, a PASS here means the metadata matches the contract, not that the file decodes — you already flag the -xerror decode step, but I would fold it into the same script and gate on it, so a PASS means "valid and decodable", not just "metadata looks right". Second, phone recordings are often variable frame rate, and the reported frame rate can hide that — have you run into a clip where the metadata said 30fps but the frames drifted from the audio? A VFR check, or comparing the container duration against the audio stream duration, would be the next rule I would add. What set the 2-90 second window — a platform limit, or your team's own handoff rule?