dasdebanna commited on
Commit
4f4b694
·
1 Parent(s): f80343c

Launcher: ensure repo-local HF/transformers cache directories are created and writable

Browse files
Files changed (1) hide show
  1. streamlit_app.py +86 -81
streamlit_app.py CHANGED
@@ -1,70 +1,108 @@
1
  # streamlit_app.py (place at repo root)
2
  """
3
  Launcher for Hugging Face Spaces / Streamlit:
4
- - force XDG_CONFIG_HOME/HOME to a writable folder in the repo
5
- - create a minimal .streamlit/config.toml if missing
6
- - ensure Hugging Face / transformers cache dirs are repo-local and writable
7
- - add repo/src to sys.path so imports like `from data_loader import ...` work
8
- - run the actual app (src/app.py) as __main__
9
- Notes:
10
- - We *assign* env vars (not setdefault) to ensure they are effective even if
11
- the environment was pre-populated earlier by the runtime.
12
- - We chmod cache dirs to 0o777 so non-root container user can create locks/write.
13
  """
14
  import os
 
 
15
  from pathlib import Path
16
  import runpy
17
- import sys
18
 
19
  ROOT = Path(__file__).parent.resolve()
20
- STREAMLIT_DIR = ROOT.joinpath(".streamlit")
21
 
22
- # ------------------------------
23
- # Force environment variables (overwrite any existing HF / Streamlit defaults)
24
- # ------------------------------
25
- # Use a repo-local .streamlit directory so Streamlit won't try to write to '/'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  os.environ["XDG_CONFIG_HOME"] = str(STREAMLIT_DIR)
27
- # Ensure HOME is a writable folder inside the repo as well
28
- os.environ["HOME"] = str(ROOT)
29
- # Force STREAMLIT_RUNTIME_DIR to repo-local runtime (overwrite anything)
30
- os.environ["STREAMLIT_RUNTIME_DIR"] = str(ROOT.joinpath(".streamlit", "runtime"))
31
 
32
- # Set repo-local caches for HF libs and transformers (overwrite any existing)
33
- CACHE_ROOT = ROOT.joinpath(".cache")
34
  os.environ["XDG_CACHE_HOME"] = str(CACHE_ROOT)
35
- # transformers prefers TRANSFORMERS_CACHE (deprecated) or HF_HOME; set both for compatibility
36
- TF_CACHE = CACHE_ROOT.joinpath("transformers")
37
  os.environ["TRANSFORMERS_CACHE"] = str(TF_CACHE)
38
- HF_HOME = CACHE_ROOT.joinpath("huggingface")
39
  os.environ["HF_HOME"] = str(HF_HOME)
40
- DATASETS_CACHE = CACHE_ROOT.joinpath("datasets")
41
  os.environ["HF_DATASETS_CACHE"] = str(DATASETS_CACHE)
42
- # optional metric cache
43
- os.environ.setdefault("HF_METRICS_CACHE", str(CACHE_ROOT.joinpath("metrics")))
44
 
45
- # ------------------------------
46
- # Create config / runtime / cache directories and make them writable
47
- # ------------------------------
48
- def ensure_dir_and_chmod(p: Path, mode: int = 0o777):
 
 
 
49
  try:
50
- p.mkdir(parents=True, exist_ok=True)
51
- p.chmod(mode)
52
- except Exception as e:
53
- # best-effort; continue and print diagnostics
54
- print(f"streamlit_app launcher: ensure_dir_and_chmod failed for {p}: {e}")
55
 
56
- # Create important directories
57
- ensure_dir_and_chmod(STREAMLIT_DIR)
58
- ensure_dir_and_chmod(ROOT.joinpath(".streamlit", "runtime"))
59
- ensure_dir_and_chmod(CACHE_ROOT)
60
- ensure_dir_and_chmod(TF_CACHE)
61
- ensure_dir_and_chmod(HF_HOME)
62
- ensure_dir_and_chmod(DATASETS_CACHE)
63
- ensure_dir_and_chmod(Path(os.environ.get("STREAMLIT_RUNTIME_DIR")))
 
 
 
 
 
 
 
64
 
65
- # ------------------------------
66
- # Create a minimal streamlit config if missing
67
- # ------------------------------
68
  cfg = STREAMLIT_DIR.joinpath("config.toml")
69
  if not cfg.exists():
70
  try:
@@ -81,38 +119,5 @@ if not cfg.exists():
81
  except Exception as e:
82
  print("streamlit_app launcher: failed to write config.toml:", e)
83
 
84
- # ------------------------------
85
- # Add src directory to Python import path so app can import modules by name
86
- # ------------------------------
87
- SRC_DIR = str(ROOT.joinpath("src"))
88
- if SRC_DIR not in sys.path:
89
- sys.path.insert(0, SRC_DIR)
90
-
91
- # ------------------------------
92
- # Print diagnostics (critical - will show in HF container logs)
93
- # ------------------------------
94
- def stat_mode(p: Path):
95
- try:
96
- s = p.stat()
97
- return oct(s.st_mode & 0o777)
98
- except Exception:
99
- return "MISSING"
100
-
101
- print("streamlit_app launcher: XDG_CONFIG_HOME =", os.environ.get("XDG_CONFIG_HOME"))
102
- print("streamlit_app launcher: HOME =", os.environ.get("HOME"))
103
- print("streamlit_app launcher: STREAMLIT_RUNTIME_DIR =", os.environ.get("STREAMLIT_RUNTIME_DIR"))
104
- print("streamlit_app launcher: XDG_CACHE_HOME =", os.environ.get("XDG_CACHE_HOME"))
105
- print("streamlit_app launcher: TRANSFORMERS_CACHE =", os.environ.get("TRANSFORMERS_CACHE"))
106
- print("streamlit_app launcher: HF_HOME =", os.environ.get("HF_HOME"))
107
- print("streamlit_app launcher: HF_DATASETS_CACHE =", os.environ.get("HF_DATASETS_CACHE"))
108
- print("streamlit_app launcher: sys.path[0] =", sys.path[0])
109
- print(".cache dir mode:", stat_mode(CACHE_ROOT))
110
- print("transformers cache mode:", stat_mode(TF_CACHE))
111
- print("hf home mode:", stat_mode(HF_HOME))
112
- print("datasets cache mode:", stat_mode(DATASETS_CACHE))
113
- sys.stdout.flush()
114
-
115
- # ------------------------------
116
- # Run the real app
117
- # ------------------------------
118
  runpy.run_path(str(ROOT.joinpath("src", "app.py")), run_name="__main__")
 
1
  # streamlit_app.py (place at repo root)
2
  """
3
  Launcher for Hugging Face Spaces / Streamlit:
4
+ - pick a writable base dir (prefer repo root if writable, otherwise /tmp/<space>)
5
+ - set XDG/STREAMLIT/TRANSFORMERS/HF cache env vars early (overwrite existing)
6
+ - create the cache/runtime directories (best-effort) and attempt to chmod them
7
+ - add repo/src to sys.path so `from data_loader import ...` works
8
+ - run the real app (src/app.py) as __main__
 
 
 
 
9
  """
10
  import os
11
+ import sys
12
+ import tempfile
13
  from pathlib import Path
14
  import runpy
 
15
 
16
  ROOT = Path(__file__).parent.resolve()
 
17
 
18
+ def _writable_test(dir_path: Path) -> bool:
19
+ """Return True if we can create & remove a small file in dir_path."""
20
+ try:
21
+ dir_path.mkdir(parents=True, exist_ok=True)
22
+ test_file = dir_path.joinpath(".write_test")
23
+ test_file.write_text("ok", encoding="utf-8")
24
+ test_file.unlink()
25
+ return True
26
+ except Exception:
27
+ return False
28
+
29
+ # 1) Choose base writeable directory
30
+ # Prefer repo root if writable, otherwise fallback to /tmp/<repo-name>-<uid>
31
+ if _writable_test(ROOT):
32
+ BASE = ROOT
33
+ else:
34
+ # use /tmp which is generally writable in containers
35
+ safe_suffix = ROOT.name.replace("/", "_").replace(" ", "_")
36
+ BASE = Path(tempfile.gettempdir()).joinpath(f"{safe_suffix}_space_runtime")
37
+ BASE.mkdir(parents=True, exist_ok=True)
38
+
39
+ # Helper to ensure and chmod (best-effort)
40
+ def ensure_dir(p: Path, mode: int = 0o777):
41
+ try:
42
+ p.mkdir(parents=True, exist_ok=True)
43
+ # chmod might fail in some containers, ignore failures
44
+ try:
45
+ p.chmod(mode)
46
+ except Exception:
47
+ pass
48
+ except Exception:
49
+ pass
50
+
51
+ # 2) Setup paths (use BASE)
52
+ STREAMLIT_DIR = BASE.joinpath(".streamlit")
53
+ STREAMLIT_RUNTIME_DIR = STREAMLIT_DIR.joinpath("runtime")
54
+ CACHE_ROOT = BASE.joinpath(".cache")
55
+ TF_CACHE = CACHE_ROOT.joinpath("transformers")
56
+ HF_HOME = CACHE_ROOT.joinpath("huggingface")
57
+ DATASETS_CACHE = CACHE_ROOT.joinpath("datasets")
58
+ METRICS_CACHE = CACHE_ROOT.joinpath("metrics")
59
+
60
+ for p in (STREAMLIT_DIR, STREAMLIT_RUNTIME_DIR, CACHE_ROOT, TF_CACHE, HF_HOME, DATASETS_CACHE, METRICS_CACHE):
61
+ ensure_dir(p)
62
+
63
+ # 3) Force environment variables (overwrite any existing ones)
64
+ # Streamlit config and runtime
65
  os.environ["XDG_CONFIG_HOME"] = str(STREAMLIT_DIR)
66
+ os.environ["STREAMLIT_RUNTIME_DIR"] = str(STREAMLIT_RUNTIME_DIR)
67
+ # Set HOME to BASE so some libs compute caches relative to it (safe)
68
+ os.environ["HOME"] = str(BASE)
 
69
 
70
+ # Hugging Face / transformers caches (overwrite)
 
71
  os.environ["XDG_CACHE_HOME"] = str(CACHE_ROOT)
 
 
72
  os.environ["TRANSFORMERS_CACHE"] = str(TF_CACHE)
 
73
  os.environ["HF_HOME"] = str(HF_HOME)
 
74
  os.environ["HF_DATASETS_CACHE"] = str(DATASETS_CACHE)
75
+ os.environ.setdefault("HF_METRICS_CACHE", str(METRICS_CACHE))
 
76
 
77
+ # 4) Add src dir to sys.path so imports like `from data_loader import ...` work
78
+ SRC_DIR = str(ROOT.joinpath("src"))
79
+ if SRC_DIR not in sys.path:
80
+ sys.path.insert(0, SRC_DIR)
81
+
82
+ # 5) Diagnostics (will appear in HF container logs)
83
+ def _stat_mode(p: Path):
84
  try:
85
+ return oct(p.stat().st_mode & 0o777)
86
+ except Exception:
87
+ return "MISSING"
 
 
88
 
89
+ print("streamlit_app launcher: BASE =", str(BASE))
90
+ print("streamlit_app launcher: XDG_CONFIG_HOME =", os.environ.get("XDG_CONFIG_HOME"))
91
+ print("streamlit_app launcher: STREAMLIT_RUNTIME_DIR =", os.environ.get("STREAMLIT_RUNTIME_DIR"))
92
+ print("streamlit_app launcher: HOME =", os.environ.get("HOME"))
93
+ print("streamlit_app launcher: XDG_CACHE_HOME =", os.environ.get("XDG_CACHE_HOME"))
94
+ print("streamlit_app launcher: TRANSFORMERS_CACHE =", os.environ.get("TRANSFORMERS_CACHE"))
95
+ print("streamlit_app launcher: HF_HOME =", os.environ.get("HF_HOME"))
96
+ print("streamlit_app launcher: HF_DATASETS_CACHE =", os.environ.get("HF_DATASETS_CACHE"))
97
+ print("streamlit_app launcher: sys.path[0] =", sys.path[0])
98
+ print(".streamlit mode:", _stat_mode(STREAMLIT_DIR))
99
+ print("runtime mode:", _stat_mode(STREAMLIT_RUNTIME_DIR))
100
+ print(".cache mode:", _stat_mode(CACHE_ROOT))
101
+ print("transformers cache mode:", _stat_mode(TF_CACHE))
102
+ print("hf home mode:", _stat_mode(HF_HOME))
103
+ sys.stdout.flush()
104
 
105
+ # 6) Create a minimal config.toml in chosen .streamlit (if not present)
 
 
106
  cfg = STREAMLIT_DIR.joinpath("config.toml")
107
  if not cfg.exists():
108
  try:
 
119
  except Exception as e:
120
  print("streamlit_app launcher: failed to write config.toml:", e)
121
 
122
+ # 7) Finally run the app script (as if python src/app.py)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  runpy.run_path(str(ROOT.joinpath("src", "app.py")), run_name="__main__")