Eric Xu commited on
Commit
c9d61d3
·
unverified ·
1 Parent(s): e56613d

Add HuggingFace Spaces deployment support

Browse files

- Dockerfile for HF Spaces (port 7860, Python 3.11)
- Per-user API key input in UI (no .env needed for hosted mode)
- Detect SPACE_ID env var, auto-bind 0.0.0.0:7860
- Persona dataset dropdown: USA, Japan, India, Singapore, Brazil, France
(all from nvidia/Nemotron-Personas collection)
- HF Spaces metadata in README frontmatter
- /api/config/api-key endpoint for browser-based key entry
- /api/nemotron/setup accepts dataset choice parameter

Files changed (4) hide show
  1. Dockerfile +22 -0
  2. README.md +9 -0
  3. web/app.py +61 -18
  4. web/static/index.html +75 -10
Dockerfile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install dependencies
6
+ COPY pyproject.toml .
7
+ RUN pip install --no-cache-dir \
8
+ "datasets>=4.0.0" \
9
+ "huggingface_hub>=0.20.0" \
10
+ "openai>=1.0.0" \
11
+ "python-dotenv>=1.0.0" \
12
+ "fastapi>=0.115.0" \
13
+ "uvicorn>=0.32.0" \
14
+ "sse-starlette>=2.0.0"
15
+
16
+ # Copy app
17
+ COPY . .
18
+
19
+ # HF Spaces expects port 7860
20
+ EXPOSE 7860
21
+
22
+ CMD ["python", "web/app.py"]
README.md CHANGED
@@ -1,3 +1,12 @@
 
 
 
 
 
 
 
 
 
1
  # SGO — Semantic Gradient Optimization
2
 
3
  You're launching a product. You think the landing page is good. But **who have you actually asked?**
 
1
+ ---
2
+ title: SGO — Semantic Gradient Optimization
3
+ emoji: 📊
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: docker
7
+ app_port: 7860
8
+ ---
9
+
10
  # SGO — Semantic Gradient Optimization
11
 
12
  You're launching a product. You think the landing page is good. But **who have you actually asked?**
web/app.py CHANGED
@@ -113,15 +113,32 @@ def get_nemotron(data_dir=None):
113
  return None
114
 
115
 
116
- def get_client():
117
- return OpenAI(
118
- api_key=os.getenv("LLM_API_KEY"),
119
- base_url=os.getenv("LLM_BASE_URL"),
120
- )
 
 
 
 
 
121
 
122
 
123
  def get_model():
124
- return os.getenv("LLM_MODEL_NAME", "openai/gpt-4o-mini")
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
 
127
  # ── Models ────────────────────────────────────────────────────────────────
@@ -162,19 +179,39 @@ async def index():
162
  return FileResponse(Path(__file__).parent / "static" / "index.html")
163
 
164
 
 
 
 
 
 
 
165
  @app.get("/api/config")
166
  async def get_config():
167
  """Return current LLM config and Nemotron status."""
168
  nem_path = find_nemotron_path()
 
169
  return {
170
  "model": get_model(),
171
- "has_api_key": bool(os.getenv("LLM_API_KEY")),
172
- "base_url": os.getenv("LLM_BASE_URL", ""),
173
  "nemotron_path": str(nem_path) if nem_path else None,
174
  "nemotron_available": nem_path is not None,
 
 
175
  }
176
 
177
 
 
 
 
 
 
 
 
 
 
 
 
178
  class SuggestChangesInput(BaseModel):
179
  entity_text: str
180
  goal: str
@@ -182,27 +219,31 @@ class SuggestChangesInput(BaseModel):
182
 
183
 
184
  class NemotronPathInput(BaseModel):
185
- path: str
 
186
 
187
 
188
  @app.post("/api/nemotron/setup")
189
  async def setup_nemotron(input: NemotronPathInput):
190
- """Point to existing Nemotron data, or download it to the given path."""
191
  p = Path(input.path).expanduser().resolve()
 
192
 
193
  if (p / "dataset_info.json").exists():
194
- # Already there — just load it
195
  ds = get_nemotron(data_dir=str(p))
196
  if ds is None:
197
  raise HTTPException(500, "Failed to load dataset")
198
- return {"status": "loaded", "path": str(p), "count": len(ds)}
199
 
200
- # Not there — download to this path
201
- from setup_data import setup
202
  try:
203
- ds = setup(data_dir=p)
 
 
 
 
204
  get_nemotron(data_dir=str(p))
205
- return {"status": "downloaded", "path": str(p), "count": len(ds)}
206
  except Exception as e:
207
  raise HTTPException(500, f"Download failed: {e}")
208
 
@@ -834,6 +875,8 @@ async def restore_sessions():
834
 
835
  if __name__ == "__main__":
836
  import uvicorn
 
 
837
  print(f"\n SGO Web Interface")
838
- print(f" http://localhost:8000\n")
839
- uvicorn.run(app, host="127.0.0.1", port=8000)
 
113
  return None
114
 
115
 
116
+ # Per-user API key override (for hosted/Spaces mode)
117
+ _user_llm_config: dict = {} # session-scoped, not persistent
118
+
119
+
120
+ def get_client(api_key_override=None):
121
+ key = api_key_override or _user_llm_config.get("api_key") or os.getenv("LLM_API_KEY")
122
+ base = _user_llm_config.get("base_url") or os.getenv("LLM_BASE_URL")
123
+ if not key:
124
+ raise HTTPException(400, "No API key configured. Enter your key above.")
125
+ return OpenAI(api_key=key, base_url=base)
126
 
127
 
128
  def get_model():
129
+ return _user_llm_config.get("model") or os.getenv("LLM_MODEL_NAME", "openai/gpt-4o-mini")
130
+
131
+
132
+ IS_SPACES = bool(os.getenv("SPACE_ID"))
133
+
134
+ NEMOTRON_DATASETS = {
135
+ "USA": "nvidia/Nemotron-Personas-USA",
136
+ "Japan": "nvidia/Nemotron-Personas-Japan",
137
+ "India": "nvidia/Nemotron-Personas-India",
138
+ "Singapore": "nvidia/Nemotron-Personas-Singapore",
139
+ "Brazil": "nvidia/Nemotron-Personas-Brazil",
140
+ "France": "nvidia/Nemotron-Personas-France",
141
+ }
142
 
143
 
144
  # ── Models ────────────────────────────────────────────────────────────────
 
179
  return FileResponse(Path(__file__).parent / "static" / "index.html")
180
 
181
 
182
+ class SetApiKeyInput(BaseModel):
183
+ api_key: str
184
+ base_url: str = ""
185
+ model: str = ""
186
+
187
+
188
  @app.get("/api/config")
189
  async def get_config():
190
  """Return current LLM config and Nemotron status."""
191
  nem_path = find_nemotron_path()
192
+ has_key = bool(_user_llm_config.get("api_key") or os.getenv("LLM_API_KEY"))
193
  return {
194
  "model": get_model(),
195
+ "has_api_key": has_key,
196
+ "base_url": _user_llm_config.get("base_url") or os.getenv("LLM_BASE_URL", ""),
197
  "nemotron_path": str(nem_path) if nem_path else None,
198
  "nemotron_available": nem_path is not None,
199
+ "is_spaces": IS_SPACES,
200
+ "persona_datasets": list(NEMOTRON_DATASETS.keys()),
201
  }
202
 
203
 
204
+ @app.post("/api/config/api-key")
205
+ async def set_api_key(input: SetApiKeyInput):
206
+ """Set LLM API key from the UI (for hosted/Spaces mode)."""
207
+ _user_llm_config["api_key"] = input.api_key
208
+ if input.base_url:
209
+ _user_llm_config["base_url"] = input.base_url
210
+ if input.model:
211
+ _user_llm_config["model"] = input.model
212
+ return {"ok": True, "model": get_model()}
213
+
214
+
215
  class SuggestChangesInput(BaseModel):
216
  entity_text: str
217
  goal: str
 
219
 
220
 
221
  class NemotronPathInput(BaseModel):
222
+ path: str = "data/nemotron"
223
+ dataset: str = "USA"
224
 
225
 
226
  @app.post("/api/nemotron/setup")
227
  async def setup_nemotron(input: NemotronPathInput):
228
+ """Point to existing data, or download a Nemotron dataset to the given path."""
229
  p = Path(input.path).expanduser().resolve()
230
+ hf_name = NEMOTRON_DATASETS.get(input.dataset, NEMOTRON_DATASETS["USA"])
231
 
232
  if (p / "dataset_info.json").exists():
 
233
  ds = get_nemotron(data_dir=str(p))
234
  if ds is None:
235
  raise HTTPException(500, "Failed to load dataset")
236
+ return {"status": "loaded", "path": str(p), "count": len(ds), "dataset": input.dataset}
237
 
238
+ # Download from HuggingFace
 
239
  try:
240
+ from datasets import load_dataset
241
+ print(f"Downloading {hf_name} ...")
242
+ ds = load_dataset(hf_name, split="train")
243
+ p.mkdir(parents=True, exist_ok=True)
244
+ ds.save_to_disk(str(p))
245
  get_nemotron(data_dir=str(p))
246
+ return {"status": "downloaded", "path": str(p), "count": len(ds), "dataset": input.dataset}
247
  except Exception as e:
248
  raise HTTPException(500, f"Download failed: {e}")
249
 
 
875
 
876
  if __name__ == "__main__":
877
  import uvicorn
878
+ port = int(os.getenv("PORT", "7860" if IS_SPACES else "8000"))
879
+ host = "0.0.0.0" if IS_SPACES else "127.0.0.1"
880
  print(f"\n SGO Web Interface")
881
+ print(f" http://{host}:{port}\n")
882
+ uvicorn.run(app, host=host, port=port)
web/static/index.html CHANGED
@@ -311,19 +311,59 @@
311
  <div id="nemotronBadge" class="config-badge" style="margin-left:8px">checking...</div>
312
  </header>
313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  <!-- Nemotron setup (shown if not available) -->
315
  <div class="step hidden" id="nemotronSetup" style="border-color:var(--yellow)">
316
  <div class="step-header">
317
  <div class="step-num" style="border-color:var(--yellow);color:var(--yellow)">!</div>
318
  <div class="step-title">Panel data not found</div>
319
  </div>
320
- <p class="step-desc">SGO needs its persona dataset to build realistic panels. Choose where to load it from, or download it now (~2 GB).</p>
321
- <div class="field">
322
- <label>Folder for panel data</label>
323
- <input type="text" id="nemotronPath" placeholder="e.g. data/nemotron">
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  </div>
325
  <div class="btn-row">
326
- <button onclick="setupNemotron()">Use this folder</button>
327
  </div>
328
  <div id="nemotronStatus" class="hidden mt-16">
329
  <div class="progress-text" id="nemotronStatusText"></div>
@@ -579,9 +619,11 @@ async function init() {
579
  if (cfg.has_api_key) {
580
  badge.textContent = cfg.model;
581
  badge.className = 'config-badge ok';
 
582
  } else {
583
- badge.textContent = 'No API key — set LLM_API_KEY in .env';
584
  badge.className = 'config-badge warn';
 
585
  }
586
 
587
  const nemBadge = document.getElementById('nemotronBadge');
@@ -599,20 +641,43 @@ async function init() {
599
  // Changes are auto-generated from evaluation concerns
600
  }
601
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602
  async function setupNemotron() {
603
- const path = document.getElementById('nemotronPath').value.trim();
604
- if (!path) return alert('Enter a folder path for the panel data.');
605
 
606
  const status = document.getElementById('nemotronStatus');
607
  const text = document.getElementById('nemotronStatusText');
608
  status.classList.remove('hidden');
609
- text.textContent = 'Loading dataset (or downloading if not found — ~2GB, may take a few minutes)...';
610
 
611
  try {
612
  const resp = await fetch('/api/nemotron/setup', {
613
  method: 'POST',
614
  headers: {'Content-Type': 'application/json'},
615
- body: JSON.stringify({path}),
616
  });
617
  const data = await resp.json();
618
  if (!resp.ok) throw new Error(data.detail || 'Failed');
 
311
  <div id="nemotronBadge" class="config-badge" style="margin-left:8px">checking...</div>
312
  </header>
313
 
314
+ <!-- API Key setup (shown if no key configured) -->
315
+ <div class="step hidden" id="apiKeySetup" style="border-color:var(--yellow)">
316
+ <div class="step-header">
317
+ <div class="step-num" style="border-color:var(--yellow);color:var(--yellow)">!</div>
318
+ <div class="step-title">Connect your LLM</div>
319
+ </div>
320
+ <p class="step-desc">SGO needs an OpenAI-compatible API key to run evaluations. Your key stays in your browser session.</p>
321
+ <div class="field">
322
+ <label>API key</label>
323
+ <input type="password" id="apiKeyInput" placeholder="sk-...">
324
+ </div>
325
+ <details class="mb-8">
326
+ <summary style="cursor:pointer;color:var(--text2);font-size:0.85rem">Custom endpoint</summary>
327
+ <div style="padding:8px 0">
328
+ <div class="field">
329
+ <label>Base URL (optional)</label>
330
+ <input type="text" id="apiBaseUrl" placeholder="e.g. https://api.openai.com/v1">
331
+ </div>
332
+ <div class="field">
333
+ <label>Model (optional)</label>
334
+ <input type="text" id="apiModel" placeholder="e.g. gpt-4o-mini">
335
+ </div>
336
+ </div>
337
+ </details>
338
+ <button onclick="saveApiKey()">Connect</button>
339
+ </div>
340
+
341
  <!-- Nemotron setup (shown if not available) -->
342
  <div class="step hidden" id="nemotronSetup" style="border-color:var(--yellow)">
343
  <div class="step-header">
344
  <div class="step-num" style="border-color:var(--yellow);color:var(--yellow)">!</div>
345
  <div class="step-title">Panel data not found</div>
346
  </div>
347
+ <p class="step-desc">SGO needs a persona dataset to build realistic panels. Pick a country and download, or point to an existing folder.</p>
348
+ <div style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap">
349
+ <div class="field" style="flex:1;min-width:120px">
350
+ <label>Country</label>
351
+ <select id="nemotronDataset" style="padding:10px 12px">
352
+ <option value="USA">USA (6M personas)</option>
353
+ <option value="Japan">Japan (6M)</option>
354
+ <option value="India">India (21M)</option>
355
+ <option value="Singapore">Singapore (888K)</option>
356
+ <option value="Brazil">Brazil (6M)</option>
357
+ <option value="France">France (6M)</option>
358
+ </select>
359
+ </div>
360
+ <div class="field" style="flex:2;min-width:200px">
361
+ <label>Folder</label>
362
+ <input type="text" id="nemotronPath" placeholder="e.g. data/nemotron">
363
+ </div>
364
  </div>
365
  <div class="btn-row">
366
+ <button onclick="setupNemotron()">Download and use</button>
367
  </div>
368
  <div id="nemotronStatus" class="hidden mt-16">
369
  <div class="progress-text" id="nemotronStatusText"></div>
 
619
  if (cfg.has_api_key) {
620
  badge.textContent = cfg.model;
621
  badge.className = 'config-badge ok';
622
+ document.getElementById('apiKeySetup').classList.add('hidden');
623
  } else {
624
+ badge.textContent = 'No API key';
625
  badge.className = 'config-badge warn';
626
+ document.getElementById('apiKeySetup').classList.remove('hidden');
627
  }
628
 
629
  const nemBadge = document.getElementById('nemotronBadge');
 
641
  // Changes are auto-generated from evaluation concerns
642
  }
643
 
644
+ async function saveApiKey() {
645
+ const key = document.getElementById('apiKeyInput').value.trim();
646
+ if (!key) return alert('Enter your API key.');
647
+ const baseUrl = document.getElementById('apiBaseUrl').value.trim();
648
+ const model = document.getElementById('apiModel').value.trim();
649
+
650
+ try {
651
+ const resp = await fetch('/api/config/api-key', {
652
+ method: 'POST',
653
+ headers: {'Content-Type': 'application/json'},
654
+ body: JSON.stringify({api_key: key, base_url: baseUrl, model: model}),
655
+ });
656
+ const data = await resp.json();
657
+ if (!resp.ok) throw new Error(data.detail || 'Failed');
658
+
659
+ document.getElementById('configBadge').textContent = data.model;
660
+ document.getElementById('configBadge').className = 'config-badge ok';
661
+ document.getElementById('apiKeySetup').classList.add('hidden');
662
+ } catch (e) {
663
+ alert('Failed to set API key: ' + e.message);
664
+ }
665
+ }
666
+
667
  async function setupNemotron() {
668
+ const path = document.getElementById('nemotronPath').value.trim() || 'data/nemotron';
669
+ const dataset = document.getElementById('nemotronDataset').value;
670
 
671
  const status = document.getElementById('nemotronStatus');
672
  const text = document.getElementById('nemotronStatusText');
673
  status.classList.remove('hidden');
674
+ text.textContent = `Loading ${dataset} personas (downloading if needed — may take a few minutes)...`;
675
 
676
  try {
677
  const resp = await fetch('/api/nemotron/setup', {
678
  method: 'POST',
679
  headers: {'Content-Type': 'application/json'},
680
+ body: JSON.stringify({path, dataset}),
681
  });
682
  const data = await resp.json();
683
  if (!resp.ok) throw new Error(data.detail || 'Failed');