Update app.py
Browse files13 unmodified lines1415161718192030 unmodified lines5152535455565758596061626364656667686970717273747516 unmodified lines92939495969798991001011021031041055 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713820 unmodified lines1591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242259 unmodified lines2352362372382392402412422432442452462472482492502512522532542552562572582592602616 unmodified lines2682692702712722732742752762776 unmodified lines2842852862872882892902912922932942952962972982993001 unmodified line3023033043053063073083093103113125 unmodified lines31831932032132232316 unmodified lines3403413423433443453463473486 unmodified lines35535635735835936036154 unmodified lines4164174184194204214221 unmodified line42442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947024 unmodified lines49549649749849950050150250350450550650719 unmodified lines5275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695702 unmodified lines5735745755765775785795805815825835845855865875885895901 unmodified line5925935945955965975987 unmodified lines60660760860961061161224 unmodified lines6376386396406416426436446456466476486496503 unmodified lines65465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969015 unmodified lines7067077087097107117127137147156 unmodified lines7227237247257267277287297307317327337347357367377387397407413 unmodified lines7457467477487497507517527531 unmodified line75575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478513 unmodified lines7998008018028038048058068078088098108118128138148158168 unmodified lines82582682782882983083183283383414 unmodified lines8498508518528538548558568578588598608618628638642 unmodified lines8678688698708718728738748751 unmodified line8778788798808818826 unmodified lines88989089189289389489589689789889990090190290390415 unmodified lines9209219229239249259269279289299309319329339349359369379389396 unmodified lines94694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698714 unmodified lines1002100310041005100610071008100910101011101211 unmodified lines1024102510261027102810291030103110321033103410351036103710381039104023 unmodified lines1064106510661067106810691070107110721073107430 unmodified lines110511061107110811091110111113 unmodified lines11251126112711281129113011312 unmodified lines11341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211733 unmodified lines11771178117911801181118211832 unmodified lines118611871188118911901191119211931194119511961197119811991200120112028 unmodified lines12111212121312141215121651 unmodified lines12681269127012711272127312741275127612771278127912807 unmodified lines12881289129012911292129312945 unmodified lines13001301130213031304130513061307130813099 unmodified lines131913201321132213231324132510 unmodified lines13361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138926 unmodified lines141614171418141914201421142214231424142514261427142818 unmodified lines144714481449145014511452145313 unmodified lines146714681469147014711472147311 unmodified lines148514861487148814891490149110 unmodified lines150215031504150515061507150832 unmodified lines154115421543154415451546154715481549155015511552155311 unmodified lines156515661567156815691570157115721 unmodified line1574157515761577157815791580158115821583158415851586158717 unmodified lines160516061607160816091610161116121613161416151616161716183 unmodified lines162216231624162516261627162816291630163116321633163416351636163716381639164016411642164310 unmodified lines16541655165616571658165916609 unmodified lines16701671167216731674167516764 unmodified lines1681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817192 unmodified lines172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618076 unmodified lines18141815181618171818181918204 unmodified lines18251826182718281829183018311832183318341835183612 unmodified lines18491850185118521853185418553 unmodified lines185918601861186218631864186518661867186818691870187118721873187418751876187718781 unmodified line1880188118821883188418851886188718881889189018913 unmodified lines1895189618971898189919001901190219031904190519061907190819094 unmodified lines1914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619373 unmodified lines194119421943194419451946194726 unmodified lines197419751976197719781979198011 unmodified lines1992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202336 unmodified lines20602061206220632064206520662067206820692070207120722073207420752076207713 unmodified lines# ============================================================# CONFIG# ============================================================MODEL_PATH = "wav2lip_models/wav2lip_gan.onnx"30 unmodified linesFACE_CONFIDENCE = 0.50FACE_PADDING = 0.20FACE_SMOOTHING = 0.15REDETECT_SECONDS = 0.40# ============================================================# MOUTH SETTINGS# ============================================================# DO NOT TEMPORALLY BLEND MOUTHS.## This is intentionally current-frame only.MOUTH_STRENGTH = 0.82# ============================================================# AUDIO / MEL SETTINGS# ============================================================SAMPLE_RATE = 1600016 unmodified lines# ============================================================# ENCODING# ============================================================CRF = 17PRESET = "medium"os.makedirs(OUTPUT_DIR,exist_ok=True5 unmodified lines)print("=" * 70)print("Wav2Lip High Quality - Ghost Free")print("=" * 70)# ============================================================# MODEL CHECK# ============================================================if not os.path.exists(MODEL_PATH):raise FileNotFoundError("\nWav2Lip ONNX model not found:\n\n"f"{MODEL_PATH}\n\n""Required structure:\n\n""wav2lip_models/\n"" wav2lip_gan.onnx\n")# ============================================================# ONNX# ============================================================available_providers = (20 unmodified lines)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(" ",inp.name,inp.shape,inp.type)print("Model outputs:")for out in SESSION.get_outputs():print(" ",out.name,out.shape,out.type)# ============================================================# DOWNLOAD FACE DETECTOR# ============================================================def download_file(url,path):if os.path.exists(path):returnprint("Downloading:",os.path.basename(path))urllib.request.urlretrieve(url,path)9 unmodified lines# ============================================================# FACE DETECTOR# ============================================================print("Loading OpenCV DNN face detector...")FACE_DETECTOR = cv2.dnn.readNetFromCaffe(FACE_PROTO,FACE_MODEL)print("Face detector loaded.")# ============================================================# AUDIO# ============================================================def load_audio(6 unmodified linesmono=True)if audio is None or len(audio) == 0:raise RuntimeError("Audio file is empty or could not be loaded.")audio = audio.astype(6 unmodified linesSAMPLE_RATE)return audio, duration# ============================================================# MEL SPECTROGRAM# ============================================================def make_mel(audio):mel = librosa.feature.melspectrogram(y=audio,sr=SAMPLE_RATE,1 unmodified linehop_length=HOP_LENGTH,win_length=WIN_LENGTH,window="hann",n_mels=N_MELS,fmin=FMIN,fmax=FMAX,power=1.0,center=True)mel = np.maximum(5 unmodified linesmel)return mel.astype(np.float32)16 unmodified linesframe,(300, 300)),1.0,(300, 300),(104, 177, 123),swapRB=False,crop=False)6 unmodified linesFACE_DETECTOR.forward())best_box = Nonebest_score = 0.054 unmodified lines)x2 = max(0,min(x2,frame_w1 unmodified line)y2 = max(0,min(y2,frame_h))bw = x2 - x1bh = y2 - y1if bw < 40 or bh < 40:continuearea = (bw * bh)score = (confidence*math.sqrt(area))if score > best_score:best_score = scorebest_box = (x1,y1,bw,bh)return best_box# ============================================================# INITIAL FACE# ============================================================def find_initial_face(24 unmodified lines"Video contains no frames.")boxes = []sample_count = min(15,total)for i in range(sample_count):19 unmodified linescontinuebox = detect_face(frame)if box is not None:boxes.append(box)cap.release()if not boxes:raise RuntimeError("No face was detected in the video.")boxes = np.asarray(boxes,dtype=np.float32)median_box = np.median(boxes,axis=0)return tuple(median_box.astype(int))# ============================================================# FACE TRACKING# ============================================================def smooth_face(old_box,new_box):2 unmodified linesreturn new_boxold_box = np.asarray(old_box,dtype=np.float32)new_box = np.asarray(new_box,dtype=np.float32)result = (old_box*(1.01 unmodified lineFACE_SMOOTHING)+new_box*FACE_SMOOTHING)7 unmodified lines# FIXED CROP SIZE# ============================================================def create_fixed_crop_size(face_box,frame_width,frame_height24 unmodified linesframe_height)return int(size)# ============================================================# FIXED FACE CROP# ============================================================def get_fixed_face_crop(frame,face_box,crop_size3 unmodified linesframe.shape[:2])x_face, y_face, w_face, h_face = (face_box)cx = (x_face+w_face / 2.0)cy = (y_face+h_face / 2.0)# Tiny upward adjustment.cy -= (h_face*0.015)x = int(cx-crop_size / 2)y = int(cy-crop_size / 2)15 unmodified lines)return (int(x),int(y),int(crop_size),int(crop_size))6 unmodified linesmel_chunk):# BGR -> RGBface_rgb = cv2.cvtColor(face_bgr,cv2.COLOR_BGR2RGB)# 96x96face96 = cv2.resize(face_rgb,(96, 96),interpolation=cv2.INTER_AREA)# Mask lower half.masked = face96.copy()masked[3 unmodified lines# 6 channels:## masked RGB + original RGB#input_image = np.concatenate([masked,face961 unmodified lineaxis=2)input_image = (input_image.astype(np.float32)/255.0)input_image = (input_image.transpose(2,0,1))input_image = (input_image[None,...])# --------------------------------------------------------# Mel input# --------------------------------------------------------mel_input = (13 unmodified lines# --------------------------------------------------------outputs = SESSION.run(None,{"mel_spectrogram":mel_input,"video_frames":input_image})prediction = outputs[0]if prediction.ndim == 4:prediction = prediction[0]8 unmodified lines))else:raise RuntimeError("Unexpected ONNX output shape: "+str(prediction.shape14 unmodified linesnp.uint8)prediction_bgr = cv2.cvtColor(prediction,cv2.COLOR_RGB2BGR)return prediction_bgr# ============================================================# MOUTH MASK# ============================================================def create_mouth_mask(2 unmodified lines):"""Tight mouth-only mask.No temporal smoothing is performed."""yy, xx = np.mgrid[1 unmodified line0:width]cx = (width*6 unmodified lines0.715)rx = (width*0.215)ry = (height*0.108)distance = (15 unmodified linesmask = np.exp(-distance*3.2)# Geographic limitstop = int(height*0.585)bottom = int(height*0.845)mask[6 unmodified lines:] = 0.0# Remove weak outer pixelsmask = np.clip((mask-0.10)/0.90,0.0,1.0)# Smoothstepmask = (mask*mask*(3.0-2.0*mask))# Small edge feather onlymask = cv2.GaussianBlur(mask.astype(np.float32),(0, 0),sigmaX=1.8,sigmaY=1.8)return np.clip(14 unmodified lines):"""Correct blue/purple/gray mouth color.NOTE:All multiplication is deliberately insideparentheses to avoid the previous SyntaxError."""original_lab = cv2.cvtColor(11 unmodified lines)strong = (mask > 0.45)if np.count_nonzero(strong) < 100:return generated_bgr# --------------------------------------------------------# L channel# --------------------------------------------------------original_l = np.median(23 unmodified linesgenerated_l)*0.35)# --------------------------------------------------------# A/B channels# --------------------------------------------------------for channel in (30 unmodified lines] += (difference*0.50)generated_lab = np.clip(13 unmodified lines# ============================================================# GHOST-FREE BLENDING# ============================================================def blend_face(2 unmodified lines):"""CRITICAL:There is NO previous-frame blending here.This function only combines:current original frame+current generated mouthThis prevents the persistence-of-vision artifact."""h, w = (original_bgr.shape[:2])# Make absolutely sure dimensions match.generated_bgr = cv2.resize(generated_bgr,(w,h),interpolation=cv2.INTER_CUBIC)# Current frame mouth mask.mask = create_mouth_mask(h,w)# Color correction.generated_bgr = (correct_generated_color(original_bgr,3 unmodified lines)# --------------------------------------------------------# CURRENT FRAME ONLY# --------------------------------------------------------alpha = (2 unmodified linesMOUTH_STRENGTH)# Very small feather.## Do not use large blur here.# Large blur can create another moving shadow.alpha = cv2.GaussianBlur(alpha.astype(np.float32),(0, 0),sigmaX=1.2,sigmaY=1.2)alpha = np.clip(8 unmodified linesNone]original = (original_bgr.astype(np.float3251 unmodified lines# ============================================================# MUX AUDIO# ============================================================def mux_audio(silent_video,audio,output):ffmpeg = get_ffmpeg()7 unmodified linessilent_video,"-i",audio,"-map","0:v:0",5 unmodified lines"libx264","-preset",PRESET,"-crf",str(CRF),"-pix_fmt","yuv420p",9 unmodified lines"-movflags","+faststart",output]result = subprocess.run(10 unmodified lines)raise RuntimeError("FFmpeg failed:\n"+result.stderr[-3000:])# ============================================================# GRADIO PATH HELPERS# ============================================================def get_video_path(video_input):if isinstance(video_input,dict):return (video_input.get("path")orvideo_input.get("name"))return video_inputdef get_audio_path(audio_input):if isinstance(audio_input,dict):return (audio_input.get("path")oraudio_input.get("name"))return audio_input# ============================================================# MAIN# ============================================================def process_video(26 unmodified linesif not video_path:raise gr.Error("Invalid source video.")if not audio_path:raise gr.Error("Invalid target audio.")work_dir = tempfile.mkdtemp(18 unmodified linesprogress(0.02,desc="Loading audio...")audio, audio_duration = (13 unmodified linesprogress(0.05,desc="Creating mel spectrogram...")mel = make_mel(11 unmodified linesprogress(0.08,desc="Opening video...")cap = cv2.VideoCapture(10 unmodified linescv2.CAP_PROP_FPS)if not fps or fps <= 0:fps = 25.032 unmodified linestotal_frames)# ====================================================# FACE# ====================================================progress(0.12,desc="Detecting face...")current_face = (11 unmodified lines# FIXED CROP# ====================================================fixed_crop_size = (create_fixed_crop_size(current_face,width,height1 unmodified line)print("Fixed crop:",fixed_crop_size,"x",fixed_crop_size)# ====================================================# WRITER# ====================================================fourcc = (17 unmodified linescap.release()raise RuntimeError("Could not create temporary video.")# ====================================================# FRAME COUNT# ====================================================audio_frame_count = int(math.ceil(audio_duration*3 unmodified linesframes_to_process = min(total_frames,audio_frame_count)# ====================================================# MEL TIMING# ====================================================mel_idx_multiplier = (MEL_FPS/fps)print("Mel index multiplier:",mel_idx_multiplier)# ====================================================10 unmodified lines)# ====================================================# PROCESS# ====================================================for frame_index in range(9 unmodified linesbreak# ------------------------------------------------# Face tracking# ------------------------------------------------if (4 unmodified lines0):detected_face = (detect_face(frame))if detected_face is not None:current_face = (smooth_face(current_face,detected_face))# ------------------------------------------------# Fixed crop# ------------------------------------------------x, y, crop_w, crop_h = (get_fixed_face_crop(frame,current_face,fixed_crop_size))face = frame[y:y + crop_h,x:x + crop_w]if face.size == 0:writer.write(frame2 unmodified linescontinue# ------------------------------------------------# Audio position# ------------------------------------------------mel_start = int(frame_index*mel_idx_multiplier)max_start = max(0,mel.shape[1]-MEL_STEP_SIZE)mel_start = min(mel_start,max_start)mel_end = (mel_start+MEL_STEP_SIZE)mel_chunk = mel[:,mel_start:mel_end]# ------------------------------------------------# Exact 80x16# ------------------------------------------------if mel_chunk.shape[1] < 16:if mel_chunk.shape[1] == 0:mel_chunk = np.zeros((80,16),dtype=np.float32)else:missing = (16-mel_chunk.shape[1])mel_chunk = np.pad(mel_chunk,((0,0),(0,missing)),mode="edge")elif mel_chunk.shape[1] > 16:mel_chunk = (mel_chunk[:,:16])# ------------------------------------------------# Wav2Lip# ------------------------------------------------6 unmodified lines)# ------------------------------------------------# Ghost-free blending# ------------------------------------------------result_face = (4 unmodified lines)# ------------------------------------------------# Put face back# ------------------------------------------------frame[y:y + crop_h,x:x + crop_w] = result_facewriter.write(12 unmodified lines0):fraction = (frame_index/max(3 unmodified lines)progress(0.18+fraction*0.70,desc=("Lip syncing "f"{frame_index + 1}/"f"{frames_to_process}"))# ====================================================# CLOSE# ====================================================cap.release()1 unmodified linewriter.release()# ====================================================# AUDIO# ====================================================progress(0.92,desc="Adding audio...")mux_audio(3 unmodified lines)# ====================================================# COMPLETE# ====================================================progress(1.0,desc="Completed!")output_size = (os.path.getsize(output_video)4 unmodified lines)status = ("## β 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""**Tight mouth mask:** ON\n\n""**Color correction:** ON\n\n""**Face tracking:** ON\n\n""**Original face texture:** preserved\n\n"f"**Output size:** `{output_size:.2f} MB`")if (3 unmodified lines):status += ("\n\n### Audio Text\n\n"+text_input.strip())26 unmodified lines# ============================================================# CSS# ============================================================CSS = """11 unmodified lines# ============================================================# GRADIO# ============================================================with gr.Blocks(title="Wav2Lip AI - Ghost Free") as demo:gr.Markdown("""# π¬ Wav2Lip AI β High Quality Lip SyncUpload a source video and target speech audio.""")gr.Markdown("""### Features- π Current-frame-only lip generation- π« No temporal mouth blending- π« No persistence-of-vision mouth ghost- π¨ Mouth color correction- π€ Face tracking- π₯ 4K source video support- π Target audio synchronization""")36 unmodified linesgr.Markdown("""### Best resultsUse a video with:- one clearly visible face- front-facing or slightly angled face- visible lips- good lighting- minimal camera movementThe **uploaded audio** controls the actual lip movement.The text field is informational only.""")13 unmodified lines1415161718192030 unmodified lines51525354555657585960616263646566676869707172737475767778798016 unmodified lines9798991001011021031041051061071081091101111121131145 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814920 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083099 unmodified lines3193203213223233243253263273283293303313323333343353363373383393403413423436 unmodified lines3503513523533543553563573583593603613623633643656 unmodified lines3723733743753763773783793803813823833843853863873883893903913923933943953963973981 unmodified line4004014024034044054064074084094104115 unmodified lines41741841942042142242342442542642742842916 unmodified lines4464474484494504514524534546 unmodified lines46146246346446546646754 unmodified lines5225235245255265275281 unmodified line53053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557624 unmodified lines60160260360460560660760860961061161261319 unmodified lines6336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756762 unmodified lines6796806816826836846856866876886896906916926936946956961 unmodified line6986997007017027037047 unmodified lines71271371471571671771824 unmodified lines7437447457467477487497507517527537547557563 unmodified lines76076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579615 unmodified lines8128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928936 unmodified lines9009019029039049059069079089099109119129139149159169179189199209219229239243 unmodified lines9289299309319329339349359369379381 unmodified line94094194294394494594694794894995095195295395495595695795895996096196296396496596696796896913 unmodified lines9839849859869879889899909919929939949959969979989991000100110021003100410058 unmodified lines1014101510161017101810191020102110221023102410251026102714 unmodified lines10421043104410451046104710481049105010511052105310541055105610572 unmodified lines1060106110621063106410651066106710681 unmodified line10701071107210731074107510761077107810796 unmodified lines1086108710881089109010911092109310941095109610971098109911001101110215 unmodified lines111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911406 unmodified lines1147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117814 unmodified lines11931194119511961197119811991200120112021203120412051206120711 unmodified lines1219122012211222122312241225122612271228122912301231123212331234123523 unmodified lines1259126012611262126312641265126612671268126930 unmodified lines130013011302130313041305130613 unmodified lines13201321132213231324132513262 unmodified lines13291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913803 unmodified lines13841385138613871388138913902 unmodified lines1393139413951396139713981399140014011402140314041405140614078 unmodified lines141614171418141914201421142214231424142551 unmodified lines14771478147914801481148214831484148514861487148814897 unmodified lines14971498149915001501150215035 unmodified lines15091510151115121513151415151516151715189 unmodified lines152815291530153115321533153410 unmodified lines15451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161026 unmodified lines163716381639164016411642164316441645164616471648164918 unmodified lines166816691670167116721673167413 unmodified lines168816891690169116921693169411 unmodified lines170617071708170917101711171210 unmodified lines1723172417251726172717281729173017311732173332 unmodified lines17661767176817691770177117721773177417751776177717781779178017811782178317841785178611 unmodified lines179817991800180118021803180418051 unmodified line1807180818091810181118121813181418151816181718181819182017 unmodified lines183818391840184118421843184418451846184718481849185018513 unmodified lines185518561857185818591860186110 unmodified lines18721873187418751876187718789 unmodified lines18881889189018911892189318944 unmodified lines18991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019412 unmodified lines1944194519461947194819491950195119521953195419551956195719586 unmodified lines19651966196719681969197019714 unmodified lines19761977197819791980198119821983198419851986198712 unmodified lines20002001200220032004200520063 unmodified lines201020112012201320142015201620172018201920202021202220232024202520262027202820291 unmodified line2031203220332034203520362037203820392040204120423 unmodified lines2046204720482049205020512052205320542055205620572058205920604 unmodified lines20652066206720682069207020712072207320742075207620772078207920802081208220833 unmodified lines208720882089209020912092209326 unmodified lines212021212122212321242125212611 unmodified lines2138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216936 unmodified lines220622072208220922102211221222132214221522162217221822192220222122222223222413 unmodified lines# ============================================================# CONFIGURATION# ============================================================MODEL_PATH = "wav2lip_models/wav2lip_gan.onnx"30 unmodified linesFACE_CONFIDENCE = 0.50# Larger crop gives Wav2Lip more surrounding face context.FACE_PADDING = 0.20# Very low smoothing.# Too much smoothing creates moving-face / mouth artifacts.FACE_SMOOTHING = 0.08# Re-detect face occasionally.REDETECT_SECONDS = 0.50# ============================================================# MOUTH SETTINGS# ============================================================# Maximum generated-mouth contribution.## Lower = more natural original skin.# Higher = stronger Wav2Lip mouth.MOUTH_STRENGTH = 0.52# ============================================================# AUDIO / WAV2LIP SETTINGS# ============================================================SAMPLE_RATE = 1600016 unmodified lines# ============================================================# VIDEO ENCODING# ============================================================VIDEO_CRF = 17VIDEO_PRESET = "medium"# ============================================================# CREATE DIRECTORIES# ============================================================os.makedirs(OUTPUT_DIR,exist_ok=True5 unmodified lines)print("=" * 72)print("Wav2Lip High Quality - Natural Mouth Compositing")print("=" * 72)# ============================================================# MODEL CHECK# ============================================================if not os.path.isfile(MODEL_PATH):raise FileNotFoundError("\n\nWav2Lip ONNX model was not found.\n\n"f"Expected:\n{MODEL_PATH}\n\n""Your Space should contain:\n\n""app.py\n""requirements.txt\n""wav2lip_models/\n"" wav2lip_gan.onnx\n")# ============================================================# ONNX PROVIDER# ============================================================available_providers = (20 unmodified lines)# ============================================================# LOAD MODEL# ============================================================print("Loading Wav2Lip ONNX model...")SESSION = ort.InferenceSession(MODEL_PATH,providers=ONNX_PROVIDERS)print("Model loaded successfully.")MODEL_INPUTS = SESSION.get_inputs()MODEL_OUTPUTS = SESSION.get_outputs()print("Model inputs:")for item in MODEL_INPUTS:print(" ",item.name,item.shape,item.type)print("Model outputs:")for item in MODEL_OUTPUTS:print(" ",item.name,item.shape,item.type)# ============================================================# DETERMINE MODEL INPUT NAMES# ============================================================MEL_INPUT_NAME = NoneVIDEO_INPUT_NAME = Nonefor item in MODEL_INPUTS:name = item.name.lower()if "mel" in name:MEL_INPUT_NAME = item.nameelif ("video" in nameor"frame" in nameor"face" in name):VIDEO_INPUT_NAME = item.nameif MEL_INPUT_NAME is None:MEL_INPUT_NAME = MODEL_INPUTS[0].nameif VIDEO_INPUT_NAME is None:if len(MODEL_INPUTS) >= 2:VIDEO_INPUT_NAME = MODEL_INPUTS[1].nameelse:raise RuntimeError("Could not identify Wav2Lip video input.")OUTPUT_NAME = (MODEL_OUTPUTS[0].name)print("Mel input:",MEL_INPUT_NAME)print("Video input:",VIDEO_INPUT_NAME)print("Output:",OUTPUT_NAME)# ============================================================# DOWNLOAD FACE DETECTOR# ============================================================def download_file(url,destination):if os.path.isfile(destination):returnprint("Downloading:",os.path.basename(destination))urllib.request.urlretrieve(url,destination)9 unmodified lines# ============================================================# OPENCV DNN FACE DETECTOR# ============================================================print("Loading OpenCV DNN face detector...")FACE_DETECTOR = cv2.dnn.readNetFromCaffe(FACE_PROTO,FACE_MODEL)print("Face detector loaded.")# ============================================================# AUDIO LOADING# ============================================================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(6 unmodified linesSAMPLE_RATE)return (audio,duration)# ============================================================# STANDARD WAV2LIP MEL# ============================================================def make_mel(audio):"""Standard Wav2Lip-style mel spectrogram.Important:power=2.0 rather than 1.0."""mel = librosa.feature.melspectrogram(y=audio,sr=SAMPLE_RATE,1 unmodified linehop_length=HOP_LENGTH,win_length=WIN_LENGTH,window="hann",center=True,pad_mode="reflect",power=2.0,n_mels=N_MELS,fmin=FMIN,fmax=FMAX)mel = np.maximum(5 unmodified linesmel)mel = np.nan_to_num(mel,nan=-5.0,posinf=-5.0,neginf=-5.0)return mel.astype(np.float32)16 unmodified linesframe,(300, 300)),scalefactor=1.0,size=(300, 300),mean=(104, 177, 123),swapRB=False,crop=False)6 unmodified linesFACE_DETECTOR.forward())best = Nonebest_score = 0.054 unmodified lines)x2 = max(x1 + 1,min(x2,frame_w1 unmodified line)y2 = max(y1 + 1,min(y2,frame_h))w = x2 - x1h = y2 - y1if w < 60 or h < 60:continuearea = w * hscore = (confidence*math.sqrt(float(area)))if score > best_score:best_score = scorebest = (x1,y1,w,h)return best# ============================================================# FIND INITIAL FACE# ============================================================def find_initial_face(24 unmodified lines"Video contains no frames.")sample_count = min(12,total)detected = []for i in range(sample_count):19 unmodified linescontinueface = detect_face(frame)if face is not None:detected.append(face)cap.release()if not detected:raise RuntimeError("No face detected in source video.")arr = np.asarray(detected,dtype=np.float32)result = np.median(arr,axis=0)return tuple(result.astype(int))# ============================================================# FACE BOX SMOOTHING# ============================================================def smooth_face_box(old_box,new_box):2 unmodified linesreturn new_boxold = np.asarray(old_box,dtype=np.float32)new = np.asarray(new_box,dtype=np.float32)result = (old*(1.01 unmodified lineFACE_SMOOTHING)+new*FACE_SMOOTHING)7 unmodified lines# FIXED CROP SIZE# ============================================================def calculate_crop_size(face_box,frame_width,frame_height24 unmodified linesframe_height)return size# ============================================================# GET FACE CROP# ============================================================def get_face_crop(frame,face_box,crop_size3 unmodified linesframe.shape[:2])fx, fy, fw, fh = (face_box)center_x = (fx+fw / 2.0)center_y = (fy+fh / 2.0)# Keep face crop slightly above center.center_y -= (fh*0.015)x = int(center_x-crop_size / 2)y = int(center_y-crop_size / 2)15 unmodified lines)return (x,y,crop_size,crop_size)# ============================================================# MEL CHUNK# ============================================================def get_mel_chunk(mel,frame_index,fps):mel_index = int(frame_index*MEL_FPS/fps)max_start = max(0,mel.shape[1]-MEL_STEP_SIZE)mel_index = min(mel_index,max_start)chunk = mel[:,mel_index:mel_index+MEL_STEP_SIZE]if chunk.shape[1] < MEL_STEP_SIZE:if chunk.shape[1] == 0:chunk = np.zeros((N_MELS,MEL_STEP_SIZE),dtype=np.float32)else:missing = (MEL_STEP_SIZE-chunk.shape[1])chunk = np.pad(chunk,((0, 0),(0, missing)),mode="edge")return chunk.astype(np.float32)6 unmodified linesmel_chunk):# --------------------------------------------------------# Resize face# --------------------------------------------------------face_rgb = cv2.cvtColor(face_bgr,cv2.COLOR_BGR2RGB)face96 = cv2.resize(face_rgb,(96, 96),interpolation=cv2.INTER_AREA)# --------------------------------------------------------# Standard Wav2Lip masking# --------------------------------------------------------masked = face96.copy()masked[3 unmodified lines# 6 channels:## masked RGB# +# original RGB#video_input = np.concatenate([masked,face961 unmodified lineaxis=2)video_input = (video_input.astype(np.float32)/255.0)video_input = (video_input.transpose(2,0,1))video_input = (video_input[None,...])# --------------------------------------------------------# Mel# --------------------------------------------------------mel_input = (13 unmodified lines# --------------------------------------------------------outputs = SESSION.run([OUTPUT_NAME],{MEL_INPUT_NAME:mel_input,VIDEO_INPUT_NAME:video_input})prediction = outputs[0]# Expected:## [1, 3, 96, 96]#if prediction.ndim == 4:prediction = prediction[0]8 unmodified lines))elif prediction.shape[-1] == 3:passelse:raise RuntimeError("Unexpected Wav2Lip output shape: "+str(prediction.shape14 unmodified linesnp.uint8)generated_bgr = cv2.cvtColor(prediction,cv2.COLOR_RGB2BGR)return generated_bgr# ============================================================# TIGHT MOUTH MASK# ============================================================def create_mouth_mask(2 unmodified lines):"""Tight, static mouth mask.This intentionally avoids a large elliptical replacement."""yy, xx = np.mgrid[1 unmodified line0:width]# --------------------------------------------------------# Mouth center# --------------------------------------------------------cx = (width*6 unmodified lines0.715)# Much tighter than previous version.rx = (width*0.135)ry = (height*0.065)distance = (15 unmodified linesmask = np.exp(-distance*2.6)# --------------------------------------------------------# Hard geographic limit# --------------------------------------------------------top = int(height*0.625)bottom = int(height*0.800)mask[6 unmodified lines:] = 0.0# --------------------------------------------------------# Remove weak outer area# --------------------------------------------------------mask = np.clip((mask-0.16)/0.84,0.0,1.0)# --------------------------------------------------------# Smooth boundary# --------------------------------------------------------mask = cv2.GaussianBlur(mask.astype(np.float32),(0, 0),0.9)return np.clip(14 unmodified lines):"""Conservative LAB color correction.Prevents:- blue lips- purple lips- gray mouth- oversaturationOnly current frame is used."""original_lab = cv2.cvtColor(11 unmodified lines)strong = (mask > 0.40)if np.count_nonzero(strong) < 50:return generated_bgr# --------------------------------------------------------# LUMINANCE# --------------------------------------------------------original_l = np.median(23 unmodified linesgenerated_l)*0.25)# --------------------------------------------------------# A/B COLOR# --------------------------------------------------------for channel in (30 unmodified lines] += (difference*0.35)generated_lab = np.clip(13 unmodified lines# ============================================================# GHOST-FREE COMPOSITING# ============================================================def blend_face(2 unmodified lines):"""IMPORTANT:There is absolutely NO temporal smoothing here.Frame N uses only:original frame Ngenerated frame NPrevious generated frame is never used."""h, w = (original_bgr.shape[:2])# --------------------------------------------------------# Safety resize# --------------------------------------------------------if generated_bgr.shape[:2] != (h,w):generated_bgr = cv2.resize(generated_bgr,(w,h),interpolation=cv2.INTER_CUBIC)# --------------------------------------------------------# Mouth mask# --------------------------------------------------------mask = create_mouth_mask(h,w)# --------------------------------------------------------# Color correction# --------------------------------------------------------generated_bgr = (correct_generated_color(original_bgr,3 unmodified lines)# --------------------------------------------------------# Very conservative alpha# --------------------------------------------------------alpha = (2 unmodified linesMOUTH_STRENGTH)# Small feather.## Large blur causes shadow motion.alpha = cv2.GaussianBlur(alpha.astype(np.float32),(0, 0),0.7)alpha = np.clip(8 unmodified linesNone]# --------------------------------------------------------# Current frame only# --------------------------------------------------------original = (original_bgr.astype(np.float3251 unmodified lines# ============================================================# ADD AUDIO# ============================================================def mux_audio(silent_video,audio_path,output_path):ffmpeg = get_ffmpeg()7 unmodified linessilent_video,"-i",audio_path,"-map","0:v:0",5 unmodified lines"libx264","-preset",VIDEO_PRESET,"-crf",str(VIDEO_CRF),"-pix_fmt","yuv420p",9 unmodified lines"-movflags","+faststart",output_path]result = subprocess.run(10 unmodified lines)raise RuntimeError("FFmpeg audio muxing failed:\n"+result.stderr[-3000:])# ============================================================# GRADIO PATH# ============================================================def get_video_path(value):if value is None:return Noneif isinstance(value,dict):return (value.get("path")orvalue.get("name"))return str(value)def get_audio_path(value):if value is None:return Noneif isinstance(value,dict):return (value.get("path")orvalue.get("name"))return str(value)# ============================================================# MAIN PROCESSING# ============================================================def process_video(26 unmodified linesif not video_path:raise gr.Error("Could not read source video.")if not audio_path:raise gr.Error("Could not read target audio.")work_dir = tempfile.mkdtemp(18 unmodified linesprogress(0.02,desc="Loading target audio...")audio, audio_duration = (13 unmodified linesprogress(0.05,desc="Creating Wav2Lip mel...")mel = make_mel(11 unmodified linesprogress(0.08,desc="Opening source video...")cap = cv2.VideoCapture(10 unmodified linescv2.CAP_PROP_FPS)if (fps is Noneorfps <= 0):fps = 25.032 unmodified linestotal_frames)if width <= 0 or height <= 0:cap.release()raise RuntimeError("Invalid video resolution.")# ====================================================# INITIAL FACE# ====================================================progress(0.10,desc="Finding face...")current_face = (11 unmodified lines# FIXED CROP# ====================================================crop_size = (calculate_crop_size(current_face,width,height1 unmodified line)print("Fixed face crop:",crop_size,"x",crop_size)# ====================================================# VIDEO WRITER# ====================================================fourcc = (17 unmodified linescap.release()raise RuntimeError("Could not create output video.")# ====================================================# FRAME COUNT# ====================================================audio_frames = int(math.ceil(audio_duration*3 unmodified linesframes_to_process = min(total_frames,audio_frames)# ====================================================10 unmodified lines)# ====================================================# PROCESS FRAMES# ====================================================for frame_index in range(9 unmodified linesbreak# ------------------------------------------------# Face detection# ------------------------------------------------if (4 unmodified lines0):detected = detect_face(frame)if detected is not None:current_face = (smooth_face_box(current_face,detected))# ------------------------------------------------# Face crop# ------------------------------------------------x, y, cw, ch = (get_face_crop(frame,current_face,crop_size))face = frame[y:y + ch,x:x + cw]if (face.size == 0orface.shape[0] != crop_sizeorface.shape[1] != crop_size):writer.write(frame2 unmodified linescontinue# ------------------------------------------------# Mel# ------------------------------------------------mel_chunk = get_mel_chunk(mel,frame_index,fps)# ------------------------------------------------# Wav2Lip# ------------------------------------------------6 unmodified lines)# ------------------------------------------------# Ghost-free mouth compositing# ------------------------------------------------result_face = (4 unmodified lines)# ------------------------------------------------# Put back into original frame# ------------------------------------------------frame[y:y + ch,x:x + cw] = result_facewriter.write(12 unmodified lines0):ratio = (frame_index/max(3 unmodified lines)progress(0.15+ratio*0.72,desc=("Generating lips "f"{frame_index + 1}/"f"{frames_to_process}"))# ====================================================# CLOSE VIDEO# ====================================================cap.release()1 unmodified linewriter.release()# ====================================================# ADD AUDIO# ====================================================progress(0.92,desc="Adding target audio...")mux_audio(3 unmodified lines)# ====================================================# RESULT# ====================================================progress(1.0,desc="Finished!")output_mb = (os.path.getsize(output_video)4 unmodified lines)status = ("## β Lip Sync Complete\n\n"f"**Source:** `{width} Γ {height}`\n\n"f"**FPS:** `{fps:.2f}`\n\n"f"**Audio:** `{audio_duration:.2f}s`\n\n"f"**Frames:** `{frames_to_process}`\n\n"f"**Face crop:** `{crop_size} Γ {crop_size}`\n\n""**Temporal mouth blending:** OFF\n\n""**Previous-frame mouth memory:** OFF\n\n""**Tight mouth mask:** ON\n\n""**Conservative color correction:** ON\n\n""**Face tracking:** ON\n\n""**Original surrounding face:** preserved\n\n"f"**Output:** `{output_mb:.2f} MB`")if (3 unmodified lines):status += ("\n\n### π Audio Text\n\n"+text_input.strip())26 unmodified lines# ============================================================# UI CSS# ============================================================CSS = """11 unmodified lines# ============================================================# GRADIO APP# ============================================================with gr.Blocks(title="Wav2Lip High Quality") as demo:gr.Markdown("""# π¬ Wav2Lip High Quality Lip SyncGenerate a lip-synced video from your source video and target audio.""")gr.Markdown("""### π Quality improvements- Tight mouth compositing- No temporal mouth blending- No previous-frame mouth persistence- Conservative color matching- Stable face crop- Standard Wav2Lip mel processing- Original face texture preserved""")36 unmodified linesgr.Markdown("""### π Recommended source videoFor the best mouth quality:- One face- Face clearly visible- Lips visible- Good lighting- Limited head movement- No hands covering the mouth- 720p or higher source is recommendedThe **audio controls lip movement**. The text field is optional and is not used to generate speech.""")
app.py+534-387