juzer09 commited on
Commit
5ca546a
Β·
verified Β·
1 Parent(s): 46f51f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -8
app.py CHANGED
@@ -392,13 +392,23 @@ async def get_info():
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
@@ -406,15 +416,43 @@ def find_available_port(start_port: int = 8000, max_attempts: int = 10) -> int:
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}")
 
 
 
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
+ import random
396
+ import time
397
+
398
+ # Add some randomization to avoid race conditions
399
+ time.sleep(random.uniform(0.1, 0.5))
400
+
401
  for port in range(start_port, start_port + max_attempts):
402
  try:
403
+ # Try to bind to the port with proper error handling
404
  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
405
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
406
  s.bind(('0.0.0.0', port))
407
+ s.listen(1)
408
+ print(f"βœ… Port {port} is available")
409
  return port
410
+ except OSError as e:
411
+ print(f"❌ Port {port} is busy: {e}")
412
  continue
413
 
414
  # If no port found, raise an exception
 
416
 
417
  if __name__ == "__main__":
418
  try:
419
+ # Check if we're in a Hugging Face environment
420
+ is_hf_space = os.getenv('SPACE_ID') is not None
421
+
422
+ if is_hf_space:
423
+ print("πŸ€— Running in Hugging Face Spaces environment")
424
+ # Use a wider port range for HF Spaces
425
+ port = find_available_port(8000, 20)
426
+ else:
427
+ # Find an available port
428
+ port = find_available_port(8000, 10)
429
+
430
  print(f"πŸš€ Starting server on port {port}")
431
+
432
+ # Add retry logic for startup
433
+ max_retries = 3
434
+ for attempt in range(max_retries):
435
+ try:
436
+ uvicorn.run(app, host="0.0.0.0", port=port)
437
+ break # If successful, break out of retry loop
438
+ except OSError as e:
439
+ if "Address already in use" in str(e) and attempt < max_retries - 1:
440
+ print(f"⚠️ Port {port} became busy, trying next port...")
441
+ port = find_available_port(port + 1, 10)
442
+ print(f"πŸ”„ Retrying on port {port}")
443
+ else:
444
+ raise
445
+
446
  except RuntimeError as e:
447
  print(f"❌ {e}")
448
+ print("πŸ’‘ Suggestions:")
449
+ print(" 1. Wait a moment and try again (another instance might be shutting down)")
450
+ print(" 2. Manually specify a different port:")
451
+ print(" uvicorn app:app --host 0.0.0.0 --port 8001")
452
+ print(" 3. Check for running processes: ps aux | grep python")
453
  except KeyboardInterrupt:
454
  print("\nπŸ›‘ Server stopped by user")
455
  except Exception as e:
456
+ print(f"❌ Failed to start server: {e}")
457
+ import traceback
458
+ traceback.print_exc()