# Active Speaker Detection demo: TalkNet-ASD + Light-ASD. # # Pipeline and model code adapted from MIT-licensed sources: # - TaoRuijie/TalkNet-ASD (demoTalkNet.py, MIT, (c) 2021 Tao Ruijie) # - Junhua-Liao/Light-ASD (Columbia_test.py / ASD.py, MIT, (c) 2023 Liao Junhua) # The face detection/tracking/cropping pipeline below is transcribed from # demoTalkNet.py (which itself derives from joonson/syncnet_python preprocessing) # with device parameterization for ZeroGPU. Scoring heads differ per model. # # LICENSE NOTE: code is MIT. The pretrained checkpoints were trained on # research-restricted data (TalkSet = modified VoxCeleb2 + LRS3). This Space is # a research demo; the checkpoints are not certified for commercial use. import os, sys, glob, math, json, shutil, subprocess, warnings import numpy as np import cv2 import torch import spaces import gradio as gr from scipy.io import wavfile from scipy import signal from scipy.interpolate import interp1d from scenedetect.video_manager import VideoManager from scenedetect.scene_manager import SceneManager from scenedetect.stats_manager import StatsManager from scenedetect.detectors import ContentDetector warnings.filterwarnings("ignore") # --------------------------------------------------------------------------- # Setup: clone MIT-licensed repos, fetch checkpoints # --------------------------------------------------------------------------- REPOS_DIR = os.path.abspath("repos") TALKNET_DIR = os.path.join(REPOS_DIR, "TalkNet-ASD") LIGHTASD_DIR = os.path.join(REPOS_DIR, "Light-ASD") TALKNET_CKPT = os.path.join(REPOS_DIR, "pretrain_TalkSet.model") LIGHTASD_CKPT = os.path.join(REPOS_DIR, "lightasd_finetuning_TalkSet.model") TALKSET_GDRIVE_ID = "1AbN9fCf9IexMxEKXLQY2KYBlb-IhSEea" # official TalkNet-ASD link MAX_CLIP_SECONDS = 90 def _run(cmd): subprocess.call(cmd, shell=True, stdout=None) def _setup(): os.makedirs(REPOS_DIR, exist_ok=True) if not os.path.isdir(os.path.join(TALKNET_DIR, ".git")): print("Cloning TalkNet-ASD ...", flush=True) _run(f"git clone --depth 1 https://github.com/TaoRuijie/TalkNet-ASD.git {TALKNET_DIR}") if not os.path.isdir(os.path.join(LIGHTASD_DIR, ".git")): print("Cloning Light-ASD ...", flush=True) _run(f"git clone --depth 1 https://github.com/Junhua-Liao/Light-ASD.git {LIGHTASD_DIR}") if not os.path.isfile(TALKNET_CKPT): print("Downloading TalkNet TalkSet checkpoint (official Google Drive) ...", flush=True) _run(f"gdown {TALKSET_GDRIVE_ID} -O {TALKNET_CKPT}") if not os.path.isfile(TALKNET_CKPT): raise RuntimeError( "TalkNet checkpoint (pretrain_TalkSet.model) could not be downloaded from " f"Google Drive id {TALKSET_GDRIVE_ID}. Upload it to a HF repo and load it " "with hf_hub_download instead." ) from huggingface_hub import hf_hub_download if not os.path.isfile(LIGHTASD_CKPT): src = hf_hub_download( repo_id="blaze-voice-ai/dubbing-light-asd", filename="finetuning_TalkSet.model" ) shutil.copy(src, LIGHTASD_CKPT) # S3FD face-detector weights ship inside the TalkNet-ASD repo. det_weights = glob.glob(os.path.join(TALKNET_DIR, "model", "faceDetector", "*.pth")) + \ glob.glob(os.path.join(TALKNET_DIR, "model", "faceDetector", "*.pt")) if not det_weights: raise RuntimeError( f"S3FD face-detector weights not found under {TALKNET_DIR}/model/faceDetector — " "check the cloned repo contents." ) print("S3FD weights:", det_weights, flush=True) # S3FD resolves its weight file relative to the repo; run from there. os.chdir(TALKNET_DIR) _setup() # --------------------------------------------------------------------------- # Model loading. Both repos expose a package named `model` and a module named # `loss`, so imports are isolated: load one repo's classes, purge sys.modules, # then load the other. Class references stay valid after the purge. # --------------------------------------------------------------------------- def _purge_modules(*prefixes): for name in list(sys.modules): if any(name == p or name.startswith(p + ".") for p in prefixes): del sys.modules[name] class _ScoredWrapper(torch.nn.Module): """Common wrapper: model + the AV loss head that provides the 256->2 FC.""" def __init__(self, model, lossAV): super().__init__() self.model = model self.lossAV = lossAV def load(self, path): # Same copy-in logic as talkNet.loadParameters / ASD.loadParameters, # with map_location='cpu' for ZeroGPU (no GPU at module scope). loaded = torch.load(path, map_location="cpu") own = self.state_dict() for orig, param in loaded.items(): name = orig if orig in own else orig.replace("module.", "") if name not in own or own[name].size() != param.size(): continue # lossA/lossV/optimizer keys not needed for inference own[name].copy_(param) self.load_state_dict(own) @torch.no_grad() def score_track(self, audio, videoFeature, device): """audio: int16 16 kHz wav samples; videoFeature: (T, 224, 224) uint8 gray. Mirrors evaluate_network in demoTalkNet.py (multi-duration scoring).""" import python_speech_features audioFeature = python_speech_features.mfcc( audio, 16000, numcep=13, winlen=0.025, winstep=0.010 ) length = min( (audioFeature.shape[0] - audioFeature.shape[0] % 4) / 100.0, videoFeature.shape[0] / 25.0, ) if length <= 0: return np.array([]) audioFeature = audioFeature[: int(round(length * 100)), :] videoFeature = videoFeature[: int(round(length * 25)), :, :] allScores = [] durationSet = [1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 6] for duration in durationSet: batchSize = int(math.ceil(length / duration)) scores = [] for i in range(batchSize): inputA = ( torch.FloatTensor(audioFeature[i * duration * 100 : (i + 1) * duration * 100, :]) .unsqueeze(0) .to(device) ) inputV = ( torch.FloatTensor(videoFeature[i * duration * 25 : (i + 1) * duration * 25, :, :]) .unsqueeze(0) .to(device) ) embedA = self.model.forward_audio_frontend(inputA) embedV = self.model.forward_visual_frontend(inputV) embedA, embedV = self.model.forward_cross_attention(embedA, embedV) out = self.model.forward_audio_visual_backend(embedA, embedV) x = out.squeeze(1) fc = getattr(self.lossAV, "FC", None) if fc is not None: logits = fc(x) # identical to lossAV.forward(x, labels=None) scores.extend(logits[:, 1].detach().float().cpu().numpy().tolist()) else: scores.extend( np.asarray(self.lossAV.forward(x.unsqueeze(1), labels=None)).tolist() ) allScores.append(scores) return np.round(np.mean(np.array(allScores, dtype=float), axis=0), 1).astype(float) def _load_talknet(): sys.path.insert(0, TALKNET_DIR) from model.talkNetModel import talkNetModel from loss import lossAV from model.faceDetector.s3fd import S3FD w = _ScoredWrapper(talkNetModel(), lossAV()) w.load(TALKNET_CKPT) w.eval() sys.path.remove(TALKNET_DIR) _purge_modules("model", "loss", "audioEncoder", "visualEncoder", "attentionLayer") print("TalkNet loaded (CPU)", flush=True) return w, S3FD def _load_lightasd(): sys.path.insert(0, LIGHTASD_DIR) from model.Model import ASD_Model from loss import lossAV w = _ScoredWrapper(ASD_Model(), lossAV()) w.load(LIGHTASD_CKPT) w.eval() sys.path.remove(LIGHTASD_DIR) _purge_modules("model", "loss", "audioEncoder", "visualEncoder", "attentionLayer") print("Light-ASD loaded (CPU)", flush=True) return w TALKNET, S3FD_CLASS = _load_talknet() LIGHTASD = _load_lightasd() DEVICE = "cuda" # --------------------------------------------------------------------------- # Preprocessing pipeline — transcribed from demoTalkNet.py (MIT), parameterized. # --------------------------------------------------------------------------- def scene_detect(videoFilePath, pyworkPath): videoManager = VideoManager([videoFilePath]) statsManager = StatsManager() sceneManager = SceneManager(statsManager) sceneManager.add_detector(ContentDetector()) baseTimecode = videoManager.get_base_timecode() videoManager.set_downscale_factor() videoManager.start() sceneManager.detect_scenes(frame_source=videoManager) sceneList = sceneManager.get_scene_list(baseTimecode) if sceneList == []: sceneList = [(videoManager.get_base_timecode(), videoManager.get_current_timecode())] with open(os.path.join(pyworkPath, "scene.pckl"), "wb") as fil: pickle.dump(sceneList, fil) return sceneList def face_detect(framesDir, facedetScale, device): """GPU: S3FD face detection. Returns dets per frame.""" det = S3FD_CLASS(device=device) flist = sorted(glob.glob(os.path.join(framesDir, "*.jpg"))) dets = [] for fidx, fname in enumerate(flist): image = cv2.imread(fname) imageNumpy = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) bboxes = det.detect_faces(imageNumpy, conf_th=0.9, scales=[facedetScale]) dets.append([]) for bbox in bboxes: dets[-1].append({"frame": fidx, "bbox": (bbox[:-1]).tolist(), "conf": bbox[-1]}) return dets, flist def bb_iou(boxA, boxB): xA, yA = max(boxA[0], boxB[0]), max(boxA[1], boxB[1]) xB, yB = min(boxA[2], boxB[2]), min(boxA[3], boxB[3]) interArea = max(0, xB - xA) * max(0, yB - yA) boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1]) boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1]) return interArea / float(boxAArea + boxBArea - interArea + 1e-8) def track_shot(sceneFaces, numFailedDet, minTrack, minFaceSize): iouThres = 0.5 tracks = [] while True: track = [] for frameFaces in sceneFaces: for face in frameFaces: if track == []: track.append(face) frameFaces.remove(face) elif face["frame"] - track[-1]["frame"] <= numFailedDet: if bb_iou(face["bbox"], track[-1]["bbox"]) > iouThres: track.append(face) frameFaces.remove(face) continue else: break if track == []: break elif len(track) > minTrack: frameNum = np.array([f["frame"] for f in track]) bboxes = np.array([np.array(f["bbox"]) for f in track]) frameI = np.arange(frameNum[0], frameNum[-1] + 1) bboxesI = [] for ij in range(0, 4): interpfn = interp1d(frameNum, bboxes[:, ij]) bboxesI.append(interpfn(frameI)) bboxesI = np.stack(bboxesI, axis=1) if max(np.mean(bboxesI[:, 2] - bboxesI[:, 0]), np.mean(bboxesI[:, 3] - bboxesI[:, 1])) > minFaceSize: tracks.append({"frame": frameI, "bbox": bboxesI}) return tracks def crop_video(framesDir, track, cropFile, audioFilePath, cropScale): flist = sorted(glob.glob(os.path.join(framesDir, "*.jpg"))) vOut = cv2.VideoWriter(cropFile + "t.avi", cv2.VideoWriter_fourcc(*"XVID"), 25, (224, 224)) dets = {"x": [], "y": [], "s": []} for det in track["bbox"]: dets["s"].append(max((det[3] - det[1]), (det[2] - det[0])) / 2) dets["y"].append((det[1] + det[3]) / 2) dets["x"].append((det[0] + det[2]) / 2) dets["s"] = signal.medfilt(dets["s"], kernel_size=13) dets["x"] = signal.medfilt(dets["x"], kernel_size=13) dets["y"] = signal.medfilt(dets["y"], kernel_size=13) for fidx, frame in enumerate(track["frame"]): bs = dets["s"][fidx] bsi = int(bs * (1 + 2 * cropScale)) image = cv2.imread(flist[frame]) image = np.pad(image, ((bsi, bsi), (bsi, bsi), (0, 0)), "constant", constant_values=(110, 110)) my = dets["y"][fidx] + bsi mx = dets["x"][fidx] + bsi face = image[int(my - bs) : int(my + bs * (1 + cropScale)), int(mx - bs * (1 + cropScale)) : int(mx + bs * (1 + cropScale))] vOut.write(cv2.resize(face, (224, 224))) audioTmp = cropFile + ".wav" audioStart = track["frame"][0] / 25 audioEnd = (track["frame"][-1] + 1) / 25 vOut.release() _run( "ffmpeg -y -i %s -async 1 -ac 1 -vn -acodec pcm_s16le -ar 16000 -ss %.3f -to %.3f %s -loglevel panic" % (audioFilePath, audioStart, audioEnd, audioTmp) ) _run("ffmpeg -y -i %st.avi -i %s -c:v copy -c:a copy %s.avi -loglevel panic" % (cropFile, audioTmp, cropFile)) os.remove(cropFile + "t.avi") return {"track": track, "proc_track": dets} def read_crop_features(cropAvi): """(T, 224, 224) grayscale uint8 center-crop of 224x224 face crops.""" _, audio = wavfile.read(cropAvi.replace(".avi", ".wav")) video = cv2.VideoCapture(cropAvi) videoFeature = [] while video.isOpened(): ret, frames = video.read() if ret: face = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY) face = cv2.resize(face, (224, 224)) face = face[int(112 - (112 / 2)) : int(112 + (112 / 2)), int(112 - (112 / 2)) : int(112 + (112 / 2))] videoFeature.append(face) else: break video.release() return audio, np.array(videoFeature) def visualize(flist, tracks, scores, pyaviPath): """Annotated video: green box = active speaker, red = not (demoTalkNet style).""" faces = [[] for _ in range(len(flist))] for tidx, tr in enumerate(tracks): score = scores[tidx] for fidx, frame in enumerate(tr["track"]["frame"].tolist()): s = np.mean(score[max(fidx - 2, 0) : min(fidx + 3, len(score) - 1)]) faces[frame].append( { "track": tidx, "score": float(s), "s": tr["proc_track"]["s"][fidx], "x": tr["proc_track"]["x"][fidx], "y": tr["proc_track"]["y"][fidx], } ) first = cv2.imread(flist[0]) fw, fh = first.shape[1], first.shape[0] vOut = cv2.VideoWriter( os.path.join(pyaviPath, "video_only.avi"), cv2.VideoWriter_fourcc(*"XVID"), 25, (fw, fh) ) for fidx, fname in enumerate(flist): image = cv2.imread(fname) for face in faces[fidx]: clr = 0 if face["score"] >= 0 else 255 # green when speaking txt = round(face["score"], 1) cv2.rectangle( image, (int(face["x"] - face["s"]), int(face["y"] - face["s"])), (int(face["x"] + face["s"]), int(face["y"] + face["s"])), (0, clr, 255 - clr), 10, ) cv2.putText(image, "%s" % txt, (int(face["x"] - face["s"]), int(face["y"] - face["s"])), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, clr, 255 - clr), 5) vOut.write(image) vOut.release() aviOut = os.path.join(pyaviPath, "video_out.avi") _run( "ffmpeg -y -i %s -i %s -c:v copy -c:a copy %s -loglevel panic" % (os.path.join(pyaviPath, "video_only.avi"), os.path.join(pyaviPath, "audio.wav"), aviOut) ) mp4Out = aviOut.replace(".avi", ".mp4") _run(f"ffmpeg -y -i {aviOut} -c:v libx264 -preset veryfast -crf 23 -c:a aac {mp4Out} -loglevel panic") return mp4Out def _summary_for(modelName, tracks, scores): rows = [] for tidx, tr in enumerate(tracks): frames = tr["track"]["frame"] sc = np.asarray(scores[tidx], dtype=float) speaking = float(np.mean(sc >= 0)) if sc.size else 0.0 rows.append( { "track": tidx, "start_s": round(frames[0] / 25.0, 2), "end_s": round((frames[-1] + 1) / 25.0, 2), "speaking_frames_pct": round(speaking * 100, 1), "mean_score": round(float(np.mean(sc)), 2) if sc.size else None, } ) return rows # --------------------------------------------------------------------------- # Gradio UI # --------------------------------------------------------------------------- @spaces.GPU(duration=180) def run_inference(video_path, clip_seconds, model_choice): if not video_path: raise gr.Error("Please upload a video first.") workdir = "/tmp/asd_run" if os.path.isdir(workdir): shutil.rmtree(workdir) pyaviPath = os.path.join(workdir, "pyavi") pyframesPath = os.path.join(workdir, "pyframes") pyworkPath = os.path.join(workdir, "pywork") pycropPath = os.path.join(workdir, "pycrop") for p in (pyaviPath, pyframesPath, pyworkPath, pycropPath): os.makedirs(p, exist_ok=True) clip_seconds = int(min(max(clip_seconds, 5), MAX_CLIP_SECONDS)) # Extract (capped) video, audio, frames — as in demoTalkNet main() videoFilePath = os.path.join(pyaviPath, "video.avi") _run( "ffmpeg -y -i %s -qscale:v 2 -ss 0 -t %d -async 1 -r 25 %s -loglevel panic" % (video_path, clip_seconds, videoFilePath) ) audioFilePath = os.path.join(pyaviPath, "audio.wav") _run("ffmpeg -y -i %s -qscale:a 0 -ac 1 -vn -ar 16000 %s -loglevel panic" % (videoFilePath, audioFilePath)) _run("ffmpeg -y -i %s -qscale:v 2 -f image2 %s -loglevel panic" % (videoFilePath, os.path.join(pyframesPath, "%06d.jpg"))) flist = sorted(glob.glob(os.path.join(pyframesPath, "*.jpg"))) if not flist: raise gr.Error("Could not decode any frames — is the file a valid video?") sceneList = scene_detect(videoFilePath, pyworkPath) dets, flist = face_detect(pyframesPath, 0.25, DEVICE) allTracks = [] for shot in sceneList: if shot[1].frame_num - shot[0].frame_num >= 10: allTracks.extend(track_shot(dets[shot[0].frame_num : shot[1].frame_num], 10, 10, 1)) if not allTracks: raise gr.Error("No face tracks found in the clip.") vidTracks = [ crop_video(pyframesPath, track, os.path.join(pycropPath, "%05d" % ii), audioFilePath, 0.40) for ii, track in enumerate(allTracks) ] files = sorted(glob.glob(os.path.join(pycropPath, "*.avi"))) crops = [read_crop_features(f) for f in files] summary, videos = {}, {} run_talknet = model_choice in ("TalkNet (TalkSet)", "Both") run_light = model_choice in ("Light-ASD (TalkSet-finetuned)", "Both") if run_talknet: TALKNET.to(DEVICE) scores = [TALKNET.score_track(a, v, DEVICE) for (a, v) in crops] videos["TalkNet"] = visualize(flist, vidTracks, scores, pyaviPath) summary["TalkNet (TalkSet)"] = _summary_for("TalkNet", vidTracks, scores) if run_light: LIGHTASD.to(DEVICE) scores = [LIGHTASD.score_track(a, v, DEVICE) for (a, v) in crops] videos["Light-ASD"] = visualize(flist, vidTracks, scores, pyaviPath) summary["Light-ASD (TalkSet-finetuned)"] = _summary_for("Light-ASD", vidTracks, scores) return ( videos.get("TalkNet") if run_talknet else None, videos.get("Light-ASD") if run_light else None, summary, ) with gr.Blocks(title="Active Speaker Detection — TalkNet + Light-ASD") as demo: gr.Markdown( "## 🗣️ Active Speaker Detection — TalkNet + Light-ASD\n" "Upload a short video and get per-face speaking scores: **green box = active speaker**, " "red = silent. Score ≥ 0 means 'speaking' (TalkNet convention). " "Adapted from MIT-licensed [TalkNet-ASD](https://github.com/TaoRuijie/TalkNet-ASD) and " "[Light-ASD](https://github.com/Junhua-Liao/Light-ASD)." ) with gr.Row(): with gr.Column(): video_in = gr.Video(label="Input video", sources=["upload"]) clip = gr.Slider(5, MAX_CLIP_SECONDS, value=60, step=5, label="Clip length from start (s)") choice = gr.Radio( ["TalkNet (TalkSet)", "Light-ASD (TalkSet-finetuned)", "Both"], value="Both", label="Model", ) btn = gr.Button("Detect speakers", variant="primary") with gr.Column(): out_tn = gr.Video(label="TalkNet output") out_la = gr.Video(label="Light-ASD output") out_json = gr.JSON(label="Per-track summary (speaking % per track)") gr.Markdown( "**License note.** Code is MIT. The pretrained checkpoints were trained on TalkSet " "(modified VoxCeleb2 + LRS3) — research-restricted provenance, **not certified for " "commercial use**. Research demo only.\n\n" "Pipeline: scene detection → S3FD faces → IOU tracking → 112×112 mouth-region crops → " "audio-visual scoring at 25 fps / 16 kHz." ) btn.click(run_inference, [video_in, clip, choice], [out_tn, out_la, out_json]) demo.launch()