Download scripts/setup_models.py from Sakda101/explorer-consultant-bot: direct link, hf CLI and curl.
- Browser
- Download file 5.17 kB
-
https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/scripts/setup_models.py
- Command line
-
hf download hf://spaces/Sakda101/explorer-consultant-bot/scripts/setup_models.py
-
curl -L -o setup_models.py https://huggingface.co/spaces/Sakda101/explorer-consultant-bot/resolve/main/scripts/setup_models.py
5.17 kB
| """ | |
| setup_models.py — download ML model artifacts at container startup. | |
| Run automatically by railway.toml start command: | |
| /opt/venv/bin/python setup_models.py && streamlit run Webapp/app.py ... | |
| Set these env vars in Railway: | |
| ARTIFACTS_DIR = /app_data/artifacts | |
| HF_REPO_ID = Sakda101/explorer-consultant-models | |
| HF_TOKEN = hf_xxxxxxxxxxxx | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import sys | |
| from pathlib import Path | |
| # --------------------------------------------------------------------------- | |
| # Configuration | |
| # --------------------------------------------------------------------------- | |
| PROJECT_ROOT = Path(__file__).resolve().parents[1] | |
| ARTIFACTS_DIR = Path(os.environ.get("ARTIFACTS_DIR", str(PROJECT_ROOT / "artifacts"))) | |
| _SENTINELS = (ARTIFACTS_DIR / "final_model.pkl", ARTIFACTS_DIR / "distilbert_stage1") | |
| HF_REPO_ID = os.environ.get("HF_REPO_ID", "Sakda101/explorer-consultant-models") | |
| HF_TOKEN = os.environ.get("HF_TOKEN", "") | |
| def _log(msg: str) -> None: | |
| print(f"[setup_models] {msg}", flush=True) | |
| def _already_downloaded() -> bool: | |
| ok = any(path.exists() for path in _SENTINELS) | |
| found = next((str(path) for path in _SENTINELS if path.exists()), "MISSING") | |
| _log(f"Sentinel check -> {found}") | |
| return ok | |
| # --------------------------------------------------------------------------- | |
| # Download from Hugging Face | |
| # --------------------------------------------------------------------------- | |
| def _download() -> None: | |
| try: | |
| from huggingface_hub import snapshot_download | |
| except ImportError: | |
| _log("ERROR: huggingface_hub not installed.") | |
| sys.exit(1) | |
| _log(f"Downloading models from Hugging Face ({HF_REPO_ID}) ...") | |
| _log("This may take several minutes for 2.3 GB ...") | |
| try: | |
| # Download to /tmp to avoid filling the persistent volume with temp files | |
| tmp_dir = Path("/tmp/_hf_download") | |
| if tmp_dir.exists(): | |
| import shutil | |
| shutil.rmtree(tmp_dir) | |
| tmp_dir.mkdir(parents=True, exist_ok=True) | |
| local_dir = snapshot_download( | |
| repo_id=HF_REPO_ID, | |
| repo_type="model", | |
| token=HF_TOKEN if HF_TOKEN else None, | |
| local_dir=str(tmp_dir), | |
| ignore_patterns=["*.gitattributes", "README.md", ".gitattributes"], | |
| ) | |
| _log(f"Downloaded to: {local_dir}") | |
| return local_dir | |
| except Exception as exc: | |
| _log(f"ERROR: Hugging Face download failed: {exc}") | |
| sys.exit(1) | |
| def _move_artifacts(local_dir: str) -> None: | |
| import shutil | |
| src = Path(local_dir) / "artifacts" | |
| if not src.exists(): | |
| # Try root of downloaded repo | |
| src = Path(local_dir) | |
| if not ((src / "final_model.pkl").exists() or (src / "distilbert_stage1").exists()): | |
| _log(f"ERROR: no final_model.pkl or distilbert_stage1 found inside {src}") | |
| _log(f"Contents: {list(src.iterdir()) if src.exists() else 'N/A'}") | |
| sys.exit(1) | |
| if ARTIFACTS_DIR.exists(): | |
| shutil.rmtree(ARTIFACTS_DIR) | |
| shutil.move(str(src), str(ARTIFACTS_DIR)) | |
| _log(f"Models moved to {ARTIFACTS_DIR}") | |
| # Clean up temp download folder from /tmp | |
| tmp = Path("/tmp/_hf_download") | |
| if tmp.exists(): | |
| shutil.rmtree(tmp, ignore_errors=True) | |
| # --------------------------------------------------------------------------- | |
| # Admin password bootstrap | |
| # --------------------------------------------------------------------------- | |
| def setup_admin_password() -> None: | |
| import hashlib, sqlite3 | |
| pw = os.environ.get("ADMIN_PASSWORD", "").strip() | |
| if not pw: | |
| return | |
| db_path = Path(os.environ.get("DB_PATH", str(PROJECT_ROOT / "explorer.db"))) | |
| if not db_path.exists(): | |
| return | |
| try: | |
| con = sqlite3.connect(str(db_path)) | |
| row = con.execute( | |
| "SELECT password_hash FROM users WHERE email = ?", | |
| ("huthsakda525@gmail.com",), | |
| ).fetchone() | |
| if row and not row[0]: | |
| salt = os.urandom(16).hex() | |
| key = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 260_000).hex() | |
| con.execute( | |
| "UPDATE users SET password_hash = ? WHERE email = ?", | |
| (salt + ":" + key, "huthsakda525@gmail.com"), | |
| ) | |
| con.commit() | |
| _log("Admin password bootstrapped.") | |
| con.close() | |
| except Exception as exc: | |
| _log(f"Password bootstrap error: {exc}") | |
| # --------------------------------------------------------------------------- | |
| # Main | |
| # --------------------------------------------------------------------------- | |
| def main() -> None: | |
| _log(f"ARTIFACTS_DIR = {ARTIFACTS_DIR}") | |
| if _already_downloaded(): | |
| _log("Models already present — skipping download.") | |
| setup_admin_password() | |
| return | |
| ARTIFACTS_DIR.parent.mkdir(parents=True, exist_ok=True) | |
| local_dir = _download() | |
| _move_artifacts(local_dir) | |
| if _already_downloaded(): | |
| _log("✓ Models ready.") | |
| else: | |
| _log("WARNING: Setup finished but sentinel still missing.") | |
| setup_admin_password() | |
| if __name__ == "__main__": | |
| main() | |