Update app.py
Browse files1234567893101167891213141516171819202122232425262728293031323334353637383940414211434445131415161718462021224748495024515253542627555657585960612962633132336465353637383966676869707172737475767778798081824283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354import osimport cv2import mathimport shutilimport subprocessimport tempfileimport traceback
import gradio as grimport torchimport librosaimport numpy as npimport soundfile as sfimport tempfilefrom demucs.pretrained import get_modelfrom demucs.apply import apply_modelimport onnxruntime as ort
# ============================================================# CONFIGURATION# ============================================================
MODEL_PATH = os.path.join( "wav2lip_models", "wav2lip_gan.onnx")
OUTPUT_DIR = "outputs"os.makedirs(OUTPUT_DIR, exist_ok=True)
# Your notebook's tested valuesSYNC_OFFSET_SEC = 0.080BLEND_STRENGTH = 0.42
# Wav2Lip audio settings from your notebookSAMPLE_RATE = 16000N_FFT = 800HOP_LENGTH = 200WIN_LENGTH = 800N_MELS = 80FMIN = 55FMAX = 7600
MEL_STEP_SIZE = 16MEL_PER_SECOND = 80.0
model = None # lazy load# Wav2Lip input face sizeFACE_SIZE = 96
def remove_vocals(audio_file): global model if model is None: model = get_model("htdemucs_small") # smaller, faster model.cpu() model.eval()
y, sr = librosa.load(audio_file, sr=44100, mono=False) if y.ndim == 1: y = np.expand_dims(y, axis=0)# ============================================================# LOAD MODEL# ============================================================
audio_tensor = torch.tensor(y).unsqueeze(0)print("=" * 60)print("Wav2Lip Gradio Space")print("=" * 60)
with torch.no_grad(): sources = apply_model(model, audio_tensor)if not os.path.exists(MODEL_PATH): raise FileNotFoundError( f"\nWav2Lip model not found:\n{MODEL_PATH}\n\n" "Upload wav2lip_gan.onnx into:\n" "wav2lip_models/wav2lip_gan.onnx" )
music_expression = sources[0][[0,1,2]].sum(dim=0)print("Loading Wav2Lip ONNX model...")
out_path = tempfile.NamedTemporaryFile(delete=False, suffix=".wav").name sf.write(out_path, music_expression.cpu().numpy().T, sr) return out_pathavailable_providers = ort.get_available_providers()
interface = gr.Interface( fn=remove_vocals, inputs=gr.Audio(type="filepath", label="Upload Audio"), outputs=gr.Audio(label="Music + Expression Sounds"), title="Vocal Remover: Keep Music + Expression Sounds"if "CUDAExecutionProvider" in available_providers: providers = [ "CUDAExecutionProvider", "CPUExecutionProvider" ]else: providers = [ "CPUExecutionProvider" ]
print("ONNX providers:", providers)
SESSION = ort.InferenceSession( MODEL_PATH, providers=providers)
interface.launch()print("Model loaded successfully.")
print("Model inputs:")
for inp in SESSION.get_inputs(): print( " ", inp.name, inp.shape, inp.type )
print("Model outputs:")
for out in SESSION.get_outputs(): print( " ", out.name, out.shape, out.type )
# ============================================================# CHECK FFMPEG# ============================================================
def check_ffmpeg(): ffmpeg = shutil.which("ffmpeg")
if ffmpeg is None: raise RuntimeError( "FFmpeg was not found in the Space runtime." )
return ffmpeg
# ============================================================# AUDIO# ============================================================
def load_audio(audio_path):
if not audio_path: raise ValueError("Please upload an audio file.")
wav, sr = librosa.load( audio_path, sr=SAMPLE_RATE, mono=True )
if wav is None or len(wav) == 0: raise ValueError("Audio file is empty or invalid.")
duration = len(wav) / SAMPLE_RATE
print( "Audio duration:", round(duration, 3), "seconds" )
return wav.astype(np.float32), duration
# ============================================================# WAV2LIP MEL SPECTROGRAM# ============================================================
def make_mel(wav):
mel = librosa.feature.melspectrogram( y=wav, sr=SAMPLE_RATE, n_fft=N_FFT, hop_length=HOP_LENGTH, win_length=WIN_LENGTH, n_mels=N_MELS, fmin=FMIN, fmax=FMAX, center=True )
# Same log compression used in your notebook mel = 20.0 * np.log10( np.maximum(1e-5, mel) )
return mel.astype(np.float32)
# ============================================================# FACE DETECTOR# ============================================================
def create_face_detector():
cascade_path = cv2.data.haarcascades + ( "haarcascade_frontalface_default.xml" )
detector = cv2.CascadeClassifier( cascade_path )
if detector.empty(): raise RuntimeError( "Could not load OpenCV face detector." )
return detector
FACE_DETECTOR = create_face_detector()
# ============================================================# FACE DETECTION# ============================================================
def detect_face(frame):
gray = cv2.cvtColor( frame, cv2.COLOR_BGR2GRAY )
gray = cv2.equalizeHist(gray)
faces = FACE_DETECTOR.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(80, 80) )
if len(faces) == 0: return None
# Select largest face faces = sorted( faces, key=lambda box: box[2] * box[3], reverse=True )
x, y, w, h = faces[0]
return ( int(x), int(y), int(w), int(h) )
# ============================================================# STABLE FACE BOX# ============================================================
def detect_face_from_video( video_path, max_samples=15):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened(): raise RuntimeError( "Could not open uploaded video." )
total_frames = int( cap.get(cv2.CAP_PROP_FRAME_COUNT) )
if total_frames <= 0: cap.release()
raise RuntimeError( "Video contains no frames." )
sample_count = min( max_samples, total_frames )
boxes = []
for i in range(sample_count):
frame_index = int( i * total_frames / sample_count )
cap.set( cv2.CAP_PROP_POS_FRAMES, frame_index )
ret, frame = cap.read()
if not ret: continue
box = detect_face(frame)
if box is not None:
x, y, w, h = box
boxes.append( [x, y, w, h] )
cap.release()
if len(boxes) == 0: raise RuntimeError( "No face was detected in the video.\n\n" "Please use a video where the person's face " "is clearly visible." )
boxes = np.array( boxes, dtype=np.float32 )
# Median is more stable than using a single frame median_box = np.median( boxes, axis=0 )
x, y, w, h = [ int(round(v)) for v in median_box ]
return ( x, y, w, h )
# ============================================================# MAKE FACE BOX SQUARE# ============================================================
def make_square_face_box( frame, box, padding=0.15):
frame_h, frame_w = frame.shape[:2]
x, y, w, h = box
# Wav2Lip works better with a square crop size = max(w, h)
size = int( size * (1.0 + padding) )
center_x = x + w / 2.0 center_y = y + h / 2.0
x1 = int( center_x - size / 2 )
y1 = int( center_y - size / 2 )
x2 = x1 + size y2 = y1 + size
# Clamp if x1 < 0: x2 -= x1 x1 = 0
if y1 < 0: y2 -= y1 y1 = 0
if x2 > frame_w: shift = x2 - frame_w x1 -= shift x2 = frame_w
if y2 > frame_h: shift = y2 - frame_h y1 -= shift y2 = frame_h
x1 = max(0, x1) y1 = max(0, y1)
x2 = min(frame_w, x2) y2 = min(frame_h, y2)
width = x2 - x1 height = y2 - y1
# Make exact square where possible size = min(width, height)
x2 = x1 + size y2 = y1 + size
return ( int(x1), int(y1), int(size), int(size) )
# ============================================================# CREATE MOUTH MASK# ============================================================
def create_mouth_mask( width, height):
mask = np.zeros( (height, width), dtype=np.float32 )
# Same approximate mouth area used # by your successful notebook version. mx1 = int(width * 0.30) mx2 = int(width * 0.70)
my1 = int(height * 0.52) my2 = int(height * 0.74)
mask[ my1:my2, mx1:mx2 ] = 1.0
mask = cv2.GaussianBlur( mask, (0, 0), sigmaX=max( 5, int(width * 0.03) ), sigmaY=max( 5, int(height * 0.03) ) )
mask = np.clip( mask, 0.0, 1.0 )
return mask
# ============================================================# COLOR MATCH# ============================================================
def color_match( generated, original, mask):
roi = mask > 0.25
if np.count_nonzero(roi) < 100: return generated
original_float = ( original.astype(np.float32) )
generated_float = ( generated.astype(np.float32) )
# Same conservative correction # used in your notebook. for c in range(3):
original_values = ( original_float[:, :, c][roi] )
generated_values = ( generated_float[:, :, c][roi] )
original_mean = np.mean( original_values )
generated_mean = np.mean( generated_values )
correction = ( original_mean - generated_mean ) * 0.65
generated_float[:, :, c] += ( correction )
generated_float = np.clip( generated_float, 0, 255 )
return generated_float.astype( np.uint8 )
# ============================================================# WAV2LIP FRAME INFERENCE# ============================================================
def generate_lip_frame( face, mel_chunk):
face_96 = cv2.resize( face, (FACE_SIZE, FACE_SIZE), interpolation=cv2.INTER_AREA )
# Mask lower half masked = face_96.copy()
masked[ FACE_SIZE // 2: ] = 0
# 3-channel masked + # 3-channel original = 6 channels combined = np.concatenate( [ masked, face_96 ], axis=2 )
combined = ( combined.astype(np.float32) / 255.0 )
combined = combined.transpose( 2, 0, 1 )
video_input = combined[ np.newaxis, ... ].astype(np.float32)
mel_input = mel_chunk[ np.newaxis, np.newaxis, :, : ].astype(np.float32)
outputs = SESSION.run( ["predicted_frames"], { "mel_spectrogram": mel_input,
"video_frames": video_input } )
prediction = outputs[0][0]
# Model output: # (3,96,96) prediction = np.clip( prediction * 255.0, 0, 255 ).astype(np.uint8)
prediction = prediction.transpose( 1, 2, 0 )
prediction = cv2.cvtColor( prediction, cv2.COLOR_RGB2BGR )
prediction = cv2.resize( prediction, (face.shape[1], face.shape[0]), interpolation=cv2.INTER_CUBIC )
return prediction
# ============================================================# MUX AUDIO# ============================================================
def mux_audio( silent_video, original_audio, output_video):
ffmpeg = check_ffmpeg()
command = [ ffmpeg, "-y",
"-i", silent_video,
"-i", original_audio,
"-map", "0:v:0",
"-map", "1:a:0",
"-c:v", "libx264",
"-preset", "veryfast",
"-crf", "18",
"-pix_fmt", "yuv420p",
"-c:a", "aac",
"-b:a", "192k",
"-shortest",
output_video ]
result = subprocess.run( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True )
if result.returncode != 0:
print(result.stderr)
raise RuntimeError( "FFmpeg audio muxing failed." )
# ============================================================# MAIN PROCESSING# ============================================================
def process_video( video_path, audio_path, text, progress=gr.Progress()):
if not video_path: raise ValueError( "Please upload a source video." )
if not audio_path: raise ValueError( "Please upload target audio." )
if not os.path.exists(video_path): raise FileNotFoundError( "Uploaded video file does not exist." )
if not os.path.exists(audio_path): raise FileNotFoundError( "Uploaded audio file does not exist." )
job_dir = tempfile.mkdtemp( prefix="wav2lip_" )
silent_video = os.path.join( job_dir, "silent.mp4" )
final_video = os.path.join( OUTPUT_DIR, "wav2lip_result.mp4" )
try:
# ---------------------------------------------------- # AUDIO # ----------------------------------------------------
progress( 0.05, desc="Loading audio..." )
wav, audio_duration = ( load_audio(audio_path) )
mel = make_mel(wav)
print( "Mel shape:", mel.shape )
# ---------------------------------------------------- # VIDEO # ----------------------------------------------------
progress( 0.10, desc="Opening video..." )
cap = cv2.VideoCapture( video_path )
if not cap.isOpened(): raise RuntimeError( "Could not open source video." )
fps = cap.get( cv2.CAP_PROP_FPS )
if fps is None or fps <= 0: fps = 25.0
width = int( cap.get( cv2.CAP_PROP_FRAME_WIDTH ) )
height = int( cap.get( cv2.CAP_PROP_FRAME_HEIGHT ) )
total_frames = int( cap.get( cv2.CAP_PROP_FRAME_COUNT ) )
if width <= 0 or height <= 0: cap.release()
raise RuntimeError( "Invalid video dimensions." )
if total_frames <= 0: cap.release()
raise RuntimeError( "Video contains no frames." )
# Number of frames determined by # target audio duration. audio_frames = int( math.ceil( audio_duration * fps ) )
num_frames = min( total_frames, audio_frames )
print( "FPS:", fps )
print( "Video size:", width, "x", height )
print( "Original frames:", total_frames )
print( "Processing frames:", num_frames )
# ---------------------------------------------------- # FACE DETECTION # ----------------------------------------------------
progress( 0.15, desc="Detecting face..." )
detected_box = ( detect_face_from_video( video_path ) )
print( "Detected face:", detected_box )
# Read first frame to create # final stable crop. cap.set( cv2.CAP_PROP_POS_FRAMES, 0 )
ret, first_frame = cap.read()
if not ret: cap.release()
raise RuntimeError( "Could not read first video frame." )
face_box = make_square_face_box( first_frame, detected_box, padding=0.15 )
x, y, w, h = face_box
print( "Final face box:", face_box )
# ---------------------------------------------------- # OUTPUT VIDEO # ----------------------------------------------------
fourcc = cv2.VideoWriter_fourcc( *"mp4v" )
writer = cv2.VideoWriter( silent_video, fourcc, fps, (width, height) )
if not writer.isOpened(): cap.release()
raise RuntimeError( "Could not create output video." )
# ---------------------------------------------------- # MASK # ----------------------------------------------------
mask = create_mouth_mask( w, h )
# ---------------------------------------------------- # PROCESS FRAMES # ----------------------------------------------------
for frame_index in range( num_frames ):
ret, frame = cap.read()
if not ret: break
# ----------------------------------------------- # SYNC CORRECTION # -----------------------------------------------
frame_time = ( frame_index / fps )
corrected_time = ( frame_time + SYNC_OFFSET_SEC )
mel_start = int( corrected_time * MEL_PER_SECOND )
mel_end = ( mel_start + MEL_STEP_SIZE )
# ----------------------------------------------- # AUDIO BOUNDS # -----------------------------------------------
if mel_start < 0:
mel_start = 0
mel_end = ( MEL_STEP_SIZE )
if ( mel_start >= mel.shape[1] ):
mel_start = max( 0, mel.shape[1] - MEL_STEP_SIZE )
mel_end = ( mel_start + MEL_STEP_SIZE )
mel_chunk = mel[ :, mel_start:mel_end ]
# Pad last chunk if ( mel_chunk.shape[1] < MEL_STEP_SIZE ):
if mel_chunk.shape[1] == 0:
mel_chunk = np.zeros( ( N_MELS, MEL_STEP_SIZE ), dtype=np.float32 )
else:
mel_chunk = np.pad( mel_chunk, ( ( 0, 0 ), ( 0, MEL_STEP_SIZE - mel_chunk.shape[1] ) ), mode="edge" )
# ----------------------------------------------- # FACE CROP # -----------------------------------------------
face = frame[ y:y+h, x:x+w ]
if face.size == 0:
writer.release() cap.release()
raise RuntimeError( f"Invalid face crop at frame " f"{frame_index}." )
# ----------------------------------------------- # WAV2LIP # -----------------------------------------------
generated = ( generate_lip_frame( face, mel_chunk ) )
# ----------------------------------------------- # COLOR MATCH # -----------------------------------------------
generated = color_match( generated, face, mask )
# ----------------------------------------------- # BLEND # -----------------------------------------------
original = face.astype( np.float32 )
generated_float = ( generated.astype( np.float32 ) )
alpha = ( mask[ :, :, np.newaxis ] * BLEND_STRENGTH )
blended = ( generated_float * alpha + original * (1.0 - alpha) )
blended = np.clip( blended, 0, 255 ).astype(np.uint8)
# Put generated face # back into original frame frame[ y:y+h, x:x+w ] = blended
writer.write(frame)
# Progress if frame_index % 5 == 0:
fraction = ( frame_index / max( 1, num_frames ) )
progress( 0.20 + fraction * 0.65, desc=( f"Generating lips... " f"{frame_index}/{num_frames}" ) )
cap.release() writer.release()
# ---------------------------------------------------- # MUX AUDIO # ----------------------------------------------------
progress( 0.90, desc="Adding target audio..." )
mux_audio( silent_video, audio_path, final_video )
# ---------------------------------------------------- # FINISHED # ----------------------------------------------------
progress( 1.0, desc="Completed!" )
size_mb = ( os.path.getsize( final_video ) / (1024 * 1024) )
print( "Final output:", final_video )
print( "Size:", round(size_mb, 2), "MB" )
status = ( "### โ
Lip-sync completed\n\n" f"**Audio duration:** " f"{audio_duration:.2f} sec\n\n" f"**FPS:** {fps:.2f}\n\n" f"**Frames processed:** " f"{num_frames}\n\n" f"**Face:** " f"`{x}, {y}, {w}, {h}`\n\n" f"**Sync correction:** " f"{SYNC_OFFSET_SEC:.3f} sec" )
if text and text.strip():
status += ( "\n\n**Text provided:**\n\n" + text.strip() )
return ( final_video, status )
except Exception as e:
print( "\nERROR:\n", traceback.format_exc() )
raise gr.Error( str(e) )
finally:
shutil.rmtree( job_dir, ignore_errors=True )
# ============================================================# GRADIO UI# ============================================================
custom_css = """.gradio-container { max-width: 1100px !important; margin: auto !important;}
.title { text-align: center;}
.description { text-align: center;}
#generate-button { min-height: 55px; font-size: 18px; font-weight: bold;}"""
with gr.Blocks( title="Wav2Lip AI Lip Sync") as demo:
gr.Markdown( """ # ๐๏ธ Wav2Lip AI Lip Sync ### Upload a video + target audio โ generate a lip-synced video """, elem_classes="title" )
gr.Markdown( """ Upload a video containing a clearly visible face and the audio you want the person to speak. The optional text field is only for reference/display; Wav2Lip uses the uploaded audio for lip synchronization. """, elem_classes="description" )
with gr.Row():
with gr.Column():
video_input = gr.Video( label="Source Video", sources=["upload"], type="filepath" )
audio_input = gr.Audio( label="Target Audio", sources=["upload"], type="filepath" )
text_input = gr.Textbox( label="Audio Text (Optional)", placeholder=( "Enter the sentence spoken in the audio..." ), lines=4 )
generate_button = gr.Button( "๐ฌ GENERATE LIP-SYNC VIDEO", variant="primary", elem_id="generate-button" )
with gr.Column():
output_video = gr.Video( label="Lip-Synced Output", autoplay=False )
status_output = gr.Markdown( label="Status" )
gr.Markdown( """ --- ### Tips
- Use a front-facing or mostly front-facing face. - Make sure the face is clearly visible. - Use clean speech audio. - For best results, keep the speaker reasonably close to the camera. - The optional text does **not** generate the audio; the uploaded audio is used directly. """ )
generate_button.click( fn=process_video, inputs=[ video_input, audio_input, text_input ], outputs=[ output_video, status_output ] )
# ============================================================# LAUNCH# ============================================================
if __name__ == "__main__":
print("=" * 60) print("Starting Gradio...") print("=" * 60)
demo.queue( max_size=10 ).launch( server_name="0.0.0.0", server_port=7860 )app.py+1340-28