Update app.py
Browse files4 unmodified lines5678910111 unmodified line1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981991 unmodified line2012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093104 unmodified linesimport librosaimport cv2import refrom transformers import Wav2Vec2Processor, Wav2Vec2Model, AutoTokenizer, AutoModelfrom torchvision import modelsimport tempfileimport os1 unmodified lineimport whisperimport subprocess# ConfigurationDEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")SAMPLE_RATE = 16000TEXT_MAX_LEN = 64LABELS = ["angry", "happy", "neutral", "sad"]# Load processorsprocessor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")# Model Architecture (same as training)class ResNetVideoEncoder(nn.Module):def __init__(self, out_dim=768):super().__init__()base = models.resnet18(pretrained=False)self.backbone = nn.Sequential(*list(base.children())[:-1])self.proj = nn.Linear(512, out_dim)def forward(self, x):B, C, T, H, W = x.shapefeats = []for t in range(T):ft = self.backbone(x[:, :, t])feats.append(ft.squeeze(-1).squeeze(-1))feats = torch.stack(feats, dim=1).mean(1)return self.proj(feats)def mean_pool(x, mask):mask = mask[:, :x.size(1)]mask = mask.unsqueeze(-1).float()return (x * mask).sum(1) / mask.sum(1).clamp(min=1e-6)class HBF(nn.Module):def __init__(self, d=768, n_layers=6):super().__init__()self.proj_a = nn.ModuleList([nn.Linear(d, d) for _ in range(n_layers)])self.proj_t = nn.ModuleList([nn.Linear(d, d) for _ in range(n_layers)])self.proj_v = nn.ModuleList([nn.Linear(d, d) for _ in range(n_layers)])self.fwd1 = nn.ModuleList([nn.Linear(3*d, d) for _ in range(n_layers)])self.fwd2 = nn.ModuleList([nn.Linear(d, d) for _ in range(n_layers)])self.drop = nn.Dropout(0.1)self.act1, self.act2 = nn.GELU(), nn.Tanh()self.n = n_layersdef forward(self, a, t, v):v_prev = Nonefor i in range(self.n):va = self.act2(self.drop(self.proj_a[i](a)))vt = self.act2(self.drop(self.proj_t[i](t)))vv = self.act2(self.drop(self.proj_v[i](v)))cat = torch.cat([va, vt, vv] if v_prev is None else [va, vt, v_prev], -1)x = self.act1(self.fwd1[i](cat))v_prev = self.fwd2[i](x)return v_prevclass AVVideoModel(nn.Module):def __init__(self, num_classes, n_layers=6):super().__init__()self.a_enc = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")self.t_enc = AutoModel.from_pretrained("bert-base-uncased")self.v_enc = ResNetVideoEncoder()self.hbf = HBF(n_layers=n_layers)self.fc = nn.Linear(768, num_classes)self.fc_audio = nn.Linear(768, num_classes)self.fc_text = nn.Linear(768, num_classes)self.fc_video = nn.Linear(768, num_classes)def forward(self, audio, audio_mask, text_ids, text_mask, video):a_out = self.a_enc(audio, attention_mask=audio_mask, return_dict=True)t_out = self.t_enc(input_ids=text_ids, attention_mask=text_mask, return_dict=True)a_pool = mean_pool(a_out.last_hidden_state, audio_mask)t_pool = mean_pool(t_out.last_hidden_state, text_mask)v_pool = self.v_enc(video)a_pool = torch.nan_to_num(a_pool, nan=0.0, posinf=1e4, neginf=-1e4)t_pool = torch.nan_to_num(t_pool, nan=0.0, posinf=1e4, neginf=-1e4)v_pool = torch.nan_to_num(v_pool, nan=0.0, posinf=1e4, neginf=-1e4)a_logits = self.fc_audio(a_pool)t_logits = self.fc_text(t_pool)v_logits = self.fc_video(v_pool)fused = self.hbf(a_pool, t_pool, v_pool)fused = torch.nan_to_num(fused, nan=0.0, posinf=1e4, neginf=-1e4)fused_logits = self.fc(fused)return fused_logits, a_logits, t_logits, v_logits# Load modelmodel = AVVideoModel(num_classes=len(LABELS)).to(DEVICE)# Download model from Hugging Face Model Hubtry:model_path = hf_hub_download(repo_id="ApurvaKondekar/emotion_model", # CHANGE THISfilename="model_weights.pth" # YOUR FILE NAME)model.load_state_dict(torch.load(model_path, map_location=DEVICE))model.eval()print("β Model loaded from Hugging Face")except Exception as e:print(f"β Failed to load model: {e}")# Alternative: Create a dummy model for testing# Load trained weights (you'll need to upload this)if os.path.exists("model_weights.pth"):model.load_state_dict(torch.load("model_weights.pth", map_location=DEVICE))model.eval()print("β Model loaded successfully")else:print("β οΈ No model weights found. Using untrained model for demo.")def extract_video_frames(video_path, max_frames=8, resize=(224, 224)):"""Extract frames from video file"""cap = cv2.VideoCapture(video_path)if not cap.isOpened():return Noneframes = []while len(frames) < max_frames:ret, frame = cap.read()if not ret:breakframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)frame = cv2.resize(frame, resize)frames.append(frame)cap.release()if len(frames) == 0:return None# Pad if neededwhile len(frames) < max_frames:frames.append(frames[-1])frames = np.array(frames[:max_frames], dtype=np.uint8)return framesdef extract_audio_from_video(video_path):"""Extract audio from video file using ffmpeg"""try:audio_path = tempfile.NamedTemporaryFile(delete=False, suffix=".wav").name# Use ffmpeg to extract audioimport subprocesscommand = ['ffmpeg', '-i', video_path,'-vn', # No video'-acodec', 'pcm_s16le', # Audio codec'-ar', str(SAMPLE_RATE), # Sample rate'-ac', '1', # Mono'-y', # Overwriteaudio_path]subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)return audio_pathexcept Exception as e:raise ValueError(f"Could not extract audio from video: {str(e)}")def transcribe_audio(audio_path):"""Transcribe audio using Whisper"""try:whisper_model = whisper.load_model("base")result = whisper_model.transcribe(audio_path)return result["text"].strip()except Exception as e:raise ValueError(f"Could not transcribe audio: {str(e)}")def preprocess_inputs(audio_path, text, video_path):"""Preprocess all three modalities"""# Audiowav, _ = librosa.load(audio_path, sr=SAMPLE_RATE)audio_inputs = processor(wav, sampling_rate=SAMPLE_RATE, return_tensors="pt")audio_values = audio_inputs.input_values.to(DEVICE)audio_mask = torch.ones_like(audio_values).to(DEVICE)# Texttext_clean = re.sub(r"[^a-zA-Z0-9\s]", "", text.lower())text_inputs = tokenizer(text_clean,truncation=True,1 unmodified linemax_length=TEXT_MAX_LEN,return_tensors="pt")text_ids = text_inputs.input_ids.to(DEVICE)text_mask = text_inputs.attention_mask.to(DEVICE)# Videoframes = extract_video_frames(video_path)if frames is None:raise ValueError("Could not extract frames from video")frames_tensor = torch.tensor(frames).permute(0, 3, 1, 2).float() / 255.0frames_tensor = frames_tensor.unsqueeze(0).permute(0, 2, 1, 3, 4).to(DEVICE)return audio_values, audio_mask, text_ids, text_mask, frames_tensordef predict_emotion(video_file):"""Main prediction function - takes only video input"""if video_file is None:return "Please provide a video file", None, ""try:# Extract audio from videoaudio_path = extract_audio_from_video(video_file)# Transcribe audiotranscribed_text = transcribe_audio(audio_path)# Preprocess all modalitiesaudio, audio_mask, text_ids, text_mask, video = preprocess_inputs(audio_path, transcribed_text, video_file)# Inferencewith torch.no_grad():fused_logits, a_logits, t_logits, v_logits = model(audio, audio_mask, text_ids, text_mask, video)# Get probabilitiesfused_probs = torch.softmax(fused_logits, dim=1)[0].cpu().numpy()# Format resultsresult = {LABELS[i]: float(fused_probs[i]) for i in range(len(LABELS))}predicted_emotion = LABELS[fused_probs.argmax()]confidence = float(fused_probs.max())result_text = f"π― **Predicted Emotion: {predicted_emotion.upper()}**\n\n**Confidence: {confidence:.2%}**"# Clean up temporary audio fileif os.path.exists(audio_path):os.remove(audio_path)return result_text, result, transcribed_textexcept Exception as e:return f"Error: {str(e)}", None, ""# Gradio Interfacewith gr.Blocks(title="Multimodal Emotion Recognition", theme=gr.themes.Soft()) as demo:gr.Markdown("""# π Multimodal Emotion RecognitionThis system predicts emotions from video by automatically extracting and analyzing:- π€ **Audio** (extracted from video)- π **Text** (transcribed from audio using Whisper)- π₯ **Video** (visual frames)### How to use:1. Upload a video file (MP4, AVI, MOV, etc.)2. Click "Predict Emotion"3. The system will automatically extract audio, transcribe speech, and analyze all modalitiesThe model will provide emotion predictions based on all three inputs.""")with gr.Row():with gr.Column():video_input = gr.Video(label="π₯ Video Input")predict_btn = gr.Button("π Predict Emotion", variant="primary", size="lg")with gr.Column():result_text = gr.Markdown(label="Result")result_output = gr.Label(label="π Prediction Results", num_top_classes=4)transcription_output = gr.Textbox(label="π Transcribed Text", lines=3, interactive=False)predict_btn.click(fn=predict_emotion,inputs=[video_input],outputs=[result_text, result_output, transcription_output])gr.Markdown("""---### π Notes:- Supported emotions: **Angry, Happy, Neutral, Sad**- Model uses Wav2Vec2 (audio), BERT (text), and ResNet18 (video)- Best results with clear audio, accurate transcripts, and visible faces""")if __name__ == "__main__":demo.launch()4 unmodified lines56789101112131415161 unmodified line181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084091 unmodified line4114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317324 unmodified linesimport librosaimport cv2import refrom transformers import (Wav2Vec2Processor,Wav2Vec2Model,AutoTokenizer,AutoModel)from torchvision import modelsimport tempfileimport os1 unmodified lineimport whisperimport subprocess# =========================================================# CONFIGURATION# =========================================================DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")SAMPLE_RATE = 16000TEXT_MAX_LEN = 64LABELS = ["angry", "happy", "neutral", "sad"]gpu_status = "π’ GPU Enabled" if torch.cuda.is_available() else "π΄ CPU Mode"# =========================================================# LOAD PROCESSORS# =========================================================processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")# =========================================================# MODEL ARCHITECTURE# =========================================================class ResNetVideoEncoder(nn.Module):def __init__(self, out_dim=768):super().__init__()base = models.resnet18(pretrained=False)self.backbone = nn.Sequential(*list(base.children())[:-1])self.proj = nn.Linear(512, out_dim)def forward(self, x):B, C, T, H, W = x.shapefeats = []for t in range(T):ft = self.backbone(x[:, :, t])feats.append(ft.squeeze(-1).squeeze(-1))feats = torch.stack(feats, dim=1).mean(1)return self.proj(feats)# =========================================================def mean_pool(x, mask):mask = mask[:, :x.size(1)]mask = mask.unsqueeze(-1).float()return ((x * mask).sum(1)/ mask.sum(1).clamp(min=1e-6))# =========================================================class HBF(nn.Module):def __init__(self, d=768, n_layers=6):super().__init__()self.proj_a = nn.ModuleList([nn.Linear(d, d) for _ in range(n_layers)])self.proj_t = nn.ModuleList([nn.Linear(d, d) for _ in range(n_layers)])self.proj_v = nn.ModuleList([nn.Linear(d, d) for _ in range(n_layers)])self.fwd1 = nn.ModuleList([nn.Linear(3*d, d) for _ in range(n_layers)])self.fwd2 = nn.ModuleList([nn.Linear(d, d) for _ in range(n_layers)])self.drop = nn.Dropout(0.1)self.act1 = nn.GELU()self.act2 = nn.Tanh()self.n = n_layersdef forward(self, a, t, v):v_prev = Nonefor i in range(self.n):va = self.act2(self.drop(self.proj_a[i](a)))vt = self.act2(self.drop(self.proj_t[i](t)))vv = self.act2(self.drop(self.proj_v[i](v)))cat = torch.cat([va, vt, vv]if v_prev is Noneelse [va, vt, v_prev],-1)x = self.act1(self.fwd1[i](cat))v_prev = self.fwd2[i](x)return v_prev# =========================================================class AVVideoModel(nn.Module):def __init__(self, num_classes, n_layers=6):super().__init__()self.a_enc = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")self.t_enc = AutoModel.from_pretrained("bert-base-uncased")self.v_enc = ResNetVideoEncoder()self.hbf = HBF(n_layers=n_layers)self.fc = nn.Linear(768, num_classes)self.fc_audio = nn.Linear(768, num_classes)self.fc_text = nn.Linear(768, num_classes)self.fc_video = nn.Linear(768, num_classes)def forward(self,audio,audio_mask,text_ids,text_mask,video):a_out = self.a_enc(audio,attention_mask=audio_mask,return_dict=True)t_out = self.t_enc(input_ids=text_ids,attention_mask=text_mask,return_dict=True)a_pool = mean_pool(a_out.last_hidden_state,audio_mask)t_pool = mean_pool(t_out.last_hidden_state,text_mask)v_pool = self.v_enc(video)a_pool = torch.nan_to_num(a_pool)t_pool = torch.nan_to_num(t_pool)v_pool = torch.nan_to_num(v_pool)fused = self.hbf(a_pool, t_pool, v_pool)fused = torch.nan_to_num(fused)fused_logits = self.fc(fused)return fused_logits# =========================================================# LOAD MODEL# =========================================================model = AVVideoModel(num_classes=len(LABELS)).to(DEVICE)try:model_path = hf_hub_download(repo_id="ApurvaKondekar/emotion_model",filename="model_weights.pth")model.load_state_dict(torch.load(model_path, map_location=DEVICE))model.eval()print("β Model loaded successfully")except Exception as e:print(f"β Error loading model: {e}")# =========================================================# VIDEO PROCESSING# =========================================================def extract_video_frames(video_path,max_frames=8,resize=(224, 224)):cap = cv2.VideoCapture(video_path)if not cap.isOpened():return Nonetotal_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))indices = np.linspace(0,total_frames - 1,max_frames,dtype=int)frames = []for idx in indices:cap.set(cv2.CAP_PROP_POS_FRAMES, idx)ret, frame = cap.read()if not ret:continueframe = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)frame = cv2.resize(frame, resize)frames.append(frame)cap.release()if len(frames) == 0:return Nonewhile len(frames) < max_frames:frames.append(frames[-1])frames = np.array(frames[:max_frames])return frames# =========================================================# AUDIO EXTRACTION# =========================================================def extract_audio_from_video(video_path):try:audio_path = tempfile.NamedTemporaryFile(delete=False,suffix=".wav").namecommand = ["ffmpeg","-i", video_path,"-vn","-acodec", "pcm_s16le","-ar", str(SAMPLE_RATE),"-ac", "1","-y",audio_path]subprocess.run(command,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)return audio_pathexcept Exception as e:raise ValueError(f"Audio extraction failed: {str(e)}")# =========================================================# TRANSCRIPTION# =========================================================whisper_model = whisper.load_model("base")def transcribe_audio(audio_path):try:result = whisper_model.transcribe(audio_path)return result["text"].strip()except Exception as e:raise ValueError(f"Transcription failed: {str(e)}")# =========================================================# PREPROCESSING# =========================================================def preprocess_inputs(audio_path,text,video_path):# AUDIOwav, _ = librosa.load(audio_path,sr=SAMPLE_RATE)audio_inputs = processor(wav,sampling_rate=SAMPLE_RATE,return_tensors="pt")audio_values = audio_inputs.input_values.to(DEVICE)audio_mask = torch.ones_like(audio_values).to(DEVICE)# TEXTtext_clean = re.sub(r"[^a-zA-Z0-9\s]","",text.lower())text_inputs = tokenizer(text_clean,truncation=True,1 unmodified linemax_length=TEXT_MAX_LEN,return_tensors="pt")text_ids = text_inputs.input_ids.to(DEVICE)text_mask = text_inputs.attention_mask.to(DEVICE)# VIDEOframes = extract_video_frames(video_path)if frames is None:raise ValueError("Could not extract video frames")frames_tensor = (torch.tensor(frames).permute(0, 3, 1, 2).float() / 255.0)frames_tensor = (frames_tensor.unsqueeze(0).permute(0, 2, 1, 3, 4).to(DEVICE))return (audio_values,audio_mask,text_ids,text_mask,frames_tensor)# =========================================================# PREDICTION FUNCTION# =========================================================def predict_emotion(video_file):if video_file is None:return ("β Please upload a video",None,"")try:# EXTRACT AUDIOaudio_path = extract_audio_from_video(video_file)# TRANSCRIBEtranscribed_text = transcribe_audio(audio_path)# PREPROCESS(audio,audio_mask,text_ids,text_mask,video) = preprocess_inputs(audio_path,transcribed_text,video_file)# INFERENCEwith torch.no_grad():logits = model(audio,audio_mask,text_ids,text_mask,video)probs = torch.softmax(logits,dim=1)[0].cpu().numpy()result = {LABELS[i]: float(probs[i])for i in range(len(LABELS))}predicted_emotion = LABELS[probs.argmax()]confidence = float(probs.max())emoji_map = {"happy": "π","sad": "π’","angry": "π ","neutral": "π"}result_text = f"""# {emoji_map[predicted_emotion]} {predicted_emotion.upper()}## Confidence Score### {confidence:.2%}"""# CLEANUPif os.path.exists(audio_path):os.remove(audio_path)return (result_text,result,transcribed_text)except Exception as e:return (f"β Error: {str(e)}",None,"")# =========================================================# CUSTOM CSS# =========================================================custom_css = """body {background: linear-gradient(to right,#0f172a,#1e293b);}.gradio-container {max-width: 1200px !important;margin: auto;}.main-title {text-align: center;font-size: 48px;font-weight: 800;color: white;margin-top: 20px;}.subtitle {text-align: center;font-size: 18px;color: #cbd5e1;margin-bottom: 25px;}.footer {text-align: center;color: #94a3b8;margin-top: 30px;font-size: 14px;}"""# =========================================================# UI# =========================================================with gr.Blocks(theme=gr.themes.Glass(),css=custom_css,title="Emotion Recognition") as demo:# HEADERgr.HTML("""<div class="main-title">π Multimodal Emotion Recognition</div><div class="subtitle">AI-powered Emotion Detection using Audio, Text & Video Fusion</div>""")gr.Markdown(f"### {gpu_status}")# INFO SECTIONwith gr.Row():with gr.Column():gr.Markdown("""### π Modalities- π€ Audio- π Text- π₯ Video""")with gr.Column():gr.Markdown("""### π€ Models Used- Wav2Vec2- BERT- ResNet18- Whisper""")gr.Markdown("---")# MAIN SECTIONwith gr.Row(equal_height=True):# LEFT SIDEwith gr.Column(scale=1):gr.Markdown("## π€ Upload Video")video_input = gr.Video(label="Input Video",height=350)predict_btn = gr.Button("π Analyze Emotion",variant="primary",size="lg")# RIGHT SIDEwith gr.Column(scale=1):gr.Markdown("## π Results")result_text = gr.Markdown(value="Upload a video to begin analysis")result_output = gr.Label(label="Emotion Probabilities",num_top_classes=4)transcription_output = gr.Textbox(label="π Transcribed Text",lines=5,interactive=False)gr.Markdown("---")# ABOUT MODELwith gr.Accordion("βΉοΈ About This Model",open=False):gr.Markdown("""This system combines:### π€ Audio AnalysisWav2Vec2 captures emotional tone and speech patterns.### π Text AnalysisBERT analyzes semantic meaning from transcripts.### π₯ Video AnalysisResNet18 extracts facial expression features.### π§ Fusion NetworkHBF combines all modalities for final prediction.---Supported Emotions:- Angry- Happy- Neutral- Sad""")# FOOTERgr.HTML("""<div class="footer">Built with β€οΈ using PyTorch, Transformers, Whisper & Gradio</div>""")# BUTTON ACTIONpredict_btn.click(fn=predict_emotion,inputs=[video_input],outputs=[result_text,result_output,transcription_output],show_progress=True)# =========================================================# LAUNCH# =========================================================if __name__ == "__main__":demo.queue()demo.launch()
app.py+597-175