alonb19 commited on
Commit
4d2d55a
·
verified ·
1 Parent(s): 659ed0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -41
app.py CHANGED
@@ -1,4 +1,3 @@
1
- # app.py - Musical Instrument Detection API con modelo específico
2
  from fastapi import FastAPI, File, UploadFile, HTTPException
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from transformers import pipeline
@@ -11,7 +10,6 @@ from datetime import datetime
11
  import torch
12
  from contextlib import asynccontextmanager
13
  import subprocess
14
- import wave
15
 
16
  # Configurar cache
17
  os.environ['TRANSFORMERS_CACHE'] = '/tmp/transformers_cache'
@@ -30,7 +28,7 @@ logger = logging.getLogger(__name__)
30
  classifier = None
31
 
32
  async def load_model():
33
- """Cargar modelo específico para instrumentos musicales"""
34
  global classifier
35
  try:
36
  logger.info("Iniciando carga del modelo...")
@@ -40,8 +38,8 @@ async def load_model():
40
  os.makedirs('/tmp/huggingface', exist_ok=True)
41
  os.makedirs('/tmp/numba_cache', exist_ok=True)
42
 
43
- # MODELO ESPECÍFICO PARA INSTRUMENTOS MUSICALES
44
- model_name = "dima806/musical_instrument_detection"
45
 
46
  logger.info(f"Cargando modelo: {model_name}")
47
 
@@ -52,11 +50,28 @@ async def load_model():
52
  return_all_scores=True
53
  )
54
 
55
- logger.info("Modelo de instrumentos musicales cargado exitosamente")
56
 
57
  except Exception as e:
58
- logger.error(f"Error cargando modelo: {e}")
59
- classifier = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  async def cleanup_model():
62
  """Limpiar recursos"""
@@ -72,8 +87,8 @@ async def lifespan(app: FastAPI):
72
 
73
  app = FastAPI(
74
  title="Musical Instrument Detection API",
75
- description="API para detectar instrumentos musicales en pistas de audio",
76
- version="3.0.0",
77
  lifespan=lifespan
78
  )
79
 
@@ -159,14 +174,63 @@ def load_audio_robust(file_path):
159
  logger.error(f"Error cargando audio: {e}")
160
  raise
161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  @app.get("/")
163
  async def root():
164
  return {
165
  "message": "Musical Instrument Detection API",
166
  "status": "online",
167
- "version": "3.0.0",
168
- "model": "dima806/musical_instrument_detection",
169
- "capabilities": ["guitar", "piano", "drums", "violin", "bass", "flute", "trumpet", "saxophone"],
170
  "endpoints": {
171
  "health": "/health",
172
  "detect": "/detect",
@@ -179,15 +243,14 @@ async def health_check():
179
  return {
180
  "status": "online" if classifier is not None else "error",
181
  "model_loaded": classifier is not None,
182
- "model_name": "dima806/musical_instrument_detection",
183
- "timestamp": datetime.now().isoformat(),
184
- "ffmpeg_available": subprocess.run(['ffmpeg', '-version'],
185
- capture_output=True).returncode == 0
186
  }
187
 
188
  @app.post("/detect")
189
  async def detect_instrument(audio: UploadFile = File(...)):
190
- """Detectar instrumentos musicales en pista de audio"""
191
  start_time = datetime.now()
192
 
193
  try:
@@ -196,17 +259,16 @@ async def detect_instrument(audio: UploadFile = File(...)):
196
  raise HTTPException(status_code=503, detail="Modelo no disponible")
197
 
198
  logger.info(f"Procesando pista: {audio.filename}")
199
- logger.info(f"Content-Type: {audio.content_type}")
200
 
201
  # Leer contenido
202
  content = await audio.read()
203
  file_size_mb = len(content) / (1024 * 1024)
204
  logger.info(f"Tamaño: {file_size_mb:.2f}MB")
205
 
206
- if file_size_mb > 15: # Aumentamos límite para pistas completas
207
- raise HTTPException(status_code=413, detail="Archivo demasiado grande. Máximo 15MB")
208
 
209
- # Crear archivo temporal
210
  with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
211
  temp_file.write(content)
212
  temp_path = temp_file.name
@@ -221,34 +283,25 @@ async def detect_instrument(audio: UploadFile = File(...)):
221
  logger.info(f"Audio cargado: {duration:.2f}s, {sample_rate}Hz")
222
 
223
  if duration < 0.5:
224
- raise HTTPException(status_code=400, detail="Audio demasiado corto para detectar instrumentos")
225
 
226
- # Para pistas largas, analizar en segmentos
227
  if duration > 60:
228
- # Analizar primeros 60 segundos
229
  max_samples = 60 * sample_rate
230
  audio_data = audio_data[:max_samples]
231
- logger.info("Analizando primeros 60 segundos de la pista")
232
 
233
  # Normalizar
234
  if np.max(np.abs(audio_data)) > 0:
235
  audio_data = audio_data / np.max(np.abs(audio_data))
236
 
237
- logger.info("Detectando instrumentos musicales...")
238
 
239
- # Clasificar instrumentos
240
  results = classifier(audio_data)
241
 
242
- # Procesar y filtrar resultados
243
- instruments_detected = []
244
- for result in results:
245
- confidence = float(result['score'])
246
- if confidence > 0.1: # Solo instrumentos con confianza > 10%
247
- instruments_detected.append({
248
- "instrument": result['label'],
249
- "confidence": round(confidence, 4),
250
- "percentage": round(confidence * 100, 2)
251
- })
252
 
253
  # Ordenar por confianza
254
  instruments_detected.sort(key=lambda x: x['confidence'], reverse=True)
@@ -257,14 +310,18 @@ async def detect_instrument(audio: UploadFile = File(...)):
257
 
258
  response = {
259
  "success": True,
260
- "instruments_detected": instruments_detected[:10], # Top 10 instrumentos
261
  "total_instruments_found": len(instruments_detected),
 
 
 
 
 
262
  "audio_info": {
263
  "filename": audio.filename,
264
  "duration": round(duration, 2),
265
  "size_mb": round(file_size_mb, 2),
266
- "sample_rate": sample_rate,
267
- "analyzed_duration": min(duration, 60)
268
  },
269
  "processing_time": round(processing_time, 3),
270
  "timestamp": datetime.now().isoformat()
 
 
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from transformers import pipeline
 
10
  import torch
11
  from contextlib import asynccontextmanager
12
  import subprocess
 
13
 
14
  # Configurar cache
15
  os.environ['TRANSFORMERS_CACHE'] = '/tmp/transformers_cache'
 
28
  classifier = None
29
 
30
  async def load_model():
31
+ """Cargar modelo MIT/AST más balanceado"""
32
  global classifier
33
  try:
34
  logger.info("Iniciando carga del modelo...")
 
38
  os.makedirs('/tmp/huggingface', exist_ok=True)
39
  os.makedirs('/tmp/numba_cache', exist_ok=True)
40
 
41
+ # MODELO MIT/AST - MÁS BALANCEADO (527 clases de AudioSet)
42
+ model_name = "MIT/ast-finetuned-audioset-10-10-0.4593"
43
 
44
  logger.info(f"Cargando modelo: {model_name}")
45
 
 
50
  return_all_scores=True
51
  )
52
 
53
+ logger.info("Modelo MIT/AST cargado exitosamente (527 clases)")
54
 
55
  except Exception as e:
56
+ logger.error(f"Error cargando modelo MIT/AST: {e}")
57
+
58
+ # Fallback al modelo anterior si MIT/AST no funciona
59
+ try:
60
+ logger.info("Intentando modelo alternativo...")
61
+ model_name_fallback = "dima806/musical_instrument_detection"
62
+
63
+ classifier = pipeline(
64
+ "audio-classification",
65
+ model=model_name_fallback,
66
+ device=-1,
67
+ return_all_scores=True
68
+ )
69
+
70
+ logger.info("Modelo alternativo cargado")
71
+
72
+ except Exception as e2:
73
+ logger.error(f"Error con modelo alternativo: {e2}")
74
+ classifier = None
75
 
76
  async def cleanup_model():
77
  """Limpiar recursos"""
 
87
 
88
  app = FastAPI(
89
  title="Musical Instrument Detection API",
90
+ description="API para detectar instrumentos musicales con modelo balanceado",
91
+ version="4.0.0",
92
  lifespan=lifespan
93
  )
94
 
 
174
  logger.error(f"Error cargando audio: {e}")
175
  raise
176
 
177
+ def filter_musical_instruments(results):
178
+ """Filtrar solo instrumentos musicales de los resultados"""
179
+ # Palabras clave de instrumentos musicales en AudioSet
180
+ instrument_keywords = [
181
+ 'guitar', 'piano', 'drum', 'violin', 'flute', 'trumpet',
182
+ 'saxophone', 'bass', 'keyboard', 'harp', 'organ', 'cello',
183
+ 'clarinet', 'trombone', 'harmonica', 'accordion', 'banjo',
184
+ 'mandolin', 'ukulele', 'cymbal', 'tambourine', 'xylophone',
185
+ 'marimba', 'vibraphone', 'synthesizer', 'electric', 'acoustic'
186
+ ]
187
+
188
+ # Instrumentos específicos de AudioSet
189
+ musical_labels = [
190
+ 'Guitar', 'Electric guitar', 'Acoustic guitar', 'Bass guitar',
191
+ 'Piano', 'Electric piano', 'Keyboard (musical)',
192
+ 'Drum', 'Drum kit', 'Snare drum', 'Bass drum', 'Cymbal',
193
+ 'Violin, fiddle', 'Cello', 'Double bass',
194
+ 'Flute', 'Clarinet', 'Saxophone', 'Trumpet', 'Trombone',
195
+ 'Harmonica', 'Accordion', 'Organ', 'Harp',
196
+ 'Synthesizer', 'Musical instrument', 'Plucked string instrument',
197
+ 'Bowed string instrument', 'Wind instrument', 'Percussion'
198
+ ]
199
+
200
+ filtered_results = []
201
+
202
+ for result in results:
203
+ label = result['label']
204
+ confidence = float(result['score'])
205
+
206
+ # Verificar si es un instrumento musical
207
+ is_instrument = (
208
+ any(keyword.lower() in label.lower() for keyword in instrument_keywords) or
209
+ label in musical_labels or
210
+ confidence > 0.3 # Incluir resultados con alta confianza
211
+ )
212
+
213
+ if is_instrument and confidence > 0.05: # Umbral mínimo 5%
214
+ # Limpiar nombre del instrumento
215
+ clean_name = label.replace('Sound_', '').replace('_', ' ').title()
216
+
217
+ filtered_results.append({
218
+ "instrument": clean_name,
219
+ "confidence": round(confidence, 4),
220
+ "percentage": round(confidence * 100, 2),
221
+ "original_label": label
222
+ })
223
+
224
+ return filtered_results
225
+
226
  @app.get("/")
227
  async def root():
228
  return {
229
  "message": "Musical Instrument Detection API",
230
  "status": "online",
231
+ "version": "4.0.0",
232
+ "model": "MIT/ast-finetuned-audioset-10-10-0.4593",
233
+ "features": ["Modelo balanceado", "527 clases de AudioSet", "Menos sesgo hacia guitarra"],
234
  "endpoints": {
235
  "health": "/health",
236
  "detect": "/detect",
 
243
  return {
244
  "status": "online" if classifier is not None else "error",
245
  "model_loaded": classifier is not None,
246
+ "model_name": "MIT/ast-finetuned-audioset-10-10-0.4593",
247
+ "total_classes": 527,
248
+ "timestamp": datetime.now().isoformat()
 
249
  }
250
 
251
  @app.post("/detect")
252
  async def detect_instrument(audio: UploadFile = File(...)):
253
+ """Detectar instrumentos musicales con modelo balanceado"""
254
  start_time = datetime.now()
255
 
256
  try:
 
259
  raise HTTPException(status_code=503, detail="Modelo no disponible")
260
 
261
  logger.info(f"Procesando pista: {audio.filename}")
 
262
 
263
  # Leer contenido
264
  content = await audio.read()
265
  file_size_mb = len(content) / (1024 * 1024)
266
  logger.info(f"Tamaño: {file_size_mb:.2f}MB")
267
 
268
+ if file_size_mb > 15:
269
+ raise HTTPException(status_code=413, detail="Archivo demasiado grande")
270
 
271
+ # Procesar audio
272
  with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
273
  temp_file.write(content)
274
  temp_path = temp_file.name
 
283
  logger.info(f"Audio cargado: {duration:.2f}s, {sample_rate}Hz")
284
 
285
  if duration < 0.5:
286
+ raise HTTPException(status_code=400, detail="Audio demasiado corto")
287
 
288
+ # Para pistas largas, analizar segmento representativo
289
  if duration > 60:
 
290
  max_samples = 60 * sample_rate
291
  audio_data = audio_data[:max_samples]
292
+ logger.info("Analizando primeros 60 segundos")
293
 
294
  # Normalizar
295
  if np.max(np.abs(audio_data)) > 0:
296
  audio_data = audio_data / np.max(np.abs(audio_data))
297
 
298
+ logger.info("Clasificando con modelo MIT/AST...")
299
 
300
+ # Clasificar con modelo balanceado
301
  results = classifier(audio_data)
302
 
303
+ # Filtrar solo instrumentos musicales
304
+ instruments_detected = filter_musical_instruments(results)
 
 
 
 
 
 
 
 
305
 
306
  # Ordenar por confianza
307
  instruments_detected.sort(key=lambda x: x['confidence'], reverse=True)
 
310
 
311
  response = {
312
  "success": True,
313
+ "instruments_detected": instruments_detected[:8], # Top 8 instrumentos
314
  "total_instruments_found": len(instruments_detected),
315
+ "model_info": {
316
+ "name": "MIT/ast-finetuned-audioset",
317
+ "total_classes": 527,
318
+ "description": "Modelo balanceado entrenado en AudioSet"
319
+ },
320
  "audio_info": {
321
  "filename": audio.filename,
322
  "duration": round(duration, 2),
323
  "size_mb": round(file_size_mb, 2),
324
+ "sample_rate": sample_rate
 
325
  },
326
  "processing_time": round(processing_time, 3),
327
  "timestamp": datetime.now().isoformat()