File size: 4,167 Bytes
cdc337a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | """
Hugging Face Spaces Keepalive Script
定期访问 HF Spaces 防止休眠
"""
import os
import sys
import time
from pathlib import Path
try:
import requests
except ImportError:
print("Error: requests library not found. Installing...")
os.system(f"{sys.executable} -m pip install requests")
import requests
def load_spaces_from_file():
"""从 spaces.txt 文件加载 Space URL 列表"""
spaces_file = Path(__file__).parent / "spaces.txt"
if not spaces_file.exists():
return []
spaces = []
with open(spaces_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
spaces.append(line)
return spaces
def load_spaces_from_env():
"""从环境变量加载 Space URL 列表"""
spaces_str = os.getenv('HF_SPACES', '')
if not spaces_str:
return []
return [s.strip() for s in spaces_str.split(',') if s.strip()]
def ping_space(url, token=None, timeout=30):
"""
访问 Space URL 进行保活
Args:
url: Space URL
token: HF Token(私有 Space 需要)
timeout: 超时时间(秒)
Returns:
bool: 是否成功
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
if token:
headers['Authorization'] = f'Bearer {token}'
try:
print(f"Pinging {url}...")
response = requests.get(url, headers=headers, timeout=timeout, allow_redirects=True)
if response.status_code == 200:
print(f"✅ Success: {url} (Status: {response.status_code})")
return True
elif response.status_code in [301, 302, 307, 308]:
print(f"✅ Success (Redirect): {url} (Status: {response.status_code})")
return True
else:
print(f"⚠️ Warning: {url} (Status: {response.status_code})")
return False
except requests.Timeout:
print(f"❌ Timeout: {url}")
return False
except requests.RequestException as e:
print(f"❌ Error: {url} - {str(e)}")
return False
def main():
"""主函数"""
print("=" * 60)
print("Hugging Face Spaces Keepalive")
print("=" * 60)
print()
# 获取 HF Token(可选)
hf_token = os.getenv('HF_TOKEN')
if hf_token:
print(f"HF Token: {'*' * 8}{hf_token[-4:]}")
else:
print("HF Token: Not configured (public spaces only)")
print()
# 加载 Space URL 列表
spaces = load_spaces_from_env()
if not spaces:
spaces = load_spaces_from_file()
if not spaces:
print("❌ Error: No spaces configured!")
print()
print("Please configure spaces using one of these methods:")
print("1. Set HF_SPACES environment variable (comma-separated URLs)")
print("2. Create spaces.txt file with one URL per line")
sys.exit(1)
print(f"Found {len(spaces)} space(s) to ping:")
for i, space in enumerate(spaces, 1):
print(f" {i}. {space}")
print()
# 访问所有 Space
results = []
for space in spaces:
success = ping_space(space, token=hf_token)
results.append((space, success))
# 避免请求过快
if space != spaces[-1]:
time.sleep(2)
# 统计结果
print()
print("=" * 60)
print("Summary")
print("=" * 60)
success_count = sum(1 for _, success in results if success)
total_count = len(results)
print(f"Total: {total_count}")
print(f"Success: {success_count}")
print(f"Failed: {total_count - success_count}")
# 详细结果
if total_count - success_count > 0:
print()
print("Failed spaces:")
for space, success in results:
if not success:
print(f" - {space}")
print()
print("=" * 60)
# 如果有失败的,返回非零退出码
if success_count < total_count:
sys.exit(1)
if __name__ == "__main__":
main()
|