[Parth Saxena] commited on
Commit ·
1aa20e6
1
Parent(s): b465c05
Fix runtime error: restore FastAPI structure, preserve all user improvements
Browse files
api.py
CHANGED
|
@@ -1,31 +1,30 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
import librosa
|
| 5 |
import tensorflow as tf
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
import
|
| 10 |
-
from
|
| 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):
|
|
@@ -37,34 +36,15 @@ def load_cache():
|
|
| 37 |
return {}
|
| 38 |
|
| 39 |
def save_cache(cache):
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 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",
|
|
@@ -73,426 +53,156 @@ emotion_to_query = {
|
|
| 73 |
"Neutral": "focus instrumental music"
|
| 74 |
}
|
| 75 |
|
| 76 |
-
|
| 77 |
-
"Angry": "
|
| 78 |
-
->
|
| 79 |
-
->
|
| 80 |
-
->
|
| 81 |
-
-> Avoid
|
| 82 |
-
->
|
| 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 |
-
|
| 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 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
except Exception as e:
|
| 165 |
-
print("
|
| 166 |
-
|
| 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 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 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 |
-
|
| 269 |
-
|
| 270 |
-
if
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
if
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 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 |
-
|
| 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 |
-
|
|
|
|
|
|
|
| 333 |
signal = custom_trim(signal, top_db=30)
|
| 334 |
signal = signal - np.mean(signal)
|
| 335 |
-
|
| 336 |
if len(signal) > SAMPLES:
|
| 337 |
start = (len(signal) - SAMPLES) // 2
|
| 338 |
-
signal = signal[start:start
|
| 339 |
else:
|
| 340 |
signal = np.pad(signal, (0, SAMPLES - len(signal)))
|
| 341 |
-
|
| 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,
|
| 357 |
-
|
| 358 |
-
feat = feat.T
|
| 359 |
-
feat = feat[..., np.newaxis]
|
| 360 |
-
|
| 361 |
-
return feat.astype(np.float32)
|
| 362 |
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
# =========================================================
|
| 366 |
-
MAX_API_CALLS = 5
|
| 367 |
-
api_call_count = 0
|
| 368 |
-
|
| 369 |
-
def get_songs(emotion, text=""):
|
| 370 |
|
| 371 |
-
|
|
|
|
|
|
|
| 372 |
|
|
|
|
|
|
|
|
|
|
| 373 |
try:
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 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("
|
| 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 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 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 |
-
|
| 453 |
-
|
| 454 |
-
|
|
|
|
| 455 |
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
emotion = correct_emotion(audio_emotion, text_sentiment, confidence)
|
| 460 |
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 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()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import json
|
| 3 |
+
import pickle
|
| 4 |
import numpy as np
|
| 5 |
import librosa
|
| 6 |
import tensorflow as tf
|
| 7 |
+
from fastapi import FastAPI
|
| 8 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
from typing import List, Optional
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
SR = 22050
|
| 14 |
+
DURATION = 3
|
| 15 |
+
SAMPLES = SR * DURATION
|
| 16 |
+
MODEL_DIR = "saved_model"
|
| 17 |
+
N_MELS = 96
|
| 18 |
+
N_MFCC = 40
|
| 19 |
+
N_FFT = 2048
|
| 20 |
+
HOP = 512
|
| 21 |
+
MAX_FRAMES = 150
|
| 22 |
+
CLASSES = ["Angry", "Disgust", "Fear", "Happy", "Neutral", "Sad"]
|
| 23 |
|
| 24 |
+
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY", "")
|
|
|
|
|
|
|
| 25 |
CACHE_FILE = "yt_cache.json"
|
| 26 |
+
api_call_count = 0
|
| 27 |
+
MAX_API_CALLS = 20
|
| 28 |
|
| 29 |
def load_cache():
|
| 30 |
if os.path.exists(CACHE_FILE):
|
|
|
|
| 36 |
return {}
|
| 37 |
|
| 38 |
def save_cache(cache):
|
| 39 |
+
try:
|
| 40 |
+
with open(CACHE_FILE, "w") as f:
|
| 41 |
+
json.dump(cache, f, indent=2)
|
| 42 |
+
except:
|
| 43 |
+
pass
|
| 44 |
|
| 45 |
yt_cache = load_cache()
|
| 46 |
|
| 47 |
+
EMOTION_TO_QUERY = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
"Angry": "calm stress relief music",
|
| 49 |
"Sad": "sad emotional hindi songs",
|
| 50 |
"Happy": "happy upbeat party songs",
|
|
|
|
| 53 |
"Neutral": "focus instrumental music"
|
| 54 |
}
|
| 55 |
|
| 56 |
+
EMOTION_TO_ACTION = {
|
| 57 |
+
"Angry": "You seem angry.\n-> Pause before reacting.\n-> Take deep breaths (inhale 4s, exhale 6s).\n-> Walk away from the situation.\n-> Avoid decisions right now.\n-> Release energy physically.",
|
| 58 |
+
"Sad": "You seem sad.\n-> Talk to someone you trust.\n-> Write your thoughts down.\n-> Listen to uplifting music.\n-> Do one small task.\n-> Avoid isolation.",
|
| 59 |
+
"Happy": "You seem happy.\n-> Use this energy productively.\n-> Start something meaningful.\n-> Share positivity.\n-> Capture the moment.\n-> Avoid wasting this state.",
|
| 60 |
+
"Fear": "You seem anxious.\n-> Slow your breathing.\n-> Ask: is this real or imagined?\n-> Break problems into small steps.\n-> Stay grounded in present.\n-> Avoid overthinking.",
|
| 61 |
+
"Disgust": "You seem uncomfortable.\n-> Step away from the trigger.\n-> Reset your environment.\n-> Shift focus.\n-> Avoid dwelling.\n-> Give your brain time.",
|
| 62 |
+
"Neutral": "You are balanced.\n-> Best time for deep work.\n-> Start something important.\n-> Avoid distractions.\n-> Plan clearly.\n-> Maintain this state."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
}
|
| 64 |
|
| 65 |
+
def get_songs(emotion):
|
| 66 |
+
global api_call_count
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
try:
|
| 68 |
+
query = EMOTION_TO_QUERY.get(emotion, "lofi music")
|
| 69 |
+
if query in yt_cache:
|
| 70 |
+
return yt_cache[query]
|
| 71 |
+
if not YOUTUBE_API_KEY or api_call_count >= MAX_API_CALLS:
|
| 72 |
+
return yt_cache.get(query, [])
|
| 73 |
+
import socket
|
| 74 |
+
socket.setdefaulttimeout(8)
|
| 75 |
+
from googleapiclient.discovery import build
|
| 76 |
+
youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY, cache_discovery=False)
|
| 77 |
+
response = youtube.search().list(q=query, part="snippet", type="video", maxResults=3).execute()
|
| 78 |
+
api_call_count += 1
|
| 79 |
+
songs = [{"title": item["snippet"]["title"], "url": f"https://www.youtube.com/watch?v={item['id']['videoId']}"} for item in response.get("items", [])]
|
| 80 |
+
yt_cache[query] = songs
|
| 81 |
+
save_cache(yt_cache)
|
| 82 |
+
return songs
|
| 83 |
except Exception as e:
|
| 84 |
+
print(f"[YOUTUBE ERROR] {e}")
|
| 85 |
+
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
HAPPY_WORDS = {"happy","joy","joyful","cheerful","delighted","pleased","glad","thrilled","ecstatic","blissful","merry","jolly","elated","overjoyed","euphoric","radiant","beaming","love","adore","cherish","dear","darling","sweetheart","beloved","fond","affection","caring","tender","warm","heart","hug","kiss","miss","romantic","crush","thanks","thank","grateful","thankful","appreciate","blessed","fortunate","lucky","excited","amazing","awesome","incredible","fantastic","wonderful","marvelous","spectacular","magnificent","extraordinary","phenomenal","outstanding","superb","brilliant","excellent","fabulous","glorious","splendid","wow","yay","hooray","beautiful","gorgeous","pretty","lovely","cute","handsome","stunning","elegant","charming","adorable","sweet","kind","gentle","generous","thoughtful","smart","brave","strong","confident","proud","success","win","won","winner","victory","achieve","accomplished","congratulations","celebrate","enjoy","fun","laugh","smile","peaceful","calm","safe","secure","healthy","good","great","nice","perfect","best","better","hope","hopeful","optimistic","yes","okay","alright","lol","haha"}
|
| 88 |
+
ANGRY_WORDS = {"angry","anger","mad","furious","rage","raging","irritated","annoyed","frustrated","outraged","livid","fuming","bitter","hostile","aggressive","violent","fight","argue","argument","scream","yell","shout","curse","blame","revenge","threat","damn","hell","stop","enough"}
|
| 89 |
+
SAD_WORDS = {"sad","sadness","unhappy","depressed","depression","miserable","gloomy","melancholy","lonely","loneliness","alone","isolated","heartbroken","grief","grieve","mourn","sorrow","cry","crying","tears","weep","sob","hopeless","helpless","weak","boring","bored","tired","exhausted","disappointed","regret","sorry","unfortunately","sadly"}
|
| 90 |
+
FEAR_WORDS = {"fear","afraid","scared","terrified","frightened","panic","panicking","anxious","anxiety","nervous","worried","worry","dread","horror","horrified","shocked","tense","stressed","stress","overwhelmed","paranoid","nightmare","creepy","spooky"}
|
| 91 |
+
DISGUST_WORDS = {"hate","hatred","despise","detest","loathe","resent","dislike","disgust","disgusting","repulsive","revolting","gross","nasty","vile","toxic","terrible","horrible","awful","dreadful","pathetic","worthless","useless","ugly","stupid","dumb","idiot","fool","lazy","cruel","mean","rude","fake","liar","cheat","betrayed","bad","worse","worst","wrong","fail","failed","failure","impossible","unfair","evil","bully","harass","destroy","ruin","reject","abandon","ugh","crap","suck","sucks","trash","garbage"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
def get_text_sentiment(text):
|
| 94 |
if not text:
|
| 95 |
return "Neutral"
|
|
|
|
| 96 |
words = set(text.lower().split())
|
| 97 |
+
scores = {"Happy": len(words & HAPPY_WORDS), "Angry": len(words & ANGRY_WORDS), "Sad": len(words & SAD_WORDS), "Fear": len(words & FEAR_WORDS), "Disgust": len(words & DISGUST_WORDS)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
max_score = max(scores.values())
|
|
|
|
| 99 |
if max_score == 0:
|
| 100 |
return "Neutral"
|
| 101 |
+
return max(scores, key=scores.get)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
def correct_emotion(audio_emotion, text_sentiment, confidence):
|
|
|
|
| 104 |
if confidence > 0.50:
|
| 105 |
return audio_emotion
|
| 106 |
+
ts = text_sentiment.capitalize()
|
| 107 |
+
if ts == "Happy" and audio_emotion in ["Angry","Sad","Fear","Disgust","Neutral"]:
|
| 108 |
+
return "Happy"
|
| 109 |
+
if ts == "Angry" and audio_emotion in ["Happy","Neutral"]:
|
| 110 |
+
return "Angry"
|
| 111 |
+
if ts == "Sad" and audio_emotion in ["Happy","Neutral"]:
|
| 112 |
+
return "Sad"
|
| 113 |
+
if ts == "Fear" and audio_emotion in ["Happy","Neutral"]:
|
| 114 |
+
return "Fear"
|
| 115 |
+
if ts == "Disgust" and audio_emotion in ["Happy","Neutral"]:
|
| 116 |
+
return "Disgust"
|
| 117 |
+
if ts == "Neutral" and audio_emotion in ["Happy","Angry","Sad"]:
|
| 118 |
+
return "Neutral"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
return audio_emotion
|
| 120 |
|
|
|
|
|
|
|
|
|
|
| 121 |
def custom_trim(y, top_db=30):
|
|
|
|
| 122 |
if len(y) == 0:
|
| 123 |
return y
|
|
|
|
|
|
|
| 124 |
ref_power = np.max(np.abs(y))
|
| 125 |
if ref_power == 0:
|
| 126 |
return y
|
|
|
|
| 127 |
threshold = ref_power / (10.0 ** (top_db / 20.0))
|
| 128 |
+
non_silent = np.where(np.abs(y) > threshold)[0]
|
| 129 |
+
return y[non_silent[0]:non_silent[-1]+1] if len(non_silent) > 0 else y
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
def preprocess(signal, src_sr):
|
| 132 |
+
signal = np.array(signal, dtype=np.float32)
|
| 133 |
+
if src_sr != SR:
|
| 134 |
+
signal = librosa.resample(signal, orig_sr=src_sr, target_sr=SR)
|
| 135 |
signal = custom_trim(signal, top_db=30)
|
| 136 |
signal = signal - np.mean(signal)
|
|
|
|
| 137 |
if len(signal) > SAMPLES:
|
| 138 |
start = (len(signal) - SAMPLES) // 2
|
| 139 |
+
signal = signal[start:start+SAMPLES]
|
| 140 |
else:
|
| 141 |
signal = np.pad(signal, (0, SAMPLES - len(signal)))
|
|
|
|
| 142 |
signal = np.nan_to_num(signal).astype(np.float32)
|
| 143 |
+
mel = librosa.feature.melspectrogram(y=signal, sr=SR, n_fft=N_FFT, hop_length=HOP, n_mels=N_MELS)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
mel = librosa.power_to_db(mel)
|
| 145 |
mfcc = librosa.feature.mfcc(y=signal, sr=SR, n_mfcc=N_MFCC)
|
|
|
|
| 146 |
feat = np.concatenate([mel, mfcc], axis=0)
|
|
|
|
| 147 |
if feat.shape[1] > MAX_FRAMES:
|
| 148 |
feat = feat[:, :MAX_FRAMES]
|
| 149 |
else:
|
| 150 |
+
feat = np.pad(feat, ((0,0),(0, MAX_FRAMES - feat.shape[1])))
|
| 151 |
+
return feat.T[..., np.newaxis].astype(np.float32)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
+
app = FastAPI()
|
| 154 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET","POST"], allow_headers=["*"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
+
model = None
|
| 157 |
+
mean = None
|
| 158 |
+
std = None
|
| 159 |
|
| 160 |
+
@app.on_event("startup")
|
| 161 |
+
def load_resources():
|
| 162 |
+
global model, mean, std
|
| 163 |
try:
|
| 164 |
+
model = tf.keras.models.load_model(os.path.join(MODEL_DIR, "emotion_model.keras"))
|
| 165 |
+
with open(os.path.join(MODEL_DIR, "norm.pkl"), "rb") as f:
|
| 166 |
+
norm = pickle.load(f)
|
| 167 |
+
mean = norm["mean"]
|
| 168 |
+
std = norm["std"]
|
| 169 |
+
print(f"[STARTUP] Model loaded. Classes: {CLASSES}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
except Exception as e:
|
| 171 |
+
print(f"[STARTUP ERROR] {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
+
class AudioData(BaseModel):
|
| 174 |
+
signal: List[float]
|
| 175 |
+
sample_rate: int = 22050
|
| 176 |
+
text: Optional[str] = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
+
@app.get("/", response_class=HTMLResponse)
|
| 179 |
+
async def read_root():
|
| 180 |
+
with open("moodwave.html", "r", encoding="utf-8") as f:
|
| 181 |
+
return f.read()
|
| 182 |
|
| 183 |
+
@app.get("/health")
|
| 184 |
+
async def health_check():
|
| 185 |
+
return {"status": "ok", "model_loaded": model is not None}
|
|
|
|
| 186 |
|
| 187 |
+
@app.post("/predict")
|
| 188 |
+
async def predict_emotion(data: AudioData):
|
| 189 |
+
try:
|
| 190 |
+
if model is None:
|
| 191 |
+
return JSONResponse(status_code=200, content={"error": "Model not loaded yet"})
|
| 192 |
+
feat = preprocess(np.array(data.signal), data.sample_rate)
|
| 193 |
+
feat_norm = (feat - mean) / (std + 1e-6)
|
| 194 |
+
feat_norm = np.expand_dims(feat_norm, axis=0)
|
| 195 |
+
probs = model.predict(feat_norm, verbose=0)[0]
|
| 196 |
+
idx = int(np.argmax(probs))
|
| 197 |
+
audio_emotion = CLASSES[idx]
|
| 198 |
+
confidence = float(probs[idx])
|
| 199 |
+
text_sentiment = get_text_sentiment(data.text or "")
|
| 200 |
+
final_emotion = correct_emotion(audio_emotion, text_sentiment, confidence)
|
| 201 |
+
confidences = {CLASSES[i]: float(p) for i, p in enumerate(probs)}
|
| 202 |
+
songs = get_songs(final_emotion)
|
| 203 |
+
action = EMOTION_TO_ACTION.get(final_emotion, "Take a break.")
|
| 204 |
+
print(f"[PREDICT] audio={audio_emotion} final={final_emotion} conf={confidence:.2f}")
|
| 205 |
+
return {"emotion": final_emotion, "audio_emotion": audio_emotion, "text_sentiment": text_sentiment, "confidence": confidence, "all_scores": confidences, "songs": songs, "action": action}
|
| 206 |
+
except Exception as e:
|
| 207 |
+
import traceback; traceback.print_exc()
|
| 208 |
+
return JSONResponse(status_code=200, content={"error": str(e), "emotion": "Neutral", "audio_emotion": "Neutral", "text_sentiment": "Neutral", "confidence": 0.0, "all_scores": {}, "songs": [], "action": EMOTION_TO_ACTION["Neutral"]})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|