Update app.py
Browse files1 unmodified line234556789103 unmodified lines14151617171819202122232324256 unmodified lines3233343635363738394042414243441 unmodified line46474850495051529 unmodified lines626364666566676869717071727374757678797778798081828182838485848586878889868788899093919293969495969798991001011021031041051061071081099811011111211318 unmodified lines13213313412313513612512613713813914014114214313114414514614714814915015115215315415515615715814015916016116216316416514716616716816917017115315417217317417517615815916016117717817918018118218316818418518618731 unmodified lines21922022120622222322420922522622722815 unmodified lines2442452462312322332342352472482372492502512522532392402412422542552442452462472562572582592602502512522612622632642652662672682692702552562572582712722732742752612622632762772782792802662812822832842852862692872882892902912922732932942952963 unmodified lines3003013022833033043053062873073083093103113123132943143153162973173183193203013213223233243253263073273283293305 unmodified lines33633733831933934034134232334334434532632734634734834935033135135235335435533333435635735835933833934036036136236336436536634534634734834935035135235335435535635735836736836136236336436536636736937037137237337437137537337437637737837938011 unmodified lines3923933943923953963973983963973993984004014024 unmodified lines4074084094094104114104114124134144158 unmodified lines42442542642642742842943043124 unmodified lines4564574584574584594604594604614624634644658 unmodified lines4744754764754774784794802 unmodified lines4834844854844864874884892 unmodified lines4924934944934954964974982 unmodified lines5015025035025045055065075085075085095105115125115135145155165175165175185195205215225235185195205215225275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965235245255265985275286016026036046056066076086096106115295305315326146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466475335345355365375385395406506516526536546555415425435446595455465475488 unmodified lines5575585596745605615625639 unmodified lines5735745756905765775785796946955805815825835842 unmodified lines5875885897045905915927075935945957105965975985996006017166026036046057 unmodified lines61361461573061661761861912 unmodified lines6326336347497506356366376386397546406416426436446457606466477626486496506514 unmodified lines65665765877365966066177677777866266366466566678166766878366967067167278767367467567667767879367968068168216 unmodified lines6997007018167027037048198207057067077087098238248258268278287107117127137148328338348358368378388398408417157167178448457187197207217227237247257267278498507287297307317327337347358548557367377387397407417428598608618628638648658668678688698708718728737437447457467477488778788798808818827497507517527537548868878888897557567577587597608938947617627638968978988999009019029039049059069079089099109119129139149159169179189199209219227647657667677687697709279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729737717727737747757767777787799779789799809819829839849859869879889899909919929939949959969977807817827837847857867877881002789790791100579279310077947957967971011798799800101480180280310171018804805806807808809810811102581281381481581681710288188198208211032822823824825826827828829103910408308318328331043834835836104683783883984084184210521053105410558438448458468478488498508518528531060106110628548558568578581 unmodified line860861862107010718638648658668674 unmodified lines872873874108287587687787810868798808818829 unmodified lines892893894110289589689789889990090111099029039049059061114111511161117111890790890991010 unmodified lines9219229231135924925113792692792892993093193293393493593693711439389399409419429439441150115111529459461154115594794894995095195295395495595695795811571158959960961116096296396496511649669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106711681068106910701171107110721073107413 unmodified lines108810891090119111921193119411951196119710911092109310941095109612011202120312041205109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189121511901191119211931219122012211222119411951196119712251226122711981199120012012 unmodified lines120412051206123612071208120912105 unmodified lines121612171218124812191220125012211222122312241225125512261227122812291230123112321262123312341235123612371238123912691270124012411242124312441245127512461247124812491 unmodified line125112521253128312541255125612578 unmodified lines12661267126812981269127012711301127212731274127529 unmodified lines130513061307133713081309131013111312134213131314131513161346134713481317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213551373137413751376137713781379136213801381138213838 unmodified lines139213931394137713951396137913971398139914005 unmodified lines14061407140813911409141014111412139514131414141514161 unmodified line141814191420140314041421142214231424142514081409142614271428142914303 unmodified lines14341435143614371438143914401441144214431444144514461447144814491450142514511452145314545 unmodified lines146014611462143714631464146514663 unmodified lines1470147114721447147314741475147621 unmodified lines1498149915001475147614771478147914801481148214831501150215031 unmodified line150515061507149115081509151015111 unmodified line151315141515149915161517151815191520152115051522152315241525152615101527152815291530151415311532153315342 unmodified lines1537153815391523154015411542154315441528154515461547154824 unmodified lines1573157415751559157615771578156215791580158115821 unmodified line158415851586157015871588157215891590159115921593159415781595159615971598159915831600160116021586158715881589159015911592159316031604160515961606160716081609161016111612160216131614161516161617161816191620162116221623162416251626162716281629163016311632160616331634163516367 unmodified lines16441645164616201647164816491650162416511652165316541655162816561657165816591 unmodified line166116621663163616641665166616671 unmodified line1669167016711644167216731674164716481649165016751676167716511678167916801655168116821683168416591660168516861687168816891664169016911692169316941695169616973 unmodified lines1701170217031674170417051676167716781679168016811682168316841685168616871688168916901706170717088 unmodified lines1717171817191705172017211722172320 unmodified lines1744174517461732174717481749175014 unmodified lines176517661767175317541768176917701771177216 unmodified lines1789179017911792179317941795179617971798179918001801180218031804180517781806180718081781180918101811181218131814181517881816181718181819179117921793182018211822182318241825182618271798182818291830183118021803183218331834183518363 unmodified lines184018411842181318431844184518461 unmodified line18481849185018211851185218531823185418551825185618571858185918601861186218321863186418651866186718681869183618701871187218734 unmodified lines187818791880184718811882188318842 unmodified lines1887188818891856189018911892185918931894189518963 unmodified lines1900190119021869190319041905190618731907190818751876187718781879190919101911191219131914191519161917191819191886188718881889189018911892192019211922192319241925192619271928192919301931189718981932193319341935193619371903193819391940194119421908194319441945194624 unmodified lines197119721973193919741975197619772 unmodified lines198019811982194819491983198419851986198719881989199019911992199319941995199619972 unmodified lines20002001200219642003200420052006200720082009201020111971197219732012201320142015201620172018201920 unmodified lines204020412042200020432044204520462 unmodified lines204920502051200920522053201120542055205620574 unmodified lines20622063206420222065206620672068202620272028206920702071207220322073207420752076207720372038203920402041204220432044204520462047204820492050205120522053207820792080208120822083208420852086208720882089209020912092209320942059209520962097209819 unmodified lines211821192120208521212122212321241 unmodified lineimport cv2import mathimport shutilimport subprocessimport tempfileimport tracebackimport subprocessimport urllib.request
import gradio as gr3 unmodified lines
# ============================================================# CONFIG# CONFIGURATION# ============================================================
MODEL_PATH = "wav2lip_models/wav2lip_gan.onnx"
OUTPUT_DIR = "outputs"
FACE_DIR = "face_detector"
FACE_PROTO = os.path.join(6 unmodified lines "res10_300x300_ssd_iter_140000.caffemodel")
PROTO_URL = (FACE_PROTO_URL = ( "https://raw.githubusercontent.com/" "opencv/opencv/master/samples/dnn/" "face_detector/deploy.prototxt")
MODEL_URL = (FACE_MODEL_URL = ( "https://github.com/opencv/opencv_3rdparty/" "raw/dnn_samples_face_detector_20170830/" "res10_300x300_ssd_iter_140000.caffemodel"1 unmodified line
# ============================================================# WAV2LIP AUDIO PARAMETERS# AUDIO# ============================================================
SAMPLE_RATE = 160009 unmodified lines
MEL_STEP_SIZE = 16
# Original Wav2Lip uses approximately 80 mel frames/sec# Wav2Lip audio timingMEL_FPS = 80.0
# ============================================================# VIDEO / FACE PARAMETERS# FACE# ============================================================
FACE_SIZE = 96
FACE_CONFIDENCE = 0.50
# Extra face crop around detected faceFACE_PADDING = 0.20# Do NOT make this too large.## A large crop followed by 96x96 resizing causes# the mouth to become soft/distorted.FACE_PADDING = 0.08
# Temporal face smoothingFACE_SMOOTHING = 0.15# Face tracking smoothingFACE_SMOOTHING = 0.25
# Mouth blend strength## 0.70 = stronger lip replacement# 0.55 = balanced# 0.40 = more original faceMOUTH_BLEND = 0.62# How frequently to re-detect faceREDETECT_SECONDS = 0.40
# ============================================================# OUTPUT QUALITY# BLENDING# ============================================================
FFMPEG_CRF = 17# 1.0 = strongest generated mouth# 0.7 = balanced# 0.55 = preserve original textureBLEND_STRENGTH = 0.72
# Lower-face mask starts around this percentage# of the crop.LOWER_FACE_START = 0.47
# ============================================================# VIDEO ENCODING# ============================================================
CRF = 17FFMPEG_PRESET = "medium"PRESET = "medium"
os.makedirs(18 unmodified linesif not os.path.exists(MODEL_PATH):
raise FileNotFoundError( "\nWav2Lip ONNX model not found:\n" "\n\nWav2Lip ONNX model not found:\n\n" f"{MODEL_PATH}\n\n" "Expected:\n" "wav2lip_models/wav2lip_gan.onnx" "Your Space should contain:\n\n" "wav2lip_models/\n" " wav2lip_gan.onnx\n" )
# ============================================================# ONNX PROVIDERS# ONNX# ============================================================
available_providers = ( ort.get_available_providers())
print( "Available ONNX providers:", available_providers)
if "CUDAExecutionProvider" in available_providers:
providers = [ PROVIDERS = [ "CUDAExecutionProvider", "CPUExecutionProvider" ]
else:
providers = [ PROVIDERS = [ "CPUExecutionProvider" ]
print( "ONNX providers:", providers "Using providers:", PROVIDERS)
# ============================================================# LOAD WAV2LIP# ============================================================
print( "Loading Wav2Lip ONNX model...")
SESSION = ort.InferenceSession( MODEL_PATH, providers=providers providers=PROVIDERS)
31 unmodified lines
# ============================================================# FACE DETECTOR# FACE DETECTOR DOWNLOAD# ============================================================
def download_file(def download_if_needed( url, path):15 unmodified lines )
urllib.request.urlretrieve( url, path )
try:
def load_face_detector(): urllib.request.urlretrieve( url, path )
download_file( PROTO_URL, FACE_PROTO ) except Exception as e:
download_file( MODEL_URL, FACE_MODEL ) raise RuntimeError( f"Could not download {url}\n{e}" )
print( "Loading OpenCV DNN face detector..." )download_if_needed( FACE_PROTO_URL, FACE_PROTO)
download_if_needed( FACE_MODEL_URL, FACE_MODEL)
detector = cv2.dnn.readNetFromCaffe( FACE_PROTO, FACE_MODEL )
# ============================================================# FACE DETECTOR# ============================================================
print( "Face detector loaded." )print( "Loading OpenCV DNN face detector...")
return detectorFACE_DETECTOR = cv2.dnn.readNetFromCaffe( FACE_PROTO, FACE_MODEL)
FACE_DETECTOR = load_face_detector()print( "Face detector loaded.")
# ============================================================# AUDIO LOADING# AUDIO# ============================================================
def load_audio(3 unmodified lines if not path:
raise ValueError( "Audio file is required." "Target audio is required." )
wav, sr = librosa.load( audio, sr = librosa.load( path, sr=SAMPLE_RATE, mono=True )
if wav is None or len(wav) == 0: if audio is None or len(audio) == 0:
raise ValueError( "Could not read audio." "Could not read target audio." )
wav = wav.astype( audio = audio.astype( np.float32 )
duration = ( len(wav) len(audio) / SAMPLE_RATE )
5 unmodified lines )
return wav, duration return audio, duration
# ============================================================# WAV2LIP-COMPATIBLE MEL SPECTROGRAM# WAV2LIP MEL# ============================================================
def wav2lip_mel( wavdef make_mel( audio):
""" Wav2Lip-style mel preprocessing. Wav2Lip-style mel spectrogram.
Important: The ONNX model expects exactly:
This is intentionally closer to the original Wav2Lip audio preprocessing than the previous implementation. [1, 1, 80, 16] """
# Pre-emphasis / STFT stft = librosa.stft( wav, mel = librosa.feature.melspectrogram( y=audio, sr=SAMPLE_RATE, n_fft=N_FFT, hop_length=HOP_LENGTH, win_length=WIN_LENGTH, window="hann", center=True )
# Magnitude magnitudes = np.abs( stft )
# Mel filter bank mel_filters = librosa.filters.mel( sr=SAMPLE_RATE, n_fft=N_FFT, n_mels=N_MELS, fmin=FMIN, fmax=FMAX )
mel = np.dot( mel_filters, magnitudes fmax=FMAX, power=1.0, center=True )
# Wav2Lip-style log compression mel = np.maximum( 1e-5, mel mel, 1e-5 )
11 unmodified lines# FACE DETECTION# ============================================================
def detect_faces(def detect_face( frame):
height, width = ( frame.shape[:2] h, w = frame.shape[:2] )
blob = cv2.dnn.blobFromImage(4 unmodified lines 1.0, (300, 300), ( 104.0, 177.0, 123.0 104, 177, 123 ) )
8 unmodified lines )
faces = [] best = None best_score = 0.0
for i in range(24 unmodified lines ] * np.array( [ width, height, width, height w, h, w, h ] ) )8 unmodified lines 0, min( x1, width - 1 w - 1 ) )
2 unmodified lines 0, min( y1, height - 1 h - 1 ) )
2 unmodified lines 0, min( x2, width w ) )
2 unmodified lines 0, min( y2, height h ) )
w = x2 - x1 h = y2 - y1 bw = x2 - x1 bh = y2 - y1
if w < 50 or h < 50: if bw < 40 or bh < 40:
continue
faces.append( { "x": x1, "y": y1, "w": w, "h": h, "confidence": confidence } area = ( bw * bh )
return faces
# ============================================================# BEST FACE# ============================================================
def best_face( frame):
faces = detect_faces( frame )
if not faces:
return None
faces.sort( key=lambda f: ( f["w"] * f["h"], f["confidence"] ), reverse=True )
f = faces[0]
return ( f["x"], f["y"], f["w"], f["h"] )
# ============================================================# FACE BOX WITH PADDING# ============================================================
def padded_square_box( frame, box):
height, width = ( frame.shape[:2] )
x, y, w, h = box
# Wav2Lip needs a little surrounding context size = max( w, h )
size = int( size * ( 1.0 + FACE_PADDING score = ( confidence * math.sqrt(area) ) )
size = min( size, width, height )
cx = ( x + w / 2.0 ) if score > best_score:
best_score = score
cy = ( y + h / 2.0 )
x1 = int( cx - size / 2 )
y1 = int( cy - size / 2 )
x1 = max( 0, min( x1, width - size ) )
y1 = max( 0, min( y1, height - size ) ) best = ( x1, y1, bw, bh )
return ( int(x1), int(y1), int(size), int(size) ) return best
# ============================================================# INITIAL FACE BOX# FIND FACE FROM SEVERAL FRAMES# ============================================================
def find_initial_face(8 unmodified lines if not cap.isOpened():
raise RuntimeError( "Could not open video." "Could not open source video." )
9 unmodified lines cap.release()
raise RuntimeError( "Video has no frames." "Source video contains no frames." )
sample_count = min( 15, samples = min( 12, total )
2 unmodified lines
for i in range( sample_count samples ):
index = int( frame_number = int( i * total / sample_count / samples )
cap.set( cv2.CAP_PROP_POS_FRAMES, index frame_number )
7 unmodified lines continue
box = best_face( box = detect_face( frame )
12 unmodified lines
raise RuntimeError( "No face detected.\n\n" "Please use a video with a clearly " "visible face." "Please use a video where the face is " "clearly visible." )
boxes = np.asarray( arr = np.asarray( boxes, dtype=np.float32 )
# Median is more stable than taking the first frame # Median is much more stable than first frame. median = np.median( boxes, arr, axis=0 )
4 unmodified lines
# ============================================================# FACE BOX SMOOTHING# SMOOTH FACE BOX# ============================================================
def smooth_box( old_box, new_boxdef smooth_face( old, new):
if old_box is None: if old is None:
return new_box return new
old = np.asarray( old_box, old, dtype=np.float32 )
new = np.asarray( new_box, new, dtype=np.float32 )
16 unmodified lines
# ============================================================# MOUTH MASK# MAKE FACE CROP# ============================================================
def create_mouth_mask( sizedef make_crop( frame, face_box):
mask = np.zeros( ( size, size ), dtype=np.float32 frame_h, frame_w = ( frame.shape[:2] )
# Important: # Don't use a rectangular mouth region. # # An ellipse gives much smoother transitions and # avoids visible square/rectangular artifacts.
center_x = int( size * 0.50 ) x, y, w, h = face_box
center_y = int( size * 0.665 # Keep crop close to actual face. size = int( max(w, h) * ( 1.0 + FACE_PADDING ) )
axis_x = int( size * 0.285 # Prevent crop from becoming enormous. size = min( size, frame_w, frame_h )
axis_y = int( size * 0.155 # Face center cx = ( x + w / 2.0 )
cv2.ellipse( mask, ( center_x, center_y ), ( axis_x, axis_y ), 0, 0, 360, 1.0, -1 cy = ( y + h / 2.0 )
# Extra blur creates a natural transition sigma = max( 2, int( size * 0.045 ) x1 = int( cx - size / 2 )
mask = cv2.GaussianBlur( mask, (0, 0), sigma y1 = int( cy - size / 2 )
return np.clip( mask, # Keep inside frame x1 = max( 0, 1 )
MOUTH_MASK = create_mouth_mask( FACE_SIZE)
# ============================================================# MOUTH-ONLY COLOR CORRECTION# ============================================================
def color_correct( generated, original, mask):
result = generated.astype( np.float32 )
original_float = ( original.astype( np.float32 min( x1, frame_w - size ) )
strong = ( mask > 0.35 )
if np.count_nonzero( strong ) < 50:
return generated
for c in range(3):
src = ( original_float[ :, :, c ][strong] )
dst = ( result[ :, :, c ][strong] )
if ( len(src) == 0 or len(dst) == 0 ):
continue
src_mean = np.mean( src )
dst_mean = np.mean( dst y1 = max( 0, min( y1, frame_h - size ) )
# Only mild correction. # Strong correction can make lips look unnatural. correction = ( src_mean - dst_mean ) * 0.35
result[ :, :, c ] += correction
return np.clip( result, 0, 255 ).astype( np.uint8 return ( int(x1), int(y1), int(size), int(size) )
# ============================================================# WAV2LIP INFERENCE# WAV2LIP MODEL# ============================================================
def run_wav2lip(def inference( face, mel mel_chunk):
# -------------------------------------------------------- # Resize to model input # 96x96 # --------------------------------------------------------
face_96 = cv2.resize( face96 = cv2.resize( face, ( FACE_SIZE, FACE_SIZE 96, 96 ), interpolation=cv2.INTER_AREA )
# -------------------------------------------------------- # Mask lower half # ORIGINAL WAV2LIP MASKING # # Upper half remains original. # Lower half is masked. # --------------------------------------------------------
masked = face_96.copy() masked = face96.copy()
masked[ FACE_SIZE // 2: 48:, : ] = 0
# -------------------------------------------------------- # 6 channels # # [masked face RGB] # [original face RGB] # [masked RGB] # [original RGB] # --------------------------------------------------------
combined = np.concatenate( input_image = np.concatenate( [ masked, face_96 face96 ], axis=2 )
combined = ( combined.astype( np.float32 ) # -------------------------------------------------------- # HWC -> CHW # --------------------------------------------------------
input_image = ( input_image .astype(np.float32) / 255.0 )
# HWC -> CHW combined = ( combined.transpose( input_image = ( input_image.transpose( 2, 0, 11 unmodified line )
video_input = ( combined[ input_image = ( input_image[ np.newaxis, ... ]4 unmodified lines
# -------------------------------------------------------- # Mel # AUDIO # --------------------------------------------------------
mel_input = ( mel[ mel_chunk[ np.newaxis, np.newaxis, :,9 unmodified lines # ONNX # --------------------------------------------------------
outputs = SESSION.run( result = SESSION.run( None, { "mel_spectrogram": mel_input,
"video_frames": video_input input_image } )
prediction = outputs[0]
# [1,3,96,96] -> [3,96,96] prediction = prediction[0] prediction = result[0][0]
# --------------------------------------------------------10 unmodified lines
prediction = np.clip( prediction * 255.0, prediction, 0, 255 1 )
prediction = ( prediction * 255.0 ).astype( np.uint8 )
# Model output is RGB # Model returns RGB prediction = cv2.cvtColor( prediction, cv2.COLOR_RGB2BGR )
# -------------------------------------------------------- # Back to original crop resolution # -------------------------------------------------------- return prediction
prediction = cv2.resize( prediction,
# ============================================================# SOFT LOWER FACE MASK# ============================================================
def make_blend_mask( h, w):
mask = np.zeros( ( face.shape[1], face.shape[0] h, w ), interpolation=cv2.INTER_CUBIC dtype=np.float32 )
return prediction start = int( h * LOWER_FACE_START )
# Start from zero at upper edge. # Gradually increase toward mouth. # # This avoids a visible rectangular patch.
for y in range( start, h ):
position = ( y - start ) / max( 1, h - start )
# Smoothstep value = ( position * position * ( 3 - 2 * position ) )
mask[y, :] = value
# Stronger around mouth center yy, xx = np.mgrid[ 0:h, 0:w ]
cx = w * 0.50 cy = h * 0.68
rx = w * 0.42 ry = h * 0.30
ellipse = ( ( (xx - cx) / rx ) ** 2 + ( (yy - cy) / ry ) ** 2 )
ellipse_mask = np.exp( -ellipse * 1.8 )
# Combine lower-face and mouth masks. mask = ( mask * ( 0.45 + 0.55 * ellipse_mask ) )
# Smooth edges. mask = cv2.GaussianBlur( mask, ( 0, 0 ), sigmaX=max( 1.0, w * 0.035 ) )
return np.clip( mask, 0, 1 )
# ============================================================# BLEND RESULT# BLEND# ============================================================
def blend_mouth(def blend_prediction( original, generated):13 unmodified lines )
mask = cv2.resize( MOUTH_MASK, ( w, h ), interpolation=cv2.INTER_CUBIC mask = make_blend_mask( h, w )
# Mild color correction generated = color_correct( generated, original, mask # -------------------------------------------------------- # Slight color matching. # # Do NOT aggressively change colors. # --------------------------------------------------------
original_float = ( original.astype( np.float32 ) )
generated_float = ( generated.astype( np.float32 ) )
mouth_area = ( mask > 0.55 )
if np.count_nonzero( mouth_area ) > 100:
for c in range(3):
src = ( original_float[ :, :, c ][mouth_area] )
gen = ( generated_float[ :, :, c ][mouth_area] )
if ( len(src) > 0 and len(gen) > 0 ):
src_mean = np.mean( src )
gen_mean = np.mean( gen )
correction = ( src_mean - gen_mean ) * 0.20
generated_float[ :, :, c ] += correction
generated_float = np.clip( generated_float, 0, 255 )
# -------------------------------------------------------- # Blend # --------------------------------------------------------
alpha = ( mask[ :, :, np.newaxis ] * MOUTH_BLEND * BLEND_STRENGTH )
result = ( generated.astype( np.float32 ) output = ( generated_float * alpha + original.astype( np.float32 ) original_float * ( 1.0 - alpha2 unmodified lines
return np.clip( result, output, 0, 255 ).astype(5 unmodified lines# FFMPEG# ============================================================
def get_ffmpeg():def ffmpeg_path():
ffmpeg = shutil.which( path = shutil.which( "ffmpeg" )
if ffmpeg is None: if path is None:
raise RuntimeError( "FFmpeg is not installed." )
return ffmpeg return path
# ============================================================# MUX AUDIO# ============================================================
def mux_audio( video,def add_audio( silent_video, audio, output):
ffmpeg = get_ffmpeg() ffmpeg = ffmpeg_path()
command = [1 unmodified line "-y",
"-i", video, silent_video,
"-i", audio,8 unmodified lines "libx264",
"-preset", FFMPEG_PRESET, PRESET,
"-crf", str(FFMPEG_CRF), str(CRF),
"-pix_fmt", "yuv420p",29 unmodified lines
raise RuntimeError( "FFmpeg audio muxing failed." "Could not add audio to output video." )
# ============================================================# MAIN PROCESS# PROCESS# ============================================================
def process_video( video_path, audio_path, text, video_input, audio_input, text_input, progress=gr.Progress()):
# ======================================================== # GET VIDEO PATH # ========================================================
video_path = video_input
# Gradio can return a dictionary in some configurations. if isinstance( video_input, dict ):
video_path = ( video_input.get( "path" ) or video_input.get( "name" ) )
# ======================================================== # AUDIO PATH # ========================================================
audio_path = audio_input
if isinstance( audio_input, dict ):
audio_path = ( audio_input.get( "path" ) or audio_input.get( "name" ) )
if not video_path:
raise gr.Error( "Please upload a video." "Please upload a source video." )
if not audio_path:
raise gr.Error( "Please upload audio." "Please upload target audio." )
8 unmodified lines )
output_video = os.path.join( output_path = os.path.join( OUTPUT_DIR, "wav2lip_hq_result.mp4" "wav2lip_result.mp4" )
5 unmodified lines
progress( 0.02, desc="Loading audio..." desc="Loading target audio..." )
wav, audio_duration = ( audio, audio_duration = ( load_audio( audio_path )1 unmodified line
progress( 0.06, desc="Creating Wav2Lip mel spectrogram..." 0.07, desc="Creating mel spectrogram..." )
mel = wav2lip_mel( wav mel = make_mel( audio )
3 unmodified lines )
if mel.shape[0] != 80:
raise RuntimeError( "Mel spectrogram has wrong number " f"of bands: {mel.shape[0]}" )
# ==================================================== # VIDEO # ====================================================
progress( 0.10, desc="Opening video..." desc="Opening source video..." )
5 unmodified lines if not cap.isOpened():
raise RuntimeError( "Could not open video." "Could not open source video." )
3 unmodified lines
if ( fps is None not fps or fps <= 0 ):
21 unmodified lines )
if total_frames <= 0:
cap.release()
raise RuntimeError( "Video contains no frames." )
print( "FPS:", fps1 unmodified line
print( "Resolution:", "Video:", width, "x", height1 unmodified line
print( "Total frames:", "Frames:", total_frames )
# ==================================================== # FACE # FIND FACE # ====================================================
progress( 0.14, desc="Finding face..." desc="Locating face..." )
initial_face = ( current_face = ( find_initial_face( video_path )2 unmodified lines
print( "Initial face:", initial_face current_face )
# ==================================================== # CREATE VIDEO WRITER # VIDEO WRITER # ====================================================
fourcc = (24 unmodified lines
# ==================================================== # PROCESS FRAME COUNT # HOW MANY VIDEO FRAMES # ====================================================
audio_frame_count = int( audio_frames = int( math.ceil( audio_duration * fps1 unmodified line )
process_frames = min( frames_to_process = min( total_frames, audio_frame_count audio_frames )
print( "Frames to process:", process_frames frames_to_process )
# ==================================================== # FACE TRACKING # FACE REDETECTION # ====================================================
current_face = initial_face
# How often to re-detect # # This prevents the face from drifting when the # person moves. REDETECT_EVERY = max( redetect_every = max( 1, int( fps * 0.5 fps * REDETECT_SECONDS ) )
# ==================================================== # PROCESS # AUDIO MAPPING # ====================================================
mel_idx_multiplier = ( MEL_FPS / fps )
print( "Mel index multiplier:", mel_idx_multiplier )
# ==================================================== # FRAME LOOP # ====================================================
for frame_index in range( process_frames frames_to_process ):
ok, frame = (7 unmodified lines
# ------------------------------------------------ # Re-detect periodically # FACE TRACKING # ------------------------------------------------
if ( frame_index % REDETECT_EVERY frame_index % redetect_every == 0 ):
detected = best_face( detected = detect_face( frame )
1 unmodified line if detected is not None:
current_face = ( smooth_box( smooth_face( current_face, detected )1 unmodified line
# ------------------------------------------------ # Face crop # FACE CROP # ------------------------------------------------
crop_box = ( padded_square_box( frame, current_face crop = make_crop( frame, current_face ) )
x, y, w, h = crop_box x, y, cw, ch = crop
face = frame[ y:y+h, x:x+w y:y+ch, x:x+cw ]
if face.size == 0: if ( face.size == 0 or face.shape[0] < 20 or face.shape[1] < 20 ):
writer.write( frame3 unmodified lines
# ------------------------------------------------ # EXACT AUDIO/VIDEO FRAME MAPPING # CORRECT MEL WINDOW # ------------------------------------------------ # # This is more important for sync than a manually # chosen arbitrary offset. # # Original Wav2Lip style: # # mel_idx_multiplier = 80 / fps # # ------------------------------------------------
mel_idx_multiplier = ( MEL_FPS / fps )
mel_start = int( frame_index8 unmodified lines
# ------------------------------------------------ # Handle final audio frames # End of audio # ------------------------------------------------
if mel_start >= (20 unmodified lines
# ------------------------------------------------ # Pad final chunk # EXACTLY 16 MEL FRAMES # ------------------------------------------------
if (14 unmodified lines
mel_chunk = np.zeros( ( N_MELS, MEL_STEP_SIZE 80, 16 ), dtype=np.float32 )16 unmodified lines )
elif ( mel_chunk.shape[1] > MEL_STEP_SIZE ):
mel_chunk = ( mel_chunk[ :, :MEL_STEP_SIZE ] )
# ------------------------------------------------ # Generate # MODEL # ------------------------------------------------
generated = run_wav2lip( generated = inference( face, mel_chunk )
# ------------------------------------------------ # Mouth-only blend # BLEND # ------------------------------------------------
result_face = ( result_face = blend_mouth( face, generated blend_prediction( face, generated ) )
# ------------------------------------------------ # Paste back # PUT FACE BACK # ------------------------------------------------
frame[ y:y+h, x:x+w y:y+ch, x:x+cw ] = result_face
3 unmodified lines
# ------------------------------------------------ # Progress # PROGRESS # ------------------------------------------------
if (1 unmodified line == 0 ):
ratio = ( fraction = ( frame_index / / max( max( 1, process_frames frames_to_process ) )
progress( 0.18 + ratio * 0.70, + fraction * 0.70,
desc=( "Lip syncing " f"{frame_index + 1}/" f"{process_frames}" f"{frames_to_process}" ) )
4 unmodified lines
# ==================================================== # AUDIO # ADD AUDIO # ====================================================
progress(2 unmodified lines )
mux_audio( add_audio( silent_video, audio_path, output_video output_path )
3 unmodified lines
progress( 1.0, desc="Finished!" desc="Completed!" )
file_size = ( size_mb = ( os.path.getsize( output_video ) / ( 1024 * 1024 output_path ) / 1024 / 1024 )
status = ( "## β
Lip-sync completed\n\n" f"**Audio:** `{audio_duration:.2f}s`\n\n" f"**FPS:** `{fps:.2f}`\n\n" f"**Frames processed:** `{process_frames}`\n\n" f"**Face tracking:** `Enabled`\n\n" f"**Mouth-only blending:** `Enabled`\n\n" f"**Output quality:** `CRF {FFMPEG_CRF}`\n\n" f"**File size:** `{file_size:.2f} MB`" f"**Video FPS:** `{fps:.2f}`\n\n" f"**Audio duration:** `{audio_duration:.2f}s`\n\n" f"**Processed frames:** `{frames_to_process}`\n\n" "**Audio mapping:** `80 FPS mel mapping`\n\n" "**Face tracking:** `Enabled`\n\n" "**Soft mouth blending:** `Enabled`\n\n" f"**Video quality:** `CRF {CRF}`\n\n" f"**Output size:** `{size_mb:.2f} MB`" )
if ( text and text.strip() text_input and text_input.strip() ):
status += ( "\n\n### π Text reference\n\n" + text.strip() + text_input.strip() )
return ( output_video, output_path, status )
24 unmodified lines
# ============================================================# GRADIO# CSS# ============================================================
CSS = """2 unmodified lines margin: auto !important;}
#generate { min-height: 58px;#generate-button { min-height: 60px; font-size: 18px; font-weight: 700;}"""
# ============================================================# UI# ============================================================
with gr.Blocks( title="Wav2Lip AI - High Quality Lip Sync") as demo:2 unmodified lines """# π¬ Wav2Lip AI β High Quality Lip Sync
### Upload a video + target audio β generate synchronized speechUpload a source video and target speech audio.The face will be tracked and the mouth synchronizedto the target speech.""" )
gr.Markdown( """**Improved version:** better Wav2Lip audio preprocessing,more accurate frame-to-audio mapping, face tracking,and smooth mouth-only blending to reduce mouth distortion.### Improved pipeline
Correct Wav2Lip-style audio preprocessing β’accurate audio/video mapping β’ face tracking β’soft mouth blending β’ high-quality H.264 output""" )
20 unmodified lines
text_input = gr.Textbox( label="π Audio Text (Optional)", label="π Audio Text β Optional", placeholder=( "Example: Hello, welcome to my video." ),2 unmodified lines
generate_button = gr.Button( "π¬ GENERATE HIGH-QUALITY LIP SYNC", "π¬ GENERATE LIP-SYNC VIDEO", variant="primary", elem_id="generate" elem_id="generate-button" )
4 unmodified lines with gr.Column():
output_video = gr.Video( label="π¬ Lip-Synced Result" label="π¬ Lip-Synced Video" )
status_output = gr.Markdown( label="Status" ) status_output = gr.Markdown()
# ======================================================== # TIPS # INFO # ========================================================
gr.Markdown( """### π‘ For the best mouth quality
- Use **one person** in the video.- Face should be clearly visible.- Front-facing or slightly angled faces work best.- Avoid hands covering the mouth.- Avoid very small faces.- Use clean speech audio.- Keep the video reasonably stable.- The target audio should contain the speech you want the person to perform.
### βοΈ Processing
The system uses the uploaded **audio waveform**, not thetext field, to generate lip movement. The text box is onlyprovided as an optional reference.### π Best input
- One clearly visible face- Face looking toward the camera- Good lighting- Mouth not covered- 720p or higher source video recommended- Clean speech audio- Avoid very fast head movement
**Note:** The text box is only a reference. The actuallip movement is generated from the uploaded audio waveform.""" )
# ======================================================== # BUTTON # EVENT # ========================================================
generate_button.click(19 unmodified linesif __name__ == "__main__":
print("=" * 70) print("Starting Wav2Lip High Quality Gradio Space") print("Starting Wav2Lip Gradio Space") print("=" * 70)
app.py+690-654