File size: 5,171 Bytes
c0205af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
158
159
160
161
162
163
164
165
"""
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()