Download modal_multitalk.py from vincentkr18/multitalk-inf-v2: direct link, hf CLI and curl.
- Browser
- Download file 36.8 kB
-
https://huggingface.co/vincentkr18/multitalk-inf-v2/resolve/main/modal_multitalk.py
- Command line
-
hf download hf://vincentkr18/multitalk-inf-v2/modal_multitalk.py
-
curl -L -o modal_multitalk.py https://huggingface.co/vincentkr18/multitalk-inf-v2/resolve/main/modal_multitalk.py
36.8 kB
import modal
import os
import json
import base64
import tempfile
import subprocess
import time
import logging
import sys
import warnings
from pathlib import Path
from typing import Optional, Dict, Any, Union
from datetime import datetime
from types import SimpleNamespace
from io import BytesIO
import requests
import random
# Suppress warnings for cleaner output
warnings.filterwarnings("ignore")
# Modal setup
app = modal.App(name="multitalk-inference")
# Create volume for model weights
volume = modal.Volume.from_name("multitalk-models", create_if_missing=True)
MODEL_DIR = Path("/vol/models")
# Define the container image with all dependencies
image = (
modal.Image.debian_slim(python_version="3.10")
.apt_install(
"ffmpeg",
"libgl1-mesa-glx",
"libglib2.0-0",
"libsm6",
"libxext6",
"libxrender-dev",
"libgomp1",
"git",
"wget",
"curl",
)
.pip_install(
# "torch>=2.0.0",
# "torchvision",
# "torchaudio",
# "numpy<2.0.0",
# "transformers",
# "easydict",
# "accelerate",
# "diffusers",
# "huggingface-hub[hf_transfer]",
# "fastapi[standard]",
# "pydantic",
# "Pillow",
# "soundfile",
# "librosa",
# "pyloudnorm",
# "einops",
# "scipy",
# "imageio",
# "imageio-ffmpeg",
# "python-multipart",
# "omegaconf",
# "requests",
# "tqdm",
# "pydantic",
"torch>=2.4.0",
"torchvision>=0.19.0",
"torchaudio>=2.4.0",
"numpy>=1.23.5,<2.0.0",
"transformers>=4.49.0",
"tokenizers>=0.20.3",
"diffusers>=0.31.0",
"accelerate>=1.1.1",
"huggingface-hub>=0.19.0",
"easydict",
"gradio>=5.0.0",
"opencv-python>=4.9.0.80",
"soundfile>=0.12.1",
"librosa>=0.10.0",
"pyloudnorm",
"einops>=0.8.0",
"tqdm",
"imageio",
"imageio-ffmpeg",
"xfuser>=0.4.1",
"xformers>=0.0.28",
"safetensors>=0.3.1",
"dashscope",
"packaging",
"pydantic",
"python-multipart",
"omegaconf",
"requests",
"fastapi[standard]",
"Pillow",
"ftfy", # β
Added missing module
"hf_transfer",
)
.env(
{
"HF_HUB_ENABLE_HF_TRANSFER": "1",
"FFMPEG_PATH": "/usr/bin/ffmpeg",
}
)
.run_commands(
# Install MultiTalk dependencies
"apt-get update && apt-get install -y git ffmpeg",
"pip install --no-cache-dir -U openmim",
"mim install mmengine",
"mim install 'mmcv==2.1.0'",
"mim install 'mmdet>=3.1.0'",
"mim install 'mmpose>=1.1.0'",
)
.copy_local_dir("./src", "/root/src")
.copy_local_dir("./wan", "/root/wan")
.add_local_python_source("wan")
)
# Download image for model setup
download_image = (
modal.Image.debian_slim()
.pip_install(
"huggingface_hub[hf_transfer]",
"requests",
"tqdm",
"pydantic",
"torch",
"hf_transfer",
)
.env({"HF_HUB_ENABLE_HF_TRANSFER": "1"})
)
from pydantic import BaseModel
# Request models
class MultiTalkRequest(BaseModel):
image: str # base64 encoded image
first_audio: str # base64 encoded audio
prompt: str = (
"A smiling man and woman wearing headphones sit in front of microphones, appearing to host a podcast."
)
second_audio: Optional[str] = None # base64 encoded audio (optional)
num_frames: int = 81
sampling_steps: int = 40
seed: Optional[int] = None
turbo: bool = True
class MultiTalkResponse(BaseModel):
video: str # base64 encoded video
metadata: Dict[str, Any]
class ModelStatus(BaseModel):
models: Dict[str, bool]
total_size_gb: float
status: str
# Utility functions
def loudness_norm(audio_array, sr=16000, lufs=-23):
"""Normalize audio loudness"""
try:
import pyloudnorm as pyln
meter = pyln.Meter(sr)
loudness = meter.integrated_loudness(audio_array)
if abs(loudness) > 100:
return audio_array
normalized_audio = pyln.normalize.loudness(audio_array, loudness, lufs)
return normalized_audio
except Exception as e:
print(f"Warning: Could not normalize audio: {e}")
return audio_array
def extract_audio_from_video(filename, sample_rate=16000):
"""Extract audio from video file with robust error handling"""
raw_audio_path = f"{os.path.splitext(os.path.basename(filename))[0]}.wav"
ffmpeg_command = [
"ffmpeg",
"-y",
"-i",
str(filename),
"-vn",
"-acodec",
"pcm_s16le",
"-ar",
str(sample_rate),
"-ac",
"2",
raw_audio_path,
]
subprocess.run(ffmpeg_command, check=True, capture_output=True)
import librosa
human_speech_array, sr = librosa.load(raw_audio_path, sr=sample_rate)
human_speech_array = loudness_norm(human_speech_array, sr)
os.remove(raw_audio_path)
return human_speech_array
def audio_prepare_single(audio_path, sample_rate=16000):
"""Prepare single audio file"""
import librosa
ext = os.path.splitext(audio_path)[1].lower()
if ext in [".mp4", ".mov", ".avi", ".mkv"]:
human_speech_array = extract_audio_from_video(audio_path, sample_rate)
return human_speech_array
else:
human_speech_array, sr = librosa.load(audio_path, sr=sample_rate)
human_speech_array = loudness_norm(human_speech_array, sr)
return human_speech_array
def audio_prepare_multi(left_path, right_path, audio_type, sample_rate=16000):
"""Prepare multi-person audio"""
human_speech_array1 = audio_prepare_single(left_path)
human_speech_array2 = audio_prepare_single(right_path)
if audio_type == "para":
new_human_speech1 = human_speech_array1
new_human_speech2 = human_speech_array2
elif audio_type == "add":
new_human_speech1 = np.concatenate(
[
human_speech_array1[: human_speech_array1.shape[0]],
np.zeros(human_speech_array2.shape[0]),
]
)
new_human_speech2 = np.concatenate(
[
np.zeros(human_speech_array1.shape[0]),
human_speech_array2[: human_speech_array2.shape[0]],
]
)
sum_human_speechs = new_human_speech1 + new_human_speech2
return new_human_speech1, new_human_speech2, sum_human_speechs
def get_embedding(
speech_array, wav2vec_feature_extractor, audio_encoder, sr=16000, device="cpu"
):
"""Extract audio embeddings optimized for GPU processing"""
from einops import rearrange
import numpy as np
import torch
audio_duration = len(speech_array) / sr
video_length = audio_duration * 25 # Assume the video fps is 25
# Extract audio features
audio_feature = np.squeeze(
wav2vec_feature_extractor(speech_array, sampling_rate=sr).input_values
)
audio_feature = torch.from_numpy(audio_feature).float().to(device=device)
audio_feature = audio_feature.unsqueeze(0)
# Generate embeddings on appropriate device
with torch.no_grad():
embeddings = audio_encoder(
audio_feature, seq_len=int(video_length), output_hidden_states=True
)
if len(embeddings) == 0:
print("β οΈ Failed to extract audio embedding")
return None
audio_emb = torch.stack(embeddings.hidden_states[1:], dim=1).squeeze(0)
audio_emb = rearrange(audio_emb, "b s d -> s b d")
# Keep on CPU for compatibility with downstream processing
audio_emb = audio_emb.cpu().detach()
return audio_emb
def download_with_resume(
url: str, dest: str, max_retries: int = 3, chunk_size: int = 8192 * 1024
) -> None:
"""Download file with resume capability and robust error handling."""
print(f"[!] Downloading from: {url}")
print(f"[~] Destination: {dest}")
# Create destination directory if it doesn't exist
os.makedirs(os.path.dirname(dest), exist_ok=True)
# Get initial file size if resuming
initial_size = 0
if os.path.exists(dest):
initial_size = os.path.getsize(dest)
print(f"[~] Resuming download from {initial_size} bytes")
for attempt in range(max_retries):
try:
# Set up headers for resume
headers = {}
if initial_size > 0:
headers["Range"] = f"bytes={initial_size}-"
# Start download with streaming
response = requests.get(url, headers=headers, stream=True)
response.raise_for_status()
# Get total file size
total_size = initial_size
if "content-length" in response.headers:
total_size = initial_size + int(response.headers["content-length"])
elif "content-range" in response.headers:
content_range = response.headers["content-range"]
if "/" in content_range:
total_size = int(content_range.split("/")[-1])
print(f"[~] Total size: {total_size / (1024**3):.2f} GB")
# Download with progress tracking
start_time = time.time()
last_progress_time = start_time
mode = "ab" if initial_size > 0 else "wb"
with open(dest, mode) as f:
downloaded = initial_size
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
downloaded += len(chunk)
# Progress update every 10 seconds
current_time = time.time()
if current_time - last_progress_time >= 10:
if total_size > 0:
progress = (downloaded / total_size) * 100
speed = (
downloaded / (current_time - start_time) / (1024**2)
)
print(
f"[~] Progress: {progress:.1f}% ({downloaded/(1024**3):.2f}/{total_size/(1024**3):.2f} GB) - Speed: {speed:.1f} MB/s"
)
last_progress_time = current_time
# Verify download completed successfully
final_size = os.path.getsize(dest)
if total_size > 0 and final_size < total_size:
print(f"[!] Download incomplete: {final_size}/{total_size} bytes")
initial_size = final_size
continue
elapsed_time = time.time() - start_time
print(f"[+] Download completed in {elapsed_time:.2f} seconds")
print(f"[+] Final size: {final_size / (1024**3):.2f} GB")
return
except requests.exceptions.RequestException as e:
print(f"[!] Download attempt {attempt + 1} failed: {str(e)}")
if attempt < max_retries - 1:
print(f"[~] Retrying in 5 seconds...")
time.sleep(5)
initial_size = os.path.getsize(dest) if os.path.exists(dest) else 0
else:
print(f"[ERROR] Failed to download after {max_retries} attempts")
raise
except Exception as e:
print(f"[ERROR] Unexpected error during download: {str(e)}")
raise
def extract_tar_file(tar_path: str, extract_dir: str) -> None:
"""Extract tar file with error handling"""
print(f"[~] Extracting {tar_path} to {extract_dir}")
try:
import tarfile
with tarfile.open(tar_path, "r") as tar:
tar.extractall(path=extract_dir)
print(f"[+] Extraction completed")
# Remove tar file to save space
os.remove(tar_path)
print(f"[+] Cleaned up {tar_path}")
except Exception as e:
print(f"[ERROR] Failed to extract {tar_path}: {str(e)}")
raise
def download_weights(url: str, dest: str) -> None:
"""Download and extract model weights with robust error handling."""
start_time = time.time()
try:
# Determine if this is a tar file that needs extraction
is_tar = dest.endswith(".tar")
extract_dir = dest.replace(".tar", "") if is_tar else dest
# Skip if already extracted
if is_tar and os.path.exists(extract_dir) and os.path.isdir(extract_dir):
print(f"[~] Model already exists at {extract_dir}, skipping download")
return
# Download the file
download_with_resume(url, dest)
# Extract if it's a tar file
if is_tar:
extract_tar_file(dest, os.path.dirname(dest))
total_time = time.time() - start_time
print(f"[+] Model setup completed in {total_time:.2f} seconds")
except Exception as e:
print(f"[ERROR] Failed to download weights from {url}: {str(e)}")
if os.path.exists(dest):
os.remove(dest)
raise
def decode_base64_file(base64_string: str, output_path: str) -> str:
"""Decode base64 string and save to file"""
try:
# Remove data URL prefix if present
if "," in base64_string:
base64_string = base64_string.split(",")[1]
# Decode and save
with open(output_path, "wb") as f:
f.write(base64.b64decode(base64_string))
return output_path
except Exception as e:
raise ValueError(f"Failed to decode base64 file: {str(e)}")
def encode_file_to_base64(file_path: str) -> str:
"""Encode file to base64 string"""
try:
with open(file_path, "rb") as f:
return base64.b64encode(f.read()).decode("utf-8")
except Exception as e:
raise ValueError(f"Failed to encode file to base64: {str(e)}")
# Check if models exist
@app.function(
volumes={MODEL_DIR.as_posix(): volume},
image=download_image,
timeout=60,
)
def check_models_exist():
"""Check if required models exist in the volume."""
models = {
"chinese-wav2vec2-base": MODEL_DIR / "chinese-wav2vec2-base",
"MeiGen-MultiTalk": MODEL_DIR / "MeiGen-MultiTalk",
"Wan2.1-I2V-14B-480P": MODEL_DIR / "Wan2.1-I2V-14B-480P",
}
status = {}
total_size = 0
for model_name, model_path in models.items():
exists = model_path.exists() and model_path.is_dir()
status[model_name] = exists
if exists:
# Calculate directory size
size = sum(f.stat().st_size for f in model_path.rglob("*") if f.is_file())
total_size += size
return {
"models": status,
"total_size_gb": total_size / (1024**3),
"all_present": all(status.values()),
}
@app.function(
volumes={MODEL_DIR.as_posix(): volume},
image=download_image,
timeout=3600,
gpu="A100",
)
def download_models():
"""Download missing models from Hugging Face using the API."""
from huggingface_hub import snapshot_download
import os
import torch
MODEL_CACHE = MODEL_DIR.as_posix()
os.makedirs(MODEL_CACHE, exist_ok=True)
os.environ["HF_HOME"] = MODEL_CACHE
os.environ["TORCH_HOME"] = MODEL_CACHE
os.environ["HF_DATASETS_CACHE"] = MODEL_CACHE
os.environ["TRANSFORMERS_CACHE"] = MODEL_CACHE
os.environ["HUGGINGFACE_HUB_CACHE"] = MODEL_CACHE
model_repos = {
"Wan2.1-I2V-14B-480P": "Wan-AI/Wan2.1-I2V-14B-480P",
"chinese-wav2vec2-base": "TencentGameMate/chinese-wav2vec2-base",
"MeiGen-MultiTalk": "MeiGen-AI/MeiGen-MultiTalk",
"Kokoro-82M": "hexgrad/Kokoro-82M",
}
print("[~] Starting model downloads using huggingface_hub...")
try:
for folder, repo_id in model_repos.items():
dest_dir = os.path.join(MODEL_CACHE, folder)
print(f"[~] Downloading {repo_id} to {dest_dir}...")
snapshot_download(
repo_id=repo_id,
local_dir=dest_dir,
local_dir_use_symlinks=False,
resume_download=True,
)
print("[+] All models downloaded successfully!")
volume.commit()
return True
except Exception as e:
print(f"[ERROR] Failed to download models: {str(e)}")
return False
# MultiTalk inference class
class MultiTalkInference:
def __init__(self):
"""Initialize the MultiTalk inference pipeline"""
import torch
import os
import sys
self.MODEL_CACHE = MODEL_DIR.as_posix()
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"Using device: {self.device}")
# Model paths
self.ckpt_dir = os.path.join(self.MODEL_CACHE, "Wan2.1-I2V-14B-480P")
self.wav2vec_dir = os.path.join(self.MODEL_CACHE, "chinese-wav2vec2-base")
self.multitalk_dir = os.path.join(self.MODEL_CACHE, "MeiGen-MultiTalk")
# Load models
self._load_models()
def _load_models(self):
"""Load all required models"""
# Add MultiTalk to path
sys.path.append("/opt/multitalk")
# Import MultiTalk components
import wan
from wan.configs import WAN_CONFIGS
from transformers import Wav2Vec2FeatureExtractor
from src.audio_analysis.wav2vec2 import Wav2Vec2Model
import torch
# Load wav2vec models
print("Loading wav2vec models...")
audio_device = self.device if torch.cuda.is_available() else "cpu"
print(f"Loading audio encoder on: {audio_device}")
self.audio_encoder = Wav2Vec2Model.from_pretrained(
self.wav2vec_dir, local_files_only=True, attn_implementation="eager"
).to(audio_device)
self.audio_encoder.feature_extractor._freeze_parameters()
self.wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
self.wav2vec_dir, local_files_only=True
)
self.audio_device = audio_device
# Load MultiTalk pipeline
print("Loading MultiTalk pipeline...")
self.cfg = WAN_CONFIGS["multitalk-14B"]
self.wan_i2v = wan.MultiTalkPipeline(
config=self.cfg,
checkpoint_dir=self.ckpt_dir,
device_id=0,
rank=0,
t5_fsdp=False,
dit_fsdp=False,
use_usp=False,
t5_cpu=False,
)
# GPU optimizations
if torch.cuda.is_available():
vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)
print(f"π Detected {vram_gb:.1f}GB VRAM")
if vram_gb > 40:
print(
"π High-VRAM detected: Enabling maximum performance optimizations"
)
torch.backends.cuda.enable_flash_sdp(True)
torch.backends.cudnn.benchmark = True
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.cuda.empty_cache()
else:
print("π§ Standard GPU optimizations enabled")
torch.backends.cuda.enable_flash_sdp(True)
torch.cuda.empty_cache()
print("β
Model setup completed successfully!")
def generate_video(self, request: MultiTalkRequest) -> MultiTalkResponse:
"""Generate video from the request"""
import torch
import soundfile as sf
import os
try:
# Import required modules
from wan.utils.multitalk_utils import save_video_ffmpeg
# Validate and process parameters
num_frames = request.num_frames
original_frames = num_frames
# Auto-correct frame count to nearest valid value (4n+1 format)
if (num_frames - 1) % 4 != 0:
n_lower = (num_frames - 1) // 4
n_upper = n_lower + 1
frames_lower = 4 * n_lower + 1
frames_upper = 4 * n_upper + 1
if abs(num_frames - frames_lower) <= abs(num_frames - frames_upper):
num_frames = frames_lower
else:
num_frames = frames_upper
num_frames = max(25, min(num_frames, 201))
while (num_frames - 1) % 4 != 0 and num_frames <= 201:
num_frames += 1
print(
f"π Auto-corrected num_frames from {original_frames} to {num_frames}"
)
# Set random seed
seed = (
request.seed
if request.seed is not None
else random.randint(0, 99999999)
)
print(f"π¬ Generating video with seed: {seed}")
with tempfile.TemporaryDirectory() as temp_dir:
# Save input files from base64
image_path = os.path.join(temp_dir, "input_image.jpg")
first_audio_path = os.path.join(temp_dir, "first_audio.wav")
decode_base64_file(request.image, image_path)
decode_base64_file(request.first_audio, first_audio_path)
second_audio_path = None
if request.second_audio:
second_audio_path = os.path.join(temp_dir, "second_audio.wav")
decode_base64_file(request.second_audio, second_audio_path)
is_multi_person = second_audio_path is not None
audio_save_dir = os.path.join(temp_dir, "audio_embeddings")
os.makedirs(audio_save_dir, exist_ok=True)
# Process audio and generate embeddings
if is_multi_person:
print("π€ Processing multi-person audio...")
audio_type = "add"
speech1, speech2, combined_speech = audio_prepare_multi(
first_audio_path, second_audio_path, audio_type
)
embedding1 = get_embedding(
speech1,
self.wav2vec_feature_extractor,
self.audio_encoder,
device=self.audio_device,
)
embedding2 = get_embedding(
speech2,
self.wav2vec_feature_extractor,
self.audio_encoder,
device=self.audio_device,
)
emb1_path = os.path.join(audio_save_dir, "1.pt")
emb2_path = os.path.join(audio_save_dir, "2.pt")
sum_audio_path = os.path.join(audio_save_dir, "sum.wav")
torch.save(embedding1, emb1_path)
torch.save(embedding2, emb2_path)
sf.write(sum_audio_path, combined_speech, 16000)
input_data = {
"prompt": request.prompt,
"cond_image": image_path,
"audio_type": audio_type,
"cond_audio": {"person1": emb1_path, "person2": emb2_path},
"video_audio": sum_audio_path,
}
else:
print("π€ Processing single-person audio...")
speech = audio_prepare_single(first_audio_path)
embedding = get_embedding(
speech,
self.wav2vec_feature_extractor,
self.audio_encoder,
device=self.audio_device,
)
emb_path = os.path.join(audio_save_dir, "1.pt")
sum_audio_path = os.path.join(audio_save_dir, "sum.wav")
torch.save(embedding, emb_path)
sf.write(sum_audio_path, speech, 16000)
input_data = {
"prompt": request.prompt,
"cond_image": image_path,
"cond_audio": {"person1": emb_path},
"video_audio": sum_audio_path,
}
print("π¬ Generating video...")
# Configure generation parameters
high_vram = (
torch.cuda.is_available()
and torch.cuda.get_device_properties(0).total_memory > 40 * 1024**3
)
if request.turbo:
teacache_thresh = 0.8
text_guide_scale = 3.0
audio_guide_scale = 3.0
shift = 5.0
offload_model = False
print(f"π TURBO MODE: {request.sampling_steps} steps")
else:
teacache_thresh = 0.3
text_guide_scale = 5.0
audio_guide_scale = 4.0
shift = 7.0
offload_model = not high_vram
print(f"π¬ QUALITY MODE: {request.sampling_steps} steps")
extra_args = SimpleNamespace(
use_teacache=True,
teacache_thresh=teacache_thresh,
use_apg=False,
size="multitalk-480",
)
# Generate video
video = self.wan_i2v.generate(
input_data,
size_buckget="multitalk-480",
motion_frame=25,
frame_num=num_frames,
shift=shift,
sampling_steps=request.sampling_steps,
text_guide_scale=text_guide_scale,
audio_guide_scale=audio_guide_scale,
seed=seed,
offload_model=offload_model,
max_frames_num=num_frames,
extra_args=extra_args,
)
# Save video
output_name = (
f"multitalk_{abs(hash(request.prompt + str(seed))) % 10000}"
)
print(f"πΎ Saving video...")
save_video_ffmpeg(video, output_name, [input_data["video_audio"]])
# Find generated video
output_file = f"{output_name}.mp4"
if not os.path.exists(output_file):
for file in os.listdir("."):
if output_name in file and file.endswith(".mp4"):
output_file = file
break
if not os.path.exists(output_file):
raise RuntimeError(
"Video generation failed - output file not found"
)
# Encode video to base64
video_b64 = encode_file_to_base64(output_file)
# Cleanup GPU memory
if torch.cuda.is_available():
torch.cuda.empty_cache()
print(f"β
Video generation completed successfully!")
return MultiTalkResponse(
video=video_b64,
metadata={
"seed": seed,
"num_frames": num_frames,
"sampling_steps": request.sampling_steps,
"turbo": request.turbo,
"is_multi_person": is_multi_person,
"prompt": request.prompt,
"original_frames_requested": original_frames,
},
)
except Exception as e:
print(f"β Error during inference: {str(e)}")
raise Exception(f"Video generation failed: {str(e)}")
# Create singleton instance
multitalk_inference = None
# Load models function
@app.function(
volumes={MODEL_DIR.as_posix(): volume},
image=image,
gpu="A100",
)
def load_models():
"""Load models and return success status"""
global multitalk_inference
import torch
try:
if multitalk_inference is None:
print("π Loading MultiTalk models...")
multitalk_inference = MultiTalkInference()
return True
except Exception as e:
print(f"β Failed to load models: {str(e)}")
return False
# MultiTalk generation function
@app.function(
volumes={MODEL_DIR.as_posix(): volume},
image=image,
gpu="A100",
memory=16384,
)
def generate_multitalk(request: MultiTalkRequest) -> MultiTalkResponse:
"""Generate MultiTalk video from image and audio inputs."""
global multitalk_inference
from wan.configs import WAN_CONFIGS
from transformers import Wav2Vec2FeatureExtractor
from src.audio_analysis.wav2vec2 import Wav2Vec2Model
import pyloudnorm as pyln
from einops import rearrange
from wan.utils.multitalk_utils import save_video_ffmpeg
import torch
# Load models if not already loaded
if multitalk_inference is None:
print("Models not loaded, attempting to load...")
success = load_models.local()
if not success:
# Try to download models if loading failed
print("Loading failed, attempting to download missing models...")
try:
download_success = download_models.local()
if download_success:
volume.reload() # Reload after download
success = load_models.local()
if not success:
raise Exception("Failed to load models after download")
else:
raise Exception("Failed to download required models")
except Exception as e:
raise Exception(f"Failed to setup models: {str(e)}")
try:
# Generate video using the loaded models
result = multitalk_inference.generate_video(request)
return result
except Exception as e:
error_msg = str(e)
print(f"β Generation error: {error_msg}")
raise Exception(f"Video generation failed: {error_msg}")
# FastAPI endpoint
@app.function(
volumes={MODEL_DIR.as_posix(): volume},
image=image,
)
@modal.asgi_app()
def fastapi_app():
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import numpy as np
import torch
from fastapi import HTTPException
web_app = FastAPI(
title="MultiTalk API",
description="Generate talking head videos from images and audio",
version="1.0.0",
)
# Add CORS middleware
web_app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@web_app.post("/generate", response_model=MultiTalkResponse)
async def generate_multitalk_endpoint(request: MultiTalkRequest):
"""Generate talking head video from image and audio inputs."""
try:
# Validate inputs
if not request.image:
raise HTTPException(status_code=400, detail="Image is required")
if not request.first_audio:
raise HTTPException(status_code=400, detail="First audio is required")
if not request.prompt:
raise HTTPException(status_code=400, detail="Prompt is required")
# Validate frame count
if request.num_frames < 25 or request.num_frames > 201:
raise HTTPException(
status_code=400, detail="num_frames must be between 25 and 201"
)
# Validate sampling steps
if request.sampling_steps < 1 or request.sampling_steps > 100:
raise HTTPException(
status_code=400, detail="sampling_steps must be between 1 and 100"
)
# Call the generation function
result = generate_multitalk.remote(request)
return result
except HTTPException:
raise
except Exception as e:
error_msg = str(e)
# Extract the actual error message if it's wrapped
if "Failed to setup models:" in error_msg:
error_msg = error_msg.split("Failed to setup models: ")[-1]
elif "Video generation failed:" in error_msg:
error_msg = error_msg.split("Video generation failed: ")[-1]
raise HTTPException(status_code=500, detail=error_msg)
@web_app.get("/health")
async def health_check():
"""Health check endpoint."""
return {
"status": "healthy",
"service": "MultiTalk API",
"timestamp": datetime.now().isoformat(),
}
@web_app.get("/models/status", response_model=ModelStatus)
async def check_models_status():
"""Check the status of all required models."""
try:
model_status = check_models_exist.remote()
return ModelStatus(
models=model_status["models"],
total_size_gb=model_status["total_size_gb"],
status="ready" if model_status["all_present"] else "missing_models",
)
except Exception as e:
return ModelStatus(models={}, total_size_gb=0.0, status=f"error: {str(e)}")
@web_app.post("/models/download")
async def download_models_endpoint():
"""Download missing models."""
try:
current_status = check_models_exist.remote()
if current_status["all_present"]:
return {
"status": "success",
"message": "All models are already present",
"models": current_status["models"],
}
print("Starting model download...")
download_success = download_models.remote()
if download_success:
# Check status after download
new_status = check_models_exist.remote()
return {
"status": "success",
"message": "Models downloaded successfully",
"models": new_status["models"],
"total_size_gb": new_status["total_size_gb"],
}
else:
return {"status": "error", "message": "Failed to download models"}
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Failed to download models: {str(e)}"
)
@web_app.get("/")
async def root():
"""Root endpoint with API information."""
return {
"service": "MultiTalk API",
"version": "1.0.0",
"description": "Generate talking head videos from images and audio",
"endpoints": {
"generate": "/generate",
"health": "/health",
"models_status": "/models/status",
"download_models": "/models/download",
},
"documentation": "/docs",
}
return web_app
# Optional: CLI commands for development
@app.local_entrypoint()
def main():
"""Main CLI entry point for development."""
import argparse
parser = argparse.ArgumentParser(description="MultiTalk API Management")
parser.add_argument(
"command",
choices=["check-models", "download-models", "serve"],
help="Command to execute",
)
args = parser.parse_args()
if args.command == "check-models":
print("Checking model status...")
status = check_models_exist.remote()
print(f"Models present: {status['all_present']}")
print(f"Total size: {status['total_size_gb']:.2f} GB")
for model_name, exists in status["models"].items():
print(f" {model_name}: {'β' if exists else 'β'}")
elif args.command == "download-models":
print("Downloading models...")
success = download_models.remote()
if success:
print("β
Models downloaded successfully!")
else:
print("β Failed to download models")
elif args.command == "serve":
print("Starting FastAPI server...")
print("Server will be available at the Modal endpoint URL")
print("Use `modal serve` to run the FastAPI app")
if __name__ == "__main__":
main()
import modal
import os
import json
import base64
import tempfile
import subprocess
import time
import logging
import sys
import warnings
from pathlib import Path
from typing import Optional, Dict, Any, Union
from datetime import datetime
from types import SimpleNamespace
from io import BytesIO
import requests
import random
# Suppress warnings for cleaner output
warnings.filterwarnings("ignore")
# Modal setup
app = modal.App(name="multitalk-inference")
# Create volume for model weights
volume = modal.Volume.from_name("multitalk-models", create_if_missing=True)
MODEL_DIR = Path("/vol/models")
# Define the container image with all dependencies
image = (
modal.Image.debian_slim(python_version="3.10")
.apt_install(
"ffmpeg",
"libgl1-mesa-glx",
"libglib2.0-0",
"libsm6",
"libxext6",
"libxrender-dev",
"libgomp1",
"git",
"wget",
"curl",
)
.pip_install(
# "torch>=2.0.0",
# "torchvision",
# "torchaudio",
# "numpy<2.0.0",
# "transformers",
# "easydict",
# "accelerate",
# "diffusers",
# "huggingface-hub[hf_transfer]",
# "fastapi[standard]",
# "pydantic",
# "Pillow",
# "soundfile",
# "librosa",
# "pyloudnorm",
# "einops",
# "scipy",
# "imageio",
# "imageio-ffmpeg",
# "python-multipart",
# "omegaconf",
# "requests",
# "tqdm",
# "pydantic",
"torch>=2.4.0",
"torchvision>=0.19.0",
"torchaudio>=2.4.0",
"numpy>=1.23.5,<2.0.0",
"transformers>=4.49.0",
"tokenizers>=0.20.3",
"diffusers>=0.31.0",
"accelerate>=1.1.1",
"huggingface-hub>=0.19.0",
"easydict",
"gradio>=5.0.0",
"opencv-python>=4.9.0.80",
"soundfile>=0.12.1",
"librosa>=0.10.0",
"pyloudnorm",
"einops>=0.8.0",
"tqdm",
"imageio",
"imageio-ffmpeg",
"xfuser>=0.4.1",
"xformers>=0.0.28",
"safetensors>=0.3.1",
"dashscope",
"packaging",
"pydantic",
"python-multipart",
"omegaconf",
"requests",
"fastapi[standard]",