petter2025 commited on
Commit
a9c9738
·
verified ·
1 Parent(s): 6d51141

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -5
app.py CHANGED
@@ -51,15 +51,25 @@ def log_memory_usage():
51
  threading.Timer(60, log_memory_usage).start()
52
 
53
  # ----------------------------------------------------------------------
54
- # Keep‑alive to prevent idle timeout (runs every 10 minutes)
55
  # ----------------------------------------------------------------------
56
  def keep_alive():
57
- """Periodically ping the app to avoid idle timeout."""
58
- url = "http://127.0.0.1:7860/"
 
 
 
 
 
 
 
 
 
 
59
  while True:
60
- time.sleep(600) # 10 minutes
61
  try:
62
- with urllib.request.urlopen(url, timeout=5) as response:
63
  status = response.getcode()
64
  logging.info(f"Keep‑alive ping: {status}")
65
  except Exception as e:
 
51
  threading.Timer(60, log_memory_usage).start()
52
 
53
  # ----------------------------------------------------------------------
54
+ # Keep‑alive to prevent idle timeout (external pings)
55
  # ----------------------------------------------------------------------
56
  def keep_alive():
57
+ """Periodically ping the public Space URL to prevent idle timeout."""
58
+ # Determine the public URL of the Space
59
+ space_id = os.environ.get('SPACE_ID')
60
+ if space_id:
61
+ # Convert "username/space-name" to "username-space-name.hf.space"
62
+ url = f"https://{space_id.replace('/', '-')}.hf.space/"
63
+ logging.info(f"Using external URL for keep‑alive: {url}")
64
+ else:
65
+ # Fallback to localhost when running locally
66
+ url = "http://127.0.0.1:7860/"
67
+ logging.warning("No SPACE_ID found, using localhost for keep‑alive – will not prevent sleep!")
68
+
69
  while True:
70
+ time.sleep(300) # 5 minutes
71
  try:
72
+ with urllib.request.urlopen(url, timeout=10) as response:
73
  status = response.getcode()
74
  logging.info(f"Keep‑alive ping: {status}")
75
  except Exception as e: