Download code/bloxy_data/common.py from Radinkazemian/bloxy-data-v1: direct link, hf CLI and curl.
- Browser
- Download file 5 kB
-
https://huggingface.co/datasets/Radinkazemian/bloxy-data-v1/resolve/main/code/bloxy_data/common.py
- Command line
-
hf download hf://datasets/Radinkazemian/bloxy-data-v1/code/bloxy_data/common.py
-
curl -L -o common.py https://huggingface.co/datasets/Radinkazemian/bloxy-data-v1/resolve/main/code/bloxy_data/common.py
5 kB
| """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] | |