Spaces:
Running on Zero
Running on Zero
Commit ·
2f663bd
1
Parent(s): 3ee7cb0
Llamacpp addition and Hugging Face Spaces Zero GPU integration
Browse files- NEMOTRON_GGUF_SETUP.md +69 -10
- app/main.py +565 -10
- app/prompts/game_generation.txt +12 -17
- app/services/generator.py +53 -18
- requirements.txt +1 -0
NEMOTRON_GGUF_SETUP.md
CHANGED
|
@@ -108,20 +108,79 @@ CMAKE_ARGS="-DLLAMA_CUDA=on -DLLAMA_CUDA_DATALAYOUT=row -DCUDAToolkit_INCLUDE_DI
|
|
| 108 |
### Issue: Out of memory
|
| 109 |
**Solution:** Reduce context window or use CPU-offloading in llama.cpp settings.
|
| 110 |
|
| 111 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
|
| 116 |
-
```
|
| 117 |
-
llama-cpp-python
|
| 118 |
-
```
|
| 119 |
|
| 120 |
-
|
| 121 |
-
- Consider n_gpu_layers parameter in `generator.py`
|
| 122 |
-
- CPU fallback is always available
|
| 123 |
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
## Hackathon Integration
|
| 127 |
|
|
|
|
| 108 |
### Issue: Out of memory
|
| 109 |
**Solution:** Reduce context window or use CPU-offloading in llama.cpp settings.
|
| 110 |
|
| 111 |
+
## Performance expectations
|
| 112 |
+
|
| 113 |
+
| Setup | First Run | Subsequent Runs | Speed |
|
| 114 |
+
|-------|-----------|-----------------|-------|
|
| 115 |
+
| CPU (no optimization) | 5-10 min | 2-5 min per game | Slow |
|
| 116 |
+
| CPU (quantized) | 5-10 min | 30-60s per game | Moderate |
|
| 117 |
+
| GPU (CUDA/Metal) | 5-10 min | 5-15s per game | Fast |
|
| 118 |
+
| HF Zero GPU (auto) | 5-10 min | 5-15s per game | Fast |
|
| 119 |
+
|
| 120 |
+
## Integration with Hugging Face Spaces (Zero GPU)
|
| 121 |
+
|
| 122 |
+
The app is fully configured for **Hugging Face Spaces** with **Zero GPU** support.
|
| 123 |
+
|
| 124 |
+
### What is Zero GPU?
|
| 125 |
+
|
| 126 |
+
Hugging Face Spaces **Zero GPU** (paid tier) provides on-demand GPU allocation:
|
| 127 |
+
- GPU is allocated only when a `@spaces.GPU`-decorated function runs
|
| 128 |
+
- GPU is **released** after the function completes (saves cost)
|
| 129 |
+
- Without the decorator, code runs on CPU
|
| 130 |
+
|
| 131 |
+
### How it works in this app
|
| 132 |
+
|
| 133 |
+
1. `app/main.py` imports `spaces` gracefully (no error if missing)
|
| 134 |
+
2. The `_generate_with_gpu()` function is wrapped with `@spaces.GPU` only at runtime on HF Spaces
|
| 135 |
+
3. Inside that function, `torch.cuda.is_available()` returns `True`, so `generator.py` auto-detects GPU via `_get_n_gpu_layers()` and sets `n_gpu_layers=-1`
|
| 136 |
+
4. On CPU (local dev or free Spaces tier), it falls back to `n_gpu_layers=0`
|
| 137 |
+
|
| 138 |
+
### Requirements
|
| 139 |
|
| 140 |
+
Add to `requirements.txt`:
|
| 141 |
+
```
|
| 142 |
+
llama-cpp-python
|
| 143 |
+
spaces
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
> **Note:** The `spaces` package is only available on the Hugging Face Spaces runtime. Local imports use `try/except ImportError` to handle this gracefully.
|
| 147 |
+
|
| 148 |
+
### File structure for HF Spaces
|
| 149 |
+
|
| 150 |
+
```
|
| 151 |
+
app/
|
| 152 |
+
main.py ← HF Spaces entry point (launches Gradio)
|
| 153 |
+
services/
|
| 154 |
+
generator.py ← Auto-detects GPU via torch.cuda
|
| 155 |
+
...
|
| 156 |
+
requirements.txt
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
On Hugging Face Spaces, the app runs `app/main.py` automatically.
|
| 160 |
+
|
| 161 |
+
### GPU auto-detection logic
|
| 162 |
+
|
| 163 |
+
In `app/services/generator.py`:
|
| 164 |
+
|
| 165 |
+
```python
|
| 166 |
+
def _get_n_gpu_layers() -> int:
|
| 167 |
+
try:
|
| 168 |
+
import torch
|
| 169 |
+
if torch.cuda.is_available():
|
| 170 |
+
return -1 # All layers on GPU
|
| 171 |
+
except ImportError:
|
| 172 |
+
pass
|
| 173 |
+
return 0 # CPU only
|
| 174 |
+
```
|
| 175 |
|
| 176 |
+
This works because `@spaces.GPU` makes `torch.cuda.is_available()` return `True` inside the decorated function.
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
+
### Deployment steps
|
|
|
|
|
|
|
| 179 |
|
| 180 |
+
1. Push the repo to Hugging Face Spaces
|
| 181 |
+
2. Set **Space SDK** to **Gradio**
|
| 182 |
+
3. Set **Space hardware** to **Zero GPU** (paid) for GPU acceleration, or leave as CPU (free)
|
| 183 |
+
4. The app auto-detects and uses GPU/CPU accordingly
|
| 184 |
|
| 185 |
## Hackathon Integration
|
| 186 |
|
app/main.py
CHANGED
|
@@ -1,14 +1,569 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import spaces
|
| 3 |
-
import torch
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
@spaces.GPU
|
| 9 |
-
def greet(n):
|
| 10 |
-
print(zero.device) # <-- 'cuda:0' 🤗
|
| 11 |
-
return f"Hello {zero + n} Tensor"
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
| 1 |
+
"""Hugging Face Spaces entry point with Zero GPU support.
|
| 2 |
+
|
| 3 |
+
On HF Spaces, @spaces.GPU auto-allocates a GPU when the function runs
|
| 4 |
+
and frees it after — saving costs on zero-GPU (paid) tier.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import uuid
|
| 9 |
+
import json
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
import gradio as gr
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
try:
|
| 15 |
+
import spaces # only available on Hugging Face Spaces runtime
|
| 16 |
+
except ImportError:
|
| 17 |
+
spaces = None
|
| 18 |
+
|
| 19 |
+
from app.services.retrieval import load_games_dataset, normalize_game_record, retrieve_examples
|
| 20 |
+
from app.services.generator import generate_game, generate_game_with_model, build_generation_prompt, NEMOTRON_MODEL_ID, NEMOTRON_GGUF_FILE
|
| 21 |
+
from app.services.validator import validate_game, repair_game
|
| 22 |
+
from app.services.schema_validator import create_minimal_game_template
|
| 23 |
+
from app.services.tracing import log_event, log_generation_trace, load_events
|
| 24 |
+
from app.services.journal import (
|
| 25 |
+
create_journal_entry, save_journal_entry, summarize_journal,
|
| 26 |
+
load_journal_entries, detect_mood, assess_story_value,
|
| 27 |
+
)
|
| 28 |
+
from app.services.scoring import compute_scores
|
| 29 |
+
from app.services.story import build_story_packet, generate_story
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# ── Load dataset once on startup ──────────────────────────────────────────────
|
| 33 |
+
DATASET_PATH = Path(__file__).resolve().parent.parent / "app/data/games_dataset.json"
|
| 34 |
+
DATA_RECORDS = []
|
| 35 |
+
try:
|
| 36 |
+
raw = load_games_dataset(str(DATASET_PATH))
|
| 37 |
+
DATA_RECORDS = [normalize_game_record(r) for r in raw]
|
| 38 |
+
print(f"✓ Loaded {len(DATA_RECORDS)} game records for retrieval")
|
| 39 |
+
except FileNotFoundError:
|
| 40 |
+
print(f"⚠ Dataset not found at {DATASET_PATH}, retrieval will be empty")
|
| 41 |
+
|
| 42 |
+
# ── In-memory session store ───────────────────────────────────────────────────
|
| 43 |
+
SESSION_STORE: dict[str, dict] = {}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ── Zero GPU wrappers ─────────────────────────────────────────────────────────
|
| 47 |
+
|
| 48 |
+
def _generate_with_gpu(config: dict, retrieved: list[dict]) -> dict:
|
| 49 |
+
"""Call the model for generation — wrapped in @spaces.GPU on HF Spaces.
|
| 50 |
+
|
| 51 |
+
Inside @spaces.GPU, torch.cuda.is_available() returns True,
|
| 52 |
+
so generator.py auto-detects GPU via _get_n_gpu_layers().
|
| 53 |
+
"""
|
| 54 |
+
prompt = build_generation_prompt(config, retrieved)
|
| 55 |
+
json_str = generate_game_with_model(prompt, model_name="nemotron")
|
| 56 |
+
if json_str:
|
| 57 |
+
try:
|
| 58 |
+
game = json.loads(json_str)
|
| 59 |
+
if all(field in game for field in ["game_id", "title", "setup", "tasks", "safety"]):
|
| 60 |
+
return game
|
| 61 |
+
except json.JSONDecodeError:
|
| 62 |
+
pass
|
| 63 |
+
# Fallback — returns mock without using GPU
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# Apply @spaces.GPU only if the decorator exists (HF Spaces runtime)
|
| 68 |
+
if spaces is not None:
|
| 69 |
+
_generate_with_gpu = spaces.GPU(_generate_with_gpu)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def run_pipeline(
|
| 73 |
+
game_type: str,
|
| 74 |
+
city: str,
|
| 75 |
+
area: str,
|
| 76 |
+
location_type: str,
|
| 77 |
+
duration_minutes: int,
|
| 78 |
+
num_players: int,
|
| 79 |
+
difficulty: str,
|
| 80 |
+
age_group: str,
|
| 81 |
+
energy_level: str,
|
| 82 |
+
):
|
| 83 |
+
"""Run the full AI generation pipeline end-to-end."""
|
| 84 |
+
session_id = str(uuid.uuid4())
|
| 85 |
+
|
| 86 |
+
config = {
|
| 87 |
+
"game_type": game_type,
|
| 88 |
+
"city": city or "Paris",
|
| 89 |
+
"area": area or "Downtown",
|
| 90 |
+
"location_type": location_type,
|
| 91 |
+
"duration_minutes": int(duration_minutes),
|
| 92 |
+
"num_players": int(num_players),
|
| 93 |
+
"difficulty": difficulty,
|
| 94 |
+
"age_group": age_group,
|
| 95 |
+
"energy_level": energy_level,
|
| 96 |
+
"photo_enabled": True,
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
state = {}
|
| 100 |
+
|
| 101 |
+
# 1 ── Retrieval
|
| 102 |
+
state["num_retrieved"] = 0
|
| 103 |
+
if DATA_RECORDS:
|
| 104 |
+
retrieved = retrieve_examples(config, DATA_RECORDS, k=3)
|
| 105 |
+
state["num_retrieved"] = len(retrieved)
|
| 106 |
+
state["retrieved_ids"] = [r["id"] for r in retrieved]
|
| 107 |
+
else:
|
| 108 |
+
retrieved = []
|
| 109 |
+
|
| 110 |
+
# 2 ── Generation (with Zero GPU if available)
|
| 111 |
+
game = _generate_with_gpu(config, retrieved)
|
| 112 |
+
if game is None:
|
| 113 |
+
from app.services.generator import generate_game_mock
|
| 114 |
+
game = generate_game_mock(config, retrieved)
|
| 115 |
+
print("Using mock generation (model unavailable or failed)")
|
| 116 |
+
|
| 117 |
+
state["game_id"] = game["game_id"]
|
| 118 |
+
state["game_title"] = game["title"]
|
| 119 |
+
|
| 120 |
+
# 3 ── Validation
|
| 121 |
+
is_valid, failures = validate_game(game, config)
|
| 122 |
+
state["validation_passed"] = is_valid
|
| 123 |
+
state["validation_failures"] = failures
|
| 124 |
+
|
| 125 |
+
# 4 ── Repair (if needed)
|
| 126 |
+
repaired = None
|
| 127 |
+
if not is_valid:
|
| 128 |
+
repaired = repair_game(game, failures, config)
|
| 129 |
+
state["repair_applied"] = True
|
| 130 |
+
is_valid2, failures2 = validate_game(repaired, config)
|
| 131 |
+
state["repair_valid"] = is_valid2
|
| 132 |
+
state["remaining_failures"] = failures2
|
| 133 |
+
else:
|
| 134 |
+
state["repair_applied"] = False
|
| 135 |
+
|
| 136 |
+
final_game = repaired if repaired is not None else game
|
| 137 |
+
|
| 138 |
+
# 5 ── Log generation trace
|
| 139 |
+
log_generation_trace(
|
| 140 |
+
session_id=session_id,
|
| 141 |
+
config=config,
|
| 142 |
+
retrieved_examples=retrieved,
|
| 143 |
+
game=final_game,
|
| 144 |
+
validation_passed=is_valid or (repaired is not None and state.get("repair_valid", False)),
|
| 145 |
+
validation_failures=failures,
|
| 146 |
+
repaired_game=repaired,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# 6 ── Reveal all tasks as events
|
| 150 |
+
for task in final_game.get("tasks", []):
|
| 151 |
+
log_event(session_id, "task_revealed", {
|
| 152 |
+
"task_id": task["task_id"],
|
| 153 |
+
"title": task["title"],
|
| 154 |
+
"points": task["points"],
|
| 155 |
+
})
|
| 156 |
+
|
| 157 |
+
# 7 ── Store session
|
| 158 |
+
SESSION_STORE[session_id] = {
|
| 159 |
+
"config": config,
|
| 160 |
+
"game": final_game,
|
| 161 |
+
"events": [],
|
| 162 |
+
"journals": [],
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
# 8 ── Build summary text
|
| 166 |
+
summary = build_summary(final_game, state, session_id)
|
| 167 |
+
return summary, final_game, session_id
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# ── Phase 3: Gameplay helpers ─────────────────────────────────────────────────
|
| 171 |
+
|
| 172 |
+
def complete_task(session_id: str, task_id: str, team_id: str = "team-a"):
|
| 173 |
+
if session_id not in SESSION_STORE:
|
| 174 |
+
return "⚠ Unknown session"
|
| 175 |
+
ev = log_event(session_id, "task_completed", {
|
| 176 |
+
"task_id": task_id,
|
| 177 |
+
"summary": f"Team {team_id} completed {task_id}",
|
| 178 |
+
}, team_id=team_id)
|
| 179 |
+
SESSION_STORE[session_id]["events"].append(ev)
|
| 180 |
+
return f"✅ Task {task_id} completed!"
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def skip_task(session_id: str, task_id: str, team_id: str = "team-a"):
|
| 184 |
+
if session_id not in SESSION_STORE:
|
| 185 |
+
return "⚠ Unknown session"
|
| 186 |
+
ev = log_event(session_id, "task_skipped", {
|
| 187 |
+
"task_id": task_id,
|
| 188 |
+
"summary": f"Team {team_id} skipped {task_id}",
|
| 189 |
+
}, team_id=team_id)
|
| 190 |
+
SESSION_STORE[session_id]["events"].append(ev)
|
| 191 |
+
return f"⏭️ Task {task_id} skipped."
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def use_hint(session_id: str, task_id: str, team_id: str = "team-a"):
|
| 195 |
+
if session_id not in SESSION_STORE:
|
| 196 |
+
return "⚠ Unknown session"
|
| 197 |
+
ev = log_event(session_id, "hint_used", {
|
| 198 |
+
"task_id": task_id,
|
| 199 |
+
"summary": f"Team {team_id} used a hint for {task_id}",
|
| 200 |
+
}, team_id=team_id)
|
| 201 |
+
SESSION_STORE[session_id]["events"].append(ev)
|
| 202 |
+
return f"💡 Hint used for {task_id} (−5 pts)"
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def record_journal(
|
| 206 |
+
session_id: str,
|
| 207 |
+
transcript: str,
|
| 208 |
+
task_id: str = "",
|
| 209 |
+
location_note: str = "",
|
| 210 |
+
team_id: str = "team-a",
|
| 211 |
+
):
|
| 212 |
+
if session_id not in SESSION_STORE:
|
| 213 |
+
return "⚠ Unknown session", ""
|
| 214 |
+
|
| 215 |
+
entry = create_journal_entry(
|
| 216 |
+
transcript=transcript,
|
| 217 |
+
session_id=session_id,
|
| 218 |
+
team_id=team_id,
|
| 219 |
+
task_id=task_id or None,
|
| 220 |
+
location_note=location_note,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
summary = summarize_journal(transcript, task_id=task_id or None, location_note=location_note)
|
| 224 |
+
entry["moment_summary"] = summary["moment_summary"]
|
| 225 |
+
entry["tags"] = summary["tags"]
|
| 226 |
+
entry["story_value"] = summary["story_value"]
|
| 227 |
+
|
| 228 |
+
save_journal_entry(entry)
|
| 229 |
+
|
| 230 |
+
ev = log_event(session_id, "journal_recorded", {
|
| 231 |
+
"journal_id": entry["journal_id"],
|
| 232 |
+
"mood": entry["mood"],
|
| 233 |
+
"story_value": summary["story_value"],
|
| 234 |
+
"summary": summary["moment_summary"],
|
| 235 |
+
}, team_id=team_id)
|
| 236 |
+
SESSION_STORE[session_id]["events"].append(ev)
|
| 237 |
+
SESSION_STORE[session_id]["journals"].append(entry)
|
| 238 |
+
|
| 239 |
+
display = (
|
| 240 |
+
f"🎙️ **Journal recorded!**\n"
|
| 241 |
+
f"- Mood: *{entry['mood']}*\n"
|
| 242 |
+
f"- Story value: **{summary['story_value']}**\n"
|
| 243 |
+
f"- Tags: {', '.join(summary['tags'])}\n"
|
| 244 |
+
f"- Summary: {summary['moment_summary']}"
|
| 245 |
+
)
|
| 246 |
+
return display, entry["journal_id"]
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def upload_photo(
|
| 250 |
+
session_id: str,
|
| 251 |
+
photo_file,
|
| 252 |
+
caption: str = "",
|
| 253 |
+
task_id: str = "",
|
| 254 |
+
team_id: str = "team-a",
|
| 255 |
+
):
|
| 256 |
+
if session_id not in SESSION_STORE:
|
| 257 |
+
return "⚠ Unknown session", []
|
| 258 |
+
|
| 259 |
+
photo_name = ""
|
| 260 |
+
if photo_file is not None:
|
| 261 |
+
if isinstance(photo_file, str):
|
| 262 |
+
photo_name = photo_file.split("/")[-1].split("\\")[-1]
|
| 263 |
+
else:
|
| 264 |
+
photo_name = getattr(photo_file, "name", "photo")
|
| 265 |
+
|
| 266 |
+
photo_id = f"photo-{uuid.uuid4().hex[:8]}"
|
| 267 |
+
|
| 268 |
+
payload = {
|
| 269 |
+
"photo_id": photo_id,
|
| 270 |
+
"photo_name": photo_name,
|
| 271 |
+
"caption": caption,
|
| 272 |
+
"summary": f"Team {team_id} uploaded photo for {task_id or 'general'}",
|
| 273 |
+
}
|
| 274 |
+
if task_id:
|
| 275 |
+
payload["task_id"] = task_id
|
| 276 |
+
|
| 277 |
+
ev = log_event(session_id, "photo_uploaded", payload, team_id=team_id)
|
| 278 |
+
SESSION_STORE[session_id]["events"].append(ev)
|
| 279 |
+
|
| 280 |
+
if "photos" not in SESSION_STORE[session_id]:
|
| 281 |
+
SESSION_STORE[session_id]["photos"] = []
|
| 282 |
+
SESSION_STORE[session_id]["photos"].append({
|
| 283 |
+
"photo_id": photo_id,
|
| 284 |
+
"photo_name": photo_name,
|
| 285 |
+
"caption": caption,
|
| 286 |
+
"task_id": task_id,
|
| 287 |
+
})
|
| 288 |
+
|
| 289 |
+
photos = SESSION_STORE[session_id]["photos"]
|
| 290 |
+
gallery_lines = [f"📸 **{p['photo_id']}** — {p['caption'] or '(no caption)'} [{p['task_id'] or 'general'}]" for p in photos]
|
| 291 |
+
|
| 292 |
+
display = (
|
| 293 |
+
f"📸 **Photo uploaded!**\n"
|
| 294 |
+
f"- ID: `{photo_id}`\n"
|
| 295 |
+
f"- Caption: {caption or '(none)'}\n"
|
| 296 |
+
f"- Related task: {task_id or 'general'}\n\n"
|
| 297 |
+
f"**All photos ({len(photos)}):**\n" + "\n".join(gallery_lines)
|
| 298 |
+
)
|
| 299 |
+
return display
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def end_game(session_id: str, team_id: str = "team-a"):
|
| 303 |
+
if session_id not in SESSION_STORE:
|
| 304 |
+
return "⚠ Unknown session"
|
| 305 |
+
|
| 306 |
+
session = SESSION_STORE[session_id]
|
| 307 |
+
game = session["game"]
|
| 308 |
+
events = load_events(session_id=session_id)
|
| 309 |
+
|
| 310 |
+
ev = log_event(session_id, "game_finished", {
|
| 311 |
+
"summary": f"Game finished — session {session_id}",
|
| 312 |
+
}, team_id=team_id)
|
| 313 |
+
events.append(ev)
|
| 314 |
+
|
| 315 |
+
scores = compute_scores(events, game)
|
| 316 |
+
session["scores"] = scores
|
| 317 |
+
|
| 318 |
+
lines = ["# 🏆 Final Scoreboard\n"]
|
| 319 |
+
for ts in scores.get("team_scores", []):
|
| 320 |
+
marker = " 🏆" if ts["team_id"] == scores.get("winner") else ""
|
| 321 |
+
lines.append(f"### Team: {ts['team_id']}{marker}")
|
| 322 |
+
lines.append(f"- **Total points:** {ts['points']}")
|
| 323 |
+
lines.append(f"- Tasks completed: {ts['completed_tasks']}/{ts['total_tasks']}")
|
| 324 |
+
lines.append(f"- Hints used: {ts['hints_used']}")
|
| 325 |
+
if ts.get("bonuses"):
|
| 326 |
+
lines.append(f"- Bonuses: {', '.join(ts['bonuses'])}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
lines.append("**Breakdown:**")
|
| 329 |
+
for b in ts.get("scoring_breakdown", []):
|
| 330 |
+
lines.append(f" • {b}")
|
| 331 |
+
lines.append("")
|
| 332 |
+
|
| 333 |
+
if scores.get("winner"):
|
| 334 |
+
lines.append(f"**Winner: {scores['winner']}** 🎉")
|
| 335 |
+
|
| 336 |
+
return "\n".join(lines), scores
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def generate_recap(session_id: str):
|
| 340 |
+
if session_id not in SESSION_STORE:
|
| 341 |
+
return "⚠ Unknown session"
|
| 342 |
+
|
| 343 |
+
session = SESSION_STORE[session_id]
|
| 344 |
+
game = session["game"]
|
| 345 |
+
events = load_events(session_id=session_id)
|
| 346 |
+
journals = load_journal_entries(session_id=session_id)
|
| 347 |
+
scores = session.get("scores", compute_scores(events, game))
|
| 348 |
+
photos = session.get("photos", [])
|
| 349 |
+
|
| 350 |
+
packet = build_story_packet(
|
| 351 |
+
game=game,
|
| 352 |
+
events=events,
|
| 353 |
+
scores=scores,
|
| 354 |
+
journal_entries=journals,
|
| 355 |
+
photo_captions=photos,
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
result = generate_story(packet, session_id=session_id)
|
| 359 |
+
|
| 360 |
+
lines = [
|
| 361 |
+
"# 📖 Episode Recap\n",
|
| 362 |
+
result["short_recap"],
|
| 363 |
+
"",
|
| 364 |
+
"---\n",
|
| 365 |
+
result["long_summary"],
|
| 366 |
+
"",
|
| 367 |
+
"---\n",
|
| 368 |
+
"### 🎨 Poster Prompt\n",
|
| 369 |
+
f"```{result['poster_prompt']}```",
|
| 370 |
+
]
|
| 371 |
+
|
| 372 |
+
return "\n".join(lines), result
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# ── Build summary text ────────────────────────────────────────────────────────
|
| 376 |
+
def build_summary(game: dict, state: dict, session_id: str = "") -> str:
|
| 377 |
+
lines = []
|
| 378 |
+
lines.append(f"# 🎮 {game.get('title', 'Untitled')}")
|
| 379 |
+
lines.append("")
|
| 380 |
+
if session_id:
|
| 381 |
+
lines.append(f"> Session `{session_id[:12]}…` — paste this in the **Play** tab to log progress.")
|
| 382 |
+
lines.append("")
|
| 383 |
+
lines.append("## 📋 Setup")
|
| 384 |
+
setup = game.get("setup", {})
|
| 385 |
+
lines.append(f"- **Location:** {setup.get('city', '?')} — {setup.get('area', '?')}")
|
| 386 |
+
lines.append(f"- **Meeting point:** {setup.get('meeting_point', '?')}")
|
| 387 |
+
lines.append(f"- **Duration:** {setup.get('duration_minutes', '?')} min")
|
| 388 |
+
lines.append(f"- **Players:** {setup.get('num_players', '?')}")
|
| 389 |
+
lines.append("")
|
| 390 |
+
|
| 391 |
+
lines.append("## 📜 Rules")
|
| 392 |
+
for i, rule in enumerate(game.get("rules", []), 1):
|
| 393 |
+
lines.append(f" {i}. {rule}")
|
| 394 |
+
lines.append("")
|
| 395 |
+
|
| 396 |
+
lines.append("## 🎯 Tasks")
|
| 397 |
+
for t in game.get("tasks", []):
|
| 398 |
+
time_str = f"{t.get('time_limit_minutes', '∞')} min" if t.get("time_limit_minutes") else "No time limit"
|
| 399 |
+
lines.append(f" **{t.get('task_id', '?')}:** {t.get('title', '?')}")
|
| 400 |
+
lines.append(f" - *{t.get('description', '')[:80]}*")
|
| 401 |
+
lines.append(f" - 🏆 {t.get('points', 0)} pts | ⏱ {time_str} | 📸 {t.get('proof_type', '?')}")
|
| 402 |
+
lines.append(f" - 💡 {t.get('hint', '')[:70]}")
|
| 403 |
+
lines.append(f" - 🛡 {t.get('safety_note', '')[:70]}")
|
| 404 |
+
lines.append("")
|
| 405 |
+
|
| 406 |
+
lines.append("## 💡 Global Hints")
|
| 407 |
+
for h in game.get("global_hints", []):
|
| 408 |
+
lines.append(f" • {h}")
|
| 409 |
+
lines.append("")
|
| 410 |
+
|
| 411 |
+
lines.append("## 🔒 Safety")
|
| 412 |
+
safety = game.get("safety", {})
|
| 413 |
+
lines.append(f"- **Zone:** {safety.get('allowed_zone', '?')}")
|
| 414 |
+
lines.append(f"- **Supervision required:** {'Yes' if safety.get('adult_supervision') else 'No'}")
|
| 415 |
+
lines.append(f"- **Forbidden:** {', '.join(safety.get('forbidden_behaviors', []))}")
|
| 416 |
+
lines.append("")
|
| 417 |
+
|
| 418 |
+
lines.append("## 📊 Scoring")
|
| 419 |
+
for s in game.get("score_rules", []):
|
| 420 |
+
lines.append(f" • {s}")
|
| 421 |
+
lines.append(f"- **Tie-breaker:** {game.get('tie_breaker', '?')}")
|
| 422 |
+
lines.append("")
|
| 423 |
+
|
| 424 |
+
lines.append("## 📖 Story Seed")
|
| 425 |
+
seed = game.get("story_seed", {})
|
| 426 |
+
lines.append(f"- **Tone:** {seed.get('tone', '?')}")
|
| 427 |
+
lines.append(f"- **Motifs:** {', '.join(seed.get('motifs', []))}")
|
| 428 |
+
lines.append(f"- **Recap style:** {seed.get('recap_style', '?')}")
|
| 429 |
+
lines.append("")
|
| 430 |
+
|
| 431 |
+
lines.append("---")
|
| 432 |
+
lines.append("### 🔍 Pipeline trace")
|
| 433 |
+
lines.append(f"- Retrieval: {state.get('num_retrieved', 0)} examples found")
|
| 434 |
+
if state.get("retrieved_ids"):
|
| 435 |
+
lines.append(f"- Retrieved IDs: {', '.join(state['retrieved_ids'])}")
|
| 436 |
+
lines.append(f"- Game ID: {state.get('game_id', '?')}")
|
| 437 |
+
if state.get("validation_passed"):
|
| 438 |
+
lines.append(f"- ✅ Validation passed")
|
| 439 |
+
else:
|
| 440 |
+
lines.append(f"- ❌ Validation failed ({len(state.get('validation_failures', []))} issues)")
|
| 441 |
+
if state.get("repair_applied"):
|
| 442 |
+
lines.append(f"- 🔧 Repair applied → {'✅ Passed' if state.get('repair_valid') else '❌ Still has issues'}")
|
| 443 |
+
for f in state.get("validation_failures", [])[:5]:
|
| 444 |
+
lines.append(f" - {f}")
|
| 445 |
+
leftover = state.get("remaining_failures", [])
|
| 446 |
+
if leftover:
|
| 447 |
+
for f in leftover[:5]:
|
| 448 |
+
lines.append(f" - ⚠ {f}")
|
| 449 |
+
|
| 450 |
+
return "\n".join(lines)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
# ── Gradio UI ─────────────────────────────────────────────────────────────────
|
| 454 |
+
with gr.Blocks(title="CityQuest-AI – Game Generator") as demo:
|
| 455 |
+
gr.Markdown(
|
| 456 |
+
"""
|
| 457 |
+
# 🌍 CityQuest-AI — AI Game Generator
|
| 458 |
+
Configure your game, play it, record journals, and get a story recap.
|
| 459 |
+
"""
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# ── Tab 1: Generate ────────────────────────────────────────────────────
|
| 463 |
+
with gr.Tab("🎮 Generate"):
|
| 464 |
+
with gr.Row():
|
| 465 |
+
with gr.Column(scale=1):
|
| 466 |
+
gr.Markdown("### Game Configuration")
|
| 467 |
+
|
| 468 |
+
game_type = gr.Dropdown(
|
| 469 |
+
label="Game Type",
|
| 470 |
+
choices=["scavenger_hunt", "hide_and_seek", "tag"],
|
| 471 |
+
value="scavenger_hunt",
|
| 472 |
+
)
|
| 473 |
+
city = gr.Textbox(label="City", value="Paris", info="Default: Paris")
|
| 474 |
+
area = gr.Textbox(label="Area", value="Le Marais", info="Neighbourhood or district")
|
| 475 |
+
location_type = gr.Radio(
|
| 476 |
+
label="Location Type",
|
| 477 |
+
choices=["park", "street", "landmark", "mixed"],
|
| 478 |
+
value="mixed",
|
| 479 |
+
)
|
| 480 |
+
duration_minutes = gr.Slider(label="Duration (minutes)", minimum=15, maximum=120, value=60, step=5)
|
| 481 |
+
num_players = gr.Slider(label="Number of Players", minimum=2, maximum=10, value=4, step=1)
|
| 482 |
+
difficulty = gr.Dropdown(label="Difficulty", choices=["easy", "medium", "hard"], value="medium")
|
| 483 |
+
age_group = gr.Dropdown(label="Age Group", choices=["kids", "teens", "adults", "mixed"], value="adults")
|
| 484 |
+
energy_level = gr.Radio(label="Energy Level", choices=["low", "medium", "high"], value="medium")
|
| 485 |
+
generate_btn = gr.Button("🚀 Generate Game", variant="primary", size="lg")
|
| 486 |
+
|
| 487 |
+
with gr.Column(scale=2):
|
| 488 |
+
gr.Markdown("### 📄 Generated Game")
|
| 489 |
+
output_md = gr.Markdown(value="Click **Generate Game** to create a new game!")
|
| 490 |
+
output_json = gr.JSON(label="Raw game JSON", visible=False)
|
| 491 |
+
session_id_box = gr.Textbox(label="Session ID (copy to Play tab)", interactive=False, visible=True)
|
| 492 |
+
|
| 493 |
+
# ── Tab 2: Play ────────────────────────────────────────────────────────
|
| 494 |
+
with gr.Tab("🎯 Play"):
|
| 495 |
+
gr.Markdown("### Simulate gameplay")
|
| 496 |
+
with gr.Row():
|
| 497 |
+
play_session_id = gr.Textbox(label="Session ID", placeholder="Paste session ID here…")
|
| 498 |
+
play_team_id = gr.Textbox(label="Team ID", value="team-a")
|
| 499 |
+
|
| 500 |
+
with gr.Row():
|
| 501 |
+
with gr.Column():
|
| 502 |
+
gr.Markdown("#### Task Actions")
|
| 503 |
+
play_task_id = gr.Textbox(label="Task ID (e.g. t1, t2)", placeholder="t1")
|
| 504 |
+
with gr.Row():
|
| 505 |
+
complete_btn = gr.Button("✅ Complete Task", variant="primary")
|
| 506 |
+
skip_btn = gr.Button("⏭️ Skip Task")
|
| 507 |
+
hint_btn = gr.Button("💡 Use Hint")
|
| 508 |
+
task_feedback = gr.Markdown(value="")
|
| 509 |
+
|
| 510 |
+
with gr.Column():
|
| 511 |
+
gr.Markdown("#### 🎙️ Voice Journal")
|
| 512 |
+
journal_transcript = gr.Textbox(label="Journal entry", lines=4, placeholder="We just found the mural near the canal — it was incredible!")
|
| 513 |
+
journal_task_id = gr.Textbox(label="Related Task ID (optional)", placeholder="t1")
|
| 514 |
+
journal_location = gr.Textbox(label="Location note", placeholder="Near the canal on Rue de Rivoli")
|
| 515 |
+
journal_btn = gr.Button("🎙️ Record Journal", variant="secondary")
|
| 516 |
+
journal_output = gr.Markdown(value="")
|
| 517 |
+
|
| 518 |
+
with gr.Row():
|
| 519 |
+
with gr.Column():
|
| 520 |
+
gr.Markdown("#### 📸 Photo Upload")
|
| 521 |
+
photo_file = gr.Image(label="Upload a photo", type="filepath", height=200)
|
| 522 |
+
photo_caption = gr.Textbox(label="Caption", placeholder="The mural we just discovered!")
|
| 523 |
+
photo_task_id = gr.Textbox(label="Related Task ID (optional)", placeholder="t1")
|
| 524 |
+
photo_btn = gr.Button("📸 Upload Photo", variant="secondary")
|
| 525 |
+
photo_output = gr.Markdown(value="")
|
| 526 |
+
|
| 527 |
+
with gr.Row():
|
| 528 |
+
end_btn = gr.Button("🏁 End Game & Score", variant="primary", size="lg")
|
| 529 |
+
scoreboard_md = gr.Markdown(value="")
|
| 530 |
+
|
| 531 |
+
# ── Tab 3: Recap ───────────────────────────────────────────────────────
|
| 532 |
+
with gr.Tab("📖 Recap"):
|
| 533 |
+
gr.Markdown("### Generate a story recap")
|
| 534 |
+
recap_session_id = gr.Textbox(label="Session ID", placeholder="Paste session ID here…")
|
| 535 |
+
recap_btn = gr.Button("📖 Generate Recap", variant="primary", size="lg")
|
| 536 |
+
recap_md = gr.Markdown(value="")
|
| 537 |
+
recap_json = gr.JSON(label="Recap data", visible=False)
|
| 538 |
+
|
| 539 |
+
# ── Wire events ────────────────────────────────────────────────────────
|
| 540 |
+
generate_btn.click(
|
| 541 |
+
fn=run_pipeline,
|
| 542 |
+
inputs=[game_type, city, area, location_type, duration_minutes, num_players, difficulty, age_group, energy_level],
|
| 543 |
+
outputs=[output_md, output_json, session_id_box],
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
complete_btn.click(fn=complete_task, inputs=[play_session_id, play_task_id, play_team_id], outputs=task_feedback)
|
| 547 |
+
skip_btn.click(fn=skip_task, inputs=[play_session_id, play_task_id, play_team_id], outputs=task_feedback)
|
| 548 |
+
hint_btn.click(fn=use_hint, inputs=[play_session_id, play_task_id, play_team_id], outputs=task_feedback)
|
| 549 |
+
|
| 550 |
+
journal_btn.click(
|
| 551 |
+
fn=record_journal,
|
| 552 |
+
inputs=[play_session_id, journal_transcript, journal_task_id, journal_location, play_team_id],
|
| 553 |
+
outputs=[journal_output, gr.Textbox(visible=False)],
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
photo_btn.click(
|
| 557 |
+
fn=upload_photo,
|
| 558 |
+
inputs=[play_session_id, photo_file, photo_caption, photo_task_id, play_team_id],
|
| 559 |
+
outputs=photo_output,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
end_btn.click(fn=end_game, inputs=[play_session_id, play_team_id], outputs=[scoreboard_md, gr.JSON(visible=False)])
|
| 563 |
+
|
| 564 |
+
recap_btn.click(fn=generate_recap, inputs=[recap_session_id], outputs=[recap_md, recap_json])
|
| 565 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
|
| 567 |
+
# ── Launch ────────────────────────────────────────────────────────────────────
|
| 568 |
+
if __name__ == "__main__":
|
| 569 |
+
demo.launch()
|
app/prompts/game_generation.txt
CHANGED
|
@@ -1,33 +1,28 @@
|
|
| 1 |
-
|
| 2 |
|
| 3 |
## Context
|
| 4 |
- City: {city}
|
| 5 |
- Area: {area}
|
| 6 |
- Game Type: {game_type}
|
| 7 |
- Duration: {duration_minutes} minutes
|
| 8 |
-
-
|
| 9 |
- Difficulty: {difficulty}
|
| 10 |
- Age Group: {age_group}
|
| 11 |
|
| 12 |
## Retrieved Examples
|
| 13 |
{retrieved_examples}
|
| 14 |
|
| 15 |
-
##
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
6. Include supervision requirements for mixed-age groups
|
| 22 |
|
| 23 |
-
##
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
- Define clear win conditions
|
| 28 |
-
- Avoid invented private or inaccessible locations
|
| 29 |
|
| 30 |
## Output Schema
|
| 31 |
{output_schema}
|
| 32 |
-
|
| 33 |
-
Generate the game JSON:
|
|
|
|
| 1 |
+
Generate a location-based game in strict JSON format.
|
| 2 |
|
| 3 |
## Context
|
| 4 |
- City: {city}
|
| 5 |
- Area: {area}
|
| 6 |
- Game Type: {game_type}
|
| 7 |
- Duration: {duration_minutes} minutes
|
| 8 |
+
- Players: {num_players}
|
| 9 |
- Difficulty: {difficulty}
|
| 10 |
- Age Group: {age_group}
|
| 11 |
|
| 12 |
## Retrieved Examples
|
| 13 |
{retrieved_examples}
|
| 14 |
|
| 15 |
+
## Safety
|
| 16 |
+
- NO entering buildings or private property
|
| 17 |
+
- NO proximity to water, traffic, or rail lines
|
| 18 |
+
- NO interacting with strangers
|
| 19 |
+
- NO purchases required
|
| 20 |
+
- All locations must be public and accessible
|
|
|
|
| 21 |
|
| 22 |
+
## Required JSON Structure
|
| 23 |
+
{output_schema}
|
| 24 |
+
|
| 25 |
+
Return ONLY the JSON object. Start with {{ and end with }}. No other text.
|
|
|
|
|
|
|
| 26 |
|
| 27 |
## Output Schema
|
| 28 |
{output_schema}
|
|
|
|
|
|
app/services/generator.py
CHANGED
|
@@ -11,7 +11,27 @@ _model_cache = {}
|
|
| 11 |
|
| 12 |
# Model configuration
|
| 13 |
NEMOTRON_MODEL_ID = "nvidia/NVIDIA-Nemotron-3-Nano-4B-GGUF"
|
| 14 |
-
NEMOTRON_GGUF_FILE = "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
def build_generation_prompt(config: dict, retrieved_examples: list[dict]) -> str:
|
|
@@ -96,34 +116,41 @@ def generate_game_with_model(prompt: str, model_name: str = "nemotron") -> Optio
|
|
| 96 |
print(f"Initializing llama.cpp with: {model_id}/{NEMOTRON_GGUF_FILE}")
|
| 97 |
|
| 98 |
# Initialize llama.cpp with the GGUF model
|
| 99 |
-
#
|
| 100 |
_model_cache[cache_key] = Llama.from_pretrained(
|
| 101 |
repo_id=model_id,
|
| 102 |
filename=NEMOTRON_GGUF_FILE,
|
| 103 |
verbose=False,
|
| 104 |
-
n_gpu_layers=
|
| 105 |
-
n_ctx=
|
| 106 |
)
|
| 107 |
|
| 108 |
llm = _model_cache[cache_key]
|
| 109 |
|
| 110 |
-
#
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
stop=["```", "\n\n"]
|
| 121 |
)
|
| 122 |
|
| 123 |
-
generated_text = result[
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
# Extract JSON from generated text
|
| 126 |
json_str = extract_json(generated_text)
|
|
|
|
|
|
|
|
|
|
| 127 |
return json_str
|
| 128 |
|
| 129 |
except ImportError:
|
|
@@ -137,18 +164,20 @@ def generate_game_with_model(prompt: str, model_name: str = "nemotron") -> Optio
|
|
| 137 |
def extract_json(text: str) -> Optional[str]:
|
| 138 |
"""Extract JSON object from generated text.
|
| 139 |
|
|
|
|
|
|
|
| 140 |
Args:
|
| 141 |
text: Generated text that may contain JSON
|
| 142 |
|
| 143 |
Returns:
|
| 144 |
JSON string or None if not found
|
| 145 |
"""
|
| 146 |
-
# Find JSON block
|
| 147 |
start_idx = text.find('{')
|
| 148 |
if start_idx == -1:
|
| 149 |
return None
|
| 150 |
|
| 151 |
-
# Find matching closing brace
|
| 152 |
depth = 0
|
| 153 |
for i in range(start_idx, len(text)):
|
| 154 |
if text[i] == '{':
|
|
@@ -156,8 +185,14 @@ def extract_json(text: str) -> Optional[str]:
|
|
| 156 |
elif text[i] == '}':
|
| 157 |
depth -= 1
|
| 158 |
if depth == 0:
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
|
|
|
| 161 |
return None
|
| 162 |
|
| 163 |
|
|
|
|
| 11 |
|
| 12 |
# Model configuration
|
| 13 |
NEMOTRON_MODEL_ID = "nvidia/NVIDIA-Nemotron-3-Nano-4B-GGUF"
|
| 14 |
+
NEMOTRON_GGUF_FILE = "*Q4_K_M.gguf" # The GGUF file name in the HF repo
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _get_n_gpu_layers() -> int:
|
| 18 |
+
"""Auto-detect GPU availability for llama.cpp.
|
| 19 |
+
|
| 20 |
+
On Hugging Face Zero GPU, torch.cuda.is_available() returns True
|
| 21 |
+
inside @spaces.GPU decorated functions.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
-1 if GPU available (all layers on GPU), 0 for CPU only
|
| 25 |
+
"""
|
| 26 |
+
try:
|
| 27 |
+
import torch
|
| 28 |
+
if torch.cuda.is_available():
|
| 29 |
+
print(f"[GPU] CUDA detected ({torch.cuda.get_device_name(0)}) — GPU acceleration ON")
|
| 30 |
+
return -1
|
| 31 |
+
except ImportError:
|
| 32 |
+
pass
|
| 33 |
+
print("[CPU] No CUDA detected — using CPU only")
|
| 34 |
+
return 0
|
| 35 |
|
| 36 |
|
| 37 |
def build_generation_prompt(config: dict, retrieved_examples: list[dict]) -> str:
|
|
|
|
| 116 |
print(f"Initializing llama.cpp with: {model_id}/{NEMOTRON_GGUF_FILE}")
|
| 117 |
|
| 118 |
# Initialize llama.cpp with the GGUF model
|
| 119 |
+
# Auto-detect GPU — works with HF Zero GPU (@spaces.GPU)
|
| 120 |
_model_cache[cache_key] = Llama.from_pretrained(
|
| 121 |
repo_id=model_id,
|
| 122 |
filename=NEMOTRON_GGUF_FILE,
|
| 123 |
verbose=False,
|
| 124 |
+
n_gpu_layers=_get_n_gpu_layers(), # Auto: -1 GPU, 0 CPU
|
| 125 |
+
n_ctx=8192, # Larger context window (model supports 1M)
|
| 126 |
)
|
| 127 |
|
| 128 |
llm = _model_cache[cache_key]
|
| 129 |
|
| 130 |
+
# Use create_chat_completion — this model uses a Nemotron chat template
|
| 131 |
+
messages = [
|
| 132 |
+
{"role": "system", "content": "You output only valid JSON. No other text."},
|
| 133 |
+
{"role": "user", "content": prompt},
|
| 134 |
+
]
|
| 135 |
|
| 136 |
+
result = llm.create_chat_completion(
|
| 137 |
+
messages=messages,
|
| 138 |
+
max_tokens=8192,
|
| 139 |
+
temperature=0.3, # Low temperature for structured output
|
| 140 |
+
top_p=0.9,
|
| 141 |
+
stop=["```"],
|
|
|
|
| 142 |
)
|
| 143 |
|
| 144 |
+
generated_text = result["choices"][0]["message"]["content"]
|
| 145 |
+
# Strip leading/trailing whitespace
|
| 146 |
+
generated_text = generated_text.strip()
|
| 147 |
+
print(f"[nemotron] Generated {len(generated_text)} chars")
|
| 148 |
|
| 149 |
# Extract JSON from generated text
|
| 150 |
json_str = extract_json(generated_text)
|
| 151 |
+
if not json_str:
|
| 152 |
+
print(f"[nemotron] JSON extraction failed on output (len={len(generated_text)})")
|
| 153 |
+
print(f"[nemotron] Preview: {generated_text[:300]}...")
|
| 154 |
return json_str
|
| 155 |
|
| 156 |
except ImportError:
|
|
|
|
| 164 |
def extract_json(text: str) -> Optional[str]:
|
| 165 |
"""Extract JSON object from generated text.
|
| 166 |
|
| 167 |
+
Handles various prefixes (e.g. double braces {{ from prompt echoing).
|
| 168 |
+
|
| 169 |
Args:
|
| 170 |
text: Generated text that may contain JSON
|
| 171 |
|
| 172 |
Returns:
|
| 173 |
JSON string or None if not found
|
| 174 |
"""
|
| 175 |
+
# Find JSON block - look for the first {
|
| 176 |
start_idx = text.find('{')
|
| 177 |
if start_idx == -1:
|
| 178 |
return None
|
| 179 |
|
| 180 |
+
# Find matching closing brace using depth counting
|
| 181 |
depth = 0
|
| 182 |
for i in range(start_idx, len(text)):
|
| 183 |
if text[i] == '{':
|
|
|
|
| 185 |
elif text[i] == '}':
|
| 186 |
depth -= 1
|
| 187 |
if depth == 0:
|
| 188 |
+
raw = text[start_idx:i+1]
|
| 189 |
+
# Normalize double braces from prompt echoing ({{ -> {)
|
| 190 |
+
# Only fix the outermost brace pair if needed
|
| 191 |
+
if raw.startswith('{{') and raw.endswith('}}'):
|
| 192 |
+
raw = raw[1:-1]
|
| 193 |
+
return raw
|
| 194 |
|
| 195 |
+
# Truncated JSON — return what we have
|
| 196 |
return None
|
| 197 |
|
| 198 |
|
requirements.txt
CHANGED
|
@@ -2,3 +2,4 @@ gradio
|
|
| 2 |
torch
|
| 3 |
llama-cpp-python
|
| 4 |
jsonschema
|
|
|
|
|
|
| 2 |
torch
|
| 3 |
llama-cpp-python
|
| 4 |
jsonschema
|
| 5 |
+
spaces
|