Transeption_iGEM_BASISCHINA_2025 / keep_alive_external.py
MoraxCheng's picture
Add external keep-alive script for Tranception Space and update settings
86d5c5f
#!/usr/bin/env python3
"""
External Keep-Alive for Tranception Space
This script runs on your local machine to keep the Space active
"""
import requests
import time
from datetime import datetime
import sys
# Space configuration
SPACE_EMBED_URL = "https://moraxcheng-transeption-igem-basischina-2025.hf.space"
GRADIO_API_URL = f"{SPACE_EMBED_URL}/run/predict"
# Keep-alive settings
PING_INTERVAL = 240 # 4 minutes
WAKE_UP_RETRIES = 3
def simple_ping():
"""Simple HTTP GET to keep connection alive"""
try:
response = requests.get(SPACE_EMBED_URL, timeout=30)
return response.status_code == 200
except:
return False
def gradio_keep_alive():
"""Send minimal Gradio API request"""
try:
# Minimal prediction request
payload = {
"data": [
"MSKGE", # 5 amino acids
1, # start
3, # end
"Small", # smallest model
False, # no mirror
1 # batch size 1
]
}
# First, initiate the prediction
response = requests.post(
GRADIO_API_URL,
json=payload,
timeout=60
)
if response.status_code == 200:
return True
except Exception as e:
print(f"API request error: {e}")
return False
def keep_alive_loop():
"""Main keep-alive loop"""
print("="*60)
print("Tranception Space Keep-Alive")
print(f"Space: {SPACE_EMBED_URL}")
print(f"Ping interval: {PING_INTERVAL} seconds")
print("Press Ctrl+C to stop")
print("="*60)
print()
consecutive_failures = 0
while True:
try:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Try simple ping first
print(f"[{timestamp}] Pinging Space...", end=" ", flush=True)
if simple_ping():
print("βœ“ Online")
consecutive_failures = 0
else:
print("βœ— No response")
consecutive_failures += 1
# Try Gradio API as fallback
print(f"[{timestamp}] Trying Gradio API...", end=" ", flush=True)
if gradio_keep_alive():
print("βœ“ Success")
consecutive_failures = 0
else:
print("βœ— Failed")
if consecutive_failures >= 3:
print("\n⚠️ WARNING: Space appears to be down!")
print("You may need to manually restart it at:")
print(f"https://huggingface.co/spaces/MoraxCheng/Transeption_iGEM_BASISCHINA_2025/settings\n")
# Wait for next ping
print(f"Next ping in {PING_INTERVAL} seconds...\n")
time.sleep(PING_INTERVAL)
except KeyboardInterrupt:
print("\n\nKeep-alive stopped by user")
break
except Exception as e:
print(f"\nUnexpected error: {e}")
print("Continuing...\n")
time.sleep(60)
if __name__ == "__main__":
# Test connection
print("Testing connection...")
if simple_ping():
print("βœ“ Space is online\n")
else:
print("⚠ Space appears to be offline")
print("Starting keep-alive anyway...\n")
# Start keep-alive
keep_alive_loop()