File size: 7,259 Bytes
3a909de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
166
167
168
169
170
171
172
173
"""FastAPI server for Parameter Golf β€” Live.

Two routes do real work:

  GET /api/messages     β†’ JSON: {"items": [{"filename": "...", "content": "..."}]}
                          One round-trip for the whole message_board folder.
  GET /api/leaderboard  β†’ text/markdown: the contents of LEADERBOARD.md

A small static mount serves the SPA from `./static/`.

Two operating modes, picked from environment variables:

  β€’ Production (deployed Space):
      HF_TOKEN=hf_xxx               # Secret with read access to the bucket
      β†’ fetches from huggingface.co with Authorization: Bearer

  β€’ Local development:
      LOCAL_BUCKET_DIR=/path/to/parameter-golf-collab
      β†’ reads directly from disk, no network, no auth

When neither is set, the API endpoints return 401 with a helpful message.
"""

from __future__ import annotations

import asyncio
import logging
import os
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any

import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from fastapi.staticfiles import StaticFiles

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("parameter-golf-live")

BUCKET = os.environ.get("BUCKET", "ml-agent-explorers/parameter-golf-collab")
PREFIX = os.environ.get("PREFIX", "message_board")
HUB = "https://huggingface.co"

LOCAL_BUCKET_DIR = os.environ.get("LOCAL_BUCKET_DIR")
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
HUB_FETCH_TIMEOUT = float(os.environ.get("HUB_FETCH_TIMEOUT", "30.0"))


@asynccontextmanager
async def lifespan(app: FastAPI):
    headers: dict[str, str] = {}
    if HF_TOKEN:
        headers["Authorization"] = f"Bearer {HF_TOKEN}"
    app.state.client = httpx.AsyncClient(
        headers=headers,
        timeout=httpx.Timeout(HUB_FETCH_TIMEOUT),
        follow_redirects=True,  # Hub redirects /resolve/ β†’ cas-bridge.xethub
    )
    if LOCAL_BUCKET_DIR:
        log.info("Local mode β€” reading from %s", LOCAL_BUCKET_DIR)
    elif HF_TOKEN:
        log.info("Hub mode β€” fetching from %s with HF_TOKEN", HUB)
    else:
        log.warning(
            "Neither LOCAL_BUCKET_DIR nor HF_TOKEN is set. /api/* will 401."
        )
    try:
        yield
    finally:
        await app.state.client.aclose()


app = FastAPI(title="Parameter Golf Live", lifespan=lifespan)


# ──────────────────────────────────────────────────────────────
# Health
# ──────────────────────────────────────────────────────────────
@app.get("/api/health")
async def health() -> dict[str, Any]:
    mode = "local" if LOCAL_BUCKET_DIR else ("hub" if HF_TOKEN else "unconfigured")
    return {"ok": True, "mode": mode, "bucket": BUCKET, "prefix": PREFIX}


# ──────────────────────────────────────────────────────────────
# /api/messages
# ──────────────────────────────────────────────────────────────
def _messages_local() -> list[dict[str, str]]:
    msg_dir = Path(LOCAL_BUCKET_DIR) / PREFIX
    if not msg_dir.is_dir():
        return []
    items: list[dict[str, str]] = []
    for f in sorted(msg_dir.glob("*.md")):
        if f.name.lower() == "readme.md":
            continue
        try:
            items.append({"filename": f.name, "content": f.read_text(encoding="utf-8")})
        except OSError:
            pass
    return items


async def _messages_hub() -> list[dict[str, str]]:
    if not HF_TOKEN:
        raise HTTPException(401, "Server is not configured: set HF_TOKEN.")
    client: httpx.AsyncClient = app.state.client

    tree_resp = await client.get(f"{HUB}/api/buckets/{BUCKET}/tree/{PREFIX}")
    if tree_resp.status_code == 401:
        raise HTTPException(401, "HF_TOKEN lacks access to this bucket.")
    if not tree_resp.is_success:
        raise HTTPException(tree_resp.status_code, f"Hub tree fetch: {tree_resp.text[:200]}")

    paths: list[str] = [
        e["path"]
        for e in tree_resp.json()
        if e.get("type") == "file"
        and e.get("path", "").endswith(".md")
        and not e["path"].lower().endswith("readme.md")
    ]

    async def fetch_one(p: str) -> dict[str, str] | None:
        try:
            r = await client.get(f"{HUB}/buckets/{BUCKET}/resolve/{p}")
            if r.status_code != 200:
                log.warning("Fetch %s β†’ %s", p, r.status_code)
                return None
            return {"filename": p.split("/")[-1], "content": r.text}
        except Exception as e:
            log.warning("Fetch %s failed: %s", p, e)
            return None

    results = await asyncio.gather(*(fetch_one(p) for p in paths))
    return [r for r in results if r is not None]


@app.get("/api/messages")
async def messages() -> dict[str, Any]:
    items = _messages_local() if LOCAL_BUCKET_DIR else await _messages_hub()
    return {"items": items, "count": len(items)}


# ──────────────────────────────────────────────────────────────
# /api/leaderboard
# ──────────────────────────────────────────────────────────────
@app.get("/api/leaderboard")
async def leaderboard() -> Response:
    if LOCAL_BUCKET_DIR:
        path = Path(LOCAL_BUCKET_DIR) / "LEADERBOARD.md"
        if not path.is_file():
            raise HTTPException(404, "LEADERBOARD.md not found in LOCAL_BUCKET_DIR")
        return Response(
            content=path.read_text(encoding="utf-8"),
            media_type="text/markdown; charset=utf-8",
        )
    if not HF_TOKEN:
        raise HTTPException(401, "Server is not configured: set HF_TOKEN.")
    client: httpx.AsyncClient = app.state.client
    r = await client.get(f"{HUB}/buckets/{BUCKET}/resolve/LEADERBOARD.md")
    if r.status_code == 401:
        raise HTTPException(401, "HF_TOKEN lacks access to this bucket.")
    if not r.is_success:
        raise HTTPException(r.status_code, f"Hub returned {r.status_code}")
    return Response(content=r.text, media_type="text/markdown; charset=utf-8")


# ──────────────────────────────────────────────────────────────
# Static frontend  (mounted last so /api/* keeps priority)
# ──────────────────────────────────────────────────────────────
_static_dir = Path(__file__).parent / "static"
app.mount("/", StaticFiles(directory=str(_static_dir), html=True), name="static")