davidtran999 commited on
Commit
28ac2d9
·
verified ·
1 Parent(s): ed12ffb

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

Browse files
backend/hue_portal/hue-portal-backendDocker/set_database_secrets.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Set DATABASE_URL + POSTGRES_* secrets/variables cho Hugging Face Space dựa
4
+ trên thông tin trong `ops/.env.tunnel`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+ from typing import Dict, Iterable, Tuple
14
+
15
+ from huggingface_hub import HfApi, login
16
+
17
+
18
+ REPO_ROOT = Path(__file__).resolve().parents[1]
19
+ OPS_DIR = REPO_ROOT / "ops"
20
+ TUNNEL_ENV = OPS_DIR / ".env.tunnel"
21
+ TUNNEL_ENV_TEMPLATE = OPS_DIR / "env.tunnel.example"
22
+ DEFAULT_SPACE_ID = "davidtran999/hue-portal-backend"
23
+
24
+
25
+ def _load_env_file(path: Path) -> Dict[str, str]:
26
+ data: Dict[str, str] = {}
27
+ if not path.exists():
28
+ return data
29
+ for raw_line in path.read_text(encoding="utf-8").splitlines():
30
+ line = raw_line.strip()
31
+ if not line or line.startswith("#") or "=" not in line:
32
+ continue
33
+ key, value = line.split("=", 1)
34
+ data[key.strip()] = value.strip().strip('"').strip("'")
35
+ return data
36
+
37
+
38
+ def load_config(env_path: Path) -> Dict[str, str]:
39
+ """Load config từ env file (actual -> template) và biến môi trường."""
40
+ config: Dict[str, str] = {}
41
+ for path in (TUNNEL_ENV_TEMPLATE, env_path):
42
+ config.update(_load_env_file(path))
43
+ config.update({key: value for key, value in os.environ.items() if value})
44
+ return config
45
+
46
+
47
+ def resolve_database_settings(config: Dict[str, str]) -> Tuple[str, str, str, str, str]:
48
+ """Trả về (host, port, db, user, password)."""
49
+ host = config.get("PG_TUNNEL_HOST") or config.get("POSTGRES_HOST", "localhost")
50
+ port = config.get("PG_TUNNEL_PORT") or config.get("POSTGRES_PORT", "5543")
51
+ database = config.get("PG_TUNNEL_DB") or config.get("POSTGRES_DB", "hue_portal")
52
+ user = config.get("PG_TUNNEL_USER") or config.get("POSTGRES_USER", "hue")
53
+ password = config.get("PG_TUNNEL_PASSWORD") or config.get("POSTGRES_PASSWORD", "")
54
+ return host, port, database, user, password
55
+
56
+
57
+ def upsert_variable(api: HfApi, repo_id: str, key: str, value: str) -> None:
58
+ """Xóa rồi set lại Space variable."""
59
+ if not value:
60
+ return
61
+ try:
62
+ api.delete_space_variable(repo_id=repo_id, key=key)
63
+ except Exception:
64
+ pass
65
+ api.add_space_variable(repo_id=repo_id, key=key, value=value)
66
+
67
+
68
+ def upsert_secret(api: HfApi, repo_id: str, key: str, value: str) -> None:
69
+ """Xóa rồi set lại Space secret."""
70
+ if not value:
71
+ return
72
+ try:
73
+ api.delete_space_secret(repo_id=repo_id, key=key)
74
+ except Exception:
75
+ pass
76
+ api.add_space_secret(repo_id=repo_id, key=key, value=value)
77
+
78
+
79
+ def apply_database_settings(space_id: str, config: Dict[str, str]) -> None:
80
+ """Đẩy DATABASE_URL + POSTGRES_* lên Space."""
81
+ host, port, database, user, password = resolve_database_settings(config)
82
+ database_url = f"postgres://{user}:{password}@{host}:{port}/{database}"
83
+
84
+ hf_token = config.get("HF_TOKEN")
85
+ if not hf_token:
86
+ cache_file = Path.home() / ".cache" / "huggingface" / "token"
87
+ if cache_file.exists():
88
+ hf_token = cache_file.read_text(encoding="utf-8").strip()
89
+ if not hf_token:
90
+ raise RuntimeError("HF token không tìm thấy. Chạy `huggingface-cli login` hoặc set HF_TOKEN.")
91
+
92
+ login(token=hf_token)
93
+ api = HfApi()
94
+
95
+ # POSTGRES_* variables (host/port/db/user) + secret (password) để backend dùng.
96
+ variable_pairs: Iterable[Tuple[str, str]] = (
97
+ ("POSTGRES_HOST", host),
98
+ ("POSTGRES_PORT", str(port)),
99
+ ("POSTGRES_DB", database),
100
+ ("POSTGRES_USER", user),
101
+ )
102
+ for key, value in variable_pairs:
103
+ upsert_variable(api, space_id, key, value)
104
+
105
+ upsert_secret(api, space_id, "POSTGRES_PASSWORD", password)
106
+ upsert_secret(api, space_id, "DATABASE_URL", database_url)
107
+
108
+ print(f"✅ Đã cập nhật DATABASE_URL + POSTGRES_* cho Space {space_id}")
109
+
110
+
111
+ def parse_args() -> argparse.Namespace:
112
+ parser = argparse.ArgumentParser(description="Set DATABASE_URL cho HF Space.")
113
+ parser.add_argument(
114
+ "--space-id",
115
+ default=None,
116
+ help="ID của Space (vd: username/space-name). Mặc định đọc từ env hoặc template.",
117
+ )
118
+ parser.add_argument(
119
+ "--env-file",
120
+ default=TUNNEL_ENV,
121
+ type=Path,
122
+ help="Đường dẫn file chứa thông tin tunnel. Mặc định: ops/.env.tunnel.",
123
+ )
124
+ return parser.parse_args()
125
+
126
+
127
+ def main() -> None:
128
+ args = parse_args()
129
+ env_path: Path = args.env_file
130
+ if not env_path.exists():
131
+ raise SystemExit(f"Không tìm thấy {env_path}. Copy ops/env.tunnel.example -> ops/.env.tunnel trước.")
132
+
133
+ config = load_config(env_path)
134
+ space_id = args.space_id or config.get("HF_SPACE_ID") or DEFAULT_SPACE_ID
135
+
136
+ try:
137
+ apply_database_settings(space_id, config)
138
+ except Exception as exc:
139
+ raise SystemExit(f"Không thể cập nhật secrets: {exc}") from exc
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()