monishaaura commited on
Commit
0198f4d
Β·
verified Β·
1 Parent(s): af819b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -3
app.py CHANGED
@@ -22,6 +22,7 @@ logging.basicConfig(level=logging.INFO)
22
  logger = logging.getLogger(__name__)
23
 
24
  # Lifespan context manager for startup/shutdown
 
25
  @asynccontextmanager
26
  async def lifespan(app: FastAPI):
27
  """
@@ -30,8 +31,13 @@ async def lifespan(app: FastAPI):
30
  """
31
  # Startup: Load model
32
  logger.info("πŸš€ Starting up Wav2Vec2 Emotion Detection API...")
33
- load_model()
34
- logger.info("βœ… Startup complete - Model loaded!")
 
 
 
 
 
35
  yield
36
  # Shutdown: Cleanup (if needed)
37
  logger.info("πŸ›‘ Shutting down...")
@@ -44,6 +50,23 @@ app = FastAPI(
44
  lifespan=lifespan
45
  )
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  # Configure CORS - Allow requests from React frontend
48
  # For public API, allow all origins (common for ML APIs)
49
  # Using allow_origins=["*"] for maximum compatibility
@@ -79,9 +102,15 @@ def load_model():
79
  """
80
  Load the Wav2Vec2-Emotion model and processor from Hugging Face.
81
  This function is called once at startup to initialize the model.
 
82
  """
83
  global model, processor, feature_extractor
84
 
 
 
 
 
 
85
  try:
86
  logger.info("πŸ”„ Loading Wav2Vec2-Emotion model from Hugging Face...")
87
  logger.info("Model: superb/wav2vec2-base-superb-er")
@@ -117,7 +146,7 @@ def load_model():
117
  raise
118
 
119
  # Load the model
120
- logger.info("πŸ“¦ Loading model...")
121
  model = Wav2Vec2ForSequenceClassification.from_pretrained(model_name)
122
 
123
  # Set model to evaluation mode (not training)
@@ -129,6 +158,8 @@ def load_model():
129
  except Exception as e:
130
  logger.error(f"❌ Error loading model: {str(e)}")
131
  logger.error(f"πŸ“‹ Full error: {repr(e)}")
 
 
132
  raise
133
 
134
 
@@ -362,6 +393,20 @@ async def predict_emotion_endpoint(
362
  Returns:
363
  JSON response with emotion, confidence, and probability distribution
364
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  try:
366
  # Read uploaded audio file
367
  audio_bytes = await audio.read()
 
22
  logger = logging.getLogger(__name__)
23
 
24
  # Lifespan context manager for startup/shutdown
25
+ # Note: If lifespan fails, we'll use @app.on_event("startup") as fallback
26
  @asynccontextmanager
27
  async def lifespan(app: FastAPI):
28
  """
 
31
  """
32
  # Startup: Load model
33
  logger.info("πŸš€ Starting up Wav2Vec2 Emotion Detection API...")
34
+ try:
35
+ load_model()
36
+ logger.info("βœ… Startup complete - Model loaded!")
37
+ except Exception as e:
38
+ logger.error(f"❌ Model loading failed during startup: {e}")
39
+ logger.warning("⚠️ App will continue, but emotion detection may not work")
40
+ logger.warning("⚠️ Model will be loaded lazily on first request")
41
  yield
42
  # Shutdown: Cleanup (if needed)
43
  logger.info("πŸ›‘ Shutting down...")
 
50
  lifespan=lifespan
51
  )
52
 
53
+ # Fallback startup event (in case lifespan doesn't work)
54
+ @app.on_event("startup")
55
+ async def startup_event():
56
+ """
57
+ Fallback startup event if lifespan doesn't work.
58
+ This ensures model loading happens even if lifespan fails.
59
+ """
60
+ global model, processor, feature_extractor
61
+ if model is None:
62
+ logger.info("πŸ”„ Lifespan didn't load model, trying fallback startup...")
63
+ try:
64
+ load_model()
65
+ logger.info("βœ… Model loaded via fallback startup!")
66
+ except Exception as e:
67
+ logger.error(f"❌ Fallback model loading failed: {e}")
68
+ logger.warning("⚠️ Model will be loaded lazily on first request")
69
+
70
  # Configure CORS - Allow requests from React frontend
71
  # For public API, allow all origins (common for ML APIs)
72
  # Using allow_origins=["*"] for maximum compatibility
 
102
  """
103
  Load the Wav2Vec2-Emotion model and processor from Hugging Face.
104
  This function is called once at startup to initialize the model.
105
+ If called again (lazy loading), it will skip if already loaded.
106
  """
107
  global model, processor, feature_extractor
108
 
109
+ # Skip if already loaded
110
+ if model is not None:
111
+ logger.info("βœ… Model already loaded, skipping...")
112
+ return
113
+
114
  try:
115
  logger.info("πŸ”„ Loading Wav2Vec2-Emotion model from Hugging Face...")
116
  logger.info("Model: superb/wav2vec2-base-superb-er")
 
146
  raise
147
 
148
  # Load the model
149
+ logger.info("πŸ“¦ Loading model (this may take a minute)...")
150
  model = Wav2Vec2ForSequenceClassification.from_pretrained(model_name)
151
 
152
  # Set model to evaluation mode (not training)
 
158
  except Exception as e:
159
  logger.error(f"❌ Error loading model: {str(e)}")
160
  logger.error(f"πŸ“‹ Full error: {repr(e)}")
161
+ import traceback
162
+ logger.error(f"πŸ“‹ Traceback:\n{traceback.format_exc()}")
163
  raise
164
 
165
 
 
393
  Returns:
394
  JSON response with emotion, confidence, and probability distribution
395
  """
396
+ # Lazy loading: If model wasn't loaded at startup, load it now
397
+ global model, processor
398
+ if model is None or processor is None:
399
+ logger.warning("⚠️ Model not loaded, attempting lazy loading...")
400
+ try:
401
+ load_model()
402
+ logger.info("βœ… Model loaded successfully on first request!")
403
+ except Exception as e:
404
+ logger.error(f"❌ Failed to load model: {e}")
405
+ raise HTTPException(
406
+ status_code=503,
407
+ detail=f"Model not available. Please wait a moment and try again. Error: {str(e)}"
408
+ )
409
+
410
  try:
411
  # Read uploaded audio file
412
  audio_bytes = await audio.read()