Update app.py
Browse files1 unmodified line23456789103 unmodified lines141516171819202122232425266 unmodified lines333435363738394041424344451 unmodified line474849505152539 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697989910010118 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017131 unmodified lines20320420520620720820921021121215 unmodified lines2282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752763 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093105 unmodified lines31631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637711 unmodified lines3893903913923933943953963973983994004014 unmodified lines4064074084094104114124134148 unmodified lines42342442542642742842924 unmodified lines4544554564574584594604614624638 unmodified lines4724734744754764774782 unmodified lines4814824834844854864872 unmodified lines4904914924934944954962 unmodified lines4995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616628 unmodified lines6716726736746756766779 unmodified lines6876886896906916926936946956966976982 unmodified lines7017027037047057067077087097107117127137147157167177187197 unmodified lines72772872973073173273312 unmodified lines7467477487497507517527537547557567577587597607617627637647654 unmodified lines77077177277377477577677777877978078178278378478578678778878979079179279379479579616 unmodified lines8138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651 unmodified line106710681069107010711072107310744 unmodified lines107910801081108210831084108510861087108810899 unmodified lines1099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112110 unmodified lines113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117413 unmodified lines11881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912302 unmodified lines12331234123512361237123812395 unmodified lines12451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781 unmodified line12801281128212831284128512868 unmodified lines129512961297129812991300130113021303130429 unmodified lines133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413658 unmodified lines1374137513761377137813791380138113825 unmodified lines138813891390139113921393139413951396139713981 unmodified line14001401140214031404140514061407140814091410141114123 unmodified lines14161417141814191420142114221423142414251426142714285 unmodified lines14341435143614371438143914403 unmodified lines144414451446144714481449145021 unmodified lines1472147314741475147614771478147914801481148214831484148514861 unmodified line14881489149014911492149314941 unmodified line14961497149814991500150115021503150415051506150715081509151015111512151315141515151615172 unmodified lines15201521152215231524152515261527152815291530153124 unmodified lines15561557155815591560156115621563156415651 unmodified line15671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816097 unmodified lines1617161816191620162116221623162416251626162716281629163016311 unmodified line16331634163516361637163816391 unmodified line1641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616673 unmodified lines167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216938 unmodified lines170217031704170517061707170820 unmodified lines172917301731173217331734173514 unmodified lines1750175117521753175417551756175716 unmodified lines1774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518063 unmodified lines18101811181218131814181518161 unmodified line18181819182018211822182318241825182618271828182918301831183218331834183518361837183818394 unmodified lines18441845184618471848184918502 unmodified lines18531854185518561857185818591860186118623 unmodified lines186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191124 unmodified lines19361937193819391940194119422 unmodified lines194519461947194819491950195119521953195419551956195719582 unmodified lines196119621963196419651966196719681969197019711972197319741975197620 unmodified lines19971998199920002001200220032 unmodified lines2006200720082009201020112012201320144 unmodified lines2019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206219 unmodified lines20822083208420852086208720881 unmodified lineimport cv2import mathimport shutilimport subprocessimport tempfileimport tracebackimport urllib.requestimport gradio as gr3 unmodified lines# ============================================================# CONFIG# ============================================================MODEL_PATH = "wav2lip_models/wav2lip_gan.onnx"OUTPUT_DIR = "outputs"FACE_DIR = "face_detector"FACE_PROTO = os.path.join(6 unmodified lines"res10_300x300_ssd_iter_140000.caffemodel")PROTO_URL = ("https://raw.githubusercontent.com/""opencv/opencv/master/samples/dnn/""face_detector/deploy.prototxt")MODEL_URL = ("https://github.com/opencv/opencv_3rdparty/""raw/dnn_samples_face_detector_20170830/""res10_300x300_ssd_iter_140000.caffemodel"1 unmodified line# ============================================================# WAV2LIP AUDIO PARAMETERS# ============================================================SAMPLE_RATE = 160009 unmodified linesMEL_STEP_SIZE = 16# Original Wav2Lip uses approximately 80 mel frames/secMEL_FPS = 80.0# ============================================================# VIDEO / FACE PARAMETERS# ============================================================FACE_SIZE = 96FACE_CONFIDENCE = 0.50# Extra face crop around detected faceFACE_PADDING = 0.20# Temporal face smoothingFACE_SMOOTHING = 0.15# Mouth blend strength## 0.70 = stronger lip replacement# 0.55 = balanced# 0.40 = more original faceMOUTH_BLEND = 0.62# ============================================================# OUTPUT QUALITY# ============================================================FFMPEG_CRF = 17FFMPEG_PRESET = "medium"os.makedirs(18 unmodified linesif not os.path.exists(MODEL_PATH):raise FileNotFoundError("\nWav2Lip ONNX model not found:\n"f"{MODEL_PATH}\n\n""Expected:\n""wav2lip_models/wav2lip_gan.onnx")# ============================================================# ONNX PROVIDERS# ============================================================available_providers = (ort.get_available_providers())if "CUDAExecutionProvider" in available_providers:providers = ["CUDAExecutionProvider","CPUExecutionProvider"]else:providers = ["CPUExecutionProvider"]print("ONNX providers:",providers)# ============================================================# LOAD WAV2LIP# ============================================================print("Loading Wav2Lip ONNX model...")SESSION = ort.InferenceSession(MODEL_PATH,providers=providers)31 unmodified lines# ============================================================# FACE DETECTOR# ============================================================def download_file(url,path):15 unmodified lines)urllib.request.urlretrieve(url,path)def load_face_detector():download_file(PROTO_URL,FACE_PROTO)download_file(MODEL_URL,FACE_MODEL)print("Loading OpenCV DNN face detector...")detector = cv2.dnn.readNetFromCaffe(FACE_PROTO,FACE_MODEL)print("Face detector loaded.")return detectorFACE_DETECTOR = load_face_detector()# ============================================================# AUDIO LOADING# ============================================================def load_audio(3 unmodified linesif not path:raise ValueError("Audio file is required.")wav, sr = librosa.load(path,sr=SAMPLE_RATE,mono=True)if wav is None or len(wav) == 0:raise ValueError("Could not read audio.")wav = wav.astype(np.float32)duration = (len(wav)/ SAMPLE_RATE)5 unmodified lines)return wav, duration# ============================================================# WAV2LIP-COMPATIBLE MEL SPECTROGRAM# ============================================================def wav2lip_mel(wav):"""Wav2Lip-style mel preprocessing.This is intentionally closer to the original Wav2Lipaudio preprocessing than the previous implementation."""# Pre-emphasis / STFTstft = librosa.stft(wav,n_fft=N_FFT,hop_length=HOP_LENGTH,win_length=WIN_LENGTH,window="hann",center=True)# Magnitudemagnitudes = np.abs(stft)# Mel filter bankmel_filters = librosa.filters.mel(sr=SAMPLE_RATE,n_fft=N_FFT,n_mels=N_MELS,fmin=FMIN,fmax=FMAX)mel = np.dot(mel_filters,magnitudes)# Wav2Lip-style log compressionmel = np.maximum(1e-5,mel)11 unmodified lines# FACE DETECTION# ============================================================def detect_faces(frame):height, width = (frame.shape[:2])blob = cv2.dnn.blobFromImage(4 unmodified lines1.0,(300, 300),(104.0,177.0,123.0))8 unmodified lines)faces = []for i in range(24 unmodified lines]* np.array([width,height,width,height]))8 unmodified lines0,min(x1,width - 1))2 unmodified lines0,min(y1,height - 1))2 unmodified lines0,min(x2,width))2 unmodified lines0,min(y2,height))w = x2 - x1h = y2 - y1if w < 50 or h < 50:continuefaces.append({"x": x1,"y": y1,"w": w,"h": h,"confidence": confidence})return faces# ============================================================# BEST FACE# ============================================================def best_face(frame):faces = detect_faces(frame)if not faces:return Nonefaces.sort(key=lambda f: (f["w"] * f["h"],f["confidence"]),reverse=True)f = faces[0]return (f["x"],f["y"],f["w"],f["h"])# ============================================================# FACE BOX WITH PADDING# ============================================================def padded_square_box(frame,box):height, width = (frame.shape[:2])x, y, w, h = box# Wav2Lip needs a little surrounding contextsize = max(w,h)size = int(size* (1.0+ FACE_PADDING))size = min(size,width,height)cx = (x+ w / 2.0)cy = (y+ h / 2.0)x1 = int(cx- size / 2)y1 = int(cy- size / 2)x1 = max(0,min(x1,width - size))y1 = max(0,min(y1,height - size))return (int(x1),int(y1),int(size),int(size))# ============================================================# INITIAL FACE BOX# ============================================================def find_initial_face(8 unmodified linesif not cap.isOpened():raise RuntimeError("Could not open video.")9 unmodified linescap.release()raise RuntimeError("Video has no frames.")sample_count = min(15,total)2 unmodified linesfor i in range(sample_count):index = int(i* total/ sample_count)cap.set(cv2.CAP_PROP_POS_FRAMES,index)7 unmodified linescontinuebox = best_face(frame)12 unmodified linesraise RuntimeError("No face detected.\n\n""Please use a video with a clearly ""visible face.")boxes = np.asarray(boxes,dtype=np.float32)# Median is more stable than taking the first framemedian = np.median(boxes,axis=0)4 unmodified lines# ============================================================# FACE BOX SMOOTHING# ============================================================def smooth_box(old_box,new_box):if old_box is None:return new_boxold = np.asarray(old_box,dtype=np.float32)new = np.asarray(new_box,dtype=np.float32)16 unmodified lines# ============================================================# MOUTH MASK# ============================================================def create_mouth_mask(size):mask = np.zeros((size,size),dtype=np.float32)# Important:# Don't use a rectangular mouth region.## An ellipse gives much smoother transitions and# avoids visible square/rectangular artifacts.center_x = int(size * 0.50)center_y = int(size * 0.665)axis_x = int(size * 0.285)axis_y = int(size * 0.155)cv2.ellipse(mask,(center_x,center_y),(axis_x,axis_y),0,0,360,1.0,-1)# Extra blur creates a natural transitionsigma = max(2,int(size * 0.045))mask = cv2.GaussianBlur(mask,(0, 0),sigma)return np.clip(mask,0,1)MOUTH_MASK = create_mouth_mask(FACE_SIZE)# ============================================================# MOUTH-ONLY COLOR CORRECTION# ============================================================def color_correct(generated,original,mask):result = generated.astype(np.float32)original_float = (original.astype(np.float32))strong = (mask > 0.35)if np.count_nonzero(strong) < 50:return generatedfor c in range(3):src = (original_float[:,:,c][strong])dst = (result[:,:,c][strong])if (len(src) == 0or len(dst) == 0):continuesrc_mean = np.mean(src)dst_mean = np.mean(dst)# Only mild correction.# Strong correction can make lips look unnatural.correction = (src_mean- dst_mean) * 0.35result[:,:,c] += correctionreturn np.clip(result,0,255).astype(np.uint8)# ============================================================# WAV2LIP INFERENCE# ============================================================def run_wav2lip(face,mel):# --------------------------------------------------------# Resize to model input# --------------------------------------------------------face_96 = cv2.resize(face,(FACE_SIZE,FACE_SIZE),interpolation=cv2.INTER_AREA)# --------------------------------------------------------# Mask lower half# --------------------------------------------------------masked = face_96.copy()masked[FACE_SIZE // 2:] = 0# --------------------------------------------------------# 6 channels## [masked face RGB]# [original face RGB]# --------------------------------------------------------combined = np.concatenate([masked,face_96],axis=2)combined = (combined.astype(np.float32)/ 255.0)# HWC -> CHWcombined = (combined.transpose(2,0,11 unmodified line)video_input = (combined[np.newaxis,...]4 unmodified lines# --------------------------------------------------------# Mel# --------------------------------------------------------mel_input = (mel[np.newaxis,np.newaxis,:,9 unmodified lines# ONNX# --------------------------------------------------------outputs = SESSION.run(None,{"mel_spectrogram":mel_input,"video_frames":video_input})prediction = outputs[0]# [1,3,96,96] -> [3,96,96]prediction = prediction[0]# --------------------------------------------------------10 unmodified linesprediction = np.clip(prediction * 255.0,0,255).astype(np.uint8)# Model output is RGBprediction = cv2.cvtColor(prediction,cv2.COLOR_RGB2BGR)# --------------------------------------------------------# Back to original crop resolution# --------------------------------------------------------prediction = cv2.resize(prediction,(face.shape[1],face.shape[0]),interpolation=cv2.INTER_CUBIC)return prediction# ============================================================# BLEND RESULT# ============================================================def blend_mouth(original,generated):13 unmodified lines)mask = cv2.resize(MOUTH_MASK,(w,h),interpolation=cv2.INTER_CUBIC)# Mild color correctiongenerated = color_correct(generated,original,mask)alpha = (mask[:,:,np.newaxis]* MOUTH_BLEND)result = (generated.astype(np.float32)* alpha+original.astype(np.float32)* (1.0- alpha2 unmodified linesreturn np.clip(result,0,255).astype(5 unmodified lines# FFMPEG# ============================================================def get_ffmpeg():ffmpeg = shutil.which("ffmpeg")if ffmpeg is None:raise RuntimeError("FFmpeg is not installed.")return ffmpeg# ============================================================# MUX AUDIO# ============================================================def mux_audio(video,audio,output):ffmpeg = get_ffmpeg()command = [1 unmodified line"-y","-i",video,"-i",audio,8 unmodified lines"libx264","-preset",FFMPEG_PRESET,"-crf",str(FFMPEG_CRF),"-pix_fmt","yuv420p",29 unmodified linesraise RuntimeError("FFmpeg audio muxing failed.")# ============================================================# MAIN PROCESS# ============================================================def process_video(video_path,audio_path,text,progress=gr.Progress()):if not video_path:raise gr.Error("Please upload a video.")if not audio_path:raise gr.Error("Please upload audio.")8 unmodified lines)output_video = os.path.join(OUTPUT_DIR,"wav2lip_hq_result.mp4")5 unmodified linesprogress(0.02,desc="Loading audio...")wav, audio_duration = (load_audio(audio_path)1 unmodified lineprogress(0.06,desc="Creating Wav2Lip mel spectrogram...")mel = wav2lip_mel(wav)3 unmodified lines)# ====================================================# VIDEO# ====================================================progress(0.10,desc="Opening video...")5 unmodified linesif not cap.isOpened():raise RuntimeError("Could not open video.")3 unmodified linesif (fps is Noneor fps <= 0):21 unmodified lines)if total_frames <= 0:cap.release()raise RuntimeError("Video contains no frames.")print("FPS:",fps1 unmodified lineprint("Resolution:",width,"x",height1 unmodified lineprint("Total frames:",total_frames)# ====================================================# FACE# ====================================================progress(0.14,desc="Finding face...")initial_face = (find_initial_face(video_path)2 unmodified linesprint("Initial face:",initial_face)# ====================================================# CREATE VIDEO WRITER# ====================================================fourcc = (24 unmodified lines# ====================================================# PROCESS FRAME COUNT# ====================================================audio_frame_count = int(math.ceil(audio_duration* fps1 unmodified line)process_frames = min(total_frames,audio_frame_count)print("Frames to process:",process_frames)# ====================================================# FACE TRACKING# ====================================================current_face = initial_face# How often to re-detect## This prevents the face from drifting when the# person moves.REDETECT_EVERY = max(1,int(fps * 0.5))# ====================================================# PROCESS# ====================================================for frame_index in range(process_frames):ok, frame = (7 unmodified lines# ------------------------------------------------# Re-detect periodically# ------------------------------------------------if (frame_index % REDETECT_EVERY== 0):detected = best_face(frame)1 unmodified lineif detected is not None:current_face = (smooth_box(current_face,detected)1 unmodified line# ------------------------------------------------# Face crop# ------------------------------------------------crop_box = (padded_square_box(frame,current_face))x, y, w, h = crop_boxface = frame[y:y+h,x:x+w]if face.size == 0:writer.write(frame3 unmodified lines# ------------------------------------------------# EXACT AUDIO/VIDEO FRAME MAPPING# ------------------------------------------------## This is more important for sync than a manually# chosen arbitrary offset.## Original Wav2Lip style:## mel_idx_multiplier = 80 / fps## ------------------------------------------------mel_idx_multiplier = (MEL_FPS/ fps)mel_start = int(frame_index8 unmodified lines# ------------------------------------------------# Handle final audio frames# ------------------------------------------------if mel_start >= (20 unmodified lines# ------------------------------------------------# Pad final chunk# ------------------------------------------------if (14 unmodified linesmel_chunk = np.zeros((N_MELS,MEL_STEP_SIZE),dtype=np.float32)16 unmodified lines)# ------------------------------------------------# Generate# ------------------------------------------------generated = run_wav2lip(face,mel_chunk)# ------------------------------------------------# Mouth-only blend# ------------------------------------------------result_face = blend_mouth(face,generated)# ------------------------------------------------# Paste back# ------------------------------------------------frame[y:y+h,x:x+w] = result_face3 unmodified lines# ------------------------------------------------# Progress# ------------------------------------------------if (1 unmodified line== 0):ratio = (frame_index/ max(1,process_frames))progress(0.18+ ratio * 0.70,desc=("Lip syncing "f"{frame_index + 1}/"f"{process_frames}"))4 unmodified lines# ====================================================# AUDIO# ====================================================progress(2 unmodified lines)mux_audio(silent_video,audio_path,output_video)3 unmodified linesprogress(1.0,desc="Finished!")file_size = (os.path.getsize(output_video)/ (1024* 1024))status = ("## β Lip-sync completed\n\n"f"**Audio:** `{audio_duration:.2f}s`\n\n"f"**FPS:** `{fps:.2f}`\n\n"f"**Frames processed:** `{process_frames}`\n\n"f"**Face tracking:** `Enabled`\n\n"f"**Mouth-only blending:** `Enabled`\n\n"f"**Output quality:** `CRF {FFMPEG_CRF}`\n\n"f"**File size:** `{file_size:.2f} MB`")if (textand text.strip()):status += ("\n\n### π Text reference\n\n"+ text.strip())return (output_video,status)24 unmodified lines# ============================================================# GRADIO# ============================================================CSS = """2 unmodified linesmargin: auto !important;}#generate {min-height: 58px;font-size: 18px;font-weight: 700;}"""with gr.Blocks(title="Wav2Lip AI - High Quality Lip Sync") as demo:2 unmodified lines"""# π¬ Wav2Lip AI β High Quality Lip Sync### Upload a video + target audio β generate synchronized speech""")gr.Markdown("""**Improved version:** better Wav2Lip audio preprocessing,more accurate frame-to-audio mapping, face tracking,and smooth mouth-only blending to reduce mouth distortion.""")20 unmodified linestext_input = gr.Textbox(label="π Audio Text (Optional)",placeholder=("Example: Hello, welcome to my video."),2 unmodified linesgenerate_button = gr.Button("π¬ GENERATE HIGH-QUALITY LIP SYNC",variant="primary",elem_id="generate")4 unmodified lineswith gr.Column():output_video = gr.Video(label="π¬ Lip-Synced Result")status_output = gr.Markdown(label="Status")# ========================================================# TIPS# ========================================================gr.Markdown("""### π‘ For the best mouth quality- Use **one person** in the video.- Face should be clearly visible.- Front-facing or slightly angled faces work best.- Avoid hands covering the mouth.- Avoid very small faces.- Use clean speech audio.- Keep the video reasonably stable.- The target audio should contain the speech you want theperson to perform.### βοΈ ProcessingThe system uses the uploaded **audio waveform**, not thetext field, to generate lip movement. The text box is onlyprovided as an optional reference.""")# ========================================================# BUTTON# ========================================================generate_button.click(19 unmodified linesif __name__ == "__main__":print("=" * 70)print("Starting Wav2Lip High Quality Gradio Space")print("=" * 70)1 unmodified line23456789103 unmodified lines1415161718192021222324256 unmodified lines323334353637383940414243441 unmodified line464748495051529 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211318 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618731 unmodified lines21922022122222322422522622722815 unmodified lines2442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952963 unmodified lines3003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293305 unmodified lines33633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938011 unmodified lines3923933943953963973983994004014024 unmodified lines4074084094104114124134144158 unmodified lines42442542642742842943043124 unmodified lines4564574584594604614624634644658 unmodified lines4744754764774784794802 unmodified lines4834844854864874884892 unmodified lines4924934944954964974982 unmodified lines5015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475488 unmodified lines5575585595605615625639 unmodified lines5735745755765775785795805815825835842 unmodified lines5875885895905915925935945955965975985996006016026036046057 unmodified lines61361461561661761861912 unmodified lines6326336346356366376386396406416426436446456466476486496506514 unmodified lines65665765865966066166266366466566666766866967067167267367467567667767867968068168216 unmodified lines6997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578581 unmodified line8608618628638648658668674 unmodified lines8728738748758768778788798808818829 unmodified lines89289389489589689789889990090190290390490590690790890991010 unmodified lines92192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107413 unmodified lines1088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012012 unmodified lines12041205120612071208120912105 unmodified lines12161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491 unmodified line12511252125312541255125612578 unmodified lines126612671268126912701271127212731274127529 unmodified lines13051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213838 unmodified lines1392139313941395139613971398139914005 unmodified lines140614071408140914101411141214131414141514161 unmodified line14181419142014211422142314241425142614271428142914303 unmodified lines1434143514361437143814391440144114421443144414451446144714481449145014511452145314545 unmodified lines14601461146214631464146514663 unmodified lines147014711472147314741475147621 unmodified lines1498149915001501150215031 unmodified line15051506150715081509151015111 unmodified line15131514151515161517151815191520152115221523152415251526152715281529153015311532153315342 unmodified lines15371538153915401541154215431544154515461547154824 unmodified lines15731574157515761577157815791580158115821 unmodified line158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516367 unmodified lines16441645164616471648164916501651165216531654165516561657165816591 unmodified line16611662166316641665166616671 unmodified line166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616973 unmodified lines170117021703170417051706170717088 unmodified lines171717181719172017211722172320 unmodified lines174417451746174717481749175014 unmodified lines1765176617671768176917701771177216 unmodified lines1789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518363 unmodified lines18401841184218431844184518461 unmodified line184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218734 unmodified lines18781879188018811882188318842 unmodified lines18871888188918901891189218931894189518963 unmodified lines1900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194624 unmodified lines19711972197319741975197619772 unmodified lines1980198119821983198419851986198719881989199019911992199319941995199619972 unmodified lines2000200120022003200420052006200720082009201020112012201320142015201620172018201920 unmodified lines20402041204220432044204520462 unmodified lines2049205020512052205320542055205620574 unmodified lines206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209819 unmodified lines21182119212021212122212321241 unmodified lineimport cv2import mathimport shutilimport tempfileimport tracebackimport subprocessimport urllib.requestimport gradio as gr3 unmodified lines# ============================================================# CONFIGURATION# ============================================================MODEL_PATH = "wav2lip_models/wav2lip_gan.onnx"OUTPUT_DIR = "outputs"FACE_DIR = "face_detector"FACE_PROTO = os.path.join(6 unmodified lines"res10_300x300_ssd_iter_140000.caffemodel")FACE_PROTO_URL = ("https://raw.githubusercontent.com/""opencv/opencv/master/samples/dnn/""face_detector/deploy.prototxt")FACE_MODEL_URL = ("https://github.com/opencv/opencv_3rdparty/""raw/dnn_samples_face_detector_20170830/""res10_300x300_ssd_iter_140000.caffemodel"1 unmodified line# ============================================================# AUDIO# ============================================================SAMPLE_RATE = 160009 unmodified linesMEL_STEP_SIZE = 16# Wav2Lip audio timingMEL_FPS = 80.0# ============================================================# FACE# ============================================================FACE_SIZE = 96FACE_CONFIDENCE = 0.50# Do NOT make this too large.## A large crop followed by 96x96 resizing causes# the mouth to become soft/distorted.FACE_PADDING = 0.08# Face tracking smoothingFACE_SMOOTHING = 0.25# How frequently to re-detect faceREDETECT_SECONDS = 0.40# ============================================================# BLENDING# ============================================================# 1.0 = strongest generated mouth# 0.7 = balanced# 0.55 = preserve original textureBLEND_STRENGTH = 0.72# Lower-face mask starts around this percentage# of the crop.LOWER_FACE_START = 0.47# ============================================================# VIDEO ENCODING# ============================================================CRF = 17PRESET = "medium"os.makedirs(18 unmodified linesif not os.path.exists(MODEL_PATH):raise FileNotFoundError("\n\nWav2Lip ONNX model not found:\n\n"f"{MODEL_PATH}\n\n""Your Space should contain:\n\n""wav2lip_models/\n"" wav2lip_gan.onnx\n")# ============================================================# ONNX# ============================================================available_providers = (ort.get_available_providers())print("Available ONNX providers:",available_providers)if "CUDAExecutionProvider" in available_providers:PROVIDERS = ["CUDAExecutionProvider","CPUExecutionProvider"]else:PROVIDERS = ["CPUExecutionProvider"]print("Using providers:",PROVIDERS)print("Loading Wav2Lip ONNX model...")SESSION = ort.InferenceSession(MODEL_PATH,providers=PROVIDERS)31 unmodified lines# ============================================================# FACE DETECTOR DOWNLOAD# ============================================================def download_if_needed(url,path):15 unmodified lines)try:urllib.request.urlretrieve(url,path)except Exception as e:raise RuntimeError(f"Could not download {url}\n{e}")download_if_needed(FACE_PROTO_URL,FACE_PROTO)download_if_needed(FACE_MODEL_URL,FACE_MODEL)# ============================================================# 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(3 unmodified linesif not path:raise ValueError("Target audio is required.")audio, sr = librosa.load(path,sr=SAMPLE_RATE,mono=True)if audio is None or len(audio) == 0:raise ValueError("Could not read target audio.")audio = audio.astype(np.float32)duration = (len(audio)/ SAMPLE_RATE)5 unmodified lines)return audio, duration# ============================================================# WAV2LIP MEL# ============================================================def make_mel(audio):"""Wav2Lip-style mel spectrogram.Important:The ONNX model expects exactly:[1, 1, 80, 16]"""mel = librosa.feature.melspectrogram(y=audio,sr=SAMPLE_RATE,n_fft=N_FFT,hop_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(mel,1e-5)11 unmodified lines# FACE DETECTION# ============================================================def detect_face(frame):h, w = frame.shape[:2]blob = cv2.dnn.blobFromImage(4 unmodified lines1.0,(300, 300),(104,177,123))8 unmodified lines)best = Nonebest_score = 0.0for i in range(24 unmodified lines]* np.array([w,h,w,h]))8 unmodified lines0,min(x1,w - 1))2 unmodified lines0,min(y1,h - 1))2 unmodified lines0,min(x2,w))2 unmodified lines0,min(y2,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 = (x1,y1,bw,bh)return best# ============================================================# FIND FACE FROM SEVERAL FRAMES# ============================================================def find_initial_face(8 unmodified linesif not cap.isOpened():raise RuntimeError("Could not open source video.")9 unmodified linescap.release()raise RuntimeError("Source video contains no frames.")samples = min(12,total)2 unmodified linesfor i in range(samples):frame_number = int(i* total/ samples)cap.set(cv2.CAP_PROP_POS_FRAMES,frame_number)7 unmodified linescontinuebox = detect_face(frame)12 unmodified linesraise RuntimeError("No face detected.\n\n""Please use a video where the face is ""clearly visible.")arr = np.asarray(boxes,dtype=np.float32)# Median is much more stable than first frame.median = np.median(arr,axis=0)4 unmodified lines# ============================================================# SMOOTH FACE BOX# ============================================================def smooth_face(old,new):if old is None:return newold = np.asarray(old,dtype=np.float32)new = np.asarray(new,dtype=np.float32)16 unmodified lines# ============================================================# MAKE FACE CROP# ============================================================def make_crop(frame,face_box):frame_h, frame_w = (frame.shape[:2])x, y, w, h = face_box# Keep crop close to actual face.size = int(max(w, h)* (1.0+ FACE_PADDING))# Prevent crop from becoming enormous.size = min(size,frame_w,frame_h)# Face centercx = (x+ w / 2.0)cy = (y+ h / 2.0)x1 = int(cx- size / 2)y1 = int(cy- size / 2)# Keep inside framex1 = max(0,min(x1,frame_w - size))y1 = max(0,min(y1,frame_h - size))return (int(x1),int(y1),int(size),int(size))# ============================================================# WAV2LIP MODEL# ============================================================def inference(face,mel_chunk):# --------------------------------------------------------# 96x96# --------------------------------------------------------face96 = cv2.resize(face,(96,96),interpolation=cv2.INTER_AREA)# --------------------------------------------------------# ORIGINAL WAV2LIP MASKING## Upper half remains original.# Lower half is masked.# --------------------------------------------------------masked = face96.copy()masked[48:,:] = 0# --------------------------------------------------------# 6 channels## [masked RGB]# [original RGB]# --------------------------------------------------------input_image = np.concatenate([masked,face96],axis=2)# --------------------------------------------------------# HWC -> CHW# --------------------------------------------------------input_image = (input_image.astype(np.float32)/ 255.0)input_image = (input_image.transpose(2,0,11 unmodified line)input_image = (input_image[np.newaxis,...]4 unmodified lines# --------------------------------------------------------# AUDIO# --------------------------------------------------------mel_input = (mel_chunk[np.newaxis,np.newaxis,:,9 unmodified lines# ONNX# --------------------------------------------------------result = SESSION.run(None,{"mel_spectrogram":mel_input,"video_frames":input_image})prediction = result[0][0]# --------------------------------------------------------10 unmodified linesprediction = np.clip(prediction,0,1)prediction = (prediction* 255.0).astype(np.uint8)# Model returns RGBprediction = cv2.cvtColor(prediction,cv2.COLOR_RGB2BGR)return prediction# ============================================================# SOFT LOWER FACE MASK# ============================================================def make_blend_mask(h,w):mask = np.zeros((h,w),dtype=np.float32)start = int(h* LOWER_FACE_START)# Start from zero at upper edge.# Gradually increase toward mouth.## This avoids a visible rectangular patch.for y in range(start,h):position = (y - start) / max(1,h - start)# Smoothstepvalue = (position* position* (3- 2 * position))mask[y, :] = value# Stronger around mouth centeryy, xx = np.mgrid[0:h,0:w]cx = w * 0.50cy = h * 0.68rx = w * 0.42ry = h * 0.30ellipse = (((xx - cx) / rx) ** 2+((yy - cy) / ry) ** 2)ellipse_mask = np.exp(-ellipse * 1.8)# Combine lower-face and mouth masks.mask = (mask* (0.45+ 0.55* ellipse_mask))# Smooth edges.mask = cv2.GaussianBlur(mask,(0,0),sigmaX=max(1.0,w * 0.035))return np.clip(mask,0,1)# ============================================================# BLEND# ============================================================def blend_prediction(original,generated):13 unmodified lines)mask = make_blend_mask(h,w)# --------------------------------------------------------# Slight color matching.## Do NOT aggressively change colors.# --------------------------------------------------------original_float = (original.astype(np.float32))generated_float = (generated.astype(np.float32))mouth_area = (mask > 0.55)if np.count_nonzero(mouth_area) > 100:for c in range(3):src = (original_float[:,:,c][mouth_area])gen = (generated_float[:,:,c][mouth_area])if (len(src) > 0and len(gen) > 0):src_mean = np.mean(src)gen_mean = np.mean(gen)correction = (src_mean- gen_mean) * 0.20generated_float[:,:,c] += correctiongenerated_float = np.clip(generated_float,0,255)# --------------------------------------------------------# Blend# --------------------------------------------------------alpha = (mask[:,:,np.newaxis]* BLEND_STRENGTH)output = (generated_float* alpha+original_float* (1.0- alpha2 unmodified linesreturn np.clip(output,0,255).astype(5 unmodified lines# FFMPEG# ============================================================def ffmpeg_path():path = shutil.which("ffmpeg")if path is None:raise RuntimeError("FFmpeg is not installed.")return path# ============================================================# MUX AUDIO# ============================================================def add_audio(silent_video,audio,output):ffmpeg = ffmpeg_path()command = [1 unmodified line"-y","-i",silent_video,"-i",audio,8 unmodified lines"libx264","-preset",PRESET,"-crf",str(CRF),"-pix_fmt","yuv420p",29 unmodified linesraise RuntimeError("Could not add audio to output video.")# ============================================================# PROCESS# ============================================================def process_video(video_input,audio_input,text_input,progress=gr.Progress()):# ========================================================# GET VIDEO PATH# ========================================================video_path = video_input# Gradio can return a dictionary in some configurations.if isinstance(video_input,dict):video_path = (video_input.get("path")orvideo_input.get("name"))# ========================================================# AUDIO PATH# ========================================================audio_path = audio_inputif isinstance(audio_input,dict):audio_path = (audio_input.get("path")oraudio_input.get("name"))if not video_path:raise gr.Error("Please upload a source video.")if not audio_path:raise gr.Error("Please upload target audio.")8 unmodified lines)output_path = os.path.join(OUTPUT_DIR,"wav2lip_result.mp4")5 unmodified linesprogress(0.02,desc="Loading target audio...")audio, audio_duration = (load_audio(audio_path)1 unmodified lineprogress(0.07,desc="Creating mel spectrogram...")mel = make_mel(audio)3 unmodified lines)if mel.shape[0] != 80:raise RuntimeError("Mel spectrogram has wrong number "f"of bands: {mel.shape[0]}")# ====================================================# VIDEO# ====================================================progress(0.10,desc="Opening source video...")5 unmodified linesif not cap.isOpened():raise RuntimeError("Could not open source video.")3 unmodified linesif (not fpsor fps <= 0):21 unmodified lines)print("FPS:",fps1 unmodified lineprint("Video:",width,"x",height1 unmodified lineprint("Frames:",total_frames)# ====================================================# FIND FACE# ====================================================progress(0.14,desc="Locating face...")current_face = (find_initial_face(video_path)2 unmodified linesprint("Initial face:",current_face)# ====================================================# VIDEO WRITER# ====================================================fourcc = (24 unmodified lines# ====================================================# HOW MANY VIDEO FRAMES# ====================================================audio_frames = int(math.ceil(audio_duration* fps1 unmodified line)frames_to_process = min(total_frames,audio_frames)print("Frames to process:",frames_to_process)# ====================================================# FACE REDETECTION# ====================================================redetect_every = max(1,int(fps* REDETECT_SECONDS))# ====================================================# AUDIO MAPPING# ====================================================mel_idx_multiplier = (MEL_FPS/ fps)print("Mel index multiplier:",mel_idx_multiplier)# ====================================================# FRAME LOOP# ====================================================for frame_index in range(frames_to_process):ok, frame = (7 unmodified lines# ------------------------------------------------# FACE TRACKING# ------------------------------------------------if (frame_index% redetect_every== 0):detected = detect_face(frame)1 unmodified lineif detected is not None:current_face = (smooth_face(current_face,detected)1 unmodified line# ------------------------------------------------# FACE CROP# ------------------------------------------------crop = make_crop(frame,current_face)x, y, cw, ch = cropface = frame[y:y+ch,x:x+cw]if (face.size == 0or face.shape[0] < 20or face.shape[1] < 20):writer.write(frame3 unmodified lines# ------------------------------------------------# CORRECT MEL WINDOW# ------------------------------------------------mel_start = int(frame_index8 unmodified lines# ------------------------------------------------# End of audio# ------------------------------------------------if mel_start >= (20 unmodified lines# ------------------------------------------------# EXACTLY 16 MEL FRAMES# ------------------------------------------------if (14 unmodified linesmel_chunk = np.zeros((80,16),dtype=np.float32)16 unmodified lines)elif (mel_chunk.shape[1]> MEL_STEP_SIZE):mel_chunk = (mel_chunk[:,:MEL_STEP_SIZE])# ------------------------------------------------# MODEL# ------------------------------------------------generated = inference(face,mel_chunk)# ------------------------------------------------# BLEND# ------------------------------------------------result_face = (blend_prediction(face,generated))# ------------------------------------------------# PUT FACE BACK# ------------------------------------------------frame[y:y+ch,x:x+cw] = result_face3 unmodified lines# ------------------------------------------------# PROGRESS# ------------------------------------------------if (1 unmodified line== 0):fraction = (frame_index/max(1,frames_to_process))progress(0.18+fraction* 0.70,desc=("Lip syncing "f"{frame_index + 1}/"f"{frames_to_process}"))4 unmodified lines# ====================================================# ADD AUDIO# ====================================================progress(2 unmodified lines)add_audio(silent_video,audio_path,output_path)3 unmodified linesprogress(1.0,desc="Completed!")size_mb = (os.path.getsize(output_path)/1024/1024)status = ("## β Lip-sync completed\n\n"f"**Video FPS:** `{fps:.2f}`\n\n"f"**Audio duration:** `{audio_duration:.2f}s`\n\n"f"**Processed frames:** `{frames_to_process}`\n\n""**Audio mapping:** `80 FPS mel mapping`\n\n""**Face tracking:** `Enabled`\n\n""**Soft mouth blending:** `Enabled`\n\n"f"**Video quality:** `CRF {CRF}`\n\n"f"**Output size:** `{size_mb:.2f} MB`")if (text_inputand text_input.strip()):status += ("\n\n### π Text reference\n\n"+ text_input.strip())return (output_path,status)24 unmodified lines# ============================================================# CSS# ============================================================CSS = """2 unmodified linesmargin: auto !important;}#generate-button {min-height: 60px;font-size: 18px;font-weight: 700;}"""# ============================================================# UI# ============================================================with gr.Blocks(title="Wav2Lip AI - High Quality Lip Sync") as demo:2 unmodified lines"""# π¬ Wav2Lip AI β High Quality Lip SyncUpload a source video and target speech audio.The face will be tracked and the mouth synchronizedto the target speech.""")gr.Markdown("""### Improved pipelineCorrect Wav2Lip-style audio preprocessing β’accurate audio/video mapping β’ face tracking β’soft mouth blending β’ high-quality H.264 output""")20 unmodified linestext_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")4 unmodified lineswith gr.Column():output_video = gr.Video(label="π¬ Lip-Synced Video")status_output = gr.Markdown()# ========================================================# INFO# ========================================================gr.Markdown("""### π Best input- One clearly visible face- Face looking toward the camera- Good lighting- Mouth not covered- 720p or higher source video recommended- Clean speech audio- Avoid very fast head movement**Note:** The text box is only a reference. The actuallip movement is generated from the uploaded audio waveform.""")# ========================================================# EVENT# ========================================================generate_button.click(19 unmodified linesif __name__ == "__main__":print("=" * 70)print("Starting Wav2Lip Gradio Space")print("=" * 70)
app.py+690-654