ravi86 commited on
Commit
810ec93
Β·
verified Β·
1 Parent(s): 2fb9208

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -201
app.py CHANGED
@@ -5,257 +5,104 @@ from PIL import Image
5
  import numpy as np
6
  import os
7
 
8
- # Try importing TensorFlow. This is crucial for .h5 models.
9
  try:
10
  import tensorflow as tf
11
  IS_TF_AVAILABLE = True
12
- print("TensorFlow is available.")
13
  except ImportError:
14
  IS_TF_AVAILABLE = False
15
- print("TensorFlow is not available. .h5 models loaded directly with tf.keras.models.load_model will not work.")
16
 
17
-
18
- # --- 1. Load the Model ---
19
- # IMPORTANT: Replace "ravi86/mood_detector" with your actual model name on Hugging Face Hub,
20
- # or ensure your local model files are correctly placed in the 'model/' directory.
21
-
22
- model_name_or_path = "ravi86/mood_detector" # Default to Hugging Face Hub model
23
  model = None
24
  processor = None
25
- is_pytorch_model = True # Flag to track model type (defaults to PyTorch)
 
 
 
26
 
27
  try:
28
- # 1. Attempt to load as a PyTorch model from Hugging Face Hub (default behavior)
29
  model = AutoModelForImageClassification.from_pretrained(model_name_or_path)
30
  processor = AutoImageProcessor.from_pretrained(model_name_or_path)
31
- print(f"Model and processor loaded successfully from Hugging Face Hub: {model_name_or_path} (PyTorch)")
32
- except Exception as e_hub_pt:
33
- print(f"Error loading PyTorch model from Hugging Face Hub ({model_name_or_path}): {e_hub_pt}")
34
-
35
- # 2. If PyTorch Hub load fails, attempt to load as a TensorFlow model from Hugging Face Hub
36
  if IS_TF_AVAILABLE:
37
  try:
38
- model = AutoModelForImageClassification.from_pretrained(model_name_or_path, from_tf=True)
39
- processor = AutoImageProcessor.from_pretrained(model_name_or_path)
40
- is_pytorch_model = False # Set flag as it's a TF model
41
- print(f"Model and processor loaded successfully from Hugging Face Hub: {model_name_or_path} (TensorFlow)")
42
- except Exception as e_hub_tf:
43
- print(f"Error loading TensorFlow model from Hugging Face Hub ({model_name_or_path}): {e_hub_tf}")
44
-
45
- # 3. If still no model loaded, try local files (both Transformers-saved and raw .h5)
46
- if model is None:
47
- print("Trying to load model from local 'model/' directory...")
48
- local_model_dir = "./model"
49
- local_h5_path = os.path.join(local_model_dir, "my_model.h5") # <--- UPDATED THIS LINE
50
-
51
- # Attempt to load as a Transformers model (might be PyTorch or TF saved with save_pretrained)
52
- try:
53
- model = AutoModelForImageClassification.from_pretrained(local_model_dir)
54
- processor = AutoImageProcessor.from_pretrained(local_model_dir)
55
- # Determine if it's PyTorch or TF based on internal attribute
56
- is_pytorch_model = hasattr(model, 'parameters') and callable(getattr(model, 'parameters'))
57
- print(f"Model and processor loaded successfully from local '{local_model_dir}' (Transformers format, {'PyTorch' if is_pytorch_model else 'TensorFlow'})!")
58
- except Exception as e_local_transformers:
59
- print(f"Error loading Transformers model from local '{local_model_dir}': {e_local_transformers}")
60
-
61
- # If it failed as a Transformers model, try loading raw .h5 if TensorFlow is available
62
- if IS_TF_AVAILABLE and os.path.exists(local_h5_path):
63
- try:
64
- model = tf.keras.models.load_model(local_h5_path)
65
- # For raw Keras .h5, we assume AutoImageProcessor (or similar preprocessor) is still valid.
66
- # If your .h5 model has custom preprocessing, you'll need to define it here.
67
- # For now, we'll try to load a processor based on the original model_name_or_path
68
- # or a generic one if no preprocessor_config.json is present in ./model.
69
- try:
70
- processor = AutoImageProcessor.from_pretrained(local_model_dir)
71
- except Exception:
72
- print("Could not load processor from local model directory, trying generic AutoImageProcessor.")
73
- # Fallback if preprocessor_config.json is missing for local .h5
74
- processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224") # Generic image processor example
75
- is_pytorch_model = False # It's a Keras TF model
76
- print(f"Model loaded successfully from local .h5 file: {local_h5_path} (TensorFlow Keras)")
77
- except Exception as e_local_h5:
78
- print(f"Error loading .h5 model directly: {e_local_h5}")
79
 
80
- # Final check if model loaded successfully
81
  if model is None or processor is None:
82
- raise RuntimeError("Failed to load facial expression model from any source. Please check model path, files, and dependencies.")
83
 
84
- # Set model to evaluation mode for PyTorch models only
85
  if is_pytorch_model:
86
  model.eval()
87
- else:
88
- # Keras models are typically ready for inference by default, no .eval() needed
89
- pass
90
 
91
- # --- 2. Define Emotion Labels and Spotify Playlist Mapping ---
92
  emotions = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
93
 
94
- # IMPORTANT: Replace these with actual Spotify playlist URLs.
95
- # You can find many public mood-based playlists on Spotify.
96
- # These are placeholder examples.
97
  spotify_playlist_mapping = {
98
- "Angry": "https://open.spotify.com/playlist/37i9dQZF1DX2LTjeP1y0aR", # Aggressive Rock/Metal
99
- "Disgust": "https://open.spotify.com/playlist/37i9dQZF1DXcK3k3gJ6usM", # Something a bit unsettling or chaotic
100
- "Fear": "https://open.spotify.com/playlist/37i9dQZF1DX4Qp4Cp4wK2N", # Dark Ambient/Suspenseful
101
- "Happy": "https://open.spotify.com/playlist/37i9dQZF1DXdPec7aLk9C1", # Happy Hits!
102
- "Sad": "https://open.spotify.com/playlist/37i9dQZF1DX7qK8TM4T5pC", # Sad Indie
103
- "Surprise": "https://open.spotify.com/playlist/37i9dQZF1DXdgnL3vj1gWM", # High Energy/Unexpected
104
- "Neutral": "https://open.spotify.com/playlist/37i9dQZF1DXasMvN3R0sVw" # Chill Instrumental
105
  }
106
 
107
- # --- 3. Prediction Function ---
108
- def classify_expression_and_suggest_music(image_input: np.ndarray):
109
  if image_input is None:
110
- return "No webcam input detected. Please allow camera access.", ""
111
 
112
- # Convert NumPy array to PIL Image (and ensure grayscale)
113
- image = Image.fromarray(image_input).convert("L") # Convert to grayscale
114
- image = image.resize((48, 48)) # Resize to model's expected input dimensions
115
 
116
- # Prepare image for model inference using the processor
117
- # The processor usually returns PyTorch tensors by default
118
  inputs = processor(images=image, return_tensors="pt")
 
119
 
120
- # If the model is a TensorFlow Keras model, convert inputs to TensorFlow tensors
121
- if not is_pytorch_model:
122
- # Assuming the processor outputs a dictionary with 'pixel_values' key for image data
123
- # Convert PyTorch tensor to NumPy, then to TensorFlow tensor
124
- # Squeeze(0) removes the batch dimension which `from_pretrained` might add
125
  pixel_values_np = inputs['pixel_values'].squeeze(0).numpy()
126
- pixel_values_tf = tf.convert_to_tensor(pixel_values_np, dtype=tf.float32)
127
- # Add batch dimension back for the model if necessary (Keras models expect batch dim)
128
- inputs_for_model = tf.expand_dims(pixel_values_tf, axis=0)
129
- else:
130
- inputs_for_model = inputs['pixel_values'] # For PyTorch, just use the pixel values
131
-
132
 
133
- # Perform inference
134
- with torch.no_grad(): # This context manager is primarily for PyTorch, does nothing for TF models
135
  if is_pytorch_model:
136
  outputs = model(inputs_for_model)
137
- logits = outputs.logits # Access logits if model output is an object (common in Transformers models)
138
  else:
139
- # For a raw Keras model, it usually returns raw logits directly
140
  outputs = model(inputs_for_model)
141
- logits = outputs # Assume direct output is logits for a simple Keras model
142
 
143
- # Ensure logits is a torch.Tensor for softmax calculation.
144
- # If it's a TensorFlow tensor from a Keras model, convert it.
145
- if IS_TF_AVAILABLE and not is_pytorch_model and isinstance(logits, tf.Tensor):
146
- logits = torch.from_numpy(logits.numpy()) # Convert TF tensor to PyTorch tensor for softmax
147
  elif not isinstance(logits, torch.Tensor):
148
- # This case handles if logits is a numpy array or other format after TF processing
149
  logits = torch.from_numpy(np.array(logits))
150
 
151
-
152
  probs = torch.softmax(logits, dim=-1)
153
 
154
- predicted_class_idx = probs.argmax().item()
155
- predicted_emotion = emotions[predicted_class_idx]
156
- confidence = probs[0, predicted_class_idx].item() * 100
157
-
158
- output_text = f"Detected Emotion: **{predicted_emotion}** (Confidence: {confidence:.2f}%)"
159
-
160
- # Get the Spotify playlist URL for the detected emotion
161
- playlist_url = spotify_playlist_mapping.get(predicted_emotion, spotify_playlist_mapping["Neutral"])
162
 
163
- # Create a clickable markdown link for the Spotify playlist
164
- spotify_link_markdown = f"**Listen on Spotify:** <a href='{playlist_url}' target='_blank'>🎧 {predicted_emotion} Vibes</a>"
 
165
 
166
- return output_text, spotify_link_markdown
167
 
168
- # --- 4. Gradio Interface ---
169
- # Define the Gradio Interface
170
  iface = gr.Interface(
171
  fn=classify_expression_and_suggest_music,
172
- inputs=gr.Image(
173
- type="numpy",
174
- source="webcam",
175
- streaming=True, # Enable continuous streaming from webcam
176
- label="Your Live Webcam Feed (Ensure good lighting and center face!)"
177
- ),
178
  outputs=[
179
  gr.Textbox(label="Emotion Detected"),
180
- gr.Markdown(label="Suggested Music") # Use Markdown to display the clickable Spotify link
181
  ],
182
- live=True, # Process input continuously as it changes
183
  title="🎭 MoodTune: Your Emotional DJ 🎢",
184
- description=(
185
- "This Hugging Face Space detects your facial expression in real-time "
186
- "and suggests a Spotify playlist tailored to your mood! "
187
- "**Ensure good lighting and center your face for best results.**"
188
- "<br>*(Click the Spotify link below to open the playlist in a new tab.)*"
189
- ),
190
- css="""
191
- .gradio-container {
192
- font-family: 'Inter', sans-serif;
193
- background-color: #f0f2f5;
194
- padding: 20px;
195
- border-radius: 12px;
196
- box-shadow: 0 4px 15px rgba(0,0,0,0.1);
197
- }
198
- h1 {
199
- color: #2c3e50;
200
- text-align: center;
201
- font-size: 2.5em;
202
- margin-bottom: 20px;
203
- }
204
- .gr-button {
205
- background-color: #3498db !important; /* A nice blue */
206
- color: white !important;
207
- border-radius: 8px;
208
- padding: 10px 20px;
209
- font-weight: bold;
210
- transition: background-color 0.3s ease;
211
- }
212
- .gr-button:hover {
213
- background-color: #2980b9 !important;
214
- }
215
- .gr-text {
216
- font-size: 1.3em;
217
- font-weight: bold;
218
- color: #2c3e50;
219
- text-align: center;
220
- padding: 15px;
221
- background-color: #ecf0f1;
222
- border-radius: 8px;
223
- margin-top: 15px;
224
- border: 1px solid #bdc3c7;
225
- }
226
- .gr-image {
227
- border: 3px solid #3498db;
228
- border-radius: 12px;
229
- box-shadow: 0 2px 10px rgba(0,0,0,0.08);
230
- width: 100%; /* Make image responsive */
231
- max-width: 600px; /* Max width for image */
232
- margin: auto; /* Center the image */
233
- }
234
- .gr-markdown {
235
- text-align: center;
236
- margin-top: 20px;
237
- font-size: 1.2em;
238
- }
239
- .gr-markdown a {
240
- color: #1DB954; /* Spotify green */
241
- text-decoration: none;
242
- font-weight: bold;
243
- }
244
- .gr-markdown a:hover {
245
- text-decoration: underline;
246
- }
247
- /* Responsive adjustments */
248
- @media (max-width: 768px) {
249
- h1 {
250
- font-size: 1.8em;
251
- }
252
- .gr-text {
253
- font-size: 1em;
254
- }
255
- }
256
- """
257
  )
258
 
259
- # Launch the Gradio app
260
- if __name__ == "__main__":
261
- iface.launch()
 
5
  import numpy as np
6
  import os
7
 
8
+ # Check for TensorFlow
9
  try:
10
  import tensorflow as tf
11
  IS_TF_AVAILABLE = True
 
12
  except ImportError:
13
  IS_TF_AVAILABLE = False
 
14
 
15
+ # --- Load Model ---
 
 
 
 
 
16
  model = None
17
  processor = None
18
+ is_pytorch_model = True
19
+
20
+ model_name_or_path = "ravi86/mood_detector"
21
+ local_h5_path = "./my_model.h5"
22
 
23
  try:
 
24
  model = AutoModelForImageClassification.from_pretrained(model_name_or_path)
25
  processor = AutoImageProcessor.from_pretrained(model_name_or_path)
26
+ except:
 
 
 
 
27
  if IS_TF_AVAILABLE:
28
  try:
29
+ model = tf.keras.models.load_model(local_h5_path)
30
+ processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
31
+ is_pytorch_model = False
32
+ except:
33
+ raise RuntimeError("Could not load .h5 model.")
34
+ else:
35
+ raise RuntimeError("Model loading failed. No valid model found.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
 
37
  if model is None or processor is None:
38
+ raise RuntimeError("Model or processor not loaded.")
39
 
 
40
  if is_pytorch_model:
41
  model.eval()
 
 
 
42
 
43
+ # --- Labels and Music Mapping ---
44
  emotions = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
45
 
 
 
 
46
  spotify_playlist_mapping = {
47
+ "Angry": "https://open.spotify.com/playlist/37i9dQZF1DX2LTjeP1y0aR",
48
+ "Disgust": "https://open.spotify.com/playlist/37i9dQZF1DXcK3k3gJ6usM",
49
+ "Fear": "https://open.spotify.com/playlist/37i9dQZF1DX4Qp4Cp4wK2N",
50
+ "Happy": "https://open.spotify.com/playlist/37i9dQZF1DXdPec7aLk9C1",
51
+ "Sad": "https://open.spotify.com/playlist/37i9dQZF1DX7qK8TM4T5pC",
52
+ "Surprise": "https://open.spotify.com/playlist/37i9dQZF1DXdgnL3vj1gWM",
53
+ "Neutral": "https://open.spotify.com/playlist/37i9dQZF1DXasMvN3R0sVw"
54
  }
55
 
56
+ # --- Predict Function ---
57
+ def classify_expression_and_suggest_music(image_input):
58
  if image_input is None:
59
+ return "No webcam input detected.", ""
60
 
61
+ image = Image.fromarray(image_input).convert("L").resize((48, 48))
 
 
62
 
 
 
63
  inputs = processor(images=image, return_tensors="pt")
64
+ inputs_for_model = inputs['pixel_values']
65
 
66
+ if not is_pytorch_model and IS_TF_AVAILABLE:
 
 
 
 
67
  pixel_values_np = inputs['pixel_values'].squeeze(0).numpy()
68
+ inputs_for_model = tf.expand_dims(tf.convert_to_tensor(pixel_values_np), 0)
 
 
 
 
 
69
 
70
+ with torch.no_grad():
 
71
  if is_pytorch_model:
72
  outputs = model(inputs_for_model)
73
+ logits = outputs.logits
74
  else:
 
75
  outputs = model(inputs_for_model)
76
+ logits = outputs
77
 
78
+ if isinstance(logits, tf.Tensor):
79
+ logits = torch.from_numpy(logits.numpy())
 
 
80
  elif not isinstance(logits, torch.Tensor):
 
81
  logits = torch.from_numpy(np.array(logits))
82
 
 
83
  probs = torch.softmax(logits, dim=-1)
84
 
85
+ idx = probs.argmax().item()
86
+ emotion = emotions[idx]
87
+ confidence = probs[0, idx].item() * 100
 
 
 
 
 
88
 
89
+ output_text = f"Detected Emotion: **{emotion}** (Confidence: {confidence:.2f}%)"
90
+ playlist_url = spotify_playlist_mapping.get(emotion, spotify_playlist_mapping["Neutral"])
91
+ spotify_link = f"**Listen on Spotify:** <a href='{playlist_url}' target='_blank'>🎧 {emotion} Vibes</a>"
92
 
93
+ return output_text, spotify_link
94
 
95
+ # --- Gradio UI ---
 
96
  iface = gr.Interface(
97
  fn=classify_expression_and_suggest_music,
98
+ inputs=gr.Image(type="numpy", source="webcam", streaming=True, label="Live Webcam"),
 
 
 
 
 
99
  outputs=[
100
  gr.Textbox(label="Emotion Detected"),
101
+ gr.Markdown(label="Suggested Music")
102
  ],
103
+ live=True,
104
  title="🎭 MoodTune: Your Emotional DJ 🎢",
105
+ description="Real-time facial expression detector that plays music to match your mood!",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  )
107
 
108
+ iface.launch() # Automatically runs in Hugging Face Spaces