mcpField
M
modelslab-deepfake

modelslab-deepfake

github.com/modelslab创意与媒体1384 次安装36 周前更新
代码仓库

关于 modelslab-deepfake

面向使用 ModelsLab API 的开发者,提供图像和视频换脸操作指南,支持替换指定人脸或处理多个面孔,并涵盖异步任务处理。

主要功能

  1. 01替换图像中的指定人脸
  2. 02对图像中的多张脸换脸
  3. 03处理单人或指定视频人脸
  4. 04通过轮询或 Webhook 获取结果

适用场景

  1. 01制作个人头像变化版本
  2. 02个性化视频模板内容
  3. 03编辑包含多人的图像或视频

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/modelslab/skills --skill modelslab-deepfake

安装后在 Claude Code 中输入/modelslab-deepfake确认已加载。

详细介绍

ModelsLab 深度伪造与换脸

使用先进的 AI 深度伪造技术替换图像和视频中的人脸。

适用场景

  • 替换照片中的人脸
  • 替换视频中的人脸
  • 创建个性化视频内容
  • 生成角色变体
  • 构建换脸应用
  • 创建娱乐内容

可用端点

图像换脸
  • 指定人脸换脸:POST https://modelslab.com/api/v6/deepfake/specific_face_swap
  • 多人脸换脸:POST https://modelslab.com/api/v6/deepfake/multiple_face_swap
视频换脸
  • 单个视频换脸:POST https://modelslab.com/api/v6/deepfake/single_video_swap
  • 指定人脸视频换脸:POST https://modelslab.com/api/v6/deepfake/specific_video_swap

指定人脸换脸(图像)

import requests

def swap_face(target_image, face_to_use, api_key):
    """Swap a face in an image.

    Args:
        target_image: URL of the image containing face to replace
        face_to_use: URL of the image with face to swap in
        api_key: Your ModelsLab API key

    Returns:
        URL of the face-swapped image
    """
    response = requests.post(
        "https://modelslab.com/api/v6/deepfake/specific_face_swap",
        json={
            "key": api_key,
            "init_image": target_image,
            "target_image": face_to_use
        }
    )

    data = response.json()

    if data["status"] == "success":
        return data["output"][0]
    else:
        raise Exception(f"Error: {data.get('message', 'Unknown error')}")

# Usage
result = swap_face(
    "https://example.com/target-photo.jpg",  # Photo to modify
    "https://example.com/face-to-swap.jpg",  # Face to insert
    "your_api_key"
)
print(f"Face swapped image: {result}")

多人脸换脸(图像)

def swap_multiple_faces(image_with_faces, face_to_use, api_key):
    """Swap all faces in an image with the same face.

    Args:
        image_with_faces: URL of image with multiple faces
        face_to_use: URL of face to swap in
    """
    response = requests.post(
        "https://modelslab.com/api/v6/deepfake/multiple_face_swap",
        json={
            "key": api_key,
            "init_image": image_with_faces,
            "target_image": face_to_use
        }
    )

    data = response.json()

    if data["status"] == "success":
        return data["output"][0]
    else:
        raise Exception(data.get("message"))

# Swap all faces in group photo
result = swap_multiple_faces(
    "https://example.com/group-photo.jpg",
    "https://example.com/celebrity-face.jpg",
    "your_api_key"
)

单个视频换脸

import time

def swap_video_faces(video_url, face_image, api_key, output_format="mp4"):
    """Swap all faces in a video.

    Args:
        video_url: URL of the video
        face_image: URL of face to swap in
        output_format: "mp4" or "gif"

    Returns:
        URL of the face-swapped video
    """
    response = requests.post(
        "https://modelslab.com/api/v6/deepfake/single_video_swap",
        json={
            "key": api_key,
            "init_video": video_url,
            "target_image": face_image,
            "output_format": output_format,
            "watermark": False  # Set to True for watermark
        }
    )

    data = response.json()

    if data["status"] == "error":
        raise Exception(f"Error: {data['message']}")

    if data["status"] == "success":
        return data["output"][0]

    # Video processing is async
    request_id = data["id"]
    print(f"Video processing... Request ID: {request_id}")

    return poll_deepfake_result(request_id, api_key)

def poll_deepfake_result(request_id, api_key, timeout=900):
    """Poll for video face swap results."""
    start_time = time.time()

    while time.time() - start_time < timeout:
        fetch = requests.post(
            f"https://modelslab.com/api/v6/deepfake/fetch/{request_id}",
            json={"key": api_key}
        )
        result = fetch.json()

        if result["status"] == "success":
            return result["output"][0]
        elif result["status"] == "failed":
            raise Exception(result.get("message", "Failed"))

        print(f"Processing... ({int(time.time() - start_time)}s)")
        time.sleep(10)

    raise Exception("Timeout")

# Usage
swapped_video = swap_video_faces(
    "https://example.com/video.mp4",
    "https://example.com/face.jpg",
    "your_api_key"
)
print(f"Face-swapped video: {swapped_video}")

指定人脸视频换脸

def swap_specific_video_face(video_url, new_face, reference_face, api_key):
    """Swap a specific face in a video (when multiple faces present).

    Args:
        video_url: URL of the video
        new_face: URL of the face to swap in
        reference_face: URL of the specific face to replace
    """
    response = requests.post(
        "https://modelslab.com/api/v6/deepfake/specific_video_swap",
        json={
            "key": api_key,
            "init_video": video_url,
            "target_image": new_face,
            "source_image": reference_face,
            "output_format": "mp4",
            "watermark": False
        }
    )

    data = response.json()

    if data["status"] == "processing":
        return poll_deepfake_result(data["id"], api_key)
    elif data["status"] == "success":
        return data["output"][0]
    else:
        raise Exception(data.get("message"))

# Swap only one person's face in multi-person video
result = swap_specific_video_face(
    "https://example.com/interview.mp4",
    "https://example.com/new-face.jpg",
    "https://example.com/face-to-replace.jpg",
    "your_api_key"
)

使用 Webhook

def deepfake_with_webhook(video_url, face_image, api_key, webhook_url, track_id):
    """Process video face swap with webhook notification."""
    response = requests.post(
        "https://modelslab.com/api/v6/deepfake/single_video_swap",
        json={
            "key": api_key,
            "init_video": video_url,
            "target_image": face_image,
            "output_format": "mp4",
            "webhook": webhook_url,
            "track_id": track_id
        }
    )

    data = response.json()
    print(f"Request submitted: {data['id']}")
    return data["id"]

# Usage
request_id = deepfake_with_webhook(
    "https://example.com/video.mp4",
    "https://example.com/face.jpg",
    "your_api_key",
    "https://yourserver.com/webhook/deepfake",
    "video_001"
)

关键参数

参数说明值
init_image要修改的目标图像图像 URL
init_video要修改的目标视频视频 URL
target_image要换入的人脸包含清晰人脸的图像 URL
source_image要替换的特定人脸图像 URL(用于指定人脸换脸)
output_format视频输出格式mp4 或 gif
watermark添加水印true 或 false
webhook异步回调 URL你的服务端点
track_id请求标识符唯一跟踪 ID

最佳实践

1. 使用高质量的人脸图像
✓ Good: Clear, well-lit frontal face photo
✓ Good: High resolution (at least 512x512)
✓ Good: Neutral expression works best

✗ Avoid: Blurry or low-resolution images
✗ Avoid: Extreme angles or profiles
✗ Avoid: Heavy shadows or poor lighting
2. 视频换脸要求
  • 视频中的人脸清晰可见
  • 光照条件良好
  • 正面或接近正面的角度效果最佳
  • 较短的视频处理速度更快
3. 处理异步操作
# Video face swaps are ALWAYS async
if data["status"] == "processing":
    result = poll_deepfake_result(data["id"], api_key)
4. 设置合适的超时时间
# Video processing takes time
poll_deepfake_result(request_id, api_key, timeout=900)  # 15 minutes
5. 为长视频使用 Webhook
# Don't poll for long videos, use webhooks
deepfake_with_webhook(video_url, face, api_key, webhook_url, track_id)

常见用例

头像生成器
def create_profile_variations(base_photo, face_images, api_key):
    """Generate multiple profile picture variations."""
    variations = []

    for i, face in enumerate(face_images):
        result = swap_face(base_photo, face, api_key)
        variations.append(result)
        print(f"Variation {i+1} created: {result}")

    return variations

# Create variations
profiles = create_profile_variations(
    "https://example.com/professional-photo.jpg",
    [
        "https://example.com/style1-face.jpg",
        "https://example.com/style2-face.jpg",
        "https://example.com/style3-face.jpg"
    ],
    api_key
)
视频个性化
def personalize_video(template_video, user_face, api_key):
    """Create personalized video with user's face."""
    personalized = swap_video_faces(
        template_video,
        user_face,
        api_key,
        output_format="mp4"
    )
    print(f"Personalized video: {personalized}")
    return personalized

# Create custom greeting video
greeting = personalize_video(
    "https://example.com/greeting-template.mp4",
    "https://example.com/user-photo.jpg",
    api_key
)
角色变体
def generate_character_variations(character_image, face_options, api_key):
    """Generate different character variations."""
    characters = []

    for face in face_options:
        char = swap_face(character_image, face, api_key)
        characters.append(char)

    return characters
合影编辑
# Replace one person in group photo
edited_group_photo = swap_specific_video_face(
    "https://example.com/group-video.mp4",
    "https://example.com/replacement-face.jpg",
    "https://example.com/person-to-replace.jpg",
    api_key
)

错误处理

try:
    result = swap_face(target, face, api_key)
    print(f"Face swap successful: {result}")
except Exception as e:
    print(f"Face swap failed: {e}")
    # Check image quality, try different images, or notify user

性能提示

  1. 使用 Webhook:处理视频时,始终使用 Webhook
  2. 优化人脸图像:使用清晰、高质量的人脸图像
  3. 批量处理:同时提交多个请求
  4. 缓存结果:存储生成的内容
  5. 监控处理时间:跟踪并优化处理时间

伦理考量

⚠️ 重要:请负责任地使用换脸技术

  • 使用他人的人脸前先征得同意
  • 不要制作具有误导性或有害的内容
  • 遵守当地法律法规
  • 尊重隐私和肖像权
  • 分享深度伪造内容时添加免责声明

企业 API

如需专属资源:

# Enterprise endpoints
url = "https://modelslab.com/api/v1/enterprise/deepfake/specific_face_swap"
url = "https://modelslab.com/api/v1/enterprise/deepfake/single_video_swap"

资源

相关技能

  • modelslab-video-generation - 生成视频
  • modelslab-webhooks - 处理异步操作
  • modelslab-sdk-usage - 使用官方 SDK

评论

支持 Markdown