Spaces:
Build error
Build error
Kevin King commited on
Commit ·
f596015
1
Parent(s): a667ff5
FEAT: Refactor app for post-hoc file upload analysis
Browse filesFiles changed (3)
- requirements.txt+4-3
- src/streamlit_app.py+164-32
- src/streamlit_app.py.oldDeleted-199
123456789--extra-index-url https://download.pytorch.org/whl/cpu# Pin the main UI components to recent, stable versionsstreamlit==1.35.0streamlit-webrtc==0.47.0streamlit-autorefresh==1.0.1# Pin ML/AI libraries to modern, known-good versionstransformers==4.40.112345678910--extra-index-url https://download.pytorch.org/whl/cpu# Core app and UI librarystreamlit==1.35.0# Library for video/audio file handlingmoviepy# Pin ML/AI libraries to modern, known-good versionstransformers==4.40.1
1234567891011121314151617181920212223242526272829303132333435363738394041import streamlit as stfrom streamlit_webrtc import webrtc_streamer, WebRtcMode, RTCConfigurationimport av# --- Page Configuration ---st.set_page_config(page_title="AffectLink Webcam Test",page_icon="📸",layout="wide")st.title("AffectLink: Webcam Feed Test")st.write("This is a minimal test to check if the webcam video stream can be established.")# --- WebRTC Configuration ---# Using a robust list of public STUN servers to help establish a connectionRTC_CONFIGURATION = RTCConfiguration({"iceServers": [{"urls": ["stun:stun.l.google.com:19302","stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302","stun:stun3.l.google.com:19302","stun:stun4.l.google.com:19302",]}]})# A simple "pass-through" function that returns the frame without modificationdef video_frame_callback(frame: av.VideoFrame) -> av.VideoFrame:return frame# --- WebRTC Streamer ---webrtc_streamer(key="webcam-test",mode=WebRtcMode.SENDRECV,rtc_configuration=RTC_CONFIGURATION,media_stream_constraints={"video": True, "audio": False},video_frame_callback=video_frame_callback,async_processing=True,)st.sidebar.info("This is a test page. All AI analysis and audio processing has been disabled.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173import osimport streamlit as stimport numpy as npimport torchimport whisperfrom transformers import pipeline, AutoModelForAudioClassification, AutoFeatureExtractorfrom deepface import DeepFaceimport loggingimport soundfile as sffrom scipy.io.wavfile import write as write_wavimport tempfilefrom PIL import Imageimport cv2from moviepy.editor import VideoFileClip# Set home directories for model caching inside the app's writable directoryos.environ['DEEPFACE_HOME'] = '/tmp/.deepface'os.environ['HF_HOME'] = '/tmp/huggingface'# --- Page Configuration ---st.set_page_config(page_title="AffectLink Batch Demo",page_icon="😊",layout="wide")st.title("AffectLink: Post-Hoc Emotion Analysis")st.write("Upload a short video clip to analyze facial expressions, speech-to-text, and the emotional tone of the audio.")# --- Logger Configuration ---logging.basicConfig(level=logging.INFO)logging.getLogger('deepface').setLevel(logging.ERROR)logging.getLogger('huggingface_hub').setLevel(logging.WARNING)logging.getLogger('moviepy').setLevel(logging.ERROR)# --- Emotion Mappings ---UNIFIED_EMOTIONS = ['neutral', 'happy', 'sad', 'angry']TEXT_TO_UNIFIED = {'neutral': 'neutral', 'joy': 'happy', 'sadness': 'sad', 'anger': 'angry','fear': None, 'surprise': None, 'disgust': None}SER_TO_UNIFIED = {'neu': 'neutral', 'hap': 'happy', 'sad': 'sad', 'ang': 'angry'}AUDIO_SAMPLE_RATE = 16000# --- Model Loading ---@st.cache_resourcedef load_models():with st.spinner("Loading AI models, this may take a moment..."):whisper_model = whisper.load_model("base", download_root="/tmp/whisper_cache")text_classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", top_k=None)ser_model_name = "superb/hubert-large-superb-er"ser_feature_extractor = AutoFeatureExtractor.from_pretrained(ser_model_name)ser_model = AutoModelForAudioClassification.from_pretrained(ser_model_name)return whisper_model, text_classifier, ser_model, ser_feature_extractorwhisper_model, text_classifier, ser_model, ser_feature_extractor = load_models()# --- UI and Processing Logic ---uploaded_file = st.file_uploader("Choose a video file...", type=["mp4", "mov", "avi"])if uploaded_file is not None:# Save the uploaded file to a temporary locationwith tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tfile:tfile.write(uploaded_file.read())temp_video_path = tfile.namest.video(temp_video_path)if st.button("Analyze Video"):facial_analysis_results = []audio_analysis_results = {}# --- Video Processing for Facial Emotion ---with st.spinner("Analyzing video for facial expressions..."):try:cap = cv2.VideoCapture(temp_video_path)fps = cap.get(cv2.CAP_PROP_FPS)frame_count = 0while cap.isOpened():ret, frame = cap.read()if not ret:break# Process one frame per secondif frame_count % int(fps) == 0:timestamp = frame_count / fpsanalysis = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False, silent=True)if isinstance(analysis, list) and len(analysis) > 0:dominant_emotion = analysis[0]['dominant_emotion']facial_analysis_results.append((timestamp, dominant_emotion.capitalize()))frame_count += 1cap.release()except Exception as e:st.error(f"An error occurred during facial analysis: {e}")# --- Audio Extraction and Processing ---with st.spinner("Extracting and analyzing audio..."):try:# Extract audio using moviepyvideo_clip = VideoFileClip(temp_video_path)with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as taudio:video_clip.audio.write_audiofile(taudio.name, fps=AUDIO_SAMPLE_RATE, logger=None)temp_audio_path = taudio.name# 1. Speech-to-Text (Whisper)result = whisper_model.transcribe(temp_audio_path, fp16=False)transcribed_text = result['text']audio_analysis_results['Transcription'] = transcribed_text# 2. Text-based Emotionif transcribed_text:text_emotions = text_classifier(transcribed_text)[0]unified_text_scores = {e: 0.0 for e in UNIFIED_EMOTIONS}for emo in text_emotions:unified_emo = TEXT_TO_UNIFIED.get(emo['label'])if unified_emo:unified_text_scores[unified_emo] += emo['score']dominant_text_emotion = max(unified_text_scores, key=unified_text_scores.get)audio_analysis_results['Text Emotion'] = dominant_text_emotion.capitalize()# 3. Speech Emotion Recognition (SER)audio_array, _ = sf.read(temp_audio_path)inputs = ser_feature_extractor(audio_array, sampling_rate=AUDIO_SAMPLE_RATE, return_tensors="pt", padding=True)with torch.no_grad():logits = ser_model(**inputs).logitsscores = torch.nn.functional.softmax(logits, dim=1).squeeze()unified_ser_scores = {e: 0.0 for e in UNIFIED_EMOTIONS}for i, score in enumerate(scores):raw_emo = ser_model.config.id2label[i]unified_emo = SER_TO_UNIFIED.get(raw_emo)if unified_emo:unified_ser_scores[unified_emo] += score.item()dominant_ser_emotion = max(unified_ser_scores, key=unified_ser_scores.get)audio_analysis_results['Speech Emotion'] = dominant_ser_emotion.capitalize()# Clean up temp audio fileos.unlink(temp_audio_path)except Exception as e:st.error(f"An error occurred during audio analysis: {e}")finally:video_clip.close()# --- Display Results ---st.header("Analysis Results")col1, col2 = st.columns(2)with col1:st.subheader("Audio Analysis")if audio_analysis_results:st.write(f"**Transcription:** \"{audio_analysis_results.get('Transcription', 'N/A')}\"")st.metric("Emotion from Text", audio_analysis_results.get('Text Emotion', 'N/A'))st.metric("Emotion from Speech", audio_analysis_results.get('Speech Emotion', 'N/A'))else:st.write("No audio results to display.")with col2:st.subheader("Facial Expression Timeline")if facial_analysis_results:for timestamp, emotion in facial_analysis_results:st.write(f"**Time {int(timestamp // 60):02d}:{int(timestamp % 60):02d}:** {emotion}")else:st.write("No faces detected or video processing failed.")# Clean up temp video fileos.unlink(temp_video_path)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import osimport streamlit as st
# Set home directories for model caching inside the app's writable directoryos.environ['DEEPFACE_HOME'] = '/tmp/.deepface'os.environ['HF_HOME'] = '/tmp/huggingface'
from streamlit_webrtc import webrtc_streamer, WebRtcMode, RTCConfigurationimport avimport numpy as npimport torchimport whisperfrom transformers import pipeline, AutoModelForAudioClassification, AutoFeatureExtractorfrom deepface import DeepFaceimport loggingimport queueimport soundfile as sffrom scipy.io.wavfile import write as write_wavimport tempfile
# --- Page Configuration ---st.set_page_config( page_title="AffectLink Online Demo", page_icon="😊", layout="wide")
st.title("AffectLink: Real-time Emotion Recognition")st.write("This demo analyzes your facial expressions in real-time and processes short audio clips for speech and text-based emotion.")
# --- Logger Configuration ---logging.basicConfig(level=logging.INFO)logging.getLogger('deepface').setLevel(logging.ERROR)logging.getLogger('huggingface_hub').setLevel(logging.WARNING)
# --- Emotion Mappings ---UNIFIED_EMOTIONS = ['neutral', 'happy', 'sad', 'angry']FACIAL_TO_UNIFIED = { 'neutral': 'neutral', 'happy': 'happy', 'sad': 'sad', 'angry': 'angry', 'fear': None, 'surprise': None, 'disgust': None}TEXT_TO_UNIFIED = { 'neutral': 'neutral', 'joy': 'happy', 'sadness': 'sad', 'anger': 'angry', 'fear': None, 'surprise': None, 'disgust': None}SER_TO_UNIFIED = { 'neu': 'neutral', 'hap': 'happy', 'sad': 'sad', 'ang': 'angry'}AUDIO_SAMPLE_RATE = 16000
# --- Model Loading ---@st.cache_resourcedef load_models(): with st.spinner("Loading AI models... This may take a moment on first run."): whisper_model = whisper.load_model("base", download_root="/tmp/whisper_cache") text_classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", top_k=None) ser_model_name = "superb/hubert-large-superb-er" ser_feature_extractor = AutoFeatureExtractor.from_pretrained(ser_model_name) ser_model = AutoModelForAudioClassification.from_pretrained(ser_model_name) return whisper_model, text_classifier, ser_model, ser_feature_extractor
whisper_model, text_classifier, ser_model, ser_feature_extractor = load_models()
# --- WebRTC and Video Processing ---# === THIS IS THE UPDATED CONFIGURATION ===RTC_CONFIGURATION = RTCConfiguration( {"iceServers": [{"urls": [ "stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302", "stun:stun2.l.google.com:19302", "stun:stun3.l.google.com:19302", "stun:stun4.l.google.com:19302", ]}]})# ==========================================
webrtc_ctx = webrtc_streamer( key="affectlink-video", mode=WebRtcMode.SENDRECV, rtc_configuration=RTC_CONFIGURATION, # Use the new config media_stream_constraints={"video": True, "audio": False}, async_processing=True,)
if 'facial_emotion' not in st.session_state: st.session_state.facial_emotion = "Neutral"if 'last_emotion_time' not in st.session_state: st.session_state.last_emotion_time = 0
def video_frame_callback(frame: av.VideoFrame) -> av.VideoFrame: img = frame.to_ndarray(format="bgr24") current_time = st.session_state.get('last_emotion_time', 0) if torch.cuda.is_available() or (hasattr(st.session_state, 'last_emotion_time') and (torch.tensor(current_time).item() + 5 < torch.tensor(frame.time).item())): try: analysis = DeepFace.analyze(img, actions=['emotion'], enforce_detection=False, silent=True) if isinstance(analysis, list) and len(analysis) > 0: dominant_emotion = analysis[0]['dominant_emotion'] st.session_state.facial_emotion = dominant_emotion.capitalize() else: st.session_state.facial_emotion = "Unknown" except Exception as e: logging.error(f"DeepFace analysis failed: {e}") st.session_state.facial_emotion = "Error" st.session_state.last_emotion_time = frame.time return av.VideoFrame.from_ndarray(img, format="bgr24")
if webrtc_ctx.video_processor: webrtc_ctx.video_processor.video_frame_callback = video_frame_callback
# --- Audio Processing ---if "audio_buffer" not in st.session_state: st.session_state.audio_buffer = []
def audio_frame_callback(frame: av.AudioFrame): sound = np.frombuffer(frame.to_ndarray(), dtype=np.int16) st.session_state.audio_buffer.append(sound)
webrtc_streamer( key="affectlink-audio", mode=WebRtcMode.RECVONLY, rtc_configuration=RTC_CONFIGURATION, # Use the new config media_stream_constraints={"video": False, "audio": True}, audio_frame_callback=audio_frame_callback, async_processing=True,)
# --- UI Layout ---st.sidebar.header("Facial Emotion")st.sidebar.metric("Current Expression", st.session_state.get('facial_emotion', 'N/A'))st.sidebar.info("Facial emotion is updated every 5 seconds.")st.sidebar.divider()
st.sidebar.header("Audio Analysis")is_recording = st.sidebar.checkbox("Start Recording Audio")
st.sidebar.subheader("Transcription:")transcription_placeholder = st.sidebar.empty()transcription_placeholder.write("_Waiting for audio..._")
st.sidebar.subheader("Text Emotion:")text_emotion_placeholder = st.sidebar.empty()text_emotion_placeholder.write("_Waiting for audio..._")
st.sidebar.subheader("Speech Emotion:")ser_placeholder = st.sidebar.empty()ser_placeholder.write("_Waiting for audio..._")
if not is_recording and st.session_state.audio_buffer: audio_data = np.concatenate(st.session_state.audio_buffer) st.session_state.audio_buffer = []
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_audio_file: write_wav(tmp_audio_file.name, AUDIO_SAMPLE_RATE, audio_data) with st.spinner("Transcribing audio..."): try: result = whisper_model.transcribe(tmp_audio_file.name, fp16=False) transcribed_text = result['text'] except Exception as e: transcribed_text = f"Transcription failed: {e}" transcription_placeholder.write(f'"{transcribed_text}"')
with st.spinner("Analyzing text emotion..."): if transcribed_text: try: text_emotions = text_classifier(transcribed_text)[0] unified_text_scores = {e: 0.0 for e in UNIFIED_EMOTIONS} for EMO in text_emotions: unified_emo = TEXT_TO_UNIFIED.get(EMO['label']) if unified_emo: unified_text_scores[unified_emo] += EMO['score'] dominant_text_emotion = max(unified_text_scores, key=unified_text_scores.get) except Exception as e: dominant_text_emotion = f"Text analysis failed: {e}" else: dominant_text_emotion = "No text to analyze." text_emotion_placeholder.write(dominant_text_emotion.capitalize())
with st.spinner("Analyzing speech emotion..."): try: audio_array, _ = sf.read(tmp_audio_file.name) inputs = ser_feature_extractor(audio_array, sampling_rate=AUDIO_SAMPLE_RATE, return_tensors="pt", padding=True) with torch.no_grad(): logits = ser_model(**inputs).logits scores = torch.nn.functional.softmax(logits, dim=1).squeeze() unified_ser_scores = {e: 0.0 for e in UNIFIED_EMOTIONS} for i, score in enumerate(scores): raw_emo = ser_model.config.id2label[i] unified_emo = SER_TO_UNIFIED.get(raw_emo) if unified_emo: unified_ser_scores[unified_emo] += score.item() dominant_ser_emotion = max(unified_ser_scores, key=unified_ser_scores.get) except Exception as e: dominant_ser_emotion = f"Speech analysis failed: {e}" ser_placeholder.write(dominant_ser_emotion.capitalize())
os.unlink(tmp_audio_file.name)
elif is_recording: st.sidebar.warning("Recording audio... Uncheck to stop and process.")requirements.txt+4-3
src/streamlit_app.py+164-32
src/streamlit_app.py.oldDeleted-199