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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Script tự động set environment variables trên Hugging Face Spaces
|
| 4 |
+
Sử dụng Hugging Face Hub API
|
| 5 |
+
|
| 6 |
+
Cần:
|
| 7 |
+
- pip install huggingface_hub
|
| 8 |
+
- HF_TOKEN environment variable hoặc login trước
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import secrets
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from huggingface_hub import HfApi, login
|
| 16 |
+
|
| 17 |
+
# Space info
|
| 18 |
+
SPACE_ID = "davidtran999/hue-portal-backend"
|
| 19 |
+
|
| 20 |
+
# Generate secret key
|
| 21 |
+
DJANGO_SECRET_KEY = secrets.token_urlsafe(50)
|
| 22 |
+
|
| 23 |
+
# Environment variables cần set
|
| 24 |
+
# Lưu ý: DATABASE_URL sẽ được set thủ công với ngrok URL
|
| 25 |
+
ENV_VARS = {
|
| 26 |
+
"DJANGO_SECRET_KEY": DJANGO_SECRET_KEY,
|
| 27 |
+
"DJANGO_DEBUG": "false",
|
| 28 |
+
"DJANGO_ALLOWED_HOSTS": "*.hf.space,davidtran999-hue-portal-backend.hf.space,localhost,127.0.0.1",
|
| 29 |
+
"CORS_ALLOW_ALL_ORIGINS": "true",
|
| 30 |
+
"LLM_PROVIDER": "none",
|
| 31 |
+
# "DATABASE_URL": "postgres://hue:huepass@YOUR_NGROK_URL:PORT/hue_portal", # Uncomment và điền ngrok URL
|
| 32 |
+
# "REDIS_URL": "redis://YOUR_REDIS_NGROK_URL:PORT/0", # Nếu có Redis qua ngrok
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
def _get_token_from_cache():
|
| 36 |
+
"""Try to get token from Hugging Face cache file."""
|
| 37 |
+
try:
|
| 38 |
+
cache_file = Path.home() / ".cache" / "huggingface" / "token"
|
| 39 |
+
if cache_file.exists():
|
| 40 |
+
token = cache_file.read_text().strip()
|
| 41 |
+
if token:
|
| 42 |
+
return token
|
| 43 |
+
except Exception:
|
| 44 |
+
pass
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
print("=" * 60)
|
| 49 |
+
print("Hugging Face Spaces - Auto Set Environment Variables")
|
| 50 |
+
print("=" * 60)
|
| 51 |
+
|
| 52 |
+
# Check for HF token - try multiple sources
|
| 53 |
+
hf_token = (
|
| 54 |
+
os.environ.get("HF_TOKEN") or
|
| 55 |
+
os.environ.get("HUGGINGFACE_HUB_TOKEN") or
|
| 56 |
+
_get_token_from_cache()
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if not hf_token:
|
| 60 |
+
print("\n⚠️ Chưa có HF_TOKEN!")
|
| 61 |
+
print("Có 2 cách:")
|
| 62 |
+
print("1. Set environment variable: export HF_TOKEN=your_token")
|
| 63 |
+
print("2. Login: huggingface-cli login")
|
| 64 |
+
print("\nHoặc chạy script thủ công: python3 set_env_vars.py")
|
| 65 |
+
return
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
# Login
|
| 69 |
+
login(token=hf_token)
|
| 70 |
+
api = HfApi()
|
| 71 |
+
|
| 72 |
+
print(f"\n✅ Đã login vào Hugging Face")
|
| 73 |
+
print(f"Space: {SPACE_ID}")
|
| 74 |
+
|
| 75 |
+
# Delete existing variables/secrets with same names to avoid collision
|
| 76 |
+
print(f"\n🗑️ Xóa các biến cũ để tránh collision...")
|
| 77 |
+
for key in ENV_VARS.keys():
|
| 78 |
+
try:
|
| 79 |
+
# Try to delete as variable first
|
| 80 |
+
api.delete_space_variable(repo_id=SPACE_ID, key=key)
|
| 81 |
+
print(f" ✅ Deleted variable: {key}")
|
| 82 |
+
except Exception as e:
|
| 83 |
+
# Variable không tồn tại, tiếp tục
|
| 84 |
+
pass
|
| 85 |
+
try:
|
| 86 |
+
# Try to delete as secret
|
| 87 |
+
api.delete_space_secret(repo_id=SPACE_ID, key=key)
|
| 88 |
+
print(f" ✅ Deleted secret: {key}")
|
| 89 |
+
except Exception as e:
|
| 90 |
+
# Secret không tồn tại, tiếp tục
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
print(f"\nĐang set các biến môi trường mới...")
|
| 94 |
+
|
| 95 |
+
# Set secrets (environment variables) - chỉ dùng secrets để tránh collision
|
| 96 |
+
for key, value in ENV_VARS.items():
|
| 97 |
+
try:
|
| 98 |
+
# Hugging Face Spaces: tất cả đều set as secret (bảo mật hơn)
|
| 99 |
+
api.add_space_secret(
|
| 100 |
+
repo_id=SPACE_ID,
|
| 101 |
+
key=key,
|
| 102 |
+
value=value
|
| 103 |
+
)
|
| 104 |
+
if key == "DJANGO_SECRET_KEY":
|
| 105 |
+
print(f" ✅ Set secret: {key} = {value[:20]}...")
|
| 106 |
+
else:
|
| 107 |
+
print(f" ✅ Set secret: {key} = {value}")
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f" ⚠️ Lỗi khi set {key}: {e}")
|
| 110 |
+
# Fallback: hướng dẫn thủ công
|
| 111 |
+
print(f" → Set thủ công: {key} = {value}")
|
| 112 |
+
|
| 113 |
+
print("\n" + "=" * 60)
|
| 114 |
+
print("✅ Hoàn tất! Space sẽ tự động rebuild")
|
| 115 |
+
print("=" * 60)
|
| 116 |
+
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"\n❌ Lỗi: {e}")
|
| 119 |
+
print("\nCó thể Hugging Face API không hỗ trợ set env vars tự động.")
|
| 120 |
+
print("Vui lòng chạy: python3 set_env_vars.py để xem hướng dẫn thủ công")
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
main()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
Script tự động set environment variables trên Hugging Face Spaces
|
| 127 |
+
Sử dụng Hugging Face Hub API
|
| 128 |
+
|
| 129 |
+
Cần:
|
| 130 |
+
- pip install huggingface_hub
|
| 131 |
+
- HF_TOKEN environment variable hoặc login trước
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
import os
|
| 135 |
+
import sys
|
| 136 |
+
import secrets
|
| 137 |
+
from pathlib import Path
|
| 138 |
+
from huggingface_hub import HfApi, login
|
| 139 |
+
|
| 140 |
+
# Space info
|
| 141 |
+
SPACE_ID = "davidtran999/hue-portal-backend"
|
| 142 |
+
|
| 143 |
+
# Generate secret key
|
| 144 |
+
DJANGO_SECRET_KEY = secrets.token_urlsafe(50)
|
| 145 |
+
|
| 146 |
+
# Environment variables cần set
|
| 147 |
+
# Lưu ý: DATABASE_URL sẽ được set thủ công với ngrok URL
|
| 148 |
+
ENV_VARS = {
|
| 149 |
+
"DJANGO_SECRET_KEY": DJANGO_SECRET_KEY,
|
| 150 |
+
"DJANGO_DEBUG": "false",
|
| 151 |
+
"DJANGO_ALLOWED_HOSTS": "*.hf.space,davidtran999-hue-portal-backend.hf.space,localhost,127.0.0.1",
|
| 152 |
+
"CORS_ALLOW_ALL_ORIGINS": "true",
|
| 153 |
+
"LLM_PROVIDER": "none",
|
| 154 |
+
# "DATABASE_URL": "postgres://hue:huepass@YOUR_NGROK_URL:PORT/hue_portal", # Uncomment và điền ngrok URL
|
| 155 |
+
# "REDIS_URL": "redis://YOUR_REDIS_NGROK_URL:PORT/0", # Nếu có Redis qua ngrok
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
def _get_token_from_cache():
|
| 159 |
+
"""Try to get token from Hugging Face cache file."""
|
| 160 |
+
try:
|
| 161 |
+
cache_file = Path.home() / ".cache" / "huggingface" / "token"
|
| 162 |
+
if cache_file.exists():
|
| 163 |
+
token = cache_file.read_text().strip()
|
| 164 |
+
if token:
|
| 165 |
+
return token
|
| 166 |
+
except Exception:
|
| 167 |
+
pass
|
| 168 |
+
return None
|
| 169 |
+
|
| 170 |
+
def main():
|
| 171 |
+
print("=" * 60)
|
| 172 |
+
print("Hugging Face Spaces - Auto Set Environment Variables")
|
| 173 |
+
print("=" * 60)
|
| 174 |
+
|
| 175 |
+
# Check for HF token - try multiple sources
|
| 176 |
+
hf_token = (
|
| 177 |
+
os.environ.get("HF_TOKEN") or
|
| 178 |
+
os.environ.get("HUGGINGFACE_HUB_TOKEN") or
|
| 179 |
+
_get_token_from_cache()
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if not hf_token:
|
| 183 |
+
print("\n⚠️ Chưa có HF_TOKEN!")
|
| 184 |
+
print("Có 2 cách:")
|
| 185 |
+
print("1. Set environment variable: export HF_TOKEN=your_token")
|
| 186 |
+
print("2. Login: huggingface-cli login")
|
| 187 |
+
print("\nHoặc chạy script thủ công: python3 set_env_vars.py")
|
| 188 |
+
return
|
| 189 |
+
|
| 190 |
+
try:
|
| 191 |
+
# Login
|
| 192 |
+
login(token=hf_token)
|
| 193 |
+
api = HfApi()
|
| 194 |
+
|
| 195 |
+
print(f"\n✅ Đã login vào Hugging Face")
|
| 196 |
+
print(f"Space: {SPACE_ID}")
|
| 197 |
+
|
| 198 |
+
# Delete existing variables/secrets with same names to avoid collision
|
| 199 |
+
print(f"\n🗑️ Xóa các biến cũ để tránh collision...")
|
| 200 |
+
for key in ENV_VARS.keys():
|
| 201 |
+
try:
|
| 202 |
+
# Try to delete as variable first
|
| 203 |
+
api.delete_space_variable(repo_id=SPACE_ID, key=key)
|
| 204 |
+
print(f" ✅ Deleted variable: {key}")
|
| 205 |
+
except Exception as e:
|
| 206 |
+
# Variable không tồn tại, tiếp tục
|
| 207 |
+
pass
|
| 208 |
+
try:
|
| 209 |
+
# Try to delete as secret
|
| 210 |
+
api.delete_space_secret(repo_id=SPACE_ID, key=key)
|
| 211 |
+
print(f" ✅ Deleted secret: {key}")
|
| 212 |
+
except Exception as e:
|
| 213 |
+
# Secret không tồn tại, tiếp tục
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
print(f"\nĐang set các biến môi trường mới...")
|
| 217 |
+
|
| 218 |
+
# Set secrets (environment variables) - chỉ dùng secrets để tránh collision
|
| 219 |
+
for key, value in ENV_VARS.items():
|
| 220 |
+
try:
|
| 221 |
+
# Hugging Face Spaces: tất cả đều set as secret (bảo mật hơn)
|
| 222 |
+
api.add_space_secret(
|
| 223 |
+
repo_id=SPACE_ID,
|
| 224 |
+
key=key,
|
| 225 |
+
value=value
|
| 226 |
+
)
|
| 227 |
+
if key == "DJANGO_SECRET_KEY":
|
| 228 |
+
print(f" ✅ Set secret: {key} = {value[:20]}...")
|
| 229 |
+
else:
|
| 230 |
+
print(f" ✅ Set secret: {key} = {value}")
|
| 231 |
+
except Exception as e:
|
| 232 |
+
print(f" ⚠️ Lỗi khi set {key}: {e}")
|
| 233 |
+
# Fallback: hướng dẫn thủ công
|
| 234 |
+
print(f" → Set thủ công: {key} = {value}")
|
| 235 |
+
|
| 236 |
+
print("\n" + "=" * 60)
|
| 237 |
+
print("✅ Hoàn tất! Space sẽ tự động rebuild")
|
| 238 |
+
print("=" * 60)
|
| 239 |
+
|
| 240 |
+
except Exception as e:
|
| 241 |
+
print(f"\n❌ Lỗi: {e}")
|
| 242 |
+
print("\nCó thể Hugging Face API không hỗ trợ set env vars tự động.")
|
| 243 |
+
print("Vui lòng chạy: python3 set_env_vars.py để xem hướng dẫn thủ công")
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
main()
|