Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567897 unmodified lines171819202122238 unmodified lines32333435363738394041429 unmodified lines525354555657585960611 unmodified line63646566676869707172737475767778792 unmodified lines82838485868788899091929394959697989910010110210310410510610714 unmodified lines1221231241251261271287 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871882 unmodified lines1911921931941951961971981992008 unmodified lines2092102112122132142152162172182192202212222232242252261 unmodified line22822923023123223323423523623723823924024124216 unmodified lines2592602612622632642653 unmodified lines2692702712722732742752762772782792802812822832842852862872882892902912922 unmodified lines2952962972982993003013022 unmodified lines3053063073083093103112 unmodified lines3143153163173183193203213223233243253263273283293303313323336 unmodified lines3403413423433443453463473483493504 unmodified lines3553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534542 unmodified lines4574584594604614624632 unmodified lines46646746846947047147247347447547647747847910 unmodified lines4904914924934944954964974984995005015025035045059 unmodified lines51551651751851952052152252352452552652752852953053153253353453553653753853954014 unmodified lines55555655755855956056156256356456556614 unmodified lines58158258358458558658758858959059159214 unmodified lines6076086096106116126136146156166176 unmodified lines624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673```python# ===============================================# 🧠 Emotion Detector - Hugging Face Spaces# Text + Image + Voice + Login# ===============================================import osimport numpy as npimport librosa7 unmodified lines# =================================================# STEP 1: LOCAL STORAGE# =================================================BASE_PATH = "./saved_results"8 unmodified lines# =================================================# STEP 2: LOGIN# =================================================def login(user, password, state):if user and password:return (gr.update(visible=False),9 unmodified lines# =================================================# STEP 3: TEXT MODEL# =================================================print("🔄 Loading Text Emotion Model...")text_classifier = pipeline("text-classification",1 unmodified linetop_k=None)print("✅ Text Emotion Model Loaded")# =================================================# STEP 4: RAVDESS AUDIO MODEL# =================================================RAVDESS_MODEL_PATH = "./model.pkl"RAVDESS_ENCODER_PATH = "./encoder.pkl"print("🔄 Loading Audio Emotion Model...")model = Noneencoder = None2 unmodified linesos.path.exists(RAVDESS_MODEL_PATH)and os.path.exists(RAVDESS_ENCODER_PATH)):try:model = joblib.load(RAVDESS_MODEL_PATH)encoder = joblib.load(RAVDESS_ENCODER_PATH)print("✅ RAVDESS Audio Model Loaded Successfully")except Exception as e:print(f"⚠️ Audio model loading failed: {e}")model = Noneencoder = Noneelse:print("⚠️ model.pkl / encoder.pkl not found.")print("⚠️ Audio fallback mode enabled.")# =================================================# STEP 5: AUDIO FEATURE EXTRACTION# =================================================def extract_audio_features(file):14 unmodified lines# =================================================# STEP 6: SAVE RESULT# =================================================def save_result(tab, result, username):7 unmodified lines)if tab == "text":path = os.path.join(TEXT_PATH,f"text_{time}.txt")elif tab == "image":path = os.path.join(IMAGE_PATH,f"image_{time}.txt")else:path = os.path.join(AUDIO_PATH,f"audio_{time}.txt")try:with open(path,"w",encoding="utf-8") as f:f.write(content)except Exception as e:print(f"⚠️ Could not save result: {e}")# =================================================# STEP 7: TEXT EMOTION# =================================================def analyze_text_emotion(text, username):if not text or not text.strip():return "Please enter text."try:results = text_classifier(text)[0]results = sorted(2 unmodified linesreverse=True)output = "📝 Text Emotion Results:\n"for item in results[:7]:output += (f"{item['label'].upper()}: "f"{item['score']:.3f}\n"8 unmodified linesreturn outputexcept Exception as e:return f"Text Error: {str(e)}"# =================================================# STEP 8: IMAGE EMOTION# =================================================def analyze_image_emotion(image, username):if image is None:return "Please upload image."try:1 unmodified linetemp_path = "/tmp/temp_img.jpg"if isinstance(image, Image.Image):image.save(temp_path)else:Image.fromarray(image).save(temp_path)# Use OpenCV first because it is lightweightbackends = ["opencv","retinaface",16 unmodified lines)print(f"✅ Image detection successful: {backend}")break3 unmodified lineslast_error = str(e)print(f"❌ {backend} failed: {e}")if result is None:return ("Image Error: All detectors failed.\n"f"Last error: {last_error}")# DeepFace can return a list or dictionaryif isinstance(result, list):result = result[0]emotions = result["emotion"]sorted_emotions = sorted(2 unmodified linesreverse=True)output = "🖼️ Image Emotion Results:\n"for emotion, score in sorted_emotions[:7]:2 unmodified linesf"{score:.2f}\n")save_result("image",output,2 unmodified linesreturn outputexcept Exception as e:return f"Image Error: {str(e)}"# =================================================# STEP 9: AUDIO EMOTION# =================================================def analyze_audio_emotion(audio_file, username):if audio_file is None:return "Please upload audio."try:6 unmodified linesfeatures).reshape(1, -1)# -----------------------------------------# RAVDESS MODEL# -----------------------------------------if (model is not Noneand encoder is not None4 unmodified lines)[0]results = sorted([(encoder.inverse_transform([i])[0],float(p))for i, p in enumerate(probs)],key=lambda x: x[1],reverse=True)# -----------------------------------------# FALLBACK# -----------------------------------------else:f = features.flatten()scores = {"angry": np.mean(f[:5]),"happy": np.mean(f[5:10]),"sad": np.mean(f[10:15]),"neutral": np.mean(f[15:20]),"fearful": np.mean(f[20:25]),"disgust": np.mean(f[25:30]),"surprised": np.mean(f[30:35])}total = sum(abs(v)for v in scores.values())results = [(k,abs(v) / totalif total != 0else 0.14)for k, v in scores.items()]results = sorted(results,key=lambda x: x[1],reverse=True)# Remove calmresults = [(e, s)for e, s in resultsif str(e).lower() != "calm"]# Normalize scorestotal_p = sum(s for _, s in results)if total_p != 0:results = [(e, s / total_p)for e, s in results]output = ("🎧 Audio Emotion Results:\n")for emo, score in results[:7]:2 unmodified linesf"{score:.2f}\n")save_result("audio",output,2 unmodified linesreturn outputexcept Exception as e:return f"Audio Error: {str(e)}"# =================================================# STEP 10: GRADIO UI# =================================================with gr.Blocks(10 unmodified linesuser_state = gr.State("")# ---------------------------------------------# LOGIN# ---------------------------------------------with login_box:gr.Markdown("## 🔐 Login Panel")user = gr.Textbox(label="Username"9 unmodified linesvariant="primary")# ---------------------------------------------# MAIN APP# ---------------------------------------------with app_box:gr.Markdown("# 🧠 Multimodal Emotion Detector\n""Text + Image + Voice")with gr.Tabs():# =====================================# TEXT# =====================================with gr.Tab("📝 Text"):t_in = gr.Textbox(lines=4,14 unmodified linest_out)# =====================================# IMAGE# =====================================with gr.Tab("🖼️ Image"):i_in = gr.Image(type="pil",14 unmodified linesi_out)# =====================================# VOICE# =====================================with gr.Tab("🎙️ Voice"):a_in = gr.Audio(type="filepath",14 unmodified linesa_out)# ---------------------------------------------# LOGIN BUTTON# ---------------------------------------------btn.click(login,[user, pwd, user_state],6 unmodified lines# =================================================# STEP 11: LAUNCH# =================================================if __name__ == "__main__":demo.launch()```### `requirements.txt`Hugging Face Space mein **ek second file** banao:**`requirements.txt`**Aur is mein ye paste karo:```txttransformerstorchdeepfacetf-kerasopencv-python-headlessPillowgradiolibrosasoundfilescikit-learnjoblibretina-facemtcnn```### Hugging Face mein files ka structureTumhari Space repository mein approximately ye hona chahiye:```textyour-space/│├── app.py├── requirements.txt├── model.pkl├── encoder.pkl│└── saved_results/```1237 unmodified lines111213141516178 unmodified lines262728293031323334359 unmodified lines454647484950515253541 unmodified line56575859606162636465666768697071722 unmodified lines75767778798081828384858687888990919293949596979814 unmodified lines1131141151161171181197 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701712 unmodified lines1741751761771781791801811828 unmodified lines1911921931941951961971981992002012022032042052061 unmodified line20820921021121221321421521621716 unmodified lines2342352362372382392403 unmodified lines2442452462472482492502512522532542552562572582592602612 unmodified lines2642652662672682692702 unmodified lines2732742752762772782 unmodified lines2812822832842852862872882892902912922932942952962976 unmodified lines3043053063073083094 unmodified lines3143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813822 unmodified lines3853863873883893902 unmodified lines39339439539639739839940040140240340410 unmodified lines4154164174184194204214224239 unmodified lines43343443543643743843944044144244344444544644744814 unmodified lines46346446546646746846914 unmodified lines48448548648748848949014 unmodified lines5055065075085095106 unmodified lines517518519520521522523524import osimport numpy as npimport librosa7 unmodified lines# =================================================# LOCAL STORAGE# =================================================BASE_PATH = "./saved_results"8 unmodified lines# =================================================# LOGIN# =================================================def login(user, password, state):if user and password:return (gr.update(visible=False),9 unmodified lines# =================================================# TEXT MODEL# =================================================print("Loading Text Emotion Model...")text_classifier = pipeline("text-classification",1 unmodified linetop_k=None)print("Text Emotion Model Loaded")# =================================================# RAVDESS AUDIO MODEL# =================================================RAVDESS_MODEL_PATH = "./model.pkl"RAVDESS_ENCODER_PATH = "./encoder.pkl"print("Loading Audio Emotion Model...")model = Noneencoder = None2 unmodified linesos.path.exists(RAVDESS_MODEL_PATH)and os.path.exists(RAVDESS_ENCODER_PATH)):try:model = joblib.load(RAVDESS_MODEL_PATH)encoder = joblib.load(RAVDESS_ENCODER_PATH)print("RAVDESS Audio Model Loaded Successfully")except Exception as e:print(f"Audio model loading failed: {e}")model = Noneencoder = Noneelse:print("model.pkl / encoder.pkl not found.")print("Audio fallback mode enabled.")# =================================================# AUDIO FEATURE EXTRACTION# =================================================def extract_audio_features(file):14 unmodified lines# =================================================# SAVE RESULT# =================================================def save_result(tab, result, username):7 unmodified lines)if tab == "text":path = os.path.join(TEXT_PATH,f"text_{time}.txt")elif tab == "image":path = os.path.join(IMAGE_PATH,f"image_{time}.txt")else:path = os.path.join(AUDIO_PATH,f"audio_{time}.txt")try:with open(path,"w",encoding="utf-8") as f:f.write(content)except Exception as e:print(f"Could not save result: {e}")# =================================================# TEXT EMOTION# =================================================def analyze_text_emotion(text, username):if not text or not text.strip():return "Please enter text."try:results = text_classifier(text)[0]results = sorted(2 unmodified linesreverse=True)output = "Text Emotion Results:\n"for item in results[:7]:output += (f"{item['label'].upper()}: "f"{item['score']:.3f}\n"8 unmodified linesreturn outputexcept Exception as e:return f"Text Error: {str(e)}"# =================================================# IMAGE EMOTION# =================================================def analyze_image_emotion(image, username):if image is None:return "Please upload image."try:1 unmodified linetemp_path = "/tmp/temp_img.jpg"if isinstance(image, Image.Image):image.save(temp_path)else:Image.fromarray(image).save(temp_path)backends = ["opencv","retinaface",16 unmodified lines)print(f"Image detection successful: {backend}")break3 unmodified lineslast_error = str(e)print(f"{backend} failed: {e}")if result is None:return ("Image Error: All detectors failed.\n"f"Last error: {last_error}")if isinstance(result, list):result = result[0]emotions = result["emotion"]sorted_emotions = sorted(2 unmodified linesreverse=True)output = "Image Emotion Results:\n"for emotion, score in sorted_emotions[:7]:2 unmodified linesf"{score:.2f}\n")save_result("image",output,2 unmodified linesreturn outputexcept Exception as e:return f"Image Error: {str(e)}"# =================================================# AUDIO EMOTION# =================================================def analyze_audio_emotion(audio_file, username):if audio_file is None:return "Please upload audio."try:6 unmodified linesfeatures).reshape(1, -1)if (model is not Noneand encoder is not None4 unmodified lines)[0]results = sorted([(encoder.inverse_transform([i])[0],float(p))for i, p in enumerate(probs)],key=lambda x: x[1],reverse=True)else:f = features.flatten()scores = {"angry": np.mean(f[:5]),"happy": np.mean(f[5:10]),"sad": np.mean(f[10:15]),"neutral": np.mean(f[15:20]),"fearful": np.mean(f[20:25]),"disgust": np.mean(f[25:30]),"surprised": np.mean(f[30:35])}total = sum(abs(v)for v in scores.values())results = [(k,abs(v) / totalif total != 0else 0.14)for k, v in scores.items()]results = sorted(results,key=lambda x: x[1],reverse=True)results = [(e, s)for e, s in resultsif str(e).lower() != "calm"]total_p = sum(s for _, s in results)if total_p != 0:results = [(e, s / total_p)for e, s in results]output = "Audio Emotion Results:\n"for emo, score in results[:7]:2 unmodified linesf"{score:.2f}\n")save_result("audio",output,2 unmodified linesreturn outputexcept Exception as e:return f"Audio Error: {str(e)}"# =================================================# GRADIO UI# =================================================with gr.Blocks(10 unmodified linesuser_state = gr.State("")with login_box:gr.Markdown("## Login Panel")user = gr.Textbox(label="Username"9 unmodified linesvariant="primary")with app_box:gr.Markdown("# Multimodal Emotion Detector\n""Text + Image + Voice")with gr.Tabs():with gr.Tab("Text"):t_in = gr.Textbox(lines=4,14 unmodified linest_out)with gr.Tab("Image"):i_in = gr.Image(type="pil",14 unmodified linesi_out)with gr.Tab("Voice"):a_in = gr.Audio(type="filepath",14 unmodified linesa_out)btn.click(login,[user, pwd, user_state],6 unmodified lines# =================================================# LAUNCH# =================================================if __name__ == "__main__":demo.launch()
app.py+30-179