juzer09 commited on
Commit
46f51f6
Β·
verified Β·
1 Parent(s): 8de9501

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -20
app.py CHANGED
@@ -17,22 +17,45 @@ import time
17
  from typing import Optional, Annotated, List
18
  import uvicorn
19
  import asyncio
 
 
20
 
21
- # Initialize FastAPI app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  app = FastAPI(
23
  title="Madverse Music API",
24
  description="AI-powered music detection API to identify AI-generated vs human-created music",
25
  version="1.0.0",
26
  docs_url="/",
27
- redoc_url="/docs"
 
28
  )
29
 
30
  # API Key Configuration
31
  API_KEY = os.getenv("MADVERSE_API_KEY", "madverse-music-api-key-2024") # Default key for demo
32
 
33
- # Global model variable
34
- model = None
35
-
36
  async def verify_api_key(x_api_key: Annotated[str | None, Header()] = None):
37
  """Verify API key from header"""
38
  if x_api_key is None:
@@ -90,20 +113,6 @@ class ErrorResponse(BaseModel):
90
  error: str
91
  message: str
92
 
93
- @app.on_event("startup")
94
- async def load_model():
95
- """Load the AI model on startup"""
96
- global model
97
- try:
98
- from sonics import HFAudioClassifier
99
- print("πŸ”„ Loading Madverse Music AI model...")
100
- model = HFAudioClassifier.from_pretrained("awsaf49/sonics-spectttra-alpha-120s")
101
- model.eval()
102
- print("βœ… Model loaded successfully!")
103
- except Exception as e:
104
- print(f"❌ Failed to load model: {e}")
105
- raise
106
-
107
  def cleanup_file(file_path: str):
108
  """Background task to cleanup temporary files"""
109
  try:
@@ -381,5 +390,31 @@ async def get_info():
381
  }
382
  }
383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  if __name__ == "__main__":
385
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  from typing import Optional, Annotated, List
18
  import uvicorn
19
  import asyncio
20
+ from contextlib import asynccontextmanager
21
+ import socket
22
 
23
+ # Global model variable
24
+ model = None
25
+
26
+ @asynccontextmanager
27
+ async def lifespan(app: FastAPI):
28
+ """Application lifespan management"""
29
+ # Startup
30
+ global model
31
+ try:
32
+ from sonics import HFAudioClassifier
33
+ print("πŸ”„ Loading Madverse Music AI model...")
34
+ model = HFAudioClassifier.from_pretrained("awsaf49/sonics-spectttra-alpha-120s")
35
+ model.eval()
36
+ print("βœ… Model loaded successfully!")
37
+ except Exception as e:
38
+ print(f"❌ Failed to load model: {e}")
39
+ raise
40
+
41
+ yield
42
+
43
+ # Shutdown
44
+ print("πŸ”„ Shutting down...")
45
+
46
+ # Initialize FastAPI app with lifespan
47
  app = FastAPI(
48
  title="Madverse Music API",
49
  description="AI-powered music detection API to identify AI-generated vs human-created music",
50
  version="1.0.0",
51
  docs_url="/",
52
+ redoc_url="/docs",
53
+ lifespan=lifespan
54
  )
55
 
56
  # API Key Configuration
57
  API_KEY = os.getenv("MADVERSE_API_KEY", "madverse-music-api-key-2024") # Default key for demo
58
 
 
 
 
59
  async def verify_api_key(x_api_key: Annotated[str | None, Header()] = None):
60
  """Verify API key from header"""
61
  if x_api_key is None:
 
113
  error: str
114
  message: str
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  def cleanup_file(file_path: str):
117
  """Background task to cleanup temporary files"""
118
  try:
 
390
  }
391
  }
392
 
393
+ def find_available_port(start_port: int = 8000, max_attempts: int = 10) -> int:
394
+ """Find an available port starting from start_port"""
395
+ for port in range(start_port, start_port + max_attempts):
396
+ try:
397
+ # Try to bind to the port
398
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
399
+ s.bind(('0.0.0.0', port))
400
+ return port
401
+ except OSError:
402
+ continue
403
+
404
+ # If no port found, raise an exception
405
+ raise RuntimeError(f"No available port found in range {start_port}-{start_port + max_attempts - 1}")
406
+
407
  if __name__ == "__main__":
408
+ try:
409
+ # Find an available port
410
+ port = find_available_port(8000)
411
+ print(f"πŸš€ Starting server on port {port}")
412
+ uvicorn.run(app, host="0.0.0.0", port=port)
413
+ except RuntimeError as e:
414
+ print(f"❌ {e}")
415
+ print("πŸ’‘ You can also manually specify a different port by running:")
416
+ print(" uvicorn app:app --host 0.0.0.0 --port YOUR_PORT_NUMBER")
417
+ except KeyboardInterrupt:
418
+ print("\nπŸ›‘ Server stopped by user")
419
+ except Exception as e:
420
+ print(f"❌ Failed to start server: {e}")