File size: 4,999 Bytes
6da8440 | 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 | """Shared helpers for building the Bloxy training set."""
from __future__ import annotations
import hashlib
import json
import random
import re
from pathlib import Path
from typing import Iterable, Iterator
SYSTEM_PROMPT = (
"You are Bloxy, an AI that builds and scripts in Roblox Studio. "
"You are best at building: you turn a description into a clean, anchored, "
"well-proportioned build made of Parts. Scale: 1 stud is 1 unit, a character "
"is about 5 studs tall, a door is about 7 studs tall, a floor is about 12 studs "
"high. You write correct, modern Luau, use Studio tools carefully when they are "
"available, and keep answers short."
)
# Rough characters-per-token for Gemma's tokenizer on code/English mixes.
# Only used for budgeting; the trainer filters by real token counts.
CHARS_PER_TOKEN = 3.3
_FENCE = re.compile(r"```.*?```", re.DOTALL)
def est_tokens(messages: list[dict]) -> int:
"""Conservative token estimate. Code (numbers, punctuation) packs ~2.4 chars per
Gemma token, prose ~3.6; checked against the real tokenizer in check_format.py."""
code = prose = 0
for m in messages:
c = m.get("content") or ""
blocks = sum(len(b) for b in _FENCE.findall(c))
code += blocks
prose += len(c) - blocks
for tc in m.get("tool_calls") or []:
code += len(json.dumps(tc.get("function", {}), ensure_ascii=False))
return int(code / 2.1 + prose / 3.6) + 8 * len(messages)
def chat(user: str, assistant: str, system: str = SYSTEM_PROMPT) -> list[dict]:
return [
{"role": "system", "content": system},
{"role": "user", "content": user.strip()},
{"role": "assistant", "content": assistant.strip()},
]
THINK_RE = re.compile(r"<think>.*?</think>\s*", re.DOTALL)
def strip_think(text: str) -> str:
return THINK_RE.sub("", text or "").strip()
def norm_for_hash(text: str) -> str:
return re.sub(r"\s+", " ", (text or "").lower()).strip()
def example_key(messages: list[dict]) -> str:
"""Dedup key: last user message + last assistant answer (normalized)."""
users = [m for m in messages if m["role"] == "user"]
asst = [m for m in messages if m["role"] == "assistant" and m.get("content")]
u = norm_for_hash(users[-1]["content"])[:2000] if users else ""
a = norm_for_hash(asst[-1]["content"])[:4000] if asst else ""
return hashlib.sha1((u + "\x00" + a).encode()).hexdigest()
def answer_key(messages: list[dict]) -> str:
"""Near-dup key on the answer only (catches the same code under new prompts)."""
asst = [m for m in messages if m["role"] == "assistant" and m.get("content")]
a = norm_for_hash(asst[-1]["content"]) if asst else ""
return hashlib.sha1(a.encode()).hexdigest()
def reservoir(items: Iterable, k: int, rng: random.Random) -> list:
out: list = []
for i, it in enumerate(items):
if i < k:
out.append(it)
else:
j = rng.randint(0, i)
if j < k:
out[j] = it
return out
def write_jsonl(path: Path, rows: Iterable[dict]) -> int:
path.parent.mkdir(parents=True, exist_ok=True)
n = 0
opener = open
if str(path).endswith(".gz"):
import gzip
opener = gzip.open # type: ignore[assignment]
with opener(path, "wt", encoding="utf-8") as f: # type: ignore[call-arg]
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
n += 1
return n
def read_jsonl(path: Path) -> Iterator[dict]:
opener = open
if str(path).endswith(".gz"):
import gzip
opener = gzip.open # type: ignore[assignment]
with opener(path, "rt", encoding="utf-8") as f: # type: ignore[call-arg]
for line in f:
if line.strip():
yield json.loads(line)
LUA_BLOCK = re.compile(r"```lua\n(.*?)```", re.DOTALL)
def luau_compiles(messages: list[dict], compiler: str) -> bool:
"""True if every ```lua block in the assistant turns compiles with luau-compile."""
import subprocess
import tempfile
for m in messages:
if m.get("role") != "assistant":
continue
for code in LUA_BLOCK.findall(m.get("content") or ""):
with tempfile.NamedTemporaryFile("w", suffix=".luau", delete=False) as f:
f.write(code)
r = subprocess.run([compiler, "--null", f.name], capture_output=True)
Path(f.name).unlink(missing_ok=True)
if r.returncode != 0:
return False
return True
def pretty_name(slug: str) -> str:
s = re.sub(r"[-_]+", " ", slug or "").strip()
s = re.sub(r"\s+\d+$", "", s) # drop trailing variant numbers: "house 2"
s = re.sub(r"\s+", " ", s)
return s
def pascal(name: str) -> str:
parts = re.findall(r"[A-Za-z0-9]+", name)
out = "".join(p[:1].upper() + p[1:] for p in parts) or "Build"
if out[0].isdigit():
out = "Build" + out
return out[:40]
|