[Parth Saxena] commited on
Commit ·
b465c05
1
Parent(s): 1a96d66
Update api.py with improved emotion correction logic and full prediction pipeline
Browse files
api.py
CHANGED
|
@@ -1,181 +1,336 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import numpy as np
|
| 4 |
import librosa
|
| 5 |
import tensorflow as tf
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
|
|
|
|
|
|
| 13 |
SR = 22050
|
| 14 |
DURATION = 3
|
| 15 |
SAMPLES = SR * DURATION
|
| 16 |
-
MODEL_DIR = "saved_model"
|
| 17 |
|
| 18 |
N_MELS = 96
|
| 19 |
N_MFCC = 40
|
| 20 |
N_FFT = 2048
|
| 21 |
-
|
| 22 |
MAX_FRAMES = 150
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
-
"
|
| 32 |
-
"
|
| 33 |
-
"
|
| 34 |
}
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
response = request.execute()
|
| 50 |
-
songs = []
|
| 51 |
-
for item in response.get("items", []):
|
| 52 |
-
title = item["snippet"]["title"]
|
| 53 |
-
video_id = item["id"]["videoId"]
|
| 54 |
-
songs.append({"title": title, "url": f"https://www.youtube.com/watch?v={video_id}"})
|
| 55 |
-
print(f"[YOUTUBE] Fetched {len(songs)} songs for {emotion}")
|
| 56 |
-
return songs
|
| 57 |
-
except Exception as e:
|
| 58 |
-
print(f"[YOUTUBE ERROR] {type(e).__name__}: {e}")
|
| 59 |
-
return []
|
| 60 |
-
|
| 61 |
-
# ---------------- TEXT SENTIMENT ----------------
|
| 62 |
-
POSITIVE_WORDS = {
|
| 63 |
-
"happy","joy","joyful","cheerful","delighted","pleased","glad","thrilled","ecstatic",
|
| 64 |
-
"blissful","merry","jolly","elated","overjoyed","euphoric","radiant","beaming",
|
| 65 |
-
"love","adore","cherish","dear","darling","sweetheart","beloved","fond","affection",
|
| 66 |
-
"caring","tender","warm","heart","hug","kiss","miss","romantic","crush",
|
| 67 |
-
"thanks","thank","grateful","thankful","appreciate","blessed","fortunate","lucky",
|
| 68 |
-
"excited","amazing","awesome","incredible","fantastic","wonderful","marvelous",
|
| 69 |
-
"spectacular","magnificent","extraordinary","phenomenal","outstanding","superb",
|
| 70 |
-
"brilliant","excellent","fabulous","glorious","splendid","wow","yay","hooray",
|
| 71 |
-
"beautiful","gorgeous","pretty","lovely","cute","handsome","stunning","elegant",
|
| 72 |
-
"charming","adorable","sweet","kind","gentle","generous","thoughtful","smart",
|
| 73 |
-
"brave","strong","confident","proud","inspiring","success","successful","win",
|
| 74 |
-
"won","winner","victory","achieve","achieved","accomplish","accomplished",
|
| 75 |
-
"congratulations","celebrate","enjoy","fun","laugh","smile","giggle","cheer",
|
| 76 |
-
"dance","sing","play","relax","peaceful","calm","comfort","comfortable","cozy",
|
| 77 |
-
"safe","secure","healthy","fresh","free","freedom","good","great","nice","fine",
|
| 78 |
-
"cool","perfect","best","better","super","top","ideal","right","helpful",
|
| 79 |
-
"friendly","pleasant","satisfied","content","fulfilled","hope","hopeful",
|
| 80 |
-
"optimistic","positive","bright","promise","faith","believe","trust","dream",
|
| 81 |
-
"yes","sure","okay","ok","alright","definitely","absolutely","totally","lol","haha"
|
| 82 |
}
|
| 83 |
|
| 84 |
-
|
| 85 |
-
"
|
| 86 |
-
"
|
| 87 |
-
"
|
| 88 |
-
"
|
| 89 |
-
"
|
| 90 |
-
"
|
| 91 |
-
"
|
| 92 |
-
"
|
| 93 |
-
"
|
| 94 |
-
"
|
| 95 |
-
"
|
| 96 |
-
"sick","illness","disease","dying","death","dead","die","kill","murder","suicide",
|
| 97 |
-
"terrible","horrible","awful","dreadful","pathetic","worthless","useless",
|
| 98 |
-
"hopeless","helpless","powerless","weak","ugly","stupid","dumb","idiot","fool",
|
| 99 |
-
"lazy","careless","selfish","cruel","mean","rude","harsh","fake","liar","cheat",
|
| 100 |
-
"betrayed","betrayal","bad","worse","worst","wrong","mistake","fail","failed",
|
| 101 |
-
"failure","loss","lost","problem","trouble","impossible","unfair","unjust","evil",
|
| 102 |
-
"fight","argue","argument","scream","yell","shout","curse","blame","punish",
|
| 103 |
-
"revenge","threat","abuse","bully","harass","destroy","ruin","quit","reject",
|
| 104 |
-
"rejected","abandon","abandoned","damn","shut","ugh","crap","suck","sucks",
|
| 105 |
-
"trash","garbage","boring","bored","tired","exhausted","disappointed","regret",
|
| 106 |
-
"sorry","unfortunately","sadly","cannot","dont","wont"
|
| 107 |
}
|
| 108 |
|
| 109 |
-
def get_text_sentiment(text
|
| 110 |
if not text:
|
| 111 |
-
return "
|
|
|
|
| 112 |
words = set(text.lower().split())
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
if confidence > 0.50:
|
| 123 |
return audio_emotion
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
| 125 |
if audio_emotion in ["Angry", "Sad", "Fear", "Disgust", "Neutral"]:
|
| 126 |
return "Happy"
|
| 127 |
-
|
| 128 |
-
|
|
|
|
| 129 |
return "Angry"
|
| 130 |
-
if audio_emotion
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
return "Sad"
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
if audio_emotion in ["Happy", "Angry", "Sad"]:
|
| 134 |
return "Neutral"
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
# ---------------- APP SETUP ----------------
|
| 138 |
-
app = FastAPI()
|
| 139 |
-
|
| 140 |
-
app.add_middleware(
|
| 141 |
-
CORSMiddleware,
|
| 142 |
-
allow_origins=["*"],
|
| 143 |
-
allow_methods=["GET", "POST"],
|
| 144 |
-
allow_headers=["*"],
|
| 145 |
-
)
|
| 146 |
|
| 147 |
-
|
| 148 |
-
encoder = None
|
| 149 |
-
mean = None
|
| 150 |
-
std = None
|
| 151 |
-
|
| 152 |
-
@app.on_event("startup")
|
| 153 |
-
def load_resources():
|
| 154 |
-
global model, encoder, mean, std
|
| 155 |
-
try:
|
| 156 |
-
model = tf.keras.models.load_model(os.path.join(MODEL_DIR, "emotion_model.keras"))
|
| 157 |
-
with open(os.path.join(MODEL_DIR, "encoder.pkl"), "rb") as f:
|
| 158 |
-
encoder = pickle.load(f)
|
| 159 |
-
with open(os.path.join(MODEL_DIR, "norm.pkl"), "rb") as f:
|
| 160 |
-
norm = pickle.load(f)
|
| 161 |
-
mean = norm["mean"]
|
| 162 |
-
std = norm["std"]
|
| 163 |
-
print(f"[STARTUP] Model loaded. Classes: {list(encoder.classes_)}")
|
| 164 |
-
except Exception as e:
|
| 165 |
-
print(f"[STARTUP ERROR] {e}")
|
| 166 |
-
|
| 167 |
-
class AudioData(BaseModel):
|
| 168 |
-
signal: List[float]
|
| 169 |
-
sample_rate: int = 22050
|
| 170 |
-
text: Optional[str] = ""
|
| 171 |
-
|
| 172 |
-
def preprocess(signal: np.ndarray, src_sr: int) -> np.ndarray:
|
| 173 |
-
signal = np.array(signal, dtype=np.float32)
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
-
|
|
|
|
|
|
|
| 179 |
signal = signal - np.mean(signal)
|
| 180 |
|
| 181 |
if len(signal) > SAMPLES:
|
|
@@ -187,82 +342,157 @@ def preprocess(signal: np.ndarray, src_sr: int) -> np.ndarray:
|
|
| 187 |
signal = np.nan_to_num(signal).astype(np.float32)
|
| 188 |
|
| 189 |
mel = librosa.feature.melspectrogram(
|
| 190 |
-
y=signal, sr=SR, n_fft=N_FFT,
|
|
|
|
| 191 |
)
|
| 192 |
mel = librosa.power_to_db(mel)
|
| 193 |
mfcc = librosa.feature.mfcc(y=signal, sr=SR, n_mfcc=N_MFCC)
|
| 194 |
-
features = np.concatenate([mel, mfcc], axis=0)
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
| 198 |
else:
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
-
|
| 202 |
-
print(f"[PREPROCESS] shape: {features.shape}")
|
| 203 |
-
return features.astype(np.float32)
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
|
|
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
|
| 214 |
-
@app.post("/predict")
|
| 215 |
-
async def predict_emotion(data: AudioData):
|
| 216 |
-
# Top-level try/except so we NEVER return a 500
|
| 217 |
try:
|
| 218 |
-
|
|
|
|
| 219 |
|
| 220 |
-
if
|
| 221 |
-
return
|
| 222 |
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
audio_emotion = encoder.inverse_transform([idx])[0]
|
| 232 |
-
confidence = float(probs[idx])
|
| 233 |
|
| 234 |
-
|
| 235 |
-
final_emotion = correct_emotion(audio_emotion, text_sentiment, confidence)
|
| 236 |
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
|
| 242 |
-
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
-
|
|
|
|
| 245 |
|
| 246 |
-
return
|
| 247 |
-
"emotion": final_emotion,
|
| 248 |
-
"audio_emotion": audio_emotion,
|
| 249 |
-
"text_sentiment": text_sentiment,
|
| 250 |
-
"confidence": confidence,
|
| 251 |
-
"all_scores": confidences,
|
| 252 |
-
"songs": songs
|
| 253 |
-
}
|
| 254 |
|
| 255 |
except Exception as e:
|
| 256 |
-
print(
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sounddevice as sd
|
| 3 |
import numpy as np
|
| 4 |
import librosa
|
| 5 |
import tensorflow as tf
|
| 6 |
+
import pickle
|
| 7 |
+
import whisper
|
| 8 |
+
import soundfile as sf
|
| 9 |
+
import json
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from googleapiclient.discovery import build
|
| 12 |
+
|
| 13 |
+
# =========================================================
|
| 14 |
+
# YOUTUBE API KEY
|
| 15 |
+
# =========================================================
|
| 16 |
+
os.environ["YOUTUBE_API_KEY"] = "AIzaSyCO79K4HCf-vmTZ4bHw4e8fajHu0dY2rSU"
|
| 17 |
+
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
|
| 18 |
+
|
| 19 |
+
if not YOUTUBE_API_KEY:
|
| 20 |
+
raise ValueError("YOUTUBE_API_KEY not found in environment variables")
|
| 21 |
+
|
| 22 |
+
youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# =========================================================
|
| 26 |
+
# CACHE SYSTEM
|
| 27 |
+
# =========================================================
|
| 28 |
+
CACHE_FILE = "yt_cache.json"
|
| 29 |
+
|
| 30 |
+
def load_cache():
|
| 31 |
+
if os.path.exists(CACHE_FILE):
|
| 32 |
+
try:
|
| 33 |
+
with open(CACHE_FILE, "r") as f:
|
| 34 |
+
return json.load(f)
|
| 35 |
+
except:
|
| 36 |
+
return {}
|
| 37 |
+
return {}
|
| 38 |
+
|
| 39 |
+
def save_cache(cache):
|
| 40 |
+
with open(CACHE_FILE, "w") as f:
|
| 41 |
+
json.dump(cache, f, indent=2)
|
| 42 |
+
|
| 43 |
+
yt_cache = load_cache()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# =========================================================
|
| 47 |
+
# LOAD MODEL + NORM (Bypassing SKLearn DLL Error!)
|
| 48 |
+
# =========================================================
|
| 49 |
+
model = tf.keras.models.load_model("saved_model/emotion_model.keras")
|
| 50 |
+
|
| 51 |
+
# We completely removed encoder.pkl and sklearn to prevent the Windows DLL error!
|
| 52 |
+
CLASSES = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad']
|
| 53 |
+
|
| 54 |
+
with open("saved_model/norm.pkl", "rb") as f:
|
| 55 |
+
norm = pickle.load(f)
|
| 56 |
+
|
| 57 |
+
mean, std = norm["mean"], norm["std"]
|
| 58 |
+
|
| 59 |
+
# =========================================================
|
| 60 |
+
# LOAD WHISPER
|
| 61 |
+
# =========================================================
|
| 62 |
+
whisper_model = whisper.load_model("base")
|
| 63 |
+
|
| 64 |
+
# =========================================================
|
| 65 |
+
# EMOTION CONFIGS
|
| 66 |
+
# =========================================================
|
| 67 |
+
emotion_to_query = {
|
| 68 |
+
"Angry": "calm stress relief music",
|
| 69 |
+
"Sad": "sad emotional hindi songs",
|
| 70 |
+
"Happy": "happy upbeat party songs",
|
| 71 |
+
"Fear": "relaxing meditation music",
|
| 72 |
+
"Disgust": "lofi chill beats",
|
| 73 |
+
"Neutral": "focus instrumental music"
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
emotion_to_action = {
|
| 77 |
+
"Angry": """You seem angry.
|
| 78 |
+
-> Pause before reacting.
|
| 79 |
+
-> Take deep breaths (inhale 4s, exhale 6s).
|
| 80 |
+
-> Walk away from the situation.
|
| 81 |
+
-> Avoid decisions right now.
|
| 82 |
+
-> Release energy physically.""",
|
| 83 |
+
|
| 84 |
+
"Sad": """You seem sad.
|
| 85 |
+
-> Talk to someone you trust.
|
| 86 |
+
-> Write your thoughts down.
|
| 87 |
+
-> Listen to uplifting music.
|
| 88 |
+
-> Do one small task.
|
| 89 |
+
-> Avoid isolation.""",
|
| 90 |
+
|
| 91 |
+
"Happy": """You seem happy.
|
| 92 |
+
-> Use this energy productively.
|
| 93 |
+
-> Start something meaningful.
|
| 94 |
+
-> Share positivity.
|
| 95 |
+
-> Capture the moment.
|
| 96 |
+
-> Avoid wasting this state.""",
|
| 97 |
+
|
| 98 |
+
"Fear": """You seem anxious.
|
| 99 |
+
-> Slow your breathing.
|
| 100 |
+
-> Ask: is this real or imagined?
|
| 101 |
+
-> Break problems into small steps.
|
| 102 |
+
-> Stay grounded in present.
|
| 103 |
+
-> Avoid overthinking.""",
|
| 104 |
+
|
| 105 |
+
"Disgust": """You seem uncomfortable.
|
| 106 |
+
-> Step away from the trigger.
|
| 107 |
+
-> Reset your environment.
|
| 108 |
+
-> Shift focus.
|
| 109 |
+
-> Avoid dwelling.
|
| 110 |
+
-> Give your brain time.""",
|
| 111 |
+
|
| 112 |
+
"Neutral": """You are balanced.
|
| 113 |
+
-> Best time for deep work.
|
| 114 |
+
-> Start something important.
|
| 115 |
+
-> Avoid distractions.
|
| 116 |
+
-> Plan clearly.
|
| 117 |
+
-> Maintain this state."""
|
| 118 |
+
}
|
| 119 |
|
| 120 |
+
# =========================================================
|
| 121 |
+
# AUDIO CONFIG
|
| 122 |
+
# =========================================================
|
| 123 |
SR = 22050
|
| 124 |
DURATION = 3
|
| 125 |
SAMPLES = SR * DURATION
|
|
|
|
| 126 |
|
| 127 |
N_MELS = 96
|
| 128 |
N_MFCC = 40
|
| 129 |
N_FFT = 2048
|
| 130 |
+
HOP = 512
|
| 131 |
MAX_FRAMES = 150
|
| 132 |
|
| 133 |
+
# =========================================================
|
| 134 |
+
# RECORD AUDIO
|
| 135 |
+
# =========================================================
|
| 136 |
+
def record_audio():
|
| 137 |
+
print("\n Recording... Speak now (3 sec)...")
|
| 138 |
+
|
| 139 |
+
audio = sd.rec(int(DURATION * SR),
|
| 140 |
+
samplerate=SR,
|
| 141 |
+
channels=1,
|
| 142 |
+
dtype='float32')
|
| 143 |
+
sd.wait()
|
| 144 |
+
|
| 145 |
+
audio = audio.flatten()
|
| 146 |
+
path = "temp.wav"
|
| 147 |
+
sf.write(path, audio, SR)
|
| 148 |
+
|
| 149 |
+
print("Recording done")
|
| 150 |
+
return audio, path
|
| 151 |
+
|
| 152 |
+
# =========================================================
|
| 153 |
+
# SPEECH TO TEXT (FIXED - BYPASSES FFMPEG / WINERROR 4551)
|
| 154 |
+
# =========================================================
|
| 155 |
+
def speech_to_text(audio_array):
|
| 156 |
+
try:
|
| 157 |
+
# Whisper requires EXACTLY 16000 Hz audio
|
| 158 |
+
# We resample our 22050 Hz recording down to 16000 Hz using librosa
|
| 159 |
+
audio_16k = librosa.resample(audio_array, orig_sr=SR, target_sr=16000)
|
| 160 |
+
|
| 161 |
+
# Passing the raw numpy array to whisper bypasses the ffmpeg.exe block!
|
| 162 |
+
result = whisper_model.transcribe(audio_16k)
|
| 163 |
+
text = result["text"].strip()
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print("Whisper error:", e)
|
| 166 |
+
text = ""
|
| 167 |
+
|
| 168 |
+
print("\nTEXT:", text)
|
| 169 |
+
return text
|
| 170 |
+
|
| 171 |
+
# =========================================================
|
| 172 |
+
# 6-CLASS TEXT SENTIMENT SYSTEM
|
| 173 |
+
# =========================================================
|
| 174 |
+
HAPPY_WORDS = {
|
| 175 |
+
"happy", "joy", "joyful", "cheerful", "delighted", "pleased", "glad", "thrilled", "ecstatic",
|
| 176 |
+
"blissful", "merry", "jolly", "elated", "overjoyed", "euphoric", "radiant", "beaming", "love",
|
| 177 |
+
"adore", "cherish", "dear", "darling", "sweetheart", "beloved", "fond", "affection", "caring",
|
| 178 |
+
"tender", "warm", "heart", "hug", "kiss", "miss", "romantic", "crush", "thanks", "thank",
|
| 179 |
+
"grateful", "thankful", "appreciate", "blessed", "fortunate", "lucky", "privilege", "excited",
|
| 180 |
+
"amazing", "awesome", "incredible", "fantastic", "wonderful", "marvelous", "spectacular",
|
| 181 |
+
"magnificent", "extraordinary", "phenomenal", "outstanding", "superb", "brilliant", "excellent",
|
| 182 |
+
"fabulous", "glorious", "splendid", "wow", "yay", "hooray", "woohoo", "hurray", "beautiful",
|
| 183 |
+
"gorgeous", "pretty", "lovely", "cute", "handsome", "stunning", "elegant", "charming", "adorable",
|
| 184 |
+
"sweet", "kind", "gentle", "generous", "thoughtful", "smart", "clever", "wise", "talented",
|
| 185 |
+
"gifted", "brave", "strong", "confident", "proud", "inspiring", "success", "successful", "win",
|
| 186 |
+
"won", "winner", "victory", "achieve", "achieved", "accomplish", "accomplished", "congratulations",
|
| 187 |
+
"congrats", "celebrate", "celebration", "promotion", "graduated", "passed", "qualified", "enjoy",
|
| 188 |
+
"enjoying", "fun", "laugh", "laughing", "smile", "smiling", "giggle", "cheer", "dance", "dancing",
|
| 189 |
+
"sing", "singing", "play", "playing", "relax", "relaxing", "peaceful", "calm", "comfort",
|
| 190 |
+
"comfortable", "cozy", "safe", "secure", "heal", "healthy", "fresh", "free", "freedom", "good",
|
| 191 |
+
"great", "nice", "fine", "cool", "perfect", "best", "better", "super", "top", "ideal", "right",
|
| 192 |
+
"correct", "fair", "worthy", "valuable", "useful", "helpful", "friendly", "pleasant", "satisfying",
|
| 193 |
+
"satisfied", "content", "fulfilled", "complete", "enough", "hope", "hopeful", "optimistic",
|
| 194 |
+
"positive", "bright", "promise", "promising", "faith", "believe", "trust", "dream", "wish",
|
| 195 |
+
"desire", "forward", "progress", "improve", "improving", "growing", "bloom", "yep", "yeah", "yes",
|
| 196 |
+
"sure", "okay", "ok", "alright", "definitely", "absolutely", "certainly", "exactly", "totally",
|
| 197 |
+
"completely", "truly", "really", "honestly", "finally", "lol", "haha", "hehe"
|
| 198 |
+
}
|
| 199 |
|
| 200 |
+
ANGRY_WORDS = {
|
| 201 |
+
"angry", "anger", "mad", "furious", "rage", "raging", "irritated", "irritating", "annoyed",
|
| 202 |
+
"annoying", "frustrated", "frustrating", "outraged", "livid", "fuming", "bitter", "hostile",
|
| 203 |
+
"aggressive", "violent", "explosive", "fight", "fighting", "argue", "arguing", "argument",
|
| 204 |
+
"scream", "screaming", "yell", "yelling", "shout", "shouting", "curse", "cursing", "swear",
|
| 205 |
+
"blame", "blaming", "punish", "punishment", "revenge", "threat", "threaten", "damn", "hell",
|
| 206 |
+
"shut", "stop", "enough"
|
| 207 |
}
|
| 208 |
|
| 209 |
+
SAD_WORDS = {
|
| 210 |
+
"sad", "sadness", "unhappy", "depressed", "depression", "miserable", "gloomy", "melancholy",
|
| 211 |
+
"lonely", "loneliness", "alone", "isolated", "heartbroken", "heartbreak", "grief", "grieve",
|
| 212 |
+
"mourn", "mourning", "sorrow", "sorrowful", "cry", "crying", "tears", "weep", "weeping", "sob",
|
| 213 |
+
"hopeless", "helpless", "powerless", "weak", "boring", "bored", "tired", "exhausted", "fed",
|
| 214 |
+
"sick", "disappointed", "disappointing", "regret", "sorry", "unfortunately", "sadly"
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
FEAR_WORDS = {
|
| 218 |
+
"fear", "afraid", "scared", "terrified", "frightened", "panic", "panicking", "anxious", "anxiety",
|
| 219 |
+
"nervous", "worried", "worry", "worrying", "dread", "dreading", "horror", "horrified", "shocking",
|
| 220 |
+
"shocked", "startled", "tense", "stressed", "stress", "overwhelmed", "paranoid", "nightmare",
|
| 221 |
+
"creepy", "spooky", "eerie", "coward"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
}
|
| 223 |
|
| 224 |
+
DISGUST_WORDS = {
|
| 225 |
+
"hate", "hatred", "despise", "detest", "loathe", "resent", "dislike", "disgust", "disgusting",
|
| 226 |
+
"disgusted", "repulsive", "revolting", "gross", "nasty", "vile", "toxic", "terrible", "horrible",
|
| 227 |
+
"awful", "dreadful", "atrocious", "pathetic", "worthless", "useless", "pointless", "meaningless",
|
| 228 |
+
"ugly", "stupid", "dumb", "idiot", "fool", "foolish", "lazy", "careless", "reckless", "selfish",
|
| 229 |
+
"greedy", "cruel", "mean", "rude", "harsh", "cold", "fake", "liar", "cheat", "cheater", "betrayed",
|
| 230 |
+
"betrayal", "bad", "worse", "worst", "wrong", "incorrect", "mistake", "error", "fail", "failed",
|
| 231 |
+
"failure", "loss", "lost", "lose", "problem", "trouble", "difficult", "hard", "impossible",
|
| 232 |
+
"unfair", "unjust", "corrupt", "evil", "wicked", "abuse", "abusing", "bully", "bullying",
|
| 233 |
+
"harass", "destroy", "destroying", "ruin", "ruined", "wreck", "quit", "quitting", "surrender",
|
| 234 |
+
"reject", "rejected", "rejection", "abandon", "abandoned", "ignore", "no", "nope", "never",
|
| 235 |
+
"nothing", "nobody", "nowhere", "ugh", "crap", "suck", "sucks", "trash", "garbage"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
}
|
| 237 |
|
| 238 |
+
def get_text_sentiment(text):
|
| 239 |
if not text:
|
| 240 |
+
return "Neutral"
|
| 241 |
+
|
| 242 |
words = set(text.lower().split())
|
| 243 |
+
|
| 244 |
+
# Calculate word overlaps for each sentiment
|
| 245 |
+
scores = {
|
| 246 |
+
"Happy": len(words & HAPPY_WORDS),
|
| 247 |
+
"Angry": len(words & ANGRY_WORDS),
|
| 248 |
+
"Sad": len(words & SAD_WORDS),
|
| 249 |
+
"Fear": len(words & FEAR_WORDS),
|
| 250 |
+
"Disgust": len(words & DISGUST_WORDS)
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
max_score = max(scores.values())
|
| 254 |
+
|
| 255 |
+
if max_score == 0:
|
| 256 |
+
return "Neutral"
|
| 257 |
+
|
| 258 |
+
# Find which emotion got the highest score
|
| 259 |
+
for emotion, score in scores.items():
|
| 260 |
+
if score == max_score:
|
| 261 |
+
return emotion
|
| 262 |
+
|
| 263 |
+
def correct_emotion(audio_emotion, text_sentiment, confidence):
|
| 264 |
+
# Only correct when model confidence is low
|
| 265 |
if confidence > 0.50:
|
| 266 |
return audio_emotion
|
| 267 |
+
|
| 268 |
+
text_sentiment = text_sentiment.capitalize()
|
| 269 |
+
|
| 270 |
+
if text_sentiment == "Happy":
|
| 271 |
if audio_emotion in ["Angry", "Sad", "Fear", "Disgust", "Neutral"]:
|
| 272 |
return "Happy"
|
| 273 |
+
|
| 274 |
+
if text_sentiment == "Angry":
|
| 275 |
+
if audio_emotion in ["Happy", "Neutral"]:
|
| 276 |
return "Angry"
|
| 277 |
+
if audio_emotion in ["Sad", "Fear", "Disgust"]:
|
| 278 |
+
return audio_emotion
|
| 279 |
+
|
| 280 |
+
if text_sentiment == "Sad":
|
| 281 |
+
if audio_emotion in ["Happy", "Neutral"]:
|
| 282 |
return "Sad"
|
| 283 |
+
if audio_emotion in ["Angry", "Fear", "Disgust"]:
|
| 284 |
+
return audio_emotion
|
| 285 |
+
|
| 286 |
+
if text_sentiment == "Fear":
|
| 287 |
+
if audio_emotion in ["Happy", "Neutral"]:
|
| 288 |
+
return "Fear"
|
| 289 |
+
if audio_emotion in ["Angry", "Sad", "Disgust"]:
|
| 290 |
+
return audio_emotion
|
| 291 |
+
|
| 292 |
+
if text_sentiment == "Disgust":
|
| 293 |
+
if audio_emotion in ["Happy", "Neutral"]:
|
| 294 |
+
return "Disgust"
|
| 295 |
+
if audio_emotion in ["Angry", "Sad", "Fear"]:
|
| 296 |
+
return audio_emotion
|
| 297 |
+
|
| 298 |
+
if text_sentiment == "Neutral":
|
| 299 |
if audio_emotion in ["Happy", "Angry", "Sad"]:
|
| 300 |
return "Neutral"
|
| 301 |
+
if audio_emotion in ["Fear", "Disgust"]:
|
| 302 |
+
return audio_emotion
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
+
return audio_emotion
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
|
| 306 |
+
# =========================================================
|
| 307 |
+
# FEATURE EXTRACTION (FIXED - NO SKLEARN / NO DLL ERRORS)
|
| 308 |
+
# =========================================================
|
| 309 |
+
def custom_trim(y, top_db=30):
|
| 310 |
+
"""Pure Numpy replacement for librosa.effects.trim to avoid sklearn DLL errors"""
|
| 311 |
+
if len(y) == 0:
|
| 312 |
+
return y
|
| 313 |
+
|
| 314 |
+
# Calculate threshold based on top_db
|
| 315 |
+
ref_power = np.max(np.abs(y))
|
| 316 |
+
if ref_power == 0:
|
| 317 |
+
return y
|
| 318 |
+
|
| 319 |
+
threshold = ref_power / (10.0 ** (top_db / 20.0))
|
| 320 |
+
|
| 321 |
+
# Find indices where amplitude > threshold
|
| 322 |
+
non_silent_indices = np.where(np.abs(y) > threshold)[0]
|
| 323 |
+
|
| 324 |
+
if len(non_silent_indices) > 0:
|
| 325 |
+
start_idx = non_silent_indices[0]
|
| 326 |
+
end_idx = non_silent_indices[-1]
|
| 327 |
+
return y[start_idx:end_idx+1]
|
| 328 |
+
else:
|
| 329 |
+
return y
|
| 330 |
|
| 331 |
+
def preprocess(signal):
|
| 332 |
+
# USE CUSTOM TRIM INSTEAD OF LIBROSA!
|
| 333 |
+
signal = custom_trim(signal, top_db=30)
|
| 334 |
signal = signal - np.mean(signal)
|
| 335 |
|
| 336 |
if len(signal) > SAMPLES:
|
|
|
|
| 342 |
signal = np.nan_to_num(signal).astype(np.float32)
|
| 343 |
|
| 344 |
mel = librosa.feature.melspectrogram(
|
| 345 |
+
y=signal, sr=SR, n_fft=N_FFT,
|
| 346 |
+
hop_length=HOP, n_mels=N_MELS
|
| 347 |
)
|
| 348 |
mel = librosa.power_to_db(mel)
|
| 349 |
mfcc = librosa.feature.mfcc(y=signal, sr=SR, n_mfcc=N_MFCC)
|
|
|
|
| 350 |
|
| 351 |
+
feat = np.concatenate([mel, mfcc], axis=0)
|
| 352 |
+
|
| 353 |
+
if feat.shape[1] > MAX_FRAMES:
|
| 354 |
+
feat = feat[:, :MAX_FRAMES]
|
| 355 |
else:
|
| 356 |
+
feat = np.pad(feat, ((0, 0), (0, MAX_FRAMES - feat.shape[1])))
|
| 357 |
+
|
| 358 |
+
feat = feat.T
|
| 359 |
+
feat = feat[..., np.newaxis]
|
| 360 |
|
| 361 |
+
return feat.astype(np.float32)
|
|
|
|
|
|
|
| 362 |
|
| 363 |
+
# =========================================================
|
| 364 |
+
# YOUTUBE SONG FETCH
|
| 365 |
+
# =========================================================
|
| 366 |
+
MAX_API_CALLS = 5
|
| 367 |
+
api_call_count = 0
|
| 368 |
|
| 369 |
+
def get_songs(emotion, text=""):
|
| 370 |
+
|
| 371 |
+
global api_call_count
|
| 372 |
|
|
|
|
|
|
|
|
|
|
| 373 |
try:
|
| 374 |
+
base_query = emotion_to_query.get(emotion, "lofi music")
|
| 375 |
+
query = base_query
|
| 376 |
|
| 377 |
+
if query in yt_cache:
|
| 378 |
+
return yt_cache[query]
|
| 379 |
|
| 380 |
+
if api_call_count >= MAX_API_CALLS:
|
| 381 |
+
print("API disabled (quota protection)")
|
| 382 |
+
return yt_cache.get(query, [{
|
| 383 |
+
"title": "Offline fallback",
|
| 384 |
+
"url": "https://youtube.com"
|
| 385 |
+
}])
|
| 386 |
|
| 387 |
+
request = youtube.search().list(
|
| 388 |
+
q=query,
|
| 389 |
+
part="snippet",
|
| 390 |
+
type="video",
|
| 391 |
+
maxResults=5
|
| 392 |
+
)
|
| 393 |
|
| 394 |
+
response = request.execute()
|
| 395 |
+
api_call_count += 1
|
|
|
|
|
|
|
| 396 |
|
| 397 |
+
songs = []
|
|
|
|
| 398 |
|
| 399 |
+
for item in response["items"]:
|
| 400 |
+
title = item["snippet"]["title"]
|
| 401 |
+
video_id = item["id"]["videoId"]
|
| 402 |
+
url = f"https://www.youtube.com/watch?v={video_id}"
|
| 403 |
|
| 404 |
+
songs.append({
|
| 405 |
+
"title": title,
|
| 406 |
+
"url": url
|
| 407 |
+
})
|
| 408 |
|
| 409 |
+
yt_cache[query] = songs
|
| 410 |
+
save_cache(yt_cache)
|
| 411 |
|
| 412 |
+
return songs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
|
| 414 |
except Exception as e:
|
| 415 |
+
print("YouTube error:", e)
|
| 416 |
+
|
| 417 |
+
return yt_cache.get(query, [{
|
| 418 |
+
"title": "Offline fallback",
|
| 419 |
+
"url": "https://youtube.com"
|
| 420 |
+
}])
|
| 421 |
+
|
| 422 |
+
# =========================================================
|
| 423 |
+
# SAVE HISTORY
|
| 424 |
+
# =========================================================
|
| 425 |
+
def save_history(data):
|
| 426 |
+
|
| 427 |
+
if os.path.exists("history.json"):
|
| 428 |
+
with open("history.json", "r") as f:
|
| 429 |
+
history = json.load(f)
|
| 430 |
+
else:
|
| 431 |
+
history = []
|
| 432 |
+
|
| 433 |
+
history.append(data)
|
| 434 |
+
|
| 435 |
+
with open("history.json", "w") as f:
|
| 436 |
+
json.dump(history, f, indent=4)
|
| 437 |
+
|
| 438 |
+
# =========================================================
|
| 439 |
+
# MAIN PIPELINE
|
| 440 |
+
# =========================================================
|
| 441 |
+
def predict():
|
| 442 |
+
|
| 443 |
+
audio, path = record_audio()
|
| 444 |
+
|
| 445 |
+
feat = preprocess(audio)
|
| 446 |
+
feat = np.expand_dims(feat, axis=0)
|
| 447 |
+
feat = (feat - mean) / (std + 1e-6)
|
| 448 |
+
|
| 449 |
+
probs = model.predict(feat, verbose=0)[0]
|
| 450 |
+
idx = np.argmax(probs)
|
| 451 |
+
|
| 452 |
+
# Use our hardcoded classes to bypass sklearn DLL errors!
|
| 453 |
+
audio_emotion = CLASSES[idx]
|
| 454 |
+
confidence = float(probs[idx])
|
| 455 |
+
|
| 456 |
+
# Pass the raw audio array directly instead of the file path!
|
| 457 |
+
text = speech_to_text(audio)
|
| 458 |
+
text_sentiment = get_text_sentiment(text)
|
| 459 |
+
emotion = correct_emotion(audio_emotion, text_sentiment, confidence)
|
| 460 |
+
|
| 461 |
+
songs = get_songs(emotion, text)
|
| 462 |
+
action = emotion_to_action.get(emotion, "Take a break.")
|
| 463 |
+
|
| 464 |
+
result = {
|
| 465 |
+
"time": str(datetime.now()),
|
| 466 |
+
"emotion": str(emotion),
|
| 467 |
+
"audio_emotion": str(audio_emotion),
|
| 468 |
+
"text_sentiment": text_sentiment,
|
| 469 |
+
"confidence": round(confidence, 3),
|
| 470 |
+
"text": text,
|
| 471 |
+
"songs": songs,
|
| 472 |
+
"action": action
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
save_history(result)
|
| 476 |
+
|
| 477 |
+
print("\nFINAL RESULT")
|
| 478 |
+
print("---------------------------")
|
| 479 |
+
print(f"Time : {result['time']}")
|
| 480 |
+
print(f"Audio Emotion : {result['audio_emotion']}")
|
| 481 |
+
print(f"Text Sentiment: {result['text_sentiment']}")
|
| 482 |
+
print(f"Final Emotion : {result['emotion']}")
|
| 483 |
+
if result['emotion'] != result['audio_emotion']:
|
| 484 |
+
print("(Corrected by text sentiment)")
|
| 485 |
+
print(f"Text : {result['text']}")
|
| 486 |
+
print(f"Confidence : {result['confidence']}")
|
| 487 |
+
print("\nRecommended Songs:")
|
| 488 |
+
for i, song in enumerate(result["songs"], 1):
|
| 489 |
+
print(f"{i}. {song['title']}")
|
| 490 |
+
print(f" {song['url']}")
|
| 491 |
+
|
| 492 |
+
print("\nWhat you should do:")
|
| 493 |
+
print(result["action"])
|
| 494 |
+
|
| 495 |
+
# =========================================================
|
| 496 |
+
# RUN
|
| 497 |
+
# =========================================================
|
| 498 |
+
predict()
|