namifusion Image/Video Face Swap

namifusion/faceswap-video

NamiFusion Video Face Swap Model Supports images and videos, easy single or multi-person face swapping. Compatible with multiple model_style options, can output realistic results or one-click beauty-enhanced versions — natural and great-looking!

Examples

namifusion Image/Video Face Swap example 1

Parameters

NameTypeDefaultConstraintsDescription
source_url *Source Faceimage_upload0–1 itemsInput face
single_face_modeSingle-face swapbooleanPerforming tasks based on single-person face swapping
model_stylemodel styleselectrealisticrealistic | beautify | losslessFace swap style. Realistic: natural look with lifelike skin tones. Beautify: smoothing and brightening enhancement. Lossless: preserves all original facial details for highest fidelity.
face_enhanceFace enhancementbooleanEnable face enhancement; enabling it will result in higher resolution faces.
face_mappingFace mappingarray<object>[]Required for multi-person face swapping. Each item maps a source face to a target face. Use the face detection API to obtain face info, then assemble into this array. `source_face_info.face_url` is the new face; `target_face_info.face_url` is the face to be replaced.
source_face_indexInput the face indexnumber≥ 0
target_face_indexIndex of the target facenumber≥ 0
source_face_infoSource Face Infoobject
target_face_infoTarget Face Infoobject

Output fields

FieldTypeDescription
videosarray<string>Face swap result video URLs

API

Call this model through one unified REST API. Get a key on the API Keys page.

cURL
# 1) Submit — returns { "task_uuid": "..." }
curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-video" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "input": {
    "source_url": [
      "https://assets-public.namifusion.com/marketplace/thumbnails/2026-01-27/d0328839a75f.png"
    ],
    "single_face_mode": true,
    "model_style": "realistic",
    "face_enhance": false,
    "face_mapping": []
  }
}'

# 2) Poll until status is "completed", then read the output URLs
curl "https://www.namifusion.com/api/v1/marketplace/run/tasks/TASK_UUID" \
  -H "Authorization: Bearer YOUR_API_KEY"
Python
import time, requests

API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# 1) Submit
resp = requests.post(
    "https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-video",
    headers=HEADERS,
    json={
        "input": {
            "source_url": [
                "https://assets-public.namifusion.com/marketplace/thumbnails/2026-01-27/d0328839a75f.png"
            ],
            "single_face_mode": True,
            "model_style": "realistic",
            "face_enhance": False,
            "face_mapping": []
        }
    },
)
resp.raise_for_status()  # 401/402/429/5xx stop here instead of polling a bad task
task = resp.json()

# 2) Poll until a terminal state (completed / failed / cancelled).
#    This model is allowed up to 1800s server-side.
deadline = time.time() + 1860
while task.get("status") not in ("completed", "failed", "cancelled"):
    if time.time() > deadline:
        raise TimeoutError(f"still {task.get('status')} — keep the task_uuid and poll later")
    time.sleep(3)
    poll = requests.get(f"https://www.namifusion.com/api/v1/marketplace/run/tasks/{task['task_uuid']}", headers=HEADERS)
    poll.raise_for_status()
    task = poll.json()

print(task["status"], task.get("output"))
JavaScript
const API_KEY = "YOUR_API_KEY";
const HEADERS = { Authorization: `Bearer ${API_KEY}` };

// 1) Submit
const resp = await fetch("https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-video", {
  method: "POST",
  headers: { ...HEADERS, "Content-Type": "application/json" },
  body: JSON.stringify({
    "input": {
      "source_url": [
        "https://assets-public.namifusion.com/marketplace/thumbnails/2026-01-27/d0328839a75f.png"
      ],
      "single_face_mode": true,
      "model_style": "realistic",
      "face_enhance": false,
      "face_mapping": []
    }
  }),
});
if (!resp.ok) throw new Error(`submit failed: ${resp.status} ${await resp.text()}`);
let task = await resp.json();

// 2) Poll until a terminal state (completed / failed / cancelled).
//    This model is allowed up to 1800s server-side.
const deadline = Date.now() + 1860 * 1000;
while (!["completed", "failed", "cancelled"].includes(task.status)) {
  if (Date.now() > deadline) throw new Error(`still ${task.status} — keep the task_uuid and poll later`);
  await new Promise((r) => setTimeout(r, 3000));
  const poll = await fetch(`https://www.namifusion.com/api/v1/marketplace/run/tasks/${task.task_uuid}`, { headers: HEADERS });
  if (!poll.ok) throw new Error(`poll failed: ${poll.status}`);
  task = await poll.json();
}

console.log(task.status, task.output);

Documentation

NamiFusion Video FaceSwap

AI Video Face Swap: Supports single-person automatic face swap and multi-person precise mapping, combined with face detection for a complete video face swap workflow.

NamiFusion Video FaceSwap is a high-quality AI video face swap service that replaces source faces onto target videos. It offers two modes: single-person face swap (automatic mode) and multi-person face swap (precise mapping mode), and can be combined with NamiFusion Detect Faces to achieve a complete workflow from face detection to face swapping.


Key Features

  • Single-Person Face Swap: Enable single_face_mode to automatically complete the face swap without any additional configuration.
  • Multi-Person Precise Mapping: Use face_mapping to precisely specify the correspondence between source faces and target faces, supporting one-to-one and many-to-many mappings.
  • Face Enhancement: Optional advanced beautification that automatically smooths skin and removes facial blemishes, improving post-swap face quality.
  • Async Tasks: Returns a task_uuid after submission; retrieve results via polling or Webhook.

Technical Specifications

ParameterDetails
Model IDnamifusion/faceswap-video
Request MethodAsync POST (submit task + poll/Webhook for results)
InputSource face image URL + target video URL
OutputFace-swapped video URL
Processing TimeTypically 30 seconds to several minutes (depends on video duration and resolution)

Quick Start

API Endpoints

EndpointMethodDescription
/api/v1/marketplace/run/namifusion/faceswap-videoPOSTSubmit a video face swap task
/api/v1/marketplace/run/tasks/{task_uuid}GETQuery task status and results

Authentication

Include your API Key in the request header:

X-API-Key: sk-your-api-key

Scenario 1: Single-Person Face Swap (Simplest Usage)

Suitable for scenarios where the source image and target video both contain only one face. With single_face_mode enabled, no face_mapping configuration is needed, and the service will automatically complete the face swap.

Step 1: Submit Face Swap Task

curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-video" \
  -H "X-API-Key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "source_url": "https://example.com/source_face.jpg",
      "target_url": "https://example.com/target_video.mp4",
      "single_face_mode": true
    }
  }'

Response Example:

{
  "task_uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "status": "pending",
  "cost_credits": 50
}

Step 2: Poll Task Status

curl -X GET "https://www.namifusion.com/api/v1/marketplace/run/tasks/a1b2c3d4-e5f6-7890-abcd-ef1234567890" \
  -H "X-API-Key: sk-your-api-key"

Processing:

{
  "task_uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "status": "processing"
}

Completed:

{
  "task_uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "model_id": "namifusion/faceswap-video",
  "status": "completed",
  "output": {
    "videos": ["https://cdn.namifusion.com/result/faceswap_abc123.mp4"]
  },
  "cost_credits": 50,
  "created_at": "2026-02-27T10:00:00Z",
  "completed_at": "2026-02-27T10:01:30Z"
}

Scenario 2: Multi-Person Face Swap

When the target video contains multiple faces and you need precise control over "which source face replaces which target face", you need to first call Detect Faces to detect faces from the video, then build face_mapping to submit the face swap task.

Step 1: Detect Faces in the Target Video

Call NamiFusion Detect Faces (POST /api/v1/marketplace/run/namifusion/detect_faces) to detect faces directly from the video, then poll for results.

Submit Detection Task:

curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/detect_faces" \
  -H "X-API-Key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "url": "https://example.com/target_video.mp4",
      "num_frames": 3,
      "return_face_url": true,
      "deduplicate": true
    }
  }'

Poll Task Result:

curl -X GET "https://www.namifusion.com/api/v1/marketplace/run/tasks/{task_uuid}" \
  -H "X-API-Key: sk-your-api-key"

Completed Response (assuming 2 persons detected):

{
  "task_uuid": "...",
  "status": "completed",
  "output": {
    "error_code": 0,
    "error_msg": "SUCCESS",
    "faces_obj": {
      "0": {
        "region": [[50, 80, 150, 200], [250, 70, 350, 190]],
        "face_urls": [
          "https://s3.amazonaws.com/faces/target_face_0.jpg",
          "https://s3.amazonaws.com/faces/target_face_1.jpg"
        ],
        "landmarks": [[[...]], [[...]]],
        "frame_time": null,
        "crop_region": [[...], [...]],
        "landmarks_str": ["...", "..."],
        "crop_landmarks": ["...", "..."]
      },
      "1": {
        "region": [],
        "face_urls": [],
        "landmarks": [],
        "frame_time": 1.0,
        "crop_region": [],
        "landmarks_str": [],
        "crop_landmarks": []
      },
      "2": {
        "region": [],
        "face_urls": [],
        "landmarks": [],
        "frame_time": 2.0,
        "crop_region": [],
        "landmarks_str": [],
        "crop_landmarks": []
      }
    }
  }
}

Now you know the target video has 2 persons (faces_obj["0"].region length is 2) and their face_urls.

Step 2: Detect Source Face Image

Similarly, call Detect Faces to submit a detection task and poll for results (if you have multiple source face images or need to pass precise face coordinate information).

Submit Detection Task:

curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/detect_faces" \
  -H "X-API-Key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "url": "https://example.com/source_face.jpg",
      "return_face_url": true
    }
  }'

Completed Response:

{
  "task_uuid": "...",
  "status": "completed",
  "output": {
    "error_code": 0,
    "error_msg": "SUCCESS",
    "faces_obj": {
      "0": {
        "region": [[100, 50, 200, 180]],
        "face_urls": ["https://s3.amazonaws.com/faces/source_face_0.jpg"],
        "landmarks": [[[...]]],
        "frame_time": null,
        "crop_region": [[...]],
        "landmarks_str": ["..."],
        "crop_landmarks": ["..."]
      }
    }
  }
}

Step 3: Build face_mapping

Based on the detection results, build the mapping from source faces to target faces.

Use the face_urls returned by Detect Faces as source_face_info.face_url and target_face_info.face_url in face_mapping:

"face_mapping": [
  {
    "source_face_info": {
      "face_url": "https://s3.amazonaws.com/faces/source_face_0.jpg"
    },
    "target_face_info": {
      "face_url": "https://s3.amazonaws.com/faces/target_face_0.jpg"
    }
  }
]

The face_url values are taken directly from the output.faces_obj["0"].face_urls[i] returned by Detect Faces in Steps 1 and 2.

face_mapping also supports source_face_index, target_face_index, bbox, and other parameters. See the "face_mapping Details" section below.

Step 4: Submit Multi-Person Face Swap Task

curl -X POST "https://www.namifusion.com/api/v1/marketplace/run/namifusion/faceswap-video" \
  -H "X-API-Key: sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "source_url": "https://example.com/source_face.jpg",
      "target_url": "https://example.com/target_video.mp4",
      "single_face_mode": false,
      "face_mapping": [
        {
          "source_face_info": {
            "face_url": "https://s3.amazonaws.com/faces/source_face_0.jpg"
          },
          "target_face_info": {
            "face_url": "https://s3.amazonaws.com/faces/target_face_0.jpg"
          }
        }
      ]
    }
  }'

Response:

{
  "task_uuid": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
  "status": "pending",
  "cost_credits": 50
}

Step 5: Get Face Swap Result

Poll the task status until status becomes completed:

curl -X GET "https://www.namifusion.com/api/v1/marketplace/run/tasks/b2c3d4e5-f6a7-8901-bcde-f12345678901" \
  -H "X-API-Key: sk-your-api-key"

Completed Response:

{
  "task_uuid": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
  "model_id": "namifusion/faceswap-video",
  "status": "completed",
  "output": {
    "videos": ["https://cdn.namifusion.com/result/faceswap_def456.mp4"]
  },
  "cost_credits": 50,
  "created_at": "2026-02-27T10:05:00Z",
  "completed_at": "2026-02-27T10:07:30Z"
}

Python Full Example: Multi-Person Video Face Swap Workflow

The following example demonstrates the complete workflow from face detection to multi-person video face swap:

import requests
import time

API_KEY = "sk-your-api-key"
BASE_URL = "https://www.namifusion.com/api/v1/marketplace/run"
HEADERS = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json",
}

source_url = "https://example.com/source_face.jpg"
target_url = "https://example.com/target_video.mp4"


def detect_faces(media_url, num_frames=None):
    """Submit face detection task and poll for result."""
    input_params = {"url": media_url, "return_face_url": True}
    if num_frames:
        input_params["num_frames"] = num_frames
    task = requests.post(
        f"{BASE_URL}/namifusion/detect_faces",
        headers=HEADERS,
        json={"input": input_params},
    ).json()

    while True:
        resp = requests.get(
            f"{BASE_URL}/tasks/{task['task_uuid']}",
            headers=HEADERS,
        ).json()

        if resp["status"] == "completed":
            return resp["output"]
        elif resp["status"] == "failed":
            raise Exception(resp.get("error_message", "Unknown error"))

        time.sleep(3)


# Step 1: detect faces in target video
target_detect = detect_faces(target_url, num_frames=3)
target_frame = target_detect["faces_obj"]["0"]

print(f"Target has {len(target_frame['face_urls'])} faces")
for i, face_url in enumerate(target_frame["face_urls"]):
    print(f"  Face {i}: region={target_frame['region'][i]}")

# Step 2: detect faces in source image
source_detect = detect_faces(source_url)
source_frame = source_detect["faces_obj"]["0"]

# Step 3: build face_mapping (replace target face 0 with source face 0)
face_mapping = [
    {
        "source_face_info": {"face_url": source_frame["face_urls"][0]},
        "target_face_info": {"face_url": target_frame["face_urls"][0]},
    }
]

# Step 4: submit video faceswap task
task_resp = requests.post(
    f"{BASE_URL}/namifusion/faceswap-video",
    headers=HEADERS,
    json={
        "input": {
            "source_url": source_url,
            "target_url": target_url,
            "single_face_mode": False,
            "face_mapping": face_mapping,
        }
    },
).json()

task_uuid = task_resp["task_uuid"]
print(f"Task submitted: {task_uuid}")

# Step 5: poll for result
while True:
    status_resp = requests.get(
        f"{BASE_URL}/tasks/{task_uuid}",
        headers=HEADERS,
    ).json()

    status = status_resp["status"]
    print(f"Status: {status}")

    if status == "completed":
        result_url = status_resp["output"]["videos"][0]
        print(f"Result: {result_url}")
        break
    elif status == "failed":
        print(f"Failed: {status_resp.get('error_message', 'Unknown error')}")
        break

    time.sleep(10)

Parameter and Response Details

Request Parameters

The request body is in JSON format, with all parameters inside the input object:

{
  "input": {
    "source_url": "https://...",
    "target_url": "https://...",
    "single_face_mode": true,
    "face_enhance": false,
    "face_mapping": [],
    "model_style": "realistic"
  }
}
ParameterTypeRequiredDefaultDescription
source_urlstringYes-Source face image URL (the face to swap onto the target). Must be publicly accessible.
target_urlstringYes-Target video URL (the video to be face-swapped). Must be publicly accessible.
single_face_modebooleanNotrueSingle face mode. When enabled, face swap is completed automatically without configuring face_mapping.
face_enhancebooleanNofalseWhether to enable face enhancement. When enabled, automatically smooths skin and removes facial blemishes for higher face quality, but increases processing time.
face_mappingarrayNonullFace mapping configuration. Only effective when single_face_mode: false. See details below.
model_stylestringNo"realistic"Face swap style. Options: "realistic", "beautify", "lossless". See the "Impact of Parameters on Output" section.

face_mapping Details

face_mapping is an array where each element defines a mapping from a source face to a target face:

FieldTypeRequiredDescription
source_face_indexintegerYesIndex of the face in the source image (0-based, sorted left to right).
target_face_indexintegerYesIndex of the face in the target video (0-based, sorted left to right).
source_face_infoobjectNoCoordinate information of the source face. When provided, skips internal re-detection to ensure consistent face ordering.
target_face_infoobjectNoCoordinate information of the target face. When provided, improves matching accuracy.

source_face_info Fields

FieldTypeDescription
bboxnumber[]Face bounding box [x1, y1, x2, y2].
kpsnumber[][]5 facial keypoint coordinates. When provided, the backend uses them directly, skipping re-detection.

target_face_info Fields

FieldTypeDescription
bboxnumber[]Target face bounding box [x1, y1, x2, y2].

Task Status

After submitting a task, poll for status. Recommended polling interval: 10 seconds.

StatusDescription
pendingTask created, waiting to be processed.
processingTask is being processed.
completedTask completed. Retrieve result URL from output.videos.
failedTask failed. Check error_message for the reason.

Response Structure

Task Submission Response

FieldTypeDescription
task_uuidstringUnique task identifier for subsequent status queries.
statusstringInitial status, typically pending.
cost_creditsnumberCredits consumed by this task.

Task Completion Response

FieldTypeDescription
task_uuidstringUnique task identifier.
model_idstringModel ID (namifusion/faceswap-video).
statusstringTask status.
output.videosstring[]List of face-swapped result video URLs.
cost_creditsnumberCredits consumed.
created_atstringTask creation time (ISO 8601).
completed_atstringTask completion time (ISO 8601).
error_messagestringError message (only returned when failed).

Impact of Parameters on Output

ParameterImpact on Result
single_face_mode: trueAutomatically completes face swap, suitable for single-person scenarios without configuring face_mapping.
single_face_mode: false + face_mappingPrecisely controls which faces to replace. Faces not specified in the mapping remain unchanged.
face_enhance: trueEnables face enhancement, automatically smoothing skin and removing blemishes for a more refined and natural look, but increases processing time by ~20-50%.
face_enhance: falseDefault mode, no additional face processing, faster processing speed.
model_style: "realistic"Realistic style. Produces a natural look close to real faces, preserving lifelike skin tones and textures.
model_style: "beautify"Beautify style. Automatic skin smoothing and brightening for a refined, smooth appearance.
model_style: "lossless"Lossless style. Ultimate lossless mode that perfectly preserves all original facial details with the highest realism, nearly indistinguishable.

Notes

  1. URLs must be publicly accessible: Both source_url and target_url must be publicly downloadable URLs.
  2. Face index sorting rule: Both source_face_index and target_face_index start from 0, sorted left to right by the x-coordinate of the face bbox's top-left corner.
  3. Strongly recommended to pass face_info: If you have already called Detect Faces, passing the detected bbox into face_mapping can avoid index inconsistency issues caused by internal re-detection in the face swap service.
  4. Polling interval: Recommended to poll task status every 10 seconds. Video face swap typically completes in 30 seconds to several minutes, depending on video duration and resolution.
  5. Result field name: The output field is named output.videos, returning the face-swapped video URL.
namifusion Image/Video Face Swap API — Pricing, Playground & Docs | NamiFusion