davidtran999 commited on
Commit
b788be0
·
verified ·
1 Parent(s): 710de5c

Upload backend/hue_portal/hue-portal-backendDocker/fix_space_collision.py with huggingface_hub

Browse files
backend/hue_portal/hue-portal-backendDocker/fix_space_collision.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Script để fix lỗi "Collision on variables and secrets names" trên HF Space.
4
+ Xóa tất cả variables và secrets có thể gây xung đột, sau đó set lại đúng cách.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from huggingface_hub import HfApi, login
13
+
14
+
15
+ REPO_ROOT = Path(__file__).resolve().parents[1]
16
+ OPS_DIR = REPO_ROOT / "ops"
17
+ TUNNEL_ENV = OPS_DIR / ".env.tunnel"
18
+ DEFAULT_SPACE_ID = "davidtran999/hue-portal-backend"
19
+
20
+ # Danh sách các key có thể gây xung đột
21
+ COLLISION_KEYS = [
22
+ "DATABASE_URL",
23
+ "POSTGRES_HOST",
24
+ "POSTGRES_PORT",
25
+ "POSTGRES_USER",
26
+ "POSTGRES_PASSWORD",
27
+ "POSTGRES_DB",
28
+ ]
29
+
30
+
31
+ def _load_env_file(path: Path) -> dict[str, str]:
32
+ """Load KEY=VALUE pairs from a dotenv-style file."""
33
+ data: dict[str, str] = {}
34
+ if not path.exists():
35
+ return data
36
+ for raw_line in path.read_text(encoding="utf-8").splitlines():
37
+ line = raw_line.strip()
38
+ if not line or line.startswith("#") or "=" not in line:
39
+ continue
40
+ key, value = line.split("=", 1)
41
+ data[key.strip()] = value.strip().strip('"').strip("'")
42
+ return data
43
+
44
+
45
+ def get_hf_token() -> str | None:
46
+ """Resolve Hugging Face token from env or cache file."""
47
+ import os
48
+
49
+ if os.environ.get("HF_TOKEN"):
50
+ return os.environ["HF_TOKEN"].strip()
51
+ cache_file = Path.home() / ".cache" / "huggingface" / "token"
52
+ if cache_file.exists():
53
+ return cache_file.read_text(encoding="utf-8").strip()
54
+ return None
55
+
56
+
57
+ def cleanup_collisions(api: HfApi, space_id: str) -> None:
58
+ """Xóa tất cả variables và secrets có thể gây xung đột."""
59
+ print(f"🧹 Đang dọn dẹp collisions cho Space: {space_id}")
60
+
61
+ # Thử xóa nhiều lần để đảm bảo
62
+ for attempt in range(2):
63
+ if attempt > 0:
64
+ print(f"\n🔄 Lần thử thứ {attempt + 1}...")
65
+
66
+ for key in COLLISION_KEYS:
67
+ # Xóa variable (thử nhiều lần)
68
+ for _ in range(2):
69
+ try:
70
+ api.delete_space_variable(repo_id=space_id, key=key)
71
+ print(f" ✅ Đã xóa variable: {key}")
72
+ break
73
+ except Exception as e:
74
+ if "not found" in str(e).lower() or "404" in str(e):
75
+ # Không tồn tại, không cần xóa
76
+ break
77
+ print(f" ⚠️ Lỗi khi xóa variable {key}: {e}")
78
+
79
+ # Xóa secret (thử nhiều lần)
80
+ for _ in range(2):
81
+ try:
82
+ api.delete_space_secret(repo_id=space_id, key=key)
83
+ print(f" ✅ Đã xóa secret: {key}")
84
+ break
85
+ except Exception as e:
86
+ if "not found" in str(e).lower() or "404" in str(e):
87
+ # Không tồn tại, không cần xóa
88
+ break
89
+ print(f" ⚠️ Lỗi khi xóa secret {key}: {e}")
90
+
91
+ print("\n✅ Hoàn tất dọn dẹp collisions")
92
+
93
+
94
+ def set_database_config(api: HfApi, space_id: str, config: dict[str, str]) -> None:
95
+ """Set lại DATABASE_URL và POSTGRES_* đúng cách."""
96
+ host = config.get("PG_TUNNEL_HOST") or config.get("POSTGRES_HOST", "localhost")
97
+ port = config.get("PG_TUNNEL_PORT") or config.get("POSTGRES_PORT", "5543")
98
+ database = config.get("PG_TUNNEL_DB") or config.get("POSTGRES_DB", "hue_portal")
99
+ user = config.get("PG_TUNNEL_USER") or config.get("POSTGRES_USER", "hue")
100
+ password = config.get("PG_TUNNEL_PASSWORD") or config.get("POSTGRES_PASSWORD", "")
101
+
102
+ database_url = f"postgres://{user}:{password}@{host}:{port}/{database}"
103
+
104
+ print(f"📝 Đang set lại database config...")
105
+
106
+ # Set POSTGRES_* as variables (không nhạy cảm)
107
+ api.add_space_variable(repo_id=space_id, key="POSTGRES_HOST", value=host)
108
+ api.add_space_variable(repo_id=space_id, key="POSTGRES_PORT", value=str(port))
109
+ api.add_space_variable(repo_id=space_id, key="POSTGRES_DB", value=database)
110
+ api.add_space_variable(repo_id=space_id, key="POSTGRES_USER", value=user)
111
+ print(" ✅ Đã set POSTGRES_* variables")
112
+
113
+ # Set passwords và DATABASE_URL as secrets (nhạy cảm)
114
+ api.add_space_secret(repo_id=space_id, key="POSTGRES_PASSWORD", value=password)
115
+ api.add_space_secret(repo_id=space_id, key="DATABASE_URL", value=database_url)
116
+ print(" ✅ Đã set POSTGRES_PASSWORD + DATABASE_URL secrets")
117
+
118
+ print(f"✅ Hoàn tất set database config")
119
+
120
+
121
+ def main() -> None:
122
+ import argparse
123
+
124
+ parser = argparse.ArgumentParser(description="Fix collision errors trên HF Space")
125
+ parser.add_argument(
126
+ "--space-id",
127
+ default=None,
128
+ help="ID của Space. Mặc định: davidtran999/hue-portal-backend",
129
+ )
130
+ parser.add_argument(
131
+ "--skip-cleanup",
132
+ action="store_true",
133
+ help="Bỏ qua bước cleanup (chỉ set lại config)",
134
+ )
135
+ args = parser.parse_args()
136
+
137
+ space_id = args.space_id or DEFAULT_SPACE_ID
138
+
139
+ # Load config từ tunnel env
140
+ config = _load_env_file(TUNNEL_ENV)
141
+ if not config:
142
+ print(f"⚠️ Không tìm thấy {TUNNEL_ENV}, sử dụng giá trị mặc định")
143
+
144
+ # Get HF token
145
+ hf_token = get_hf_token()
146
+ if not hf_token:
147
+ print("❌ Không tìm thấy HF token. Chạy `huggingface-cli login` hoặc set HF_TOKEN.")
148
+ sys.exit(1)
149
+
150
+ login(token=hf_token)
151
+ api = HfApi()
152
+
153
+ print("=" * 60)
154
+ print(f"Fix Collision cho Space: {space_id}")
155
+ print("=" * 60)
156
+
157
+ # Cleanup collisions
158
+ if not args.skip_cleanup:
159
+ cleanup_collisions(api, space_id)
160
+ print()
161
+
162
+ # Set lại config đúng cách
163
+ set_database_config(api, space_id, config)
164
+
165
+ print()
166
+ print("=" * 60)
167
+ print("✅ Hoàn tất! Space sẽ tự động restart.")
168
+ print(f" Kiểm tra tại: https://huggingface.co/spaces/{space_id}")
169
+ print("=" * 60)
170
+
171
+
172
+ if __name__ == "__main__":
173
+ main()
174
+