yukee1992 commited on
Commit
a7a251d
Β·
verified Β·
1 Parent(s): 22ad173

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -30
app.py CHANGED
@@ -6,6 +6,7 @@ import shutil
6
  from datetime import datetime
7
  from typing import List, Optional
8
  from pathlib import Path
 
9
 
10
  import requests
11
  from fastapi import FastAPI, HTTPException, Form, UploadFile, File
@@ -14,16 +15,47 @@ from pydantic import BaseModel
14
  import torch
15
  import numpy as np
16
 
 
 
 
 
 
 
 
 
 
17
  # Configure environment
18
  os.makedirs("/tmp/voices", exist_ok=True)
19
  os.makedirs("/tmp/output", exist_ok=True)
20
 
21
- # Initialize FastAPI app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  app = FastAPI(
23
  title="TTS API",
24
  description="API for text-to-speech with Coqui TTS",
25
  docs_url="/",
26
- redoc_url=None
 
27
  )
28
 
29
  # Add CORS middleware
@@ -35,25 +67,9 @@ app.add_middleware(
35
  allow_headers=["*"],
36
  )
37
 
38
- # Configuration
39
- OCI_UPLOAD_API_URL = os.getenv("OCI_UPLOAD_API_URL", "").strip()
40
- if OCI_UPLOAD_API_URL:
41
- OCI_UPLOAD_API_URL = OCI_UPLOAD_API_URL.rstrip('/')
42
-
43
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
44
-
45
  print(f"βœ… Using device: {DEVICE}")
46
  print(f"πŸ”§ OCI Upload URL: {OCI_UPLOAD_API_URL or 'Not configured - uploads will be local only'}")
47
 
48
- # Global state
49
- tts = None
50
- model_loaded = False
51
- current_model = ""
52
- model_loading = False
53
- current_voice_style = "default_female"
54
- voice_cloning_supported = False
55
- app_startup_time = datetime.now()
56
-
57
  # Pydantic models
58
  class TTSRequest(BaseModel):
59
  text: str
@@ -345,6 +361,15 @@ def load_tts_model(voice_style="default_female"):
345
  model_loading = False
346
 
347
  # Health check endpoints - CRITICAL FOR DEPLOYMENT
 
 
 
 
 
 
 
 
 
348
  @app.get("/health")
349
  async def health_check():
350
  """Health check endpoint - must respond quickly"""
@@ -680,18 +705,6 @@ async def get_status():
680
  "uptime": str(datetime.now() - app_startup_time)
681
  }
682
 
683
- # Startup event - NO MODEL LOADING to avoid timeouts
684
- @app.on_event("startup")
685
- async def startup_event():
686
- """Startup event - no model loading to avoid timeouts"""
687
- print("=" * 50)
688
- print("πŸš€ TTS API Starting Up...")
689
- print(f"βœ… Device: {DEVICE}")
690
- print(f"πŸ”§ OCI Upload: {OCI_UPLOAD_API_URL or 'Local only'}")
691
- print("πŸ“ Models will load on first request (lazy loading)")
692
- print("⏰ Startup time:", app_startup_time.isoformat())
693
- print("=" * 50)
694
-
695
  if __name__ == "__main__":
696
  import uvicorn
697
  uvicorn.run(app, host="0.0.0.0", port=8000, access_log=False)
 
6
  from datetime import datetime
7
  from typing import List, Optional
8
  from pathlib import Path
9
+ from contextlib import asynccontextmanager
10
 
11
  import requests
12
  from fastapi import FastAPI, HTTPException, Form, UploadFile, File
 
15
  import torch
16
  import numpy as np
17
 
18
+ # Global state
19
+ tts = None
20
+ model_loaded = False
21
+ current_model = ""
22
+ model_loading = False
23
+ current_voice_style = "default_female"
24
+ voice_cloning_supported = False
25
+ app_startup_time = datetime.now()
26
+
27
  # Configure environment
28
  os.makedirs("/tmp/voices", exist_ok=True)
29
  os.makedirs("/tmp/output", exist_ok=True)
30
 
31
+ # Configuration
32
+ OCI_UPLOAD_API_URL = os.getenv("OCI_UPLOAD_API_URL", "").strip()
33
+ if OCI_UPLOAD_API_URL:
34
+ OCI_UPLOAD_API_URL = OCI_UPLOAD_API_URL.rstrip('/')
35
+
36
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
37
+
38
+ @asynccontextmanager
39
+ async def lifespan(app: FastAPI):
40
+ # Startup
41
+ print("=" * 50)
42
+ print("πŸš€ TTS API Starting Up...")
43
+ print(f"βœ… Device: {DEVICE}")
44
+ print(f"πŸ”§ OCI Upload: {OCI_UPLOAD_API_URL or 'Local only'}")
45
+ print("πŸ“ Models will load on first request (lazy loading)")
46
+ print("⏰ Startup time:", app_startup_time.isoformat())
47
+ print("=" * 50)
48
+ yield
49
+ # Shutdown
50
+ print("πŸ›‘ TTS API Shutting Down...")
51
+
52
+ # Initialize FastAPI app with lifespan
53
  app = FastAPI(
54
  title="TTS API",
55
  description="API for text-to-speech with Coqui TTS",
56
  docs_url="/",
57
+ redoc_url=None,
58
+ lifespan=lifespan
59
  )
60
 
61
  # Add CORS middleware
 
67
  allow_headers=["*"],
68
  )
69
 
 
 
 
 
 
 
 
70
  print(f"βœ… Using device: {DEVICE}")
71
  print(f"πŸ”§ OCI Upload URL: {OCI_UPLOAD_API_URL or 'Not configured - uploads will be local only'}")
72
 
 
 
 
 
 
 
 
 
 
73
  # Pydantic models
74
  class TTSRequest(BaseModel):
75
  text: str
 
361
  model_loading = False
362
 
363
  # Health check endpoints - CRITICAL FOR DEPLOYMENT
364
+ @app.get("/")
365
+ async def root():
366
+ """Root endpoint - redirect to docs"""
367
+ return {
368
+ "status": "running",
369
+ "service": "TTS API",
370
+ "message": "Visit /docs for API documentation"
371
+ }
372
+
373
  @app.get("/health")
374
  async def health_check():
375
  """Health check endpoint - must respond quickly"""
 
705
  "uptime": str(datetime.now() - app_startup_time)
706
  }
707
 
 
 
 
 
 
 
 
 
 
 
 
 
708
  if __name__ == "__main__":
709
  import uvicorn
710
  uvicorn.run(app, host="0.0.0.0", port=8000, access_log=False)