Spaces:
Running
Running
Commit ·
dd6dcad
0
Parent(s):
feat: Migrate Speech Emotion Recognition to a dedicated Hugging Face Space and update client-side integration.
Browse filesFiles changed (3)
- DockerfileAdded+24
- app/main.pyAdded+91
- requirements.txtAdded+6
123456789101112131415161718192021222324FROM python:3.9-slim
WORKDIR /app
# Instalar dependencias del sistema necesarias para audio y FunASRRUN apt-get update && apt-get install -y \ libsndfile1 \ ffmpeg \ && rm -rf /var/lib/apt/lists/*
# Instalar dependencias PythonCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copiar el código de la appCOPY app /app
# Removed build-time model caching to avoid OOM. Model will download on first boot.
# Exponer el puerto de Hugging Face SpacesEXPOSE 7860
# Comando para iniciar fastapiCMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091from fastapi import FastAPI, UploadFile, File, HTTPExceptionimport shutilimport osfrom funasr import AutoModelimport uvicorn
app = FastAPI(title="AInterviewer SER Model", version="emotion2vec_plus_large_interino")
# Cargar modelo en memoria al inicioprint("Cargando modelo emotion2vec_plus_large...")try: model = AutoModel(model="iic/emotion2vec_plus_large") print("Modelo cargado exitosamente.")except Exception as e: print(f"Error cargando modelo: {e}") model = None
# Mapeo de 9 clases a 4 clasesEMOTION_MAP = { "happy": "happy", "sad": "sad", "angry": "angry", "disgusted": "angry", "neutral": "neutral", "other": "neutral", "unknown": "neutral", "fearful": "neutral", # o descartar "surprised": "neutral" # o descartar}
@app.get("/health")def healthcheck(): return {"status": "ok", "model_loaded": model is not None}
@app.get("/version")def version(): return {"version": "emotion2vec_plus_large_interino"}
@app.post("/analyze")async def analyze_audio(file: UploadFile = File(...)): if not model: raise HTTPException(status_code=503, detail="Model unvailable")
temp_path = f"/tmp/{file.filename}" try: with open(temp_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer)
# Inferencia result = model.generate(temp_path, granularity="utterance", extract_embedding=False) # Result es una lista de dicts. Tomamos el primer elemento. # Format ej: [{'labels': ['happy', 'neutral'], 'scores': [0.8, 0.2]}] if not result or not isinstance(result, list): raise ValueError("Unexpected model output format") res_data = result[0] labels = res_data.get("labels", []) scores = res_data.get("scores", []) # Sumar scores para nuestras 4 clases mapped_scores = {"happy": 0.0, "sad": 0.0, "angry": 0.0, "neutral": 0.0} for label, score in zip(labels, scores): target_class = EMOTION_MAP.get(label, "neutral") mapped_scores[target_class] += float(score) # Normalizar si no suma 1 por el descarte total = sum(mapped_scores.values()) if total > 0: for k in mapped_scores: mapped_scores[k] = round(mapped_scores[k] / total, 4) dominant = max(mapped_scores.items(), key=lambda x: x[1])[0]
return { "dominant": dominant, "distribution": mapped_scores, "model": "emotion2vec_plus_large_interino", "raw_labels": labels, # útil para debug "raw_scores": [round(float(s), 4) for s in scores] }
except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if os.path.exists(temp_path): os.remove(temp_path)
if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=7860)123456fastapiuvicornpython-multipartfunasrmodelscopetorchaudioDockerfileAdded+24
app/main.pyAdded+91
requirements.txtAdded+6