Update app.py
Browse files12310 unmodified lines14151617181920212223242520 unmodified lines4647484950515253545556575859606162636465666768697016 unmodified lines87888990919293949596979816 unmodified lines1151161171181191201211221234 unmodified lines1281291301311321331341351361375 unmodified lines14314414514614714815 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881893 unmodified lines1931941951961971981992002012025 unmodified lines2082092102112122132142152162172182192202212222232242252262275 unmodified lines2332342352362372381 unmodified line2402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234246 unmodified lines4314324334344354364374384394404414424434444454464474484494504514524534544554564574581 unmodified line46046146246346446546614 unmodified lines48148248348448548648748848949049149249349449554 unmodified lines55055155255355455555632 unmodified lines5895905915925935942 unmodified lines5975985996006016022 unmodified lines60560660760860961045 unmodified lines65665765865966066166224 unmodified lines6876886896906916926931 unmodified line69569669769869970070145 unmodified lines7477487497507517527533 unmodified lines7577587597607617628 unmodified lines77177277377477577677741 unmodified lines8198208218228238248252 unmodified lines82882983083183283383483583683783822 unmodified lines86186286386486586686730 unmodified lines89889990090190290390490590690790890911 unmodified lines92192292392492592692731 unmodified lines9599609619629639649659669671 unmodified line9699709719729739749759769772 unmodified lines9809819829839849859869879884 unmodified lines993994995996997998999100010011002100310043 unmodified lines10081009101010111012101310141015101621 unmodified lines1038103910401041104210431044104510468 unmodified lines10551056105710581059106010611062106310 unmodified lines1074107510761077107810791080108110821083108410851086108710888 unmodified lines109710981099110011011102110311041105110611071108110911 unmodified lines1121112211231124112511261127112811295 unmodified lines11351136113711381139114011411 unmodified line1143114411451146114711481 unmodified line115011511152115311541155115611 unmodified lines116811691170117111721173117411751176117711781179118011811182118311841185118611871188118917 unmodified lines1207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512 unmodified lines12781279128012811282128312841 unmodified line128612871288128912901291129212931294129512961297129812997 unmodified lines13071308130913101311131213131314131553 unmodified lines136913701371137213731374137513761377137813791380138133 unmodified lines14151416141714181419142014216 unmodified lines14281429143014311432143314341435143614374 unmodified lines14421443144414451446144714481 unmodified line14501451145214531454145514561457145814591460146114627 unmodified lines14701471147214731474147514763 unmodified lines14801481148214831484148514866 unmodified lines1493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715284 unmodified lines153315341535153615371538128 unmodified lines166716681669167016711672167352 unmodified lines17261727172817291730173117323 unmodified lines173617371738173917401741174217431744174517461747174825 unmodified lines1774177517761777177817791780178117821783178417851786178726 unmodified lines181418151816181718181819182015 unmodified lines183618371838183918401841184210 unmodified lines1853185418551856185718581859186018611862186315 unmodified lines187918801881188218831884188544 unmodified lines193019311932193319341935193612 unmodified lines194919501951195219531954195519561957195819591960196119626 unmodified lines196919701971197219731974197525 unmodified lines20012002200320042005200620072008200920102011201212 unmodified lines202520262027202820292030203110 unmodified lines20422043204420452046204720487 unmodified lines205620572058205920602061206240 unmodified lines210321042105210621072108210959 unmodified lines216921702171217221732174217521762177217821792180218121822183218451 unmodified lines22362237223822392240224122425 unmodified lines224822492250225122522253225435 unmodified lines22902291229222932294229522963 unmodified lines230023012302230323042305230619 unmodified lines232623272328232923302331233214 unmodified lines23472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023714 unmodified lines237623772378237923802381238230 unmodified lines241324142415241624172418241911 unmodified lines2431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524667 unmodified lines247424752476247724782479248024812482248324842485248624872488248924902491249224932 unmodified lines24962497249824992500250125026 unmodified lines25092510251125122513251425152 unmodified lines251825192520252125222523252425252526252725282529253025312532253325342535253625372538253913 unmodified lines25532554255525562557255825592 unmodified lines2562256325642565256625672568256925702571import osimport cv2import math10 unmodified lines# ============================================================# CONFIG# ============================================================MODEL_PATH = "wav2lip_models/wav2lip_gan.onnx"OUTPUT_DIR = "outputs"FACE_DIR = "face_detector"FACE_PROTO = os.path.join(20 unmodified lines# ============================================================# QUALITY SETTINGS# ============================================================# Lower value preserves original face texture.# Higher value = stronger generated lips.BLEND_STRENGTH = 0.50# Temporal stabilization.# 0.25-0.40 is good for natural lip movement.TEMPORAL_ALPHA = 0.35# Face tracking.FACE_SMOOTHING = 0.15# Re-detect face every N seconds.REDETECT_SECONDS = 0.50# Padding around detected face.FACE_PADDING = 0.18# ============================================================16 unmodified linesMEL_STEP_SIZE = 16# Wav2Lip uses approximately 80 mel frames/sec.MEL_FPS = 80.0# ============================================================# OUTPUT SETTINGS# ============================================================CRF = 1716 unmodified lines)print("=" * 70)print("Wav2Lip High Quality Lip Sync")print("=" * 70)# ============================================================4 unmodified linesraise FileNotFoundError("\n\n""Wav2Lip ONNX model not found:\n"f"{MODEL_PATH}\n\n""Expected structure:\n""wav2lip_models/wav2lip_gan.onnx\n")5 unmodified linesort.get_available_providers())if "CUDAExecutionProvider" in available_providers:ONNX_PROVIDERS = [15 unmodified lines# ============================================================# LOAD ONNX MODEL# ============================================================print("Loading Wav2Lip ONNX model...")SESSION = ort.InferenceSession(MODEL_PATH,providers=ONNX_PROVIDERS)print("Model loaded successfully.")print("Model inputs:")for inp in SESSION.get_inputs():print(3 unmodified linesinp.type)print("Model outputs:")for out in SESSION.get_outputs():print(5 unmodified lines# ============================================================# DOWNLOAD FACE DETECTOR# ============================================================def download_file(url, path):if os.path.exists(path):returnprint("Downloading:",os.path.basename(path))urllib.request.urlretrieve(url,path5 unmodified linesFACE_PROTO)download_file(FACE_MODEL_URL,FACE_MODEL1 unmodified line# ============================================================# FACE DETECTOR# ============================================================print("Loading OpenCV DNN face detector...")FACE_DETECTOR = cv2.dnn.readNetFromCaffe(FACE_PROTO,FACE_MODEL)print("Face detector loaded.")# ============================================================# TEMPORAL SMOOTHER# ============================================================class MouthTemporalSmoother:def __init__(self,alpha=0.35):self.alpha = alphaself.previous = Nonedef reset(self):self.previous = Nonedef smooth(self,generated,mask):current = generated.astype(np.float32)# ----------------------------------------------------# First frame# ----------------------------------------------------if self.previous is None:self.previous = current.copy()return generated# ----------------------------------------------------# CRITICAL FIX## Previous face crop can have different dimensions.## Example:## 1033 x 1033# 1055 x 1055## Resize previous frame before blending.# ----------------------------------------------------if (self.previous.shape[:2]!=current.shape[:2]):self.previous = cv2.resize(self.previous,(current.shape[1],current.shape[0]),interpolation=cv2.INTER_LINEAR)self.previous = (self.previous.astype(np.float32))# ----------------------------------------------------# Ensure mask matches current frame.# ----------------------------------------------------if (mask.shape[:2]!=current.shape[:2]):mask = cv2.resize(mask.astype(np.float32),(current.shape[1],current.shape[0]),interpolation=cv2.INTER_LINEAR)# ----------------------------------------------------# Temporal smoothing.## This removes the "shadow moving over lips".# ----------------------------------------------------smoothed = (self.previous*self.alpha+current*(1.0-self.alpha))# ----------------------------------------------------# Only stabilize mouth.# ----------------------------------------------------m = mask[..., None]result = (smoothed * m+current * (1.0 - m))result = np.clip(result,0,255).astype(np.uint8)self.previous = (result.astype(np.float32))return resultMOUTH_SMOOTHER = MouthTemporalSmoother(alpha=TEMPORAL_ALPHA)# ============================================================# LOAD AUDIO# ============================================================def load_audio(6 unmodified linesmono=True)if audio is None:raise RuntimeError("Could not load audio.")if len(audio) == 0:raise RuntimeError("Audio file is empty.")audio = audio.astype(np.float32)duration = (len(audio)/SAMPLE_RATE)return (audio,duration1 unmodified line# ============================================================# CREATE MEL# ============================================================def make_mel(14 unmodified linescenter=True)mel = np.maximum(mel,1e-5)mel = np.log10(mel)return mel.astype(np.float32)54 unmodified lines)if confidence < 0.50:continue32 unmodified lines))y1 = max(0,min(2 unmodified lines))x2 = max(0,min(2 unmodified lines))y2 = max(0,min(45 unmodified lines# ============================================================# FIND INITIAL FACE# ============================================================def find_initial_face(24 unmodified linescap.release()raise RuntimeError("Video has no frames.")1 unmodified linesample_count = min(12,total)45 unmodified linesif not boxes:raise RuntimeError("No face detected in video.")3 unmodified lines)median_box = np.median(boxes,axis=08 unmodified lines# ============================================================# SMOOTH FACE POSITION# ============================================================def smooth_face(41 unmodified lines# ============================================================# FIXED CROP SIZE# ============================================================def create_fixed_crop_size(2 unmodified linesframe_height):x, y, w, h = face_boxsize = int(max(w, h)*(1.022 unmodified lines# ============================================================# GET FIXED FACE CROP# ============================================================def get_fixed_face_crop(30 unmodified lines)# Small upward correction.cy -= h_face * 0.02# --------------------------------------------------------# Fixed-size crop.# --------------------------------------------------------x = int(11 unmodified lines# --------------------------------------------------------# Keep inside frame.# --------------------------------------------------------x = max(31 unmodified linesmel_chunk):# ========================================================# BGR -> RGB# ========================================================face_rgb = cv2.cvtColor(face_bgr,1 unmodified line)# ========================================================# 96x96# ========================================================face96 = cv2.resize(face_rgb,2 unmodified lines)# ========================================================# MASK LOWER HALF# ========================================================masked = face96.copy()4 unmodified lines] = 0# ========================================================# 6 CHANNEL INPUT## masked RGB + original RGB# ========================================================input_image = np.concatenate([masked,3 unmodified lines)# ========================================================# HWC -> CHW# ========================================================input_image = (input_image.astype(21 unmodified lines)# ========================================================# MEL# ========================================================mel_input = (mel_chunk[8 unmodified lines)# ========================================================# ONNX# ========================================================outputs = SESSION.run(None,10 unmodified linesprediction = outputs[0]# ========================================================# OUTPUT# ========================================================if prediction.ndim == 4:prediction = prediction[0]if prediction.shape[0] == 3:prediction = (8 unmodified linesraise RuntimeError("Unexpected Wav2Lip output shape: "f"{prediction.shape}")# ========================================================# 0-1 -> 0-255# ========================================================prediction = np.clip(prediction,11 unmodified lines)# ========================================================# RGB -> BGR# ========================================================prediction_bgr = cv2.cvtColor(prediction,5 unmodified lines# ============================================================# PRECISE MOUTH MASK# ============================================================def create_mouth_mask(1 unmodified linewidth):yy, xx = np.mgrid[0:height,0:width1 unmodified line# --------------------------------------------------------# Mouth center.# --------------------------------------------------------cx = (11 unmodified lines# --------------------------------------------------------# Tighter mouth area.## This is important for removing the moving shadow.# --------------------------------------------------------rx = (width*0.25)ry = (height*0.13)17 unmodified linesmask = np.exp(-distance*2.6)# --------------------------------------------------------# Restrict mouth.# --------------------------------------------------------top = int(height*0.57)bottom = int(height*0.87)mask[:top,:] = 0mask[bottom:,:] = 0# --------------------------------------------------------# Soft threshold.# --------------------------------------------------------mask = np.clip((mask-0.08)/0.92,0,1)# --------------------------------------------------------# Smoothstep.# --------------------------------------------------------mask = (12 unmodified lines# --------------------------------------------------------# Feather.# --------------------------------------------------------mask = cv2.GaussianBlur(1 unmodified linenp.float32),(0, 0),2.5)return np.clip(mask,0,1)7 unmodified linesmask):# --------------------------------------------------------# BGR -> LAB# --------------------------------------------------------original_lab = cv2.cvtColor(original_bgr,53 unmodified linesoriginal_l-generated_l) * 0.30# --------------------------------------------------------# COLOR## Prevent blue/purple mouth.# --------------------------------------------------------for channel in (33 unmodified lines] += (difference*0.45)6 unmodified lines)# --------------------------------------------------------# LAB -> BGR# --------------------------------------------------------corrected = cv2.cvtColor(generated_lab,cv2.COLOR_LAB2BGR4 unmodified lines# ============================================================# FINAL FACE BLENDING# ============================================================def blend_face(1 unmodified linegenerated_bgr):h, w = (original_bgr.shape[:2])# --------------------------------------------------------# Resize generated face.# --------------------------------------------------------generated_bgr = cv2.resize(7 unmodified lines# --------------------------------------------------------# Mouth mask.# --------------------------------------------------------mask = create_mouth_mask(3 unmodified lines# --------------------------------------------------------# Color correction.# --------------------------------------------------------generated_bgr = (6 unmodified lines# --------------------------------------------------------# Temporal stabilization.## Only apply it to mouth region.# --------------------------------------------------------temporal_mask = np.clip(mask*0.60,0,1)generated_bgr = (MOUTH_SMOOTHER.smooth(generated_bgr,temporal_mask))# --------------------------------------------------------# Final blending.# --------------------------------------------------------alpha = (mask*BLEND_STRENGTH)4 unmodified lines]original = (original_bgr.astype(np.float32128 unmodified lines)raise RuntimeError("FFmpeg failed to add audio.")52 unmodified lines# ============================================================# MAIN PROCESS# ============================================================def process_video(3 unmodified linesprogress=gr.Progress()):# ========================================================# RESET TEMPORAL MEMORY# ========================================================MOUTH_SMOOTHER.reset()# ========================================================# VALIDATION# ========================================================25 unmodified linesif not video_path:raise gr.Error("Invalid video file.")if not audio_path:raise gr.Error("Invalid audio file.")26 unmodified linesprogress(0.02,desc="Loading audio...")15 unmodified lines# ====================================================progress(0.06,desc="Creating mel spectrogram...")10 unmodified lines# ====================================================# OPEN VIDEO# ====================================================progress(0.10,desc="Opening source video...")15 unmodified lines)if not fps or fps <= 0:fps = 25.044 unmodified lines# ====================================================progress(0.13,desc="Detecting face...")12 unmodified lines# ====================================================# FIX CROP SIZE## THIS PREVENTS:## 1033x1033# 1055x1055## broadcasting error.# ====================================================fixed_crop_size = (6 unmodified linesprint("Fixed face crop size:",fixed_crop_size)25 unmodified linescap.release()raise RuntimeError("Could not create output video.")# ====================================================# PROCESS ONLY AUDIO DURATION# ====================================================audio_frame_count = int(12 unmodified lines# ====================================================# AUDIO -> VIDEO FRAME TIMING# ====================================================mel_idx_multiplier = (10 unmodified lines# ====================================================# FACE REDETECTION INTERVAL# ====================================================redetect_every = max(7 unmodified lines# ====================================================# PROCESS# ====================================================for frame_index in range(40 unmodified lines# =================================================# FIXED-SIZE CROP# =================================================x, y, crop_w, crop_h = (59 unmodified lines# =================================================# EXACT 80x16# =================================================if mel_chunk.shape[1] < 16:if (mel_chunk.shape[1]==0):mel_chunk = np.zeros((51 unmodified lines# =================================================# QUALITY BLEND# =================================================result_face = (5 unmodified lines# =================================================# PUT FACE BACK# =================================================frame[35 unmodified linesfraction*0.70,desc=("Lip syncing "f"{frame_index + 1}/"3 unmodified lines# ====================================================# RELEASE# ====================================================cap.release()19 unmodified lines# ====================================================# FINISHED# ====================================================progress(14 unmodified linesstatus = ("## ✅ Lip Sync Completed\n\n"f"**Source resolution:** "f"`{width} × {height}`\n\n"f"**FPS:** "f"`{fps:.2f}`\n\n"f"**Audio duration:** "f"`{audio_duration:.2f}s`\n\n"f"**Frames processed:** "f"`{frames_to_process}`\n\n"f"**Fixed face crop:** "f"`{fixed_crop_size} × {fixed_crop_size}`\n\n""**Lip color correction:** ✅\n\n""**Blue-mouth protection:** ✅\n\n""**Mouth shadow reduction:** ✅\n\n""**Temporal stabilization:** ✅\n\n""**Face tracking:** ✅\n\n""**Original skin texture:** preserved\n\n"f"**Output size:** "f"`{output_size:.2f} MB`")4 unmodified lines):status += ("\n\n### 📝 Text Reference\n\n"+text_input.strip())30 unmodified lines# ============================================================# CSS# ============================================================CSS = """11 unmodified lines# ============================================================# GRADIO APP# ============================================================with gr.Blocks(title="Wav2Lip AI - High Quality Lip Sync") as demo:gr.Markdown("""# 🎬 Wav2Lip AI — High Quality Lip SyncUpload a source video and target speech audio.The AI will synchronize the mouth with the target audio.""")gr.Markdown("""### ✨ Processing improvements- 👄 More natural visible lips- 🎞️ Temporal mouth stabilization- 🌈 Blue/purple mouth correction- 🧴 Reduced lip shadow/flicker- 🎯 Tight mouth mask- 🎨 LAB color matching- 🎥 Stable face tracking- 🔊 Accurate audio/mel timing- 💎 Original skin texture preserved""")7 unmodified lineswith gr.Column():video_input = gr.Video(label="🎥 Source Video",sources=["upload"])audio_input = gr.Audio(label="🎵 Target Audio",sources=["upload"],type="filepath")text_input = gr.Textbox(label="📝 Audio Text — Optional",placeholder=("Example: Hello, welcome to my video."),2 unmodified linesgenerate_button = gr.Button("🎬 GENERATE LIP-SYNC VIDEO",variant="primary",elem_id="generate-button")6 unmodified lineswith gr.Column():output_video = gr.Video(label="🎬 Lip-Synced Video")2 unmodified linesgr.Markdown("""### 📌 Best results- Face looking toward camera- Lips clearly visible- Good lighting- Minimal motion blur- Clear speech- 720p or higher sourceThe **audio controls the lip movement**. The optional text is only displayed as a reference.""")# ========================================================# BUTTON# ========================================================generate_button.click(13 unmodified lines# ============================================================# LAUNCH# ============================================================if __name__ == "__main__":2 unmodified lines"Starting Wav2Lip Gradio Space...")demo.queue(max_size=5).launch(server_name="0.0.0.0",server_port=7860,css=CSS)123410 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535420 unmodified lines7576777879808182838485868788899091929394959697989910010110216 unmodified lines11912012112212312412512612712812916 unmodified lines1461471481491501511521531544 unmodified lines1591601611621631641651661671681695 unmodified lines17517617717817918018115 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212222232242252263 unmodified lines2302312322332342352362372382392402415 unmodified lines2472482492502512522532542552562572582592602612622632642652662672682692702715 unmodified lines2772782792802812822831 unmodified line2852862872882892902912922932942952962972982993003013023033043053063073083093103116 unmodified lines3183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493501 unmodified line35235335435535635735814 unmodified lines37337437537637737837938038138238338438538638738838939054 unmodified lines44544644744844945045132 unmodified lines4844854864874884894902 unmodified lines4934944954964974984992 unmodified lines50250350450550650750845 unmodified lines55455555655755855956024 unmodified lines5855865875885895905911 unmodified line59359459559659759859945 unmodified lines6456466476486496506513 unmodified lines6556566576586596606616628 unmodified lines67167267367467567667741 unmodified lines7197207217227237247252 unmodified lines72872973073173273373473573673773873974074174274322 unmodified lines76676776876977077177230 unmodified lines80380480580680780880981081181281381481581681781881911 unmodified lines83183283383483583683731 unmodified lines8698708718728738748758768771 unmodified line8798808818828838848858868872 unmodified lines8908918928938948958968978988999009014 unmodified lines9069079089099109119129139149153 unmodified lines91992092192292392492592692721 unmodified lines9499509519529539549559569578 unmodified lines96696796896997097197297397410 unmodified lines98598698798898999099199299399499599699799899910001001100210038 unmodified lines101210131014101510161017101810191020102110221023102410251026102711 unmodified lines1039104010411042104310441045104610475 unmodified lines10531054105510561057105810591 unmodified line10611062106310641065106610671068106910701071107210731074107510761 unmodified line107810791080108110821083108411 unmodified lines1096109710981099110011011102110311041105110611071108110911101111111211131114111517 unmodified lines1133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119112 unmodified lines12041205120612071208120912101 unmodified line1212121312141215121612171218121912201221122212231224122512267 unmodified lines123412351236123712381239124012411242124312441245124612471248124953 unmodified lines13031304130513061307130813091310131113121313131433 unmodified lines13481349135013511352135313546 unmodified lines1361136213631364136513664 unmodified lines13711372137313741375137613771 unmodified line13791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514067 unmodified lines14141415141614171418141914203 unmodified lines14241425142614271428142914306 unmodified lines143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514864 unmodified lines1491149214931494149514961497149814991500128 unmodified lines16291630163116321633163416351636163752 unmodified lines16901691169216931694169516963 unmodified lines17001701170217031704170525 unmodified lines1731173217331734173517361737173817391740174117421743174426 unmodified lines177117721773177417751776177715 unmodified lines179317941795179617971798179910 unmodified lines1810181118121813181418151816181718181819182015 unmodified lines1836183718381839184018411842184318441845184644 unmodified lines189118921893189418951896189712 unmodified lines19101911191219131914191519166 unmodified lines19231924192519261927192819291930193125 unmodified lines19571958195919601961196219631964196519661967196812 unmodified lines198119821983198419851986198710 unmodified lines19981999200020012002200320047 unmodified lines201220132014201520162017201840 unmodified lines205920602061206220632064206559 unmodified lines21252126212721282129213021312132213321342135213651 unmodified lines21882189219021912192219321945 unmodified lines220022012202220322042205220635 unmodified lines2242224322442245224622473 unmodified lines225122522253225422552256225719 unmodified lines227722782279228022812282228314 unmodified lines2298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023214 unmodified lines2326232723282329233023312332233330 unmodified lines236423652366236723682369237011 unmodified lines2382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624177 unmodified lines242524262427242824292430243124322433243424352436243724382439244024412442244324442 unmodified lines24472448244924502451245224536 unmodified lines24602461246224632464246524662 unmodified lines246924702471247224732474247524762477247824792480248124822483248424852486248713 unmodified lines25012502250325042505250625072 unmodified lines25102511251225132514251525162517251825192520import osimport cv2import math10 unmodified lines# ============================================================# WAV2LIP HIGH QUALITY - GHOST FREE VERSION# ============================================================## IMPORTANT:## This version DOES NOT temporally blend generated mouth frames.## Previous approach:## previous_generated_mouth# +# current_generated_mouth# =# ghost / persistence artifact## New approach:## original frame# +# current generated mouth only# =# stable mouth## ============================================================# ============================================================# CONFIGURATION# ============================================================MODEL_PATH = "wav2lip_models/wav2lip_gan.onnx"OUTPUT_DIR = "outputs"FACE_DIR = "face_detector"FACE_PROTO = os.path.join(20 unmodified lines# ============================================================# VIDEO / FACE SETTINGS# ============================================================FACE_CONFIDENCE = 0.50FACE_SMOOTHING = 0.12REDETECT_SECONDS = 0.40FACE_PADDING = 0.20# ============================================================# MOUTH COMPOSITING# ============================================================# Strong enough to prevent the original lip edges# from showing through the generated mouth.## This is intentionally NOT 1.0 because some original# texture should remain.MOUTH_STRENGTH = 0.78# ============================================================16 unmodified linesMEL_STEP_SIZE = 16MEL_FPS = 80.0# ============================================================# OUTPUT ENCODING# ============================================================CRF = 1716 unmodified lines)print("=" * 72)print("Wav2Lip High Quality - Ghost Free Mouth")print("=" * 72)# ============================================================4 unmodified linesraise FileNotFoundError("\n\n""Wav2Lip ONNX model not found:\n\n"f"{MODEL_PATH}\n\n""Your Space should contain:\n\n""wav2lip_models/\n"" wav2lip_gan.onnx\n")5 unmodified linesort.get_available_providers())if "CUDAExecutionProvider" in available_providers:ONNX_PROVIDERS = [15 unmodified lines# ============================================================# LOAD WAV2LIP ONNX# ============================================================print("Loading Wav2Lip ONNX model...")SESSION = ort.InferenceSession(MODEL_PATH,providers=ONNX_PROVIDERS)print("Model loaded successfully.")print("Model inputs:")for inp in SESSION.get_inputs():print(3 unmodified linesinp.type)print("Model outputs:")for out in SESSION.get_outputs():print(5 unmodified lines# ============================================================# DOWNLOAD OPENCV FACE MODEL# ============================================================def download_file(url,path):if os.path.exists(path):returnprint("Downloading:",os.path.basename(path))urllib.request.urlretrieve(url,path5 unmodified linesFACE_PROTO)download_file(FACE_MODEL_URL,FACE_MODEL1 unmodified line# ============================================================# LOAD FACE DETECTOR# ============================================================print("Loading OpenCV DNN face detector...")FACE_DETECTOR = cv2.dnn.readNetFromCaffe(FACE_PROTO,FACE_MODEL)print("Face detector loaded.")# ============================================================# AUDIO LOADER# ============================================================def load_audio(6 unmodified linesmono=True)if audio is None:raise RuntimeError("Could not load audio.")if len(audio) == 0:raise RuntimeError("Audio file is empty.")audio = audio.astype(np.float32)duration = (len(audio)/SAMPLE_RATE)return (audio,duration1 unmodified line# ============================================================# MEL SPECTROGRAM# ============================================================def make_mel(14 unmodified linescenter=True)mel = np.maximum(mel,1e-5)mel = np.log10(mel)return mel.astype(np.float32)54 unmodified lines)if confidence < FACE_CONFIDENCE:continue32 unmodified lines))y1 = max(0,min(2 unmodified lines))x2 = max(0,min(2 unmodified lines))y2 = max(0,min(45 unmodified lines# ============================================================# INITIAL FACE# ============================================================def find_initial_face(24 unmodified linescap.release()raise RuntimeError("Video contains no frames.")1 unmodified linesample_count = min(15,total)45 unmodified linesif not boxes:raise RuntimeError("No face was detected.")3 unmodified lines)# Median is more stable than selecting# the first detected face.median_box = np.median(boxes,axis=08 unmodified lines# ============================================================# FACE TRACKING SMOOTHING# ============================================================def smooth_face(41 unmodified lines# ============================================================# FIXED FACE CROP SIZE# ============================================================def create_fixed_crop_size(2 unmodified linesframe_height):x, y, w, h = (face_box)size = int(max(w,h)*(1.022 unmodified lines# ============================================================# FIXED FACE CROP# ============================================================def get_fixed_face_crop(30 unmodified lines)# Tiny upward correction.# Keeps mouth position consistent.cy -= (h_face*0.015)# --------------------------------------------------------# Fixed square crop# --------------------------------------------------------x = int(11 unmodified lines# --------------------------------------------------------# Clamp# --------------------------------------------------------x = max(31 unmodified linesmel_chunk):# --------------------------------------------------------# BGR -> RGB# --------------------------------------------------------face_rgb = cv2.cvtColor(face_bgr,1 unmodified line)# --------------------------------------------------------# 96x96# --------------------------------------------------------face96 = cv2.resize(face_rgb,2 unmodified lines)# --------------------------------------------------------# Wav2Lip masking## Lower half is masked and original image# is concatenated as second 3 channels.# --------------------------------------------------------masked = face96.copy()4 unmodified lines] = 0# 6 channels:## [masked RGB][original RGB]#input_image = np.concatenate([masked,3 unmodified lines)# --------------------------------------------------------# HWC -> CHW# --------------------------------------------------------input_image = (input_image.astype(21 unmodified lines)# --------------------------------------------------------# MEL# --------------------------------------------------------mel_input = (mel_chunk[8 unmodified lines)# --------------------------------------------------------# ONNX# --------------------------------------------------------outputs = SESSION.run(None,10 unmodified linesprediction = outputs[0]# --------------------------------------------------------# Remove batch# --------------------------------------------------------if prediction.ndim == 4:prediction = prediction[0]# --------------------------------------------------------# CHW -> HWC# --------------------------------------------------------if prediction.shape[0] == 3:prediction = (8 unmodified linesraise RuntimeError("Unexpected Wav2Lip output shape: "+str(prediction.shape))# --------------------------------------------------------# 0..1 -> 0..255# --------------------------------------------------------prediction = np.clip(prediction,11 unmodified lines)# --------------------------------------------------------# RGB -> BGR# --------------------------------------------------------prediction_bgr = cv2.cvtColor(prediction,5 unmodified lines# ============================================================# TIGHT MOUTH MASK# ============================================================def create_mouth_mask(1 unmodified linewidth):"""Creates a tight mouth mask.IMPORTANT:The mask is intentionally smaller than the previousversion to prevent the generated lips from leakinginto cheeks/chin/nose areas."""yy, xx = np.mgrid[0:height,0:width1 unmodified line# --------------------------------------------------------# Mouth center# --------------------------------------------------------cx = (11 unmodified lines# --------------------------------------------------------# Mouth dimensions# --------------------------------------------------------rx = (width*0.215)ry = (height*0.108)17 unmodified linesmask = np.exp(-distance*3.2)# --------------------------------------------------------# Hard limits# --------------------------------------------------------top = int(height*0.585)bottom = int(height*0.845)mask[:top,:] = 0.0mask[bottom:,:] = 0.0# --------------------------------------------------------# Remove weak outer area# --------------------------------------------------------mask = np.clip((mask-0.10)/0.90,0.0,1.0)# --------------------------------------------------------# Smoothstep# --------------------------------------------------------mask = (12 unmodified lines# --------------------------------------------------------# Feather only the boundary# --------------------------------------------------------mask = cv2.GaussianBlur(1 unmodified linenp.float32),(0, 0),sigmaX=2.2,sigmaY=2.2)return np.clip(mask,0.0,1.0)7 unmodified linesmask):"""Match generated mouth color to original face.This helps eliminate:blue lipspurple lipsgray lipsoversaturated lips"""original_lab = cv2.cvtColor(original_bgr,53 unmodified linesoriginal_l-generated_l)* 0.35# --------------------------------------------------------# A/B COLOR# --------------------------------------------------------for channel in (33 unmodified lines] += (difference*0.50)6 unmodified lines)corrected = cv2.cvtColor(generated_lab,cv2.COLOR_LAB2BGR4 unmodified lines# ============================================================# GHOST-FREE FACE BLENDING# ============================================================def blend_face(1 unmodified linegenerated_bgr):"""IMPORTANT:There is NO temporal frame blending here.We only use:original current frame+current Wav2Lip generated mouthThis eliminates persistence-of-vision artifacts."""h, w = (original_bgr.shape[:2])# --------------------------------------------------------# Resize current generated face# --------------------------------------------------------generated_bgr = cv2.resize(7 unmodified lines# --------------------------------------------------------# Mouth mask# --------------------------------------------------------mask = create_mouth_mask(3 unmodified lines# --------------------------------------------------------# Color correction# --------------------------------------------------------generated_bgr = (6 unmodified lines# --------------------------------------------------------# IMPORTANT:## NO:## previous * alpha# +# current * (1-alpha)## because that causes ghost lips.# --------------------------------------------------------# --------------------------------------------------------# Strong current-frame mouth# --------------------------------------------------------alpha = (mask*MOUTH_STRENGTH)# --------------------------------------------------------# Very small edge feather## Do NOT over-blur.# Over-blurring creates moving shadow.# --------------------------------------------------------alpha = cv2.GaussianBlur(alpha.astype(np.float32),(0, 0),sigmaX=1.3,sigmaY=1.3)alpha = np.clip(alpha,0.0,MOUTH_STRENGTH)4 unmodified lines]# --------------------------------------------------------# Float blending# --------------------------------------------------------original = (original_bgr.astype(np.float32128 unmodified lines)raise RuntimeError("FFmpeg failed:\n"+result.stderr[-3000:])52 unmodified lines# ============================================================# MAIN PROCESSING FUNCTION# ============================================================def process_video(3 unmodified linesprogress=gr.Progress()):# ========================================================# VALIDATION# ========================================================25 unmodified linesif not video_path:raise gr.Error("Invalid source video.")if not audio_path:raise gr.Error("Invalid target audio.")26 unmodified linesprogress(0.02,desc="Loading target audio...")15 unmodified lines# ====================================================progress(0.05,desc="Creating mel spectrogram...")10 unmodified lines# ====================================================# VIDEO# ====================================================progress(0.09,desc="Opening source video...")15 unmodified lines)if (not fpsorfps <= 0):fps = 25.044 unmodified lines# ====================================================progress(0.12,desc="Detecting face...")12 unmodified lines# ====================================================# FIXED CROP# ====================================================fixed_crop_size = (6 unmodified linesprint("Fixed face crop:",fixed_crop_size,"x",fixed_crop_size)25 unmodified linescap.release()raise RuntimeError("Could not create temporary video.")# ====================================================# NUMBER OF FRAMES# ====================================================audio_frame_count = int(12 unmodified lines# ====================================================# AUDIO -> VIDEO TIMING# ====================================================mel_idx_multiplier = (10 unmodified lines# ====================================================# FACE RE-DETECTION# ====================================================redetect_every = max(7 unmodified lines# ====================================================# FRAME LOOP# ====================================================for frame_index in range(40 unmodified lines# =================================================# FIXED FACE CROP# =================================================x, y, crop_w, crop_h = (59 unmodified lines# =================================================# FORCE EXACT 80x16# =================================================if mel_chunk.shape[1] < 16:if mel_chunk.shape[1] == 0:mel_chunk = np.zeros((51 unmodified lines# =================================================# GHOST-FREE COMPOSITING# =================================================result_face = (5 unmodified lines# =================================================# PLACE CURRENT FACE BACK# =================================================frame[35 unmodified linesfraction*0.70,desc=("Lip syncing "f"{frame_index + 1}/"3 unmodified lines# ====================================================# CLOSE VIDEO# ====================================================cap.release()19 unmodified lines# ====================================================# COMPLETE# ====================================================progress(14 unmodified linesstatus = ("## Lip Sync Completed\n\n"f"**Resolution:** "f"`{width} × {height}`\n\n"f"**FPS:** "f"`{fps:.2f}`\n\n"f"**Audio:** "f"`{audio_duration:.2f}s`\n\n"f"**Frames:** "f"`{frames_to_process}`\n\n"f"**Face crop:** "f"`{fixed_crop_size} × {fixed_crop_size}`\n\n""**Ghost-mouth temporal blending:** OFF\n\n""**Current-frame mouth:** ON\n\n""**Blue/purple correction:** ON\n\n""**Tight mouth mask:** ON\n\n""**Face tracking:** ON\n\n""**Original skin texture:** preserved\n\n"f"**Output:** `{output_size:.2f} MB`")4 unmodified lines):status += ("\n\n""### Audio Text\n\n"+text_input.strip())30 unmodified lines# ============================================================# GRADIO CSS# ============================================================CSS = """11 unmodified lines# ============================================================# GRADIO UI# ============================================================with gr.Blocks(title="Wav2Lip AI - Ghost Free High Quality") as demo:gr.Markdown("""# Wav2Lip AI — High Quality Lip SyncUpload a source video and target speech audio.The generated video synchronizes the mouth with the target audio.""")gr.Markdown("""### Improvements in this version- Ghost / persistence-of-vision reduction- No previous generated-mouth blending- Current-frame-only lip generation- Tight mouth mask- Natural lip visibility- Blue/purple mouth correction- Stable face tracking- 4K source support- Accurate mel-to-frame timing""")7 unmodified lineswith gr.Column():video_input = gr.Video(label="Source Video",sources=["upload"])audio_input = gr.Audio(label="Target Audio",sources=["upload"],type="filepath")text_input = gr.Textbox(label="Audio Text - Optional",placeholder=("Example: Hello, welcome to my video."),2 unmodified linesgenerate_button = gr.Button("GENERATE LIP-SYNC VIDEO",variant="primary",elem_id="generate-button")6 unmodified lineswith gr.Column():output_video = gr.Video(label="Lip-Synced Video")2 unmodified linesgr.Markdown("""### Best inputFor the best result, use a video where the face is relativelyfront-facing, the mouth is visible, and lighting is consistent.The optional text field is only a reference. The uploaded audiocontrols the actual lip movement.""")# ========================================================# EVENT# ========================================================generate_button.click(13 unmodified lines# ============================================================# START SERVER# ============================================================if __name__ == "__main__":2 unmodified lines"Starting Wav2Lip Gradio Space...")demo.queue(max_size=5).launch(server_name="0.0.0.0",server_port=7860,css=CSS)
app.py+324-375