Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- .env.example +5 -2
- README.md +19 -8
- app.py +13 -1
- witgym/config.py +5 -1
- witgym/hub_data.py +74 -20
- witgym/retriever.py +9 -11
.env.example
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
|
|
| 1 |
HF_TOKEN=hf_...
|
| 2 |
-
WITGYM_DATA_REPO=
|
| 3 |
-
WITGYM_SKIP_HUB=1
|
| 4 |
LLM_BACKEND=hf_api
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Runtime (Space or local with Hub fetch)
|
| 2 |
HF_TOKEN=hf_...
|
| 3 |
+
WITGYM_DATA_REPO=build-small-hackathon/witgym-data
|
|
|
|
| 4 |
LLM_BACKEND=hf_api
|
| 5 |
+
|
| 6 |
+
# Local offline dev only — skip Hub, use files in data/
|
| 7 |
+
# WITGYM_SKIP_HUB=1
|
README.md
CHANGED
|
@@ -43,28 +43,32 @@ export LLM_BACKEND=hf_api
|
|
| 43 |
python app.py
|
| 44 |
```
|
| 45 |
|
| 46 |
-
## Hugging Face Space secrets
|
|
|
|
|
|
|
| 47 |
|
| 48 |
| Secret | Value |
|
| 49 |
|--------|--------|
|
| 50 |
-
| `HF_TOKEN` |
|
| 51 |
| `LLM_BACKEND` | `hf_api` (recommended on Spaces) |
|
| 52 |
-
| `WITGYM_DATA_REPO` |
|
| 53 |
|
| 54 |
Optional: `HF_INFERENCE_PROVIDER` (defaults to `together` for Qwen3.5-9B — required for `enable_thinking: false`), `WITGYM_INDEX_PATH`.
|
| 55 |
|
|
|
|
|
|
|
| 56 |
## Large data on Hugging Face Hub
|
| 57 |
|
| 58 |
-
Files over 1 MB (`office_generated.txt`, `index.npz`) live in a **private
|
| 59 |
|
| 60 |
-
**One-time setup** (create private dataset `witgym-data`, then upload):
|
| 61 |
|
| 62 |
```bash
|
| 63 |
-
hf upload
|
| 64 |
data/transcripts/office_generated.txt office_generated.txt \
|
| 65 |
--repo-type dataset --private
|
| 66 |
|
| 67 |
-
hf upload
|
| 68 |
data/index.npz index.npz \
|
| 69 |
--repo-type dataset
|
| 70 |
```
|
|
@@ -75,7 +79,14 @@ hf upload akshay4/witgym-data \
|
|
| 75 |
|
| 76 |
## Deploy (GitHub → Space)
|
| 77 |
|
| 78 |
-
Pushes to `main` sync to [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
## Architecture
|
| 81 |
|
|
|
|
| 43 |
python app.py
|
| 44 |
```
|
| 45 |
|
| 46 |
+
## Hugging Face Space secrets (runtime)
|
| 47 |
+
|
| 48 |
+
Set these on the Space at [build-small-hackathon/WitGym](https://huggingface.co/spaces/build-small-hackathon/WitGym/settings) — **not** in GitHub. A green deploy only syncs code; the app still needs runtime auth.
|
| 49 |
|
| 50 |
| Secret | Value |
|
| 51 |
|--------|--------|
|
| 52 |
+
| `HF_TOKEN` | Write token with read access to the data dataset below |
|
| 53 |
| `LLM_BACKEND` | `hf_api` (recommended on Spaces) |
|
| 54 |
+
| `WITGYM_DATA_REPO` | `build-small-hackathon/witgym-data` (default on Spaces if unset) |
|
| 55 |
|
| 56 |
Optional: `HF_INFERENCE_PROVIDER` (defaults to `together` for Qwen3.5-9B — required for `enable_thinking: false`), `WITGYM_INDEX_PATH`.
|
| 57 |
|
| 58 |
+
Do **not** set `WITGYM_SKIP_HUB` on the Space.
|
| 59 |
+
|
| 60 |
## Large data on Hugging Face Hub
|
| 61 |
|
| 62 |
+
Files over 1 MB (`office_generated.txt`, `index.npz`) live in a **private org dataset**, not in git. The app tries `index.npz` first at startup; if Hub auth fails, it falls back to rebuilding from bundled transcripts.
|
| 63 |
|
| 64 |
+
**One-time setup** (create private dataset `build-small-hackathon/witgym-data`, then upload):
|
| 65 |
|
| 66 |
```bash
|
| 67 |
+
hf upload build-small-hackathon/witgym-data \
|
| 68 |
data/transcripts/office_generated.txt office_generated.txt \
|
| 69 |
--repo-type dataset --private
|
| 70 |
|
| 71 |
+
hf upload build-small-hackathon/witgym-data \
|
| 72 |
data/index.npz index.npz \
|
| 73 |
--repo-type dataset
|
| 74 |
```
|
|
|
|
| 79 |
|
| 80 |
## Deploy (GitHub → Space)
|
| 81 |
|
| 82 |
+
Pushes to `main` sync code to the Space via [`.github/workflows/sync-to-hub.yml`](.github/workflows/sync-to-hub.yml).
|
| 83 |
+
|
| 84 |
+
| Where | Secret | Purpose |
|
| 85 |
+
|-------|--------|---------|
|
| 86 |
+
| GitHub repo secrets | `HF_TOKEN` | CI upload to Space only |
|
| 87 |
+
| Space secrets | `HF_TOKEN`, `WITGYM_DATA_REPO`, `LLM_BACKEND` | Runtime Hub API + dataset + inference |
|
| 88 |
+
|
| 89 |
+
These are **two different** `HF_TOKEN` placements. Configuring GitHub does not configure the Space runtime.
|
| 90 |
|
| 91 |
## Architecture
|
| 92 |
|
app.py
CHANGED
|
@@ -155,6 +155,18 @@ def _loading_html(message: str) -> str:
|
|
| 155 |
return f'<div class="wg-transcript"><div class="wg-empty">{html.escape(message)}</div></div>'
|
| 156 |
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
def _bg_warmup():
|
| 159 |
"""Preload embedder/index/model in background — keeps submit queue free."""
|
| 160 |
global _warmup_error
|
|
@@ -166,7 +178,7 @@ def _bg_warmup():
|
|
| 166 |
_get_shared()
|
| 167 |
except Exception as e:
|
| 168 |
logger.exception("Background warmup failed")
|
| 169 |
-
_warmup_error =
|
| 170 |
finally:
|
| 171 |
_warmup_done.set()
|
| 172 |
|
|
|
|
| 155 |
return f'<div class="wg-transcript"><div class="wg-empty">{html.escape(message)}</div></div>'
|
| 156 |
|
| 157 |
|
| 158 |
+
def _format_warmup_error(exc: Exception) -> str:
|
| 159 |
+
from witgym.hub_data import get_startup_status
|
| 160 |
+
|
| 161 |
+
lines = [str(exc)]
|
| 162 |
+
status = get_startup_status()
|
| 163 |
+
if status:
|
| 164 |
+
lines.append("")
|
| 165 |
+
lines.append("Diagnostics:")
|
| 166 |
+
lines.extend(f"• {entry}" for entry in status)
|
| 167 |
+
return "\n".join(lines)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
def _bg_warmup():
|
| 171 |
"""Preload embedder/index/model in background — keeps submit queue free."""
|
| 172 |
global _warmup_error
|
|
|
|
| 178 |
_get_shared()
|
| 179 |
except Exception as e:
|
| 180 |
logger.exception("Background warmup failed")
|
| 181 |
+
_warmup_error = _format_warmup_error(e)
|
| 182 |
finally:
|
| 183 |
_warmup_done.set()
|
| 184 |
|
witgym/config.py
CHANGED
|
@@ -57,7 +57,11 @@ CLICHE_PENALTY_TOKENS = 6 # Penalise first N tokens of the obvious response
|
|
| 57 |
|
| 58 |
# HuggingFace auth + inference backend
|
| 59 |
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
# "local" = Transformers on device; "hf_api" = Inference Providers (Spaces default)
|
| 62 |
LLM_BACKEND = os.getenv("LLM_BACKEND", "local")
|
| 63 |
# Qwen3.5-9B thinking-mode toggle requires Together; "auto" often 400s on extra_body
|
|
|
|
| 57 |
|
| 58 |
# HuggingFace auth + inference backend
|
| 59 |
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 60 |
+
# Org dataset on Spaces; override via env for local dev (e.g. akshay4/witgym-data)
|
| 61 |
+
WITGYM_DATA_REPO = os.getenv(
|
| 62 |
+
"WITGYM_DATA_REPO",
|
| 63 |
+
"build-small-hackathon/witgym-data" if os.getenv("SPACE_ID") else "",
|
| 64 |
+
)
|
| 65 |
# "local" = Transformers on device; "hf_api" = Inference Providers (Spaces default)
|
| 66 |
LLM_BACKEND = os.getenv("LLM_BACKEND", "local")
|
| 67 |
# Qwen3.5-9B thinking-mode toggle requires Together; "auto" often 400s on extra_body
|
witgym/hub_data.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""Fetch >1MB artifacts from a private HF dataset repo."""
|
| 2 |
import os
|
| 3 |
from pathlib import Path
|
| 4 |
-
from typing import Optional
|
| 5 |
|
| 6 |
from loguru import logger
|
| 7 |
|
|
@@ -10,6 +10,21 @@ from witgym import config
|
|
| 10 |
HUB_ARTIFACTS = ("index.npz", "office_generated.txt")
|
| 11 |
HUB_CACHE_DIR = "data/hub_cache"
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
def _local_default_path(filename: str) -> Optional[Path]:
|
| 15 |
if filename == "index.npz":
|
|
@@ -19,34 +34,73 @@ def _local_default_path(filename: str) -> Optional[Path]:
|
|
| 19 |
return None
|
| 20 |
|
| 21 |
|
| 22 |
-
def
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
default = _local_default_path(filename)
|
| 25 |
if default is not None and default.exists():
|
|
|
|
| 26 |
return default
|
| 27 |
|
| 28 |
cache_dest = Path(local_dir) / filename
|
| 29 |
if cache_dest.exists():
|
|
|
|
| 30 |
return cache_dest
|
| 31 |
|
| 32 |
-
if os.getenv("WITGYM_SKIP_HUB")
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
from huggingface_hub import hf_hub_download
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
local_dir=local_dir,
|
| 44 |
-
)
|
| 45 |
-
return Path(downloaded)
|
| 46 |
|
| 47 |
|
| 48 |
def materialize_hub_transcripts() -> None:
|
| 49 |
-
"""
|
| 50 |
if os.getenv("WITGYM_SKIP_HUB") or not config.WITGYM_DATA_REPO:
|
| 51 |
return
|
| 52 |
|
|
@@ -54,11 +108,11 @@ def materialize_hub_transcripts() -> None:
|
|
| 54 |
if dest.exists():
|
| 55 |
return
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
return
|
| 61 |
|
| 62 |
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 63 |
dest.write_bytes(hub_txt.read_bytes())
|
| 64 |
-
|
|
|
|
| 1 |
"""Fetch >1MB artifacts from a private HF dataset repo."""
|
| 2 |
import os
|
| 3 |
from pathlib import Path
|
| 4 |
+
from typing import List, Optional
|
| 5 |
|
| 6 |
from loguru import logger
|
| 7 |
|
|
|
|
| 10 |
HUB_ARTIFACTS = ("index.npz", "office_generated.txt")
|
| 11 |
HUB_CACHE_DIR = "data/hub_cache"
|
| 12 |
|
| 13 |
+
_startup_status: List[str] = []
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_startup_status() -> List[str]:
|
| 17 |
+
return list(_startup_status)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def clear_startup_status() -> None:
|
| 21 |
+
_startup_status.clear()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _record(msg: str) -> None:
|
| 25 |
+
_startup_status.append(msg)
|
| 26 |
+
logger.info(msg)
|
| 27 |
+
|
| 28 |
|
| 29 |
def _local_default_path(filename: str) -> Optional[Path]:
|
| 30 |
if filename == "index.npz":
|
|
|
|
| 34 |
return None
|
| 35 |
|
| 36 |
|
| 37 |
+
def _hub_fetch_error_message(exc: Exception, filename: str) -> str:
|
| 38 |
+
err = str(exc).lower()
|
| 39 |
+
if "401" in err or "invalid username or password" in err or "unauthorized" in err:
|
| 40 |
+
return (
|
| 41 |
+
f"Hub auth failed for {filename}: HF_TOKEN cannot read "
|
| 42 |
+
f"{config.WITGYM_DATA_REPO}. Use a Write token with dataset access."
|
| 43 |
+
)
|
| 44 |
+
if "404" in err or "not found" in err or "repository not found" in err:
|
| 45 |
+
return f"Hub artifact missing: {filename} not in {config.WITGYM_DATA_REPO}"
|
| 46 |
+
return f"Hub fetch failed for {filename}: {exc}"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def try_ensure_artifact(filename: str, local_dir: str = HUB_CACHE_DIR) -> Optional[Path]:
|
| 50 |
+
"""Return local path or None. Hub HTTP/auth errors never propagate."""
|
| 51 |
default = _local_default_path(filename)
|
| 52 |
if default is not None and default.exists():
|
| 53 |
+
_record(f"Using local {filename} at {default}")
|
| 54 |
return default
|
| 55 |
|
| 56 |
cache_dest = Path(local_dir) / filename
|
| 57 |
if cache_dest.exists():
|
| 58 |
+
_record(f"Using cached {filename} at {cache_dest}")
|
| 59 |
return cache_dest
|
| 60 |
|
| 61 |
+
if os.getenv("WITGYM_SKIP_HUB"):
|
| 62 |
+
_record(f"Hub fetch skipped for {filename} (WITGYM_SKIP_HUB=1)")
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
if not config.WITGYM_DATA_REPO:
|
| 66 |
+
_record(f"Hub fetch skipped for {filename} (WITGYM_DATA_REPO not set)")
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
if not config.HF_TOKEN:
|
| 70 |
+
_record(f"Hub fetch skipped for {filename} (HF_TOKEN not set)")
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
from huggingface_hub import hf_hub_download
|
| 75 |
+
|
| 76 |
+
logger.info(f"Downloading {filename} from {config.WITGYM_DATA_REPO}")
|
| 77 |
+
downloaded = hf_hub_download(
|
| 78 |
+
repo_id=config.WITGYM_DATA_REPO,
|
| 79 |
+
filename=filename,
|
| 80 |
+
repo_type="dataset",
|
| 81 |
+
token=config.HF_TOKEN,
|
| 82 |
+
local_dir=local_dir,
|
| 83 |
+
)
|
| 84 |
+
path = Path(downloaded)
|
| 85 |
+
_record(f"Downloaded {filename} from {config.WITGYM_DATA_REPO}")
|
| 86 |
+
return path
|
| 87 |
+
except Exception as e:
|
| 88 |
+
msg = _hub_fetch_error_message(e, filename)
|
| 89 |
+
logger.warning(msg)
|
| 90 |
+
_record(msg)
|
| 91 |
+
return None
|
| 92 |
|
|
|
|
| 93 |
|
| 94 |
+
def ensure_artifact(filename: str, local_dir: str = HUB_CACHE_DIR) -> Path:
|
| 95 |
+
"""Return local path; raise FileNotFoundError if unavailable."""
|
| 96 |
+
path = try_ensure_artifact(filename, local_dir)
|
| 97 |
+
if path is None:
|
| 98 |
+
raise FileNotFoundError(f"{filename} not found locally and Hub fetch failed or disabled")
|
| 99 |
+
return path
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
|
| 102 |
def materialize_hub_transcripts() -> None:
|
| 103 |
+
"""Optional: copy hub transcript into data/transcripts/. Never aborts startup."""
|
| 104 |
if os.getenv("WITGYM_SKIP_HUB") or not config.WITGYM_DATA_REPO:
|
| 105 |
return
|
| 106 |
|
|
|
|
| 108 |
if dest.exists():
|
| 109 |
return
|
| 110 |
|
| 111 |
+
hub_txt = try_ensure_artifact("office_generated.txt")
|
| 112 |
+
if hub_txt is None:
|
| 113 |
+
_record("office_generated.txt unavailable — continuing with bundled transcripts")
|
| 114 |
return
|
| 115 |
|
| 116 |
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 117 |
dest.write_bytes(hub_txt.read_bytes())
|
| 118 |
+
_record(f"Materialized {dest} from Hub")
|
witgym/retriever.py
CHANGED
|
@@ -22,27 +22,25 @@ def load_index(index_path: str = config.INDEX_PATH) -> dict:
|
|
| 22 |
if _index_cache is not None:
|
| 23 |
return _index_cache
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
path = index_path
|
| 26 |
if path.endswith(".json") and not os.path.exists(path):
|
| 27 |
npz_fallback = path.removesuffix(".json") + ".npz"
|
| 28 |
if os.path.exists(npz_fallback):
|
| 29 |
path = npz_fallback
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
if not os.path.exists(path) and config.WITGYM_DATA_REPO:
|
| 36 |
-
from witgym.hub_data import ensure_artifact
|
| 37 |
-
|
| 38 |
-
try:
|
| 39 |
-
path = str(ensure_artifact("index.npz"))
|
| 40 |
-
except FileNotFoundError:
|
| 41 |
-
pass
|
| 42 |
|
| 43 |
if not os.path.exists(path):
|
| 44 |
transcript_dir = Path(config.TRANSCRIPT_DIR)
|
| 45 |
if transcript_dir.is_dir() and any(transcript_dir.glob("*.txt")):
|
|
|
|
| 46 |
from witgym.indexer import build_index
|
| 47 |
|
| 48 |
build_path = path if path.endswith(".npz") else config.INDEX_PATH
|
|
|
|
| 22 |
if _index_cache is not None:
|
| 23 |
return _index_cache
|
| 24 |
|
| 25 |
+
from witgym.hub_data import clear_startup_status, materialize_hub_transcripts, try_ensure_artifact
|
| 26 |
+
|
| 27 |
+
clear_startup_status()
|
| 28 |
+
|
| 29 |
path = index_path
|
| 30 |
if path.endswith(".json") and not os.path.exists(path):
|
| 31 |
npz_fallback = path.removesuffix(".json") + ".npz"
|
| 32 |
if os.path.exists(npz_fallback):
|
| 33 |
path = npz_fallback
|
| 34 |
|
| 35 |
+
if not os.path.exists(path):
|
| 36 |
+
hub_index = try_ensure_artifact("index.npz")
|
| 37 |
+
if hub_index is not None:
|
| 38 |
+
path = str(hub_index)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
if not os.path.exists(path):
|
| 41 |
transcript_dir = Path(config.TRANSCRIPT_DIR)
|
| 42 |
if transcript_dir.is_dir() and any(transcript_dir.glob("*.txt")):
|
| 43 |
+
materialize_hub_transcripts()
|
| 44 |
from witgym.indexer import build_index
|
| 45 |
|
| 46 |
build_path = path if path.endswith(".npz") else config.INDEX_PATH
|