Skip to content
Guides

How to Swap Faces in a Video With Python

A face swap video Python script: check and convert the clip with ffmpeg, upload the faces, price and submit the edit, wait, then save the new clip.

Updated 5 min read

A face swap video Python script needs only requests and ffmpeg: it sends your clip and one photo per face to an edit API, waits for the job, and saves the same clip with the new faces, while the moves, lips, scene and sound stay as they were. Here the API is Frameport and the model is Frameport Replace 1, so no GPU is needed on your side, and an edit costs $0.12 per second of clip at 768p, charged only when it succeeds.

The script comes in four parts that you paste into one file, swap.py: check and convert the clip, upload it with the faces, price and submit the edit, then wait and download. A last section handles scenes longer than one edit takes.

What a face swap video Python script needs

  • Python 3.9 or later with requests (pip install requests), and ffmpeg plus ffprobe on your PATH to measure and convert clips.
  • An API key in the FRAMEPORT_API_KEY environment variable. Uploading files and asking for quotes cost nothing; the edit is paid from your balance.
  • A clip the model takes: 2 to 10 seconds, MP4 or MOV, 64 MB at most, at 24 frames per second. The script reads these limits from the API, converts a clip whose format, frame rate or size is off, and trims one that runs long.
  • One photo per person you replace: PNG, JPEG or WebP, up to 10 MB, with the face sharp, lit evenly, uncovered and turned roughly toward the camera.
  • Consent for every face. Use your own face, the face of someone who agreed to this use, or a character you generated. The acceptable use policy rules out real, identifiable people without their consent, anything involving minors, and any impersonation or fraud; everything you make must be fiction.

Upload the clip and the faces

Part 1 asks GET /v1/models/fp-replace-1 for the model's limits, so the script follows them if they ever change. It measures the clip with ffprobe, re-encodes it only when it has to, and sends each file once:

swap.py, part 1: check, convert, upload
import argparse
import hashlib
import json
import os
import subprocess
import time

import requests

API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}"}
MODEL = "fp-replace-1"
TYPES = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
         ".mp4": "video/mp4", ".mov": "video/quicktime"}

INFO = requests.get(f"{API}/models/{MODEL}", headers=HEADERS, timeout=30).json()
LIMITS, RESOLUTIONS = INFO["edit"], INFO["options"]["resolutions"]


def probe(path):
    """A clip's length in seconds, its video codec and its frame rate, read by ffprobe."""
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
         "stream=codec_name,avg_frame_rate:format=duration", "-of", "json", path],
        capture_output=True, text=True, check=True,
    ).stdout
    info = json.loads(out)
    stream = info["streams"][0]
    num, den = (float(part) for part in stream["avg_frame_rate"].split("/"))
    return float(info["format"]["duration"]), stream["codec_name"], num / den if den else 0.0


def prepare(path):
    """The clip as the model takes it: H.264, 24 fps, within the length and size limits."""
    seconds, codec, fps = probe(path)
    if seconds < LIMITS["min_seconds"]:
        raise SystemExit(f"{path} lasts {seconds:.1f} s: the model takes {LIMITS['min_seconds']} s at least")
    ready = (os.path.splitext(path)[1].lower() in (".mp4", ".mov") and codec == "h264"
             and abs(fps - LIMITS["fps"]) < 0.01 and seconds <= LIMITS["max_seconds"]
             and os.path.getsize(path) <= LIMITS["max_bytes"])
    if ready:
        return path, seconds
    out = f"{os.path.splitext(path)[0]}-ready.mp4"
    subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", path, "-t", str(LIMITS["max_seconds"]),
                    "-r", str(LIMITS["fps"]), "-c:v", "libx264", "-crf", "20", "-pix_fmt", "yuv420p",
                    "-c:a", "aac", out], check=True)
    return out, min(seconds, LIMITS["max_seconds"])


def upload(path):
    """Sends one file as the raw body; the upl_ id it returns works in any request for 24 hours."""
    with open(path, "rb") as file:
        res = requests.post(
            f"{API}/uploads",
            params={"filename": os.path.basename(path)},
            headers={**HEADERS, "Content-Type": TYPES[os.path.splitext(path)[1].lower()]},
            data=file,
            timeout=300,
        )
    if not res.ok:
        raise SystemExit(f"{path}: {res.json()['error']['message']}")
    return res.json()["id"]

A clip over the length limit is trimmed here; the last section keeps all of a longer scene instead. An upload streams as it is sent, and its first bytes must be what its Content-Type says, so a file that is not really a picture or a clip is turned away at once. A workspace keeps up to 100 uploads at a time and may send 10 a minute; the uploads reference covers the rest. You can skip the upload for a clip that already sits at a public https URL, or for one of your own outputs, named by its file_… id.

Submit the edit

Before anything is spent, part 2 asks for the exact price: POST /v1/generations/quote with the clip's length in seconds holds nothing and does not count against the rate limit. Then it submits the edit:

swap.py, part 2: price and submit
def quote(seconds, resolution):
    answer = requests.post(f"{API}/generations/quote", headers=HEADERS, timeout=30,
                           json={"model": MODEL, "seconds": seconds, "resolution": resolution}).json()
    if answer.get("error"):
        raise SystemExit(answer["error"]["message"])
    return answer


def submit(video, faces, targets, resolution, keep_outfit):
    body = {"model": MODEL, "video": video, "faces": faces, "resolution": resolution, "keep_outfit": keep_outfit}
    if targets:
        body["targets"] = targets
    # Sending this exact body again (a retry after a timeout) returns the first edit, not a second one
    key = "swap-" + hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()[:32]
    gen = requests.post(f"{API}/videos/edits", headers={**HEADERS, "Idempotency-Key": key}, json=body, timeout=120).json()
    if gen.get("error"):
        raise SystemExit(f"{gen['error']['code']}: {gen['error']['message']}")
    return gen

The 202 arrives once the clip has been fetched and measured. Two things about the money are worth knowing. At submit, the price of the longest clip the model takes is held first and then lowered to your clip's price, so the balance must cover the larger amount for a moment. For the same reason, an edit's max_cost_usd is compared with that first hold rather than with your clip's price: leave it out, or set it no lower than the quote's reserved_usd.

Every refusal at this step is free. A clip outside the limits answers 400 invalid_video, and the message names the fix, such as "takes clips at 24 fps: convert the clip first". A request the content policy refuses answers 400 content_policy. While the workspace's content filter is on, it reads the note (prompt) and each target as well, and a refusal there is 400 content_filtered.

Wait and download

The edit runs on its own after the 202. Part 3 reads it every five seconds, stops on a failure, which leaves nothing charged, and streams the finished file to disk with your key:

swap.py, part 3: wait and download
def wait(gen, every=5):
    while gen["status"] in ("queued", "running"):
        time.sleep(every)
        gen = requests.get(f"{API}/videos/edits/{gen['id']}", headers=HEADERS, timeout=30).json()
    if gen["status"] == "failed":
        raise SystemExit(f"failed, nothing charged: {gen['error']['message']}")
    return gen


def download(gen, path):
    with requests.get(f"{API}/generations/{gen['id']}/content", headers=HEADERS, stream=True, timeout=300) as res:
        res.raise_for_status()
        with open(path, "wb") as out:
            for chunk in res.iter_content(chunk_size=1 << 20):
                out.write(chunk)

Reads do not count against the workspace's rate limit, and the docs suggest a read every 2 to 5 seconds, so this loop stays well inside the rules. For a batch of clips, one webhook beats a loop per clip: the AI video API webhooks guide builds the receiver. Files are not kept forever, so the copy on your disk is the one to keep.

Swapping several people

Part 4 is the command line. One face needs nothing more. For several, pass one photo per person, from left to right, and one --target per photo saying whom it replaces, in the same order:

swap.py, part 4: the command line
def main():
    parser = argparse.ArgumentParser(description="Swap the faces in a clip")
    parser.add_argument("clip")
    parser.add_argument("faces", nargs="+", help="one photo per person, left to right")
    parser.add_argument("--target", action="append", default=[], help='who a face replaces: "the man in the red jacket"')
    parser.add_argument("--resolution", default="768p", choices=RESOLUTIONS)
    parser.add_argument("--new-outfit", action="store_true", help="dress each person as in their photo")
    parser.add_argument("--out", default="swapped.mp4")
    args = parser.parse_args()

    if len(args.faces) > LIMITS["max_faces"]:
        raise SystemExit(f"{LIMITS['max_faces']} faces at most")
    if len(args.faces) > 1 and len(args.target) != len(args.faces):
        raise SystemExit("with several faces, give one --target per face, in the same order")

    clip, seconds = prepare(args.clip)
    price = quote(seconds, args.resolution)
    print(f"{price['breakdown']} · enough balance: {price['enough_balance']}")

    video = upload(clip)
    faces = [upload(face) for face in args.faces]
    gen = wait(submit(video, faces, args.target, args.resolution, keep_outfit=not args.new_outfit))
    download(gen, args.out)
    print(f"saved {args.out} · charged {gen['cost_usd']}")


if __name__ == "__main__":
    main()
One face, then two
python swap.py dance.mp4 me.jpg
python swap.py duet.mp4 ana.jpg ben.jpg \
  --target "the woman on the left in the yellow coat" \
  --target "the man on the right" --resolution 1080p

A target works best when it names what the camera sees: where the person stands, what they wear, what they are doing. Adding faces adds nothing to the bill, since an edit is priced on the clip's seconds only: $0.12 a second at 768p and $0.25 at 1080p, so a 6-second clip at 768p comes to $0.72. With --new-outfit the script sends "keep_outfit": false, and each person also takes the clothes of their photo, which makes it a character swap.

Clips longer than the limit

One edit takes up to 10 seconds of clip, so a longer scene goes through in pieces. Cut it at exact boundaries, run the script on each piece with the same faces and targets, then join the results:

Cut, swap each piece, join
ffmpeg -i long.mp4 -r 24 -c:v libx264 -crf 20 -c:a aac \
  -force_key_frames "expr:gte(t,n_forced*10)" \
  -f segment -segment_time 10 -reset_timestamps 1 part-%03d.mp4

for part in part-*.mp4; do python swap.py "$part" me.jpg --out "swapped-$part"; done

for part in swapped-part-*.mp4; do echo "file '$part'"; done > parts.txt
ffmpeg -f concat -safe 0 -i parts.txt -c copy swapped-long.mp4

A final piece under 2 seconds is refused, so trim the scene or move a cut until the last piece is long enough. If the joined file stutters where pieces meet, re-encode instead of copying (-c:v libx264 -c:a aac in place of -c copy). The request itself, with every field, limit and price, is covered in the face swap video API guide and the edits reference; to wrap this in a product with uploads, consent and pricing, read how to build a face swap app. For several people in one shot, see multiple face swap video, and to budget a long clip, face swap API pricing for video.

FAQ

Is there face swap Python code on GitHub?

Yes: several open-source face swap projects publish Python code, and they run the models on your own machine, usually with a GPU. The script on this page is different: it is only a client, so the rendering happens on the API's side and a laptop without a GPU can run it.

Which Python version does the face swap script need?

Python 3.9 or later, with requests installed and ffmpeg on the PATH. It runs the same on macOS, Linux and Windows.

Can I swap faces in a video for free with Python?

The account, the API key, uploads and quotes cost nothing, and an edit that fails is not charged. A successful edit is paid from a prepaid balance, per second of clip: $0.12 a second at 768p.

How do I swap faces in many clips at once?

Run the script once per clip, or submit them all and let a webhook tell you as each one finishes. A workspace runs up to 20 generations at once and sends 10 uploads a minute, so queue a large batch on your side.

Why is my clip refused with invalid_video?

It misses one of the model's limits: it is too short or too long, over 64 MB, not MP4 or MOV, or not at 24 frames per second. The message says which one, nothing is charged, and the prepare function above converts the clip with ffmpeg before sending it.

Start building.

Your API key is free. Top up from $10 when you are ready.